Generating PDF…

Preparing…
← Back

Mini Project: Real-Time Temperature Monitoring System

Microcontrollers 1 & Programming 2

Multi-Sensor Web Dashboard with Containerization

Project Overview

Objective: Build a containerized web application that displays real-time temperature data from multiple sources in an interactive dashboard.

What You'll Build:

  • Arduino-based temperature sensing system with DHT11 and MF52A sensors
  • Flask web application with real-time plotting (frontend & WebSocket code provided)
  • Integration with external weather API for comparison
  • Dockerized application with proper serial port mapping

Skills Applied: Microcontroller programming, web development, API integration, containerization, and real-time data visualization

Step 1: Hardware Setup & Arduino Programming

Sensors You'll Use:

  • DHT11: Digital temperature & humidity sensor (Pin 2)
  • MF52A: Analog thermistor (Pin A0)

Reference Materials:

Your Task: Write Arduino code that reads both sensors and sends temperature data via Serial in a structured format (e.g., JSON or CSV)

💡 Tip: Use JSON, one reading per line: {"dht":25.5,"mf52":25.3}. Python can parse it with json.loads() (next slide).

Arduino Serial Communication

Recommended Serial Output Format:

Your Arduino should continuously output temperature readings in a parseable format. Here's an example:

💡 Pro Tips:

  • Use a delimiter that's easy to split (comma, pipe, or JSON)
  • Set Serial baud rate to 9600
  • Send readings every 2-3 seconds
void loop() {
  float dht_temp = dht.readTemperature();
  float mf52_temp = readMF52Temperature();
  
  // JSON format (recommended)
  Serial.print("{\"dht\":");
  Serial.print(dht_temp);
  Serial.print(",\"mf52\":");
  Serial.print(mf52_temp);
  Serial.println("}");
  
  delay(2000);
}

Step 2: Web Application Architecture

Technology Stack (what we use):

  • Backend: Python + Flask (you know this from Week 8 & 12)
  • Serial: PySerial reads the Arduino
  • Real-time push: Flask-SocketIO (WebSocket), given to you
  • Frontend: HTML + CSS + JavaScript + Chart.js, given to you

How data flows: every 2 seconds, Python reads the sensors, then pushes the numbers to every open browser. The browser draws them on the charts. No page refresh needed.

┌──────────┐  USB/Serial   ┌─────────────────────┐
│ Arduino  │ ────────────▶ │  Flask (app.py)     │
│ DHT11    │  {"dht":25.5, │                     │
│ MF52A    │   "mf52":25.3}│  read_arduino()  ✏️ │
└──────────┘               │  get_outdoor_temp()✏️│◀── Weather API
                           │                     │
                           │  broadcast_loop() 📋│
                           └─────────┬───────────┘
                                     │ WebSocket
                                     │ 'sensor_data'
                           ┌─────────▼───────────┐
                           │ Browser             │
                           │ index.html       📋 │
                           │ style.css        📋 │
                           │ dashboard.js     📋 │
                           │ (3 live charts)     │
                           └─────────────────────┘

What's Given vs. What You Build

WebSockets and JavaScript were not covered in class, so the whole frontend and the WebSocket "glue" are provided. You copy them, read the explanations, and focus on the parts you have learned.

File / PartStatus
templates/index.html📋 COPY AS-IS
static/style.css📋 COPY AS-IS
static/dashboard.js📋 COPY AS-IS
app.py: Flask + WebSocket setup, broadcast loop🧩 COPY + FILL IN TODOs
arduino/sensor_reader.ino✏️ YOU BUILD THIS
read_arduino(): serial reading + JSON parsing✏️ YOU BUILD THIS
get_outdoor_temp(): weather API + caching✏️ YOU BUILD THIS
requirements.txt, Dockerfile, docker-compose.yml, .env✏️ YOU BUILD THIS

💡 Grading focus: the hardware, the Python backend logic, error handling, and containerization. You are not expected to modify the JavaScript (but you may customise it if you want!).

Project Structure (Flask Layout)

Same layout as the Week 12 To-Do app: Flask looks for HTML in templates/ and for CSS/JS in static/. The folder names are not optional!

Setup:

