Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Intelligent Edge StudioMachine Learning and Edge AIExperimentsWorkspaces
ENGINEERING WORKSPACE
Home/WSL Laboratories/Lab 43 · MQTT → Telegraf → InfluxDB
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Python & IoT / P43
IoT Programming and Applications

Lab 43 · MQTT → Telegraf → InfluxDB

Ask Dr. Mohammad · P43 →

The Wokwi ESP32 or Python simulator publishes to local Mosquitto. Telegraf writes data to InfluxDB.

Open MQTT packet analyzer →

Design experiment & verify evidence →
P43 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingP43 · MQTT → Telegraf → InfluxDB
Readiness checksRevision deckEngineering workspaceRecord evidence

Related course access: IoT Security and Privacy · Networking and Communication — same laboratory, notebook and completion record.

P43 · Academic orientation

Scope and objectives

Scope of the experiment

Follow each publication through subscription topic, JSON decoding and configured database admission.

The focus of this experiment is to trace MQTT telemetry through Telegraf into InfluxDB. Students then identify topic, parsing and field-mapping requirements, and compare input messages and stored points to locate pipeline failures. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.

Learning objectives

  • Trace MQTT telemetry through Telegraf into InfluxDB.
  • Identify topic, parsing and field-mapping requirements.
  • Compare input messages and stored points to locate pipeline failures.
  • Record the relevant inputs, intermediate states and final verification result before changing the reference configuration.
  • Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.

Expected learning outcomes

On completion, students can trace MQTT telemetry through Telegraf into InfluxDB, identify topic, parsing and field-mapping requirements, and compare input messages and stored points to locate pipeline failures.

Required deliverables

Submit the derivation or state trace for the named operation, the exact reference and changed configurations, the associated simulator or practical evidence, and a short validation statement addressing compare input messages and stored points to locate pipeline failures. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 44 · Grafana dashboard for IoT data.

Environment and experimental methodology

Browser teaching model, the named WSL or Python environment, and the physical board/components only for the hardware activity described in the practical instructions.

Begin with a manual prediction, record the baseline, change one independent condition at a time, and compare the resulting trace or measurements with the original prediction. Record observations and uncertainty separately from reference values. Follow the experiment’s specific procedure, safety limits, and acceptance checks.

P43 / PREPARE

Before starting

Follow the setup guide and use the named terminal or editor. A browser model is not a real GPIO measurement or a running service.

Ubuntu WSL setup →
Before you run / verification gate

Choose exactly one broker profile for all terminals and firmware. Start subscriber first; verify synthetic publisher before Wokwi. For storage, finish P42 token setup, then start one Telegraf instance. Public demo broker is not private. Stop only your own processes.

CONCEPTS / ACTIVE RECALL

Understand the experiment

MQTT → Telegraf → InfluxDB

Separate transport acknowledgment, parsing and persistence
Separate transport acknowledgment, parsing and persistence

Scientific architecture · MQTT–Telegraf–InfluxDB telemetry pipeline

MQTT Telegraf InfluxDB — Publisher / JSON payload; Broker / topic routing; Telegraf / parse & map; InfluxDB / timestamped point; Query / verify same sample ID
Scientific concept map: MQTT publisher — Topic + JSON; Broker — Route publication; Telegraf — Decode payload; InfluxDB — Store field and timestamp; Query — Confirm ingestion.

Scientific foundations and analytical reasoning

MQTT publication, subscription matching, payload parsing and database writes are distinct pipeline stages.

Before operating the equipment or executing the program, derive the expected outcome using the required theoretical work in Experiment. Use the diagram to identify the variables and system boundaries.

Scientific theory · Publish, parse and persist

An MQTT broker routes published topics to matching subscriptions. Telegraf subscribes and parses payloads, then writes measurements to InfluxDB. Connection credentials, topic configuration, parser format and database write privileges are separate dependencies. Timestamp and measurement mapping affect later queries.

Worked example and engineering interpretation

A broker receives 10 messages; a subscriber observes 10 but only 8 parse successfully and 7 reach storage. The delivery stage can work while the storage stage loses records. Use a unique sample ID to trace one message through each component.

Engineering principles · additional worked teaching example

The broker routes publications by topic; Telegraf parses payload fields and writes points; InfluxDB stores them. A successful MQTT delivery proves only the first stage. If 10 received records have 2 malformed JSON and 1 rejected write among parsed records, storage count is 7.

From theory to experiment

Predict the reference result before operating the workbench; check the actual intermediate state, units and constraints. The existing simulation, implementation and procedure below are distinct sources of evidence.

How to investigate Lab 43 · MQTT → Telegraf → InfluxDB

Trace MQTT telemetry through Telegraf and InfluxDB; verify each stage independently.

Analytical investigation means collecting an observation, identifying the mechanism, using a calculation or state trace to explain it, and checking your conclusion against evidence. Controlled comparison means changing one independent variable, holding the remaining relevant conditions constant, and measuring a dependent variable against a baseline. Experimental validation means comparing a predicted result to a reproducible observation or assertion; agreement inside a model does not certify hardware. Evidence-based reasoning connects a specific observation to a theoretical rule and states uncertainty, not merely an opinion. Performance characterization records a named metric and its units across conditions; sensitivity analysis changes one parameter across several values. A threat assessment links an asset, threat, consequence and evidence to a mitigation.

Experiment-specific guided practice

Objective: Trace MQTT telemetry through Telegraf and InfluxDB; verify each stage independently.

  1. Send valid JSON on the default topic. Record a stored point.
  2. Change topic to a nonmatching one; restore and disable valid JSON. Compare outcomes.
  3. Make the database unavailable, send three valid messages, restore it and flush. Record queue and stored counts.
  4. Run the existing publisher and Telegraf configuration and query the bucket. The model buffer does not represent guaranteed real retry behavior.

Reference check:

Model boundary:

Independent task and submission evidence

2. Change topic to a nonmatching one; restore and disable valid JSON. Compare outcomes. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat.

Before execution write the independent variable and its levels, dependent observation with units where applicable, baseline, controlled variables, measurement method and expected result. For a state machine use state/event/output rather than inventing a numeric metric. Record failures and repeat the baseline. A weak conclusion is “it works”; a supported conclusion names the changed setting, observed value/state, corresponding rule and one limitation.

TrialChanged settingFixed settingsPredicted resultActual observation / unitsEvidence / uncertainty
A: baselineReferenceRecordPredictRecordRecord
B: one changeRecordSame as APredictRecordRecord
A: repeatRestoreSame as APredictRecordRecord

Completion: submit the filled table, relevant simulator screenshot or terminal/notebook output, reasoning with units/assumptions, and one limitation. Preserve the independent assessment questions; this guide does not fill their answers.

Worked engineering reasoning and boundary conditions

Engineering reference configuration: Published messages = 8; Topic matches Telegraf subscription = true; Malformed JSON every N (0=none) = 0; Database writer authorized = true. In the classroom model, Published = 8; Consumed = 8; Parsed = 8; Stored points = 8. No actual broker or database is contacted. A closed, deterministic browser model. The existing practical instructions and source files provide independent execution; browser results are not hardware measurements.

Use the diagram to follow the calculation or state progression. Keep the teaching configuration separate from the independent exercise values; compare observations with the actual model and implementation.

Concept animation · quantity comparison

Explore the teaching example independently of the simulator. Each step reveals an operation, data relationship or calculated state. The Simulation view has separate editable inputs.

Lab 43 · MQTT → Telegraf → InfluxDB: quantity comparisonPublished8 Consumed8 Parsed8 Stored8

Step 1 of 4 · Published

Published

Published
8

Teaching example only; inspect live calculations or real practical evidence separately.

Recall the concept before revealing its explanation.

0 / 3 revealed
P43 · 01 / 08What is MQTT?Reveal explanation
Engineering explanation

A broker-based publish/subscribe protocol.

P43 · 02 / 08Why verify each pipeline stage?Reveal explanation
Engineering explanation

Receipt at the broker does not prove Node-RED, Telegraf or InfluxDB works.

P43 · 03 / 08Which MQTT, Telegraf and storage prerequisites must be established before diagnosis?Reveal explanation
Engineering explanation

Choose exactly one broker profile for all terminals and firmware. Start subscriber first; verify synthetic publisher before Wokwi. For storage, finish P42 token setup, then start one Telegraf instance. Public demo broker is not private. Stop only your own processes.

P43 · 04 / 08Where can telemetry disappear in the pipeline?Reveal explanation
Engineering reasoning

Publisher/topic, broker authorization, Telegraf decoding or flushing, and InfluxDB write/query can fail independently.

P43 · 05 / 08Why compare the exact topic and payload before debugging storage?Reveal explanation
Engineering reasoning

It verifies the input contract to Telegraf; a database query cannot recover a message that never reached ingestion.

P43 · 06 / 08Telemetry passes MQTT, Telegraf and InfluxDB. Select every technically valid statement. A. Check a known message at each stage. B. Use consistent topic and field mappings. C. Broker acceptance proves that InfluxDB has stored the record. D. Changing the dashboard query repairs an incorrect publisher topic.Reveal explanation
Applied scenario

Correct: A. Check a known message at each stage.; B. Use consistent topic and field mappings.

P43 · 07 / 08In MQTT → Telegraf → InfluxDB, which command or code executes the final documented practical action?Reveal explanation
Implementation recall

source ~/psut-wsl/activate.sh source ~/.config/psut-wsl/mqtt-hive.env cd ~/psut-wsl/labs/python/lab43 source ~/.config/psut-wsl/influx.env sleep 5 python my_device_history.py

P43 · 08 / 08For MQTT → Telegraf → InfluxDB, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

First finish P42 token setup. Select one profile, local (1884) or HiveMQ public demonstration (1883); source the matching file in every terminal. Start subscriber A; Telegraf B; publisher C with MESSAGES=5 PERIOD=2. Check subscriber payloads first, then wait for Telegraf flush and query stored history. Only then run Wokwi with matching broker/topic (public route uses assigned session ID). For local route Wokwi private gateway/forwarding is required; test port before firmware. No real private data on HiveMQ. Stop only the foreground processes you started.

WOKWI / WSL INTEGRATION

Connect to actual MQTT telemetry

Run the supplied ESP32 greenhouse firmware and inspect received messages, live sensor readings and per-device history. No browser-generated readings are inserted into the live view.

Open Live Telemetry Studio →

Build and validate this circuit in Circuit Studio →

Time-series deployment center

Follow the complete 16-stage walkthrough: install, configure tokens, test direct writes, start Telegraf, test MQTT, query stored data and provision Grafana.

Open Telegraf / InfluxDB / Grafana →
Execution boundary · Real Telegraf + InfluxDB. Browser simulation below is a teaching model, not execution of Python or firmware. The real commands run in VS Code/WSL; Wokwi is used for Arduino/ESP32 where indicated.

