Interface and Application Programming

This week focuses on writing an application that interfaces with an input or output device. For my project, I built two applications: a local web-based monitoring dashboard that reads live sensor data and streams video, and a cloud-connected MQTT agent that lets users control the hive remotely through a web dashboard. Both interface with the custom board I designed in Week 9 (Input Devices) — all running on the Raspberry Pi 5.

Assignment Requirements

Group Assignment:

Individual Assignment:

Project Documentation

Overview

For this week, I wrote a web application that interfaces with the custom sensor extension board I designed and milled in Week 9. The board is a pass-through PCB with STEMMA QT connectors that extends the I²C cable reach from the Adafruit PCA9548 multiplexer to the SHT45 sensors placed in each hive box. The multiplexer is a separate off-the-shelf Adafruit board — my custom board extends the wiring distance so the sensors can reach all three boxes. The web app reads live data from these sensors and also streams video from the two Pi Camera Module 3 Wide units — giving me a complete monitoring interface for the beehive.

The Custom Board

The board I'm interfacing with is the sensor extension board I designed in Week 9. It's a pass-through PCB with two female STEMMA QT connectors that extends the I²C cable reach from the multiplexer to the SHT45 sensors placed in each hive box. The board carries VCC, GND, SDA, and SCL — allowing the Pi to communicate with the sensors over longer distances than the stock 300mm Adafruit cables allow.

The full signal chain: Pi 5 → PCA9548 Multiplexer → STEMMA QT cable → Extension Board → STEMMA QT cable → SHT45 sensor

The Application — Web Dashboard

The monitoring website is a Python-based web server running on the Pi that serves:

  • Live camera feeds — dual MJPEG streams from both entrance cameras (Camera 0 and Camera 1)
  • Real-time sensor data — temperature and humidity readings from all 3 SHT45 sensors, updated every 2 seconds
  • Snapshot endpoints — single JPEG frames from either camera on demand
  • JSON API — sensor data available as JSON at /sensors for integration with other tools or logging

How It Works

The server runs on port 8080 and combines the camera streaming (from Week 11) with sensor reading into one unified dashboard:

  1. Sensor reading: A background thread selects each multiplexer channel (0, 1, 2) in sequence, reads the SHT45 on that channel, and stores the latest temperature/humidity values in memory.
  2. Camera streaming: Two rpicam-vid processes stream MJPEG from each CSI camera port. The web server proxies these streams to the browser.
  3. Web frontend: An HTML page displays both camera feeds as <img> tags pointing to the MJPEG endpoints, plus a JavaScript section that polls /sensors every 2 seconds and updates the displayed temperature/humidity values.

Endpoints

Path Description
/Dashboard — cameras + live sensor readings
/snap0Camera 0 single JPEG snapshot
/snap1Camera 1 single JPEG snapshot
/sensorsJSON array: [{"temp": 34.2, "hum": 62.1}, ...]

Technologies Used

  • Python — server-side application logic, sensor reading, camera control
  • HTTP server — Python's built-in http.server module (no external frameworks needed)
  • MJPEG streamingmultipart/x-mixed-replace content type for live video in the browser
  • I²C communication — reading SHT45 sensors through the PCA9548 multiplexer via Linux i2c-dev
  • HTML/CSS/JavaScript — frontend dashboard with live-updating sensor values
  • JSON API — structured data endpoint for sensor readings

How This Meets the Assignment

Requirement How It's Met
Write an application Python web server with HTML/JS frontend dashboard
Interfaces a user with a device User views live sensor data and camera feeds through a web browser
Input device you made Custom sensor extension board (Week 9) connecting SHT45 sensors via I²C multiplexer

Overview

Beyond the local web dashboard, I also wrote the application layer that interfaces the Pi with the cloud backend. This is the hive-monitor-agent — a Python application running on the Pi that publishes sensor data, receives commands, and manages device state through MQTT and REST APIs. Full networking protocol details are on the Week 11 — Networking and Communications page; this section focuses on the application code that interfaces the user (via the cloud dashboard) with the input/output devices on the Pi.

What the Application Does

