Asema IoT Central

Arduino example manual


Chapter 1. Introduction

The Arduino samples comprise free sample code that allows you to test the functionality of Asema IoT Central with real hardware by connecting an Arduino board to it. It contains the following sample applications

  1. A button reader. The typical Hello World intro to playing with an Arduino. Press a button, get a value. Simple.
  2. A potentiometer reader. Get some more value from an Arduino, in this case analog readings of a potentiometer.
  3. A light controller. A more elaborate but still straightforward lighting control sample in which the Arduino sets a pin output to switch for example light on or off after receiving the corresponding command. This demonstrates how to do simple controls with the board.
  4. A solar panel monitor. An example that reads analog measurement input from a solar panel and transforms that into measurement values. This sample demonstrates a typical sensoring application.

The button reader and potentiometer reader use serial port as the communication method and will work directly with the USB cable that connects to the Arduino for programming. They are also small enough to run on any Arduino board.

The light control and solar panel are configured to use an ethernet cable and CoAP protocol. These require some more hardware to be able to connect the cabling, most likely an Arduino Mega.

Chapter 2. Configuring and installing the Arduino code for buttons and potentiometer

To use the serial port samples, all you need to do is to

  • Connect the Arduino board with a USB cable to a PC
  • Copy the sample code to an Arduino IDE and upload it to the board
  • Create a schema on Asema IoT Central that matches the data from the Arduino
  • Create an object Asema IoT Central that uses the schema

Let's look at the sample code for the button example:

const int greenPin = 2;
const int redPin =  3;
const int bluePin =  4;
uint8_t msg[5];

void setup() {
	Serial.begin(9600);
	pinMode(greenPin, INPUT);
	pinMode(redPin, INPUT);
	pinMode(bluePin, INPUT);
	msg[0] = 128;
	msg[4] = 255;
}

void loop() {
	msg[1] = digitalRead(greenPin);
	msg[2] = digitalRead(redPin);
	msg[3] = digitalRead(bluePin);

	for (int i = 0; i < 5; i++) Serial.write(msg[i]);
	delay(10); 
}
			

What we're setting up here is three pins for three color buttons, red, green and blue. The program loops over the pin values, then packs the values to an array and sends the array over serial port. The five byte long message that is sent will contain one preamble byte and one trailing byte as frame markers for parsing the incoming data correctly.

To read this data correctly, we need to define this format at Asema IoT Central. That is done with a schema. Here is a schema for that data:

{
    "preamble": [
        128
    ],
    "single": {
        "attrs": [
            {
                "datatype": "char",
                "len": 1,
                "property": "red_led",
                "start": 0
            },
            {
                "datatype": "char",
                "len": 1,
                "property": "green_led",
                "start": 1
            },
            {
                "datatype": "char",
                "len": 1,
                "property": "blue_led",
                "start": 2
            },
            {
                "datatype": null,
                "len": 1,
                "property": null,
                "start": 3
            }
        ]
    },
    "type": "byte"
}
			

In this schema, we are saying the following

  • There is a one byte preamble with decimal value 128
  • There are four values that follow the preamble, each with a lenght of one byte (the last value is the trailing byte)
  • The bytes start at position 0 (first byte after preamble) and continue to positions 1 and 2
  • Values of those bytes will be stored to properties red_led, green_led and blue_led respectively

To use this schema, do as follows

  1. Login to Asema IoT Central admin UI
  2. Go to Objects > Hardware > Serial
  3. Click on "Add new"
  4. Copy-paste the schema above into the schema field
  5. Give your device a name
  6. Fill in the details of the serial port. Make sure the baud rate matches that of the Arduino (9600 in this case). Stop and parity bits should be fine as defaults.

Once you have added the object, you can view and visualize the button presses with the monitoring tools of the Asema IoT Central.

Chapter 3. Configuring and installing the Arduino code for light control and solar panel

To run the basic example, what you need to do is modify config.h header file, then compile and upload to Arduino. Then, on the Asema IoT Central side, create a new object that matches the settings of you Arduino. That's pretty much it to get your board configured and connected.

Important

Note that both the Arduino and the Asema IoT Central can run either as server or client. One needs to be the server, one the client. Pay attention to the roles you set up.

3.1. Code structure

The following parts make up the functionality of the samples that use CoAP:

  • SolarpanelServerClient.ino The main Arduino executable for the program.
  • config.h All configuration settings.
  • coap_server.h/.c A generic CoAP library. There should be no need to touch these files.
  • endpoints.h/.c Definitions of sample services the Arduino responds to when in server mode. Edit this if you want to create new applications.
  • solarpanel.h/.c A sample application logic for hardware connectivity. Reads values from a solar panel as raw analog data and converts to digital readings.

3.2. Settings

All settings can be found in config.h It contains four parts:

  1. A define to switch between client mode and server mode
  2. Common settings
  3. Settings only needed for running Arduino as CoAP client
  4. Settings only needed for running Arduino as CoAP server

