Skip to main content
  1. Posts/

IoT Complete Guide: From Concept to Practice

sun.ao
Author
sun.ao
I’m sun.ao, a programmer passionate about technology, focusing on AI and digital transformation.
Table of Contents

What is IoT?
#

IoT (Internet of Things) is a simple yet profound concept: connecting everything, letting objects “speak.”

Traditional internet connects people—you watch videos on your phone, send emails on your computer. IoT connects objects—temperature sensors, smart bulbs, industrial robots, soil monitors in farmland…

The essence of IoT: digitizing the physical world, giving objects the ability to sense, communicate, and compute.

A Simple Example
#

Imagine a smart greenhouse:

┌─────────────────────────────────────────────────────────┐
│                   Smart Greenhouse System                │
│                                                         │
│  ┌──────────┐    ┌──────────┐    ┌──────────┐          │
│  │Temp Sensor│    │Humid Sensor│   │Light Sensor│        │
│  └─────┬────┘    └─────┬────┘    └─────┬────┘          │
│        │               │               │                │
│        └───────────────┼───────────────┘                │
│                        ▼                                │
│              ┌─────────────────┐                        │
│              │  Edge Gateway/   │                        │
│              │  Controller      │                        │
│              │ (Data collection │                        │
│              │  + decision)     │                        │
│              └────────┬────────┘                        │
│                       │                                 │
│        ┌──────────────┼──────────────┐                  │
│        ▼              ▼              ▼                  │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐              │
│  │Ventilation│  │Irrigation│  │Sunshade  │              │
│  │  System   │  │  System  │  │  Curtain │              │
│  └──────────┘  └──────────┘  └──────────┘              │
│                                                         │
│     High temp → Auto ventilate    Dry soil → Auto water │
│     Strong light → Lower sunshade curtain                │
└─────────────────────────────────────────────────────────┘

Without human intervention, the greenhouse automatically maintains optimal growing conditions. This is the power of IoT.

IoT Three-Layer Architecture
#

To understand IoT, first understand its layered architecture:

┌─────────────────────────────────────────────────────────┐
│                  Application Layer                       │
│       User interface, business logic, data analysis,     │
│              AI decision making                          │
│        Mobile App, Web Platform, Dashboard               │
└─────────────────────────────────────────────────────────┘
                           │ Cloud Communication (MQTT/HTTP/CoAP)
┌─────────────────────────────────────────────────────────┐
│                    Network Layer                         │
│    Data transmission, protocol conversion, edge         │
│    computing, security authentication                    │
│      Gateway, Router, Base Station, Edge Server         │
└─────────────────────────────────────────────────────────┘
                           │ Local Communication (WiFi/Bluetooth/Zigbee)
┌─────────────────────────────────────────────────────────┐
│                   Perception Layer                       │
│       Data collection, device control, local processing  │
│     Sensors, Actuators, Embedded Devices, Smart Terminals│
└─────────────────────────────────────────────────────────┘

Perception Layer: IoT’s “Senses”
#

The perception layer is IoT’s “eyes” and “hands”:

Sensors (Perceiving the World):

TypeFunctionApplication
Temperature/HumiditySense environmental conditionsSmart home, agriculture, warehousing
Light sensorDetect light intensitySmart lighting, agriculture
Motion sensorDetect human movementSecurity, smart switches
Gas sensorDetect harmful gasesIndustrial safety, air quality
GPS/BeiDouPosition trackingLogistics, fleet management
CameraVisual perceptionSecurity, facial recognition

Actuators (Changing the World):

TypeFunctionApplication
RelayControl circuit on/offSmart plugs, lighting control
MotorMechanical movementSmart curtains, robotics
Solenoid valveControl fluid flowSmart irrigation, gas control
Buzzer/SpeakerSound outputAlarms, voice interaction

Network Layer: IoT’s “Nerves”
#

The network layer handles data transmission, serving as IoT’s “neural pathways.”

Communication Protocol Comparison
#

