Node-RED is a graphical programming tool that makes it easy to interact with web-based events. It’s called a “Low-code” solution because you can do a lot without writing much code. I love it because it’s the right balance of handling the hard stuff for me. Initial ease of use, while still making it possible to drop in custom code when I need it. I’ve been using that to control my IoT devices on the Golioth Cloud, and today I’m sharing how I do it.

Note: the concept of a node will be highlighted with bold text throughout this article to help clarify we’re discussing one of the blobs shown on screen in Node-RED

Why use Node-RED with Golioth

Earlier this year Ben Mawbey showed us how he uses Node-RED to manipulate data as it arrives on the Golioth cloud. This approach listens for realtime data using WebSockets. But this has a couple of limitations:

  • We will only see the data when it changes
  • We aren’t able to send or update data using WebSockets.

On that second point, the Golioth REST API lets us send/update data and query stored data.

Node-RED is a good choice here, since it’s relatively easy to set up a connection to WebSockets and the REST API. It’s powerful enough to do any data manipulation we want. It does need to run on a server, but on the upside that means it is always running and can be accessible to multiple end users via any web browser, no need to install an app. Let’s dive in!

Prerequisites

This example assumes you have already taken care of the following:

  • a Node-RED server
    • The Get Started page offers several solutions like running it locally on a Raspberry Pi, or on a cloud server
  • Golioth account, and a device added on the Golioth Console
    • As always, our getting started guide will walk you through all of these details
    • You can follow the demo below without having a hardware device, we just need to create a device on the Golioth Console to send data back and forth to the cloud

Connect Node-RED to WebSockets

The secret sauce in connecting a WebSocket is the URL which includes the Golioth API key. Go to the Golioth Console and choose API Keys from the left sidebar to create a new key:

The exact formatting of the WebSockets URL is detailed on our reference page, but I’ll show you how to do it here. Notice the three pieces of important data in the diagram below: project id, device id, and finally the API key.

I have chosen to connect to the dataendpoint to monitor LightDB state data. (If you want to monitor LightDB stream you can change data to stream.)

wss://api.golioth.io/v1/ws/projects/node-red-demo/devices/62695497404e12cd12628117/data?x-api-key=ynhJQQjLautKYLxQESuqB8VJLWMEVpH7

Setting up the Node-RED flow begins by adding a WebSocket-in node and connecting it to a debug node. I have also connected a JSON node for convenient data access later.

The WebSocket-in node is configured as follows:

The WebSocket type is “Connect to” which allows us to add a new URL. Click the pencil icon or the right side of that field and in the new window paste the URL. Because we are passing the API key as part of the URL, we do not need to add a TLS configuration.

Data will only appear on this WebSocket-in node when it first arrives on the Golioth Cloud. So generate an update by going to the Golioth Console and adding the key/value pairs shown above. In the Node-RED shown in the flow setup step, notice the debug output includes the raw payload as well as the JSON object.

Connect Node-RED to REST API

Setting up the REST API connection requires a bit of code, but uses the same project, device, and API key info from the last step. Two inject nodes (that send a 1 or a 0), a function node, an https request node, and a debug node complete this flow:

The inject node and http request node need a quick settings adjustment:

Set the payload of the inject node to pass 0 or 1 as a number (not a string). In the http request node, change the method to “set by msg.method”. The magic will all happen in the function node:

Code for this function is listed below. The variables at the top are used to set up the API URL, so you will need to enter your project id, device id, API key, and the LightDB state key that makes up the endpoint (led0 in my example).

var proj_id = "node-red-demo"
var dev_id = "62695497404e12cd12628117";
var api_key = "ynhJQQjLautKYLxQESuqB8VJLWMEVpH7";
var endpoint_name = "led0";

var dev_url = "https://api.golioth.io/v1/projects/" + proj_id + "/devices/";
var endpoint = "/data/" + endpoint_name;

var data = msg.payload;

var msg = {
	"method" : "PUT",
	"url" : dev_url + dev_id + endpoint,
	"headers" : {
		"Content-Type": "application/json",
		"x-api-key": api_key
	},
	"payload" : JSON.stringify(data)
};

return msg;

This code intercepts the incoming data (which will be a 0 or 1 from the inject node), formats it as a PUT command, and sends it to the http request node which will submit it to Golioth. In this demo, clicking one of the inject nodes updates the led0 value in LightDB state.

