Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 79 ยท Wireless and Mobile Networks

Bluetooth, Zigbee, LoRa and IoT Networking

Compare short-range and low-power radios (Bluetooth, BLE, Zigbee, LoRa), see how mesh networks relay messages, and learn MQTT and CoAP, the IoT application protocols.

Not every wireless link needs to move video. A door sensor sends a few bytes a day, a wireless earbud streams audio a meter from your phone, and a soil probe in a field must run for years on two batteries. For these jobs Wi-Fi uses too much power and cellular costs too much, so a family of specialized radios and protocols exists.

This lesson sorts them by range and power, explains personal-area networks like Bluetooth and Zigbee, long-range low-power networks like LoRa, and how mesh networks pass messages along. It ends with the two application protocols that dominate the Internet of Things, MQTT and CoAP, and a runnable publish/subscribe broker that behaves like MQTT.

Choosing a radio: range, rate and power

Every wireless technology trades three things against each other. Pushing range up costs data rate or battery. Pushing data rate up costs range or battery. A rough map:

Technology Typical range Data rate Power Typical use
Bluetooth Classic ~10 m 1 to 3 Mbit/s medium headphones, car audio
Bluetooth Low Energy (BLE) 10 to 100 m up to 2 Mbit/s very low wearables, beacons, sensors
Zigbee / Thread (802.15.4) 10 to 100 m per hop, more with mesh 250 kbit/s very low smart-home lighting, sensors
Wi-Fi 30 to 100 m tens to thousands of Mbit/s high laptops, TVs
LoRa / LoRaWAN 2 to 15 km 0.3 to 50 kbit/s extremely low farms, meters, city sensors
NB-IoT / LTE-M cell coverage tens to hundreds of kbit/s low trackers, utility meters

The numbers are typical, not guarantees. Walls, antennas and interference change them a lot.

Personal-area networks

A PAN (personal-area network) connects devices around one person or desk, over a few meters. The big technologies are Bluetooth and the IEEE 802.15.4 family.

Bluetooth and BLE

Bluetooth works in the same 2.4 GHz unlicensed band as Wi-Fi, so it must live with interference. It uses frequency hopping: the radio jumps between channels many times per second, following a pseudo-random sequence both devices know, so a burst of noise on one channel damages only a few packets. (Adaptive hopping skips channels that are busy with Wi-Fi.)

There are two incompatible modes:

  • Bluetooth Classic (BR/EDR) keeps a connection open and streams, which suits audio.
  • Bluetooth Low Energy (BLE) sleeps almost all the time and wakes for milliseconds. It has 40 channels of 2 MHz; three of them (37, 38 and 39) are advertising channels.

A BLE device announces itself by advertising: it broadcasts a tiny packet (name, services, sometimes sensor data) every so often. Phones scan for these. Beacons (shop and museum tags) only advertise and never connect. If a client wants to talk, it sends a connection request, and the two exchange data at agreed intervals, sleeping in between.

Once connected, BLE data is organized by GATT (Generic Attribute Profile) as a small tree: a device exposes services (for example "Heart Rate"), each with characteristics (the actual values, such as the current heart rate). A client can read a characteristic, write it, or subscribe to be notified when it changes. Devices pair to create shared keys, and newer versions use elliptic-curve key exchange so a passive listener cannot derive them (see cryptography for networking).

Bluetooth connections form small topologies: one central (your phone) talks to several peripherals in a star. A separate standard, Bluetooth Mesh, builds a many-to-many network for lighting control.

Zigbee, Thread and 802.15.4

IEEE 802.15.4 defines the radio and link layer for low-rate, low-power devices: 250 kbit/s at 2.4 GHz with 16 channels, and small frames of at most 127 bytes. Several protocols sit on top:

  • Zigbee adds its own network and application layers, and is built for mesh networks with three roles: one coordinator (forms the network, holds security keys), routers (mains-powered nodes that relay) and end devices (battery nodes that sleep and talk only to their parent).
  • Thread also uses 802.15.4 but carries ordinary IPv6 packets using 6LoWPAN, a compression layer that squeezes a 40-byte IPv6 header into a few bytes and fragments packets to fit the 127-byte frames. Because Thread devices are real IP hosts, they can be reached from the Internet through a border router.
  • Matter is an application standard for smart homes that runs over Thread, Wi-Fi and Ethernet so that devices from different brands interoperate.

