Skip to content

Internet of Things Systems

Introduction

The Internet of Things (IoT) connects physical-world devices through networks to enable data collection, remote control, and intelligent decision-making. This article covers IoT architecture, communication protocols, edge computing, device management, and security.


1. IoT System Architecture

┌──────────────────────────────────────────┐
│              Cloud Platform               │
│  ┌──────┐ ┌────────┐ ┌──────┐ ┌────────┐│
│  │Storage│ │Analytics│ │Rules │ │Apps/    ││
│  │       │ │Engine  │ │Engine│ │Dashboard││
│  └──────┘ └────────┘ └──────┘ └────────┘│
└────────────────┬─────────────────────────┘
                 │ MQTT/HTTPS/AMQP
┌────────────────┴─────────────────────────┐
│           Gateway Layer                   │
│  Protocol conversion, data aggregation,   │
│  local caching, edge computing            │
└────────────────┬─────────────────────────┘
                 │ BLE/Zigbee/LoRa/WiFi
┌────────────────┴─────────────────────────┐
│         Edge Devices                      │
│  ┌──────┐ ┌────────┐ ┌──────┐ ┌─────┐   │
│  │Sensor│ │Actuator│ │Camera│ │ MCU │   │
│  └──────┘ └────────┘ └──────┘ └─────┘   │
└──────────────────────────────────────────┘

Three-Layer Architecture

Layer Role Representatives
Perception Layer Data collection, action execution Sensors, MCUs, actuators
Network Layer Data transmission, protocol conversion Gateways, routers
Application Layer Storage, analysis, visualization Cloud platforms, applications

2. Communication Protocols

2.1 MQTT

MQTT (Message Queuing Telemetry Transport) is the most popular IoT protocol, based on a publish/subscribe model.

Publisher                Broker               Subscriber
   │                       │                      │
   │── CONNECT ──────→     │                      │
   │← CONNACK ────────     │                      │
   │                       │    ←── SUBSCRIBE ─── │
   │                       │       (topic: temp)   │
   │── PUBLISH ──────→     │                      │
   │  (topic: temp,        │── PUBLISH ─────────→ │
   │   payload: 25.5)      │   (topic: temp,       │
   │                       │    payload: 25.5)     │

QoS Levels:

QoS Name Guarantee Use Case
0 At most once May be lost Sensor telemetry
1 At least once May be duplicated Alert notifications
2 Exactly once Guaranteed exactly once Billing data

MQTT Topic Design:

# Hierarchical structure
building/floor1/room101/temperature
building/floor1/room101/humidity
building/floor1/+/temperature    # + matches a single level
building/#                        # # matches multiple levels

# Best practice
{project}/{site}/{device_type}/{device_id}/{telemetry_type}
factory/shanghai/sensor/temp-001/temperature
# Python MQTT client
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    client.subscribe("sensors/+/temperature")

def on_message(client, userdata, msg):
    print(f"{msg.topic}: {msg.payload.decode()}")

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.tls_set()  # enable TLS
client.username_pw_set("device01", "secret")
client.connect("broker.example.com", 8883)
client.loop_forever()

2.2 CoAP

CoAP (Constrained Application Protocol) is a REST-style protocol designed for resource-constrained devices.

Feature CoAP HTTP
Transport layer UDP TCP
Header overhead 4 bytes Hundreds of bytes
Methods GET/POST/PUT/DELETE Same
Discovery /.well-known/core No standard
Observation Observe option Long polling/WebSocket
Suited for Constrained devices General web

2.3 Other Protocols

Protocol Features Use Cases
HTTP/HTTPS General-purpose, high overhead Non-constrained devices, cloud APIs
WebSocket Full-duplex, real-time Real-time monitoring dashboards
BLE Low power, short range Wearable devices
Zigbee Mesh network, low power Smart home
LoRa/LoRaWAN Long range (several km) Agriculture, environmental monitoring
NB-IoT Cellular network, low power Smart cities, metering

3. Edge Computing

3.1 Why Edge Computing

Requirement Cloud Computing Issue Edge Computing Solution
Low latency Network round-trip delay Local processing
Bandwidth Uploading raw data is expensive Local filtering/compression
Privacy Sending sensitive data to cloud is risky Process locally, transmit only results
Offline Cannot work with unstable network Autonomous local operation

3.2 Edge Inference

Running AI models on edge devices:

# TensorFlow Lite inference on Raspberry Pi
import tflite_runtime.interpreter as tflite
import numpy as np

# Load quantized model
interpreter = tflite.Interpreter(model_path="model_quant.tflite")
interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Inference
input_data = np.array(sensor_reading, dtype=np.float32).reshape(1, -1)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
result = interpreter.get_tensor(output_details[0]['index'])