ProtocolRangePowerBandwidthTypical Application
WiFi50-100mHighHighSmart home, video surveillance
Bluetooth (BLE)10-100mLowMediumWearables, smart locks
Zigbee10-100mVery LowLowSmart home, industrial sensors
Z-Wave30mVery LowLowSmart home
LoRa2-15kmVery LowVery LowSmart agriculture, cities
NB-IoT10km+Very LowLowSmart metering, bike sharing
5GSeveral kmMediumVery HighAutonomous driving, industrial control

How to Choose a Communication Protocol?
#

                    Need to transmit video/large data?
              ┌────────────┴────────────┐
              │ Yes                     │ No
              ▼                         ▼
         WiFi / 5G              Need long-range transmission?
                        ┌────────────┴────────────┐
                        │ Yes                     │ No
                        ▼                         ▼
                   LoRa / NB-IoT           Battery-powered device?
                                  ┌────────────┴────────────┐
                                  │ Yes                     │ No
                                  ▼                         ▼
                            Zigbee / BLE                 WiFi
                            (Low power mesh)          (Easy access)

Application Layer: IoT’s “Brain”
#

The application layer is what users directly interact with, including:

  • User Interface: Mobile App, Web Platform, Mini-programs
  • Data Storage: Time-series databases (InfluxDB, TimescaleDB)
  • Data Processing: Real-time stream processing, batch analysis
  • AI Decision Making: Anomaly detection, predictive maintenance, intelligent control

Core Communication Protocols Explained
#

MQTT: The De Facto Standard for IoT
#

MQTT (Message Queuing Telemetry Transport) is the most popular IoT communication protocol, designed for low-bandwidth, unstable networks.

Core Concepts
#

┌──────────────┐         ┌──────────────┐         ┌──────────────┐
│   Publisher  │         │    Broker    │         │  Subscriber  │
│(Temp Sensor) │         │(Message Agent)│        │ (Mobile App) │
└──────┬───────┘         └──────┬───────┘         └──────┬───────┘
       │                        │                        │
       │  Publish               │                        │
       │  Topic: home/temp      │                        │
       │  Payload: {"temp":25}  │                        │
       │───────────────────────▶│                        │
       │                        │  Forward               │
       │                        │  Topic: home/temp      │
       │                        │───────────────────────▶│
       │                        │                        │

Key Features:

FeatureDescription
Pub/Sub PatternDecouples devices and applications, supports one-to-many
QoS Levels0-At most once, 1-At least once, 2-Exactly once
Last WillAuto-notification on abnormal disconnection
Retained MessageNew subscribers immediately get latest state
LightweightMinimum message header only 2 bytes

QoS Levels Explained
#

QoS 0: At Most Once
┌───────┐                    ┌───────┐
│Publisher│───PUBLISH───▶    │Broker │
└───────┘                    └───────┘
"Fire and forget, no delivery guarantee"
Use case: Frequent sensor data, losing a few is fine

QoS 1: At Least Once
┌───────┐                    ┌───────┐
│Publisher│───PUBLISH───▶    │Broker │
│         │◀──PUBACK────     │       │
└───────┘                    └───────┘
"Confirmed delivery, possible duplicates"
Use case: Important data, receiver can deduplicate

QoS 2: Exactly Once
┌───────┐                    ┌───────┐
│Publisher│───PUBLISH───▶    │Broker │
│         │◀──PUBREC────     │       │
│         │───PUBREL───▶     │       │
│         │◀──PUBCOMP───     │       │
└───────┘                    └───────┘
"Four-way handshake, exact delivery"
Use case: Billing, payments where duplicates are unacceptable

Code Example
#

# Python MQTT Client Example
import paho.mqtt.client as mqtt
import json
import random
import time

# Connection callback
def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    # Subscribe to topic
    client.subscribe("home/+/command")

# Message callback
def on_message(client, userdata, msg):
    print(f"Topic: {msg.topic}, Payload: {msg.payload.decode()}")

# Create client
client = mqtt.Client(client_id="temp-sensor-001")
client.on_connect = on_connect
client.on_message = on_message

# Connect to Broker
client.connect("broker.example.com", 1883, 60)

