JPY | USD

Use a Raspberry Pi and Mozilla Open Framework to Rapidly Develop an IoT Gateway

著者 Stephen Evanczuk

Digi-Keyの北米担当編集者 の提供

Gateway devices bring cloud services closer to Internet of Things (IoT) end devices to speed processing, reduce latency, and maintain high availability. As they create their gateway designs, however, developers soon find themselves sorting through a confusing array of options for hardware and software needed to connect diverse IoT peripherals to the cloud.

Now, using a Raspberry Pi and open-source software from Mozilla, developers can rapidly and cost effectively implement a gateway based on emerging IoT standards.

To guide designers through the process, this article first briefly reviews the role of gateways in IoT networks, their key requirements, and associated implementation challenges. It then describes the role of standards efforts, highlighting the World Wide Web Consortium’s approach for describing entities in IoT networks.

This article focuses on how developers can rapidly deploy a gateway using a Raspberry Pi 3, wireless add-ons, and open-source software from Mozilla. In particular, the article describes how developers can use the Mozilla software framework to easily extend their gateway to support any number of peripheral add-ons required to meet specialized connectivity requirements.

The growing need for gateways

On the Web, the use of standard protocols enables users to employ a range of browsers to contact diverse servers despite large differences in the underlying hardware and software of the browser and server platforms. While building on many of those same standard protocols, the IoT presents significantly greater challenges in enabling the kind of interoperability that continues to drive the Web. Just as Web browsers identify themselves and their capabilities in request headers, IoT devices need standard approaches for identifying their functionality and the nature of the data they provide.

In a typical multilayered IoT architecture, however, the number and type of entities can be overwhelming, particularly at the lowest layer comprising sensors and actuators. To meet diverse connectivity requirements for these devices, gateway devices have emerged as a preferred solution. With their ability to support multiple wired and wireless connectivity options, gateways provide a key service in complex IoT systems. The role of the gateway has expanded significantly as IoT developers take advantage not only of its diverse connectivity, but also its ability to provide more substantial services in complex IoT networks.

A gateway’s role

In their simplest role, gateway devices buffer communications between high-throughput cloud connections and hundreds or thousands of IoT peripheral devices generating data streams at rates that can differ by orders of magnitude from each other and the cloud. If connections are lost to the cloud, the gateway can provide local versions of cloud services to IoT devices. Conversely, if an IoT device goes offline for any reason, the gateway can provide the cloud with a virtual IoT device that emulates the basic functionality and last-known state of the corresponding physical IoT device. In either case, the higher-level IoT application can continue to operate normally despite interruptions in connectivity.

Because they are typically free of the real-time and power constraints of IoT peripheral devices, IoT edge devices can take advantage of high-performance processor architectures to provide a powerful processing capability close to the source of IoT data. IoT experts continue to take advantage of this local processing capability by moving more sophisticated cloud services and even advanced machine learning algorithms to these devices to provide faster response loops for local processes, or reduce the size of the data streams flowing upstream to the cloud application.

Commercial IoT platforms such as Amazon Web Services IoT, IBM Watson IoT, and Microsoft Azure IoT provide their own proprietary interfaces and protocols in their end-to-end service offerings (Figure 1). Yet, for many reasons including concern about lock-in or because of broader based requirements, IoT application developers continue to look for solutions that can simplify use of more diverse IoT devices and services.

Diagram of Amazon Web Services (AWS) IoT

Figure 1: Commercial IoT platforms such as Amazon Web Services (AWS) IoT use low-level Internet standards to support each layer of an IoT application, but need to provide their own solutions to the industry’s lack of IoT-specific standards. (Image source: Amazon Web Services)

Leading the charge for defining IoT standards is the World Wide Web Consortium (W3C), though there are others also working to define the elements of a standard IoT architecture. In its own evolving specifications, the W3C Web of Things (WoT) identifies a few key interfaces that would allow individual devices to communicate with a gateway, cloud server, Web client, or even another IoT device (Figure 2).