Network performance laboratory

Investigate seeded abstract queueing, traffic scalability and QoS trade-offs separately from actual service deployment.

Open Network Lab →
Shared research workbenches · network designer & advanced studies
Concurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery research

Live experimental workstations

Loading experiment-specific apparatus…
Previous model / additional reference tools
Simulation task

Trace MQTT telemetry through Telegraf and InfluxDB; verify each stage independently.

Explore the model using its own controls. Record a prediction before changing a condition. Compare the reference with a changed condition, then use the Experiment tab for the procedure, acceptance criteria and notebook. Model outputs and physical observations must remain separate.

Interactive engineering workbenchP43 · Existing model

Explore the interactive 3D electronics laboratory ↗ · 3D system simulation ↗

01 / Explore

Interactive lab simulation

Browser model

Pin and connection reference

WSL uses simulated GPIO. These are source-derived signal mappings; physical connection notes are guidance, not a claim of physical testing.

ComponentSignal / pinConnection notesSource
DHT22 DATAESP32 D15VCC → 3V3; GND → GND.1wokwi/esp32-greenhouse/diagram.json
Soil potentiometer SIGESP32 D34VCC → 3V3; GND → GND.1wokwi/esp32-greenhouse/diagram.json
Publish indicatorESP32 GPIO2Onboard LED, firmware uses GPIO2wokwi/esp32-greenhouse/src/main.cpp
P43 · Model-linked instrumentation

Visual observation lens

Back to controls ↑

Original virtual instrument; model signals and execution trace.

Loading instrument…

Awaiting model display.

Experimental instrumentation · A/B

Compare two model conditions

Capture a baseline, change one experimental condition, run the model if required and capture the comparison. Snapshots contain visible controls and display text, not physical sensor readings. Review before exporting.

Open simulation view
Baseline A
Not captured
Comparison B
Not captured

Capture a baseline to begin.

Evidence portfolio →
V19.0 · Contextual AI workspace

Ask your engineering assistants

P43 · current context

Ask Dr. Mohammad locally, or prepare an experiment-aware prompt for ChatGPT, Gemini or Claude. The external providers open in their own tabs; nothing is automatically submitted.

Dr. Mohammad · offline
Dr. Mohammad

Offline curriculum-grounded assistance.

Open local tutor
Lab 43 · MQTT → Telegraf → InfluxDB

Public course objective, displayed commands, source excerpts and procedure. Private assessment content is not collected.

Prepare a contextual AI prompt

0 characters

Common secret and email patterns are redacted on preparation; this is not a comprehensive privacy filter. Review the entire editable prompt, including student work and unpublished research, before sharing. The providers apply their own accounts, privacy settings and limits.

Prepare → review → copy & open your selected provider → paste and submit there.

Run & verify — acceptance checklist

Build verification: Static MQTT profile and telemetry validation tests passed; live services pending.

First finish P42 token setup. Select one profile, local (1884) or HiveMQ public demonstration (1883); source the matching file in every terminal. Start subscriber A; Telegraf B; publisher C with MESSAGES=5 PERIOD=2. Check subscriber payloads first, then wait for Telegraf flush and query stored history. Only then run Wokwi with matching broker/topic (public route uses assigned session ID). For local route Wokwi private gateway/forwarding is required; test port before firmware. No real private data on HiveMQ. Stop only the foreground processes you started.

Record the actual output, source (mock/model or physical), and any error. A missing tool, timeout or untested external service is not a pass.

Complete lab-by-lab verification report →Open automated verification center → Ask Engineering Copilot →

Independent theoretical exercises

Before the simulation or practical, solve both experiment-specific tasks. List the given inputs, show the intermediate calculation or state trace, identify the expected observation, and state a limitation. Show formulas and intermediate calculations where relevant, or draw the requested state/sequence diagram. These are independent classroom fixtures; where they differ from the reference configuration below, do not treat them as measured values. Compare your predictions with the corresponding experiment afterwards.

01 · Predict and derive using the given inputs

For eight messages with every third malformed, a matching subscription and an authorized writer, calculate accepted and rejected counts. Repeat for a nonmatching topic.

02 · Compare or justify using evidence

Draw stage-level counters and explain what can be inferred from a broker receipt but not from a database query failure.

03 · Pipeline diagnosis

Pipeline diagnosis · Independent work

Publish 20 messages; 4 do not match subscription; 3 matched messages fail parsing; 2 parsed writes fail. Calculate counts at each stage and locate the first failing gate for each loss.

Work is saved locally when browser storage is available. Export it for submission; no remote upload or automatic grade is assigned.

Expanded independent theoretical exercise bank

Progress from calculation and interpretation to diagnosis and controlled engineering design. Complete the questions without opening the simulation first; show intermediate steps.

Intermediate · Explain a changed-input result

Independent theoretical exercise · P43-01

Use the reference configuration (Published messages = 8; Topic matches Telegraf subscription = true; Malformed JSON every N (0=none) = 0; Database writer authorized = true), but change Published messages = 10. The model reports Published = 10. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · P43-02

Two model observations of Published are 8 (reference) and 10 (changed condition). Compute signed change and, when the reference is nonzero, percentage change. Explain why units matter.

Intermediate · Interpret a technical trace

Independent theoretical exercise · P43-03

For Topic matches Telegraf subscription = false, the model supplies this excerpt from Telemetry trace: Sequence · Consumed · Parsed · Stored 1 · No · No · No 2 · No · No · No 3 · No · No · No 4 · No · No · No 5 · No · No · No Count rows whose Consumed value is exactly “No”, and identify the displayed row numbers. Explain what the count describes.

Advanced · Reverse reasoning

Independent theoretical exercise · P43-04

An observation is Consumed = 0. Candidate A uses Published messages = 8; Topic matches Telegraf subscription = true; Malformed JSON every N (0=none) = 0; Database writer authorized = true. Candidate B changes the listed settings (Topic matches Telegraf subscription = false) and keeps the remaining settings fixed. Which is consistent with the observation? If both can explain it, say what additional evidence is required.

Advanced · Diagnose a reported mismatch

Independent theoretical exercise · P43-05

A student configures Malformed JSON every N (0=none) = 2 while preserving all other reference settings, but copies the reference report of Parsed = 8. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · P43-06

Design a controlled comparison for Lab 43 · MQTT → Telegraf → InfluxDB using reference Published messages = 8; Topic matches Telegraf subscription = true; Malformed JSON every N (0=none) = 0; Database writer authorized = true and test Published messages = 10. Specify the changed setting(s), measured metric Published, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Live simulation · MQTT and Telegraf pipeline

Perform these controlled trials before the existing practical experiment. Independent workstations have separate state.

  1. Send valid JSON on the default topic. Record a stored point.
  2. Change topic to a nonmatching one; restore and disable valid JSON. Compare outcomes.
  3. Make the database unavailable, send three valid messages, restore it and flush. Record queue and stored counts.
  4. Run the existing publisher and Telegraf configuration and query the bucket. The model buffer does not represent guaranteed real retry behavior.

Evidence

Record initial settings, actual observations, one failure and a restored condition. Compare calculated values with the practical run; distinguish virtual and physical/cloud evidence.

Step-by-step experimental procedure

Follow each publication through subscription topic, JSON decoding and configured database admission.

1 · Reference workbench configuration

Use the named reference workbench and its reference inputs. Additional live instruments may have different controls; use the matching instrument. Record virtual and practical results separately.

Published messages8
Topic matches Telegraf subscriptionYes
Malformed JSON every N (0=none)0
Database writer authorizedYes

2 · Perform the investigation in order

  1. Run eight reports with matching topic, valid JSON and authorized writer. Compare published, consumed, parsed and stored counts.
  2. Change topic match only; observe publications still exist but no consumption.
  3. Restore topic; inject malformed JSON every second report.
  4. Disable database authorization. Verify that broker delivery does not prove database persistence. Run the existing Telegraf/InfluxDB notebook for real integration evidence.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Complete pipelineUse reference inputs aboveStored points: 8Record actual result
Topic mismatchTopic matches Telegraf subscription = NoStored points: 0Record actual result
Malformed alternateMalformed JSON every N (0=none) = 2Stored points: 4Record actual result
Database deniedDatabase writer authorized = NoStored points: 0Record actual result

4 · Analyze and report

Locate failures by boundary instead of using one global success flag.

Required evidence: Record the named metrics and trace for the reference and changed cases, then attach the corresponding practical command output or device evidence if available.

Model boundary: A closed, deterministic browser model. The existing practical instructions and source files provide independent execution; browser results are not hardware measurements.

Loading laboratory-specific procedure…

Python / Google Colab notebook

Actual TCP MQTT + SQLite local path with virtual GPIO; opt-in InfluxDB OSS 2 + HiveMQ TLS/Telegraf. Vendor installation and live services require target-runtime verification. Default profile executed in an isolated local Python kernel. Live services and physical hardware are separate acceptance tasks.

Download NotebookOpen Google ColabAll Python notebooksFull service setup and acceptance

Independent implementation sequence

  1. Prepare broker, Node-RED and optional storage
  2. Terminal A — monitor MQTT
  3. Terminal B — optional Telegraf storage
  4. Terminal C — test Python publisher
  5. Windows VS Code — open Wokwi firmware
  6. Local route only — Windows forwarding
  7. Build and run Wokwi
  8. Optional — query InfluxDB history
02 / Implement

Step-by-step instructions

Before you run / verification gate

Choose exactly one broker profile for all terminals and firmware. Start subscriber first; verify synthetic publisher before Wokwi. For storage, finish P42 token setup, then start one Telegraf instance. Public demo broker is not private. Stop only your own processes.

Run only the selected broker branch. Each terminal needs activation and profile sourcing.

Choose ONE broker for a run. Local Mosquitto = 127.0.0.1:1884 in WSL, host.wokwi.internal:1884 in Wokwi. HiveMQ public = broker.hivemq.com:1883; simulated data only, no student IDs or secrets. Open the broker & Node-RED setup first. Use the same profile in every terminal.
01

Prepare broker, Node-RED and optional storage

Complete dashboard setup. Node-RED does not need InfluxDB. For the full Telegraf/InfluxDB path, complete Lab 42 first.

Checkpoint Broker profile generated, dashboard deployed.
02

Terminal A — monitor MQTT

Keep this running.

WSL · Bash
source ~/psut-wsl/activate.sh
source ~/.config/psut-wsl/mqtt-local.env
mosquitto_sub -h "$MQTT_HOST" -p "$MQTT_PORT" -t "$GREENHOUSE_TOPIC" -q 1 -v
✓ Expected: The subscriber remains open. Once a matching publisher sends data, topic and JSON payload appear; an initially blank screen is normal.
Expected result for each action (3)
  1. source ~/psut-wsl/activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
  2. source ~/.config/psut-wsl/mqtt-local.envThe local MQTT profile is loaded silently. Verify host 127.0.0.1, port 1884 and the matching topic in this shell.
  3. mosquitto_sub -h "$MQTT_HOST" -p "$MQTT_PORT" -t "$GREENHOUSE_TOPIC" -q 1 -vThe subscriber remains open. Once a matching publisher sends data, topic and JSON payload appear; an initially blank screen is normal.