The Bluetooth network and protocol stack

Bluetooth devices form tiny networks of their own.

A piconet has one primary (also called the master or central) and up to seven active secondary (peripheral) devices. All the traffic goes through the primary, which sets the frequency-hopping sequence and the time slots, so there are no collisions inside a piconet. A device that is not active can still be "parked": the primary knows it but gives it no slot until it is needed. Many such piconets can exist in the same room, each with its own hopping sequence.

A scatternet joins piconets. A device that takes part in two piconets (secondary in one and primary in another, or secondary in both) acts as a bridge, so data can hop between them. The bridge device must share its time between the two hopping sequences, which lowers its throughput.

The Bluetooth stack is layered, and a few layers are worth knowing:

Layer Job
Radio and baseband Frequency hopping, time slots, packets, and link management
L2CAP (Logical Link Control and Adaptation Protocol) Multiplexes many upper-layer connections over one link, and splits and reassembles large packets to fit the baseband
RFCOMM Emulates a serial (RS-232) cable, so old serial-port programs can run over Bluetooth
SDP Service discovery: asks a device which services it offers
OBEX (Object Exchange) Sends objects such as files, contacts and calendar items, a lightweight cousin of HTTP
Profiles Rules for one use case: audio streaming (A2DP), hands-free calls (HFP), HID for keyboards and mice, and so on

Everyday examples are an in-car hands-free headset (HFP profile), a stereo headset (A2DP), a keyboard and a mouse (HID), a Bluetooth printer (serial-like printing profiles) and an image or contact transfer (OBEX). Disadvantages are short range, a slower speed than Wi-Fi, interference in the crowded 2.4 GHz band, security weaknesses in poorly implemented pairing, and a limited number of active devices per piconet.

Zigbee channel access and roles

Zigbee's 802.15.4 radio has two ways to give devices turns. In the contention-based method (CSMA-CA), a device listens before sending and backs off for a random time if the channel is busy, like Wi-Fi. In the contention-free method, the coordinator sends a periodic beacon that divides time into a superframe, and gives some devices guaranteed time slots (GTS) so that urgent traffic, such as an alarm, always gets through at a known time. Zigbee suits home automation, smart lighting, metering and industrial monitoring. Its disadvantages are a low data rate (250 kbit/s at best), a short range per hop, and the fact that devices from different vendors do not always interoperate unless they use the same application profile.

Mesh networks

In a star topology every device talks directly to a hub, so range is the hub's range. In a mesh network, nodes also relay for each other, so coverage extends hop by hop and the network can route around a failed node. The price is complexity, latency, and the energy spent forwarding.

There are two main ways a mesh forwards:

  • Routing: nodes learn paths (Zigbee uses an on-demand distance-vector method related to distance-vector routing). Efficient, but needs state and repair when nodes disappear.
  • Managed flooding: a node broadcasts a message and every node that hears it rebroadcasts it once, discarding duplicates, until a hop limit (a TTL, just like in IPv4) is used up. Bluetooth Mesh works this way. It needs no routing tables and survives failures, but it uses more airtime.
flowchart LR
    F["f (sensor)"] --- E["e"]
    E --- C["c"]
    E --- D["d"]
    C --- A["a"]
    C --- B["b"]
    D --- B
    A --- GW["gw (gateway)"]
    B --- GW

A message from the sensor f needs four hops to reach the gateway. Two different paths exist, so one failed relay does not cut it off.

Python Managed flooding in a mesh

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice the trade-off in the output: a TTL that is too small never reaches the gateway, and a TTL larger than needed wastes transmissions. A real mesh also adds random delays before relaying, so neighbors do not all transmit at the same instant.

Long range, low power: LoRa and LoRaWAN