Explanation of each part is found later in this document.

3.3. Choosing between server and client

One setting SERVER_MODE will determine whether the CoAP code on the Arduino runs as server or client. With value 1 the server parts will be compiled in, with value 0 the client code gets compiled.

It is up to you to decide which mode to use. The applicability will for instance depend on whether you can set up a fixed or in some cases public IP number to which party. Usually the server should have the fixed IP. The choice also depends on how much data traffic you wish to have. When the Arduino works in server mode, you can for instance set up a configuration where for instance traffic only occurs when the user of an app presses a button. Then again, if you are looking to record values at regular intervals, the Arduino most likely should be a client.

3.4. Common settings

You will always need to modify the common settings in config.h to match your network configuration.

3.4.1. Network IP address

In network settings, you may either use DHCP to try to configure the network automatically or use manual settings.

static uint8_t mac[]. MAC address of your Arduino board. Set to match your board.

#define USE_DHCP 1. Uncomment to use DHCP instead of manual IP configuration.

IPAddress local_ip. The manually set IP address of your Arduino board.

IPAddress dns_ip. The manually set IP address of primary DNS server.

IPAddress gateway_ip. The manually set IP address of default gatway.

3.4.2. Network time server

As the sample code will send sensoring values with a timestamp, it is recommended that you set the Arduino clock from a network time server (NTP). Configure the settings for the server as follows

IPAddress ntp_server_ip. The IP address of the NTP server.

#define NTP_SERVER_PORT. The listening port number of NTP server. By default, NTP server uses port 123.

#define NTP_LOCAL_PORT. You can pick any unused UDP port number of Arduino, the number should be larger than 1024, and not 5683.

3.5. Configuring Arduino as server

To run Arduino as server, find the setting SERVER_MODE. Set it as follows

#define SERVER_MODE 1

3.5.1. Configure the request path

The following variables are needed to define the paths at which the Arduino responds to requests to a particular application. These are for the two sample applications. If you create applications of your own on the Arduino, define similar other path names to separate the application calls from each other.

#define SAMPLE_LIGHT_APPLICATION_CALL_PATH. Path to the sample light application.

#define SAMPLE_SOLAR_PANEL_APPLICATION_CALL_PATH. Path to the sample solar panel application.

3.6. Configuring Arduino as a client

To run Arduino as client, find the setting SERVER_MODE. Set it as follows

#define SERVER_MODE 0

3.6.1. Configure the server end point

The following variables are IoT Central’s CoAP server IP address and port number.

IPAddress remote_server_ip. The IP address of Asema IoT Central you'll be connecting to.

int remote_server_port. The port Asema IoT Central you'll be connecting to listens to (default is 5683).

3.6.2. Configure data identifiers

char* data_feed_url_service. The path of the inbound data feed service. This should be set to feed.

char* data_feed_url_unit. The unique data identifier of data coming from this unit. For example mydata.

uint8_t data_feed_url_service_length. Make this match the number of characters in data_feed_url_service.

uint8_t data_feed_url_unit_length. Make this match the number of characters in data_feed_url_unit.

3.6.3. Set data send rate

#define CLIENT_DATA_SEND_INTERVAL_SECONDS. Set to your desired value how often data is sent.

Chapter 4. Configuring Asema IoT Central

4.1. Configuring Asema IoT Central as CoAP server

For using together with Arduino client mode, IoT Central’s built-in CoAP server should be enabled. With IoT Central’s CoAP server enabled, Arduino CoAP client application can directly report data to IoT Central. The following steps are for enabling IoT Central’s CoAP server.

4.1.1. Add a request parser data schema

  1. From IoT Central main page, click “Objects” tag, it opens “Control and monitor” page as left part of Figure 4.1, “IoT Central Control and Monitor page”.
  2. On “Control and monitor” page, click the “>” beside “Server API objects” item, it opens “Server API objects” page as left part of Figure 4.2, “Server API objects page”.
  3. On “Server API objects” page, click the “>” beside “API schemas” item, then click “+ Add new”, this opens “Schemas” page that specifies how IoTC should interpret received data from Arduino CoAP client. Input name and schema there, then click “save” button.

Figure 4.1. IoT Central Control and Monitor page

IoT Central Control and Monitor page

Figure 4.2. Server API objects page

Server API objects page

4.1.2. Define a schema that matches the data from your Arduino

The sample code on the Arduino, when in client mode, will send at regular intervals a UDP packet with 10 bytes as payload. When received, Asema IoT Central will attempt to parse that data and assign the values as properties to an object. To be able to do this, the parser needs information on the strcuture of this data, i.e. a schema. In the data, the first four are the timestamp as 32 bit int corresponding to seconds from epoch. The next four bytes are the measurement reading as 32 bit float. The trailing two bytes are always zeros and should be discarded. The following is a sample schema matches the data from the example code.