Checkpoint Waiting for exact session topics.
03

Terminal B — optional Telegraf storage

Skip only if using Node-RED alone. Complete Lab 42 first; keep Telegraf running.

WSL · Bash
source ~/psut-wsl/activate.sh
source ~/.config/psut-wsl/mqtt-local.env
cd ~/psut-wsl/labs/python/lab43
source ~/.config/psut-wsl/influx.env
telegraf --config telegraf.conf
✓ Expected: Telegraf starts its MQTT input and InfluxDB output and remains running. Look for connection or write errors, then query stored records independently.
Expected result for each action (5)
  1. source ~/psut-wsl/activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
  2. source ~/.config/psut-wsl/mqtt-local.envThe local MQTT profile is loaded silently. Verify host 127.0.0.1, port 1884 and the matching topic in this shell.
  3. cd ~/psut-wsl/labs/python/lab43Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
  4. source ~/.config/psut-wsl/influx.envThe token becomes available to child processes without being printed. Check only whether it is set, then test authorized access.
  5. telegraf --config telegraf.confTelegraf starts its MQTT input and InfluxDB output and remains running. Look for connection or write errors, then query stored records independently.
Checkpoint MQTT consumer connected to selected profile; no write errors.
04

Terminal C — test Python publisher

Test before starting Wokwi.

WSL · Bash
source ~/psut-wsl/activate.sh
source ~/.config/psut-wsl/mqtt-local.env
cd ~/psut-wsl/labs/python/lab43
MESSAGES=5 PERIOD=2 python device_simulator.py
✓ Expected: Five telemetry messages are published at the configured interval. Confirm their reception in the matching subscriber and dashboard.
Expected result for each action (4)
  1. source ~/psut-wsl/activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
  2. source ~/.config/psut-wsl/mqtt-local.envThe local MQTT profile is loaded silently. Verify host 127.0.0.1, port 1884 and the matching topic in this shell.
  3. cd ~/psut-wsl/labs/python/lab43Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
  4. MESSAGES=5 PERIOD=2 python device_simulator.pyFive telemetry messages are published at the configured interval. Confirm their reception in the matching subscriber and dashboard.
Checkpoint Five accepted readings in Terminal A and Node-RED; select python-sim.
05

Windows VS Code — open Wokwi firmware

Open the Windows-extracted psut-wsl/wokwi/esp32-greenhouse folder in a local VS Code window. Install PlatformIO and Wokwi. In WSL run the profile generator again to print the three exact firmware settings. In the Windows copy of src/main.cpp, set BROKER, BROKER_PORT, STUDENT_ID to those printed values. Save. Local default needs no edits.

Checkpoint For HiveMQ the session starts demo-; never use personal identifiers.
06

Local route only — Windows forwarding

If using HiveMQ skip this step. Enable Wokwi private gateway in VS Code; follow the WSL bridge checklist.

Windows PowerShell
Test-NetConnection localhost -Port 1884
✓ Expected: Look for TcpTestSucceeded : True for the specified port. This proves TCP reachability only.
Checkpoint TcpTestSucceeded: True
07

Build and run Wokwi

PlatformIO: Build → Ctrl+Shift+P → Wokwi: Start Simulator. Change DHT22 and potentiometer. Wait 10 seconds between messages.

Checkpoint Serial shows MQTT connected and sent JSON; Node-RED shows esp32-01. Wokwi publishes QoS 0; serial sent does not prove dashboard delivery.
08

Optional — query InfluxDB history

Run in Terminal C only if Telegraf is running.

WSL · Bash
source ~/psut-wsl/activate.sh
source ~/.config/psut-wsl/mqtt-local.env
cd ~/psut-wsl/labs/python/lab43
source ~/.config/psut-wsl/influx.env
sleep 5
python my_device_history.py
✓ Expected: Stored records matching the configured session and time window are displayed if ingestion succeeded. An empty result requires investigation.
Expected result for each action (6)
  1. source ~/psut-wsl/activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
  2. source ~/.config/psut-wsl/mqtt-local.envThe local MQTT profile is loaded silently. Verify host 127.0.0.1, port 1884 and the matching topic in this shell.
  3. cd ~/psut-wsl/labs/python/lab43Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
  4. source ~/.config/psut-wsl/influx.envThe token becomes available to child processes without being printed. Check only whether it is set, then test authorized access.
  5. sleep 5No output; execution pauses for the specified time, then continues. This is not evidence of delivery.
  6. python my_device_history.pyStored records matching the configured session and time window are displayed if ingestion succeeded. An empty result requires investigation.
Checkpoint History shows python-sim and esp32-01. Stop Wokwi and A/B when done.

Experimental notebook

Record your own results. Values are not prefilled or independently verified.

03 / Inspect

Source code and method

labs/python/lab43/device_simulator.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Example 1b: a Python stand-in for the ESP32 greenhouse node
# Publishes the same JSON as the ESP32 sketch to the same topic, so you can test
# Telegraf + InfluxDB without Wokwi (for example in Google Colab).
# Needs:  pip install paho-mqtt

import json
import math
import os
import time
import threading
import re

import paho.mqtt.client as mqtt

BROKER = os.getenv("MQTT_BROKER", "127.0.0.1")   # local WSL Mosquitto
PORT = int(os.getenv("MQTT_PORT", "1884"))
STUDENT_ID = os.getenv("STUDENT_ID", "lab-local")  # topic label, not authentication
NODE = os.getenv("NODE", "python-sim")             # which device this is
TOPIC = f"psut/iot/{STUDENT_ID}/greenhouse/{NODE}/telemetry"
MESSAGES = int(os.getenv("MESSAGES", "30"))       # how many readings to send
PERIOD = float(os.getenv("PERIOD", "0.5"))        # seconds between readings


# ---- The same simulated sensors as Lab 42 (identical numbers every run)
def reading(i: int) -> dict:
    return {
        "source": "mock",
        "temperature": round(24.0 + 0.3 * i + 0.4 * math.sin(1.3 * i), 1),
        "humidity": round(max(0,min(100,72.0 - 0.6 * i + 1.2 * math.sin(0.7 * i))), 1),
        "soil_moisture": round(max(0,min(100,60.0 - 1.0 * i + 0.8 * math.sin(0.9 * i))), 1),
    }


def main() -> None:
    if MESSAGES < 1 or PERIOD <= 0: raise ValueError("MESSAGES and PERIOD must be positive")
    if BROKER.lower() == "broker.hivemq.com" and not re.fullmatch(r"demo-[0-9a-f]{16}", STUDENT_ID):
        raise SystemExit("Run tools/mqtt_profile.py hive and source the generated profile first")
    client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
    ready = threading.Event()
    def connected(c,u,f,reason,p):
        if not reason.is_failure: ready.set()
    client.on_connect = connected
    client.connect(BROKER, PORT, keepalive=30)
    client.loop_start()
    try:
        if not ready.wait(10): raise RuntimeError("MQTT CONNACK timeout")
        for i in range(MESSAGES):
            payload = json.dumps(reading(i), allow_nan=False)
            info = client.publish(TOPIC, payload, qos=1, retain=False)
            info.wait_for_publish(timeout=10)
            if not info.is_published(): raise RuntimeError("MQTT PUBACK timeout")
            print(f"{TOPIC} {payload}", flush=True)
            if i+1 < MESSAGES: time.sleep(PERIOD)
    finally:
        client.disconnect(); client.loop_stop()

if __name__ == "__main__":
    main()
labs/python/lab43/esp32_greenhouse_mqtt.inoDownload source
INO · source file
// ------------------------------------------------------------
// Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
// PSUT IoT Engineering Learning Platform
// ------------------------------------------------------------
// ---- Example 1: ESP32 greenhouse node (Wokwi) → MQTT broker
// Every 10 s: read the DHT22 and the soil probe (a potentiometer in Wokwi),
// build one JSON message and publish it to YOUR topic on the local broker.
// Libraries (Wokwi Library Manager): PubSubClient, DHT sensor library for ESPx

#include <WiFi.h>
#include <PubSubClient.h>
#include "DHTesp.h"

// ---- Settings: use profile values; never use a university ID on a public broker
const char* WIFI_SSID   = "Wokwi-GUEST";          // Wokwi's simulated Wi-Fi, no password
const char* WIFI_PASS   = "";
const char* BROKER      = "host.wokwi.internal";     // local WSL broker via Wokwi gateway
const int   BROKER_PORT = 1884;
const char* STUDENT_ID  = "lab-local";               // session label; not authentication
const char* NODE        = "esp32-01";               // this device's name

// ---- Pins
const int DHT_PIN  = 15;                            // DHT22 data
const int SOIL_PIN = 34;                            // potentiometer wiper = soil probe (ADC1)
const int LED_PIN  = 2;                             // blinks on every publish

DHTesp dht;
WiFiClient net;
PubSubClient mqtt(net);
char topic[96];
unsigned long lastSend = 0;

// ---- Connect (or reconnect) to the broker with a unique client ID
void connectMqtt() {
  while (!mqtt.connected()) {
    String id = String("psut-") + STUDENT_ID + "-" + NODE + "-" + String((uint32_t)esp_random(), HEX);
    Serial.print("MQTT connecting as "); Serial.println(id);
    if (mqtt.connect(id.c_str())) {
      Serial.println("MQTT connected");
    } else {
      Serial.print("failed, state="); Serial.println(mqtt.state());
      delay(2000);                                  // wait, then try again
    }
  }
}

void setup() {
  Serial.begin(115200);
  if (strcmp(BROKER, "broker.hivemq.com") == 0) {
    String session = STUDENT_ID;
    bool valid = session.startsWith("demo-") && session.length() == 21;
    for (unsigned int i=5; i<session.length(); i++) {
      char c=session[i]; valid = valid && ((c>='0' && c<='9') || (c>='a' && c<='f'));
    }
    if (!valid) { Serial.println("Generate a HiveMQ demo session first"); while(true) delay(1000); }
  }
  pinMode(LED_PIN, OUTPUT);
  dht.setup(DHT_PIN, DHTesp::DHT22);
  snprintf(topic, sizeof(topic), "psut/iot/%s/greenhouse/%s/telemetry", STUDENT_ID, NODE);

  WiFi.begin(WIFI_SSID, WIFI_PASS);                 // ---- Wi-Fi first
  Serial.print("Wi-Fi");
  while (WiFi.status() != WL_CONNECTED) { delay(250); Serial.print("."); }
  Serial.println(" connected");

  mqtt.setServer(BROKER, BROKER_PORT);              // ---- then the broker
  connectMqtt();
  Serial.print("Publishing to "); Serial.println(topic);
}