The agent application is the bridge between the physical devices (sensors, cameras, servo, LEDs) and the user's cloud dashboard. It:

  • Reads sensors — polls SHT45 temperature/humidity sensors every 60 seconds via I²C multiplexer, formats readings into structured JSON
  • Publishes telemetry — sends sensor data, weight, door state, fan state, and GPS coordinates to AWS IoT Core over MQTT
  • Receives commands — subscribes to MQTT topics for door open/close, LED control, and camera start/stop
  • Manages device shadow — reports current device state and receives desired-state deltas from the cloud (config changes, metadata updates)
  • Buffers offline — queues publishes in a local SQLite database when the network is down, replays them on reconnect

Application Architecture

┌─────────────────────────────────────────────────────┐
│              hive-monitor-agent (Python)             │
├─────────────────────────────────────────────────────┤
│                                                     │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────┐  │
│  │ Driver       │  │ Telemetry    │  │ Command  │  │
│  │ Scheduler    │  │ Publisher    │  │ Handler  │  │
│  │              │  │              │  │          │  │
│  │ • SHT45 read │  │ • 60s cycle  │  │ • door   │  │
│  │ • HX711 read │  │ • JSON fmt   │  │ • LED    │  │
│  │ • door state │  │ • QoS 1      │  │ • camera │  │
│  └──────┬───────┘  └──────┬───────┘  └────┬─────┘  │
│         │                  │               │        │
│  ┌──────▼──────────────────▼───────────────▼─────┐  │
│  │           MQTT Client (paho-mqtt)             │  │
│  │  • mTLS with X.509 cert                      │  │
│  │  • Auto-reconnect with exponential backoff    │  │
│  │  • LWT for disconnect detection              │  │
│  └──────────────────────┬────────────────────────┘  │
│                         │                           │
│  ┌──────────────────────▼────────────────────────┐  │
│  │         Offline Buffer (SQLite)               │  │
│  │  • /var/lib/hive-monitor/buffer.db            │  │
│  │  • 7-day / 500 MB FIFO cap                   │  │
│  │  • Replay at ≤50 msg/s on reconnect          │  │
│  └───────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────┘
         │
         │ TCP 8883 (MQTT over mTLS)
         ▼
   AWS IoT Core → Cloud Dashboard (user interface)

Key Interfaces

1. REST API — Bootstrap & Binding

Before the MQTT connection is established, the Pi uses a REST API client to bootstrap itself:

Endpoint Method Purpose
/devices/{serial}/bind-packetGETPoll for device credentials (cert, key, config)
/hives/bindPOSTManual bind with one-time token

The bootstrap application handles HTTP response codes intelligently: 404 means "keep polling" (device not claimed yet), 200 means install the bind packet, anything else triggers exponential backoff (10s → 300s cap).

2. MQTT — Telemetry Publishing

The main application interface is MQTT publish/subscribe. The agent formats sensor readings into JSON and publishes to topic-scoped channels:

// Example telemetry payload published every 60s
{
  "timestamp": "2026-05-18T14:30:00Z",
  "seq": 4521,
  "sensors": {
    "brood_box": {"temp_c": 34.8, "humidity_pct": 62.1},
    "super_1":   {"temp_c": 31.2, "humidity_pct": 58.4},
    "ambient":   {"temp_c": 22.5, "humidity_pct": 45.0}
  },
  "weight_kg": 38.7,
  "door_state": "open",
  "fan_state": "auto",
  "fan_rpm": 3200,
  "led_state": "off",
  "gps": {"lat": 35.227, "lon": -80.843}
}
3. MQTT — Command Handling

The application subscribes to downlink topics and executes commands on the physical devices:

  • .../door/command → drives the servo to open/close the entrance gate
  • .../led/command → toggles LED boards via GPIO MOSFETs
  • .../camera/{channel}/control → starts/stops camera streaming sessions

Each command includes a request_id for idempotent deduplication — if the same command arrives twice (network retry), the application only executes it once.

4. Device Shadow — State Synchronization

The AWS IoT Device Shadow provides a persistent state store that syncs between the Pi and the cloud dashboard:

  • Reported state — the Pi publishes what it's currently doing (sensor readings, door position, config version)
  • Desired state — the cloud dashboard sets what it wants (new sampling rate, updated sensor config, metadata changes)
  • Delta — when desired ≠ reported, the Pi receives a delta and applies the change

This means a user can change the hive's sampling interval from the web dashboard, and the Pi picks it up automatically — even if it was offline when the change was made.

Technologies Used

  • Python — application logic, sensor drivers, MQTT client
  • paho-mqtt — MQTT 5 client library with mTLS support
  • HTTPS (urllib/requests) — REST API client for bootstrap and binding
  • SQLite — offline message buffer with FIFO eviction
  • JSON — structured data format for all API payloads
  • X.509 certificates — mutual TLS authentication
  • systemd — service management, auto-restart, conditional startup