Head over to the Golioth Console and look at the LightDB state data for your device to see the changes. In practice, you can implement the desired state versus actual state principles discussed in my recent article and use this flow to update an LED on an actual piece of hardware.

Further Exercises: Dashboard/Web App

I’ve covered a lot of ground in this article and unfortunately have run out of column inches. But before signing off, I want to mention the potential for turning Node-RED flows into web apps.

The Node-RED dashboard node adds a UI which can be loaded on any browser. It looks spectacular with almost no work from us. Here you can see I’ve set up a display that shows the state of the LED, displays the latest value of the counter, and adds two buttons to turn the LED on or off.

If you want to test this out, here is an export of this flow that you can import into your Node-RED.

A word of caution: your flow contains an API key for accessing device information on Golioth. This must be kept secure. Please make time to review how to secure Node-RED and ensure that you authenticate users if you decide to build and share a web interface.

Communicating with IoT devices over a network connection presents a few challenges you must consider when designing your firmware. The most obvious is how to deal with spotty connections. Did your device get the command you sent? Does the reported state in the cloud accurately reflect the actual device state?

At Golioth we’ve built a device cloud that eases the process of provisioning, connecting with, and controlling fleets of IoT devices. To get the most out of the platform consider using a few design patterns related to Digital Twin, a virtual representation of a device that is present in the cloud and provides a framework for interacting with the real hardware.

I’ll demonstrate this using the Golioth platform, but of course the concept is applicable to all connected devices.

Avoiding Confused Users and Confused Devices

While there are innumerable ways in the IoT realm to confuse your users and your devices (trust me, I’m trying to find them all), the most obvious is the challenge keeping the device and the cloud in sync with each other. For ease of understanding, let’s consider a box with one button and one LED that is connected to the internet over a cellular connection. We want the button to toggle the LED but also allow the cloud side to change the state of the LED. This might represent the state of some running service, but to keep it simple we’ll leave that out of the example.

If we rely on the cloud to control the device LED, the user will push the button and have to wait for the button press to make it to the cloud, wait for the state of LED on the cloud to be changed, and wait for this change to make its way back to the device to update the LED. The user is likely to think the button press was missed and press it again.

If the device directly controls the LED, what happens if the cloud misses the button press because of connectivity issues? When not carefully planned for, the state of the LED will be different from the state of the service in the cloud. What happens if the LED state on the cloud is changed at almost the same time the button is pressed? We have a race condition to see which update propagates the fastest.

One design pattern we should all be familiar with uses a separation of state from command/control so that the device and its digital twin will remain in sync even when there are latency or connection issues. A device just coming on line should be able to quickly enter a desired state from the server, and report back the actual state.

Keeping Desired State and Actual State Separate

The issues outline above can be avoided by using different endpoints for a device to communicate with its virtual equivalent.

  • On the cloud there will be one representation where the physical device reports its current state. For the cloud this data is read-only, only the device can make updates to it.
  • A separate representation is made for the desired state of the device. The cloud side can make changes to this and the physical device will watch for and react to these changes. The physical device usually has a mechanism that indicates the desired operations were received.

Digital twin uses both a desired state and an actual stateOur simple example only has one “actual state” variable that keeps track of the LED state. A server might watch this data via a WebSocket to toggle some service as the value changes.

The cloud can populate the “desired state” with endpoints that request changes to the LED status. This might happen when some service the cloud is watching changes state and the IoT device needs to be aware of that.

Demo Using Golioth

Golioth stores persistent data using LightDB state. We can use a simple data structure to represent the digital twin of our hypothetical IoT device:

{
  "state": {
    "led": 0
  },
  "cmd": {
    "led_on": 1649691282
  }
}

The state endpoint stores the last-reported state (on) of the device’s LED. The cmd endpoint reflects the cloud’s desire for that LED to be on by setting the led_on key to the current timestamp. The cloud could also set led_off to a timestamp, and when the device acts upon the desired state, it can compare timestamps for all existing keys to establish which command is the most recent.

I like to have the IoT device delete the command keys once they are received (another approach would be to have the device set an acknowledged value to the timestamp the desired state was serviced). In the above example, since the led_on key exists, we assume the device has not yet seen it. Once it does, the device will turn on the LED, update the status key for that LED to 1, and delete the cmd/led_on endpoint.

Our app can be set up to watch the desired state by observing the cmd endpoint and running an on_update function when a change is detected.