# Simulate temperature reporting
def publish_temperature():
    temp = round(20 + random.random() * 10, 1)
    payload = json.dumps({
        "device_id": "temp-sensor-001",
        "temperature": temp,
        "timestamp": int(time.time())
    })
    client.publish("home/livingroom/temperature", payload, qos=1)
    print(f"Published: {payload}")

# Start network loop
client.loop_start()

while True:
    publish_temperature()
    time.sleep(5)

CoAP: Constrained Device Protocol
#

CoAP (Constrained Application Protocol) is designed for resource-constrained devices, similar to a “lightweight HTTP.”

HTTP vs CoAP Comparison:

HTTP:
GET /sensors/temperature HTTP/1.1
Host: example.com
Accept: application/json
User-Agent: Mozilla/5.0...
(Hundreds of bytes in headers)

CoAP:
CON GET /sensors/temperature
Token: 0x01
Accept: application/json
(Only a few bytes in headers)

Use Cases: Embedded devices, low-power sensor networks

HTTP/REST: Universal Solution
#

For devices with stable power and network connections, HTTP REST API remains a simple and reliable choice:

# Report temperature data
POST /api/v1/devices/temp-sensor-001/telemetry
Content-Type: application/json

{
  "temperature": 25.6,
  "humidity": 65,
  "timestamp": "2026-03-26T10:30:00Z"
}

# Get device status
GET /api/v1/devices/temp-sensor-001/status

# Send control command
POST /api/v1/devices/smart-plug-001/command
{
  "action": "turn_on",
  "params": {}
}

Edge Computing: Bringing Compute to the Data Source
#

Why Edge Computing?
#

Traditional cloud computing: All data uploaded to cloud for processing

┌─────────┐                    ┌─────────┐
│ Sensor  │────Upload data────▶│  Cloud  │
└─────────┘                    │ Process │
                               │ Analyze │
                               └────┬────┘
                               ┌────▼────┐
                               │Send cmd │
                               └────┬────┘
┌─────────┐                         │
│Actuator │◀────────────────────────┘
└─────────┘

Problems:
- High latency (round-trip to cloud)
- High bandwidth cost (massive data upload)
- Privacy risk (sensitive data leaves local)
- Poor reliability (offline = broken)

Edge computing: Process data locally

┌─────────────────────────────────────────┐
│          Edge Gateway/Edge Server        │
│  ┌─────────┐  ┌─────────┐  ┌─────────┐  │
│  │Data     │  │Local    │  │Protocol │  │
│  │Processing│ │Decision │  │Conversion│ │
│  └─────────┘  └─────────┘  └─────────┘  │
└────────────────────┬────────────────────┘
                     │ Only upload key data/results
              ┌─────────┐
              │  Cloud  │
              │ Global  │
              │ Analysis│
              └─────────┘

Advantages:
- Low latency (local processing, millisecond response)
- Save bandwidth (only upload necessary data)
- More secure (sensitive data stays local)
- More reliable (works offline)

Edge Computing Architecture
#

┌─────────────────────────────────────────────────────────────┐
│                        Cloud Layer                           │
│     Global analysis, model training, historical data storage │
└─────────────────────────────┬───────────────────────────────┘
                              │ MQTT/HTTP
┌─────────────────────────────────────────────────────────────┐
│                        Edge Layer                            │
│  ┌───────────────────────────────────────────────────────┐  │
│  │                Edge Gateway/Edge Server                │  │
│  │  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐     │  │
│  │  │Data     │ │Rule     │ │Local    │ │AI       │     │  │
│  │  │Aggregation│Engine   │ │Storage  │ │Inference │     │  │
│  │  └─────────┘ └─────────┘ └─────────┘ └─────────┘     │  │
│  └───────────────────────────────────────────────────────┘  │
└─────────────────────────────┬───────────────────────────────┘
           ┌──────────────────┼──────────────────┐
           │                  │                  │
           ▼                  ▼                  ▼
    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐
    │   Zigbee    │    │  Bluetooth  │    │   Wired     │
    │ Coordinator │    │ BLE Gateway │    │ Serial/RS485│
    └──────┬──────┘    └──────┬──────┘    └──────┬──────┘
           │                  │                  │
    ┌──────┴──────┐    ┌──────┴──────┐    ┌──────┴──────┐
    │ Zigbee      │    │ BLE Devices │    │ Industrial  │
    │ Devices     │    │             │    │ Sensors     │
    └─────────────┘    └─────────────┘    └─────────────┘