Repository Structure — Smart-Beehive

The application code lives in the hive-monitor repository. Key directories:

hive-monitor/
├── pi/
│   ├── agent/                  # hive-monitor-agent — main application
│   │   ├── drivers/            # Sensor drivers (SHT45, HX711, camera)
│   │   ├── mqtt_client.py      # MQTT connection, pub/sub, reconnect logic
│   │   ├── telemetry.py        # Telemetry publisher (60s cycle)
│   │   ├── command_handler.py  # Downlink command execution (door, LED, camera)
│   │   ├── shadow_client.py    # AWS IoT Device Shadow sync
│   │   └── offline_buffer.py   # SQLite FIFO buffer for network outages
│   ├── installer/
│   │   └── bind.sh             # Device binding script (manual path)
│   ├── bootstrap/
│   │   └── bootstrap.py        # Fleet bootstrap polling service
│   └── image/                  # Pi OS image build scripts
├── docs/                       # Architecture docs, manual bind guide
└── .github/workflows/          # CI — image builds, linting

The agent is structured as a set of cooperating services managed by systemd. Each driver (sensor, camera, servo) runs independently and publishes to shared state that the telemetry publisher picks up on its 60-second cycle.

How This Meets the Assignment

Requirement How It's Met
Write an application Python MQTT agent + REST API client running as a systemd service
Interfaces a user with a device User controls door/LEDs and views sensor data through cloud dashboard, which communicates with the Pi via MQTT
Input device you made Custom sensor extension board (Week 9) — SHT45 readings published as telemetry
Output device you made Custom LED PCBs (Week 10) — controlled via MQTT commands from the dashboard

See Week 11 — Networking and Communications for the full protocol specification (MQTT topics, auth model, firewall rules, offline behavior).

Overview — Why I Built This

I built a full cloud-hosted web application at hive-monitor.com because I want to turn this into a real product. The key differentiator is the live camera view — other DIY hive monitors exist as hobby projects with basic sensor logging, but none of them offer a consumer-ready package with live video streaming from inside the hive entrance. That's the part that doesn't exist on the market right now. Being able to watch your bees come and go in real time from your phone, combined with environmental data, is what makes this more than just another temperature logger.

The Pi 5 I'm using is likely overkill for production (an 8GB Pi 5 at $80 is expensive for a consumer device), and some of the other components could be cheaper alternatives. Bringing the per-unit cost down to something a hobbyist beekeeper would pay is a major challenge I haven't solved yet. But for the proof of concept, I prioritized getting everything working reliably first.

The Web Application — What It Does Today

The dashboard is a full-stack web application hosted on AWS with a custom domain (hive-monitor.com) registered through Route 53. It's currently live and reporting real data from my Pi. Here's what's working:

  • Live sensor reporting — all 3 SHT45 temperature/humidity sensors report in real time to the dashboard
  • CPU temperature monitoring — the Pi's CPU temp is tracked and displayed, which is important because the Pi 5 runs hot (especially with dual cameras) and thermal throttling would degrade performance
  • Multi-hive support — the system is designed for multiple hives from the start. You can add hives, give them names, and set their GPS locations
  • Hive sharing — users can share access to their hives with other users (useful for beekeeping clubs or commercial operations with multiple managers)
  • Map view — hives are displayed on a map with their GPS coordinates. You can change names and locations from the dashboard
  • User authentication — full sign-up/login system so each beekeeper has their own account and hives

What I'm Still Working On

  • UI aesthetics — the frontend works but needs design polish. It's functional, not pretty yet.
  • Camera feed integration — live video streaming to the web dashboard (currently works locally, need to pipe it through the cloud)
  • Historical data graphs — time-series charts for temperature, humidity, and weight trends
  • Alert system — notifications when sensors go out of range or the hive loses connection
  • Cost optimization — finding cheaper hardware alternatives for a consumer price point

How the Binding System Works

When a new Pi is flashed with the hive-monitor image and powered on, it needs to be "bound" to a specific hive in the dashboard. This is the zero-touch provisioning flow:

  1. Operator creates a hive in the web dashboard — gives it a name, location, and notes
  2. Pi boots up and starts polling the API with its CPU serial number: "Has anyone claimed me yet?"
  3. Operator claims the Pi in the dashboard by entering the serial number (printed on a sticker on the Pi)
  4. API returns a bind packet — contains the device certificate, private key, IoT endpoint, and hive configuration
  5. Pi installs the credentials and connects to AWS IoT Core over MQTT
  6. Dashboard shows the hive as online — sensor data starts flowing immediately