err = golioth_lightdb_observe(client,
					GOLIOTH_LIGHTDB_PATH("cmd"),
					COAP_CONTENT_FORMAT_TEXT_PLAIN,
					observe_reply, on_update);

The IoT device will write a simple string of “0” or “1” as the actual state when the button is pressed, and each time the device acts upon a desired state request.

char sbuf[2] = "0";
if (led_state & 0x01) {
	sbuf[0] = '1';
}
int err = golioth_lightdb_set(client,
					GOLIOTH_LIGHTDB_PATH("state/led"),
					COAP_CONTENT_FORMAT_TEXT_PLAIN,
					sbuf, strlen(sbuf));

So let’s imagine that our IoT device is in power-saving mode. When it wakes up and connects to the network, it will immediately see the command endpoint is requesting an LED state change. Using this design pattern means your desired state changes are not missed; even when a network connection is unavailable the device will be able to update to the most recent commands the next time it connects.

You can try this out for yourself on the Golioth cloud right now. I’ve implemented the desired state pattern in sample code, and the Dev tier of Golioth lets you test 50 devices on our platform for free.

Further Learning

At its core, this design pattern is incredibly simple. When you put it into use, things may become more complex. Perhaps you want to have a command queue so that there is a history of changes for the device to review the next time it connects to a network. Instead of deleting the commands when acting upon them, a device may place an acknowledged timestamp next to them, or some other scheme that fits your needs. But at its core, the separation between a device reporting it’s state and the cloud requesting state changes is an excellent IoT approach, and a great way to start learning about the concept of digital twins.

Live data visualization shows you what is going on with your IoT fleet right now, and it makes for impressive customer demos. We previously wrote about how to visualize live data on the self-hosted version of Grafana using the WebSocket plugin we wrote. Today let’s walk through how to connect live Golioth IoT data to Grafana Cloud.

Overview

Golioth is the translation layer between your fleet of IoT devices and the cloud. Among our many ways of accessing the collected data, WebSockets are one way to get live updates as soon as the data arrives.

Grafana visualizing temperature, pressure, and humidity

We wrote a WebSockets plugin for Grafana, the monitoring and observability software. The plugin is open source (here’s the code repository) and as of just a few days ago it’s available in Grafana Cloud, the cloud-hosted version of the software. Today I’ll guide you through:

  1. Sending some temperature sensor data to Golioth
  2. Configuring the Golioth WebSocket API on the Grafana Cloud
  3. Graphing the temperature data in realtime

This example has everything you need to adapt it for your own needs.

1. Send Sensor Data to Golioth

Prerequisite: You should already have a Golioth account, and have the Zephyr toolchain installed. To do so, please follow the Golioth Getting Started guide and Setting Up Zephyr for ESP32.

For this guide I’m using the LightDB Stream example that is part of the Golioth SDK, and running it on an ESP32. This example is a good one, since it will either use a temperature sensor you have configured in the devicetree, or simulate a temperature sensor if there is not one available.

Get device credentials from console.golioth.io

First, find your device credentials in the Golioth Console by selecting Devices from the left sidebar menu and clicking the name of your device on the resulting list.

CONFIG_GOLIOTH_SYSTEM_CLIENT_PSK_ID="esp32-temperature-pskid@ttgo-demo"
CONFIG_GOLIOTH_SYSTEM_CLIENT_PSK="a_strong_password"

CONFIG_ESP32_WIFI_SSID="your_wifi_ssid"
CONFIG_ESP32_WIFI_PASSWORD="your_wifi_password"

Now add the device credentials–Identity (PDK-ID) and Pre-Shared Key (PSK)–and your WiFi access point credentials to the project’s prj.conf file. This file should be located at ~/zephyrproject/modules/lib/golioth/samples/lightdb_stream/prj.conf. Add the lines in the format shown above.

$ west build -b esp32 samples/lightdb_stream -p
$ west flash

Finally, use the commands above to build and flash the sample to your ESP32.

streaming temperature data in Golioth console

If you go to Monitor→LightDB Stream you will see new temperature data coming in every five seconds. In this window, choose the Last 4h setting from the time selector, your device from the device selector, and enable 5s auto-refresh in the upper right.

Each time one of these packets comes in, the data will be automatically updated in Grafana. We just need to set that up, which is next!

2. Configure the Golioth WebSocket API in Grafana Cloud

generating Golioth API keys

