API Usage

The following sections describe each API module. The functions are presented in a simplified form here as a quick reference; please see the RIIM SDK API Reference document included in the SDK for details. The RIIM SDK API Reference is distributed with the SDK and is located at RIIM_SDK/docs/RIIM_API_Reference.html.

Errors, Exceptions and Faults

The RIIM SDK provides a comprehensive error handling mechanism. Most functions return a UAPI_Status code to indicate success or failure. Always check the return value of API calls and handle errors appropriately. Some functions return other types instead, for example a boolean, a count, or a handle (such as Timer.create).

UAPI_Status return codes

Code

Meaning

UAPI_OK

Success

UAPI_IN_PROGRESS

Operation started and still in progress

UAPI_FINISHED

Operation finished

UAPI_INVALID_CALL

The call is not valid in the current context

UAPI_INVALID_PARAMETER

A parameter is invalid

UAPI_NOT_FOUND

The requested item was not found

UAPI_OUT_OF_MEMORY

Not enough memory

UAPI_BUSY

The resource is busy

UAPI_BAD_STATE

The call is not valid in the current state

UAPI_NOT_SUPPORTED

The function is not supported, for example with the selected MAC type

UAPI_NOT_CONNECTED

Not connected

UAPI_INVALID_VALUE

A value is invalid or out of range

UAPI_FAIL

General failure

For unforeseen runtime and asynchronous errors and exceptions, the RIIM SDK includes a fault handler that can be used to capture and log error information. The fault callback receives a FaultStruct with the fault type (FAULT_MEMORY, FAULT_RADIO, FAULT_NETWORK, FAULT_HARDWARE or FAULT_INTERNAL_ERROR), a fault value, and optionally a pointer to additional data and its length.

Error handling example code
void faultCallback(FaultStruct *fault)
{
    Util.printf("Fault occurred. Type: %i ,  Value: %u\n", fault->FaultType, fault->FaultValue);
}

RIIM_SETUP()
{
    // ..... existing code .....

    Node.RegisterFaultCallback(faultCallback);

    // ..... existing code .....
}

Note

RIIM includes a stack analysis algorithm. If a stack overflow is detected, the module will reset immediately, and no fault callback will be executed. This is by design to limit damage and erroneous behavior. After reset, the reset reason can be read using Debug.getResetReason(). It will show up as a software reset: 0x06 (Software reset via SYSRESET).

Multicast

Multicast is supported for IPv6 transmissions that do not require responses. This means that you can use multicast for the functions UDP.send6 and CoAP.sendNoAck. In the RIIM wireless network, multicast acts as a broadcast, since the target group is “all nodes.” The following example shows how to send a UDP packet to all nodes in the network.

Multicast delivery is tuned with the MPL parameters in RIIMConfig and with the NODEPARAM_MULTICAST_LIFETIME and NODEPARAM_MULTICAST_GUARDTIME node parameters. See Network Tuning and the Node module below.

Multicast example code
const IPAddr Addr=UAPI_ADDR_ALL_RIIM_NODES;

UDP.send6(Addr, 12345, payload, payloadSize);

One-hop Multicast

RIIM also supports multicast to a node’s immediate neighbors only. A multicast sent like this will not be able to hop and will only be responded to by nodes within radio range of the sending node.

One-hop multicast example code
const IPAddr Addr=UAPI_ADDR_LINKLOCAL_NODES;

UDP.send6(Addr, 12345, payload, payloadSize);

RIIM_UAPI

All API documentation has been moved to Doxygen. The Doxygen output is distributed as part of the SDK.

This is basically an include file that includes everything you need to develop in ICI. It includes all User API definitions and needed standard C header files.

Simply put this include line on top of your source file:

#include "RIIM_UAPI.h"

Each API module is accessed through a global object with the name of the module: ADC, Clock, CoAP, Debug, Ethernet, GPIO, I2C, LongRangeBroadcast, Network, Node, NVS, OTA, SECUART, SPI, Timer, UART, UDP and Util. The functions of a module are called through this object, for example Timer.create(...).

The ICI application entry point is RIIM_SETUP(). It must return a UAPI_Status, and returns UAPI_OK when the setup went well.

The SDK also provides the time constants MILLISECOND, SECOND(S) and MINUTE(S), all expressed in milliseconds, for use with timers. For example, 5*SECOND equals 5000.

API Descriptions

ADC

The ADC module lets you sample and convert the analog input of the module.

RC18xx-IPM supports 2 ADC channels, called ADC0 and ADC1.

ADC.init() selects the channel, the reference voltage and the sampling duration. The reference is either ADC_FIXED_REFERENCE (a fixed internal 4.3 V reference) or ADC_BATTERY_REFERENCE (scales with the supply voltage). The sampling duration ranges from ADC_SAMPLING_DURATION_2_7_US to ADC_SAMPLING_DURATION_10_9_MS. A longer sampling duration gives higher accuracy for inputs with a high source impedance, at the cost of a longer conversion time.

ADC.convert() returns the raw 16-bit conversion result, while ADC.convertToMicroVolts() returns the result as a 32-bit value in microvolts. All ADC functions return UAPI_OK on success and UAPI_FAIL on failure.

Warning

Do not exceed the maximum GPIO voltage, even when using ADC_FIXED_REFERENCE. The pin does not tolerate higher voltages.

The following example shows an example usage where the ADC is initialized, read, and the value is converted to millivolts and printed on the console.

ADC example code
static uint32_t milliVolts;

void ADC_DemoFunc()
{
    milliVolts=0;

    // Set up interface
    ADC.init(ADC0, ADC_FIXED_REFERENCE, ADC_SAMPLING_DURATION_10_6_US);

    ADC.convertToMicroVolts(ADC0, &milliVolts);
    milliVolts /= 1000;

    // Print directly to console to show the latest values
    Util.printf("ADC sensor read: Voltage(mV): %i\n",milliVolts);

    return;
}

The following functions are part of the ADC module.

Function

Description

init

Initializes the ADC module input

convert

Convert input voltage to its raw ADC value

convertToMicroVolts

Convert input voltage to microvolts

Clock

Note

The Clock API requires TSCH to work.

The Clock module provides ways to synchronize and distribute global time throughout the RIIM network. All nodes that are part of a network are synchronized to within a few milliseconds of each other, enabling synchronous actions to take place across the RIIM network.

Note

For the border router, a call to the Clock API can only be made > 100 ms after the StartBorderRouter command.

The Clock module provides two ways of representing time: Time of Day (ToD) and Epoch. ToD provides a 24-hour clock represented by hour, minute, second, and millisecond. It can be used to perform an action at a specific time during a day and can be repetitive. Epoch provides an absolute time that’s always increasing. It’s represented in milliseconds, and can be used to measure absolute time or trigger an action at some specific time. It’s not repetitive.