This means a customer would just plug in the Pi, open the app, scan or type the serial, and they're connected. No SSH, no command line, no technical knowledge required.

Custom Raspberry Pi Image

I built a custom Raspberry Pi OS image using pi-gen (the official Raspberry Pi image builder). The image comes pre-configured with everything the hive monitor needs — the agent software, systemd services, firewall rules, and bootstrap configuration are all baked in at build time. A beekeeper just flashes the image to an SD card, inserts it, and powers on. The CI pipeline builds new images automatically from the repo on every release.

Architecture — How Data Flows

┌─────────────┐         ┌──────────────────┐         ┌─────────────────┐
│  Pi in the  │  MQTT   │   AWS IoT Core   │  Event  │  Cloud Backend  │
│  Beehive    │────────▶│   (us-east-1)    │────────▶│  (API + DB)     │
│             │  8883   │                  │  Rules  │                 │
│ • Sensors   │◀────────│  Device Shadow   │         │ • User auth     │
│ • Cameras   │  cmds   │  (state sync)    │         │ • Hive CRUD     │
│ • Servo     │         └──────────────────┘         │ • Data storage  │
│ • LEDs      │                                      │ • Sharing       │
└─────────────┘                                      └────────┬────────┘
                                                              │
                                                              │ HTTPS
                                                              ▼
                                                     ┌─────────────────┐
                                                     │  Web Dashboard  │
                                                     │  hive-monitor   │
                                                     │  .com           │
                                                     │                 │
                                                     │ • Live sensors  │
                                                     │ • CPU temp      │
                                                     │ • Map view      │
                                                     │ • Multi-hive    │
                                                     │ • User sharing  │
                                                     └─────────────────┘

Hero Shot — Dashboard

Hive Monitor dashboard showing live sensor data and hive management

Hive Monitor dashboard — live sensor readings with interactive graphs. Each graph is interactive (hover for values, zoom, pan). Currently working on displaying each sensor individually rather than aggregated.

Product Vision — Why This Matters

Smart hive monitors exist as DIY projects on forums and GitHub, but nobody is selling a complete, plug-and-play system that a non-technical beekeeper can set up in 5 minutes. The market is wide open. My goal is to get a working proof of concept this summer, validate it with real beekeepers, and then figure out the manufacturing and cost reduction needed to make it a viable product. The software side (cloud dashboard, mobile app, fleet management) is where the real value is — the hardware is relatively straightforward once the cost is optimized.

For the group assignment, we compared different interface and application programming tools. Full group documentation: Charlotte Lab — Week 14 Group Assignment

My Contributions — Python Web Server + MQTT Cloud Interface

For the group comparison, I documented the Python web server + MQTT cloud interface approach that I used for my individual assignment. The group page compares four different tools:

  • MIT App Inventor (McKinnon) — visual block-based mobile app builder
  • MQTT (Yian) — lightweight publish/subscribe messaging protocol for IoT
  • Tkinter (Max) — Python's built-in GUI library for desktop interfaces
  • Python Web Server + MQTT (me) — combining Python's built-in HTTP server with MQTT for both local and cloud interfaces

What I Learned from Comparing Tools

  • MIT App Inventor is great for quick mobile prototypes — drag-and-drop UI with Bluetooth/Wi-Fi hardware communication. No coding needed, but limited customization.
  • Tkinter is the fastest path to a desktop GUI in Python — zero dependencies, works cross-platform. But it looks dated and threading with hardware can get tricky.
  • MQTT alone is just the transport layer — you still need a UI on top of it. But the pub/sub model makes it easy to decouple devices from dashboards.
  • My approach (Python HTTP + MQTT) gives the most flexibility — web-based so it works on any device with a browser, and MQTT handles the cloud communication. The tradeoff is more complexity: you're managing a web server, MQTT client, and sensor drivers all in one application.

If I were building a quick one-off demo, I'd probably use Tkinter or MIT App Inventor. For a real product that needs to work remotely and scale to multiple hives, the web + MQTT approach is the right choice — which is why I went that direction for the Smart Beehive.

Useful Links