mkdir temperature-monitor
cd temperature-monitor
python -m venv venv
# activate venv (see Week 12), then:
pip install flask flask-socketio simple-websocket pyserial requests
pip freeze > requirements.txt

💡 Tip: create all the empty files and folders first, then fill them in using the next slides.

temperature-monitor/
├── arduino/
│   └── sensor_reader.ino   ✏️ you write
├── templates/
│   └── index.html          📋 copy
├── static/
│   ├── style.css           📋 copy
│   └── dashboard.js        📋 copy
├── app.py                  🧩 copy + fill TODOs
├── requirements.txt        ✏️ you create
├── .env                    ✏️ you create (never commit!)
├── Dockerfile              ✏️ you write
└── docker-compose.yml      ✏️ you write
✏️ YOU BUILD THIS

Step 1b: Reading Serial Data in Python

Using PySerial Library:

Install with: pip install pyserial

💡 Important Tips:

  • Use auto-detection to find Arduino automatically
  • Ports usually: /dev/ttyUSB0, /dev/ttyACM0 (Linux/Mac) or COM3, COM4 (Windows)
  • Always handle connection errors gracefully
  • Wrap json.loads() in try/except: the first line after connecting is often half a line!
  • This becomes your read_arduino() function in app.py
import serial
import serial.tools.list_ports
import json

def find_arduino_port():
    """Auto-detect Arduino port"""
    ports = serial.tools.list_ports.comports()
    for port in ports:
        # Look for Arduino in description
        if 'Arduino' in port.description or \
           'USB' in port.description:
            return port.device
    return None

# Auto-detect or use environment variable
port = find_arduino_port() or '/dev/ttyUSB0'
ser = serial.Serial(port, 9600, timeout=1)

def read_arduino_data():
    if ser.in_waiting > 0:
        line = ser.readline().decode('utf-8').strip()
        data = json.loads(line)
        return {'dht': data['dht'], 'mf52': data['mf52']}
    return None
✏️ YOU BUILD THIS

Step 3: Integrating Weather API

Reference Your Previous Learning:

Refer back to your weather API slides for details on API keys, endpoints, and data parsing.

Your Task:

  • Make periodic API calls to get outdoor temperature (every 5-10 minutes is sufficient)
  • Cache the results to avoid excessive API calls
  • Handle API errors (network issues, rate limits)
  • This becomes your get_outdoor_temp() function in app.py; return a float or None

💡 Best Practices:

  • Don't call the API every second - weather doesn't change that fast!
  • Store your API key in environment variables (never hardcode it)
  • Simple caching idea: store last_value and last_time; only call the API again if time.time() - last_time > 600

Step 4: WebSockets in One Slide

Normal HTTP (what you know): the browser asks, the server answers, the connection closes. To get new data the browser has to ask again and again.

WebSocket: the browser opens a connection once and keeps it open. Now the server can push new data whenever it wants. Perfect for live sensor readings!

Socket.IO is a library that makes WebSockets easy. It works with named events:

  • Python sends: socketio.emit('sensor_data', {...})
  • JavaScript receives: socket.on('sensor_data', (data) => {...})
  • The event name must be exactly the same on both sides

💡 That's all you need to understand. The code that does this is provided on the next slides.

HTTP (request / response)
  Browser ── "give me data?" ──▶ Server
  Browser ◀──── "25.5" ──────── Server
  (connection closed, ask again...)

WebSocket (always open)
  Browser ════ open once ═════▶ Server
  Browser ◀── sensor_data ───── Server
  Browser ◀── sensor_data ───── Server
  Browser ◀── sensor_data ───── Server
           (every 2 seconds)

The Data Contract ⚠️

The provided frontend expects your backend to send an event called sensor_data containing a dictionary with exactly these keys:

KeyTypeMeaning
dhtfloat or NoneDHT11 temperature (°C)
mf52float or NoneMF52A temperature (°C)
outdoorfloat or NoneTemperature from the weather API (°C)
timestringTimestamp shown on the x-axis

If a value is None, the chart simply skips that point and shows --.

💡 Good news: the provided broadcast_loop() in app.py already builds this dictionary. Your functions just have to return the right numbers.

