Building Wireless Sensor Networks with OpenThread (Extract)

Page 1

Building Wireless Sensor Networks with OpenThread Developing CoAP Applications for Thread Networks with Zephyr

9|1803 2|1800 8|1802 1|6C00 5|2000 7|F009 4|F000 11|6C0B 3|2003 12|4000 12|6C0C Koen Vervloesem
booksbooks

Building Wireless Sensor Networks with OpenThread

Developing CoAP applications for Thread networks with Zephyr

Koen Vervloesem

● This is an Elektor Publication. Elektor is the media brand of Elektor International Media B.V.

PO Box 11, NL-6114-ZG Susteren, The Netherlands

Phone: +31 46 4389444

● All rights reserved. No part of this book may be reproduced in any material form, including photocopying, or storing in any medium by electronic means and whether or not transiently or incidentally to some other use of this publication, without the written permission of the copyright holder except in accordance with the provisions of the Copyright Designs and Patents Act 1988 or under the terms of a licence issued by the Copyright Licencing Agency Ltd., 90 Tottenham Court Road, London, England W1P 9HE. Applications for the copyright holder's permission to reproduce any part of the publication should be addressed to the publishers.

● Declaration

The authors and publisher have used their best efforts in ensuring the correctness of the information contained in this book. They do not assume, or hereby disclaim, any liability to any party for any loss or damage caused by errors or omissions in this book, whether such errors or omissions result from negligence, accident or any other cause.

● British Library Cataloguing in Publication Data

A catalogue record for this book is available from the British Library

● ISBN 978-3-89576-618-3 Print

ISBN 978-3-89576-619-0 eBook

● © Copyright 2024 Elektor International Media www.elektor.com

Editor: Martin Cooke, Denis Meyer

Prepress Production: D-Vision, Julian van den Berg

Printers: Ipskamp , Enschede, The Netherlands

Elektor is the world's leading source of essential technical information and electronics products for pro engineers, electronics designers, and the companies seeking to engage them. Each day, our international team develops and delivers high-quality content - via a variety of media channels (including magazines, video, digital media, and social media) in several languages - relating to electronics design and DIY electronics. www.elektormagazine.com

● 4

2.2.1

Contents ● 5 Contents Preface ........................................................... 11 Chapter 1• Introduction .............................................. 12 1.2 Thread’s architecture ............................................ 13 1.2.1 Link layer: IEEE 802.15.4 ....................................... 14 1.2.2 Network layer: 6LoWPAN and IPv6 ................................. 15 1.2.3 Transport layer: UDP ........................................... 16 1.2.4 Thread lacks an application layer .................................. 17 1.3 Advantages of Thread ........................................... 18 1.3.1 Scalability .................................................. 18 1.3.2 Security .................................................... 18 1.3.3 Reliability ................................................... 18 1.3.4 Low power consumption ........................................ 18 1.3.5 Interoperability............................................... 19 1.4 Disadvantages of Thread ......................................... 19 1.4.1 Limited range ................................................ 19 1.4.2 Low data rates ............................................... 19 1.4.3 Complexity.................................................. 19 1.5 Platforms used in this book ........................................ 19 1.5.1 Nordic Semiconductor’s nRF52840 SoC .............................. 20 1.5.2 OpenThread ................................................. 20 1.5.3 Zephyr .................................................... 21 1.6 How to use this book 22 1.7 Summary and further exploration 25 Chapter 2 • Preparing the development environment ....................... 26 2.1 The Zephyr development environment for Nordic Semiconductor devices 26 2.1.1 Building a Zephyr application 27 2.1.2 Flashing a Zephyr application 29 2.1.3 Flashing an OpenThread echo server 31
Wireshark and a 802.15.4 sniffer dongle 33
2.2
Downloading Wireshark and the nRF Sniffer for 802.15.4 33

3.1.3

Building wireless sensor networks with OpenThread ● 6 2.2.2 Installing the nRF Sniffer for 802.15.4 firmware 34 2.2.3 Installing the nRF Sniffer capture tool 35 2.2.4 Testing an 802.15.4 packet capture 37 2.2.5 Decrypting encrypted packets 38 2.2.6 Other important Wireshark settings 39
Testing communication between Thread devices 40 2.3 The OpenThread Network Simulator 41 2.3.1 Building and installing OTNS 41 2.3.3 Running the simulator 43 2.3.4 Interacting with nodes on the command line 44 2.4 Summary and further exploration ................................... 45 Chapter 3 • Setting up Thread Border Routers ............................ 47 3.1 Responsibilities of a Thread Border Router ............................. 47 3.1.1 Bidirectional IPv6 connectivity .................................... 47 3.1.2 Service discovery ............................................. 48
2.2.7
Transmission Control Protocol (TCP) ................................ 49 3.2 OpenThread Border Router with Raspberry Pi and nRF52840 Dongle . . . . . . . . . . . 49 3.2.1 Installing Raspberry Pi OS on a Raspberry Pi .......................... 49 3.2.2 Preparing Raspberry Pi OS ....................................... 55 3.2.3 Installing OTBR............................................... 57 3.2.4 Building and flashing the RCP firmware .............................. 58 3.2.5 Connecting the RCP............................................ 59 3.3 Espressif Thread Border Router ..................................... 62
Setting up the IDF development environment ......................... 64 3.3.2 Building the RCP firmware ....................................... 64 3.3.3 Building the ESP Thread BR firmware ............................... 65 3.3.4 Flashing the ESP Thread BR firmware ............................... 66 3.4 Forming a Thread network from the OpenThread CLI ...................... 67 3.5 Joining an existing Thread network .................................. 70 3.6 Using the Border Router’s web interface ............................... 73 3.7 Alternative Thread Border Routers ................................... 78
3.3.1
Contents ● 7
Summary and further exploration 79 Chapter 4 • Thread networking fundamentals ............................. 80 4.1 Device roles: Router and End Device 80 4.1.1 Router 81 4.1.2 End Device 81 4.2 Device types: Full Thread Device and Minimal Thread Device 82 4.2.1 Full Thread Device 82 4.2.2 Minimal Thread Device 83 4.3 Upgrading and downgrading of Routers 83 4.4 Special devices in a Thread network: Leader and Border Router 85 4.4.1 Leader ..................................................... 85 4.4.2 Border Router................................................ 87 4.5 IPv6 addresses in a Thread network ................................. 87 4.5.1 Unicast .................................................... 88 4.5.2 Multicast ................................................... 88 4.5.3 Anycast .................................................... 89 4.6 Unicast address types in a Thread network ............................. 90
Link-Local Address (LLA) ........................................ 90 4.6.2 Mesh-Local EID (ML-EID) ........................................ 90 4.6.3 Routing Locator (RLOC) ......................................... 91 4.6.4 Anycast Locator (ALOC) ......................................... 93 4.6.5 Global Unicast Address (GUA) .................................... 94 4.7 Deciphering all IP addresses of your Border Router ....................... 94 4.8 Summary and further exploration ................................... 96 Chapter 5 • Setting up a Thread network ................................ 97
Creating a basic OpenThread application with Zephyr ..................... 97
Directory structure ............................................ 98 5.1.2 Building the application ........................................ 101 5.1.3 Exploring Zephyr’s configuration options ............................ 101 5.1.4 Configuring the OpenThread version ............................... 105 5.1.5 Configuring the operational dataset ............................... 105
3.8
4.6.1
5.1
5.1.1