The prerequisite for this step is to get an API key from Golioth.

  1. Use the API Keys option on the left sidebar of the Golioth Console
  2. Click the Create button in the upper right of the main window
  3. In the resulting dialog (show above), press the Create button

The final dialog displays the key and some useful path information. We will use this path along with the wss://api.golioth.io/v1/ws/ WebSocket endpoint which I looked up in the Golioth WebSocket docs.

Grafana Cloud login

Log into Grafana Cloud. There are a number of services offered, the one we want is simply called Grafana.

On the left sidebar, hover over the gear icon and select Plugins. Search for WebSocket on the next screen and click the “WebSocket API” tile. Follow this 3-step process to add the WebSocket plugin (shown in the screenshots above):

  1. Click the Install via grafana.com button
  2. On the next screen click the Install plugin button
  3. Go back to the previous screen and refresh that page. It may take a minute or two, but when the new button appears click Create a WebSocket API data source

Grafana WebSocket data source configuration

This brings us to setting up our data source.

  1. Name can be anything you want
  2. Host is the wss://api.golioth.io/v1/ws/ from the Golioth Docs
  3. Click the Add header button
    1. Enter x-api-key for the header value
    2. Paste your API key from the Golioth Console in the Value box
  4. Click the Save & test button

We have completed the WebSocket connect between Grafana and Golioth. Now it’s time to visualize the incoming data!

3. Graphing Temperature Data in Grafana

In the left sidebar of Grafana, click the big plus icon and choose Dashboard, then click Add Panel.

Grafana panel setup

  1. In the Data source box on the left, select the name of the data source you just set up.
  2. For now, enter just a $into the Field box
  3. Click the Path tab
    1. Follow this format which was shown on the confirmation dialog when you created your API key:/projects/<name of Golioth project>/stream
    2. Notice I have switched from /devices to /stream.
  4. At the top of the window in the center, turn the Table view on

You should begin to see JSON data come in over the table view. Remember that WebSockets visualize realtime data, so JSON will only appear when new packets are sent.

Now that we’ve seen the JSON data coming in, we can use it to identify two types of data to use for the graph: temperature and timestamp.

More specific JSON fields

Going back to the Fields tab, we can change the $ character (which means to show all the JSON coming in) to a specific key/value pair.

  • Enter $.result.data.timestamp
    • You will see the data in the table-view change as you type, this is helpful in navigating the hierarchy
  • Click the + button all the way to the right of the Field box to add another field
  • Enter $.result.data.data.temp

Graphing simulated temperature data

When you click the Table view button at the top, the view will be replaced by a visualization of your data. Here you can see it is obvious that I’m using simulated temperature data. You can also change the way it is visualized by clicking on the Time series menu in the upper right.

Conclusion

This is one simple example that is graphing a single stream from one device. But the principle scales with your IoT fleet. Graphing large numbers of devices across multiple projects takes little more than changing how you use your Path and Field settings on the panel. With Grafana you can easily group together multiple panels into a dashboard, with visualization options tailored to almost any data type.

 

Golioth has just released a Grafana WebSocket Data Source plugin. This open source plugin allows you to create a graphic dashboard using data from any WebSocket URL that uses JSON formatting. This means you can you directly connect the Golioth Cloud API and have Grafana render incoming data in real time as graphs, charts, maps, etc.

Grafana Takes Care of Data Visualization

Temperature data display as graphs

Realtime data from Golioth devices looks great in Grafana!

Grafana is an open source visualization and analytics software from GrafanaLabs. It allows you to query, visualize, alert on, and understand your metrics no matter where they are stored. We chose Grafana because we heard it mentioned multiples times by our community members and found that it streamlines the process of managing device data and visualizing. You can build from source and run it locally (the power of open source), or use the free tier of the hosted Grafana Cloud platform.

We’re Going to Need WebSockets

At Golioth, we recently added WebSocket support for some of our services like Logs, LightDB State, and LightdDB Stream. Actaully, Chris wrote a blog post all about it. You can now connect to a WebSocket URL and get real-time data updates from your devices without the need to poll for updates like you would with a REST API.

As awesome as it is, Grafana didn’t have a WebSockets plugin, so we created one! It allows you to connect to any WebSocket URL and visualize the data in Grafana. You can get a copy of the WebSockets plugin code in our repo. But we have also submitted it as an official plugin – it should be available in Grafana soon!

Let’s Try the Demo!

Setting Up a Device to Send Data