{
    "type": "byte",
    "single": {
        "attrs": [
            {
                "datatype": "integer",
                "start": 0,
				"len": 4,
                "property": "timestamp"
            },
            {
                "datatype": "float",
                "start": 4,
				"len": 4,
                "property": "watts_generated"
            },
            {
                "datatype": null,
                "start": 8,
				"len": 2,
                "property": null
            }
        ]
    }
}
					

4.1.3. Create a new object and link it with the schema

On “Server API objects” page, click the “>” beside “API objects” item, then click “+ Add new”, this opens “Data feeds” page like right part of Figure 4.3, “Data Feeds page”. On “Data Feeds” page, the following items are worth of attention.

Figure 4.3. Data Feeds page

Data Feeds page


  • Name – a unique name for your device or what it represents. E.g. "solarpanel" or "bedroom lamp"
  • Protocol – choose CoAP
  • Schema – choose the schema you've just created in the previous step.
  • Identifier – make this match the identifier you set up to your Arduino board. See: 3.6.2, “Configure data identifiers” .

Finally, click “Save” button.

4.2. Configuring Asema IoT Central as a client

When CoAP client mode is enabled, Asema IoT Central will poll Arduino’s CoAP server regularly. The following steps are for enabling Asema IoT Central’s CoAP client.

4.2.1. Add a request serializer data schema

  1. From IoT Central main page, click “Objects” tag, it opens “Control and monitor” page, as left part of Figure 4.1, “IoT Central Control and Monitor page”.
  2. On “Control and monitor” page, click the “>” beside “Network client objects”, it opens “Network client objects” page, like left part of Figure 4.4, “Network client objects page”.
  3. On “Network client objects” page, click “>” beside “Client request serializers” item, then click “+ Add new”, it opens “Request serializer” page, like the right part of Figure 4.4, “Network client objects page”. Input name and Schema there, then click “save” button.

Figure 4.4. Network client objects page

Network client objects page


4.2.2. Define a request schema that matches the data expected by your Arduino

This schema specifies what kind of requests Asema IoT Central sends to the CoAP server on Arduino to fetch data, primarily the payloads. In the sample application on the Arduino, the requests are processed as GET requests. As GET has no payload, the schema is also pretty much empty. All you have to do is to define one empty request i.e. {}. The resulting schema looks like this:

{
    "requests": [
        {}
    ]
}
					

For details on how to define schemas that have some actual content, in case you for instance build Arduino applications that need POST. please refer to the Asema IoT Central schema design manual.

4.2.3. Add a response parser data schema

This schema specifies how IoTC should interpret response message from Arduino CoAP server, which contains actual data IoTC is asking for.
  1. On “Network client objects” page, click “>” beside “Client response parsers” item, then click “+ Add new”, it opens “Response parser” page.
  2. Input name and Schema there, then click “save” button.

4.2.4. Define a schema that matches the data sent back by your Arduino

In the sample application, Arduino responds with an array of 10 bytes. The first four are the timestamp as 32 bit int corresponding to seconds from epoch. The next found bytes are the measurement reading as 32 bit float. The trailing two bytes are always zeros. The following schema describes this data to the parser and tells it to insert the data into two properties the an object: timestamp and watts_generated

{
    "type": "byte",
    "single": {
        "attrs": [
            {
                "datatype": "integer",
                "start": 0,
                "len": 4,
                "property": "timestamp"
            },
            {
                "datatype": "float",
				"start": 4,
				"len": 4,
                "property": "watts_generated"
            },
            {
                "datatype": null,
                "start": 8,
				"len": 2,
                "property": null
            }
        ]
    }
}
					

4.2.5. Create a new object and link it with the schemas

On “Network client objects” page, click “>” beside “Client objects” item, then click “+ Add new”, it opens “Data pull clients” page, like right part of Figure 4.5, “Data pull clients page”. On “Data pull clients” page, the following items are worth of attention.

Figure 4.5. Data pull clients page

Data pull clients page


  • Name – a unique name for your device or what it represents. E.g. "solarpanel" or "bedroom lamp"
  • Active – make sure it is checked, if non-active your Arduino will not be polled for values..
  • Protocol – choose CoAP
  • Server address – The IP address of your Arduino board.
  • Path – make this match the request path of the sample application on Arduino you set up in 3.5.1, “Configure the request path”.
  • Querying of values – check “On timer” if you want value polling on regular intervals
  • Timer interval – How often does Asema IoT Central request data from Arduino. In seconds.
  • Request schema – Choose the request schema you created in the previous configuration step
  • Response schema – Choose the response schema you created in the previous configuration step

Finally, click save button.

Colophon

<bookinfo>Asema Electronics Ltd<copyright><year>2011-2019</year></copyright><legalnotice>

No part of this publication may be reproduced, published, stored in an electronic database, or transmitted, in any form or by any means, electronic, mechanical, recording, or otherwise, for any purpose, without the prior written permission from Asema Electronics Ltd.

Asema E is a registered trademark of Asema Electronics Ltd.

</legalnotice>
</bookinfo>