void loop() {
  if (WiFi.status() != WL_CONNECTED) { WiFi.reconnect(); delay(1000); return; }
  if (!mqtt.connected()) connectMqtt();
  mqtt.loop();                                      // keep the MQTT connection alive

  if (millis() - lastSend >= 10000) {               // ---- one reading every 10 s
    lastSend = millis();
    TempAndHumidity th = dht.getTempAndHumidity();
    if (isnan(th.temperature) || isnan(th.humidity)) { Serial.println("DHT22 read failed"); return; }
    float soil = analogRead(SOIL_PIN) * 100.0 / 4095.0;   // 0–4095 → 0–100 %

    // ---- JSON payload: the keys become InfluxDB fields through Telegraf
    char payload[128];
    snprintf(payload, sizeof(payload),
             "{\"source\":\"wokwi\",\"temperature\":%.1f,\"humidity\":%.1f,\"soil_moisture\":%.1f}",
             th.temperature, th.humidity, soil);
    bool ok = mqtt.publish(topic, payload);
    Serial.print(ok ? "sent " : "NOT sent "); Serial.println(payload);
    digitalWrite(LED_PIN, HIGH); delay(50); digitalWrite(LED_PIN, LOW);
  }
}
labs/python/lab43/install_telegraf.shDownload source
SH · source file
#!/usr/bin/env bash
set -euo pipefail
bash "$HOME/psut-wsl/setup_wsl.sh" --influx
echo "Use foreground telegraf --config telegraf.conf as instructed in Lab 43."
labs/python/lab43/my_device_history.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Example 2: the history of YOUR devices, as stored by Telegraf
# pivot() turns the three field rows of each moment into one row with three columns.

import os
from statistics import mean

from influxdb_client import InfluxDBClient

URL = os.getenv("INFLUX_URL", "http://localhost:8086")
TOKEN = os.environ["INFLUX_TOKEN"]
ORG = os.getenv("INFLUX_ORG", "psut")
BUCKET = os.getenv("INFLUX_BUCKET", "greenhouse")
STUDENT_ID = os.getenv("STUDENT_ID", "lab-local")

FLUX = f'''from(bucket: "{BUCKET}")
  |> range(start: -1h)
  |> filter(fn: (r) => r._measurement == "environment" and r.student == "{STUDENT_ID}")
  |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value")'''


def main() -> None:
    with InfluxDBClient(url=URL, token=TOKEN, org=ORG) as client:
        tables = client.query_api().query(FLUX, org=ORG)

    rows = [rec.values for table in tables for rec in table.records]   # one dict per moment
    if not rows:
        raise SystemExit(f"No data for student {STUDENT_ID}: is Telegraf running and your device publishing?")

    print(f"History of student {STUDENT_ID}, last hour")
    print(f"{'node':<12}{'readings':>9}{'T min':>8}{'T mean':>8}{'T max':>8}{'last soil':>11}")
    for node in sorted({r['node'] for r in rows}):
        mine = sorted((r for r in rows if r['node'] == node), key=lambda r: r['_time'])
        temps = [r['temperature'] for r in mine]
        print(f"{node:<12}{len(mine):>9}{min(temps):>8.1f}{mean(temps):>8.2f}{max(temps):>8.1f}"
              f"{mine[-1]['soil_moisture']:>11.1f}")


if __name__ == "__main__":
    main()
labs/python/lab43/telegraf.confDownload source
CONF · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Telegraf: subscribe to YOUR greenhouse topics on the MQTT broker and
#      store every message in InfluxDB 2. No Python needed: only this file.
# ${STUDENT_ID} and ${INFLUX_TOKEN} are read from the environment when Telegraf starts.

[agent]
  flush_interval = "2s"            # write to InfluxDB at most every 2 s
  omit_hostname = true             # do not add a "host" tag to every point
  skip_processors_after_aggregators = true   # the future default; silences a start-up warning

# ---- Input: MQTT consumer (one subscription, many devices)
[[inputs.mqtt_consumer]]
  servers = ["${MQTT_SERVER}"]
  topics = ["psut/iot/${STUDENT_ID}/greenhouse/+/telemetry"]   # + = any device name
  qos = 1                          # the broker resends until Telegraf confirms
  topic_tag = ""                   # do not store the whole topic as a tag
  data_format = "json_v2"          # the payload is JSON

  # Topic levels → tags:  psut / iot / <student> / greenhouse / <node> / telemetry
  [[inputs.mqtt_consumer.topic_parsing]]
    topic = "psut/iot/+/greenhouse/+/telemetry"
    tags = "_/_/student/_/node/_"

  # JSON keys → fields, always as floats (avoids field-type conflicts, Lab 42 Step 5)
  [[inputs.mqtt_consumer.json_v2]]
    measurement_name = "environment"
    [[inputs.mqtt_consumer.json_v2.tag]]
      path = "source"
      optional = true
    [[inputs.mqtt_consumer.json_v2.field]]
      path = "temperature"
      type = "float"
    [[inputs.mqtt_consumer.json_v2.field]]
      path = "humidity"
      type = "float"
    [[inputs.mqtt_consumer.json_v2.field]]
      path = "soil_moisture"
      type = "float"

# ---- Output: InfluxDB 2 (the same bucket as Lab 42)
[[outputs.influxdb_v2]]
  urls = ["http://127.0.0.1:8086"]
  token = "${INFLUX_TOKEN}"
  organization = "psut"
  bucket = "greenhouse"
wokwi/esp32-greenhouse/diagram.jsonDownload source
JSON · source file
{
  "version": 1,
  "author": "PSUT IoT Learning Studio",
  "editor": "wokwi",
  "parts": [
    {
      "type": "wokwi-esp32-devkit-v1",
      "id": "board",
      "top": 0,
      "left": 0,
      "attrs": {}
    },
    {
      "type": "wokwi-dht22",
      "id": "dht",
      "top": -25,
      "left": 220,
      "attrs": {}
    },
    {
      "type": "wokwi-potentiometer",
      "id": "soil",
      "top": 145,
      "left": 220,
      "attrs": {}
    }
  ],
  "connections": [
    [
      "board:3V3",
      "dht:VCC",
      "red",
      []
    ],
    [
      "board:GND.1",
      "dht:GND",
      "black",
      []
    ],
    [
      "board:D15",
      "dht:SDA",
      "green",
      []
    ],
    [
      "board:3V3",
      "soil:VCC",
      "red",
      []
    ],
    [
      "board:GND.1",
      "soil:GND",
      "black",
      []
    ],
    [
      "board:D34",
      "soil:SIG",
      "blue",
      []
    ]
  ]
}
wokwi/esp32-greenhouse/platformio.iniDownload source
INI · source file
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
lib_deps =
  knolleary/PubSubClient@2.8
  beegee-tokyo/DHT sensor library for ESPx@1.19
wokwi/esp32-greenhouse/src/main.cppDownload source
CPP · source file
#include <Arduino.h>
// ------------------------------------------------------------
// Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
// PSUT IoT Engineering Learning Platform
// ------------------------------------------------------------
// ---- Example 1: ESP32 greenhouse node (Wokwi) → MQTT broker
// Every 10 s: read the DHT22 and the soil probe (a potentiometer in Wokwi),
// build one JSON message and publish it to YOUR topic on the local broker.
// Libraries (Wokwi Library Manager): PubSubClient, DHT sensor library for ESPx

#include <WiFi.h>
#include <PubSubClient.h>
#include "DHTesp.h"

// ---- Settings: use profile values; never use a university ID on a public broker
const char* WIFI_SSID   = "Wokwi-GUEST";          // Wokwi's simulated Wi-Fi, no password
const char* WIFI_PASS   = "";
const char* BROKER      = "host.wokwi.internal";     // local WSL broker via Wokwi gateway
const int   BROKER_PORT = 1884;
const char* STUDENT_ID  = "lab-local";               // session label; not authentication
const char* NODE        = "esp32-01";               // this device's name

// ---- Pins
const int DHT_PIN  = 15;                            // DHT22 data
const int SOIL_PIN = 34;                            // potentiometer wiper = soil probe (ADC1)
const int LED_PIN  = 2;                             // blinks on every publish

DHTesp dht;
WiFiClient net;
PubSubClient mqtt(net);
char topic[96];
unsigned long lastSend = 0;

// ---- Connect (or reconnect) to the broker with a unique client ID
void connectMqtt() {
  while (!mqtt.connected()) {
    String id = String("psut-") + STUDENT_ID + "-" + NODE + "-" + String((uint32_t)esp_random(), HEX);
    Serial.print("MQTT connecting as "); Serial.println(id);
    if (mqtt.connect(id.c_str())) {
      Serial.println("MQTT connected");
    } else {
      Serial.print("failed, state="); Serial.println(mqtt.state());
      delay(2000);                                  // wait, then try again
    }
  }
}

void setup() {
  Serial.begin(115200);
  if (strcmp(BROKER, "broker.hivemq.com") == 0) {
    String session = STUDENT_ID;
    bool valid = session.startsWith("demo-") && session.length() == 21;
    for (unsigned int i=5; i<session.length(); i++) {
      char c=session[i]; valid = valid && ((c>='0' && c<='9') || (c>='a' && c<='f'));
    }
    if (!valid) { Serial.println("Generate a HiveMQ demo session first"); while(true) delay(1000); }
  }
  pinMode(LED_PIN, OUTPUT);
  dht.setup(DHT_PIN, DHTesp::DHT22);
  snprintf(topic, sizeof(topic), "psut/iot/%s/greenhouse/%s/telemetry", STUDENT_ID, NODE);

  WiFi.begin(WIFI_SSID, WIFI_PASS);                 // ---- Wi-Fi first
  Serial.print("Wi-Fi");
  while (WiFi.status() != WL_CONNECTED) { delay(250); Serial.print("."); }
  Serial.println(" connected");

  mqtt.setServer(BROKER, BROKER_PORT);              // ---- then the broker
  connectMqtt();
  Serial.print("Publishing to "); Serial.println(topic);
}

