Featured image for Apache Kafka credential management with Node.js

The goal of the Drogue IoT project is to make it easy to connect devices to cloud-based applications. This article will demonstrate how to implement firmware in Rust based on Drogue's device support. This way, a device can communicate with the cloud using the low power LoRaWAN protocol. We will also illustrate how Node.js handles the server side.

The purpose of Drogue IoT

Many open source technologies already exist in the realm of messaging and the Internet of Things ( IoT). However, technologies change over time, and not everything that exists now is fit for the world of tomorrow. For instance, C and C++ still have issues with memory safety. The concepts of cloud native, serverless, and pods might also need a different approach to designing cloud-side applications. Drogue IoT aims to help support these new environments.

Drogue Device is a firmware framework written in Rust with an actor-based programming model. Drogue Cloud is a thin layer of services that creates an IoT-friendly API for existing technologies such as Knative and Apache Kafka and a cloud-friendly API using CloudEvents on the other side. The idea is to give you an overall solution ready to run IoT as a service. Figure 1 illustrates the Drogue IoT architecture.

Figure 1: Devices send data using standard protocols of Drogue Cloud, where they are transformed and exported.

LoRaWAN network coverage

LoRaWAN is a low-power wireless network that enables you to run a device on batteries for months, sending telemetry data to the cloud every now and then. To achieve this efficient connectivity, you need LoRaWAN network coverage, and The Things Network (TTN) provides exactly that. You can extend the TTN network by running your gateway if your local area lacks coverage. TTN provides a public service that allows you to exchange data between devices and applications.

Drogue Device

Exchanging data with Drogue Device is easy. The following snippet focuses on the code  that exchanges data:

let mut tx = String::<heapless::consts::U32>::new();
let led = match self.config.user_led.state().unwrap_or_default() {
    true => "on",
    false => "off",
};
write!(&mut tx, "ping:{},led:{}", self.counter, led).ok();
let tx = tx.into_bytes();

let mut rx = [0; 64];
let result = cfg
    .lora
    .request(LoraCommand::SendRecv(&tx, &mut rx))
    .unwrap()
    .await;

Notice the await keyword at the end? Yes, that is indeed asynchronous Rust. A hardware access layer (HAL) named Embassy, another Drogue IoT project, allows the program to run on the device, which in this example is an embedded STM32 Cortex-M0 board. Thanks to Embassy and the drivers in Drogue Device, asynchronous programming becomes pretty simple. And thanks to Rust, your code is less likely to cause any undefined behavior, like corrupted memory.

Node.js

The cloud side of the IoT application needs a simple "reconcile loop." The device reports its current state, and you derive the desired state from that. The information received might result in a command you send back to the device.

The application in this article is pretty much the same as connect-quarkus-applications-drogue-iot-and-lorawan written by Jens Reimann. But his version uses the Quarkus Java framework as the backend implementation, whereas our application uses Node.js.

The entry point of the application is index.js, which configures and starts an HTTP server and an MQTT client. The HTTP server serves content from the static directory, which contains an index.html file shown in the screenshot below. This file contains a <script> element that uses Server Sent Events (SSE) to allow the server to send updates to it. In addition to serving the static content, the  HTTP server sends events through SSE. Fastify builds the server, and fastify-sse handles the SSE.

The MQTT client handles a message event as follows:

client.on('message', (receiveTopic, message) => {
    const json = JSON.parse(message);
    const framePayload = Buffer.from(json.data.uplink_message.frm_payload, 'base64');

    const event = {
      deviceId: json.device,
      timestamp: json.time,
      payload: framePayload.toString('utf8')
    };
    sse.sendMessageEvent(event);

    if (event.payload.startsWith('ping')) {
      const command = {
        deviceId: event.deviceId,
        payload: getPayload(event, sse)
      };
      sse.updateResponse(sse.lastResponse);
      sse.sendCommandEvent(command);

      const sendTopic = `command/${appName}/${command.deviceId}/port:1`;
      const responsePayload = Buffer.from(command.payload, 'utf8');
      client.publish(sendTopic, responsePayload, {qos: QOS_AT_LEAST_ONCE});
    }
  });

Pretty simple, isn't it? For more details on the Node.js implementation, please see the ttn-lorawan workshop.

Drogue Cloud

So far, the code shown in this article is fairly straightforward, focusing on our use case. However, we are missing a big chunk in the middle. How do we connect Node.js with the actual device? Sure, we could recreate all that ourselves, implementing the TTN API, registering devices, and processing events. Alternatively, we could simply use Drogue Cloud and let it do the plumbing for us.

Creating a new application and device is easy using the drg command-line tool. Installation instructions are on the drg installation page:

$ drg create application my-app
$ drg create device --app my-app my-device

The device registry in Drogue Cloud not only stores device information but can also reconcile with other services. Adding the following information makes it sync with TTN:

$ drg create application my-app --spec '{
    "ttn": {
            "api": {
                "apiKey": "...",
                "owner": "my-ttn-username",
            "region": "eu1"
            }
    }
}'
$ drg create --app my-app device my-device --spec '{
    "ttn": {
        "app_eui": "0123456789ABCDEF",
        "dev_eui": "ABCDEF0123456789",
            "app_key": "0123456789ABCDEF...",
        "frequency_plan_id": "...",
        "lorawan_phy_version": "PHY_V1_0",
            "lorawan_version": "MAC_V1_0"
    }
}'

This code creates a new TTN application, registers the device, sets up a webhook, creates the gateway configuration in Drogue Cloud, and ensures that credentials are present and synchronized.

Learn more in the LoRaWAN end-to-end workshop

Did that seem a bit fast? Yes, indeed! This is a lot of information for a single article, so we focused on the essential parts. We put together everything you need to know in the LoRaWAN end-to-end workshop, which provides more detail and background information. By the end of that workshop, you should have a web front-end to control your device, as shown in Figure 2. Most importantly, you will have a solid foundation for creating your own applications on top of Drogue IoT.

Figure 2: The application displays messages received from the device.

 

We hope you enjoyed this article. Now, you are ready to get started with Node.js and Drogue IoT. To learn more about what Red Hat is up to on the Node.js front, please explore our Node.js topic page.

Comments