As a hardware beginner, I followed one of our easiest samples using PlatformIO and our Arduino SDK to get my ESP32 board connected to our platform, see our examples folder on our Arduino SDK repo.

Note: The arduino-sdk repository showcased in this post is deprecated. GoliothLabs has an experimental repository that may work as a replacement:

I’m writing data on both of our services in a 5 seconds loop, updating my device’s state with LightDB State and reporting time series data for our LightDB Stream service.

// Every 5 seconds loop
...
  int core_temp = randomNumber(40, 60);
  int room_temp = randomNumber(27, 33);
  int uptime = millis() / 1000;
  String payload =
    "{
      \"core\":
        {
          \"temp\":" + String(core_temp) + ",
          \"uptime\":" + String(uptime) +
        "},
    \"room\":
      {
        \"temp\":" + String(room_temp) + "
      }
    }";
  
  client->setLightDBStateAtPath("/", payload.c_str());
  client->sendLightDBStream("/", payload.c_str());
...

This small program sends random numbers as core/room temperatures, and the device’s uptime. We have data, now let’s graph it!

Golioth’s WebSockets API

LightDB state data

Devices > Your Device > LightDB State

LightDB Stream Data

Monitor > LightDB Stream

WebSockets “listens” for changes, so every 5 seconds those updates on State and Stream are also available thru Golioth’s WebSocket API. We can follow the WebSockets docs to setup a connection to listen to them.

Below you can see how the WebSocket hosts URLs are formatted. Use the Golioth Console to find the projectId, deviceId, API key, and any paths you need. (This information is also available using the goliothctl command line tool.)

LightDB State

// Websocket URL format: wss://api.golioth.io/v1/ws/projects/{projectId}/devices/{deviceId}/data{/path=**}?{x-api-key|jwt}={API_KEY|JWT}

wss://api.golioth.io/v1/ws/projects/smart-house/devices/61d315e441da400dd6934493/data?x-api-key={projectApiKey}

LightDB Stream

// Websocket URL format: wss://api.golioth.io/v1/ws/projects/{projectId}/stream?{x-api-key|jwt}={API_KEY|JWT}

wss://api.golioth.io/v1/ws/projects/smart-house/stream?x-api-key={projectApiKey}

With those I was able to test the endpoint using websocat to make sure that the data my device was sending created notifications through the WebSocket connection as expected.

websocat command line tool used to test WebSocket feed

Grafana WebSocket Plugin Setup

For this demo I’m running everything locally (both Grafana and the Plugin itself), but we have submitted the signed plugin to Grafana’s Cloud so soon you will be able to find it there by default.

To use the plugin, there are a few configuration steps we need to follow:

  • Once you’ve logged into Grafana, go to the Configuration page (gear icon) and then to Plugins
  • Search for WebSocket API, select and then click on Create a WebSocket API data source

Now we fill in the fields as the API requires and hit save. For Golioth’s WebSocket API you can see I’ve entered the URL, and I’ve specified x-api-key and stored the API key that I generated on the Golioth Console.

Grafana WebSocket data source

Notice that I’m not using the full path, but only through the project level (smart-house). This way we can select the specific path we want to listen to later on the Panel’s Query page. This allows more flexibility.

Building the Dashboard that Shows the Data

With the data source set up, it’s time for us to build the query on an actual panel.

Something to keep in mind is that, right now, it will only listen to future events, so if there’s any update on the Query Field, Path, Panel or Dashboard, the current stored data will be wiped.

Graphing LightDB Stream:

  • Hover on the plus sign at the sidebar and select Dashboard
  • Then click on Add a new panel
  • Select WebSocket API under the Query’s data source
  • Go to Query A Path tab and fill with your desired path. In my case /stream

Grafana WebSockets path setting

  • Under Fields tab, use JSONPath reference to transform the JSON result into something that the dashboard can display. Here I’ve used $.result.data.timestamp, $..core.temp, and $..room.temp
  • I want to display the last 5 minute events of my device’s temperature, both for the core and room. So I changed the panel’s type into Time Series on the top right corner, and filled with the fields required:
  • Hit Save, and its done.

Grafana WebSockets field configuration

As long as data is streaming in from a device, it will be graphed in real time. One tip as you get used to handling data, try starting with Table View on to better understand the JSON by your query.

Displaying LightDB State

To create another panel for the LightDB State we can just duplicate the first one and update his its Path, so:

Grafana state data path configuration