void loop() {
  if (WiFi.status() != WL_CONNECTED) { WiFi.reconnect(); delay(1000); return; }
  if (!mqtt.connected()) connectMqtt();
  mqtt.loop();                                      // keep the MQTT connection alive

  if (millis() - lastSend >= 10000) {               // ---- one reading every 10 s
    lastSend = millis();
    TempAndHumidity th = dht.getTempAndHumidity();
    if (isnan(th.temperature) || isnan(th.humidity)) { Serial.println("DHT22 read failed"); return; }
    float soil = analogRead(SOIL_PIN) * 100.0 / 4095.0;   // 0–4095 → 0–100 %

    // ---- JSON payload: the keys become InfluxDB fields through Telegraf
    char payload[128];
    snprintf(payload, sizeof(payload),
             "{\"source\":\"wokwi\",\"temperature\":%.1f,\"humidity\":%.1f,\"soil_moisture\":%.1f}",
             th.temperature, th.humidity, soil);
    bool ok = mqtt.publish(topic, payload);
    Serial.print(ok ? "sent " : "NOT sent "); Serial.println(payload);
    digitalWrite(LED_PIN, HIGH); delay(50); digitalWrite(LED_PIN, LOW);
  }
}
wokwi/esp32-greenhouse/wokwi.tomlDownload source
TOML · source file
[wokwi]
version = 1
firmware = ".pio/build/esp32dev/firmware.bin"
elf = ".pio/build/esp32dev/firmware.elf"
04 / Verify

Evidence of completion

Save the actual terminal output from the checkpoints above. For simulated inputs explicitly record browser model, fakepi, mock or Wokwi. Never present those data as physical measurements. If a checkpoint fails, see the troubleshooting guide.

Integrated IoT System Studio

Follow the complete telemetry pipeline, compare live and stored evidence, and investigate controlled failures.

Open integrated system workbench →

Python / Google Colab laboratory

P43 · 15 notebook cells · 5 executable Python cells

Complete the theoretical investigation first. Run the cells in order, record actual outputs and compare against your prediction.

How to execute

  1. Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
  2. Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
  3. Perform the baseline and controlled changes. Save the notebook with actual outputs and your written interpretation.

Execution scope: Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.

01Instructions · Markdown
# P43 · Lab 43 · MQTT → Telegraf → InfluxDB **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction This notebook turns the original laboratory into a repeatable software experiment. Virtual readings and GPIO values are explicitly distinguished from physical measurements. ## How to run 1. In Google Colab choose File → Upload notebook; select this `.ipynb`. A CPU Python runtime is sufficient. 2. Read the goals and select the execution profile in the configuration cell. Run the implementation cells in order or use Runtime → Run all. 3. Compare the measured software output against the stated acceptance criteria. Run the controlled second trial and record differences. 4. Never use physical GPIO, private telemetry, real credentials or identifiable student information on a public broker. Stop the runtime after the lab. **Scope:** Local tests run actual software components using bounded virtual inputs. A successful local trial does not certify external services.
02Instructions · Markdown
## Experiment-specific preparation Trace MQTT telemetry through Telegraf and InfluxDB; verify each stage independently. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Send valid JSON on the default topic. Record a stored point. 2. Change topic to a nonmatching one; restore and disable valid JSON. Compare outcomes. 3. Make the database unavailable, send three valid messages, restore it and flush. Record queue and stored counts. 4. Run the existing publisher and Telegraf configuration and query the bucket. The model buffer does not represent guaranteed real retry behavior. 5. Run eight reports with matching topic, valid JSON and authorized writer. Compare published, consumed, parsed and stored counts. **Evidence:** **Boundary:**
03Instructions · Markdown
## 1. Goals and architecture - Produce timestamped virtual greenhouse readings and threshold-controlled GPIO17 fan state. - Publish synthetic JSON to a unique HiveMQ topic; Telegraf subscribes and writes to InfluxDB. - Compare observed record counts and values with transmitted data. **Local mode:** virtual device → real MQTT 3.1.1 TCP packets → restricted loopback teaching peer → subscriber → actual SQLite → plot. **Stack mode:** virtual device → HiveMQ TLS MQTT → Telegraf → InfluxDB 2 → Flux query. Local mode is NOT an InfluxDB/Grafana result. Control the sampling count and threshold; use identical synthetic readings for the two configurations. The local peer supports only exact topics and QoS 1; it is not a full broker.
04Python · executable cell
PYTHON · Code cell
# =====================================================================
# P43 | Code cell 01 | Lab 43 · MQTT → Telegraf → InfluxDB
# Purpose: 1. Goals and architecture - Produce timestamped virtual greenhouse readings and threshold-controlled GPIO17 fan state. - Publish synthetic JSON to a unique HiveMQ topic; Telegraf subscribes and writes to Influx
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import contextlib, csv, io, json, math, os, secrets, socket, socketserver, sqlite3, ssl, struct, threading, time, uuid

from pathlib import Path

from urllib.request import Request, urlopen

from urllib.parse import urlencode

# Define the reusable operation check; keep its logic separate from the trial.
def check(condition, message):
    if not condition: raise RuntimeError(message)

# Define the reusable operation u16; keep its logic separate from the trial.
def u16(n): return struct.pack('!H', n)

# Define the reusable operation string; keep its logic separate from the trial.
def string(s):
    b=s.encode('utf-8');return u16(len(b))+b

# Define the reusable operation exact; keep its logic separate from the trial.
def exact(s,n):
    b=bytearray()
    while len(b)<n:
        c=s.recv(n-len(b))
        if not c: raise EOFError('peer closed')
        b.extend(c)
    return bytes(b)

# Define the reusable operation packet; keep its logic separate from the trial.
def packet(s,head,body=b''):
    n=len(body);out=bytearray([head])
    while True:
        digit=n%128;n//=128;out.append(digit|(128 if n else 0))
        if not n: break
    s.sendall(out+body)

# Define the reusable operation read packet; keep its logic separate from the trial.
def read_packet(s):
    h=exact(s,1)[0];n=0;mul=1
    for _ in range(4):
        b=exact(s,1)[0];n+=(b&127)*mul
        if not b&128:break
        mul*=128
    else:raise ValueError('invalid MQTT length')
    check(n<=65536,'packet too large for lab');return h,exact(s,n)

# Define the reusable operation split string; keep its logic separate from the trial.
def split_string(b):
    check(len(b)>=2,'truncated MQTT field');n=int.from_bytes(b[:2],'big');check(len(b)>=2+n,'truncated MQTT string');return b[2:2+n].decode(),b[2+n:]

# Small synchronous teaching client: clean session, exact-topic QoS 1.
class MQTT:
    """Small synchronous teaching client: clean session, exact-topic QoS 1.
    Separate publisher/subscriber sockets; no reconnect, keepalive or wildcard API.
    """
    def __init__(self,host,port,tls=False):
        s=socket.create_connection((host,port),timeout=8);s.settimeout(8)
        try:
            if tls:s=ssl.create_default_context().wrap_socket(s,server_hostname=host)
            self.s=s;self.pid=0
            packet(s,0x10,string('MQTT')+b'\x04\x02'+u16(60)+string('psut-'+uuid.uuid4().hex[:16]))
            h,b=read_packet(s);check(h==0x20 and b==b'\x00\x00','CONNACK failed')
        except BaseException:s.close();raise
    def next_id(self):self.pid=self.pid%65535+1;return u16(self.pid)
    def subscribe(self,topic):
        pid=self.next_id();packet(self.s,0x82,pid+string(topic)+b'\x01');h,b=read_packet(self.s);check(h==0x90 and b==pid+b'\x01','QoS 1 SUBACK not granted')
    def publish(self,topic,payload):
        pid=self.next_id();packet(self.s,0x32,string(topic)+pid+payload);h,b=read_packet(self.s);check(h==0x40 and b==pid,'PUBACK mismatch')
    def receive(self):
        h,b=read_packet(self.s);check(h>>4==3 and ((h>>1)&3)==1,'expected QoS 1 PUBLISH');topic,rest=split_string(b);check(len(rest)>=2,'missing packet ID');packet(self.s,0x40,rest[:2]);return topic,rest[2:]
    def close(self):
        try:packet(self.s,0xe0)
        except OSError:pass
        self.s.close()
    def __enter__(self):return self
    def __exit__(self,*args):self.close()

# Encapsulate state and operations for Peer; keep its logic separate from the trial.
class Peer(socketserver.BaseRequestHandler):
    def handle(self):
        s=self.request;s.settimeout(15);server=self.server
        try:
            h,b=read_packet(s);proto,b=split_string(b);check(h==0x10 and proto=='MQTT' and b[:2]==b'\x04\x02','unsupported CONNECT');packet(s,0x20,b'\x00\x00')
            while True:
                h,b=read_packet(s)
                if h==0x82:
                    topic,tail=split_string(b[2:]);check(tail==b'\x01' and '+' not in topic and '#' not in topic,'exact QoS1 only')
                    with server.lock:server.subs.setdefault(topic,set()).add(s)
                    packet(s,0x90,b[:2]+b'\x01')
                elif h==0x32:
                    topic,tail=split_string(b);check(len(tail)>=2,'missing packet ID')
                    with server.lock:
                        for target in list(server.subs.get(topic,())):
                            server.seq=server.seq%65535+1
                            try:packet(target,0x32,string(topic)+u16(server.seq)+tail[2:])
                            except OSError:server.subs[topic].discard(target)
                    packet(s,0x40,tail[:2])
                elif h==0x40:continue # no retransmission in this restricted fixture
                elif h==0xc0:packet(s,0xd0)
                elif h==0xe0:break
                else:raise ValueError('unsupported packet')
        except (EOFError,OSError,ValueError,RuntimeError):pass
        finally:
            with server.lock:
                for targets in server.subs.values():targets.discard(s)

# Encapsulate state and operations for LoopbackPeer; keep its logic separate from the trial.
class LoopbackPeer(socketserver.ThreadingTCPServer):
    daemon_threads=True
    def __init__(self):
        self.lock=threading.Lock();self.subs={};self.seq=0;super().__init__(('127.0.0.1',0),Peer)

# Define the reusable operation endpoint; keep its logic separate from the trial.
@contextlib.contextmanager
def endpoint(mode):
    if mode=='hivemq':
        yield 'broker.hivemq.com',8883,True
    elif mode=='local':
        with LoopbackPeer() as p:
            t=threading.Thread(target=p.serve_forever,daemon=True);t.start()
            try:yield '127.0.0.1',p.server_address[1],False
            finally:p.shutdown();t.join(3)
    else:raise ValueError('Choose local or hivemq explicitly')

# Explicit logical device adapter. Not an electrical or timing emulator.
class VirtualGPIO:
    """Explicit logical device adapter. Not an electrical or timing emulator."""
    def __init__(self):self.pins={};self.trace=[]
    def setup(self,pin,direction,pull=0):
        check(direction in ('in','out') and type(pin)==int and 0<=pin<=27,'invalid pin setup');self.pins[pin]=[direction,float(pull)]
    def _set(self,pin,val,direction):
        check(pin in self.pins and self.pins[pin][0]==direction,'incorrect pin direction');check(0<=val<=1,'invalid logical level');self.pins[pin][1]=float(val);self.trace.append((pin,float(val)))
    def write(self,pin,val):self._set(pin,val,'out')
    def drive_input(self,pin,val):self._set(pin,val,'in')
    def read(self,pin):return self.pins[pin][1]
    def pwm(self,pin,duty):self.write(pin,duty)

