Cosa: An Object-Oriented Platform for Arduino programming

Just a question @kowalski:
As my intention is to base all my nodes on Cosa, some additional chip & functional support should be added to the Cosa eco system :blush:

I guess the best way to make that visible is to add an issue on GitHub for each chip and/or function??

MarsWarrior:
As my intention is to base all my nodes on Cosa, some additional chip & functional support should be added to the Cosa eco system :blush:
I guess the best way to make that visible is to add an issue on GitHub for each chip and/or function??

@MarsWarrior

That sounds like a good idea. The issue list on github is the right place for that.

There are a few things to consider. At this stage Cosa is not a commercial product or project as Arduino. There is no license, no registration, and no release handling with maintenance. The idea is to collaborate and build an industry strength high quality fully OOP alternative to the Arduino codebase. If and when we reach critical mass the next stage will offer release and maintenance.

For now anybody may contribute by building and test, writing code, donating hardware, giving improvement suggestions, etc. Contributing code requires normal open source git handling; clone/fork and pull request. The contributed code should follow the coding standard and must have test and/or example code. Contributed code will follow the normal refactoring of Cosa. The high level of refactoring right now is also part of the current stage.

Easiest way to get new device drivers is to contribute hardware. This is important even when contributing code to the main repository. It is difficult to add code that cannot be tested. This will need a lot of convincing :-).

Cheers!

x iscrizione

The latest Cosa update includes porting and configuration of the Arduino-Makefile GitHub - sudar/Arduino-Makefile: Makefile for Arduino sketches. It defines the workflows for compiling code, flashing it to Arduino and even communicating through Serial.. This allows simple build using "traditional" make files. To get started simply configure the build template with your Arduino installation path (Cosa/Cosa.mk at master · mikaelpatel/Cosa · GitHub) and write a three line makefile in the same directory as the sketch.

COSA_DIR = $(HOME)/Sketchbook/hardware/Cosa
BOARD_TAG = duemilanove
include $(COSA_DIR)/build/Cosa.mk

The COSA_DIR variable is the path of the Cosa installation. The BOARD_TAG is the type of board to build the sketch for. The possible board tags are:

BOARD_TAG		DESCRIPTION
================================================================================
miniwireless		Cosa Anarduino MiniWireless (ATmega328/BOOT_168)
duemilanove		Cosa Arduino Duemilanove (ATmega328/BOOT_168)
leonardo		Cosa Arduino Leonardo (ATmega32U4/Caterina)
mega			Cosa Arduino Mega (ATmega2560/STK500v2)
nano			Cosa Arduino Nano (ATmega328/BOOT_168)
pro-micro		Cosa Arduino Pro Micro (ATmega32U4/Caterina)
pro-mini		Cosa Arduino Pro Mini (ATmega328/BOOT_168)
pro-mini-8		Cosa Arduino Pro Mini (ATmega328/BOOT_168, 3.3V, 8 MHz)
uno			Cosa Arduino Uno (ATmega328/Optiboot)
attiny84-8		Cosa Breadboard (ATtiny84, 8 MHz internal clock)
attiny85-8		Cosa Breadboard (ATtiny85, 8 MHz internal clock)
attiny861-8		Cosa Breadboard (ATtiny861, 8 MHz internal clock)
atmega328-8		Cosa Breadboard (ATmega328, 8 MHz internal clock)
mighty			Cosa Breadboard (ATmega1284/BOOT_1284P)
mighty-opt		Cosa Breadboard (ATmega1284/Optiboot)
lilypad			Cosa LilyPad Arduino (ATmega328/BOOT_168, 8 MHz)
lilypad-usb		Cosa LilyPad Arduino USB (ATmega32U4/Caterina, 8 MHz)
moteino			Cosa LowPowerLab Moteino (ATmega328/DualOptiboot)
microduino-core		Cosa Microduino-Core (ATmega328/Optiboot)
microduino-core32u4	Cosa Microduino-Core32u4 (ATmega32U4/Caterina)
microduino-core-plus	Cosa Microduino-Core+ (ATmega644P/Optiboot)
pinoccio		Cosa Pinoccio Scout (ATmega256RFR2/STK500v2)
teensy-2_0		Cosa Teensy 2.0 (ATmega32U4/halfkay)
teensypp-2_0		Cosa Teensy++ 2.0 (AT90USB1286/halfkay)