Both are derived from the network absolute time, which is the time in milliseconds since the network was started by the border router. ToD is the absolute time plus a ToD offset, modulo 24 hours, and Epoch is the absolute time plus an epoch offset. The offsets are set implicitly by setToD and setEpoch, and are distributed to the other nodes by sendClockToAllNodes. A node can ask the border router for the current values with getClockFromBR.

Note

When the node is not using TSCH, the functions that depend on the network time (getToD, setToD, getEpoch, setEpoch, sendClockToAllNodes and getClockFromBR) return UAPI_NOT_SUPPORTED. getToD and getEpoch return UAPI_FAIL if the time has not been set yet.

Timed actions are registered with registerToDTimedAction and registerEpochTimedAction. Up to 10 ToD actions and 10 epoch actions can be registered at the same time. Both functions return an ID that is passed to stopToDTimedAction or stopEpochTimedAction, or -1 if the action could not be registered. A ToD action can optionally repeat every day.

The clock synchronization messages use UDP port 63000, which is therefore reserved.

Function

Description

getToD

Returns the ToD

setToD

Set the ToD

getEpoch

Returns the Epoch

setEpoch

Set the Epoch

getAbsoluteTime

Get absolute time

registerToDTimedAction

Register a ToD action

registerEpochTimedAction

Register an Epoch action

stopToDTimedAction

Stop a planned ToD action

stopEpochTimedAction

Stop a planned epoch action

sendClockToAllNodes

Send Epoch and ToD to all nodes

getClockFromBR

Retrieve the Epoch and ToD from the border router

getOffsets

Get the raw offset values for ToD and epoch

setOffsets

Set the raw offset values for ToD and epoch

getLastSynchronizeTimestamp

Get timestamp when the node last received a clock synchronization

Clock example code
EpochType epoch; // Set to zero in RIIM_SETUP()

// Epoch callback
void epochCallback(void)
{
    EpochType thisEpoch;
    Clock.getEpoch(&thisEpoch);
    Util.printf("Epoch callback at : %i" , (int32_t)thisEpoch);

    // Set next callback to be in 5 seconds
    epoch=epoch+5000;
    Clock.registerEpochTimedAction(&epoch, epochCallback);
    Util.printf(" - New set to : %i\n" , (int32_t)epoch);

    return;
}
Time of day example code
static ToDType timeOfDay;
static int8_t  todAction;

static void todCallback(void)
{
    // Runs every day at 22:25:00.000
}

static void registerToD(void)
{
    timeOfDay.Hour        = 22;
    timeOfDay.Minute      = 25;
    timeOfDay.Second      = 0;
    timeOfDay.Millisecond = 0;

    // The second parameter selects whether the action repeats every day
    todAction = Clock.registerToDTimedAction(&timeOfDay, true, todCallback);
}

CoAP

The CoAP module lets you start and run a CoAP server and lets you transmit CoAP messages to and from a server. Whether the server is at the border router or on a mesh router is up to the implementer. The CoAP resources on the server side need to be registered along with a callback function (ResourceHandler). This function is called every time the module receives a CoAP request for the resource. The ResourceHandler receives the request type (GET, POST, PUT or DELETE), the IP address of the requester, and the request payload. It also receives a pointer to the response buffer and the response size that will be sent upon returning from the callback. This response can be filled in during the callback, if a value is intended to be returned in the response. The generateResponse() function is a support function to fill the response with boundary-checked data.

The client needs to connectToServer to allow communication with the server. A node can only be connected to one CoAP server at a time. It also needs to register a callback function to handle responses from the server. This can be an empty response to a PUT command or a response with a value related to a GET command. Then the client can issue CoAP requests when it wants and wait for responses.

The CoAP protocol includes automatic retries in case of no response. The retries are after 20 seconds and then it times out after slightly over 1 minute. Observe that the CoAP payload is limited to 127 bytes (CoAP_MAXSIZE).

CoAP requests can be sent with DTLS by setting the secure parameter of CoAP.send and CoAP.sendNoAck to true. For DTLS to work, the key must be set with CoAP.setKey (maximum 16 bytes). The identity can be set with CoAP.setIdentity (maximum 32 bytes). If it is not set, the identity “RIIMUser” is used. Note that connectToServer returns UAPI_OK if DTLS is not used.

        sequenceDiagram
    participant Client
    participant Server

    Server->>Server: CoAP.registerResource(ResourceHandler)
    Client->>Client: CoAP.connectToServer(Server)
    Client->>Client: CoAP.registerResponseHandler(RespHandler)
    Client->>Client: CoAP.send()
    Client->>Server: "CoAP REQUEST"

    Server->>Server: ResourceHandler()
    Server->>Client: "RESPONSE"
    Client->>Client: RespHandler()
    

The following example demonstrates how you set up a response handler and a resource access handler. When this node receives a PUT, POST, GET or DELETE CoAP message, it will call the CoAP_Handler routine. Five CoAP resources can be registered, and CoAP.registerResource will return an error if more resources are requested.

CoAP example code
static const char Resource_Name[]="data";

static void CoAP_Handler(RequestType type, IPAddr src_ipAddr, uint8_t *payload, uint8_t payloadSize, uint8_t *response, uint8_t *responseSize)
{
    // In this example we only print the payload directly to the UART
    Debug.printPayload(payload, payloadSize);
    Util.printf("\n"); // Add a newline for readability in console
    return;
}

void ResponseHandler(const uint8_t *payload, uint8_t payload_size)
{
    Util.printf("# Got CoAP Response. Doing nothing with it.\n");
    return;
}

RIIM_SETUP()
{
    Network.startBorderRouter(NULL, NULL, NULL, NULL);

    // Setup coap resource. The second parameter (resourceID) is deprecated and ignored
    CoAP.registerResponseHandler(ResponseHandler);
    CoAP.registerResource(Resource_Name,0,CoAP_Handler);

    return UAPI_OK;
}

The following functions are part of the CoAP module.

Function

Description

init

Initializes the CoAP module. Normally not needed in the user application

connectToServer

Connect to a CoAP server using URI. This must be done before accessing it.

connectToServer4

Connect to a CoAP server using IPv4, optionally with DTLS. This must be done before accessing it.

connectToServer6

Connect to a CoAP server using IPv6, optionally with DTLS. This must be done before accessing it.

setKey

Set DTLS key (maximum 16 bytes). Must be set for DTLS to work

setIdentity

Set DTLS Identity (maximum 32 bytes). Default is “RIIMUser”

registerResponseHandler

Register a handler to be executed when a CoAP response arrives

registerResource

Register a new resource that will be accessible on the node

generateResponse

Generate a response message and send it back to the caller

send

Send a GET, PUT, POST or DELETE message to a CoAP server

sendNoAck

Send a GET, PUT, POST or DELETE message to a CoAP server, but don’t ask for a CoAP response

disconnectFromServer