if result[0] > 0.8:
    send_alert("Anomaly detected!")  # only report when anomaly is detected

Edge AI hardware:

Hardware Compute Power Power Consumption Use Case
Raspberry Pi General CPU 5-15W Prototyping, lightweight inference
NVIDIA Jetson GPU-accelerated 5-30W Vision, complex models
Google Coral TPU-accelerated 2W Classification, detection
MCU (STM32) Limited mW range Keyword detection, gestures

3.3 Data Filtering and Aggregation

class EdgeDataProcessor:
    def __init__(self, window_size=60):
        self.buffer = []
        self.window_size = window_size

    def process(self, reading):
        self.buffer.append(reading)

        if len(self.buffer) >= self.window_size:
            # Local aggregation to reduce upload volume
            summary = {
                "mean": np.mean(self.buffer),
                "max": np.max(self.buffer),
                "min": np.min(self.buffer),
                "std": np.std(self.buffer),
                "anomaly_count": sum(1 for x in self.buffer if self._is_anomaly(x))
            }
            self.buffer.clear()
            return summary  # only upload the summary
        return None

4. Device Management

4.1 Device Lifecycle

Provisioning → Activation → Operation → Maintenance → Decommission

4.2 Device Provisioning

# Device first connection: auto-registration
device_info = {
    "device_id": get_unique_id(),      # hardware unique identifier
    "firmware_version": "1.2.0",
    "model": "sensor-v3",
    "capabilities": ["temperature", "humidity"],
    "certificate": load_device_cert()   # X.509 certificate
}

# Register with cloud platform
response = requests.post(
    "https://iot.example.com/api/devices/register",
    json=device_info,
    cert=("device.crt", "device.key")  # mutual TLS
)

4.3 OTA Firmware Updates

Cloud platform → Notify device of new firmware
Device → Download firmware (chunked, resumable)
Device → Verify firmware (CRC + digital signature)
Device → Install to backup partition
Device → Reboot, run new firmware
Device → Self-test succeeds → Report to cloud
                            → Fails → Rollback

4.4 Device Monitoring

Monitoring metrics:

Metric Description
Online status Heartbeat detection (MQTT Last Will)
Firmware version Confirm update status
Battery level Low battery warning
Signal strength Network quality
Error logs Remote fault diagnosis
Resource usage CPU, memory, storage

5. IoT Security

5.1 Threat Model

Threat Description Protection
Eavesdropping Intercepting communication data TLS/DTLS encryption
Spoofing Impersonating legitimate devices Device certificate authentication
Tampering Modifying transmitted data Message integrity verification
Firmware extraction Reading device firmware Secure boot, encrypted storage
Physical attack Physical access to device Tamper-resistant hardware, secure elements
DDoS Hijacking large numbers of devices Traffic monitoring, device authentication

5.2 TLS/DTLS

Device ←────── TLS 1.3 ──────→ MQTT Broker
      Mutual certificate authentication (mTLS)

Device certificate chain:
Root CA → Intermediate CA → Device Certificate

5.3 Device Certificate Management

# Device side: connect using X.509 certificates
import ssl

context = ssl.create_default_context()
context.load_cert_chain(
    certfile="/certs/device.crt",
    keyfile="/certs/device.key"
)
context.load_verify_locations(cafile="/certs/root_ca.crt")

# Connect to MQTT broker
client.tls_set_context(context)
client.connect("broker.example.com", 8883)

6. IoT Cloud Platforms

6.1 Major Platform Comparison

Platform Protocol Support Edge Capability Features
AWS IoT Core MQTT, HTTP, WebSocket Greengrass Rules engine, Shadow
Azure IoT Hub MQTT, AMQP, HTTP IoT Edge Digital Twins
Google Cloud IoT MQTT, HTTP Edge TPU AI/ML integration
Alibaba Cloud IoT MQTT, CoAP Link Edge Thing model, all-in-one

6.2 Device Shadow/Twin

A device shadow is a cloud-side mirror of device state, allowing operations while the device is offline:

{
    "state": {
        "desired": {
            "temperature_threshold": 30,
            "report_interval": 60
        },
        "reported": {
            "temperature": 25.5,
            "firmware_version": "1.2.0",
            "battery": 85
        }
    },
    "metadata": {
        "timestamp": "2024-01-15T10:30:00Z"
    }
}

Workflow:

  1. Application modifies desired state
  2. Device comes online and receives the diff between desired and reported
  3. Device executes the operation and updates reported state
  4. Diff is eliminated, synchronization complete

Relations to Other Topics

References

  • "Designing the Internet of Things" - Adrian McEwen
  • MQTT Specification: https://mqtt.org
  • AWS IoT Developer Guide
  • "IoT Inc" - Bruce Sinclair

评论 #