There’s a small differences here, LightDB State can have deeper paths e.g. .../data/core/temp but they will only be notified via WebSockets when there’s an update on them. Because I want to listen to multiple path updates for this Panel, I will leave the path set to the root level, that is .../data.

Grafana state field queries

  • Transform the query fields to use $..core.temp and $..room.temp
  • Hit Save, and it’s another one done.

Final Results

Grafana state field queries

Like that, we have 2 panels ready to listen for updates coming from both LightDB Stream and State in real-time. Feel free to add more data and to listen to different State paths.

Conclusion

Grafana is an awesome tool that allows us to connect and create professional visualizations. Because it is open source, a major part of its improvement over time is a result of its community. We’re building an amazing platform at Golioth and we also want to empower our community with the freedom to build things they love with us. With WebSockets now available on our platform, we built this plugin to share that excitement with our users and with the entire world.

Hopefully you’ll give this a try, and we want your feedback! Get in touch with us on the Golioth Discord server and please join us there for our Office Hours every Wednesday at 10 am Pacific Time.

This guest post is contributed by Ben Mawbey, a community member who is active on the Golioth Discord and frequently takes part in Office Hours.

Data wants to be visualized. The impact of showing a customer a slick plot of the information their devices have been collecting is massive compared to pointing at a few hundred lines of text from a log file or database query.

I was looking for some sort of dashboard or charting application for a demo for a sensor system we’ve built. I figured this will appease the clients’ need for pretty pictures over boring reports. I found exactly what I needed, and it only took me about 30 minutes to get it up and running.

Grafana graphing data

This looks great, even if you have no idea what the graphs mean! Let’s dig into how to get from numbers in a database to pretty pictures in a dashboard.

Pieces of the Puzzle: Golioth WebSockets, Node-RED, InfluxDB, and Grafana

Golioth is brilliant at getting your device data from the real world up to the cloud, climbing the IoT bean-stalk some would say. While abstracting some of the trickiest IoT problems, Golioth can present your time-series data as a convenient cloud resource using LightDB Stream service. By leveraging the built-in WebSockets support and some open-source tools we can rapidly store, manipulate and display this data!

Grafana is the open-source blockbuster for this application and can be easily set up to graph sensor data directly from Golioth LightDB Stream using the REST API. This has two major drawbacks:

  • Grafana must periodically poll for new data
  • While LightDB Stream does provide convenient data retention, I prefer to use my own data storage

Enter InfluxDB, the time-series database powerhouse and an ideal companion to Grafana when talking about IoT real-time applications. This pairing is so popular that the InfluxDB data source integration is baked right into Grafana! By utilizing InfluxDB to store our sensor data, we can perform more complex queries much faster.

The question remaining is how to shuffle data from Golioth to InfluxDB? There are many potential solutions to this hurdle, but my favorite is Node-RED which defines itself as a low code programming tool for wiring up event-driven systems.

Node-RED editor window

Node-RED uses graphical flows to connect data sources and destinations, bending protocols and translating data formats in innumerable ways

Node-RED has exploded in popularity and provides all sorts of integrations to connect your systems together. It provides simple blocks to perform actions and a slick graphical interface to wire up your data flows. Conceptually Node-RED acts as our rule engine to process and direct data.

Dashboards: Grafana and InfluxDB

System diagram

Grafana is immensely powerful at providing example custom views, data transformations, and alerting. That said, it is only as good as the quality of data you can provide. Having a tightly coupled InfluxDB instance with carefully curated data via Node-RED, allows you to quickly configure complex data queries on large datasets with low latency.

Before we can play with Grafana the first step is InfluxDB setup. After you’ve installed InfluxDB, create a new database on your InfluxDB instance:

> CREATE DATABASE golioth

Configure the InfluxDB Data Source in your Grafana instance by clicking the gear icon on the left sidebar, choosing and adding a data source, then searching for the InfluxDB plugin. Here’s how I’ve set up my data source:

Grafana InfluxDB source configuration

Assuming you have some data in your DB, we can quickly create a new time-series dashboard panel in Grafana and query the dataset using this integration:

Grafana panel configuration

This simple query shows how we structured the data in the DB, allowing us to select from a particular measurement, specifying a specific device identity tag and aggregating data points with specific time buckets. Adjusting the time range instantly updates the graph from our local InfluxDB instance.

Now how do we get the data from Golioth into InfluxDB?

Node-RED