Disconnect from the CoAP server

Note: CoAP packets will be retransmitted several times if they’re lost on the way to their destination. Each retransmission with an increased timeout. The total time might be in the order of minutes, and hence the CoAP queue can easily fill up. It’s therefore important to wait for the CoAP response before sending new CoAP packets.

Debug

The Debug module contains useful functions for debugging.

Important

Debug.printSetup() will not show all updated configuration information immediately in RIIM_SETUP(). Some configurations, such as maximum number of nodes in the network, will only be set after RIIM_SETUP() completes as that is when the configuration is actually applied. You can still call it in RIIM_SETUP(), but it is better to call it in a callback, for example via a one-shot timer.

The following example shows how you can dump the configuration of the node by calling Debug.printSetup().

Note

If output is missing, see Cannot connect to bootloader during upload and Quickstart.

Debug example code (print setup via timer callback)
static uint8_t debugTimer;

static void printSetupCallback(void)
{
    Debug.printSetup();
}

RIIM_SETUP()
{
    Network.startBorderRouter(NULL, NULL, NULL, NULL);

    // Run Debug.printSetup() from a callback after startup
    debugTimer = Timer.create(ONE_SHOT, 1000, printSetupCallback);
    Timer.start(debugTimer);

    return UAPI_OK;
}

The following functions are part of the Debug module.

Function

Description

printPayload

Dump the payload to the UART

printSetup

Print the current node setup on the UART

printIPAddr

Print IPAddr

radioTest

Test the radio in continuous unmodulated, modulated or receive mode.

getResetReason

Get the reset code for the last module reset

Note

For the radioTest function:

  1. The test mode is selected with RadioTest_Unmodulated (continuous unmodulated carrier), RadioTest_Modulated (continuous modulated transmission) or RadioTest_RX (continuous reception). The test runs on the channel set with Network.setChannel().

  2. This command is blocking, meaning that the module needs to be externally reset after it is called.

  3. This command can’t be called in RIIM_SETUP(), but must be executed in a callback

Debug.getResetReason() returns one of the following reset codes:

Code

Reset reason

0x0

Power on

0x1

Pin reset

0x2

Brown out detect on VDDS

0x4

Brown out detect on VDDR

0x5

Clock loss detect

0x6

Software reset via SYSRESET register

0x7

Software reset via PRCM warm reset request

Ethernet

The Ethernet module is used to interface with the Ethernet system. The Ethernet MAC is by default set using the EUI64 / IEEE address of the module, which is unique for each module.

Note

The Ethernet module (and its hardware) is automatically enabled if any of the IPv4 parameters (address, netmask or gateway) in the call Network.startBorderRouter is non-NULL. The IPv6 prefix parameter does not enable Ethernet.

Important

Ensure that the Ethernet hardware is connected if enabling Ethernet.

The following example shows how to read the MAC address.

Ethernet example code
RIIM_SETUP()
{
    // Set Ethernet MAC address
    uint8_t Mac[6];
    Ethernet.getMACAddress(Mac);

    return UAPI_OK;
}

Function

Description

init

Initialize the Ethernet module. Normally not used in the user application

getMACAddress

Read the Ethernet MAC address

GPIO

The GPIO module is used to control the GPIOs. By default all GPIOs are tri-state inputs with no pullup or pulldown.

All GPIOs also include PWM controllers capable of working autonomously.

Note

PWM could impact current consumption

The GPIO pins are named GPIO_0 to GPIO_8. A pin can be set to INPUT, OUTPUT (push-pull) or OUTPUT_OPEN_DRAIN, and inputs can have a pull-up or pull-down resistor (PULL_UP, PULL_DOWN or NO_PULL).

GPIO.setHandler() registers a handler that is called when the selected transition happens on a pin: RISING_EDGE, FALLING_EDGE or BOTH_EDGES. Using NO_EDGE disables the interrupt. The handler receives the pin that triggered.

GPIO.startPWM() takes the pin, the frequency in Hz and the duty cycle in per thousand (0-1000, so 500 is 50%). To keep the accuracy better than 1%, the frequency must be below 480 kHz. Only one pin can have an active PWM at any time.

The following example shows how to configure GPIO 9 as output and set it to logical ‘1’.

GPIO example code
RIIM_SETUP()
{
    // Set up GPIO 9
    GPIO.setDirection(GPIO_9, OUTPUT);
    GPIO.setValue(GPIO_9, HIGH);

    return UAPI_OK;
}

The following functions are part of the GPIO module.

Function

Description

init

Initialize the GPIO module

setDirection

Set the GPIO direction to input or output

setPull

Set pullup, pulldown or no pull on an input pin

setHandler

Register a handler to be called when a specific transition happens on a GPIO

setValue

Set the value on an output GPIO to logical 0 or 1

toggle

Invert the output value on a GPIO

getValue

Read the value of a GPIO pin

startPWM

Start PWM output

stopPWM

Stop PWM output

stopPWMWithIndex

Stop PWM output on a specific PWM pin index

I2C

The I2C module provides functions needed to interface with the I2C bus. It always operates as master and supports clock stretching. It supports two speeds: 100 KHz and 400 KHz. The slave address is the 7-bit address. If the write or read buffer is NULL in I2C.transfer, the write or read phase is skipped. The functions return UAPI_BAD_STATE if the I2C module has not been initialized with I2C.init, and UAPI_FAIL on a bus error.

The following example demonstrates how the module is initialized and an example transmission towards a Sensirion SHT35 Temperature/Humidity sensor.

I2C example code
static void ReadSensor()
{
    static uint8_t wbuf[2];
    static uint8_t rbuf[10];

    // The command 0x2C0D starts a medium repeatability measurement
    // with clock stretching enabled. See Sensirion SHT35 datasheet.
    wbuf[0]=0x2C;
    wbuf[1]=0x0D;

    I2C.transfer(0x44,wbuf,2,rbuf, 7);

    .......

}

RIIM_SETUP()
{
    // Set up interface towards the SHT35-sensor
    I2C.init(I2C_400KHZ);

    .........

    return UAPI_OK;
}

The following functions are part of the I2C module.

Function

Description

init

Initializes the I2C driver with the chosen speed

transfer

Transfers data both to and from the slave at bus address SlaveAddress. Data is first written on bus, then read

read

Perform only read on the I2C bus

write

Perform only write on the I2C bus

close

Closes the I2C interface

LongRangeBroadcast

The LongRangeBroadcast module provides functions for sending and receiving long range broadcast messages. Long range broadcast messages are used to communicate with as many nodes in a network as possible simultaneously without using hopping. It uses lower bitrates and a pre-defined channel.

Important

Long range broadcast messages are limited to 1 to 4 bytes of payload. A payload of any other size is rejected with UAPI_INVALID_VALUE.

Important