Diagram of W3C Web of Things (WoT)

Figure 2: The W3C approaches interoperability in the Web of Things through a series of standard interfaces and data models such as the Thing Description (triangle), which encapsulates information for each device. (Image source: W3C)

Although the details of the W3C architecture are beyond the scope of this article, a few key definitions bear mentioning. One of the most important is the Thing, which encompasses both a physical device and its metadata, or Thing Description, represented by the small triangles in Figure 2.

Beyond just a listing of basic metadata such as name and human-readable description, the Thing Description can directly support the application with features including data typing, validation, and even specific end points that other entities can call to execute that particular Thing’s unique functionality.

Using standard communications methods (“WoT Binding Templates” in Figure 2), different participants in an IoT application need only consume the Thing Description of a new device or gateway to understand how to work with it and its data capabilities. With its data model and application programming interface (API) definitions, Mozilla provides developers with one of the first available frameworks for building this type of interoperable gateway.

Mozilla gateway

As part of its W3C WoT efforts, Mozilla’s Things gateway specification includes a data model for a Thing Description and related Thing types as well as simple APIs for using WebSockets or basic REST mechanisms. Mozilla’s Thing Description specifies basic metadata including name, type, and description as well as properties such as “on” and “level” for a connected LED light (Listing 1).

Copy

{

  "name":"My Lamp",

  "type": "thing",

  "description": "A web connected lamp",

  "properties": {

    "on": {

      "type": "boolean",

      "description": "Whether the lamp is turned on",

      "href": "/things/lamp/properties/on"

    },

    "level" : {

      "type": "number",

      "description": "The level of light from 0-100",

      "minimum" : 0,

      "maximum" : 100,

      "href": "/things/lamp/properties/level"

    }

  },

  "actions": {

    "fade": {

      "description": "Fade the lamp to a given level",

      "input": {

        "type": "object",

        "properties": {

          "level": {

            "type": "number",

            "minimum": 0,

            "maximum": 100

          },

          "duration": {

            "type": "number",

            "unit": "milliseconds"

          }

        }

      },

      "href": "/things/lamp/actions/fade"

    }

  },

  "events": {

    "overheated": {

      "type": "number",

      "unit": "celsius",

      "description": "The lamp has exceeded its safe operating temperature",

      "href": "/things/lamp/events/overheated"

    }

  },

  "links": [

    {

      "rel": "properties",

      "href": "/things/lamp/properties"

    },

    {

      "rel": "actions",

      "href": "/things/lamp/actions"

    },

    {

      "rel": "events",

      "href": "/things/lamp/events"

    },

    {

      "rel": "alternate",

      "href": "wss://mywebthingserver.com/things/lamp"

    },

    {

      "rel": "alternate",

      "mediaType": "text/html",

      "href": "/things/lamp"

    }

  ]

}

Listing 1: The Mozilla Gateway Thing Description uses a standard JSON format to describe a Thing and its functional capabilities. (Code source: Mozilla)

Other entries in the Thing Description include more complex objects that encapsulate actions such as fading a light. By accessing the “fade” action in the Thing Description, a gateway or other entity can find the entry point to a function able to perform the “fade” operation based on specified properties such as fade level and duration. Consequently, the Thing Description provides a standard approach for identifying an IoT device and executing the various actions it is designed to perform.

To interact with a Thing, developers can use the familiar REST Web protocol to read (GET) or write (PUT or POST) Thing properties defined in the Thing Description. In turn, the normal REST response would provide the data requested with a read or the status of the write operation.

For example, to fade an LED to 50% brightness over a two second transition period, the developer would POST the corresponding JSON body to the associated fade end point, receiving in turn a 201 response and JSON body confirming the properties and status of the requested action queued by the device (Listing 2).

Copy

POST https://mythingserver.com/things/lamp/actions/

Accept: application/json

 

{

  "fade": {

    "input": {

      "level": 50,

      "duration": 2000

    }

  }

}

 

201 Created

 

