UNIT 4: IoT LAB - EXAM-FOCUSED SHORT NOTES
4.1 Intermediate IoT Communication Protocols & Implementation
MQTT (Message Queuing Telemetry Transport) Deep Dive
-
Core Architecture: Broker-Client model using Publish/Subscribe pattern. Clients (publishers/subscribers) connect to a central Broker. Decouples senders from receivers.
-
QoS (Quality of Service) Levels:
| Level | Guarantee | Use Case in Labs | | :--- | :--- | :--- | | 0 (At most once) | Fire-and-forget. May be lost. | Non-critical, frequent sensor data (e.g., temperature every sec). | | 1 (At least once) | Guaranteed delivery, possible duplicates. | Command & control, critical but non-time-sensitive data. | | 2 (Exactly once) | Guaranteed, no duplicates. 4-step handshake. | Financial transactions, critical state changes. High overhead. |
-
Topic Design: Hierarchical, slash-separated strings (e.g.,
factory/floor1/machine5/temp). Enables wildcard subscriptions (+single,#multi-level) for scalable monitoring. -
Popular Brokers: Mosquitto (lightweight, open-source), HiveMQ (enterprise), Cloud brokers (AWS IoT Core, GCP IoT Core).
-
Client Libraries: Paho (standard for Python, Node.js, Arduino, embedded C). Key functions:
connect(),publish(),subscribe(),on_messagecallback.
[!TIP] Exam Focus: Know the trade-off between QoS levels (reliability vs. overhead). Be able to design a topic hierarchy for a given scenario (e.g., smart home, industrial).
CoAP (Constrained Application Protocol)
-
RESTful architecture designed for constrained devices (low power, low bandwidth).
-
UDP-based (vs. TCP for MQTT/HTTP), minimizing overhead. Uses confirmable (CON) and non-confirmable (NON) messages.
-
Key Features: Resource observation (client subscribes to resource changes via
GET; observe), block-wise transfer for large payloads. -
Lab Comparison:
-
MQTT: Pub/Sub, better for many-to-many, event-driven.
-
CoAP: Request/Response (REST), better for direct device interaction, fits web semantics.
-
HTTP: Too heavy for constrained nodes; CoAP is its optimized cousin.
-
HTTP/REST APIs for IoT
-
Design: Treat sensors as resources (e.g.,
/api/devices/{id}/sensors/temp). Use standard methods:-
GET: Read sensor data. -
POST: Create new resource/trigger action. -
PUT: Update configuration/state. -
DELETE: Remove resource.
-
-
Payload Format: JSON is standard. Lightweight, human-readable. XML is heavier, less common in modern IoT.
-
Lab Use: Simple cloud-to-device commands, device provisioning, or when devices have sufficient resources (e.g., Raspberry Pi as gateway).
4.2 Cloud IoT Platform Integration & Development
Platform-Agnostic Concepts
-
Device Shadow / Digital Twin: A JSON document in the cloud that stores the desired (cloud's intent) and reported (device's actual) state of a device. Enables cloud-to-device (C2D) commands and state sync even if device is offline.
-
desired:{"led": "ON"}(from cloud app) -
reported:{"led": "ON", "temp": 25.5}(from device) -
delta: Difference between desired and reported triggers action on device.
-
-
Rule Engine: Routes device data to other services (e.g., Lambda, DB, Pub/Sub) based on SQL-like rules.
SELECT * FROM 'topic/sensor' WHERE temperature > 30. -
Secure Provisioning: Just-In-Time (JIT) / Just-In-Time Registration (JITR). Device uses a one-time certificate to connect, platform auto-registers it and issues a permanent certificate.
Hands-on with Major Platforms
| Platform | Core Entity | Key Security | Key Integration |
|---|---|---|---|
| AWS IoT Core | Thing (device), Certificate/Policy | X.509 certs, IAM policies | Rules → Lambda, S3, Kinesis, DynamoDB |
| Google Cloud IoT Core | Registry (group of devices) | Public key auth (RSA/ES256) | Pub/Sub, Dataflow, BigQuery |
| Microsoft Azure IoT Hub | Device Identity, Twin | SAS tokens, X.509 certs | Stream Analytics, Functions, Cosmos DB |
| Blynk/ThingSpeak/Ubidots | Device, Dashboard Widget | API Tokens, simple auth | Built-in visualization, easy prototyping |
Building Custom Dashboards
-
Grafana: Connect to time-series DBs (InfluxDB, Prometheus) or cloud services. Excellent for historical plotting and alerting.
-
Node-RED Dashboard: UI nodes (
ui_gauge,ui_chart) for quick, web-based dashboards. Flows data from MQTT/HTTP. -
Custom Web Apps: Use JavaScript libraries (Chart.js, D3.js) consuming data from cloud APIs (REST/WebSockets).
4.3 IoT Security Fundamentals in Lab Context
Security at Different Layers
| Layer | Threats | Lab Countermeasures |
|---|---|---|
| Device/Hardware | Physical tampering, key extraction. | Secure Boot, TPM/SE (Trusted Platform Module/Secure Element), store keys in secure flash/OTP. |
| Communication | Eavesdropping, MITM, spoofing. | TLS/DTLS (for MQTT/CoAP over TCP/UDP), certificate-based auth (mTLS). |
| Cloud/Application | Unauthorized access, data leak. | Principle of Least Privilege (IAM), secure API endpoints, rate limiting. |
Practical Security Implementation in Labs
-
X.509 Certificates: Generate a CA, then device certificates signed by it. Use
opensslor platform tools (AWS IoT:create-certificate-from-CSR). -
mTLS for MQTT: Broker (e.g., Mosquitto) configured to require client certificates. Client library (Paho) loads its cert/key.
-
JWT for HTTP APIs: Device/App gets a JSON Web Token from auth server, sends
Authorization: Bearer <token>header. Validate token signature on server. -
Code Hygiene: Never hardcode keys/certs in source. Use environment variables or secure storage. Close unused ports. Validate all inputs.
[!TIP] Common Pitfall: Using default broker ports (1883 for MQTT, 8883 for MQTT over TLS) without firewall rules. Always change defaults in lab setups.
4.4 Edge Computing & Local Processing
Edge vs. Cloud Paradigm
| Factor | Cloud Computing | Edge Computing |
|---|---|---|
| Latency | High (network round-trip). | Very Low (local processing). |
| Bandwidth | High usage (send all data). | Reduced (send summaries/alerts). |
| Privacy | Data leaves premises. | Data stays local. |
| Reliability | Needs internet. | Works offline. |
| Compute | Massive, scalable. | Limited (gateway/node). |
Edge Implementation Frameworks
-
AWS Greengrass / Azure IoT Edge: Run Lambda functions or containers on edge devices (Raspberry Pi, industrial gateway). Sync with cloud, run offline.
-
Local MCU Processing: Run TensorFlow Lite Micro for simple ML (keyword spotting, anomaly detection). Do data filtering/aggregation (e.g., compute min/max/avg locally).
-
Pi as Edge Gateway: Runs local MQTT broker (Mosquitto), Node-RED for local automation, SQLite for local storage. Acts as a buffer and local brain.
4.5 Advanced Actuation & Control Systems
PWM & Motor Control
-
PWM (Pulse Width Modulation): Controls power/ speed by varying duty cycle (percentage of ON time in a period).
Duty Cycle (%) = (ON time / Period) * 100. -
Motor Drivers: Interface low-power MCU to high-power motors.
-
L293D / L298N: Dual H-bridge for DC motors (direction & speed via PWM).
-
PCA9685: 16-channel 12-bit PWM driver (I2C). Ideal for multiple servos (e.g., robotics).
-
-
Closed-Loop Control (PID Concept): Use feedback (sensor) to correct error between setpoint and process variable.
-
P (Proportional): Corrects current error.
-
I (Integral): Eliminates steady-state error.
-
D (Derivative): Predicts future error, dampens oscillations.
-
Lab Example: PID for temperature control (heater + thermocouple) or DC motor speed (encoder feedback).
-
Relay & High-Power Load Control
-
Relay Module: Electromechanical switch. Isolates low-voltage control circuit (MCU) from high-voltage AC/DC load.
-
Safety: Never wire AC directly to MCU pins. Use opto-isolated relay modules. Add fuses and interlock switches.
-
State Monitoring: Use relay's NC/NO contacts or a separate current sensor (ACS712) to confirm load state.
Multi-Actuator Synchronization
-
Coordinated Actions: Sequence based on multiple sensor inputs.
- Example: Conveyor belt (actuator 1) starts only when sensor A (item present) AND sensor B (path clear) are true.
-
State Machine: Model system behavior with states (Idle, Running, Paused, Error) and transitions (triggered by events/sensor values). Implement in code using
switch-caseor state pattern.
4.6 IoT Project Lifecycle & Best Practices (Lab Focus)
System Design & Prototyping
-
Define Requirements: What to measure? What to control? Constraints (power, cost, range)?
-
Select Components:
-
Sensor/Actuator: Compatibility (analog/digital, voltage), accuracy.
-
MCU/MPU: GPIO count, comms (Wi-Fi/BLE/LoRa), power, cost (NodeMCU vs. Pi vs. Arduino).
-
Comm Module/Platform: Range, bandwidth, cost (Wi-Fi vs. cellular vs. LoRaWAN).
-
-
Build POC: Breadboard first. Test each module (sensor reading, actuator control, network connectivity) independently.
Code Structure & Firmware Development
-
Modular Programming:
main.ino ├── sensors/ (temp_sensor.cpp, dht11.cpp) ├── actuators/ (relay.cpp, motor.cpp) ├── comms/ (mqtt_client.cpp, http_client.cpp) ├── utils/ (logger.cpp, config.cpp) └── logic/ (control_loop.cpp, state_machine.cpp) -
OTA Updates: Concept: Firmware stored in external flash (SPIFFS). Bootloader checks cloud for new version, downloads, validates, switches partition.
-
Robustness:
-
Error Handling: Check return values of all functions (network, sensor read). Implement retries with backoff.
-
Watchdog Timer (WDT): Reset MCU if code hangs (stops feeding the "dog").
-
Power Management: Use deep sleep modes (ESP32:
esp_sleep_enable_timer_wakeup()). Wake, sample, transmit, sleep.
-
Testing, Debugging & Documentation
-
Serial Debugging:
Serial.println()for state/error logs. Use multiple serial ports if available. -
Network Analysis: Wireshark with filters:
-
mqtt(for MQTT packets) -
http(for REST) -
coap(for CoAP)
-
-
Logging Strategies:
-
Local: Write to SD card (CSV format) or circular buffer in RAM.
-
Cloud: Send logs as messages to a dedicated MQTT topic or CloudWatch Logs.
-
-
Lab Project Journal (CRITICAL for Viva/Report): Maintain a bound notebook or digital doc with:
-
Circuit Diagrams (Fritzing or hand-drawn).
-
Code Snippets (key functions, config).
-
Configuration Details (broker URL, topic names, cloud credentials [redacted]).
-
Test Results (table of inputs vs. outputs, range tests).
-
Troubleshooting Log (problem, cause, solution).
-
-
Final Deliverables Structure:
-
Abstract/Objective
-
Block Diagram & Circuit Diagram
-
Methodology (Hardware/Software)
-
Implementation (Code highlights, cloud setup screenshots)
-
Results & Screenshots (Dashboard, serial monitor, packet capture)
-
Conclusion & Future Scope
-
Demo Video (2-3 min showing working system).
-
[!TIP] Exam Viva Strategy: Your project journal is your best friend. Be ready to explain any circuit connection, any line of code, and any troubleshooting step you documented. It shows systematic working.