LoRa is a radio modulation (chirp spread spectrum) for sub-GHz license-free bands such as 868 MHz in Europe and 915 MHz in North America. It trades speed for range: a signal can be decoded even when it is weaker than the background noise, giving ranges of kilometers from a tiny battery-powered device.

The spreading factor (SF7 to SF12) is the main dial. A higher SF sends each bit more slowly and more redundantly, so it reaches farther and survives weaker signals, but it takes much longer on the air. Each step up roughly doubles the time on air. Because the spectrum is shared, regions limit transmitters to a duty cycle, for example 1 percent of the time in much of Europe. That limits how often a device may send, and it makes airtime a budget to plan, not a free resource.

LoRaWAN is the network protocol on top of LoRa. It uses a star-of-stars topology: devices broadcast to any gateway in range, gateways forward everything over the Internet to a central network server, and the server removes duplicates and routes the data to an application. Devices do not join one gateway as in Wi-Fi. Class A devices open two short receive windows right after each transmission, which keeps battery life long but means a server can only send to a device after it has sent something.

Python LoRa time on air and the duty-cycle budget

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

At SF12 a 12-byte reading occupies the air for over a second, which leaves room for only about 31 packets per hour under a 1 percent limit. At SF7 the same reading takes 41 ms and the budget allows about 873. This is why LoRa sensors send small, infrequent messages.

IoT layers, sensors and actuators

The Internet of Things (IoT) is the idea of connecting everyday objects that sense or act, so software can read and control them. A common four-layer view:

  1. Perception (sensing) layer. The physical devices: sensors that measure something, and actuators that change something.
  2. Network layer. Carries the data using radios such as Wi-Fi, Bluetooth, Zigbee, LoRa or cellular, through a gateway.
  3. Processing (middleware) layer. Stores and analyzes the data. Instead of sending everything to a distant cloud, edge and fog computing do part of the work close to the devices, which cuts delay and saves bandwidth.
  4. Application layer. Dashboards, mobile apps and automation rules that give the data meaning.

Common sensors measure temperature, humidity, light, motion (accelerometers and gyroscopes measure acceleration and rotation), proximity and distance (ultrasonic sensors time an echo), gas (for example smoke or carbon monoxide), pressure and position (GPS). Actuators do something in response: switch a relay, turn a motor, open a valve, sound a buzzer. A control loop reads a sensor, decides, and triggers an actuator, for example a thermostat that switches the heating when the temperature falls below a threshold.

IoT is used for smart homes, healthcare and wearables, industrial IoT (IIoT) for machine monitoring, precision agriculture, and transport and logistics, where tracking improves decisions and cuts cost. The drawbacks are security (cheap devices with default passwords are easy targets), privacy of the data collected, dependence on connectivity and batteries, and the difficulty of updating thousands of devices.

Python A sensor, a rule and an actuator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Running this logic on the device itself (at the edge) means the heating keeps working even if the Internet link is down, and only summaries need to be sent to the cloud.

IoT application protocols

HTTP works, but it is heavy for a sensor with 8 KB of RAM. Two lightweight protocols are standard in IoT. They solve different problems.

MQTT: publish and subscribe over TCP

MQTT is a messaging protocol with a very small header (as little as 2 bytes). Devices never talk to each other directly. They connect over TCP (port 1883, or 8883 with TLS) to a central broker.

  • A client publishes a message to a topic, a hierarchical string such as home/livingroom/temperature.
  • A client subscribes to a topic filter. The broker forwards each matching message to every subscriber.
  • Filters can use wildcards: + matches exactly one level (home/+/temperature), and # matches everything below (home/livingroom/#).

Publishers and subscribers do not know about each other, so they can come and go independently, and one reading can reach many consumers. That decoupling is the point of the pattern. MQTT adds features that matter on unreliable networks:

  • QoS levels: 0 means at most once (fire and forget), 1 means at least once (acknowledged, duplicates possible), 2 means exactly once (a four-step handshake).
  • Retained messages: the broker remembers the last value of a topic and gives it to new subscribers immediately, so a dashboard does not have to wait for the next reading.
  • Last will: a client registers a message the broker publishes if the client vanishes without saying goodbye, which announces "sensor offline".
  • Keep-alive pings, so the broker notices dead connections.