# Python side (already in app.py)
socketio.emit("sensor_data", {
    "dht": 25.5,
    "mf52": 25.3,
    "outdoor": 18.2,
    "time": "14:05:32",
})

# JavaScript side (already in dashboard.js)
# socket.on('sensor_data', (data) => {
#     data.dht      -> 25.5
#     data.mf52     -> 25.3
#     data.outdoor  -> 18.2
#     data.time     -> "14:05:32"
# })
📋 COPY AS-IS

Frontend File 1: templates/index.html

The page skeleton: a header, three panels, and the scripts.

  • Each panel has a big number (id="dhtValue") and a <canvas> where Chart.js draws the chart
  • {{ url_for('static', ...) }} is Jinja2 (Week 12): it builds the link to files in static/
  • Two libraries are loaded from the internet: Chart.js (charts) and Socket.IO (WebSocket)
  • dashboard.js is loaded last, so the page and libraries exist before it runs

💡 The id values must match the ones used in dashboard.js. Don't rename them.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Temperature Monitor</title>
  <!-- url_for() finds the file inside the static/ folder -->
  <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
  <header>
    <h1>🌡️ Real-Time Temperature Monitor</h1>
    <span id="status" class="status">● Disconnected</span>
  </header>

  <main class="grid">
    <!-- Panel 1: DHT11 -->
    <section class="panel">
      <h2>DHT11 Sensor</h2>
      <div class="value" id="dhtValue">--</div>
      <div class="chart-box"><canvas id="dhtChart"></canvas></div>
    </section>

    <!-- Panel 2: MF52A -->
    <section class="panel">
      <h2>MF52A Thermistor</h2>
      <div class="value" id="mf52Value">--</div>
      <div class="chart-box"><canvas id="mf52Chart"></canvas></div>
    </section>

    <!-- Panel 3: Outdoor (Weather API) -->
    <section class="panel">
      <h2>Outdoor (Weather API)</h2>
      <div class="value" id="outdoorValue">--</div>
      <div class="chart-box"><canvas id="outdoorChart"></canvas></div>
    </section>
  </main>

  <footer>Last update: <span id="lastUpdate">--</span></footer>

  <!-- Libraries (loaded from the internet) -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
  <script src="https://cdn.socket.io/4.7.5/socket.io.min.js"></script>
  <!-- Our dashboard code (must be loaded LAST) -->
  <script src="{{ url_for('static', filename='dashboard.js') }}"></script>
</body>
</html>
📋 COPY AS-IS

Frontend File 2: static/style.css

Makes the dashboard look nice. Nothing here affects how the data works.

  • .grid uses CSS Grid: the 3 panels sit side by side, and wrap on a small screen
  • .chart-box gives each chart a fixed height (Chart.js needs this)
  • .status.connected turns the status text green when the WebSocket connects

🎨 Optional: this is the safest file to personalise: change colours, fonts, sizes.

/* style.css: dashboard look & feel (provided) */
body {
  margin: 0;
  font-family: "Segoe UI", Roboto, Arial, sans-serif;
  background: #f1f4f9;
  color: #2d3436;
}

header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 32px;
  background: #2d3436;
  color: white;
}
header h1 { margin: 0; font-size: 1.5rem; }