Edge Computing Platforms
#

PlatformFeaturesUse Case
AWS IoT GreengrassAWS ecosystem, Lambda supportAWS users
Azure IoT EdgeMicrosoft ecosystem, container supportAzure users
KubeEdgeKubernetes nativeCloud-native environments
EdgeX FoundryOpen source, hardware-agnosticGeneral industrial scenarios
Node-REDVisual programmingRapid prototyping

IoT Platforms: Accelerating Development
#

Why IoT Platforms?
#

Building an IoT system from scratch requires handling:

  • Device connectivity and management
  • Authentication and security
  • Data collection and storage
  • Rule engines and alerts
  • Visualization and APIs

IoT platforms package these common capabilities so you can focus on business logic.

Mainstream IoT Platforms Comparison
#

PlatformTypeFeaturesPricing
AWS IoT CoreCloudComprehensive features, rich ecosystemPay-as-you-go
Azure IoT HubCloudEnterprise-grade, deep Azure integrationPay-as-you-go
Alibaba Cloud IoTCloudGood China ecosystem, Chinese supportPay-as-you-go
Tencent Cloud IoTCloudWeChat mini-program integrationPay-as-you-go
ThingsBoardOpen SourceSelf-hosted, powerful featuresFree/Commercial
EMQXOpen SourceMQTT Broker specialistFree/Enterprise
Home AssistantOpen SourceSmart home favoriteFree

ThingsBoard Quick Start
#

ThingsBoard is an open-source IoT platform supporting device management, data visualization, and rule engines.

# docker-compose.yml
version: '3'
services:
  thingsboard:
    image: thingsboard/tb-postgres
    ports:
      - "9090:9090"
      - "1883:1883"
      - "7070:7070"
    environment:
      TB_QUEUE_TYPE: in-memory
    volumes:
      - ./data:/data
      - ./logs:/var/log/thingsboard

Device Integration Example:

import paho.mqtt.client as mqtt
import json
import time

# ThingsBoard MQTT Integration
THINGSBOARD_HOST = "localhost"
ACCESS_TOKEN = "your-device-token"

client = mqtt.Client()
client.username_pw_set(ACCESS_TOKEN)
client.connect(THINGSBOARD_HOST, 1883, 60)

# Report telemetry data
while True:
    telemetry = {
        "temperature": 25.5,
        "humidity": 60
    }
    client.publish("v1/devices/me/telemetry", json.dumps(telemetry))
    time.sleep(5)

Security: IoT’s Lifeline
#

IoT Security Challenges
#

IoT devices are numerous, distributed, and computationally limited, facing unique security challenges:

┌─────────────────────────────────────────────────────────────┐
│                    IoT Security Threats                      │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Device Layer Threats:                                       │
│  ├── Firmware vulnerability exploitation                     │
│  ├── Physical attacks (disassembly, tampering)              │
│  ├── Default/weak passwords                                 │
│  └── Malicious firmware flashing                            │
│                                                             │
│  Communication Layer Threats:                                │
│  ├── Man-in-the-middle attacks (eavesdropping, tampering)   │
│  ├── Replay attacks                                         │
│  ├── DDoS attacks (devices as botnets)                      │
│  └── Protocol vulnerability exploitation                     │
│                                                             │
│  Platform Layer Threats:                                     │
│  ├── Data breaches                                          │
│  ├── Unauthorized access                                    │
│  ├── API abuse                                              │
│  └── Supply chain attacks                                   │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Security Best Practices
#

1. Device Identity Authentication
#

Each device should have a unique identity, eliminating “default passwords”:

# Device certificate authentication example
import ssl