Build, upload and monitor the sketch with the following command.

make upload monitor

The Cosa Arduino-Makefile uses miniterm.py as serial monitor. The exit command is CTRL-ALT GR ]

Build for another board by either changing the BOARD_TAG in the Makefile or simply giving the command:

make "BOARD_TAG=uno"

More details in the Cosa/build directory and on the original Arduino-Makefile site. Please see the example makefiles in the CosaBlink and CosaBenchmarkPins directories.

Cheers!

Command line build of Cosa based sketches is now as easy as it gets. A new shell script (cosa) eliminates the need for makefiles. Used as follows:

cosa BOARD COMMAND

Where BOARD is one of the BOARD_TAGs and COMMAND is what is passed to make (Arduino-Makefile). Typical usage are:

  1. Some basic instructions on how to use the tool and make targets.
user@host:~/Sketchbook/hardware/Cosa/examples/Blink/CosaBlink$ cosa help
Available targets (default is compile the code):
  upload            - upload
  ispload           - upload using an ISP
  raw_upload        - upload without first resetting
  eeprom            - upload the eep file
  raw_eeprom        - upload the eep file without first resetting
  clean             - remove all our dependencies
  depends           - update dependencies
  reset             - reset the Arduino by tickling DTR or changing baud
                      rate on the serial port.
  boards            - list all the boards defined in boards.txt
  config            - list configuration
  monitor           - connect to the Arduino's serial port
  size              - show the size of the compiled output (relative to
                      resources, if you have a patched avr-size).
  verify_size       - verify that the size of the final file is less than
                      the capacity of the micro controller.
  symbol_sizes      - generate a .sym file containing symbols and their
                      sizes.
  disasm            - generate a .lss file that contains disassembly
                      of the compiled file interspersed with your
                      original source code.
  generate_assembly - generate a .s file containing the compiler
                      generated assembly of the main sketch.
  burn_bootloader   - burn bootloader and fuses
  set_fuses         - set fuses without burning bootloader
  help_vars         - print all variables that can be overridden
  avanti            - short cut for upload and monitor
  help              - show this help
More details in:
/home/user/Sketchbook/hardware/Cosa/build/Arduino-Makefile/Arduino.mk
/home/user/Sketchbook/hardware/Cosa/build/Cosa.mk
  1. Get the current configuration.
user@host:~/Sketchbook/hardware/Cosa/examples/Blink/CosaBlink$ cosa uno config
-------------------------
Arduino.mk Configuration:
- [AUTODETECTED]       CURRENT_OS = LINUX 
- [USER]               ARDMK_DIR = /home/user/Sketchbook/hardware/Cosa/build/Arduino-Makefile 
- [USER]               ARDUINO_DIR = /home/user/opt/arduino-1.0.5 
- [AUTODETECTED]       ARDUINO_VERSION = 105 
- [AUTODETECTED]       ARDUINO_PREFERENCES_PATH = /home/user/.arduino/preferences.txt 
- [AUTODETECTED]       ARDUINO_SKETCHBOOK = /home/user/Sketchbook (from arduino preferences file)
- [BUNDLED]            AVR_TOOLS_DIR = /home/user/opt/arduino-1.0.5/hardware/tools/avr (in Arduino distribution)
- [COMPUTED]           ARDUINO_LIB_PATH = /home/user/opt/arduino-1.0.5/libraries (from ARDUINO_DIR)
- [USER]               ARDUINO_CORE_PATH = /home/user/Sketchbook/hardware/Cosa/cores/cosa 
- [USER]               ARDUINO_VAR_PATH = /home/user/Sketchbook/hardware/Cosa/variants 
- [USER]               BOARDS_TXT = /home/user/Sketchbook/hardware/Cosa/boards.txt 
- [DEFAULT]            USER_LIB_PATH = /home/user/Sketchbook/libraries (in user sketchbook)
- [DEFAULT]            PRE_BUILD_HOOK = pre-build-hook.sh 
- [USER]               BOARD_TAG = uno 
- [COMPUTED]           OBJDIR = build-uno (from BOARD_TAG)
- [ASSUMED]            MONITOR_BAUDRATE = 9600 
- [DEFAULT]            OPTIMIZATION_LEVEL = s 
- [DEFAULT]            MCU_FLAG_NAME = mmcu 
- [DEFAULT]            CFLAGS_STD = -std=gnu99 
- [AUTODETECTED]       DEVICE_PATH =  
- [AUTODETECTED]       Size utility: AVR-aware for enhanced output
- [COMPUTED]           BOOTLOADER_PARENT = /home/user/opt/arduino-1.0.5/hardware/arduino/bootloaders (from ARDUINO_DIR)
-------------------------
Please refer to /home/user/Sketchbook/hardware/Cosa/build/Arduino-Makefile/Arduino.mk for more details.
  1. Get a list of the available boards.