# Define the reusable operation samples; keep its logic separate from the trial.
def samples(count=12,threshold=27):
    check(type(count)==int and 3<=count<=30,'3–30 samples');check(20<=threshold<=35,'threshold 20–35 C')
    g=VirtualGPIO();g.setup(17,'out');run=uuid.uuid4().hex;ts=int(time.time())-count*2
    out=[]
    for i in range(count):
        t=round(24+.55*i+.2*math.sin(i),2);g.write(17,int(t>=threshold))
        out.append({'run':run,'source':'virtual','node':'pi-01','seq':i,'ts':ts+i*2,'temperature':t,'humidity':round(72-.6*i,2),'soil_moisture':round(60-i*.8,2),'fan':int(g.read(17))})
    return out

# Define the reusable operation valid record; keep its logic separate from the trial.
def valid_record(raw,run):
    try:
        r=json.loads(raw);check(type(r)==dict and r['run']==run and r['source']=='virtual' and r['node']=='pi-01','identity');check(type(r['seq'])==int and 0<=r['seq']<30 and type(r['ts'])==int,'sequence');check(all(type(r[k]) in (int,float) and math.isfinite(r[k]) and lo<=r[k]<=hi for k,lo,hi in [('temperature',-40,80),('humidity',0,100),('soil_moisture',0,100),('fan',0,1)]),'range');return r
    except (KeyError,TypeError,ValueError,RuntimeError):return None

# Real TCP packets and SQL inserts. Public mode is opt-in, virtual data only.
def local_pipeline(mode='local',count=12,threshold=27):
    """Real TCP packets and SQL inserts. Public mode is opt-in, virtual data only."""
    rows=samples(count,threshold);run=rows[0]['run'];topic=f'psut/colab/{run}/telemetry';rejected=duplicates=0;start=time.monotonic();received=[]
    with contextlib.closing(sqlite3.connect(':memory:')) as db,endpoint(mode) as addr:
        db.execute('CREATE TABLE environment(seq INTEGER PRIMARY KEY,ts INTEGER,t REAL,rh REAL,soil REAL,fan INTEGER)')
        with MQTT(*addr) as sub,MQTT(*addr) as pub:
            sub.subscribe(topic)
            payloads=[json.dumps(r,allow_nan=False).encode() for r in rows]+[json.dumps(rows[0]).encode(),b'{bad json}']
            # Publish one message at a time and inspect the separate subscriber's receipt.
            for payload in payloads:
                pub.publish(topic,payload);actual_topic,raw=sub.receive();check(actual_topic==topic,'topic isolation failure');check(raw==payload,'unexpected or modified delivery');r=valid_record(raw,run)
                if r is None:rejected+=1;continue
                cur=db.execute('INSERT OR IGNORE INTO environment VALUES(?,?,?,?,?,?)',(r['seq'],r['ts'],r['temperature'],r['humidity'],r['soil_moisture'],r['fan']))
                if not cur.rowcount:duplicates+=1
            # Foreign-topic publication is not part of the subscribed stream.
            pub.publish(topic+'/other',b'not for this subscription')
            # A known final marker proves the next received packet is from the subscribed topic.
            pub.publish(topic,b'{}');actual_topic,raw=sub.receive();check(actual_topic==topic and raw==b'{}','foreign topic leaked');rejected+=1
        db.commit();received=db.execute('SELECT seq,ts,t,rh,soil,fan FROM environment ORDER BY seq').fetchall()
        check(len(received)==count and duplicates==1 and rejected==2,'unexpected conservation counts');check([r[0] for r in received]==list(range(count)),'sequence gap');check(all(a[2]==b['temperature'] and a[5]==b['fan'] for a,b in zip(received,rows)),'SQL readback mismatch')
        mean=db.execute('SELECT AVG(t) FROM environment').fetchone()[0];check(math.isclose(mean,sum(r['temperature'] for r in rows)/count),'mean mismatch')
    return {'schema':'psut-iot-pipeline-v2077','transport':'actual HiveMQ TLS MQTT' if mode=='hivemq' else 'actual loopback MQTT packets / restricted teaching peer','storage':'actual SQLite, not InfluxDB','source':'virtual','topic':topic,'published':count+4,'subscribed_received':count+3,'stored':count,'duplicates':duplicates,'rejected':rejected,'foreign':1,'mean_temperature':mean,'elapsed_s':round(time.monotonic()-start,4),'rows':received,'records':rows}

# Define the reusable operation plot pipeline; keep its logic separate from the trial.
def plot_pipeline(result):
    import matplotlib.pyplot as plt
    rows=result['rows'];x=[a[0] for a in rows]
    fig,ax=plt.subplots(figsize=(8,3.5));ax.plot(x,[a[2] for a in rows],marker='o',label='Queried temperature');ax.set(xlabel='Sequence',ylabel='Temperature (°C)',title='Stored telemetry — '+result['source']);ax.grid(alpha=.25);ax.legend(loc='upper left');other=ax.twinx();other.step(x,[a[5] for a in rows],where='post',linestyle='--',label='Virtual GPIO17');other.set(yticks=[0,1],ylabel='Fan state');fig.tight_layout();plt.show();plt.close(fig)
Ask Dr. Mohammad about this cell
05Instructions · Markdown
## 2. Select the runtime `local` needs no external services. `stack` starts actual vendor binaries, optionally downloaded through signed APT indexes in a disposable Linux runtime. Set `DOWNLOAD_SERVICES=True` in Colab if the binaries are absent. This may require substantial download space. A failed installation, connection or assertion must be investigated; no fallback can produce a service PASS. On a local WSL runtime, use the official installed binaries and leave downloads disabled. Grafana is accessed through its loopback API within the notebook, not a public tunnel or hosted web UI. The process and database are temporary and cleaned up after the trial. Full interactive Grafana UI remains available through the original WSL lab. Public HiveMQ TLS protects transport but does not provide private topics or identity; only generated virtual values are sent. No credentials are published. Vendor setup: [InfluxDB OSS 2](https://docs.influxdata.com/influxdb/v2/install/) · [Telegraf](https://docs.influxdata.com/telegraf/v1/install/) · [Grafana OSS](https://grafana.com/docs/grafana/latest/setup-grafana/installation/debian/) · [HiveMQ public broker](https://www.hivemq.com/mqtt/public-mqtt-broker/).
06Python · executable cell
PYTHON · Code cell
# =====================================================================
# P43 | Code cell 02 | Lab 43 · MQTT → Telegraf → InfluxDB
# Purpose: 2. Select the runtime local needs no external services. stack starts actual vendor binaries, optionally downloaded through signed APT indexes in a disposable Linux runtime. Set DOWNLOAD_SERVICES=True in Colab i
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Set MODE for the next computation or reference condition.
MODE = "local"  # change to "stack" to run genuine services
# Set DOWNLOAD_SERVICES for the next computation or reference condition.
DOWNLOAD_SERVICES = False  # True in a disposable Colab runtime if vendor binaries are absent
# Set COUNT for the next computation or reference condition.
COUNT = 12
# Set THRESHOLD for the next computation or reference condition.
THRESHOLD = 27
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert MODE in ("local", "stack")
Ask Dr. Mohammad about this cell
07Instructions · Markdown
## 3. Real-service installation, health checks and API implementation This code defines the optional stack. APT verifies repository signatures and package hashes; packages are extracted into temporary directories. Versions are reported at execution. No system service or public web server is created.
08Python · executable cell
PYTHON · Code cell
# =====================================================================
# P43 | Code cell 03 | Lab 43 · MQTT → Telegraf → InfluxDB
# Purpose: 3. Real-service installation, health checks and API implementation This code defines the optional stack. APT verifies repository signatures and package hashes; packages are extracted into temporary directories.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
"""Opt-in full service acceptance. No fallback: external errors are visible.
Run in a disposable Linux Colab runtime, or use already installed local binaries.
Requires signed apt packages, InfluxDB OSS 2.x (Flux), Telegraf, Grafana OSS.
"""
import base64, subprocess, tempfile, shutil
from urllib.error import HTTPError, URLError

# Define the reusable operation http; keep its logic separate from the trial.
def http(base,path,body=None,headers=None,method=None):
    h=dict(headers or {})
    if isinstance(body,dict):body=json.dumps(body).encode();h.setdefault('Content-Type','application/json')
    req=Request(base+path,data=body,headers=h,method=method)
    with urlopen(req,timeout=12) as r:return r.status,r.read()

# Define the reusable operation jhttp; keep its logic separate from the trial.
def jhttp(base,path,body=None,headers=None):return json.loads(http(base,path,body,headers)[1])
# Define the reusable operation free port; keep its logic separate from the trial.
def free_port():
    with socket.socket() as s:s.bind(('127.0.0.1',0));return s.getsockname()[1]

# Fetch actual vendor .deb packages via signed apt indexes, extract in scratch space.
def provision_binaries(root,required,download=False):
    """Fetch actual vendor .deb packages via signed apt indexes, extract in scratch space.
    No system-wide services or Docker, no unverified binary installation.
    """
    root=Path(root);out={};packages={'influxd':'influxdb2','telegraf':'telegraf','grafana':'grafana'}
    if not download:
        for name in required:
            candidates=[shutil.which(name)]
            if name=='grafana':candidates+=['/usr/share/grafana/bin/grafana']
            p=next((Path(c).resolve() for c in candidates if c and Path(c).is_file()),None)
            check(p is not None,f'{name} missing: install vendor package or enable DOWNLOAD_SERVICES in disposable Colab');out[name]=p
        return out
    check(os.name=='posix' and shutil.which('apt-get') and shutil.which('gpg') and shutil.which('dpkg-deb'),'Linux apt, gpg and dpkg-deb required')
    root.mkdir(parents=True,exist_ok=True);root.chmod(0o755);(root/'lists/partial').mkdir(parents=True);(root/'packages').mkdir();(root/'etc').mkdir()
    sources=[]
    repos=[('influx','https://repos.influxdata.com/influxdata-archive.key','24C975CBA61A024EE1B631787C3D57159FC2F927','https://repos.influxdata.com/debian')]
    if 'grafana' in required:repos.append(('grafana','https://apt.grafana.com/gpg-full.key','B53AE77BADB630A683046005963FA27710458545','https://apt.grafana.com'))
    for name,url,fpr,repo in repos:
        key=root/'etc'/f'{name}.asc';key.write_bytes(urlopen(url,timeout=30).read())
        fingerprints=subprocess.check_output(['gpg','--batch','--show-keys','--with-colons',str(key)],text=True,stderr=subprocess.DEVNULL)
        check(any(line.startswith('fpr:') and line.split(':')[9]==fpr for line in fingerprints.splitlines()),f'{name} signing key changed: review official installation instructions')
        # APT accepts an ASCII-armored keyring plus an explicit signing fingerprint.
        sources.append(f'deb [signed-by={key},{fpr}] {repo} stable main')
    src=root/'etc/sources.list';src.write_text('\n'.join(sources)+'\n')
    opts=['-o',f'Dir::Etc::sourcelist={src}','-o','Dir::Etc::sourceparts=-','-o',f'Dir::State::lists={root/"lists"}','-o','APT::Get::List-Cleanup=0','-o','Acquire::Retries=1','-o','Acquire::https::Timeout=30','-o','Acquire::AllowInsecureRepositories=false','-o','APT::Get::AllowUnauthenticated=false']
    subprocess.run(['apt-get',*opts,'update'],check=True,timeout=180)
    for name in required:
        dest=root/'packages'/name;dest.mkdir();subprocess.run(['apt-get',*opts,'download',packages[name]],cwd=dest,check=True,timeout=240)
        deb=list(dest.glob('*.deb'));check(len(deb)==1,'expected one signed package');version=subprocess.check_output(['dpkg-deb','-f',str(deb[0]),'Version'],text=True).strip();print(packages[name],version)
        extracted=dest/'extracted';subprocess.run(['dpkg-deb','-x',str(deb[0]),str(extracted)],check=True,timeout=180)
        paths=[p for p in extracted.rglob(name) if p.is_file() and os.access(p,os.X_OK) and not p.is_symlink()];check(bool(paths),name+' executable missing');out[name]=paths[0]
    return out