Several networking integrations are provided with Node-RED. Presently the most relevant to Golioth would be HTTP nodes for REST API requests and the WebSockets node which is the easiest to configure.

You can see your sensor data collecting in the Golioth LightDB Stream by using the Golioth Console web interface:

Golioth Console showing LightDB stream data

We can use Node-RED flows to connect to Golioth via WebSockets and store the resulting data in our local DB:

NodeRED editor window

The nodes in this flow were set up as follows, taking care to give them appropriate names making it obvious to see their function. All of the nodes I’m using should come as part of every Node-RED installation except for the InfluxDB nodes. But don’t worry, these are trivial to install. On Linux is looks something like this:

cd ~/.node-red
npm install node-red-contrib-influxdb
sudo systemctl restart nodered.service

WebSockets Node:Node-RED websockets

First set up the credentials to your Golioth project using your generated API key and connect to the WebSockets LightDB Stream endpoint.

Debug Node:Node-RED debug

Drop a few of these nodes along the way and click the small green button to turn the debug log on. This is super handy to check data coming through and make sense of it.

JSON Node:Node-RED json

The LightDB Stream endpoint provides us with a JSON object representation containing our sensor data as well as meta information such as the data timestamp and device identity. This node allows us to parse this JSON into a javascript object so that we can work with it more easily in subsequent nodes.

Change Node:Node-RED change node

This node clearly shows the power of Node-RED as we can craft any sort of data manipulations or transformation.

We could do without this node and jump straight to InfluxDB, however, should any malformed data arrive we risk polluting the DB with bad data. By selectively transforming the incoming data and mapping it into a new object we can not only filter only good packets and arrange the measurement names but also add tags to build a solid data representation in the DB making our queries far more powerful.

InfluxDB Out Node:

Node-RED InfluxDB input nodeNode-RED InfluxDB server settings window

Finally, we can configure the data connection to our InfluxDB instance, set appropriately for your server configuration and database created earlier.

Assuming your flow is set up correctly, you should be able to see data collecting in your database. We know it works, but as I mentioned before, this visual is not going to impress our customers.

InfluxDB data

Revisiting the Grafana panel we previously created, you can see InfluxDB data is now being plotted!

Grafana graphing data

Corner Cases

One of the downsides of WebSockets is their ethereal nature, should there be some temporary connectivity issue, any data packets would be lost from the point of view of your InfluxDB database. A solution around this could be to set up another flow that executes periodically to sync with the LightDB Stream using the REST API. Node-RED could then be configured to check this data and add any missing values into the InfluxDB instance and prevent consistency issues.

Another concern with open-source self-hosted systems is security. It can be challenging to secure your server and services should they be public-facing. If you are handling sensitive data then it would be best to consult with an expert in this field. Fortunately, all of the tools discussed have subscription-based cloud services available that sort all of this out in the background.

Conclusion

Being able to set up a simple demo like this in less than 30 minutes demonstrates the power and flexibility of these modern open-source solutions. Coupled with the reliability and maintenance advantages of the Docker system, it’s a breeze to test locally on your desktop or Raspberry Pi and then deploy to production a moment later on your cloud server of choice. The rules engine and ease of wiring up blocks provided by Node-RED opens up a massive pool of possibilities, from countless other integrations to building intelligent processes. One such idea I would like to explore is integrating a device provisioning process into the flow such that we can link a device to a dataset or location during deployment or maintenance.

Every IoT project needs to provision devices that are going to be available in the field. Leveraging open standards, Golioth cuts down on the required time and hassle for IoT development teams.

Provisioning is a critical step in IoT projects when they go to production. Unfortunately, this process remains a mystery for many engineers due to lack of information about the process. At a high level, provisioning is passing configurations and credentials to an IoT device so it can connect securely to the cloud. Once provisioned, the device can send telemetry, receive commands, or be updated (by OTA DFU) when it’s out in the field. How you provision a device depends a lot on the use case. 

(click the image above to see the full diagram)

Example use cases

First, let’s examine a customer-facing product like a smart light bulb. In this scenario, the first step would be for the user to provide WiFi credentials to connect to the user’s home network. On the platform side, the device would obtain a new set of credentials to connect to the backend services. These credentials would be specific to that particular user and device. Later, the user might decide to clean up the device to sell it, so the ability to remove device configurations and deleting a given set of credentials is important. This is a perfect example for using BLE provisioning like shown in the video below.  The user experience is seamless with any existing mobile app used for controlling the bulb and reporting data back from the end device.