context = ssl.create_default_context()
context.load_cert_chain(
    certfile="/path/to/device.crt",
    keyfile="/path/to/device.key"
)
context.load_verify_locations("/path/to/ca.crt")

client.tls_set_context(context)
client.tls_insecure_set(False)  # Force server certificate verification

2. Communication Encryption
#

All communications must be encrypted using TLS/DTLS:

Unencrypted communication:
Device ────Plaintext data────▶ Server
        ⚠️ Can be eavesdropped, tampered

TLS Encrypted communication:
Device ════Encrypted data════▶ Server
        ✓ Confidentiality, integrity, authenticity

3. Secure Firmware Updates
#

Support OTA (Over-The-Air) secure updates:

Secure OTA Update Process:

1. Server signs firmware
   Firmware + Private key signature → Signed firmware package

2. Device verifies signature
   Signed firmware package + Public key → Verification passed → Install
                                      → Verification failed → Reject

3. Secure boot
   Verify firmware integrity on every boot

4. Principle of Least Privilege
#

Devices only have minimum permissions needed to complete tasks:

{
  "device_id": "temp-sensor-001",
  "permissions": {
    "publish": ["home/livingroom/temperature"],
    "subscribe": ["home/livingroom/command"]
  }
}

Hands-on: Building a Smart Home System
#

System Architecture
#

┌─────────────────────────────────────────────────────────────┐
│                    Smart Home System                         │
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │                   Home Assistant                     │   │
│  │              (Smart Home Control Center)             │   │
│  │  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐   │   │
│  │  │Automation│ │ Scenes  │ │ Voice   │ │ Mobile  │   │   │
│  │  │ Rules   │ │         │ │ Control │ │ Control │   │   │
│  │  └─────────┘ └─────────┘ └─────────┘ └─────────┘   │   │
│  └─────────────────────────────────────────────────────┘   │
│                           │                                 │
│              ┌────────────┼────────────┐                   │
│              │            │            │                   │
│              ▼            ▼            ▼                   │
│  ┌──────────────┐ ┌──────────────┐ ┌──────────────┐       │
│  │ Zigbee Hub   │ │ WiFi Devices │ │ Bluetooth    │       │
│  │              │ │              │ │ Devices      │       │
│  └──────┬───────┘ └──────┬───────┘ └──────┬───────┘       │
│         │                │                │                │
│  ┌──────┴───────┐ ┌──────┴───────┐ ┌──────┴───────┐       │
│  │Smart bulbs/  │ │Smart plugs/  │ │Smart locks/  │       │
│  │switches      │ │cameras       │ │sensors       │       │
│  │Curtain motors│ │Smart speakers│ │Thermometers  │       │
│  └──────────────┘ └──────────────┘ └──────────────┘       │
└─────────────────────────────────────────────────────────────┘

Home Assistant Installation
#

# docker-compose.yml
version: '3'
services:
  homeassistant:
    container_name: homeassistant
    image: homeassistant/home-assistant:stable
    volumes:
      - ./config:/config
      - /etc/localtime:/etc/localtime:ro
    restart: unless-stopped
    privileged: true
    network_mode: host

Automation Rule Examples
#

# configuration.yaml
automation:
  # Auto turn on lights when arriving home
  - alias: "Turn on lights when arriving home"
    trigger:
      - platform: state
        entity_id: device_tracker.phone
        to: "home"
    action:
      - service: light.turn_on
        target:
          entity_id: light.living_room
        data:
          brightness_pct: 80

  # Auto turn on AC when temperature is high
  - alias: "Turn on AC when temperature is high"
    trigger:
      - platform: numeric_state
        entity_id: sensor.living_room_temperature
        above: 28
    condition:
      - condition: state
        entity_id: binary_sensor.home_occupied
        state: "on"
    action:
      - service: climate.set_temperature
        target:
          entity_id: climate.living_room_ac
        data:
          temperature: 26
          hvac_mode: cool

  # Auto turn off all lights at midnight
  - alias: "Turn off all lights at midnight"
    trigger:
      - platform: time
        at: "00:00:00"
    action:
      - service: light.turn_off
        target:
          entity_id: all