{

  "fade": {

    "input": {

      "level": 50,

      "duration": 2000

    },

    "href": "/things/lamp/actions/fade/123e4567-e89b-12d3-a456-426655"

    "status": "pending"

  }

}

Listing 2: Using the entry point and properties specified in the Thing Description, developers can POST a request to fade, receiving in turn a 201 response and JSON body confirming the properties and status of the requested action. (Code source: Mozilla)

Although the Mozilla documentation provides a detailed description of its data models and APIs, developers still face the prospect of writing the extensive software packages required to turn this theory into a working gateway. Fortunately, Mozilla removes the theoretical aspects of its specification by providing a full implementation designed to work on the Raspberry Pi family.

Gateway platform

As noted earlier, a gateway design presents relatively modest requirements in its basic role of providing multiple connectivity options needed to mix and match different IoT peripheral devices. Indeed, the Raspberry Pi family provides an effective hardware base for creating such devices. The latest version, Raspberry Pi 3 Model B+, upgrades the family with substantially higher throughput for both wired and wireless networks. Based on a quad-core Arm® Cortex®-A53 applications processor, this board also offers an effective platform for exploring the kind of sophisticated local-processing capabilities mentioned earlier.

Even before using the full processing potential of the Raspberry Pi 3 Model B+, developers can begin exploring basic gateway functionality simply by loading the board with a firmware image available as a free download from a Mozilla github repo. The firmware implements a basic gateway that allows developers to connect wireless peripherals simply by plugging a wireless controller dongle into a Raspberry Pi 3 board’s standard USB connector. The Mozilla software implementation comes with out-of-the-box support for various wireless USB dongles such as the Sigma Designs ACC-UZB3-U-STA Z-Wave USB controller.

After powering up the board, the software takes the developer through a few basic initialization steps and then immediately begins searching the local wireless environment for devices. Using a Web interface, developers tap buttons to connect discovered devices to the gateway (Figure 3A) and then view or modify device properties (Figure 3B) as defined in the corresponding Thing Description.

Image of Mozilla’s Things gateway software

Figure 3: Mozilla’s Things gateway software lets users easily connect Things to their gateway (A) and interact with each device (B) according to its capabilities as defined in its Thing Description. (Image source: Mozilla)

Enhance gateways using ecosystem hardware

Aside from the ease of implementing a basic gateway, the combination of the Raspberry Pi ecosystem and Mozilla’s open-source code provides developers with a comprehensive environment for extending the basic design. Developers can download the design’s complete source code package to gain a better understanding of gateway operation, change specific operating characteristics, or even create custom gateway applications. Designed to run on Node.js, the source code illustrates key design patterns for each component of a sophisticated gateway software application.

Using this development platform, it’s possible to quickly create gateways able to support a wide range of connectivity options enabled by a wealth of available hardware add-on boards. For example, add the Pimoroni PIM213 Automation HAT to a Raspberry Pi board to enable a gateway to support high voltage and high current wired connections required in industrial environments.

For operating environments with poor or no Internet connectivity, add narrowband LTE connectivity to a gateway by connecting the Raspberry Pi board to a NimbeLink NL-AB-RPI dev board equipped with a NimbleLink NL-SW-LTE-SVZM20 LTE CAT M1 module and a Taoglas Limited 4G LTE antenna.

Developers are not limited only to Raspberry Pi add-ons. They can plug different adapter cards into their Raspberry Pi boards to gain access to the rich series of add-ons available with other interface standards. For example, using the Seeed Technology 103990079 Arduino adaptor, a Digi International XK-WDM board can add Digi’s power efficient DigiMesh mesh network connectivity to a gateway. For applications requiring a standard mesh connectivity option, plug in Digi’s XKB2-Z7T-WZM Zigbee board.

In the same way, developers can use the Seeed 103010002 Grove adapter to support LoRaWAN mesh networking with the Seeed 113060006 Grove LoRaWAN board, or extended range sub-GHz networks with the Seeed 113060000 Grove RF link add-on.