Next, we’ll consider factory-level provisioning. An example device like a cellular asset tracker would be pre-provisioned at the factory before being used by your customer. Later the user will only associate that device with their account, but the credentials to talk to the cloud are already set on the device. This can be done as part of the manufacturing process, probing the device via Serial/UART to get the device hardware ID, provisioning it to the cloud, and sending credentials back to the device via the same transport. We can even have different firmware that will only provision in the factory. The device accepts the initial device configuration and saves the credentials to flash. Subsequent firmware that doesn’t have that initial feature enabled, making sure external parties can’t change or reverse engineer the initial configuration.

There are myriad ways that provisioning can be done. Each instance will depend on the factory environment, the capabilities of the user, and on the end application. The video below is a setup similar to the first example explained above, using a Bluetooth application to read and then program the end device, all while working with the Golioth cloud.

Our demo application

As you can see in the video, we developed an end-to-end sample that shows a practical scenario of provisioning IoT devices with a native mobile app, talking with an IoT device over Bluetooth, and provisioning device/credentials in Golioth Cloud. We leverage different tools for doing so:

  • MCUmgr as the device management subsystem and protocol.
  • Zephyr as the real-time operating system, that implements MCUmgr.
  • Open-source mobile SDK to integrate MCUmgr on an app
  • Golioth’s API and the Device/Credentials Management capabilities. 

The MCUmgr community developed multiple types of transports to interact with devices, a benefit of MCUmgr being an open standard and having a vibrant community. One option is to communicate with the device over serial UART using the `mcumgr` cli or even integrate that into your own set of provisioning tools. Another option is to use a mobile SDK that implements MCUmgr protocols over BLE to talk with devices.

We took the Bluetooth approach and forked Nordic’s MCmgr Example application, adding communication with Golioth APIs to manage devices. Once we discover the name of the device, we assign credentials via the REST API and securely send them over Bluetooth to the end device. The device is running one of Golioth’s samples that accepts dynamic configuration for WiFi and DTLS Pre Shared Keys to talk securely with our cloud. The device uses a different Golioth service called LightDB. Using this configuration engine, we can publish the on/off state of the light bulb using LightDB,show that data on a UI, and even send commands to change the state on the device. 

Source code for the mobile app:

More details on how to use our REST API and how to generate API Keys can be checked on our docs website.

References

“I’m sorry boss, I am working as fast as I can here. I reprogrammed about 36 out of the total 50 units, but this is slow going. I only have one programming cable and I need to disassemble the deployed units so I can get to the header on the boards first.”

A bad firmware image on your deployed IoT devices can mean ruined weekends, upset customers, and lost time. Many businesses pursue a network based firmware update so that they can push new versions to their devices. In fact, this is a critical part of the firmware development process, often a very early one. Developing or implementing a bootloader allows engineers to ship new control software to their devices. A straw poll on Twitter showed that some engineers spend a significant amount of time putting this tooling in place.

While the “barely any time” group seems large, it also includes those who aren’t doing a custom bootloader, nor a bootloader that is networked:

In the past, networked firmware updates took a significant amount of planning and coordination between hardware, firmware, software, and web teams. Golioth has collapsed this down to a simple process.

Update all the devices in your fleet with the click of a button

Golioth Device Firmware Update (DFU) is possible because the Golioth SDK is built on top of the Zephyr Project. Part of that implementation includes MCUboot, an open source bootloader. Using open source software up and down the stack, Golioth enables quick, secure deployment of firmware packages to IoT devices throughout the world. The Golioth Console enables easy management of firmware releases, including multi-part binary bundles, enabling updates for devices as diverse as smart speakers, digital signage, machine learning enabled sensor systems, multiple processor embedded devices, and more.

In the video linked below, Lead Engineer Alvaro Viebrantz demonstrates with Chris Gammell how to update the firmware of an nRF52 based device over Ethernet. The video includes code snippets in Zephyr and walking through the build process using the command line tool West. Once the firmware image is built, Alvaro showcases how to push the image to the Golioth cloud, package it for delivery, and then deploying to Golioth enabled devices.

No more fussing with programming cables out in the field, Golioth allows engineers to update their devices with new features, requested fixes, and efficiency improvements. Try it out today!

About Golioth

Golioth is a cloud company dedicated to making it easier to prototype, deploy, and manage IoT systems. Learn more by joining the Golioth Beta program and reading through Golioth Documentation.