Industrial IoT (IIoT): The Core of Smart Manufacturing
#

Industry 4.0 and IIoT
#

Industrial IoT (IIoT) is the core technology of Industry 4.0:

Industry 1.0 → Industry 2.0 → Industry 3.0 → Industry 4.0
Steam engine    Electrification  Automation      Intelligence
Mechanical      Assembly line    PLC control     IIoT + AI

Industry 4.0 Core Features:
├── Interconnectivity: Full connection of devices, systems, people
├── Data-driven: Data becomes core production factor
├── Intelligent decisions: AI-assisted or autonomous decisions
└── Flexible production: Personalized customization, flexible manufacturing

Predictive Maintenance
#

Traditional maintenance approaches:

ApproachDescriptionProblem
ReactiveFix after failureHigh downtime loss
PreventiveReplace parts on scheduleOver-maintenance, waste
PredictivePredict based on device conditionJust right, optimal solution

Predictive Maintenance Implementation:

┌─────────────────────────────────────────────────────────────┐
│                Predictive Maintenance System                 │
│                                                             │
│  Data Collection Layer:                                      │
│  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐          │
│  │Vibration│ │Temp     │ │Current  │ │Acoustic │          │
│  │Sensor   │ │Sensor   │ │Sensor   │ │Sensor   │          │
│  └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘          │
│       └───────────┼───────────┼───────────┘                │
│                   ▼                                         │
│  ┌─────────────────────────────────────────────────────┐   │
│  │              Edge Computing Gateway                  │   │
│  │  ┌─────────┐ ┌─────────┐ ┌─────────┐              │   │
│  │  │Data     │ │Feature  │ │Anomaly  │              │   │
│  │  │Preprocess│ │Extraction│ │Detection│              │   │
│  │  └─────────┘ └─────────┘ └─────────┘              │   │
│  └─────────────────────────────────────────────────────┘   │
│                   │                                         │
│                   ▼                                         │
│  ┌─────────────────────────────────────────────────────┐   │
│  │              Cloud AI Platform                       │   │
│  │  ┌─────────┐ ┌─────────┐ ┌─────────┐              │   │
│  │  │Model    │ │Lifetime │ │Maintenance│             │   │
│  │  │Training │ │Prediction│ │Recommendation│          │   │
│  │  └─────────┘ └─────────┘ └─────────┘              │   │
│  └─────────────────────────────────────────────────────┘   │
│                   │                                         │
│                   ▼                                         │
│  ┌─────────────────────────────────────────────────────┐   │
│  │              Maintenance Execution System            │   │
│  │  "Motor bearing predicted to fail within 72 hours,   │   │
│  │   recommend immediate replacement"                   │   │
│  └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

Digital Twin
#

A digital twin is a “mirror” of a physical device in the digital world:

Physical World                      Digital World
┌─────────────┐                    ┌─────────────┐
│ Physical    │◀────Real-time─────▶│ Digital     │
│ Device      │     data           │ Twin        │
│ (Motor/Line)│                    │ (3D Model)  │
└─────────────┘                    └──────┬──────┘
                              ┌───────────┼───────────┐
                              ▼           ▼           ▼
                         ┌─────────┐ ┌─────────┐ ┌─────────┐
                         │Performance│ │Fault   │ │Training │
                         │Optimization│ │Simulation│ │Drills  │
                         └─────────┘ └─────────┘ └─────────┘

Value:
- Trial and error in digital world, zero risk
- Apply optimized parameters to physical world
- Simulate extreme conditions, discover issues early

IoT Development Tech Stack
#

Embedded Development
#

PlatformFeaturesUse Case
ESP32WiFi+Bluetooth, cost-effectiveSmart home, wearables
STM32Industrial-grade, reliableIndustrial control, automotive
Raspberry PiLinux OS, powerfulEdge gateway, prototyping
ArduinoEasy to learn, rich ecosystemEducation, rapid prototyping

ESP32 Example Code:

#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>

// WiFi Configuration
const char* ssid = "your-ssid";
const char* password = "your-password";