Long range broadcast requires TSCH. With CSMA (single channel), LongRangeBroadcast.send returns UAPI_NOT_SUPPORTED. The message is only transmitted while the node is part of a network. It’s also not supported with the 6TiSCH minimal schedule (see 6TiSCH Minimal Schedule). The period of the long range broadcast slots is set with NODEPARAM_LRB_COMMON_PERIOD.

Note

Long range broadcast messages are typically used for emergency or alarm messages that need to reach as many nodes as possible in a network in a short time, even if the nodes are far away from each other.

LongRangeBroadcast example code
static const uint8_t msg[] = {'T', 'e', 's', 't'}; // Max 4 bytes

void lrb_handler(IPAddr sourceIpAddr, uint8_t* payload, uint8_t payloadSize)
{
    Debug.printPayload(payload, payloadSize);
}

void lrb_send_example()
{
    LongRangeBroadcast.send(msg, sizeof(msg));
}

RIIM_SETUP()
{
    // ..... existing code .....

    // Register the handler for incoming long range broadcast messages
    LongRangeBroadcast.setRxHandler(lrb_handler);

    // ..... existing code .....
}

Function

Description

send

Send a long-range broadcast packet

setRxHandler

Register a handler for incoming long-range broadcast packets

NVS

The NVS module provides access to internal and external non-volatile storage.

The internal storage is located in the microcontroller FLASH. It is 8 KB (one page) and can be erased approximately 60000 times. Its content is preserved across resets and power cycles. A FLASH bit can only be changed from ‘1’ to ‘0’ by a write. To change a bit back to ‘1’, the whole page must be erased, which fills it with 0xFF. The memory can be written several times without erasing in between, as long as these limits are respected, and can therefore be appended to until the page is full. There is no buffer for temporary storage of the content during an erase. If the content must be kept, the ICI application needs to read it out, erase the page, and write it back, while staying within the RAM available to the ICI application.

The external storage is an SPI FLASH. NVS.InitExternalMemory erases the first sector and resets the record of which sectors have been erased. NVS.WriteExternalMemory erases the sectors it touches the first time they are written after the initialization. A maximum of 80 bytes can be read per NVS.ReadExternalMemory call, and the function returns the number of bytes read, or 0 on failure. The other functions return UAPI_OK on success and UAPI_FAIL on failure.

Function

Description

WriteMemory

Write data to internal non-volatile memory

ReadMemory

Read data from internal non-volatile memory

ClearMemory

Erase internal non-volatile memory page

WriteExternalMemory

Write data to external non-volatile memory

ReadExternalMemory

Read data from external non-volatile memory

InitExternalMemory

Initialize external non-volatile memory

Network

The Network module provides functions needed for network operations. Before the node can join any network, it must be started by a call to either startSlip, startBorderRouter, startMeshRouter, or startLeaf. Some functions will only have an effect depending on the RIIM variant (single channel or TSCH) used.

Note

The UART API can’t be used if SLIP is used, as SLIP uses the UART to transfer data. After Network.startSlip the UART functions and Util.printf no longer work. In this case, use SECUART instead.

Important

The Ethernet module (and its hardware) is automatically enabled if any of the IPv4 parameters (address, netmask or gateway) in the call Network.startBorderRouter is non-NULL. The IPv6 prefix parameter does not enable Ethernet. Ensure that the Ethernet hardware is connected if using this option.

The following example shows how to start a node as a router:

Network example code
RIIM_SETUP()
{
    // Simply start as a router node. Nothing more is needed.
    Network.startMeshRouter();

    return UAPI_OK;
}

Selecting MAC and bitrate in RIIM_SETUP

The following examples show the typical startup pattern for selecting MAC mode and bitrate in RIIM_SETUP().

Example A - CSMA (single channel)
RIIM_SETUP()
{
    const uint8_t nwKey[16] = {0, 1, 2, 3, 4, 5, 6, 7,
                               8, 9, 10, 11, 12, 13, 14, 15};
    Network.setNWKey((uint8_t *)nwKey);

    Node.SetParameter(NODEPARAM_MACTYPE, MACTypeCSMA);

    // Single channel MAC: choose one RF channel for all nodes.
    // Network.setChannel() returns UAPI_NOT_SUPPORTED when TSCH is used.
    Network.setChannel(32);

    Network.startMeshRouter();
    return UAPI_OK;
}
Example B - TSCH, 50 kbps profile
RIIM_SETUP()
{
    const uint8_t nwKey[16] = {0, 1, 2, 3, 4, 5, 6, 7,
                               8, 9, 10, 11, 12, 13, 14, 15};
    Network.setNWKey((uint8_t *)nwKey);

    Node.SetParameter(NODEPARAM_MACTYPE, MACTypeTSCH);
    Node.SetParameter(NODEPARAM_BITRATE, 50);

    Network.startMeshRouter();
    return UAPI_OK;
}
Example C - TSCH, 150 kbps profile
RIIM_SETUP()
{
    Node.SetParameter(NODEPARAM_MACTYPE, MACTypeTSCH);
    Node.SetParameter(NODEPARAM_BITRATE, 150);

    Network.startMeshRouter();
    return UAPI_OK;
}

Warning

All nodes in the same network must use compatible MAC/bitrate settings. Do not mix 50 kbps and 150 kbps nodes in one network.

The following functions are part of the Network module.

Function

SC

TSCH

Description

startBorderRouter

x

x

Start the node as a Border Router. Takes the IPv6 prefix and the IPv4 address, netmask and gateway. Use NULL for unused parameters

startMeshRouter

x

x

Start the node as a Mesh Router.

startLeaf

x

x

Start the node as a Leaf.

getBorderRouterAddress

x

x

Get the address of the Border Router

getParentRSSI

x

x

Get the RSSI value of the parent. Returns INT16_MIN if the node has no parent

getNeighbors

x

x

Get a list of all neighbors, including RSSI

getNeighborTxPower

x

x

Get configured TX power towards a specific neighbor

getNetworkState

x

x

Get the state of the network

radio_On

x

Turn radio on. Only used in leaf nodes

radio_Off

x

Turn radio off. Only used in leaf nodes

join

x

x

(Re)-join a network

leave

Deprecated. Do not use. Always returns UAPI_NOT_SUPPORTED

setFreqBand

x

x

Set the frequency band. Resets the channel to the default. Cannot be set after the node is started

setPanId

x

x

Set the PAN ID of the node

getPanId

x

x

Get the PAN ID of the node

getAddress

x

x

Get the IP (v6) address of the node

getAddress4

x

X

Get the IPv4 address of the node

getNetworkLinks

x

x

Get a list of links between nodes. Border Router only

setTxPower

x

x

Set the output transmission power

getNodeType

x

x

Get the configured node type

setChannel

x

Set the RF channel to use. Returns UAPI_NOT_SUPPORTED in TSCH

isPartOfNetwork

x

x

