Day 1 of 5
⏱ ~60 minutes
IoT in 5 Days — Day 1

IoT Architecture

IoT is not a technology — it's a layered system connecting physical sensors to cloud intelligence. Today you'll understand every layer and why each exists.

The IoT Stack

From bottom to top: Perception layer — sensors (temperature, motion, pressure) and actuators (relays, motors). Network layer — WiFi, BLE, LoRa, Zigbee, cellular carry data to gateways. Edge/Gateway layer — Raspberry Pi, industrial gateways aggregate and pre-process. Platform layer — MQTT brokers, time-series databases, stream processors. Application layer — dashboards, mobile apps, ML inference, alerting.

Edge vs Cloud

Process at the edge when: latency matters (local decisions must happen in milliseconds), bandwidth is limited (sending raw video from 100 cameras is expensive), privacy is required (medical data shouldn't leave the facility), or the internet connection is unreliable. Send to the cloud when: you need historical analysis across devices, ML training requires aggregated data, firmware updates must reach all devices simultaneously.

Protocols Overview

MQTT: pub/sub, TCP, 2-byte overhead, best for low-power devices. HTTP/REST: request/response, familiar, high overhead, good for infrequent data. CoAP: like HTTP but UDP-based, designed for constrained devices. WebSocket: bidirectional, real-time, browser-friendly. LoRaWAN: long range (10km+), low bandwidth (250 bytes/s), very low power — ideal for remote sensors.

python
# IoT architecture simulation in Python
# Models the message flow from sensor to cloud

import json, time, random
from datetime import datetime

class Sensor:
    # Simulates a temperature/humidity sensor
    def __init__(self, device_id, location):
        self.id = device_id
        self.location = location
        self._base_temp = 22.0
    
    def read(self):
        # Simulate realistic sensor drift
        temp = self._base_temp + random.gauss(0, 0.5)
        humidity = 45 + random.gauss(0, 3)
        return {"temp": round(temp, 1), "humidity": round(humidity, 1)}

class EdgeGateway:
    # Pre-processes and filters sensor data
    def __init__(self, max_rate_hz=1):
        self.min_interval = 1.0 / max_rate_hz
        self.last_sent = {}
        self.dropped = 0
    
    def process(self, device_id, payload):
        now = time.time()
        last = self.last_sent.get(device_id, 0)
        
        if now - last < self.min_interval:
            self.dropped += 1
            return None  # rate limit
        
        self.last_sent[device_id] = now
        
        # Add metadata, validate
        payload['device_id'] = device_id
        payload['ts'] = datetime.utcnow().isoformat()
        payload['gateway'] = 'edge-01'
        
        # Anomaly detection at the edge
        if payload['temp'] > 35:
            payload['alert'] = 'HIGH_TEMP'
        
        return payload

class CloudPlatform:
    # Receives, stores, and acts on sensor data
    def __init__(self):
        self.store = []
        self.alerts_sent = 0
    
    def ingest(self, payload):
        self.store.append(payload)
        if payload.get('alert'):
            self.alerts_sent += 1
            print(f"  ALERT: {payload['device_id']} - {payload['alert']}")
    
    def latest_by_device(self):
        seen = {}
        for p in reversed(self.store):
            if p['device_id'] not in seen:
                seen[p['device_id']] = p
        return seen

# Run simulation
sensors = [Sensor(f"sensor-{i:02d}", f"room-{i}") for i in range(3)]
gateway = EdgeGateway(max_rate_hz=0.5)  # max 1 msg per 2 seconds
cloud   = CloudPlatform()

print("Simulating IoT pipeline for 10 events...")
for _ in range(10):
    for s in sensors:
        raw = s.read()
        processed = gateway.process(s.id, raw)
        if processed:
            cloud.ingest(processed)
            print(f"  {processed['device_id']}: {processed['temp']}°C")
    time.sleep(0.3)

print(f"
Cloud: {len(cloud.store)} msgs stored, {cloud.alerts_sent} alerts")
print(f"Gateway: {gateway.dropped} messages dropped (rate limited)")
💡
Edge processing is not a replacement for cloud — it's a complement. The rule of thumb: react at the edge, analyze in the cloud. Local decisions (turn off a valve if pressure exceeds 100 PSI) must be immediate. Trend analysis (is pressure increasing over 30 days?) needs historical cloud data.
📝 Day 1 Exercise
Map an IoT Architecture
  1. Pick a real IoT application: smart home, industrial monitoring, agriculture, or fleet tracking.
  2. Draw the full stack: sensors → connectivity → gateway → platform → application. Label the protocol at each layer.
  3. Run the simulation script. Modify it to simulate 10 sensors instead of 3. What happens to message volume?
  4. Calculate bandwidth: 10 sensors, 1 reading/minute, 200 bytes/reading. How much data per day? Per year?
  5. Research AWS IoT Core pricing. How much would it cost to run 1000 sensors sending 1 message/minute for a year?

Day 1 Summary

  • IoT is a 5-layer stack: perception → network → edge → platform → application
  • Process at edge for latency/privacy/bandwidth; aggregate in cloud for analysis and ML
  • MQTT is the dominant IoT protocol: lightweight, pub/sub, QoS levels, works on 2G networks
  • Rate limiting at the gateway prevents cloud cost explosions from noisy sensors
Challenge

Research LoRaWAN. A LoRa sensor can transmit 250 bytes every 15 minutes with a 3V battery lasting 2+ years. Design a soil moisture monitoring network for a 100-acre farm: how many sensors, what gateway coverage, what cloud platform? Calculate battery life, cost, and data volume. Write a 1-page architecture document.

Finished this lesson?