# Define the reusable operation service; keep its logic separate from the trial.
@contextlib.contextmanager
def service(cmd,root,env=None):
    # Private transient process; no service manager, no public bind, no credential logs exported.
    with open(Path(root)/('process-'+uuid.uuid4().hex+'.txt'),'wb') as log:
        proc=subprocess.Popen([str(c) for c in cmd],stdout=log,stderr=subprocess.STDOUT,env=env)
        try:yield proc
        finally:
            if proc.poll() is None:
                proc.terminate()
                try:proc.wait(timeout=8)
                except subprocess.TimeoutExpired:proc.kill();proc.wait(timeout=5)

# Define the reusable operation await ready; keep its logic separate from the trial.
def await_ready(proc,fn,seconds=45):
    deadline=time.monotonic()+seconds
    while time.monotonic()<deadline:
        check(proc.poll() is None,'service exited before readiness; check dependencies and vendor version')
        try:return fn()
        except (HTTPError,URLError,OSError,ValueError):time.sleep(.5)
    raise RuntimeError('service readiness timeout')

# Define the reusable operation flux for; keep its logic separate from the trial.
def flux_for(run,field):
    check(len(run)==32 and all(c in '0123456789abcdef' for c in run),'bad run id');check(field in ('temperature','humidity','soil_moisture','fan'),'bad field')
    return f'from(bucket: "greenhouse") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "environment" and r.run == "{run}" and r._field == "{field}") |> sort(columns: ["_time"])'

# Define the reusable operation influx values; keep its logic separate from the trial.
def influx_values(base,token,query):
    _,b=http(base,'/api/v2/query?org=psut',{'query':query,'type':'flux'},{'Authorization':'Token '+token,'Accept':'application/csv'})
    # Annotated CSV may contain multiple tables and repeated headers.
    result=[];header=None
    for row in csv.reader(io.StringIO(b.decode())):
        if not row or row[0].startswith('#'):continue
        if '_value' in row and '_time' in row:header=row;continue
        if header and len(row)==len(header) and row[header.index('_value')]:result.append(float(row[header.index('_value')]))
    return result

# Define the reusable operation line protocol; keep its logic separate from the trial.
def line_protocol(r):
    return (f'environment,run={r["run"]},node={r["node"]},source=virtual '
            f'temperature={float(r["temperature"])},humidity={float(r["humidity"])},soil_moisture={float(r["soil_moisture"])},fan={int(r["fan"])}i,seq={int(r["seq"])}i {r["ts"]}')