Check if a given IP address is part of the network. Border Router only

setNWKey

x

x

Set the network (LLSEC) key

setRobustnessFactor

x

x

Set the node’s robustness factor

setTschMaxBroadcastRate

x

Set the maximum network broadcast period

getNodeCount

x

x

Get the number of nodes in the network. Border Router only

startSlip

x

x

Start the SLIP interface

setTSCHParameters

x

Deprecated. Use Node.SetCurrentConfiguration instead.

reConnect

x

x

Reconnect to (possibly another) network

autoupdateTSCHParameters

x

Enable/disable automatic update of TSCH parameters

setNetworkChangeHandler

x

x

Register a callback for network state changes

stop

x

x

Stop all RF traffic and disjoin any network. Only works for leaf nodes in single channel

Node types and network state

Network.getNodeType() returns one of ROOT_NODE (Border Router with Ethernet), ROOT_STANDALONE_NODE (Border Router without Ethernet), ROUTER_NODE (Mesh Router), LEAF_NODE or UNDEFINED_NODE (not started).

Network.getNetworkState() returns ONLINE or OFFLINE. For a regular Border Router it is always ONLINE. For a SLIP Border Router it is OFFLINE until a prefix has been received. For a Mesh Router or Leaf it is ONLINE when the node is part of a network. Note that it can take a while for a node to notice that it is no longer part of a network. In TSCH this can be 10 minutes or more, and in single channel 30 minutes or more.

Network.setNetworkChangeHandler() registers a callback that is called with a NetworkEvent when the network state changes. It returns the latest network event.

Event

Meaning

NW_EVENT_TSCH_SCAN

The node started scanning for a network

NW_EVENT_TSCH_JOINING

The node is joining a network

NW_EVENT_TSCH_NEW_TIMESOURCE

The node selected a new time source

NW_EVENT_TSCH_ASSOCIATE

The node associated with the network

NW_EVENT_TSCH_DISASSOCIATE

The node disassociated from the network

NW_EVENT_TSCH_LEAVE

The node left the network

Network.getNeighbors() fills a NeighborTable with the interface ID, the RSSI (in dBm) and a parent flag for each neighbor, and returns the number of neighbors. The table has room for up to 128 neighbors, and exactly one of the neighbors is the parent. Network.getNetworkLinks(), Network.isPartOfNetwork() and Network.getNodeCount() can only be used on the Border Router.

Frequency band, channel and output power

Network.setFreqBand() selects the frequency band with one of RF_BAND_868, RF_BAND_915, RF_BAND_920_AUS (Australia), RF_BAND_866_IND (India), RF_BAND_920_VNM (Vietnam), RF_BAND_920_BRA (Brazil), RF_BAND_868_1HOP (868 MHz with a 1 hop restriction, high power channel), RF_BAND_922_TWN (Taiwan) and RF_BAND_922_KOR (Korea). All nodes in the network must use the same band. The channel is reset to the default when the band is changed.

Network.setChannel() selects the RF channel in single channel mode. TSCH hops between channels, so the function returns UAPI_NOT_SUPPORTED when TSCH is used.

Network.setTxPower() sets the output power in dBm. Intermediate values are rounded upwards, and values above the module maximum are limited to the maximum.

Module

Power levels (dBm)

Default

RC1882

-20, -15, -10, -5, 0, 1, 2, … 14

14 dBm

RC1882HP

2, 9, 14, 18, 21, 23, 25, 26, 27

27 dBm

RC1892HP

3, 9, 14, 18, 21, 23, 25, 26, 27

27 dBm

Robustness and broadcast rate

Network.setRobustnessFactor() sets the minimum RSSI (in dBm) a link must have to be used. Links with a weaker RSSI are not made, and an extra hop is created instead. Values are limited to the range -120 to 0. A link that qualifies stays qualified if its RSSI drops up to 5 dB below the limit.

Network.setTschMaxBroadcastRate() sets the maximum period (in seconds) between the Enhanced Beacons broadcast by a node. A shorter period gives faster joining for new nodes but more network traffic and power consumption. If it is set to 0, nodes broadcast no beacons and other nodes will not be able to join the network. The function returns UAPI_NOT_SUPPORTED when CSMA is used.

Node

The Node module contains functions for reading and writing node information and settings.

Node.getNodeInfo() fills a NodeInfo struct with the hardware ID and revision, the platform ID and version, the version of the ICI application, the EUI64 address, the MAC type (see MACType), the bootloader version and the RF data rate in kbps.

Node example code
static void DemoFunc()
{
    NodeInfo info;
    Node.getNodeInfo(&info);
    Util.printf("HW Revision is %i\n", info.Hardware_Rev);

    return;
}

The detailed and advanced settings are available in the RIIMConfig struct. To change them, read the current values with Node.GetCurrentConfiguration(), modify the fields you want to change, and write the struct back with Node.SetCurrentConfiguration(). Node.GetDefaultConfiguration() returns the factory settings.

RIIMConfig fields

Field

Description

RobustnessFactor

Minimum RSSI (dBm) for a link. Default -120. See Network.setRobustnessFactor()

EBBroadcastRate

Rate of broadcast for Enhanced Beacons, in milliseconds (TSCH)

TSCHParameters

Active, Unicast, Shared, Beacon and Root TSCH parameters. See Network Tuning. Active can only be set in RIIM_SETUP() before the network is started

AutoUpdateTSCHParameters

Enable or disable automatic update of TSCH parameters from the network. Default disabled

JoinChannels

Number of channels used for joining. See Network Tuning

RPLParameters

DIOInterval_IMin and DIOInterval_IMax (milliseconds, default 14 and 896) and DAODelay (milliseconds, default 18000). The intervals must be between 2 and 65536, DIOInterval_IMax must not be less than DIOInterval_IMin, and DAODelay must be between 8 and 65535

MPLParameters

Multicast trickle timer settings. See the example below

FreshnessInitialValue

Initial freshness value of neighbors, between 0 and 3. Higher numbers give faster join times, but less tested (for stability) links between nodes

The MPLParameters, RPLParameters and FreshnessInitialValue can only be changed in RIIM_SETUP(). Node.SetCurrentConfiguration() returns UAPI_FAIL if these are changed later, or if a value is invalid.

For the MPL parameters, IMin is given in milliseconds (1 to 1000000), IMax is the number of times IMin is doubled (1 to 15), and K is the break factor (1 to 20). The defaults are IMin = 12500 ms in TSCH and 640 ms in single channel, IMax = 1 and K = 1, for both control and data messages. See Network Tuning for details.