.status { font-weight: bold; color: #ff7675; }   /* red  */
.status.connected { color: #55efc4; }            /* green */

/* 3 panels side by side; they wrap on small screens */
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  gap: 20px;
  padding: 24px 32px;
}

.panel {
  background: white;
  border-radius: 12px;
  padding: 16px 20px;
  box-shadow: 0 4px 14px rgba(0, 0, 0, 0.08);
}
.panel h2 { margin: 0 0 4px; font-size: 1.1rem; color: #636e72; }

.value { font-size: 2.4rem; font-weight: bold; margin-bottom: 8px; }

.chart-box { position: relative; height: 260px; }

footer { text-align: center; color: #636e72; padding-bottom: 24px; }
📋 COPY AS-IS

Frontend File 3: static/dashboard.js

The "brain" of the page. It has 4 parts (explained on the next slide):

  1. Create the three charts
  2. Helper functions to add a point and show a value
  3. Connect to the server via WebSocket
  4. Receive sensor_data and update everything

💡 Scroll inside the code box to see the whole file, or just press Copy.

// dashboard.js: PROVIDED CODE. Copy it as-is.
// It connects to your Flask server with a WebSocket (Socket.IO)
// and draws the incoming temperatures on three Chart.js charts.

const MAX_POINTS = 50;   // keep only the last 50 readings per chart

// ---------- 1. Create the three charts ----------
function createChart(canvasId, label, color) {
  return new Chart(document.getElementById(canvasId), {
    type: 'line',
    data: {
      labels: [],                       // x-axis: time stamps
      datasets: [{
        label: label,
        data: [],                       // y-axis: temperatures
        borderColor: color,
        backgroundColor: color + '33',  // same colour, transparent
        fill: true,
        tension: 0.3,
        pointRadius: 2
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      animation: false,
      scales: {
        x: { title: { display: true, text: 'Time' } },
        y: { title: { display: true, text: 'Temperature (°C)' } }
      }
    }
  });
}

const dhtChart     = createChart('dhtChart',     'DHT11',   '#e17055');
const mf52Chart    = createChart('mf52Chart',    'MF52A',   '#0984e3');
const outdoorChart = createChart('outdoorChart', 'Outdoor', '#00b894');

// ---------- 2. Helper functions ----------
function addPoint(chart, time, value) {
  if (value === null || value === undefined) return;  // skip missing data
  chart.data.labels.push(time);
  chart.data.datasets[0].data.push(value);
  if (chart.data.labels.length > MAX_POINTS) {        // sliding window
    chart.data.labels.shift();
    chart.data.datasets[0].data.shift();
  }
  chart.update();
}

function showValue(elementId, value) {
  const el = document.getElementById(elementId);
  el.textContent = (value === null || value === undefined)
    ? '--'
    : Number(value).toFixed(1) + ' °C';
}

// ---------- 3. Connect to the server (WebSocket) ----------
const socket = io();   // connects to the same server that served this page
const statusEl = document.getElementById('status');

socket.on('connect', () => {
  statusEl.textContent = '● Connected';
  statusEl.classList.add('connected');
});

socket.on('disconnect', () => {
  statusEl.textContent = '● Disconnected';
  statusEl.classList.remove('connected');
});

// ---------- 4. Receive data from the server ----------
// Python sends: socketio.emit('sensor_data', {...})
// data = { dht: 25.5, mf52: 25.3, outdoor: 18.2, time: '14:05:32' }
socket.on('sensor_data', (data) => {
  const time = data.time || new Date().toLocaleTimeString();

  addPoint(dhtChart, time, data.dht);
  showValue('dhtValue', data.dht);

  addPoint(mf52Chart, time, data.mf52);
  showValue('mf52Value', data.mf52);

  addPoint(outdoorChart, time, data.outdoor);
  showValue('outdoorValue', data.outdoor);

  document.getElementById('lastUpdate').textContent = time;
});

How dashboard.js Works

JavaScript ↔ Python cheat-sheet (to help you read it):

JavaScriptPython equivalent
const x = 5;x = 5
function addPoint(chart, t, v) { ... }def add_point(chart, t, v):
arr.push(v) / arr.shift()lst.append(v) / lst.pop(0)
data.dhtdata["dht"]
nullNone
(data) => { ... }lambda data: ... (a small function)
console.log(x)print(x) (see it with F12 → Console)

The key idea: socket.on('sensor_data', ...) is like a Flask route, but instead of the browser asking, the function runs every time Python emits that event.

// Part 1: one function creates any chart
const dhtChart = createChart('dhtChart', 'DHT11', '#e17055');

// Part 2: sliding window, keep last 50 points
chart.data.labels.push(time);
if (chart.data.labels.length > MAX_POINTS) {
  chart.data.labels.shift();   // drop the oldest
}

// Part 3: connect (to the server that served the page)
const socket = io();
socket.on('connect', () => { /* show "Connected" */ });

// Part 4: runs every time Python does
//   socketio.emit("sensor_data", {...})
socket.on('sensor_data', (data) => {
  addPoint(dhtChart, data.time, data.dht);
  showValue('dhtValue', data.dht);
  // ... same for mf52 and outdoor
});
🧩 COPY + FILL IN TODOs

Backend: app.py Starter

Copy this file. The Flask + WebSocket parts are done for you. You only fill in the two functions marked TODO:

  • read_arduino(): return (dht, mf52) using your PySerial code (Step 1b)
  • get_outdoor_temp(): return the outdoor temperature using your weather API code (Step 3)

What the provided part does:

  • SocketIO(app) adds WebSocket support to Flask
  • broadcast_loop() runs in the background, calls your two functions every 2 s and emits sensor_data
  • socketio.run(...) replaces app.run(...); host="0.0.0.0" is needed for Docker

💡 You may move your functions to serial_reader.py / weather_api.py and import them. Good structure earns marks!

# app.py: Temperature Monitor backend
import os
import time
from flask import Flask, render_template
from flask_socketio import SocketIO

app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*")      # PROVIDED

SERIAL_PORT = os.getenv("SERIAL_PORT", "/dev/ttyUSB0")
WEATHER_API_KEY = os.getenv("WEATHER_API_KEY")


# ===================== YOUR CODE =====================
def read_arduino():
    """TODO (Step 1): read ONE line from the serial port,
    parse the JSON and return (dht, mf52) as floats.
    Return (None, None) if there is no valid reading."""
    return None, None


def get_outdoor_temp():
    """TODO (Step 3): return the outdoor temperature (float)
    from the weather API. Cache it: only call the API every
    5-10 minutes! Return None if the API fails."""
    return None
# =====================================================


# ============ PROVIDED: WebSocket broadcast ==========
def broadcast_loop():
    """Runs forever in the background. Every 2 seconds it
    pushes the latest readings to every open browser."""
    while True:
        dht, mf52 = read_arduino()
        outdoor = get_outdoor_temp()

        if dht is not None or mf52 is not None:
            socketio.emit("sensor_data", {
                "dht": dht,
                "mf52": mf52,
                "outdoor": outdoor,
                "time": time.strftime("%H:%M:%S"),
            })
        socketio.sleep(2)


@app.route("/")
def index():
    return render_template("index.html")


@socketio.on("connect")
def on_connect():
    print("Browser connected")


if __name__ == "__main__":
    socketio.start_background_task(broadcast_loop)
    socketio.run(app, host="0.0.0.0", port=8000,
                 allow_unsafe_werkzeug=True)

Test the Dashboard First (Fake Data) 🧪

Before touching the Arduino, check that the copied frontend works. Temporarily make your functions return random numbers:

Then:

  1. Run python app.py
  2. Open http://localhost:8000
  3. Status should turn ● Connected and all 3 charts should move every 2 s

Not working?

  • Press F12 → Console to see JavaScript errors
  • TemplateNotFound: check the templates/ folder name
  • Page has no style / charts: check the static/ folder and file names
  • Charts frozen: check the terminal running Python for errors

✅ Once this works, replace the fake data with your real serial + API code.

import random

def read_arduino():
    # FAKE DATA - for testing only!
    dht = round(random.uniform(20, 30), 1)
    mf52 = round(random.uniform(20, 30), 1)
    return dht, mf52

def get_outdoor_temp():
    # FAKE DATA - for testing only!
    return 18.2

Step 5: Containerizing Your Application

Why Containerize?

  • Ensures application runs the same on any machine
  • Easy deployment and sharing
  • Includes all dependencies in one package

Prerequisites:

  • Install Docker Desktop on your machine
  • Ensure your application runs successfully outside Docker first

💡 Development Tip: Always test your app locally before containerizing. Debug Docker issues separately from application bugs!

Creating Your Dockerfile

Basic Dockerfile Structure:

This example is for a Python Flask application

💡 Key Points:

  • Start with appropriate base image
  • Install dependencies first (better caching)
  • Copy your application code
  • Expose necessary ports
  • Add a .dockerignore with venv/ and .env so they are not copied
FROM python:3.10-slim

WORKDIR /app

# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy application code
# (app.py, templates/, static/)
COPY . .

# Expose port
EXPOSE 8000

# Run the application
CMD ["python", "app.py"]

🔴 Critical: Mapping Serial Ports to Docker

The Challenge: Docker containers are isolated from your host's hardware. You must explicitly give the container access to the serial port.

Step 1: Find Your Arduino Port

  • Linux/Mac: ls /dev/tty* or ls /dev/cu.*
  • Windows: Check Device Manager (usually COM3, COM4, etc.)

Step 2: Add Device Mapping to Docker Command

Use the --device flag to map the serial port:

docker run --device=/dev/ttyUSB0:/dev/ttyUSB0 your-image

💡 Important: The port path inside the container (after the colon) should match what your code expects!

Using Docker Compose (Recommended)

Docker Compose makes running containers easier:

Key Configuration:

  • devices: Map the serial port
  • privileged: May be needed for serial access (use cautiously)
  • ports: Expose web application port

Run with: docker-compose up

version: '3.8'

services:
  temp-monitor:
    build: .
    ports:
      - "8000:8000"
    devices:
      - "/dev/ttyUSB0:/dev/ttyUSB0"
    environment:
      - SERIAL_PORT=/dev/ttyUSB0
      - WEATHER_API_KEY=${WEATHER_API_KEY}
    # Optional: if serial access issues persist
    # privileged: true

Troubleshooting Serial Port Access in Docker

Common Issues & Solutions:

Problem 1: Permission Denied

  • Linux Solution: Add your user to dialout group: sudo usermod -a -G dialout $USER
  • Then logout/login or restart

Problem 2: Port Not Found

  • Verify Arduino is connected: ls -l /dev/ttyUSB*
  • Check cable connections
  • Ensure no other program is using the port (close Arduino IDE)

Problem 3: Port Name Changes

  • Use environment variables for port names
  • Create udev rules for persistent names (advanced)

💡 Debug Tip: Test serial communication outside Docker first, then troubleshoot Docker-specific issues

Building and Testing Your Container

Build Process:

💡 Testing Checklist:

  • ✓ Serial communication working
  • ✓ Weather API calls successful
  • ✓ Dashboard status shows "● Connected"
  • ✓ All three charts updating
  • ✓ Application accessible from browser
# Build the Docker image
docker build -t temp-monitor .

# Run with serial port mapping
docker run -p 8000:8000 \
  --device=/dev/ttyUSB0:/dev/ttyUSB0 \
  -e WEATHER_API_KEY=your_key_here \
  temp-monitor

# Or use docker-compose
docker-compose up

# Access in browser
# http://localhost:8000

Managing Configuration with Environment Variables

Never hardcode sensitive information!

Create a .env file:

💡 Security Tips:

  • Add .env to .gitignore
  • Provide .env.example for others
  • Document required variables in README
# .env file (don't commit this!)
WEATHER_API_KEY=abc123xyz789
SERIAL_PORT=/dev/ttyUSB0
BAUD_RATE=9600

# .env.example (commit this)
WEATHER_API_KEY=your_api_key_here
SERIAL_PORT=/dev/ttyUSB0
BAUD_RATE=9600

# Access in Python
import os
api_key = os.getenv('WEATHER_API_KEY')

Final Integration Checklist

Before Submission, Verify:

✓ Hardware Layer:

  • Both sensors reading correctly on Arduino
  • Serial output properly formatted and consistent

✓ Software Layer:

  • Backend successfully reads serial data
  • Weather API integration working with error handling
  • Dashboard shows "● Connected" and live data arrives every ~2 s
  • All three panels displaying and updating correctly

✓ Containerization:

  • Dockerfile builds without errors
  • Serial port correctly mapped
  • Application runs in container
  • Documentation includes how to run the container

Common Pitfalls to Avoid

🚫 Don't Do This:

  • Hardcoding paths/ports: Use environment variables or configuration files
  • Calling Weather API too frequently: Cache results for 5-10 minutes
  • Ignoring error handling: Network failures, sensor errors, and serial disconnections WILL happen
  • Renaming things in the contract: the event name sensor_data and keys dht, mf52, outdoor, time must match the provided JavaScript
  • Wrong folder names: Flask needs exactly templates/ and static/
  • Using app.run(): with WebSockets you must start the server with socketio.run()
  • Committing API keys: Always use .env files and add them to .gitignore
  • Testing only in Docker: Debug locally first, then containerize
  • Not closing serial connections: This can prevent reconnection

✅ Do This Instead: Plan your architecture, test incrementally, handle errors gracefully, document as you go!