With the rich set of available add-ons, developers can quickly augment their hardware platform to offer multiple connectivity options. On the software side, the Mozilla project provides a straightforward set of requirements and examples for implementing the software interfaces needed to support new hardware.

To build an add-on for the Things gateway, developers need to provide code for three entities: Device, Property, and Adapter. The Device code would typically extend the base Device class with attributes and methods (functions) unique to a specific device or device type.

For example, a device module might contain separate classes associated with different variations of the basic device – such as a class for a basic LED and another for a smart bulb. The Property module would extend the base Property class to provide a set of property classes with methods for updating specific device properties, such as the color or brightness of an LED (Listing 3).

Copy

class TPLinkProperty(Property):

    """TP-Link property type."""

 

    def __init__(self, device, name, description, value):

        """

        Initialize the object.

 

        device -- the Device this property belongs to

        name -- name of the property

        description -- description of the property, as a dictionary

        value -- current value of this property

        """

        Property.__init__(self, device, name, description)

        self.set_cached_value(value)

 

 

   .

   .

   .

class TPLinkBulbProperty(TPLinkProperty):

    """Property type for TP-Link smart bulbs."""

 

    def set_value(self, value):

        """

        Set the current value of the property.

 

        value -- the value to set

        """

        try:

            if self.name == 'on':

                self.device.hs100_dev.state = 'ON' if value else 'OFF'

            elif self.name == 'color':

                self.device.hs100_dev.hsv = rgb_to_hsv(value)

            elif self.name == 'level':

                self.device.hs100_dev.brightness = value

            elif self.name == 'colorTemperature':

                value = max(value, self.description['min'])

                value = min(value, self.description['max'])

                self.device.hs100_dev.color_temp = int(value)

            else:

                return

        except SmartDeviceException:

            return

 

        self.set_cached_value(value)

        self.device.notify_property_changed(self)

   .

   .

   .

Listing 3: In creating their own gateway add-on software packages, developers can find key design patterns such as this snippet showing Property class used in a Python-based Things gateway add-on for TP-Link smart devices. (Code source: Mozilla)

Finally, the Adapter module would extend the base Adapter class to provide classes that initialize the device communications channel, support network commissioning, and provide support for other device or communication-specific features.

Although the main gateway package is implemented in Javascript for Node.js, the platform also officially supports Python. Nevertheless, developers can conceptually build compliant add-ons in any suitable language. For example, developers have created add-ons in Rust, Mozilla’s C++-like memory safety language. For developers able to use the existing Node.js backend, this relatively simple add-on approach provides a powerful capability for rapidly creating gateways able to connect through diverse connectivity options to a wide range of IoT peripheral devices.

Conclusion

For IoT gateways, developers are challenged to ensure interoperability among different IoT devices, gateways, and servers. Although standards bodies are rapidly evolving suitable specifications for IoT interoperability, developers have been largely left to translate specifications into workable solutions.

As shown, using Mozilla’s Things gateway software in combination with a Raspberry Pi 3, developers can rapidly and cost effectively evaluate gateway applications and easily extend the gateway to support diverse connectivity options.

免責条項:このウェブサイト上で、さまざまな著者および/またはフォーラム参加者によって表明された意見、信念や視点は、Digi-Key Electronicsの意見、信念および視点またはDigi-Key Electronicsの公式な方針を必ずしも反映するものではありません。

著者について

Stephen Evanczuk

Stephen Evanczuk氏は、IoTを含むハードウェア、ソフトウェア、システム、アプリケーションなど幅広いトピックについて、20年以上にわたってエレクトロニクス業界および電子業界に関する記事を書いたり経験を積んできました。彼はニューロンネットワークで神経科学のPh.Dを受け、大規模に分散された安全システムとアルゴリズム加速法に関して航空宇宙産業に従事しました。現在、彼は技術や工学に関する記事を書いていないときに、認知と推薦システムへの深い学びの応用に取り組んでいます。

出版者について

Digi-Keyの北米担当編集者