Example setting MPL parameters
RIIM_SETUP()
{
    RIIMConfig Configuration;
    Node.GetCurrentConfiguration(&Configuration);
    Configuration.MPLParameters.MPL_Control_Message_IMin=128;   // Milliseconds
    Configuration.MPLParameters.MPL_Control_Message_IMax=4;     // Doublings of IMin: 128 ms * 2^4 = 2048 ms
    Configuration.MPLParameters.MPL_Control_Message_K=1;
    Configuration.MPLParameters.MPL_Data_Message_IMin=128;      // Milliseconds
    Configuration.MPLParameters.MPL_Data_Message_IMax=5;        // Doublings of IMin: 128 ms * 2^5 = 4096 ms
    Configuration.MPLParameters.MPL_Data_Message_K=3;
    Node.SetCurrentConfiguration(&Configuration);

    return UAPI_OK;
}

The following functions are part of the Node module:

Function

Description

getNodeInfo

Return info about the node: Hardware ID+Revision, Platform ID+Version, Application version, EUI64, MAC type, bootloader version and RF data rate

GetDefaultConfiguration

Get the default configuration (Factory settings)

GetCurrentConfiguration

Get the current (in-use) configuration

SetCurrentConfiguration

Set the current (in-use) configuration

SetParameter

Set a runtime RIIM parameter value

GetParameter

Get a runtime RIIM parameter value

RegisterFaultCallback

Register callback for platform fault events

All NODEPARAM constants are defined in UAPI_Node.h. Use Node.SetParameter(NODEPARAM_xxx, value) to configure them and Node.GetParameter(NODEPARAM_xxx, &value) to read them.

Some parameters may only be set inside RIIM_SETUP(). Calling them after startup will return UAPI_BAD_STATE (NODEPARAM_LRB_COMMON_PERIOD returns UAPI_FAIL).

Parameter

R/W

Valid values

Notes

NODEPARAM_MACTYPE

W

MACTypeTSCH (1), MACTypeCSMA (2)

Must be set in RIIM_SETUP. Default: TSCH. Cannot be read with GetParameter, use Node.getNodeInfo (MAC_Type)

NODEPARAM_BITRATE

R/W

5, 50, 150, 300 (kbps)

Must be set in RIIM_SETUP. Default: 50. Returns UAPI_FAIL for an unsupported bitrate

NODEPARAM_MAX_NUMBER_OF_NEIGHBORS

R/W

≥ 1

RIIM_SETUP only. Returns UAPI_OUT_OF_MEMORY if combined neighbor + DAG node pool is exceeded.

NODEPARAM_MAX_NODES_IN_NETWORK

R/W

≥ 1

RIIM_SETUP only. Returns UAPI_OUT_OF_MEMORY if combined pool is exceeded.

NODEPARAM_LRB_COMMON_PERIOD

R/W

0–255 (slotframe length)

RIIM_SETUP only. Length of the slotframe used for long range broadcast (default 37). TSCH only — not compatible with CSMA. Returns UAPI_INVALID_VALUE if set when CSMA is active. No effect with 6TiSCH minimal.

NODEPARAM_MULTICAST_LIFETIME

R/W

1–120 (minutes)

Can be set at any time. Default: 30.

NODEPARAM_MULTICAST_GUARDTIME

R/W

1–120 (minutes)

Can be set at any time. Default: 4. Should be less than LIFETIME.

NODEPARAM_ENABLE_APC

R/W

1 (enable)

Can be set at any time. Enables Adaptive Power Control. It can’t be disabled again. Reads 1 if enabled.

NODEPARAM_ENABLE_6TISCH_MINIMAL

R/W

1 (enable), 0 (disable)

TSCH only. Default: 0. Uses the 6TiSCH minimal schedule instead of Orchestra. Set it in RIIM_SETUP before the network is started, and use the same setting on all nodes. See 6TiSCH Minimal Schedule.

NODEPARAM_ENABLE_BR_ETHERNET

R only

0, 1

Read only. Use Network.startBorderRouter to control Ethernet.

Common error codes returned by SetParameter:

  • UAPI_BAD_STATE – parameter is setup-only but was called after startup.

  • UAPI_INVALID_VALUE – value is outside the allowed range.

  • UAPI_INVALID_PARAMETER – the parameter ID is unknown. GetParameter also returns this for parameters that cannot be read.

  • UAPI_OUT_OF_MEMORY – combined memory for neighbors and DAG nodes would exceed the pool.

Memory sizing example

The maximum number of neighbors and DAG nodes are set at compile time per variant. They can be overridden in RIIM_SETUP() using NODEPARAM_MAX_NUMBER_OF_NEIGHBORS and NODEPARAM_MAX_NODES_IN_NETWORK. Increasing either reduces the headroom for the other; if the combined pool is exceeded, UAPI_OUT_OF_MEMORY is returned.

Scaling neighbors and DAG nodes for a larger network
RIIM_SETUP()
{
    Node.SetParameter(NODEPARAM_MAX_NUMBER_OF_NEIGHBORS, 30);
    Node.SetParameter(NODEPARAM_MAX_NODES_IN_NETWORK, 200);

    Network.startMeshRouter();
    return UAPI_OK;
}

Multicast tuning example

Adjusting multicast lifetime and guardtime
RIIM_SETUP()
{
    // Reduce from the defaults (30 min lifetime, 4 min guardtime)
    Node.SetParameter(NODEPARAM_MULTICAST_LIFETIME, 5);
    Node.SetParameter(NODEPARAM_MULTICAST_GUARDTIME, 2);

    Network.startMeshRouter();
    return UAPI_OK;
}

Adaptive Power Control (APC) example

Enabling APC
RIIM_SETUP()
{
    Node.SetParameter(NODEPARAM_ENABLE_APC, 1);
    Network.startMeshRouter();
    return UAPI_OK;
}

LPWAN common period example (TSCH only)

Setting LPWAN broadcast period on a Border Router
RIIM_SETUP()
{
    const uint8_t nwKey[16] = {0, 1, 2, 3, 4, 5, 6, 7,
                               8, 9, 10, 11, 12, 13, 14, 15};
    Network.setNWKey((uint8_t *)nwKey);

    Node.SetParameter(NODEPARAM_MACTYPE, MACTypeTSCH);
    Node.SetParameter(NODEPARAM_BITRATE, 50);
    // LPWAN common period is the slotframe length used for long range broadcast.
    // Only valid in TSCH mode — not compatible with CSMA.
    Node.SetParameter(NODEPARAM_LRB_COMMON_PERIOD, 10);

    Network.startBorderRouter(NULL, NULL, NULL, NULL);
    return UAPI_OK;
}

6TiSCH minimal example (TSCH only)

The 6TiSCH minimal schedule replaces Orchestra with one shared slot used by all nodes. It’s simple, but uses more power. See 6TiSCH Minimal Schedule for the trade-offs.