user@host:~/Sketchbook/hardware/Cosa/examples/Blink/CosaBlink$ cosa boards
atmega328-8           Cosa Breadboard (ATmega328, 8 MHz internal clock)
attiny84-8            Cosa Breadboard (ATtiny84, 8 MHz internal clock)
attiny85-8            Cosa Breadboard (ATtiny85, 8 MHz internal clock)
attiny861-8           Cosa Breadboard (ATtiny861, 8 MHz internal clock)
duemilanove           Cosa Arduino Duemilanove (ATmega328/BOOT_168)
leonardo              Cosa Arduino Leonardo (ATmega32U4/Caterina)
lilypad               Cosa LilyPad Arduino (ATmega328/BOOT_168, 8 MHz)
lilypad-usb           Cosa LilyPad Arduino USB (ATmega32U4/Caterina, 8 MHz)
mega                  Cosa Arduino Mega (ATmega2560/STK500v2)
microduino-core32u4   Cosa Microduino-Core32u4 (ATmega32U4/Caterina)
microduino-core       Cosa Microduino-Core (ATmega328/Optiboot)
microduino-core-plus  Cosa Microduino-Core+ (ATmega644P/Optiboot)
mighty                Cosa Breadboard (ATmega1284/BOOT_1284P)
mighty-opt            Cosa Breadboard (ATmega1284/Optiboot)
miniwireless          Cosa Anarduino MiniWireless (ATmega328/BOOT_168)
moteino               Cosa LowPowerLab Moteino (ATmega328/DualOptiboot)
nano                  Cosa Arduino Nano (ATmega328/BOOT_168)
pinoccio              Cosa Pinoccio Scout (ATmega256RFR2/STK500v2)
pro-micro             Cosa Arduino Pro Micro (ATmega32U4/Caterina)
pro-mini-8            Cosa Arduino Pro Mini (ATmega328/BOOT_168, 3.3V, 8 MHz)
pro-mini              Cosa Arduino Pro Mini (ATmega328/BOOT_168)
uno                   Cosa Arduino Uno (ATmega328/Optiboot)
  1. Build the CosaBenchmarkPins sketch for Arduino Uno, upload and start the serial monitor.
user@host:~/Sketchbook/hardware/Cosa/examples/Benchmarks/CosaBenchmarkPins$ cosa uno avanti

To install this new build feature please either add Cosa/build to your PATH or symbolic link from you local bin directory to the build script $COSA_DIR/build/cosa. The default path for COSA_DIR is $HOME/Sketchbook/hardware/Cosa. You can set COSA_DIR as an exported environment variable.

To use GNU Emacs as the Cosa IDE simply use the command M-X compile with "cosa BOARD upload" (only needed the first time per session). You can directly move to any compile error with M-X goto-next-locus. Add the following to your .emacs file to allow bind compile-upload to F2 and goto-next-error to F3. The first line below will make GNU Emacs recognize .pde/.ino files as C++ and automatically switch to the correct mode.