flowchart LR
    S["Sensor<br/>publishes home/kitchen/temperature"] --> B["Broker"]
    B --> D["Dashboard<br/>subscribes home/#"]
    B --> A["Alarm<br/>subscribes home/+/temperature"]
    B --> L["Logger<br/>subscribes #"]

One publisher, three subscribers with different filters. The broker does the matching.

The program below is not real MQTT (real MQTT is a binary protocol), but it is a working broker with the same ideas: topics, + and # wildcards, and retained messages. It runs on the loopback interface, with clients and broker in the same process.

Node.js A tiny publish/subscribe broker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The dashboard gets only living-room topics, the alarm gets both temperatures but no humidity, and the late joiner receives the retained garage-door state without anyone publishing again.

CoAP: REST for constrained devices

CoAP (Constrained Application Protocol) takes the opposite approach: it keeps the request/response style of HTTP (GET, POST, PUT, DELETE on URLs, with response codes like 2.05 Content and 4.04 Not Found) but squeezes it into a compact binary format over UDP (port 5683, or 5684 with DTLS). A message has just a 4-byte fixed header.

Because UDP is unreliable, CoAP implements just enough reliability itself:

  • A confirmable message (CON) must be acknowledged (ACK). The sender retransmits with an increasing timeout until it gets one.
  • A non-confirmable message (NON) is sent once and forgotten.
  • Observe lets a client register interest in a resource and get a notification when it changes, which gives a publish/subscribe-like effect.
  • A proxy can translate between CoAP and HTTP, so a web app can reach a sensor.

Which to choose? MQTT fits many-to-many telemetry through a central broker and needs a TCP connection that stays open. CoAP fits direct request/response with a device, runs well on sleepy battery devices and 6LoWPAN links, and maps cleanly to REST. Both are common in the same system.

IoT devices are attractive targets: they are numerous, rarely updated and often shipped with default passwords. Use TLS (or DTLS) on MQTT and CoAP, give every device its own credentials, and keep firmware updatable. Attacks like these come back in network security fundamentals.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does Bluetooth use frequency hopping in the crowded 2.4 GHz band?

    The radio keeps jumping between channels along a sequence both devices know, so a burst of noise on one channel damages only a small share of the traffic.
  2. 2. In a managed-flooding mesh, what stops a message from circulating forever?

    Nodes remember messages they already relayed and drop duplicates, and the hop limit (TTL) is decremented at each relay so the message eventually dies.
  3. 3. Raising the LoRa spreading factor from SF7 to SF12 mainly does what?

    A higher spreading factor sends each symbol more slowly and redundantly. It reaches farther but occupies the air much longer, so fewer packets fit into a duty-cycle budget.
  4. 4. A subscriber uses the MQTT filter home/+/temperature. Which topic matches it?

    The + wildcard matches exactly one level. So home/kitchen/temperature matches, but a topic with two levels between home and temperature does not.
  5. 5. Which pairing of protocol and transport is correct?

    MQTT keeps a TCP connection to a broker. CoAP uses UDP and adds its own optional retransmission with confirmable messages.

Summary

  • Pick a radio by range, data rate and power: Bluetooth/BLE for personal devices, 802.15.4 (Zigbee, Thread) for home meshes, LoRa for kilometers at tiny rates, cellular IoT for wide-area coverage.
  • BLE devices advertise, connect and expose data as GATT services and characteristics; Bluetooth hops across 2.4 GHz channels to survive interference.
  • Mesh networks relay via routing or managed flooding; a TTL and duplicate suppression keep flooding under control.
  • LoRa trades speed for range with the spreading factor, and duty-cycle rules turn airtime into a budget; LoRaWAN uses gateways in a star-of-stars.
  • MQTT is topic-based publish/subscribe through a broker over TCP (wildcards, QoS, retained messages, last will); CoAP is compact REST over UDP with confirmable messages.

Next, protect all of this traffic: network security fundamentals.