Enabling 6TiSCH minimal
RIIM_SETUP()
{
    Node.SetParameter(NODEPARAM_MACTYPE, MACTypeTSCH);
    Node.SetParameter(NODEPARAM_ENABLE_6TISCH_MINIMAL, 1);

    int64_t enabled = 0;
    Node.GetParameter(NODEPARAM_ENABLE_6TISCH_MINIMAL, &enabled); // enabled == 1

    Network.startMeshRouter();
    return UAPI_OK;
}

SECUART

Note

This is available from platform version 4.1.0 and later

The SECUART module controls the secondary UART port. It can be configured with respect to baud rate, parity, number of data bits, and number of stop bits — identical options to the primary UART. SECUART uses dedicated pins separate from the primary UART and can be used concurrently with SLIP.

RS485 half-duplex — calling SECUART.enableRXTX(true) makes the CTS/RXTX pin toggle automatically around each transmission: the pin goes high just before TX becomes active and low again after TX completes. This drives an RS485 transceiver without requiring additional GPIO logic.

Wake-on-UART — SECUART.wakeOnUART() registers a callback that fires when activity is detected on the SECUART RX pin. This allows the module to enter a low-power sleep state and wake up automatically when an external device starts transmitting.

Advanced receive — SECUART.startReceive_Adv() extends basic receive with configurable intra-byte and total timeouts, a termination byte (reception stops when this byte is seen), and a dynamic-length mode where the first byte received is interpreted as the payload length.

SECUART basic example
static void TXCallback(uint8_t len) { /* transmission complete, len bytes sent */ }

static void DemoFunc()
{
    const uint8_t buffer[] = "Test";

    SECUART.init(115200, UART_PARITY_NONE, UART_DATA_8_BITS, UART_STOP_1_BIT);
    SECUART.startTransmit(buffer, sizeof(buffer), TXCallback);
}
SECUART RS485 half-duplex example
static void DemoRS485()
{
    SECUART.init(9600, UART_PARITY_NONE, UART_DATA_8_BITS, UART_STOP_1_BIT);
    SECUART.enableRXTX(true); // CTS/RXTX pin driven automatically for RS485
    const uint8_t msg[] = "Hello RS485";
    SECUART.startTransmit(msg, sizeof(msg), NULL);
}
SECUART wake-on-UART example
static void rxCallback(uint8_t *buffer, uint8_t len)
{
    // len bytes were received into buffer
}

static void wakeCallback(void)
{
    // Module has woken; start receiving the incoming message (up to 64 bytes)
    SECUART.startReceive(rxCallback, 64);
}

static void DemoWakeOnUART()
{
    SECUART.init(115200, UART_PARITY_NONE, UART_DATA_8_BITS, UART_STOP_1_BIT);
    SECUART.wakeOnUART(wakeCallback);
}

Function

Description

init

Initialize the SECUART module. Returns true if successful

startReceive

Start reception. The callback is called with the received bytes when the wanted number of bytes is received, or on timeout

cancelReceive

Stop an ongoing reception

startTransmit

Start transmission of a buffer of bytes

isTXActive

Return true if SECUART TX is currently active

isRXActive

Return true if SECUART RX is currently active

enableRXTX

Toggle CTS/RXTX pin around transmissions (RS485 half-duplex)

startReceive_Adv

Receive with configurable timeouts, termination byte, and dynamic length

wakeOnUART

Register callback to wake module on SECUART RX activity

printf

Formatted output on SECUART

SPI

The SPI module provides all functions needed for accessing the SPI bus. For chip-select control, the user must use a GPIO. For all data transfer and initialization, the SPI module can be used. The example below demonstrates usage of both GPIO and SPI. Only 4-wire SPI is supported.

SPI.init() sets the clock frequency in Hz and the clock polarity and phase: SPI_POL_0_PHA_0, SPI_POL_0_PHA_1, SPI_POL_1_PHA_0 or SPI_POL_1_PHA_1. All SPI transfers are full duplex, so bytes are always received while bytes are transmitted. In SPI.transfer(), the transmit buffer can be NULL to transmit only zeros, and the receive buffer can be NULL to ignore the received bytes.

The following example shows how to set up SPI and access the ST LIS3DE accelerometer:

SPI example code
RIIM_SETUP()
{
    // Set up GPIO. We must use one GPIO for SPI chip select
    GPIO.setDirection(GPIO_3, OUTPUT);
    GPIO.setValue(GPIO_3, HIGH);

    // Set up interface towards the LIS3DE-sensor
    SPI.init(4000000,SPI_POL_0_PHA_0);

    // Setup accelerometer to update every second
    uint8_t wbuf[2];
    wbuf[0]=0x20; // 0 (write), 0(don't increment), 0x20 (register address)
    wbuf[1]=0x17; // 1 Hz, enable X,Y and Z axes

    GPIO.setValue(GPIO_3, LOW);
    SPI.transfer(2, wbuf, NULL);
    GPIO.setValue(GPIO_3, HIGH);

    return UAPI_OK;
}

The following functions are part of the SPI module:

Function

Description

init

Initialize the SPI module

transfer

Transfer bytes over the SPI bus

Timer

The Timer module enables the user to create various timers. The timers will call a function when they’re triggered, and can be configured as periodic or one-shot, started and stopped.

A maximum of 10 timers can be created, and they cannot be deleted. It is therefore a good idea to create all timers in RIIM_SETUP(). Timer.create() returns the timer ID, or TIMER_NONE (0) if no more timers can be created. The period is given in milliseconds, and the constants SECOND and MINUTE can be used, for example 5*MINUTE. A timer can only be reconfigured with Timer.config() while it is stopped, otherwise UAPI_BAD_STATE is returned.

The following example creates a periodic timer that calls the function ReadSensor every 10 seconds:

Timer example code
static const uint32_t TimerPeriod=10000;
static uint8_t Sensor_timer_handler;

static void ReadSensor()
{
    Util.printf("Reading sensors....\n");

    return;
}

RIIM_SETUP()
{
    // Create timer that sends the CoAP PUT message
    Sensor_timer_handler=Timer.create(PERIODIC, TimerPeriod, ReadSensor);
    Timer.start(Sensor_timer_handler);

    return UAPI_OK;
}

Function

Description

create

Create a new timer

start

Start the timer

stop

Stop the timer

isActive

Check if the timer is active

config

(Re)-configure a timer

UART

Note

The UART API can’t be used if SLIP is used, as SLIP uses the UART to transfer data. However, SECUART can be used even if SLIP is used.

The UART module controls the UART port. The UART can be configured with respect to baud rate, parity, number of data bits, and number of stop bits. UART.init() returns true if the initialization was successful. The text printed with Util.printf() is also sent on the UART.