5.7

5.8

6.3.3

Building wireless sensor networks with OpenThread ● 8 5.1.6 Configuring the device type and role 106 5.2 Network discovery 107 5.3 Upgrading to a Router 110 5.4 Downgrading to a REED 112 5.5 Using IPv4 addresses with NAT64 112 5.6 Sending DNS queries 114
Multicast addresses across a Thread and non-Thread network 115
Sending and receiving UDP messages 118
Summary and further exploration 120 Chapter 6 • Network commissioning ................................... 121 6.1 Flashing the Joiner firmware ...................................... 121 6.2 On-mesh commissioning ........................................ 122 6.2.1 Flashing the Commissioner firmware ............................... 122 6.2.2 Authenticating the Joiner onto the network .......................... 123 6.3 External commissioning ......................................... 124
Generating a pre-shared key for the Commissioner ..................... 125
Building the Commissioner CLI tool ................................ 126
5.9
6.3.1
6.3.2
Connecting the Commissioner to the Border Router .................... 127 6.3.4 Authenticating the Joiner onto the network .......................... 128 6.4 Summary and further exploration .................................. 130 Chapter 7 • Using CoAP in a Thread network ............................ 131 7.1 What is CoAP? ................................................ 131 7.1.1 Messages .................................................. 132 7.1.2 Requests and responses ....................................... 134 7.2 Sending and receiving CoAP messages from the OpenThread command line ..... 138 7.3 Controlling an LED with a CoAP server ............................... 141
Initializing the LED ........................................... 145 7.3.2 Setting up the CoAP server ..................................... 147 7.3.3 Processing a CoAP request ...................................... 149 7.3.4 Sending a CoAP response ...................................... 152 7.3.5 Testing the CoAP server ........................................ 154
7.3.1

7.5.2

8.1

9.1

Contents ● 9
Sending CoAP requests on button presses 155 7.4.1 Initializing the button 159 7.4.2 Initializing CoAP 160 7.4.3 Sending a CoAP request 160 7.4.4 Processing a CoAP response 162 7.4.5 Testing the CoAP client 162
Sending sensor measurements over a Thread network 163
Approach 163
7.4
7.5
7.5.1
Hardware 163
Project structure 164 7.5.4 Source code ................................................ 166 7.5.5 Sending the sensor measurements ................................ 172 7.6 Using CoAP on your computer ..................................... 173 7.6.1 Using a CoAP client on the command line ........................... 173 7.6.2 Running a simple CoAP server in Python ............................ 175 7.7 Summary and further exploration .................................. 177 Chapter 8 • Service registration and discovery ........................... 179
7.5.3
Browsing the Border Router’s services with mDNS and DNS-SD ............. 179 8.2 Setting up an SRP client on the OpenThread command line ................ 181 8.3 Browsing your Thread device’s services on non-Thread devices .............. 186 8.4 Reaching your Thread devices by their registered hostname ................ 187 8.5 Registering a CoAP server as an SRP service ........................... 189 8.6 Finding an SRP service from your computer ........................... 197 8.7 Summary and further exploration .................................. 202 Chapter 9 • Securing application protocols with DTLS ..................... 204
Securing CoAP messages from the OpenThread command line .............. 204 9.2 Controlling an LED using a CoAPS server ............................. 210 9.3 Sending CoAPS requests on button presses ........................... 213 9.4 Using X.509 certificates instead of a pre-shared key ..................... 217 9.4.1 Generating the certificates ...................................... 217 9.4.2 Setting up a CoAPS server with a X.509 certificate ..................... 223
Building wireless sensor networks with OpenThread ● 10 9.4.3 Setting up a CoAPS client with a X.509 certificate 227 9.5 Summary and further exploration 229 Chapter 10 • Low-power Thread devices ................................ 231 10.1 Measuring power consumption using Nordic Semiconductor’s Power Profiler Kit II 231 10.1.1 Using Ampere Meter mode 233 10.1.2 Using Source Meter mode 233 10.2 Measuring your Thread application’s power consumption 234 10.3 Reducing power consumption 236 10.4 Summary and further exploration 241 Chapter 11 • Conclusion............................................. 243 11.1 Other Thread platforms ........................................ 243 11.2 More about Thread and OpenThread ............................... 245 11.3 Some ideas for further exploration ................................. 246 Chapter 12 • Appendix .............................................. 248 12.1 Establishing a serial connection to a device over USB .................... 248 12.1.1 Checking the port ........................................... 248 12.1.2 Installing the USB-to-serial driver ................................ 248 12.1.3 Giving the user access ........................................ 249 12.1.4 Starting the serial connection ................................... 249 12.2 Debugging tips for OpenThread applications .......................... 249 12.3 Programming boards with the Adafruit nRF52 bootloader . . . . . . . . . . . . . . . . . 250 12.3.1 Automatic UF2 conversion ..................................... 251 12.3.2 Manual UF2 conversion ....................................... 252 12.3.3 Flashing the firmware ........................................ 252 Index ........................................................... 253

