Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

A demonstration of Drogue IoT using Node.js

August 18, 2022
Daniel Bevenius
Related topics:
RustNode.jsOpen source
Related products:
Red Hat build of 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.

    An illustration of devices sending data that is transformed and exported.
    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.

    A screenshot of the application displaying messages received from the device.
    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.

    Last updated: August 14, 2023

    Related Posts

    • Connect Quarkus applications with Drogue IoT and LoRaWAN

    • Connect IoT devices with Drogue IoT and OpenShift Streams for Apache Kafka

    • LoRaWAN setup at the EclipseCon IoT playground

    • Building Containerized IoT solutions on OpenShift Lab

    Recent Posts

    • Every layer counts: Defense in depth for AI agents with Red Hat AI

    • Fun in the RUN instruction: Why container builds with distroless images can surprise you

    • Trusted software factory: Building trust in the agentic AI era

    • Build a zero trust AI pipeline with OpenShift and RHEL CVMs

    • Red Hat Hardened Images: Top 5 benefits for software developers

    What’s up next?

    10 tips for nodejs cheat sheet tile card

    Run secure and efficient Node.js applications on OpenShift and other container environments. This cheat sheet rounds up 10 tips to help you learn best practices and get up to speed quickly.

    Get the cheat sheet
    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Chat Support

    Please log in with your Red Hat account to access chat support.