UART.startReceive() is non-blocking. The callback receives the buffer and the number of bytes read when the wanted number of bytes has been received, or when a timeout occurs. Note that calling it terminates any ongoing UART operation, so calling it right after Util.printf() can cut the printout short. UART.startReceive_Adv() adds more termination criteria: the maximum number of bytes, a timeout between bytes, a total timeout (both in milliseconds), a termination byte, and a dynamic-length mode in which the first received byte is used as the length. UART_Timeout_Infinite and UART_No_Termination_Character disable the timeouts and the termination byte. If startReceive_Adv or cancelReceive is called in a reception callback, it should be the last operation in the callback. UART.cancelReceive() cancels a reception that is still waiting for bytes, and triggers the reception callback if one is set. Cancelling a reception that is no longer needed allows the module to sleep.

UART.enableRXTX() makes the CTS/RXTX pin go high just before the UART starts transmitting and low again when the transmission is finished. This can control an RS485 transceiver. When it is enabled, the UART only supports half duplex communication.

UART.wakeOnUART() registers a callback that is called when a transition is detected on the UART RX pin, for example to wake the module from sleep. It only triggers while the UART is not used for reception or transmission. The UART is not enabled automatically, so enable it in the callback if needed. A NULL callback disables wake-on-UART.

The SECUART module has the same functions and behavior, but on the secondary UART.

UART example code
static void TxCallback(uint8_t len)
{
    Util.printf("Sent %i bytes\n", len);

    return;
}

static void DemoFunc()
{
    const uint8_t buffer[]="Test";

    UART.init(115200, UART_PARITY_NONE, UART_DATA_8_BITS, UART_STOP_1_BIT);
    UART.startTransmit(buffer, sizeof(buffer), TXCallback);

    return;
}

Function

Description

init

Initialize the UART module

startReceive

Start reception

cancelReceive

Stop reception

startTransmit

Start transmission of a buffer of bytes

isTXActive

Returns true if UART TX is active

isRXActive

Returns true if UART RX is active

enableRXTX

Enables RXTX functionality on CTS pin. Compatible with RS485

startReceive_Adv

Advanced version of startReceive

wakeOnUART

Enable or disable wake-on-UART

printf

Formatted output on UART

UDP

The UDP module controls the sending and reception of UDP packets. It has functions for receiving and sending over IPv6 or IPv4.

Note

Do not use UDP port numbers 10000-12000, 63000-63010 and 5683-5684, as these are reserved for internal use and CoAP.

UDP.addConnection() adds a UDP endpoint with a local port to listen on and a remote port to accept packets from. If the remote port is 0, packets from all ports are accepted. It returns a connection handle, or 0 if it was unsuccessful. The handler receives the source and destination addresses and ports in addition to the payload. UDP.setup() is a legacy function for a single endpoint with a simpler handler, and UDP.addConnection() is recommended. In UDP.send6WithSourcePort(), a source port of 0 selects a random ephemeral port in the range 32768-60999.

UDP example code
static uint8_t handle;

void udpCallback(IPAddr src_ipAddr, uint16_t src_port, IPAddr dst_ipAddr, uint16_t dst_port, uint8_t *payload, uint8_t payloadSize)
{
    int i;

    Util.printf("Msg from ");
    for(i=0;i<16;i++){
        Util.printf("%.02x" , src_ipAddr.byte[i]);
    }
    Util.printf(" : %.*s\n" , payloadSize, payload);
    UDP.send6(src_ipAddr, 12345, payload, payloadSize);
}

RIIM_SETUP()
{
    .....
    handle=UDP.addConnection(udpCallback, 12345, 23456);
    .....
}

Function

Description

send4

Send a UDP packet to an IPv4 address, typically to the internet

send6

Send a UDP packet to an IPv6 address, typically inside the RIIM wireless network

setup

Set up a handler for reception of UDP packets

addConnection

Add a UDP endpoint. Supports multiple UDP endpoints and a more advanced callback function

send6WithSourcePort

IPv6 send version where the source port can be specified

Util

The Util module contains useful helper functions. The module provides common C library functions for the ICI user application to use: printf, sprintf, snprintf. It also provides a random number generator.

Warning

Util.printf, Util.sprintf and Util.snprintf do not support floating point (float/double). The maximum length of a Util.printf string is 255 bytes. Util.sprintf does not check the size of the destination buffer, so prefer Util.snprintf.

Util.getTemperature() returns the MCU temperature in degrees Celsius, and Util.getVoltage() returns the supply voltage in millivolts. Util.getRand() returns a 32-bit random number, while Util.getTRN() returns a 32-bit number from the true random number generator and returns UAPI_FAIL if it could not be generated.

Util.enterCritical() disables interrupts, so the code that follows is not interrupted. Keep the time in a critical section as short as possible to avoid side effects such as lost RF packets and timing issues. A critical section must be left with Util.exitCritical() before leaving the callback. Critical sections cannot be nested: enterCritical returns UAPI_BAD_STATE if a critical section is already entered, and exitCritical returns UAPI_BAD_STATE if there is none.

The following example shows how to print something on the console (UART).

Util example code
static void DemoFunc()
{
    Util.printf("Reading sensors....\n");

    return;
}

Function

Description

printf

Standard C-library printf

sprintf

Standard C-library sprintf

snprintf

Standard C-library snprintf

getRand

Get a random number

reset

Reset the module

getTemperature

Get the MCU temperature in degrees Celsius

strlen

Return string length

strcmp

Standard C-library strcmp

strncmp

Standard C-library strncmp

getVoltage

Get voltage on the supply pin of the module, in millivolts

enterCritical

Enter critical section

exitCritical

Exit critical section

getTRN

Get true random number

OTA

The OTA module provides functions for performing Over-The-Air (OTA) updates on the device using the flooding OTA mechanism. See Over-The-Air (OTA) FW Updates for a description of the mechanism and complete examples.

In automatic mode, OTA.setConfiguration() sets how often the node checks for a new image (clientAutomaticOtaTimerPeriod, in milliseconds) and how many simultaneous downloads the node can serve to other nodes (serverMaxActiveDownloads, maximum 5). OTA.activateAutomaticOta() then starts the periodic check. OTA.getAvailableImageInfo() must not be used in automatic mode.

The following example shows how to configure and activate automatic OTA updates:

OTA example code
static void DemoFunc()
{
    OtaConfiguration_t configuration;
    configuration.clientAutomaticOtaTimerPeriod = 1000 * 60 * 60 * 24; // 1 day
    configuration.serverMaxActiveDownloads      = 3; // max 3 simultaneous downloads (maximum is 5)

    OTA.setConfiguration(&configuration);
    OTA.activateAutomaticOta();

    return;
}

Function

Description

requestAvailableImageInfo

Issue CoAP request to retrieve information about the available OTA image from CoAP server

getAvailableImageInfo

Get information about the currently available OTA image

requestAvailableImage

Issue CoAP request to retrieve a chunk of the available OTA image from CoAP server

requestSetSwitchStatus

Issue CoAP request to set the switch status of the OTA image

activateAutomaticOta

Start timer for automatic OTA updates

setConfiguration

Set configurations used in automatic OTA updates