Preface

Thread is a protocol for building efficient, secure and scalable wireless mesh networks for the Internet of Things (IoT), based on IPv6. OpenThread is an open-source implementation of the Thread protocol, originally developed by Google. It offers a comprehensive Application Programming Interface (API) that is both operating system and platform agnostic. OpenThread is the industry’s reference implementation and the go-to platform for professional Thread application developers.

This book uses OpenThread in conjunction with Zephyr, an open-source real-time operating system designed for use with resource-constrained devices. This allows you to develop Thread applications that work on various hardware platforms, without the need to delve into low-level details or to learn another API when switching hardware platforms.

With its practical approach, this book not only explains theoretical concepts, but also demonstrates Thread’s network features with the use of practical examples. It explains the code used for a variety of basic Thread applications based on Constrained Application Protocol (CoAP). This includes advanced topics such as service discovery and security. As you work through this book, you’ll build on both your knowledge and skills. By the time you finish the final chapter, you’ll have the confidence to effectively implement Thread-based wireless networks for your own IoT projects.

Vervloesem, February 2024

● 11

Chapter 1• Introduction

Thread is a protocol for building efficient, secure, and scalable wireless mesh networks for Internet of Things (IoT) applications. This book will serve as a comprehensive guide to help you understand and implement wireless sensor networks using the Thread protocol. In this book, you’ll learn how to:

• Set up Thread Border Routers to connect a Thread network to a non-Thread network.

• Establish a Thread network between devices, using advanced features such as NAT64 and multicast addressing.

• Permit devices to join a Thread network by using network commissioning.

• Use Constrained Application Protocol (CoAP) as a communication protocol for messages between Thread devices.

• Discover Thread devices and their services on a network using SRP and mDNS/ DNS-SD protocols.

• Secure application protocols such as CoAP with Datagram Transport Layer Security (DTLS).

• Reduce power consumption of Thread devices.

This introductory chapter takes an overview of the Thread protocol, its advantages and disadvantages. It also goes on to list the other software and hardware platforms used in this book.