(setq auto-mode-alist (cons '("\\.\\(pde\\|ino\\)$" . c++-mode) auto-mode-alist))
(global-set-key (quote [f2]) (quote compile))
(global-set-key (quote [f3]) (quote goto-next-locus))

Below is an example of compiling the CosaBlink example sketch with a bad modification and stepping to the error line (F2 and F3).

GNU Emacs will help you with indentation, quick incremental search, color coding comments, etc. Together with the new Cosa build script GNU Emacs gives a productive IDE for Arduino programming that is easy to customize.

The Arduino version is configured in the file Cosa/build/Cosa.mk. There is support for the following Arduino versions; 1.0.5, 1.5.6-r2 and the nightly build with GCC 4.8.1.

Cheers!

The latest update of Cosa includes a device driver for MAX7219/MAX7221 Serially Interfaced, 8-digit LED Display Drivers.

The device driver implements the Cosa LCD/IOStream::Driver interface. It handles carriage-return-line-feed, backspace, alert, horizontal tab and form-feed. The period character is translated to the 7-segment LED decimal point of the previous written character. The example sketch (https://github.com/mikaelpatel/Cosa/blob/master/examples/LCD/CosaMAX72XX/CosaMAX72XX.ino) shows how to output floating-point numbers to a Cosa IOStream.

Cheers!

Ref.
Interface: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/LCD/Driver/MAX72XX.hh
Source: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/LCD/Driver/MAX72XX.cpp

The latest update of the Cosa command line build script adds support for attiny devices. The below example command line will build the CosaBlink sketch for an ATtiny84 (internal clock 8 MHz) and upload with ISP device on the given port.

user@host:~/Sketchbook/hardware/Cosa/examples/Blink/CosaBlink$ cosa attiny84-8 ispload ISP_PORT=/dev/ttyACM0

The command "cosa boards" lists the devices that require ISP device upload as "Cosa Breadboard" with the MCU and clock type/frequency. The default ISP device is defined as "arduino:arduinoisp" in the Cosa/boards.txt file.

The latest update also includes an updated version of miniterm.py (serial monitor) so that 1) the board may signal shutdown of the serial monitor and 2) LF/CR is handled correctly both for RX and TX to the board. The shutdown signal is used by the Cosa ASSERT macro and the Trace::fatal_P() member function on error detect. The ASSERT error message uses the same format as GCC compiler errors and warnings so that the M-X goto-next-locus (F3) command can be used in GNU Emacs to directly step to the ASSERT code line.

Cheers!

Hello, I hope this is right place to ask the question. I have Mega1280 board and I don't know what should I choose in tools/boards. In the arduino ide there is mega1280, what would be equivalent in cosa?
Kind Regards,
Adam

g_ad:
Hello, I hope this is right place to ask the question. I have Mega1280 board and I don't know what should I choose in tools/boards. In the arduino ide there is mega1280, what would be equivalent in cosa?
Kind Regards,
Adam

@g_ad

Hi Adam! Ok with the question here on the Arduino forum but you would get faster response on the Cosa github issues list. Issues · mikaelpatel/Cosa · GitHub

The current Mega 2560 support will not work for the Mega 1280 as this board has a different bootloader. To fix this I have added a board definition for the Mega 1280 to the Cosa boards definition file. Please download from github https://github.com/mikaelpatel/Cosa/archive/master.zip and install Cosa/02-install.md at master · mikaelpatel/Cosa · GitHub.

Cheers!

kowalski:

g_ad:
Hello, I hope this is right place to ask the question. I have Mega1280 board and I don't know what should I choose in tools/boards. In the arduino ide there is mega1280, what would be equivalent in cosa?
Kind Regards,
Adam

@g_ad

Hi Adam! Ok with the question here on the Arduino forum but you would get faster response on the Cosa github issues list. Issues · mikaelpatel/Cosa · GitHub

The current Mega 2560 support will not work for the Mega 1280 as this board has a different bootloader. To fix this I have added a board definition for the Mega 1280 to the Cosa boards definition file. Please download from github https://github.com/mikaelpatel/Cosa/archive/master.zip and install Cosa/02-install.md at master · mikaelpatel/Cosa · GitHub.

Cheers!

@kowalski
Good news ans super fast response, thank you very much.
This is my beginning of the adventure with Cosa plaftorm :slight_smile: The note is taken where to post questions :slight_smile:
Kind regards,
Adam

g_ad:
Good news ans super fast response, thank you very much.
This is my beginning of the adventure with Cosa plaftorm :slight_smile: The note is taken where to post questions :slight_smile:
Kind regards,
Adam

@g_ad
You are welcome. Please let me know how the update works with Arduino Mega 1280 as I do not have that specific board to test. As the MCU is very similar to the Mega 2560, half the amount of program memory but otherwise the same, I believe that it should work just fine.

I have also added support for the Arduino Diecimila (Add support for Diecimila (ATmega168) · Issue #209 · mikaelpatel/Cosa · GitHub). All boards can be built with the command line tool.

Cheers!

kowalski:
@g_ad
You are welcome. Please let me know how the update works with Arduino Mega 1280 as I do not have that specific board to test. As the MCU is very similar to the Mega 2560, half the amount of program memory but otherwise the same, I believe that it should work just fine.

I have also added support for the Arduino Diecimila (Add support for Diecimila (ATmega168) · Issue #209 · mikaelpatel/Cosa · GitHub). All boards can be built with the command line tool.

Cheers!

@kowalski
I can confirm, Mega1280 is working now :), however it seems that the uart1 doesn't work, I've tried the MegaUARTs example and had to change to uart2 to test it.

Time to get my head around to understand the software, as I'm rather beginner than advanced - it will take some time.

Kind regards,
Adam

g_ad:
@kowalski
I can confirm, Mega1280 is working now :), however it seems that the uart1 doesn't work, I've tried the MegaUARTs example and had to change to uart2 to test it.

@g_ad
Thanks for the info. Great that you got your Mega 1280 board up and running with Cosa. I will look into the UART numbering. Seems like the ISRs might have got mixed up.

Cheers!

The latest Cosa development have been focused on implementing a file system for the flash device driver (S25FL127S). The device is accessed through SPI and has a total size of 16 Mbyte (128 Mbit). Typical access time with the optimized Cosa SPI functions are approx. 600 Kbyte/s read and 200 Kbyte/s at 16 MHz clock and DIV2 SPI clock (i.e. 8 Mhz).

The Cosa Flash File System takes advantage of the S25FL127S hybrid sector structure with 16 X 4 Kbyte sectors followed by 255 x 64 Kbyte sectors. The file system allows for up to 16 directories with up to 128 files per directory. The total number of data files is limited to 255. The file and directory API is very traditional Linux with open, close, remove, tell, seek, read, write and ls, cd, mkdir and more.

The API follows the Cosa FAT16 interface so that SD and Flash access can replace each other in a sketch. Also the CFFS::File and FAT16::File classes implement the Cosa IOStream interface and all the output functions and operators can be used directly. Both binary and text data can be written to files on the flash. The only restriction is that the last data entry cannot be 0xff. This works fine for text while binary data records must be padded.

Interface: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/FS/CFFS.hh


Example sketch: https://github.com/mikaelpatel/Cosa/blob/master/examples/Sandbox/CosaCFFS/CosaCFFS.ino

The example sketch demonstrates the file system functionality and binding a file to an iostream for log output in text (i.e. analog sample written to the file). Above is a screen shot of the output.

Cheers!

Hi guys,

I am struggling with putting together SNMP with a webserver on one device.

I have mangled together the SNMP and webserver examples, but with no luck. I can get either couple of snmp requests or web pages (from the example), or both within couple of seconds of the device start, but after than that it just freezes on me.

Any thoughts ?

thanks !

Mispulin:
Any thoughts ?

  • Running out of RAM memory?
  • Same behaviour if you comment either SMNP or the Webserver calls?

Hi MarsWarrior,

its a Mega, so there is plenty of mem - more than 7300 bytes.

this is my loop :

  // Service SNMP requests with given MIB handlers
  server.request();
  SNMP::PDU pdu;
  if (snmp.request(pdu) < 0) return;

#if defined(PRINT_PDU)
  // Print available memory and resulting protocol data unit
  TRACE(free_memory());
  trace << pdu << endl;
#endif

when I comment out the server.request the snmp works fine, the same goes the other way.
When i Leave both in place, I can get the page to load once or twice - then there is no response.
I've put some debug info to the webservers on_request and it seems that function is not even called when it hangs.

I am too tired to think straight, but it seems to me that something is blocking either the ethernet (as an object) or the stream library, it might be because i mixed the two examples together the bad way.

this is the entire source code, to doublecheck.

/**
 

#include "Cosa/Memory.h"
#include "Cosa/InputPin.hh"
#include "Cosa/AnalogPin.hh"
#include "Cosa/Trace.hh"
#include "Cosa/Watchdog.hh"
#include "Cosa/INET/SNMP.hh"
#include "Cosa/Socket/Driver/W5100.hh"
#include "Cosa/IOStream/Driver/UART.hh"
#include "Cosa/INET.hh"
#include "Cosa/INET/HTTP.hh"
#include "Cosa/IOStream.hh"



/**
 * Arduino MIB OID(1.3.6.1.4.1.36582)
 */
class ARDUINO_MIB : public SNMP::MIB {
private:
  enum {
    ardDigitalPin = 1,	      // Digital pin[0..22](0..1), read-only
    ardAnalogPin = 2,	      // Analog pin[0..7](0..1023), read-only
    ardVcc = 3,		      // Power supply[0](0..VCC), mV, read-only
  } __attribute__((packed));

public:
  /**
   * @override SNMP::MIB
   * Return object identity root for Arduino MIB.
   */
  virtual const uint8_t* get_oid()
  {
    return (SNMP::ARDUINO_MIB_OID);
  }
    
  /**
   * @override SNMP::MIB
   * Handle Arduino MIB objects SNMP requests. Returns true and
   * value for SNMP::GET in given protocol data unit, otherwise false.
   * @param[in,out] pdu protocol data unit.
   * @return bool
   */
  virtual bool is_request(SNMP::PDU& pdu);
};

bool 
ARDUINO_MIB::is_request(SNMP::PDU& pdu)
{
  // Match with Arduino MIB OID root
  int pos = pdu.oid.match(get_oid(), false);
  if (pos < 0 || pdu.oid.length != 11) return (false);

  // Access pin type and number
  uint8_t sys = pdu.oid.name[pos];
  uint8_t pin = pdu.oid.name[pos + 1];
  
  // Get next value; adjust pin referens
  if (pdu.type == SNMP::PDU_GET_NEXT) {
    switch (sys) {
    case 0:
      sys = ardDigitalPin;
      pin = 0;
      break;
    case ardDigitalPin:
      if (pin < 22)
	pin += 1;
      else {
	pin = 0;
	sys = ardAnalogPin;
      } 
      break;
    case ardAnalogPin:
      if (pin < 7)
	pin += 1;
      else {
	pin = 0; 
	sys = ardVcc;
      }
      break;
    case ardVcc:
      return (false);
    }
    pdu.oid.name[pos] = sys;
    pdu.oid.name[pos + 1] = pin;
    pdu.type = SNMP::PDU_GET;
  }

  // Check request type
  if (sys < ardDigitalPin || sys > ardVcc) return (false);
  
  // Get value for digital or analog pin, or power supply voltage
  if (pdu.type == SNMP::PDU_GET) {
    switch (sys) {
    case ardDigitalPin:
      if (pin > 22)
	pdu.error_status = SNMP::NO_SUCH_NAME;
      else
	pdu.value.encode(SNMP::SYNTAX_INT, (int16_t) InputPin::read(pin));
      break;
    case ardAnalogPin:
      if (pin > 7)
	pdu.error_status = SNMP::NO_SUCH_NAME;
      else
	pdu.value.encode(SNMP::SYNTAX_INT, (int16_t) AnalogPin::sample(pin));
      break;
    case ardVcc:
      if (pin > 0)
	pdu.error_status = SNMP::NO_SUCH_NAME;
      else
	pdu.value.encode(SNMP::SYNTAX_INT, (int16_t) AnalogPin::bandgap());
      break;
    }
  }

  // Set value is not allowed (yet)
  else if (pdu.type == SNMP::PDU_SET) {
    pdu.error_status = SNMP::READ_ONLY;
  }
  return (true);
}



// HTML end of line
#define CRLF "\r\n"

// Example WebServer that responds with HTTP page with state of pins 
class WebServer : public HTTP::Server {
public:
  // Construct WebServer and initiate sequence counter
  WebServer() : m_nr(0) {}

  // Response member function
  virtual void on_request(char* http);

private:
  // Request sequence number
  uint16_t m_nr;
};

void 
WebServer::on_request(char* http)
{
  // Uptime in seconds
  uint32_t uptime =  Watchdog::millis() / 1000;
  uint16_t h = uptime / 3600;
  uint8_t m = (uptime / 60) % 60;
  uint8_t s = uptime % 60;

  // Bind the socket to an iostream
  IOStream page(m_sock);
  INET::addr_t addr;

  // Get client connection information; MAC, IP address and port
  m_sock->get_src(addr);

  // Reply page; header and footer are static, contents dynamic
  static const char header[] __PROGMEM = 
    "HTTP/1.1 200 OK" CRLF
    "Content-Type: text/html" CRLF
    "Connection: close" CRLF 
    "Refresh: 5" CRLF CRLF
    "<!DOCTYPE HTML>" CRLF
    "<HTML>" CRLF
    "<HEAD><TITLE>CosaWebServer</TITLE></HEAD>" CRLF 
    "<BODY>" CRLF;
  static const char footer[] __PROGMEM = 
    "</BODY>" CRLF 
    "</HTML>";
  static const char BR[] __PROGMEM = 
    "
" CRLF;

  // Construct the page; header-contents-footer
  page << header;
  for (uint8_t i = 0; i < 14; i++)
    page << PSTR("D") << i << PSTR(": ") << InputPin::read(i) << BR;
  for (uint8_t i = 0; i < 4; i++)
    page << PSTR("A") << i << PSTR(": ") << AnalogPin::sample(i) << BR;
  page << PSTR("Vcc (mV): ") << AnalogPin::bandgap() << BR;
  page << PSTR("Memory (byte): ") << free_memory() << BR;
  page << PSTR("Uptime (h:m:s): ") << h << ':' << m << ':' << s << BR;
  page << PSTR("Request(") << ++m_nr << PSTR("): ") << http << BR;
  page << PSTR("MAC: "); INET::print_mac(page, addr.mac); page << BR;
  page << PSTR("IP: "); INET::print_addr(page, addr.ip, addr.port); page << BR;
  page << footer;

}



// Network configuration
#define IP 192,168,2,129
#define SUBNET 255,255,255,0
#define GATEWAY 192,168,2,254
#define PORTIK 80


static const uint8_t mac[6] __PROGMEM = { 0xde, 0xad, 0xbe, 0xef, 0xfe, 0xed };

// SNMP MIB-2 System configuration
static const char descr[] __PROGMEM = "<service description>";
static const char contact[] __PROGMEM = "<contact information>";
static const char name[] __PROGMEM = "<device name>";
static const char location[] __PROGMEM = "<device location>";

W5100 ethernet(mac);


SNMP::MIB2_SYSTEM mib2(descr, contact, name, location);
ARDUINO_MIB arduino;
SNMP snmp;
WebServer server;


void setup()
{
  uint8_t ip[4] = { IP };
  uint8_t subnet[4] = { SUBNET };

  // Start watchdog and uart. Use uart for trace output
  uart.begin(9600);
  trace.begin(&uart, PSTR("CosaSNMP: started"));
  Watchdog::begin();

  // Start ethernet controller and request network address for hostname
  ASSERT(ethernet.begin_P(PSTR("CosaSNMPAgent")));

  // Alternative give network address and subnet mask
  // ASSERT(ethernet.begin(ip, subnet));

  // Print the given or default network address
  ethernet.get_addr(ip, subnet);
  trace << PSTR("IP = ");
  INET::print_addr(trace, ip);
  trace << endl;
  
  // Print some memory statistics
  TRACE(free_memory());
  TRACE(sizeof(W5100));
  TRACE(sizeof(SNMP));
  TRACE(sizeof(SNMP::OID));
  TRACE(sizeof(SNMP::VALUE));
  TRACE(sizeof(SNMP::PDU));
  TRACE(sizeof(SNMP::MIB2_SYSTEM));
  TRACE(sizeof(ARDUINO_MIB));

  // Start the SNMP manager with a connection-less socket
    ASSERT(server.begin(ethernet.socket(Socket::TCP, 80)));
  ASSERT(snmp.begin(ethernet.socket(Socket::UDP, SNMP::PORT), &mib2, &arduino));
}

void loop()
{


  // Service SNMP requests with given MIB handlers
  server.request();
  SNMP::PDU pdu;
  if (snmp.request(pdu) < 0) return;

#if defined(PRINT_PDU)
  // Print available memory and resulting protocol data unit
  TRACE(free_memory());
//  trace << pdu << endl;
#endif

}

thanks for any inputs on this.

@Mispulin

The quick answer is add a timeout to the requests and it works fine.

void loop()
{
   const uint32_t TIMEOUT = 100L; 
  // Service incoming requests
  server.run(TIMEOUT);
   
  // Service SNMP requests with given MIB handlers
  SNMP::PDU pdu;
  snmp.request(pdu, TIMEOUT);
}

Tested it on an Arduino Leonardo :slight_smile: with an Ethernet Shield.

user@host: cosa leonardo upload
.....
AVR Memory Usage
----------------
Device: atmega32u4

Program:   22380 bytes (68.3% Full)
(.text + .data + .bootloader)

Data:        793 bytes (31.0% Full)
(.data + .bss + .noinit)

The long answer is if you look at the description of HTTP::Server::run() and SNMP:request() there is a timeout parameter that is default blocking.

Ref.

  1. https://dl.dropboxusercontent.com/u/993383/Cosa/doc/html/d0/d12/classHTTP_1_1Server.html#adca760526a455a0e034862daa802acd1
  2. https://dl.dropboxusercontent.com/u/993383/Cosa/doc/html/d8/d36/classSNMP.html#a111be2e37fb479a15df3cc77347097c9

Cheers!

BW: You left out the code in the first post and then in the next post you had removed the copyright notice. And you have only pasted together two example sketches. That is very very very bad practice.

Always post code. Always post environment; board, core, host, versions, versions, version. And always keep copyright notices if you are copying.

Hi & thanks or the answer. I will check on monday to confirm.

Checking just on my mobile and wanted to react to your message - i had to remove the shorten the code due to the max allowed message length on the forum. I do agree that its unfortunate and am sorry that I had to do that. I mentioned that its just two examples mixed together, and as I had to make the message shorter, the big commented block was the first to go.

Thanks for Your help, I was too close to see such an easy fix :slight_smile: could have been there for quite a long time.

@Mispulin

No problems. The intent is more in the line "Please remember to...". And there is no problem with links to the copied code and just posting the changes and some of the context.

Testing new combinations gives insights to new usage and possible conflicts between components or as in this case the drawback with default parameters. They are great when the API is know but while learning they might hide issues.

During the testing I found an issue with the pin numbering in the SNMP part. The SNMP pin index to Cosa Board pin mapping was missing. There is an update with this change and an updated map. Please note that the mapping is not the full Arduino Mega pin set. The SNMP and Web Server part will deliver the same value. Add and adjust digital and analog pin maps. · mikaelpatel/Cosa@d87eec1 · GitHub

Cheers!