// MQTT Configuration
const char* mqtt_server = "broker.example.com";
const char* mqtt_user = "device-001";
const char* mqtt_password = "device-token";

// Sensor Configuration
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  Serial.begin(115200);
  dht.begin();

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");

  // Configure MQTT
  client.setServer(mqtt_server, 1883);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  // Read sensor data
  float temp = dht.readTemperature();
  float hum = dht.readHumidity();

  if (!isnan(temp) && !isnan(hum)) {
    // Construct JSON message
    char payload[100];
    snprintf(payload, sizeof(payload),
             "{\"temperature\":%.1f,\"humidity\":%.1f}", temp, hum);

    // Publish to MQTT
    client.publish("home/livingroom/telemetry", payload);
    Serial.println(payload);
  }

  delay(5000);  // Report every 5 seconds
}

void reconnect() {
  while (!client.connected()) {
    if (client.connect("esp32-client", mqtt_user, mqtt_password)) {
      Serial.println("MQTT connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      delay(5000);
    }
  }
}

Backend Development
#

Common IoT backend tech stack:

LanguageFrameworkUse Case
Node.jsExpress, NestJSHigh concurrency, real-time
PythonFastAPI, DjangoRapid development, AI integration
GoGin, EchoHigh performance, microservices
JavaSpring BootEnterprise applications

Node.js + MQTT Example:

// server.js
const express = require('express');
const mqtt = require('mqtt');
const app = express();

// Connect to MQTT Broker
const client = mqtt.connect('mqtt://broker.example.com', {
  username: 'server',
  password: 'server-password'
});

// Subscribe to all device telemetry
client.subscribe('home/+/telemetry');

// Handle device messages
client.on('message', (topic, message) => {
  const deviceId = topic.split('/')[1];
  const data = JSON.parse(message.toString());

  console.log(`Device ${deviceId}:`, data);

  // Save to database
  saveTelemetry(deviceId, data);

  // Check alert rules
  if (data.temperature > 30) {
    sendAlert(deviceId, 'Temperature too high!');
  }
});

// REST API: Get device list
app.get('/api/devices', async (req, res) => {
  const devices = await getDevices();
  res.json(devices);
});

// REST API: Send control command
app.post('/api/devices/:id/command', async (req, res) => {
  const { id } = req.params;
  const { action, params } = req.body;

  client.publish(`home/${id}/command`, JSON.stringify({ action, params }));

  res.json({ success: true });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Time-Series Databases
#

IoT data is typical time-series data, requiring specialized databases:

DatabaseFeaturesUse Case
InfluxDBHigh write performance, built-in query languageMonitoring, IoT
TimescaleDBPostgreSQL extension, SQL compatibleTeams familiar with SQL
TDengineChinese, high performanceLarge-scale IoT
PrometheusMonitoring ecosystem, PromQLMonitoring and alerting

InfluxDB Example:

from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS

# Connect to database
client = InfluxDBClient(url="http://localhost:8086", token="your-token")

# Write data
write_api = client.write_api(write_options=SYNCHRONOUS)

point = Point("temperature") \
    .tag("device_id", "sensor-001") \
    .tag("location", "living_room") \
    .field("value", 25.5) \
    .field("humidity", 60.0)

write_api.write(bucket="iot", org="my-org", record=point)

# Query data
query_api = client.query_api()
query = '''
from(bucket: "iot")
  |> range(start: -1h)
  |> filter(fn: (r) => r._measurement == "temperature")
  |> filter(fn: (r) => r.device_id == "sensor-001")
'''
tables = query_api.query(query, org="my-org")

IoT Application Scenarios Overview
#

┌─────────────────────────────────────────────────────────────────────┐
│                    IoT Application Scenarios                         │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  Smart Home              Smart City             Smart Agriculture   │
│  ├── Smart lighting      ├── Smart traffic      ├── Precision       │
│  ├── Security monitoring │ ├── Environmental    │    irrigation     │
│  ├── Energy management   │    monitoring        ├── Soil monitoring │
│  └── Voice control       ├── Smart parking      ├── Greenhouse      │
│                          └── Waste management   │    control        │
│                                                 └── Pest early      │
│                                                     warning          │
│  Industrial IoT          Smart Healthcare        Smart Logistics    │
│  ├── Predictive          ├── Remote monitoring   ├── Cargo tracking │
│  │    maintenance        ├── Wearables           ├── Cold chain     │
│  ├── Production line     ├── Smart pill box      │    monitoring    │
│  │    monitoring         └── Rehabilitation      ├── Warehouse      │
│  ├── Digital twin           training             │    management    │
│  └── Quality tracing                            └── Route           │
│                                                      optimization   │
│  Smart Energy            Smart Retail            Connected Vehicles │
│  ├── Smart meters        ├── Smart shelves       ├── Vehicle        │
│  ├── Distributed energy  ├── Customer flow       │    tracking      │
│  ├── Load prediction     │    analysis           ├── Remote         │
│  └── Grid monitoring     ├── Auto replenishment  │    diagnostics   │
│                          └── Electronic          └── Autonomous     │
│                              price tags              driving        │
└─────────────────────────────────────────────────────────────────────┘

Future Trends#

1. AI + IoT = AIoT
#

Deep integration of AI and IoT, evolving devices from “connected” to “thinking”:

Traditional IoT: Collect data → Upload to cloud → Manual analysis
AIoT: Collect data → Edge AI analysis → Intelligent decision → Auto execute

Application Examples:
- Smart cameras: From "recording" to "understanding" (face recognition, behavior analysis)
- Industrial equipment: From "monitoring" to "predicting" (fault prediction, lifetime estimation)
- Smart speakers: From "listening to commands" to "understanding intent" (context understanding, proactive service)

2. Edge AI Chips
#

Dedicated AI chips give edge devices powerful computing:

ChipComputing PowerApplication
NVIDIA JetsonHighRobotics, autonomous driving
Google Edge TPUMediumVisual AI
Rockchip RK3588MediumEdge gateway
ESP32-S3LowVoice/image recognition

3. Matter Protocol Unifies Smart Home
#

Matter is a unified standard for smart home, breaking brand barriers:

Current State:
Xiaomi devices ←→ Xiaomi App
Huawei devices ←→ Huawei App
Apple devices ←→ HomeKit

Matter Era:
Any Matter device ←→ Any Matter platform

4. LPWAN Proliferation
#

NB-IoT, LoRa and other technologies take IoT to broader scenarios:

Traditional: Devices need frequent battery replacement or power source
LPWAN: One battery lasts 5-10 years

Applications:
- Smart water/gas meters (underground, no power)
- Bike sharing (scattered, no power)
- Agricultural monitoring (outdoor, no power)

Summary
#

IoT is moving from “concept” to “reality,” from “point applications” to “comprehensive connectivity.”

Key Takeaways
#

LayerCore TechnologyKey Points
PerceptionSensors, ActuatorsChoose appropriate sensors and communication methods
NetworkMQTT, CoAP, LoRaChoose protocol based on scenario, balance power and bandwidth
PlatformIoT platforms, Time-series DBUse existing platforms, avoid reinventing the wheel
ApplicationData analysis, AIData value mining, intelligent decisions
SecurityAuthentication, EncryptionSecurity throughout the lifecycle

Learning Path Recommendations
#

Beginner Stage:
├── Learn embedded development (Arduino/ESP32)
├── Understand MQTT protocol
├── Build smart home system (Home Assistant)
└── Practice small projects (temperature monitoring, smart switch)

Intermediate Stage:
├── Deep dive into IoT platforms (ThingsBoard/AWS IoT)
├── Learn edge computing
├── Master time-series databases
└── Understand Industrial IoT (OPC UA, Modbus)

Advanced Stage:
├── AIoT development (edge AI inference)
├── Large-scale system architecture design
├── Security system construction
└── Industry solution design

IoT is an interdisciplinary field requiring knowledge of hardware, software, networking, and security. But getting started isn’t hard—begin with a smart bulb, a temperature sensor, and gradually dive deeper. You’ll find the world of IoT fascinating.

Further Reading
#

Related articles