# Define the reusable operation grafana spec; keep its logic separate from the trial.
def grafana_spec(run):
    ds={'type':'influxdb','uid':'psut-influx'}
    panels=[]
    for i,field in enumerate(('temperature','humidity','soil_moisture','fan')):
        panels.append({'id':i+1,'type':'timeseries','title':field.replace('_',' ').title(),'datasource':ds,'gridPos':{'x':12*(i%2),'y':8*(i//2),'w':12,'h':8},'targets':[{'refId':'A','datasource':ds,'query':flux_for(run,field)}],'fieldConfig':{'defaults':{'unit':'celsius' if field=='temperature' else 'percent' if field!='fan' else 'none'},'overrides':[]}})
    return {'uid':'psut-virtual-iot','title':'PSUT virtual greenhouse','schemaVersion':39,'version':0,'time':{'from':'now-1h','to':'now'},'panels':panels}

# Define the reusable operation telegraf config; keep its logic separate from the trial.
def telegraf_config(topic,base):
    # Credentials are injected through a private environment, not printed or persisted.
    return f'''[agent]
  flush_interval = "1s"
  omit_hostname = true
[[inputs.mqtt_consumer]]
  servers = ["ssl://broker.hivemq.com:8883"]
  topics = ["{topic}"]
  qos = 1
  client_id = "psut-telegraf-{uuid.uuid4().hex[:12]}"
  persistent_session = false
  topic_tag = ""
  data_format = "json"
  name_override = "environment"
  tag_keys = ["run", "node", "source"]
  json_time_key = "ts"
  json_time_format = "unix"
[[outputs.influxdb_v2]]
  urls = ["{base}"]
  token = "${{PSUT_INFLUX_TOKEN}}"
  organization = "psut"
  bucket = "greenhouse"
'''

# Execute genuine service path. Raises on any missing component or mismatch.
def actual_stack(use_telegraf=True,use_grafana=True,download=False,count=12,threshold=27):
    """Execute genuine service path. Raises on any missing component or mismatch.
    Virtual readings only; MQTT topic is unique and public. No secret in payload.
    """
    rows=samples(count,threshold);run=rows[0]['run'];topic=f'psut/colab/{run}/telemetry';expected=[r['temperature'] for r in rows]
    # Separate cache directory permits APT's sandbox user to read signing files.
    with tempfile.TemporaryDirectory(prefix='psut-binaries-') as binary_dir,tempfile.TemporaryDirectory(prefix='psut-private-') as private:
        Path(binary_dir).chmod(0o755);root=Path(private);required=['influxd']+(['telegraf'] if use_telegraf else [])+(['grafana'] if use_grafana else []);bins=provision_binaries(Path(binary_dir)/'vendor',required,download)
        base=f'http://127.0.0.1:{free_port()}';token=secrets.token_hex(32);password=secrets.token_urlsafe(24)
        with contextlib.ExitStack() as stack:
            influx=stack.enter_context(service([bins['influxd'],'--http-bind-address',base.removeprefix('http://'),'--bolt-path',root/'influx.bolt','--engine-path',root/'engine','--reporting-disabled'],root))
            await_ready(influx,lambda:jhttp(base,'/health'))
            jhttp(base,'/api/v2/setup',{'username':'psut','password':password,'org':'psut','bucket':'greenhouse','token':token})
            print('InfluxDB setup and health: OK')
            if use_telegraf:
                cfg=root/'telegraf.conf';cfg.write_text(telegraf_config(topic,base));env=dict(os.environ,PSUT_INFLUX_TOKEN=token)
                tg=stack.enter_context(service([bins['telegraf'],'--config',cfg],root,env));time.sleep(4);check(tg.poll() is None,'Telegraf failed to start')
                # Second subscriber verifies public broker delivery independently of Telegraf.
                with MQTT('broker.hivemq.com',8883,True) as sub,MQTT('broker.hivemq.com',8883,True) as pub:
                    sub.subscribe(topic)
                    for r in rows:
                        payload=json.dumps(r,allow_nan=False).encode();pub.publish(topic,payload);t,b=sub.receive();check(t==topic and b==payload,'MQTT delivery mismatch')
            else:
                status,_=http(base,'/api/v2/write?org=psut&bucket=greenhouse&precision=s','\n'.join(map(line_protocol,rows)).encode(),{'Authorization':'Token '+token,'Content-Type':'text/plain; charset=utf-8'});check(status==204,'write not acknowledged')
            q=flux_for(run,'temperature');deadline=time.monotonic()+35;values=[]
            while time.monotonic()<deadline:
                values=influx_values(base,token,q)
                if len(values)>=count:break
                time.sleep(1)
            check(len(values)==count and all(math.isclose(a,b,abs_tol=1e-6) for a,b in zip(values,expected)),'InfluxDB count/value mismatch; no service PASS')
            observed={'temperature':values}
            for field in ('humidity','soil_moisture','fan'):
                actual_field=influx_values(base,token,flux_for(run,field));check(len(actual_field)==count and all(math.isclose(a,b[field],abs_tol=1e-6) for a,b in zip(actual_field,rows)),field+' readback mismatch');observed[field]=actual_field
            print('InfluxDB actual readback:',len(values),'records in each of four fields')
            dashboard=grafana_spec(run);grafana_count=None
            if use_grafana:
                gf=f'http://127.0.0.1:{free_port()}';gp=bins['grafana'];home=gp.parent.parent if (gp.parent.parent/'conf/defaults.ini').exists() else Path('/usr/share/grafana');check((home/'conf/defaults.ini').is_file(),'Grafana homepath missing')
                provision=root/'provisioning';provision.mkdir();env=dict(os.environ,GF_SERVER_HTTP_ADDR='127.0.0.1',GF_SERVER_HTTP_PORT=gf.split(':')[-1],GF_PATHS_DATA=str(root/'grafana-data'),GF_PATHS_LOGS=str(root/'grafana-logs'),GF_PATHS_PLUGINS=str(root/'grafana-plugins'),GF_PATHS_PROVISIONING=str(provision),GF_SECURITY_ADMIN_USER='psut',GF_SECURITY_ADMIN_PASSWORD=password,GF_AUTH_ANONYMOUS_ENABLED='false',GF_ANALYTICS_REPORTING_ENABLED='false',GF_ANALYTICS_CHECK_FOR_UPDATES='false',GF_PLUGINS_PREINSTALL_AUTO_UPDATE='false')
                gfproc=stack.enter_context(service([gp,'server','--homepath',home],root,env));await_ready(gfproc,lambda:jhttp(gf,'/api/health'),75)
                auth={'Authorization':'Basic '+base64.b64encode(('psut:'+password).encode()).decode()}
                ds={'name':'PSUT InfluxDB','type':'influxdb','uid':'psut-influx','access':'proxy','url':base,'jsonData':{'version':'Flux','organization':'psut','defaultBucket':'greenhouse'},'secureJsonData':{'token':token}}
                jhttp(gf,'/api/datasources',ds,auth);jhttp(gf,'/api/dashboards/db',{'dashboard':dashboard,'overwrite':True},auth)
                saved=jhttp(gf,'/api/dashboards/uid/psut-virtual-iot',headers=auth);check(len(saved['dashboard']['panels'])==4,'dashboard readback failed')
                result=jhttp(gf,'/api/ds/query',{'from':'now-1h','to':'now','queries':[{'refId':'A','datasource':{'type':'influxdb','uid':'psut-influx'},'query':q,'maxDataPoints':1000,'intervalMs':1000}]},auth)
                a=result['results']['A'];check(not a.get('error') and a.get('status',200)==200,'Grafana query error');actual=[]
                for frame in a.get('frames',[]):
                    for i,field in enumerate(frame['schema']['fields']):
                        if field.get('type')=='number':actual.extend(frame['data']['values'][i])
                check(len(actual)==count and all(math.isclose(x,y,abs_tol=1e-6) for x,y in zip(actual,expected)),'Grafana query readback mismatch');grafana_count=len(actual);print('Grafana dashboard and datasource query: OK')
            evidence={'schema':'psut-iot-stack-v2077','transport':'HiveMQ TLS / Telegraf' if use_telegraf else 'InfluxDB HTTP','storage':'actual InfluxDB OSS 2','source':'virtual','run':run,'rows':[[r['seq'],r['ts'],values[i],observed['humidity'][i],observed['soil_moisture'][i],observed['fan'][i]] for i,r in enumerate(rows)],'stored':len(values),'grafana_count':grafana_count,'dashboard':dashboard,'status':'passed'}
        # Write only non-secret evidence; local services are stopped before leaving.
        Path('psut-grafana-dashboard.json').write_text(json.dumps(dashboard,indent=2));Path('psut-stack-evidence.json').write_text(json.dumps(evidence,indent=2));return evidence
Ask Dr. Mohammad about this cell
09Instructions · Markdown
## 4. Execute, inspect actual query results and export evidence Reference: 12 readings, 27°C threshold. Local mode additionally injects a duplicate, malformed payload and foreign-topic message; expect exactly 12 unique stored readings, one duplicate, two invalid subscribed payloads and one isolated foreign publication. Stack mode verifies each field in InfluxDB; Grafana lab also checks actual Grafana data-source query output.
10Python · executable cell
PYTHON · Code cell
# =====================================================================
# P43 | Code cell 04 | Lab 43 · MQTT → Telegraf → InfluxDB
# Purpose: 4. Execute, inspect actual query results and export evidence Reference: 12 readings, 27°C threshold. Local mode additionally injects a duplicate, malformed payload and foreign-topic message; expect exactly 12 u
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
if MODE == "stack":
    result = actual_stack(use_telegraf=True, use_grafana=False, download=DOWNLOAD_SERVICES, count=COUNT, threshold=THRESHOLD)
else:
    result = local_pipeline('local', COUNT, THRESHOLD)
    assert result['stored'] == COUNT and result['duplicates'] == 1 and result['rejected'] == 2
    dashboard = grafana_spec(result['records'][0]['run'])
    # An exportable definition is NOT a running Grafana dashboard.
    Path('psut-grafana-dashboard.json').write_text(json.dumps(dashboard, indent=2))
    Path('psut-stack-evidence.json').write_text(json.dumps(result, indent=2))
print({k:v for k,v in result.items() if k not in ('rows','records','dashboard')})
plot_pipeline(result)
Ask Dr. Mohammad about this cell
11Instructions · Markdown
## 5. Controlled repeat and interpretation The second local trial changes only the control threshold. The virtual temperature sequence should not change, while the fan activity should decrease. This is a software-control investigation, not a calibrated thermal model. Compare delivery and query counts, describe why duplicate suppression matters, and explain why HiveMQ TLS alone does not authenticate the data producer.
12Python · executable cell
PYTHON · Code cell
# =====================================================================
# P43 | Code cell 05 | Lab 43 · MQTT → Telegraf → InfluxDB
# Purpose: 5. Controlled repeat and interpretation The second local trial changes only the control threshold. The virtual temperature sequence should not change, while the fan activity should decrease. This is a software-
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Set low for the next computation or reference condition.
low=local_pipeline("local",COUNT,24)
# Set high for the next computation or reference condition.
high=local_pipeline("local",COUNT,35)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert [r[2] for r in low["rows"]] == [r[2] for r in high["rows"]]
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert sum(r[5] for r in low["rows"]) >= sum(r[5] for r in high["rows"])
print("Fan ON counts:",sum(r[5] for r in low["rows"]),sum(r[5] for r in high["rows"]))
print("LOCAL controlled repeat: PASS; this is independent of live service status")
Ask Dr. Mohammad about this cell
13Instructions · Markdown
## Original portal implementation (reference only) These are the actual laboratory snippets. They are retained for comparison; follow the portal setup for WSL, hardware or services. They are **not** executed by Run all. ```bash source ~/psut-wsl/activate.sh source ~/.config/psut-wsl/mqtt-local.env cd ~/psut-wsl/labs/python/lab43 MESSAGES=5 PERIOD=2 python device_simulator.py ``` ```bash source ~/psut-wsl/activate.sh source ~/.config/psut-wsl/mqtt-hive.env cd ~/psut-wsl/labs/python/lab43 MESSAGES=5 PERIOD=2 python device_simulator.py ``` ```bash source ~/psut-wsl/activate.sh source ~/.config/psut-wsl/mqtt-local.env cd ~/psut-wsl/labs/python/lab43 source ~/.config/psut-wsl/influx.env sleep 5 python my_device_history.py ``` ```bash source ~/psut-wsl/activate.sh source ~/.config/psut-wsl/mqtt-hive.env cd ~/psut-wsl/labs/python/lab43 source ~/.config/psut-wsl/influx.env sleep 5 python my_device_history.py ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- Example 1b: a Python stand-in for the ESP32 greenhouse node # Publishes the same JSON as the ESP32 sketch to the same topic, so you can test # Telegraf + InfluxDB without Wokwi (for example in Google Colab). # Needs: pip install paho-mqtt import json import math import os import time import threading import re import paho.mqtt.client as mqtt BROKER = os.getenv("MQTT_BROKER", "127.0.0.1") # local WSL Mosquitto PORT = int(os.getenv("MQTT_PORT", "1884")) STUDENT_ID = os.getenv("STUDENT_ID", "lab-local") # topic label, not authentication NODE = os.getenv("NODE", "python-sim") # which device this is TOPIC = f"psut/iot/{STUDENT_ID}/greenhouse/{NODE}/telemetry" MESSAGES = int(os.getenv("MESSAGES", "30")) # how many readings to send PERIOD = float(os.getenv("PERIOD", "0.5")) # seconds between readings # ---- The same simulated sensors as Lab 42 (identical numbers every run) def reading(i: int) -> dict: return { "source": "mock", "temperature": round(24.0 + 0.3 * i + 0.4 * math.sin(1.3 * i), 1), "humidity": round(max(0,min(100,72.0 - 0.6 * i + 1.2 * math.sin(0.7 * i))), 1), "soil_moisture": round(max(0,min(100,60.0 - 1.0 * i + 0.8 * math.sin(0.9 * i))), 1), } def main() -> None: if MESSAGES < 1 or PERIOD <= 0: raise ValueError("MESSAGES and PERIOD must be positive") if BROKER.lower() == "broker.hivemq.com" and not re.fullmatch(r"demo-[0-9a-f]{16}", STUDENT_ID): raise SystemExit("Run tools/mqtt_profile.py hive and source the generated profile first") client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) ready = threading.Event() def connected(c,u,f,reason,p): if not reason.is_failure: ready.set() client.on_connect = connected client.connect(BROKER, PORT, keepalive=30) client.loop_start() try: if not ready.wait(10): raise RuntimeError("MQTT CONNACK timeout") for i in range(MESSAGES): payload = json.dumps(reading(i), allow_nan=False) info = client.publish(TOPIC, payload, qos=1, retain=False) info.wait_for_publish(timeout=10) if not info.is_published(): raise RuntimeError("MQTT PUBACK timeout") print(f"{TOPIC} {payload}", flush=True) if i+1 < MESSAGES: time.sleep(PERIOD) finally: client.disconnect(); client.loop_stop() if __name__ == "__main__": main() ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- Example 2: the history of YOUR devices, as stored by Telegraf # pivot() turns the three field rows of each moment into one row with three columns. import os from statistics import mean from influxdb_client import InfluxDBClient URL = os.getenv("INFLUX_URL", "http://localhost:8086") TOKEN = os.environ["INFLUX_TOKEN"] ORG = os.getenv("INFLUX_ORG", "psut") BUCKET = os.getenv("INFLUX_BUCKET", "greenhouse") STUDENT_ID = os.getenv("STUDENT_ID", "lab-local") FLUX = f'''from(bucket: "{BUCKET}") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "environment" and r.student == "{STUDENT_ID}") |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value")''' def main() -> None: with InfluxDBClient(url=URL, token=TOKEN, org=ORG) as client: tables = client.query_api().query(FLUX, org=ORG) rows = [rec.values for table in tables for rec in table.records] # one dict per moment if not rows: raise SystemExit(f"No data for student {STUDENT_ID}: is Telegraf running and your device publishing?") print(f"History of student {STUDENT_ID}, last hour") print(f"{'node':<12}{'readings':>9}{'T min':>8}{'T mean':>8}{'T max':>8}{'last soil':>11}") for node in sorted({r['node'] for r in rows}): mine = sorted((r for r in rows if r['node'] == node), key=lambda r: r['_time']) temps = [r['temperature'] for r in mine] print(f"{node:<12}{len(mine):>9}{min(temps):>8.1f}{mean(temps):>8.2f}{max(temps):>8.1f}" f"{mine[-1]['soil_moisture']:>11.1f}") if __name__ == "__main__": main() ```
14Instructions · Markdown
## Experimental record and discussion Record your selected profile, configuration, actual outputs and assertions, failures, and conclusions. Distinguish software-observed packet/HTTP/SQL behavior, virtual sensor values, and actual hardware measurements. If a live mode is unavailable, record it as blocked. Do not claim a hosted service or physical experiment passed on the basis of the local reference trial. Export your notebook outputs or the generated JSON evidence.
15Instructions · Markdown
## Guided reasoning and evidence A controlled comparison changes one independent input while keeping the other relevant inputs fixed; the dependent variable is the recorded output. Use this lab’s reference condition above. **Independent task:** 2. Change topic to a nonmatching one; restore and disable valid JSON. Compare outcomes. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat. | Trial | Input/configuration | Prediction | Observation | Evidence / limitation | |---|---|---|---|---| | A | Reference | | | | | B | Changed input | | | | | A repeat | Reference | | | | A conclusion is supported only when it cites the recorded values or observed states and explains them with the experiment theory.