Thread is a low-power, wireless, and IPv6-based networking protocol designed specifically for IoT devices. Development of the protocol is managed by the Thread Group (https:// www.threadgroup.org), an alliance founded in 2015. This is a consortium of major industry players, including Google, Apple, Amazon, Qualcomm, Silicon Labs, and Nordic Semiconductor.

The Thread specification can be downloaded from https://www.threadgroup.org/ support#specifications (registration is required). The version history is as follows:

Thread 1.0 2015 Never implemented in commercial products

Thread 1.1 2017

Thread 1.2 2019

Thread 1.3 2023

The ability to automatically move to a clear channel on detecting interference (channel agility)

The ability to reset a master key and drive new rotating keys in the network

Enhancements to scalability and energy efficiency

Support for large-scale networking applications, including the ability to integrate multiple Thread networks into one singular Thread domain

Enhancements to scalability, reliability, and robustness of Thread networks

Standardization of Thread Border Routers, Matter support, and firmware upgrades for Thread devices

Table 1.1 Versions of the Thread specification

Building wireless sensor networks with OpenThread ● 12
Version Release year Remarks

All versions of the Thread specification maintain backward compatibility.

1.2 Thread’s architecture

Thread employs a mesh networking architecture that allows devices to communicate directly with each other, eliminating the need for a central hub or gateway. This architecture offers inherent redundancy, as devices can relay data using multiple paths, ensuring increased reliability in case of any single node failure.

The Thread protocol stack is built upon the widely used IPv6 protocol, which simplifies the integration of Thread networks into existing IP infrastructures. Thread is designed to be lightweight, streamlined and efficient, making it an excellent protocol for IoT devices running in resource-constrained environments.

Before discussing Thread, it’s essential to understand its place in the network protocol environment. Most modern networks are based on the Internet Protocol suite, which uses a four-layer architecture. The layers of the Internet Protocol suite are, from bottom to top:

Link layer

Defines the device’s connection with a local network. Protocols like Ethernet and WiFi operate within this layer. In the more complex Open Systems Interconnection (OSI) model, this layer includes the physical and data link layers.

Network layer

Enables communication across network boundaries, known as routing. The Internet Protocol (IP) operates within this layer and defines IP addresses.

Transport layer

Enables communication between two devices, either on the same network or on different networks with routers in between. The transport layer also defines the concept of a port. User Datagram Protocol (UDP) and Transmission Control Protocol (TCP) operate within this layer.

Application

layer

Facilitates communication between applications on the same device or different devices. Protocols like HyperText Transfer Protocol (HTTP), Domain Name System (DNS), Simple Mail Transfer Protocol (SMTP), and Message Queuing Telemetry Transport (MQTT) operate within this layer.

When data is transmitted across the network, the data of each layer is embedded in the layer below it, as shown in this diagram:

Chapter 1• Introduction ● 13

Figure 1.1 Network data is encapsulated in the four layers of the Internet Protocol suite (based on: Colin Burnett, CC BY-SA 3.0)

Thread operates in the network and transport layers. However, it’s important to know what’s going on in all layers.

1.2.1 Link layer: IEEE 802.15.4

For its link layer, Thread builds upon the IEEE 802.15.4 standard, a specification by the Institute of Electrical and Electronics Engineers (IEEE). This is the same link layer that Zigbee uses. It focuses on low power consumption, allowing devices to communicate for months or even years on a single battery charge. The direct communication range is approximately 10 meters under normal conditions.

IEEE 802.15.4 is a radio standard operating in the license-free 2.4 GHz frequency band with data rates up to 250 kbit/s. It has 16 channels (channels 11 to 26), ranging from 2405 to 2530 MHz with 5 MHz channel spacing. This is the same 2.4 GHz frequency band used by Bluetooth and Wi-Fi.

Note:

In Europe and North America, IEEE 802.15.4 also supports channels at frequencies of 868 MHz and 920 MHz, respectively. Channel 0 (with a data rate of 20 kbit/s) is for 868.3 MHz, and channels 1 to 10 (with a data rate of 40 kbit/s) are for 906 to 924 MHz with 2 MHz channel spacing.

An IEEE 802.15.4 network includes two types of devices:

Full Function Device (FFD)

A device that implements the complete feature set of the IEEE 802.15.4 standard. It can communicate with all other IEEE 802.15.4 devices within its immediate radio range.

Reduced Function Device (RFD)

A device that implements only a subset of features of the IEEE 802.15.4 standard to conserve device resources. It can only communicate with the FFD through which it joined the network.

Building wireless sensor networks with OpenThread ● 14

An IEEE 802.15.4 network is known as a Personal Area Network (PAN). Each PAN is identified by a unique PAN ID that no other PAN in range is allowed to have. Within each PAN, one FFD is the PAN coordinator. This device initiates and manages the PAN, enabling other devices to join the network.

IEEE 802.15.4 includes built-in encryption and authentication, using AES-128 (128bit Advanced Encryption Standard) in CCM* mode, a variation of CCM mode (counter with cipher block chaining message authentication code). This mode provides authenticated encryption by combining encryption in CTR (counter) mode with authentication using CBC-MAC (cipher block chaining message authentication code). The original message is transmitted alongside a MIC (Message Integrity Check) so the recipient can validate that the message has not been tampered with.

Devices can only communicate with each other in an IEEE 802.15.4 network if they use the same 128-bit AES key. The IEEE 802.15.4 standard doesn’t, however, define the key exchange process. The key must therefore either be stored in each device during manufacture, entered manually by the user, or by a key exchange protocol in the layers above the link layer.

IEEE 802.15.4 data packets can transmit data from 0 to 127 bytes long. Each IEEE 802.15.4 device has an EUI-64 (Extended Unique Identifier) address set by the manufacturer, which is used as a MAC address. When a device joins a PAN, it’s also assigned a 16-bit short address. This allows the transmitted packets to be shorter because they only need to use two instead of eight bytes to define source and target addresses. Some special short addresses exist, such as 0xffff as a broadcast address to send packets to all devices, and 0xfffe as an unassigned address, used by devices while joining a network.

1.2.2 Network layer: 6LoWPAN and IPv6

Thread’s network layer consists of IPv6 over Low-Power Wireless Access Networks (6LoWPAN). This is an IETF specification described in RFC 4944, "Transmission of IPv6 Packets over IEEE 802.15.4 Networks", with an update for the compression mechanism in RFC 6282, "Compression Format for IPv6 Datagrams over IEEE 802.15.4-Based Networks". 6LoWPAN’s purpose is to allow even the smallest devices with limited processing power and low energy requirements to be part of the Internet of Things.

6LoWPAN essentially enables you to run an IPv6 network over the IEEE 802.15.4 link layer. It acts as an ‘adaptation layer’ between IPv6 and IEEE 802.15.4 and is therefore sometimes considered part of the link layer. This adaptation poses some challenges. For example, IPv6 mandates that all links can handle datagram sizes of at least 1280 bytes, but IEEE 802.15.4, as explained in the previous subsection, limits a frame to 127 bytes. 6LoWPAN solves this by excluding information in the 6LoWPAN header that can already be derived from IEEE 802.15.4 frames and by using local, shortened addresses. If the payload is still too large, it’s divided into fragments.

The link-local IPv6 addresses of 6LoWPAN devices are derived from the IEEE 802.15.4 EUI64 addresses and their shortened 16-bit addresses. The devices in a 6LoWPAN network

Chapter 1• Introduction ● 15

can communicate directly with ‘normal’ IPv6 devices in a network if connected via an edge router. This means there is no need for translation via a gateway, in contrast to non-IP networks such as Zigbee or Z-Wave. Communication with non-6LoWPAN networks purely involves forwarding data packets at the network layer.

In this layer, Thread builds upon IEEE 802.15.4 to create an IPv6-based mesh network. In IEEE 802.15.4 only communication between devices that are in immediate radio range is possible, whereas routing allows devices that aren’t in immediate range to communicate.

If you want to delve into more details of Thread’s network layer, consult the Thread Group’s white paper "Thread Usage of 6LoWPAN" (https://www.threadgroup.org/Portals/0/ documents/support/6LoWPANUsage_632_2.pdf).

1.2.3 Transport layer: UDP

On top of 6LoWPAN and IPv6, Thread’s transport layer employs the User Datagram Protocol (UDP), which is the lesser known alternative to Transmission Control Protocol (TCP).

UDP has the following properties:

Connectionless

Unlike TCP, UDP doesn’t require establishing a connection before transferring data. It sends datagrams (packets) directly without any prior setup.

No error checking and recovery

UDP doesn’t provide built-in error checking, nor does it ensure the delivery of packets. If data is lost or corrupted during transmission, UDP doesn’t attempt to recover or resend it.

Speed

UDP is faster than TCP, as it doesn’t involve the overhead of establishing and maintaining a connection, error checking, or guaranteeing packet delivery.

UDP is ideal for use by Thread for several reasons:

Resource constraints

Thread devices often have limited processing power, memory, and energy. The simplicity and low overhead of UDP make it a better fitting choice for such resourceconstrained devices compared to TCP.

Lower latency

UDP’s connectionless and lightweight nature guarantees data transmission with low latency, making it appropriate for wireless sensors.

Building wireless sensor
with OpenThread ● 16
networks

1.2.4 Thread lacks an application layer

Unlike home automation protocols such as Zigbee, Z-Wave, or Matter, the Thread standard doesn’t define an application layer. A Thread network merely offers network infrastructure that applications can use to communicate. Just as your web browser and email client use TCP/IP over Ethernet or Wi-Fi, home automation devices can use Thread over IEEE 802.15.4 as their network infrastructure.

Several application layers exist that can make use of Thread:

Constrained Application Protocol (CoAP)

A simpler version of HTTP, designed for resource-constrained devices and using UDP instead of TCP.

MQTT for Sensor Networks (MQTT-SN)

A variant of MQTT designed to be used over UDP.

Apple HomeKit

Apple’s application protocol for home automation devices.

Matter

A new home automation standard developed by the Connectivity Standards Alliance (CSA).

Note:

Matter was developed by the Zigbee Alliance, the original developers of the Zigbee standard for home automation. Following the introduction of Matter, the Zigbee Alliance rebranded to the Connectivity Standards Alliance. Matter’s application layer is heavily influenced by Zigbee. It not only runs on top of Thread, but can also be used over Wi-Fi and Ethernet.

Like your home network which simultaneously hosts a lot of application protocols including HTTP, DNS, and SMTP, a Thread network can also run all these application protocols concurrently.

Figure 1.2 The Thread network stack supports multiple application protocols simultaneously.

Throughout this book, we will be using CoAP as an application protocol in a Thread network. Once you have a Thread network set up, you can also use it for Apple HomeKit and Matter devices.

Chapter 1• Introduction ● 17

Chapter 1• Introduction

1.3 Advantages of Thread

Some of Thread’s key benefits include:

1.3.1 Scalability

Thread’s mesh network architecture allows for large-scale deployment of IoT devices, supporting hundreds of devices within a single network. Thread accommodates up to 32 Routers per network and up to 511 End Devices per Router (you’ll learn about these different device roles in chapter 4). In addition, from Thread 1.2, multiple Thread networks can be integrated into one single Thread domain, allowing thousands of devices within a mesh network.

1.3.2 Security

Devices can’t access a Thread network without authorization. Moreover, all communication on a Thread network is encrypted using IEEE 802.15.4 security mechanisms. As a result, an outsider without access to the network credentials can’t read network traffic.

1.3.3 Reliability

Thread networks are robust and support self-healing and self-organizing network properties at various levels, ensuring the network’s resilience against failures. This all happens transparently to the user; messages are automatically routed around any bad node via alternative paths.

For example, an End Device requires a parent Router to communicate with the rest of the network. If communication with this parent Router fails for any reason and it becomes unavailable the End Device will choose another parent Router in its neighborhood, after which communication resumes.

Thread Routers also relay packets from their End Devices to other Routers using the most efficient route they can find. In case of connection problems, the Router will immediately seek an alternate route. Router-Eligible End Devices can also temporarily upgrade their status to Routers if necessary. Each Thread network has a Leader who supervises the Routers and whose role is dynamically selected by the Routers. If the Leader fails, another Router automatically takes over as Leader.

Border Routers have the same built-in resilience. In a Thread network with multiple Border Routers, communication between Thread devices and devices on another IP network (such as a home network) occurs along multiple routes. If one Border Router loses connectivity, communications will be rerouted via the other Border Routers. If your Thread network only has a single Border Router, this will become a single point of failure for communication with the outside network.

1.3.4 Low power consumption

Thread is based on the power-efficient IEEE 802.15.4 link layer. This enables devices to operate on batteries for prolonged periods. Sleepy End Devices will also switch off their radio during idle periods and only wake up periodically to communicate with their parent Router, thereby giving even longer battery life.

Building wireless sensor networks with OpenThread ● 18

1.3.5 Interoperability

As the protocol is built upon IPv6, Thread devices are straightforward to incorporate into existing networks, both in industrial and home infrastructure, and for both local networks and cloud connections. You don’t need a proprietary gateway; every IP-based device is able to communicate with Thread devices, as long as there’s a route between both devices facilitated by a Border Router.

1.4 Disadvantages of Thread

In life, they say there’s no such thing as a free lunch and Thread is no exception to this rule. Some of its limitations are:

1.4.1 Limited range

Thread’s emphasis on low power consumption can lead to a restricted wireless range compared with other technologies such as Wi-Fi. Although this can be offset by its mesh architecture, where Routers relay messages, it still means that devices in general can’t be placed too far apart.

1.4.2 Low data rates

Thread supports lower data rates than some rival IoT technologies. This makes Thread unsuitable for applications requiring high throughput.

1.4.3 Complexity

The Thread protocol stack may be more challenging to implement compared to other IoT networking solutions, potentially ramping up development costs and time.

1.5 Platforms used in this book

In this book we focus on building wireless sensor networks using the Thread protocol together with the following hardware and software environments:

Nordic Semiconductor’s nRF52840 SoC

A powerful yet energy-efficient and low cost hardware solution for Thread-based IoT devices

OpenThread (https://openthread.io)

An open-source implementation of the Thread protocol, originally developed by Google, making it easy to incorporate Thread into your IoT projects

Zephyr (https://zephyrproject.org)

An open-source real-time operating system designed for resource-constrained devices

Armed with these tools and by using practical examples we will go on to guide you step-bystep through the details of the hardware and software required to build Thread networks and OpenThread-based applications.

Chapter 1• Introduction ● 19

1.5.1 Nordic Semiconductor’s nRF52840 SoC

Nordic Semiconductor’s nRF52840 is a SoC built around the 32-bit ARM Cortex-M4 CPU running at 64 MHz. This chip supports Bluetooth Low Energy (BLE), Bluetooth Mesh, Thread, Zigbee, IEEE 802.15.4, ANT and 2.4 GHz proprietary stacks. With its 1 MB flash storage and 256 KB RAM, it offers ample resources for advanced Thread applications.

This SoC is available for developers in the form of Nordic Semiconductor’s user-friendly nRF52840 Dongle. You can power and program this small, low-cost USB dongle via a computer USB port. The documentation at https://docs.nordicsemi.com/bundle/ug_ nrf52840_dongle/page/UG/nrf52840_Dongle/intro.html lists comprehensive information about the dongle.

Figure 1.3 Nordic Semiconductor’s nRF52840 Dongle is a low-cost USB dongle ideal for experimenting with Thread.

1.5.2 OpenThread

Thread is basically a networking protocol; in order to work with it we need an implementation of the Thread networking protocol. The industry’s reference implementation, used even by professional Thread device developers, is OpenThread. It’s a BSD-licensed implementation, with development ongoing via its GitHub repository https://github.com/openthread/ openthread. The license for this software allows for its use in both open-source and proprietary applications.

OpenThread provides an Application Programming Interface (API) that’s operating system and platform agnostic. It has a narrow platform abstraction layer to achieve this, and has a small memory footprint, making it highly portable. In this book, we will be using OpenThread in conjunction with Zephyr, but the same API can be used in other combinations, such as ESP-IDF for Espressif’s Thread SoCs.

Building wireless sensor networks with OpenThread ● 20

Figure 1.4 The BSD-licensed OpenThread project is the industry’s standard implementation of the Thread protocol.

1.5.3 Zephyr

Zephyr is an open-source real-time operating system (RTOS) designed for resourceconstrained devices. It incorporates OpenThread as a module, simplifying the process of creating Thread applications based on Zephyr and OpenThread. Because of Zephyr’s hardware abstraction layer, these applications will run on all SoCs supported by Zephyr that have an IEEE 802.15.4 radio facility.

Chapter 1• Introduction ● 21

Figure 1.5 Zephyr is an open-source real-time operating system (RTOS) with excellent support for OpenThread.

1.6 How to use this book

Like a lot of manuals covering IoT topics, this book combines network administration, programming, and electronics. The electronics part is minimal, largely restricted to connecting a sensor and hookup to a power supply. However, the other two topics are substantial. Hence, I assume that you have some prior experience in network administration and programming. The programs for Zephyr are written in C, some prior basic knowledge will be useful here.

For the hardware, I recommend a Nordic Semiconductor nRF52840 Dongle, but you can use any microcontroller board with Thread radio supported by Zephyr (see chapter 11 for some alternatives). There are variants of the dongle by other manufacturers, such as the April USB Dongle 52840 (with an external antenna) or the nRF52840 MDK USB Dongle from makerdiary (with a case). Consult the appendix at the end of this book if you want to use one of these, as they come with a different bootloader.

Building wireless sensor networks with OpenThread ● 22

Figure 1.6 From left to right: April Brother’s April USB Dongle 52840, Nordic Semiconductor’s nRF52840 Dongle, and makerdiary’s nRF52840 MDK USB Dongle.

The more devices you have in a Thread network, the better it works, because Routers can relay messages via other devices. Having more devices also aids in understanding how Thread operates: we can turn devices on and off, run commands on them through Zephyr’s shell, and observe how the network reacts. So, if possible, I recommend purchasing a handful of nRF52840 Dongles or other IEEE 802.15.4 devices supported by Zephyr. A USB hub with several Thread devices plugged in makes an excellent test setup, as shown in this example:

Figure 1.7 A USB hub with some Thread dongles plugged in is a great test setup to get to know Thread networking.

If you’re serious about Thread development with Zephyr, I also recommend Nordic Semiconductor’s nRF52840 Development Kit. This is the bigger (and slightly less affordable) brother of the nRF52840 Dongle, offering more capabilities to debug code easily. With one of these, you can carry out initial development and debugging then flash the code to the nRF52840 Dongle once all the bugs have been ironed out.

Chapter 1• Introduction ● 23

Figure 1.8 Nordic Semiconductor’s nRF52840 Development Kit has some powerful debugging capabilities.

This book serves as a practical guide. It not only explains theoretical concepts, but also demonstrates the network features using examples, accompanied by code for a variety of basic Thread applications. I encourage you to make use of all these examples as you progress through the book.

By the time you finish you will have gained the necessary knowledge and skills to confidently implement Thread-based wireless sensor networks for your own IoT projects.

Here’s a brief overview of what we will be covering in this book:

Chapter 1: Introduction

An introduction to Thread, its layered architecture, its advantages and disadvantages.

Chapter 2: Preparing your development environment

A guide to preparing the development environment for Zephyr, as well as some tools for inspecting IEEE 802.15.4 traffic and simulating Thread networks.

Chapter 3: Setting up Thread Border Routers

Steps for setting up a Thread Border Router, using a Raspberry Pi or an ESP32-based platform.

Chapter 4: Thread networking fundamentals

A deep dive into Thread networking basics, including device roles, device types, and the diverse types of IPv6 addresses used within a Thread network.

Chapter 5: Setting up a Thread network

Setup of a minimal Zephyr application and a closer look at network discovery, NAT64, DNS queries, multicast addresses across Thread and non-Thread networks, including UDP communication.

Chapter 6: Network commissioning

An explanation of network commissioning as a more user-friendly way to add devices to a Thread network.

Building wireless sensor networks with OpenThread ● 24

Chapter 7: Using CoAP in a Thread network

An introduction to CoAP, with various applications running a CoAP server and client using a Thread network.

Chapter 8: Service registration and discovery

An explanation of how to register services of Thread devices with a Border Router and how to discover them

Chapter 9: Securing application protocols with DTLS

Adding application-level security with Datagram Transport Layer Security (DTLS) for CoAP applications, including the setup of pre-shared keys and X.509 certificates

Chapter 10: Low-power Thread devices

An exploration and optimization of power consumption of Thread devices

Chapter 11: Conclusion

A wrap-up to this book, offering some resources for learning more about Thread and some ideas for further exploration

Appendix

Some specialized tips that will come in handy in various situations

Note:

All the code examples from this book are published on https://github.com/ koenvervloesem/openthread-applications. Read the instructions in this GitHub repository for more information about how to download them. The repository also lists any errors that may have been found in this book since its publication as well as information about changes that affect the examples herein.

1.7

Summary and further exploration

In this introductory chapter, we took a look at the basics of the Thread protocol and its layered architecture. We also gained insights into some of the advantages and disadvantages of this particular network protocol.

At the end of this chapter, we took a look at all the hardware and software platforms used throughout this book. Here we focus on the Zephyr RTOS with the OpenThread API running on Nordic Semiconductor’s nRF52840 Dongle. These particular platforms aren’t the only fish in the sea when it comes to platforms for use with Thread programming. For instance, I didn’t cover Espressif’s ESP-IDF platform for its ESP32-H2 SoCs, which also includes OpenThread. With the knowledge you pick up from this book about Thread networking basics, and in particularly with the OpenThread API, you will be in a good position to understand any Thread APIs running on other platforms.

In the next chapter, you’ll learn how to set up a development environment including the support tools you will need for all the exercises described in this book.

Chapter
Introduction ● 25
1•

Index

6LoWPAN 15, 39, 69

A

Acknowledgment (ACK) 132, 133, 137, 140, 141, 151, 152, 154, 162, 172

Adafruit nRF52 bootloader 250

Address Solicit Request 111

Address Solicit Response 111

Advertisement 111 aiocoap 173

All-Nodes multicast address 89, 96, 107, 111, 155, 160, 162, 170, 172, 177, 236

All-Routers multicast addresses 82, 83, 89, 96, 111

ALOC16 93

Ampere Meter mode 232, 233

anycast address 89

Anycast Locator (ALOC) 90, 93, 95 Apple HomeKit 17 application layer 13, 17

B

Base64

223

battery power 83

Beacon 107

Beacon Request 107

bidirectional IPv6 connectivity 47 block-wise transfer 178

BME280 163, 165

bootloader 30

Border Agent 124, 180

Border Router 18, 19, 47, 78, 87, 94, 112, 122, 124, 179, 181, 182, 185, 186, 187, 246 button 159

C

ca.conf 217 certificate 224, 226, 227

Certificate Authority (CA) 217

Certificate Authority (CA) certificate 218, 224, 226, 227

Certificate Signing Request (CSR) 219, 221 channel 36, 65, 66, 69, 70, 107, 108, 178

child

80, 81, 84, 90, 91, 92, 110, 111, 112, 192

Child ID 91, 109

Child ID Request 109

Child ID Response 109

child table 72, 110, 112

Child Update Request 109

Child Update Response 109

CMake 99

CMakeLists.tst 99

CoAP 39, 111, 123, 178, 204

CoAP client 139, 155, 160, 162, 163

CoAP ping 134, 138

CoAPS client 213, 227

Coap Secure (CoAPS) 204

CoAP server 139, 140, 141, 147, 149, 162, 163, 174, 175, 179, 189

CoAPS server 210, 223, 224

Commissioner 65, 74, 93, 121, 122, 123, 124

Commissioner Candidate 123

Commissioner Credential 125, 129 commissioning 81, 90, 121, 178, 204 configuration overlay 58, 100, 106

Confirmable (CON) 132, 133, 134, 136, 137, 138, 141, 151, 152, 154, 155, 161, 162, 174, 175

Constrained Application Protocol (CoAP) 17, 131 current consumption 235, 238, 240

D

Datagram Transport Layer Security (DTLS) 131, 204

DELETE (0.04) 135 development environment 26

Device firmware updates (DFU) 246

device roles 80 device tree 145, 146, 147, 159, 236

device tree overlay 58, 146, 160, 165, 166, 236 device types 82

Device Under Test (DUT) 231, 232 DFU (Device Firmware Upgrade) mode 30

Index ● 253

Building wireless sensor networks with OpenThread

DNS 114

DNS-SD (DNS-based Service Discovery) 179, 180, 186, 197

E

edge router 16, 87

EMPTY (0.00) 134

End Device 18, 72, 80, 81, 82, 83, 91

ESP32-C6 244

ESP32-H2 63, 244

ESP-IDF 64, 244

Espressif Thread Border Router 47, 62

EUI-64 15, 123, 128, 169, 170, 177

Extended PAN ID 125

External Commissioner 124, 180

F

factory reset

122

firmware package 30

flashing 29, 31, 66

Full End Device (FED) 43, 83

Full Function Device (FFD) 14

Full Thread Device (FTD) 82, 89, 106

G

GET (0.01) 135, 139, 140, 141, 152, 153, 154, 155, 163, 174, 175, 207

Global Unicast Address (GUA) 90, 94, 95, 100, 119, 174, 183 guiconfig 104

H

Home Assistant 79 hostname 189

I

I²C 163, 165

ICMP Echo (ping) request 40, 113, 117

ICMPv6 Router Advertisements (RA) 187

IEEE 802.15.4 14

IEEE 802.15.4 radio 82, 83, 107

instance name 189

interface identifier (IID) 87, 90

Internet Protocol (IP) 13

Internet Protocol suite 13

IP addresses 40, 69, 90, 92, 94, 183

IPv4 112, 114, 115, 119

IPv6 13, 15, 19

IPv6 addresses 47, 87 IPv6 address prefix 87

J

Joiner 65, 121, 123

Joiner Credential 123, 129 JSON 170, 176

K

Kconfig 99, 101, 121, 122, 211, 224, 237

L

Leader 18, 68, 85, 93, 108, 111, 123, 192

LED 145, 147, 153, 154, 155, 210

Link Accept 111

Link Accept and Request 111

link layer 13, 14, 107 , 204

Link-Local IPv6 address 15, 40, 72, 88, 89, 90, 95, 96 Link Request 111

M Matter 17

Mbed TLS 183, 189, 205, 211, 224 mDNS 48, 179, 197

mDNS hostname 187, 188 menuconfig 102 MeshCoP (mesh commissioning protocol) 123, 127

Mesh Link Establishment (MLE) Advertisement 27, 108, 235

Mesh-Local EID (ML-EID) 88, 89, 90, 92, 95, 96, 118, 139, 154, 182, 195, 206, 228

Mesh-Local prefix 39, 90, 92, 95 mesh network 16

Message ID 133, 137, 153, 154, 155

message type 132, 138, 150, 151, 152, 161 method code 134, 150, 153, 161

Minimal End Device (MED) 43, 80 , 83, 89, 107

Minimal Thread Device (MTD) 82, 83, 106

MLE Advertisement 107

MLE Announce 107

MLE Attach 108, 111, 112

● 254

MLE Link Request

111

MQTT for Sensor Networks (MQTT-SN) 17, 243, 246

multicast address 88, 95, 115, 116

Multicast Listener Discovery 96

Multicast Listener Registration (MLR) 58, 100

N

NAT64

112, 114, 119

Native Commissioner 122 neighbors 90

netdata 113

network key 38, 65, 66, 68, 69, 70, 74, 77, 121, 204

network layer 13, 15

network name 70, 74, 107, 125, 180

network prefixes 68

network resilience 48

Non-confirmable (NON) 132, 134, 136, 138, 140, 151, 152, 155, 170, 172, 175, 176

nRF52840 20

nRF52840 Development Kit 23, 29, 164

nRF52840 Dongle 20, 30, 33, 49, 58, 100, 159, 163, 165

nRF Connect for Desktop 231

nRF Sniffer for 802.15.4 33

nRF Thread Topology Monitor 46

nrfutil 27

O

Observe option 178

Off-Mesh Routable (OMR) address 68, 94, 95, 174, 183

Off-Mesh Routable (OMR) prefix 68, 69, 94

On-mesh commissioning 122

OpenSSL 217

OpenThread 20

OpenThread Border Router (OTBR) 47, 49

OpenThread C API 245

OpenThread CLI 245

OpenThread commands 62, 66

OpenThread Network Simulator (OTNS) 41, 80

OpenThread shell 61

operational dataset 65, 67, 68, 70, 105, 125

Option Numbers 170 OTBR API 79

P

PAN ID 15, 74, 105, 107, 108, 123, 129, 178

parent 80, 83, 91, 92, 109, 110

Parent Request 109

Parent Response 109

partition 86

PEM (Privacy-Enhanced Mail) 223, 224, 227

Personal Area Network (PAN) 15 petitioning 123 piggybacked response 137, 140, 154 polling period 107, 238, 240

POST (0.02) 135 power consumption 231 power management 238

Power Profiler 231, 235

Power Profiler Kit II (PPK2) 231 pre-shared key 125, 205, 206, 208, 209, 210, 211, 212, 213

Primary Backbone Router (PBBR) 93, 115 private key 217, 218, 219, 221, 224, 226, 227 prj.conf 99, 138, 141, 155, 166, 189, 204, 210, 213, 223, 227, 237

PUT (0.03) 135, 140, 141, 151, 152, 55, 161, 162, 163, 170, 175, 176

PuTTY 32, 66

Pyspinel 46

R

Radio Co-Processor (RCP) 49, 58, 63, 122

radio interference 59

Raspberry Pi 47, 49

Raspberry Pi OS 49

Reduced Function Device (RFD) 14 reliability 18

Reset (RST) 132, 133, 134, 138, 151 response code 135, 137, 150, 153 RLOC16 44, 81, 90, 91, 92, 95, 111 Router 18, 43, 71, 80, 81, 82, 83, 91, 106, 107, 108, 109, 110, 192 Router capabilities 82, 83

Index ● 255

Router Eligible End Device (REED) 18, 82, 83, 106, 107, 109

Router ID 91, 111

router table 71, 110, 111, 112

Routing Locator (RLOC) 90, 91, 92, 95

routing table 82, 83

S screen 32, 66

security 18

self-healing 18, 85

serial connection 32, 66, 100, 217, 248, 249

serial terminal 66

service discovery 48, 68, 93, 179

service name 189

Service Registration Protocol (SRP) 48, 179

Service Registry 181

sleep mode 83

Sleepy End Device (SED) 18, 43, 83, 89, 107, 238

Source Meter mode 232, 233

Spinel 63

SRP client 181, 182, 184

SRP server 181, 182, 185

SRP service 179, 186, 189

Stateless Address Autoconfiguration (SLAAC) 100

Synchronized Sleepy End Device (SSED) 83 synthesized IPv6 address 114, 115, 120 T

Thread Group 12, 245

Thread Management Framework (TMF) 178

Thread protocol stack 13

Thread specification 12, 245

Thread version 105, 180

TLV (Type-Length-Value) 109 token 135, 137, 153, 155, 154

Transmission Control Protocol (TCP) 13, 49 transport layer 13, 16

U

UF2 251 unicast address 88, 90

Unique Local Address (ULA) 90

USB extension cable 59 User Datagram Protocol (UDP) 13, 16, 118

west 29, 97 west build 29 west flash 29 Wireshark 33, 70

X.509 certificate 217, 223, 227 XPAN ID 74, 107

Zephyr 21

Zephyr development environment 26

Zephyr shell 33, 100, 237 zeroconf 197 Zigbee 14, 16, 17

wireless sensor
OpenThread ● 256
Building
networks with
W
X
Z

Building Wireless Sensor Networks with OpenThread

Developing CoAP applications for Thread networks with Zephyr

This book will guide you through the operation of Thread*, the setup of a Thread network, and the creation of your own Zephyr-based OpenThread applications to use it. You’ll acquire knowledge on:

> The capture of network packets on Thread networks using Wireshark and the nRF Sni er for 802.15.4.

> Network simulation with the OpenThread Network Simulator.

> Connecting a Thread network to a non-Thread network using a Thread Border Router.

> The basics of Thread networking, including device roles and types, as well as the diverse types of unicast and multicast IPv6 addresses used in a Thread network.

> The mechanisms behind network discovery, DNS queries, NAT64, and multicast addresses.

> The process of joining a Thread network using network commissioning.

> CoAP servers and clients and their OpenThread API.

> Service registration and discovery.

> Securing CoAP messages with DTLS, using a pre-shared key or X.509 certificates.

> Investigating and optimizing a Thread device’s power consumption.

Once you‘ve set up a Thread network with some devices and tried connecting and disconnecting them, you’ll have gained a good insight into the functionality of a Thread network, including its self-healing capabilities. After you’ve experimented with all code examples in this book, you’ll also have gained useful programming experience using the OpenThread API and CoAP.

*Thread is a protocol for building e icient, secure and scalable wireless mesh networks for the Internet of Things (IoT), based on IPv6. OpenThread is an open-source implementation of the Thread protocol, originally developed by Google. It o ers a comprehensive Application Programming Interface (API) that is both operating system and platform agnostic. OpenThread is the industry’s reference implementation and the go-to platform for professional Thread application developers.

Koen Vervloesem has been writing for over 20 years on Linux, open-source software, security, home automation, artificial intelligence (AI), programming, and the Internet of Things (IoT). He holds a Master’s degree in Computer Science Engineering, a Master’s degree in Philosophy, and an LPIC-3 303 Security certificate. He is a teaching Linux and Python classes to students aspiring to an Associate degree in Internet of Things. Elektor International Media www.elektor.com

6|4006 10|2004
booksbooks

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.