Skip to content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Intelligent Edge StudioMachine Learning and Edge AIExperimentsWorkspaces
ENGINEERING WORKSPACE
Home/Engineering Workspaces/Time-series Studio
PSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
P42 · P43 · P44 / data engineering
Supporting engineering workspace

Time-series Studio

Telegraf, InfluxDB 2 and Grafana — from MQTT to stored evidence. Build the pipeline one verified layer at a time.

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 →
Already installed everything in Setup? Skip the installer command for services that are installed and running; continue with their version/status checks and configuration. One-time installation guide →

Choose a data path

Node-RED is a parallel live subscriber, not a mandatory link between Telegraf and InfluxDB. Direct P42 writes bypass MQTT. ThingSpeak is a separate cloud route.

Interactive pipeline and fault laboratory

Model: select a fault, send a sample, and ask Dr. Mohammad to diagnose the failing stage. Actual readback requires Step 15.

Detailed deployment · 16 deployment checkpoints

Use one broker route throughout. Keep A, B and C terminals distinct. Do not paste credentials into the tutor.

01

Prepare the VS Code WSL workspace

Complete the base Setup page first. In Windows VS Code select the green remote indicator → Connect to WSL. Open ~/psut-wsl as the folder; Terminal → New Terminal. Commands below run in Ubuntu Bash unless marked otherwise. Do not enter them in the Python REPL.

WSL · Bash
cd ~/psut-wsl
source activate.sh
python --version
python -m pip check
ps -p 1 -o comm=
✓ Expected: systemd should be printed for the service-based workflow.
Expected result for each action (5)
  1. cd ~/psut-wslNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
  2. source activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
  3. python --versionThe installed version is printed. For this toolkit InfluxDB must be 2.x; version numbers otherwise depend on installation.
  4. python -m pip checkNo broken requirements found. Resolve any reported conflicts before continuing.
  5. ps -p 1 -o comm=systemd should be printed for the service-based workflow.
Checkpoint Python version is printed; pip reports no broken requirements; PID 1 is systemd.
02

Install InfluxDB 2 and Telegraf

Run in the WSL terminal. This uses the optional installer, not InfluxDB 3. It installs Telegraf but stops the packaged default agent so the lab can use its own foreground configuration. Re-running will reuse the virtual environment; verify versions before proceeding.

WSL · Bash
bash ~/psut-wsl/setup_wsl.sh --influx
influxd version
telegraf version
systemctl is-active influxdb
curl -fsS http://127.0.0.1:8086/health
✓ Expected: InfluxDB health JSON includes status pass when the service is healthy; this does not verify bucket permissions or stored data.
Expected result for each action (5)
  1. bash ~/psut-wsl/setup_wsl.sh --influxThe installer completes and returns to the prompt. Verify the selected services and run the toolkit self-test; package logs may vary.
  2. influxd versionThe installed version is printed. For this toolkit InfluxDB must be 2.x; version numbers otherwise depend on installation.
  3. telegraf versionThe installed version is printed. For this toolkit InfluxDB must be 2.x; version numbers otherwise depend on installation.
  4. systemctl is-active influxdbAn active line is expected for each required running service; inactive/failed requires investigation.
  5. curl -fsS http://127.0.0.1:8086/healthInfluxDB health JSON includes status pass when the service is healthy; this does not verify bucket permissions or stored data.
Checkpoint InfluxDB 2.x, active service, health status pass. Telegraf version prints; do not expect its default service to be active.
03

Create the organization and bucket

Open http://localhost:8086 in the Windows browser. On a fresh instance choose Get Started, username and unique password, Initial Organization = psut, Initial Bucket = greenhouse; continue to the UI. On an existing instance sign in and use Load Data → Buckets to verify greenhouse in organization psut. Do not reset an existing database. Keep bucket retention long enough for the lab (e.g. 7 days).

Checkpoint The organization is psut and bucket greenhouse exists. Menu labels may differ slightly by InfluxDB 2 release.
04

Generate a read/write lab token

In InfluxDB select Load Data → API Tokens → Generate API Token → Custom API Token. Name it PSUT lab writer; give read and write permission only to greenhouse. Copy the token privately when created; paste into the hidden prompt below. Existing saved tokens may be reused if valid.

WSL · Bash
mkdir -p ~/.config/psut-wsl
chmod 700 ~/.config/psut-wsl
read -rsp "InfluxDB greenhouse read/write token: " token; echo
(umask 077; printf 'export INFLUX_TOKEN=%q\n' "$token" > ~/.config/psut-wsl/influx.env)
unset token
chmod 600 ~/.config/psut-wsl/influx.env
source ~/.config/psut-wsl/influx.env
test -n "${INFLUX_TOKEN:-}" && echo Token-loaded
✓ Expected: The success message prints only if the variable is nonempty. This does not establish that the credential is valid.
Expected result for each action (8)
  1. mkdir -p ~/.config/psut-wslNormally silent. The requested directory exists afterward; verify with ls -d.
  2. chmod 700 ~/.config/psut-wslNormally silent. Verify with ls -l or stat; a private directory should be 700 and a private credential file 600 where specified.
  3. read -rsp "InfluxDB greenhouse read/write token: " token; echoA secret-entry prompt appears; typing is not echoed. Enter only your local lab credential. Nothing should expose its value.
  4. (umask 077; printf 'export INFLUX_TOKEN=%q\n' "$token" > ~/.config/psut-wsl/influx.env)The private token configuration file is written without displaying its contents. Verify permissions are 600.
  5. unset tokenUsually silent. The named variable is removed from the current shell, not from existing files or external services.
  6. chmod 600 ~/.config/psut-wsl/influx.envNormally silent. Verify with ls -l or stat; a private directory should be 700 and a private credential file 600 where specified.
  7. 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.
  8. test -n "${INFLUX_TOKEN:-}" && echo Token-loadedThe success message prints only if the variable is nonempty. This does not establish that the credential is valid.
Checkpoint Token-loaded prints without showing token. Treat this file as a secret; do not upload it.
05

P42 — prove storage before MQTT

Run the direct Python writer. It generates 30 mathematical sensor readings tagged source=mock and writes them into the environment measurement, node=pi-01. Then run the controller. This tests the database independently of Telegraf and MQTT.

WSL · Bash
source ~/psut-wsl/activate.sh
source ~/.config/psut-wsl/influx.env
cd ~/psut-wsl/labs/python/lab42
python greenhouse_node.py
python greenhouse_controller.py
✓ Expected: Controller decisions based on stored greenhouse history are printed; the exact counts depend on existing data.
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/influx.envThe token becomes available to child processes without being printed. Check only whether it is set, then test authorized access.
  3. cd ~/psut-wsl/labs/python/lab42Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
  4. python greenhouse_node.pyThe program writes 30 historical points using the configured token and bucket; inspect errors and query history separately.
  5. python greenhouse_controller.pyController decisions based on stored greenhouse history are printed; the exact counts depend on existing data.
Checkpoint Wrote 30 points; the controller prints decisions. A repeat in the same five-minute interval may overwrite identical timestamps.
06

Explore the stored data in InfluxDB

In the browser open Data Explorer → Script Editor (or Flux script editor). Paste this Flux query, not in Bash. Click Submit. It selects P42’s pi-01 values within one hour; switch the table/graph view to see values and timestamps.

InfluxDB Data Explorer · Flux
from(bucket: "greenhouse")
  |> range(start: -1h)
  |> filter(fn: (r) => r._measurement == "environment" and r.node == "pi-01")
  |> filter(fn: (r) => r._field == "temperature" or r._field == "humidity" or r._field == "soil_moisture")
✓ Expected: Run the whole query in InfluxDB Data Explorer. Matching field records appear if data and permissions are available; an empty table requires checking the time range and filters.
Checkpoint Three sensor fields and timestamps appear. If empty, verify the previous write, bucket and time range.
07

Prepare broker and Node-RED (P43)

Choose one route below. For Node-RED first follow the MQTT & Node-RED integration center, import its generated profile flow once and Deploy. Node-RED is an independent subscriber, so it can show data without storage. Local Mosquitto uses 1884; HiveMQ public uses 1883 and anonymous simulated sessions only.

WSL · Bash
python3 ~/psut-wsl/tools/mqtt_profile.py local
source ~/.config/psut-wsl/mqtt-local.env
printf 'Broker: %s:%s\nTopic: %s\n' "$MQTT_HOST" "$MQTT_PORT" "$GREENHOUSE_TOPIC"
✓ Expected: The selected broker address, port and topic are printed. They must match the chosen profile, without revealing credentials.
Expected result for each action (3)
  1. python3 ~/psut-wsl/tools/mqtt_profile.py localThe requested broker profile and matching Node-RED flow are generated under ~/.config/psut-wsl; use the same profile/session in all terminals.
  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. printf 'Broker: %s:%s\nTopic: %s\n' "$MQTT_HOST" "$MQTT_PORT" "$GREENHOUSE_TOPIC"The selected broker address, port and topic are printed. They must match the chosen profile, without revealing credentials.
WSL · Bash
python3 ~/psut-wsl/tools/mqtt_profile.py hive
source ~/.config/psut-wsl/mqtt-hive.env
printf 'Broker: %s:%s\nTopic: %s\n' "$MQTT_HOST" "$MQTT_PORT" "$GREENHOUSE_TOPIC"
✓ Expected: The selected broker address, port and topic are printed. They must match the chosen profile, without revealing credentials.
Expected result for each action (3)
  1. python3 ~/psut-wsl/tools/mqtt_profile.py hiveThe requested broker profile and matching Node-RED flow are generated under ~/.config/psut-wsl; use the same profile/session in all terminals.
  2. source ~/.config/psut-wsl/mqtt-hive.envThe public demo profile is loaded silently. Verify broker.hivemq.com:1883 and the generated demo session topic; use fictional data only.
  3. printf 'Broker: %s:%s\nTopic: %s\n' "$MQTT_HOST" "$MQTT_PORT" "$GREENHOUSE_TOPIC"The selected broker address, port and topic are printed. They must match the chosen profile, without revealing credentials.
Checkpoint Host/port and greenhouse wildcard match selected route. Node-RED input is connected if using it.
08

Terminal A — verify MQTT delivery

Open a second WSL Bash terminal in VS Code using Terminal → New Terminal. Source the selected profile; leave this subscriber open. The + wildcard matches any device within your session. A waiting blank screen is normal before publication.

WSL · Bash
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 (2)
  1. 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.
  2. 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.
WSL · Bash
source ~/.config/psut-wsl/mqtt-hive.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 (2)
  1. source ~/.config/psut-wsl/mqtt-hive.envThe public demo profile is loaded silently. Verify broker.hivemq.com:1883 and the generated demo session topic; use fictional data only.
  2. 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 Subscriber stays open; after Step 10 it prints exact topics and JSON.
09

Terminal B — run Telegraf with the lab config

Open a separate WSL Bash terminal. Source both configuration files before launching Telegraf. Inspect telegraf.conf: inputs.mqtt_consumer subscribes to the session, JSON v2 converts fields to floats, topic parsing creates student/node tags, outputs.influxdb_v2 writes to greenhouse. Keep this process running. Do not start a second copy or the default service.

WSL · Bash
source ~/psut-wsl/activate.sh
source ~/.config/psut-wsl/mqtt-local.env
source ~/.config/psut-wsl/influx.env
cd ~/psut-wsl/labs/python/lab43
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. 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.
  4. 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.
  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.
WSL · Bash
source ~/psut-wsl/activate.sh
source ~/.config/psut-wsl/mqtt-hive.env
source ~/.config/psut-wsl/influx.env
cd ~/psut-wsl/labs/python/lab43
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-hive.envThe public demo profile is loaded silently. Verify broker.hivemq.com:1883 and the generated demo session topic; use fictional data only.
  3. 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.
  4. 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.
  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 No MQTT connection, JSON parser or InfluxDB write errors; consumer is waiting for readings.
10

Terminal C — publish five known samples

Open another WSL Bash terminal. Test Python before Wokwi. The simulator publishes temperature, humidity and soil_moisture on the greenhouse topic and checks QoS 1 acknowledgement. Keep terminals A and B running. Wait for the five messages and flush interval before querying.

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.
WSL · 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
✓ 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-hive.envThe public demo profile is loaded silently. Verify broker.hivemq.com:1883 and the generated demo session topic; use fictional data only.
  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 JSON messages print in publisher and subscriber; Node-RED python-sim appears if deployed. PUBACK alone does not prove storage.
11

Terminal C — query stored P43 history

After the publisher finishes, source the InfluxDB token and selected profile in Terminal C. The script filters by the exact current session student tag, pivots fields into rows, and prints per-node statistics. P42 direct points do not contain the student tag and will not appear in this query.

WSL · Bash
source ~/psut-wsl/activate.sh
source ~/.config/psut-wsl/mqtt-local.env
source ~/.config/psut-wsl/influx.env
cd ~/psut-wsl/labs/python/lab43
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. 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.
  4. 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.
  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.
WSL · Bash
source ~/psut-wsl/activate.sh
source ~/.config/psut-wsl/mqtt-hive.env
source ~/.config/psut-wsl/influx.env
cd ~/psut-wsl/labs/python/lab43
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-hive.envThe public demo profile is loaded silently. Verify broker.hivemq.com:1883 and the generated demo session topic; use fictional data only.
  3. 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.
  4. 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.
  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 python-sim appears with recent readings. Previous same-session readings may also be included. If no data, inspect Telegraf log before changing Grafana.
12

Optional Wokwi ESP32 source

Use P43 steps 5–7: open the Windows-extracted esp32-greenhouse project in a local VS Code window, not the Remote WSL workspace. Run mqtt_profile.py for your route, copy the printed BROKER, BROKER_PORT and STUDENT_ID into src/main.cpp. Local route needs Wokwi private gateway and Windows-to-WSL TCP 1884 reachability. PlatformIO Build, then Wokwi: Start Simulator; change sensor controls, wait ten seconds. Keep A/B running. HiveMQ route does not need local forwarding. Wokwi plan/license may be needed.

Checkpoint Terminal A receives esp32-01 data; repeat Step 11 and verify esp32-01 in history.
13

Install and provision Grafana (P44)

Back in a WSL terminal install Grafana. Open InfluxDB and create a SECOND custom API token with READ permission only on greenhouse, named PSUT Grafana reader. Paste into the hidden prompt. The supplied provisioning script installs the Flux datasource, dashboard and root-only environment file, then restarts Grafana. Do not use the writer token here.

WSL · Bash
bash ~/psut-wsl/setup_wsl.sh --grafana
cd ~/psut-wsl/labs/python/lab44
read -rsp "InfluxDB read-only token: " INFLUX_READ_TOKEN; echo
export INFLUX_READ_TOKEN
bash provision.sh
unset INFLUX_READ_TOKEN
curl -fsS http://127.0.0.1:3000/api/health
✓ Expected: Grafana health JSON reports database ok when healthy; datasource queries still require independent verification.
Expected result for each action (7)
  1. bash ~/psut-wsl/setup_wsl.sh --grafanaThe installer completes and returns to the prompt. Verify the selected services and run the toolkit self-test; package logs may vary.
  2. cd ~/psut-wsl/labs/python/lab44Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
  3. read -rsp "InfluxDB read-only token: " INFLUX_READ_TOKEN; echoA secret-entry prompt appears; typing is not echoed. Enter only your local lab credential. Nothing should expose its value.
  4. export INFLUX_READ_TOKENUsually silent. The variable is inherited by child processes launched from this terminal; never print a secret to verify it.
  5. bash provision.shGrafana provisioning completes and restarts the service; check the health endpoint and datasource query.
  6. unset INFLUX_READ_TOKENUsually silent. The named variable is removed from the current shell, not from existing files or external services.
  7. curl -fsS http://127.0.0.1:3000/api/healthGrafana health JSON reports database ok when healthy; datasource queries still require independent verification.
Checkpoint Grafana health shows database ok. This does not yet prove the datasource query succeeds.
14

Open and verify the Grafana dashboard

Open http://localhost:3000 in Windows; fresh install usually admin/admin, change password at first login. Connections → Data sources → InfluxDB greenhouse: verify URL http://localhost:8086, Flux, organization psut, default bucket greenhouse; use Save & test if the provisioned UI permits it. Open Dashboards → PSUT IoT → Greenhouse or direct dashboard link. Select Last 1 hour, choose pi-01 or python-sim/esp32-01, refresh. If provisioned datasource is read-only in the UI, inspect Explore or dashboard queries instead. Grafana uses node filter, not per-session authorization; use a private local database only.

Checkpoint Stats and time-series panels show stored measurements for the chosen node; compare timestamps to Data Explorer. Node-RED and Grafana may display different time windows.
15

Optional — actual read-only website preview

The browser model above does not talk to services by default. For real readback, start the supplied local-only helper from WSL. It asks for the extracted Version 4 website folder (Windows path via /mnt/c) and a greenhouse READ-ONLY token. Open http://localhost:8765/analytics.html and choose device → Connect read-only preview. For HiveMQ source mqtt-hive.env rather than mqtt-local.env. The helper is single-user and loopback-only, no authentication; do not expose or forward it.

WSL · Bash
source ~/.config/psut-wsl/mqtt-local.env
read -rp "Full WSL path to extracted V4 website folder: " SITE
python3 ~/psut-wsl/tools/analytics_preview.py --site-root "$SITE" --session "$STUDENT_ID"
✓ Expected: The local preview server starts on port 8765 after local configuration. Keep the terminal open and verify its page in the browser.
Expected result for each action (3)
  1. 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.
  2. read -rp "Full WSL path to extracted V4 website folder: " SITEThe shell prompts for the requested value and waits for Enter. Use the actual channel ID or path, not an example placeholder.
  3. python3 ~/psut-wsl/tools/analytics_preview.py --site-root "$SITE" --session "$STUDENT_ID"The local preview server starts on port 8765 after local configuration. Keep the terminal open and verify its page in the browser.
WSL · Bash
source ~/.config/psut-wsl/mqtt-hive.env
read -rp "Full WSL path to extracted V4 website folder: " SITE
python3 ~/psut-wsl/tools/analytics_preview.py --site-root "$SITE" --session "$STUDENT_ID"
✓ Expected: The local preview server starts on port 8765 after local configuration. Keep the terminal open and verify its page in the browser.
Expected result for each action (3)
  1. source ~/.config/psut-wsl/mqtt-hive.envThe public demo profile is loaded silently. Verify broker.hivemq.com:1883 and the generated demo session topic; use fictional data only.
  2. read -rp "Full WSL path to extracted V4 website folder: " SITEThe shell prompts for the requested value and waits for Enter. Use the actual channel ID or path, not an example placeholder.
  3. python3 ~/psut-wsl/tools/analytics_preview.py --site-root "$SITE" --session "$STUDENT_ID"The local preview server starts on port 8765 after local configuration. Keep the terminal open and verify its page in the browser.
Checkpoint The local helper prints the URL. Readback shows actual field records or an explicit no-data/error state; it never silently substitutes simulated values. Ctrl+C stops helper.
16

Close the experiment and capture evidence

Save screenshots of subscriber output, Telegraf log without secrets, InfluxDB Data Explorer and Grafana/Node-RED. Stop Wokwi and the foreground subscriber, Telegraf, live publisher and preview server with Ctrl+C in their own terminals. Database and Grafana can remain running for later labs. Run the local offline checks below.

WSL · Bash
python3 ~/psut-wsl/tools/test_static.py
python3 ~/psut-wsl/tools/test_analytics_preview.py
bash ~/psut-wsl/tools/selftest.sh
✓ Expected: The toolkit reports checks for the installed components. Review any FAIL or unavailable optional service before continuing.
Expected result for each action (3)
  1. python3 ~/psut-wsl/tools/test_static.pyThe corresponding test program reports its checks and returns; investigate any failed assertion or error.
  2. python3 ~/psut-wsl/tools/test_analytics_preview.pyThe local preview server starts on port 8765 after local configuration. Keep the terminal open and verify its page in the browser.
  3. bash ~/psut-wsl/tools/selftest.shThe toolkit reports checks for the installed components. Review any FAIL or unavailable optional service before continuing.
Checkpoint No core failures. Optional service availability is separate from end-to-end ingestion; actual stored points are the decisive evidence.

Actual pipeline configuration and source

labs/python/lab42/greenhouse_node.pyDownload source
Source file · inspect, do not paste in Bash
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Example 1: smart greenhouse sensor node → InfluxDB 2 (time-series database)
# The Raspberry Pi node reads temperature, humidity and soil moisture and stores
# every reading as a time-stamped point in the InfluxDB bucket "greenhouse".
# The sensors are simulated (same numbers every run), so the program runs in
# Google Colab or on a laptop. Needs:  pip install influxdb-client

import math                                     # sin() gives the readings a natural wobble
import os                                       # read the connection settings from the environment
import time                                     # sleep() between live samples
from datetime import datetime, timedelta, timezone

from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import SYNCHRONOUS


# ---- Connection settings: where InfluxDB runs and who we are
# Never hard-code a real token in a shared file: set INFLUX_TOKEN in the environment.
URL = os.getenv("INFLUX_URL", "http://localhost:8086")      # InfluxDB HTTP API
TOKEN = os.environ["INFLUX_TOKEN"]  # API token with write access
ORG = os.getenv("INFLUX_ORG", "psut")                       # organisation (workspace)
BUCKET = os.getenv("INFLUX_BUCKET", "greenhouse")           # bucket = database + retention


# ---- Who this node is: these become TAGS (indexed text that describes the data)
SITE = "psut-greenhouse"                        # which greenhouse
NODE = "pi-01"                                  # which Raspberry Pi
ZONE = "A"                                      # which growing zone

HISTORY_MINUTES = 30                            # simulate the last 30 minutes, one reading per minute
LIVE = False                                    # True on the real Pi: keep sampling forever
LIVE_PERIOD = 60                                # seconds between live readings


# ---- Simulated sensors: a warming afternoon and slowly drying soil
class MockSensors:
    """Stand-in for a DHT22 (temperature, humidity) and a soil-moisture probe.

    On a real Pi, read() would call the sensor libraries instead. The numbers
    follow a fixed formula, so every run (and every student) sees the same data.
    """

    def __init__(self) -> None:
        self.i = 0                              # sample counter (minutes since the start)

    def read(self) -> dict:
        """Return one reading: temperature in °C, humidity and soil moisture in %."""
        i = self.i
        self.i += 1
        return {
            "temperature": round(24.0 + 0.3 * i + 0.4 * math.sin(1.3 * i), 1),   # 24 → 33 °C
            "humidity": round(72.0 - 0.6 * i + 1.2 * math.sin(0.7 * i), 1),      # air dries out
            "soil_moisture": round(60.0 - 1.0 * i + 0.8 * math.sin(0.9 * i), 1), # 60 → 31 %
        }


# ---- One reading → one InfluxDB point (measurement + tags + fields + timestamp)
def make_point(reading: dict, when: datetime) -> Point:
    """Build the point that InfluxDB stores for one reading."""
    return (
        Point("environment")                    # measurement: like a table name
        .tag("site", SITE)                      # tags: indexed, used in filters and group by
        .tag("node", NODE)
        .tag("zone", ZONE)
        .tag("source", "mock")
        .field("temperature", reading["temperature"])        # fields: the measured values
        .field("humidity", reading["humidity"])
        .field("soil_moisture", reading["soil_moisture"])
        .time(when, WritePrecision.S)           # timestamp, stored with 1-second precision
    )


# ---- Main program: connect, write 30 minutes of history, then (optionally) live data
def main() -> None:
    with InfluxDBClient(url=URL, token=TOKEN, org=ORG) as client:
        if not client.ping():                   # GET /ping: is the server up?
            raise SystemExit(f"InfluxDB is not reachable at {URL}")
        print(f"Connected to InfluxDB at {URL}")
        write_api = client.write_api(write_options=SYNCHRONOUS)   # write now and wait for "OK"
        sensors = MockSensors()

        # ---- History: 30 readings, one per minute, ending at the last 5-minute mark
        now = int(time.time())
        end = datetime.fromtimestamp(now - now % 300, tz=timezone.utc)   # e.g. 10:35:00
        start = end - timedelta(minutes=HISTORY_MINUTES)                 # e.g. 10:05:00
        points = []
        for k in range(HISTORY_MINUTES):
            reading = sensors.read()
            points.append(make_point(reading, start + timedelta(minutes=k)))
            if k < 3 or k == HISTORY_MINUTES - 1:   # print the first three and the last
                print(f"t-{HISTORY_MINUTES - k:02d} min  T={reading['temperature']:4.1f} °C  "
                      f"RH={reading['humidity']:4.1f} %  soil={reading['soil_moisture']:4.1f} %")
            elif k == 3:
                print("   ...")

        # ---- What actually travels over HTTP: InfluxDB line protocol
        line = points[0].to_line_protocol()     # measurement,tags fields timestamp
        print("Line protocol of the first point (timestamp hidden):")
        print("  " + line.rsplit(" ", 1)[0] + " <unix-seconds>")

        write_api.write(bucket=BUCKET, org=ORG, record=points)   # one HTTP request, 30 points
        print(f"Wrote {len(points)} points to bucket '{BUCKET}'")

        # ---- Live mode (real Pi): one reading per LIVE_PERIOD seconds, time = now
        while LIVE:
            reading = sensors.read()
            write_api.write(bucket=BUCKET, org=ORG,
                            record=make_point(reading, datetime.now(timezone.utc)))
            print(f"live  T={reading['temperature']:4.1f} °C  soil={reading['soil_moisture']:4.1f} %")
            time.sleep(LIVE_PERIOD)


if __name__ == "__main__":
    main()
labs/python/lab42/greenhouse_controller.pyDownload source
Source file · inspect, do not paste in Bash
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Example 2: greenhouse controller — query InfluxDB, decide, drive GPIO, log
# Reads the data that Example 1 stored, asks InfluxDB questions in Flux,
# switches a fan (GPIO17) and a water pump (GPIO27) with hysteresis rules,
# and writes every decision back to InfluxDB as an "actuator" point.
# The GPIO is the mock from Lab 41, so it runs in Google Colab too.

import os
from datetime import datetime, timezone

from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS


# ---- Connection settings (same as the sensor node)
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")
SITE, NODE = "psut-greenhouse", "pi-01"

# ---- Control rules with hysteresis: two thresholds, so the relay does not chatter
FAN_ON_ABOVE, FAN_OFF_BELOW = 30.0, 28.0        # °C, mean of the last 10 readings
PUMP_ON_BELOW, PUMP_OFF_ABOVE = 35.0, 45.0      # % soil moisture, latest reading
SMOOTHING = 10                                  # readings averaged for the fan rule


# ---- Mock RPi.GPIO and the LED class from Lab 41 (an LED stands in for each relay)
class MockGPIO:
    """Stand-in for RPi.GPIO: prints every call instead of driving hardware."""
    BCM, OUT, HIGH, LOW = 'BCM', 'OUT', True, False

    @staticmethod
    def setmode(mode):
        print(f"GPIO mode set to {mode}")

    @staticmethod
    def setup(pin, mode):
        print(f"GPIO pin {pin} set up as {mode}")

    @staticmethod
    def output(pin, state):
        print(f"GPIO pin {pin} set to {'HIGH' if state else 'LOW'}")

    @staticmethod
    def cleanup():
        print("GPIO cleanup")


GPIO = MockGPIO                                 # on a real Pi: import RPi.GPIO as GPIO


class LED:
    """One output on one GPIO pin (here: the indicator LED of a relay)."""

    def __init__(self, pin: int) -> None:
        self.pin = pin
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.pin, GPIO.OUT)
        self.state = GPIO.LOW
        GPIO.output(self.pin, self.state)       # start OFF

    def turn_on(self) -> None:
        self.state = GPIO.HIGH
        GPIO.output(self.pin, self.state)

    def turn_off(self) -> None:
        self.state = GPIO.LOW
        GPIO.output(self.pin, self.state)

    @staticmethod
    def check_pin_availability(pin: int) -> bool:
        return 1 <= pin <= 40

    @classmethod
    def create_led(cls, pin: int) -> 'LED':
        if cls.check_pin_availability(pin):
            return cls(pin)
        raise ValueError("GPIO pin is not available")

    def cleanup(self) -> None:
        GPIO.cleanup()


# ---- Flux queries: each one is a pipeline of functions joined by |>
def flux_latest(field: str) -> str:
    """The newest value of one field."""
    return f'''from(bucket: "{BUCKET}")
  |> range(start: -1h)
  |> filter(fn: (r) => r._measurement == "environment" and r._field == "{field}")
  |> filter(fn: (r) => r.node == "{NODE}")
  |> last()'''


def flux_recent_mean(field: str, n: int) -> str:
    """The mean of the newest n values of one field (smooths sensor noise)."""
    return f'''from(bucket: "{BUCKET}")
  |> range(start: -1h)
  |> filter(fn: (r) => r._measurement == "environment" and r._field == "{field}")
  |> filter(fn: (r) => r.node == "{NODE}")
  |> tail(n: {n})
  |> mean()'''


def flux_windows(field: str) -> str:
    """One mean per 5-minute window (what a dashboard graph shows)."""
    return f'''from(bucket: "{BUCKET}")
  |> range(start: -1h)
  |> filter(fn: (r) => r._measurement == "environment" and r._field == "{field}")
  |> filter(fn: (r) => r.node == "{NODE}")
  |> aggregateWindow(every: 5m, fn: mean, createEmpty: false)'''


def flux_actuator_state() -> str:
    """The last logged state of every actuator (one table per device tag)."""
    return f'''from(bucket: "{BUCKET}")
  |> range(start: -1h)
  |> filter(fn: (r) => r._measurement == "actuator" and r._field == "state")
  |> filter(fn: (r) => r.node == "{NODE}")
  |> last()'''


def first_value(query_api, flux: str):
    """Run a query and return the first value, or None if there is no data."""
    tables = query_api.query(flux, org=ORG)
    if not tables or not tables[0].records:
        return None
    return tables[0].records[0].get_value()


# ---- Hysteresis: switch on above one threshold, off below another, else keep
def decide(is_on: bool, value: float, on_when, off_when) -> bool:
    if not is_on and on_when(value):
        return True
    if is_on and off_when(value):
        return False
    return is_on


# ---- Main program
def main() -> None:
    fan = pump = None
    try:
        with InfluxDBClient(url=URL, token=TOKEN, org=ORG) as client:
            query_api = client.query_api()
            write_api = client.write_api(write_options=SYNCHRONOUS)

            # ---- 1. What is happening now?
            t = first_value(query_api, flux_latest("temperature"))
            h = first_value(query_api, flux_latest("humidity"))
            s = first_value(query_api, flux_latest("soil_moisture"))
            if t is None:
                raise SystemExit("No data yet: run Example 1 (greenhouse_node.py) first.")
            print(f"Latest reading: T={t:.1f} °C  RH={h:.1f} %  soil={s:.1f} %")

            # ---- 2. The trend: one mean per 5-minute window, oldest first
            records = query_api.query(flux_windows("temperature"), org=ORG)[0].records
            print("Temperature, 5-minute means (oldest first):")
            for number, rec in enumerate(records, start=1):
                print(f"  window {number}  {rec.get_value():5.2f} °C")   # rec.get_time() = window end

            # ---- 3. Smoothed value for the fan rule
            t_mean = first_value(query_api, flux_recent_mean("temperature", SMOOTHING))
            print(f"Mean of the last {SMOOTHING} temperatures: {t_mean:.2f} °C")

            # ---- 4. Previous actuator states are stored in InfluxDB too (OFF if none yet)
            previous = {"fan": False, "pump": False}
            for table in query_api.query(flux_actuator_state(), org=ORG):
                for rec in table.records:
                    previous[rec.values["device"]] = rec.get_value() == 1

            # ---- 5. Decide with hysteresis
            fan_on = decide(previous["fan"], t_mean,
                            lambda v: v > FAN_ON_ABOVE, lambda v: v < FAN_OFF_BELOW)
            pump_on = decide(previous["pump"], s,
                             lambda v: v < PUMP_ON_BELOW, lambda v: v > PUMP_OFF_ABOVE)

            # ---- 6. Act: drive the GPIO pins (fan relay GPIO17, pump relay GPIO27)
            fan = LED.create_led(17)
            pump = LED.create_led(27)
            fan.turn_on() if fan_on else fan.turn_off()
            pump.turn_on() if pump_on else pump.turn_off()
            print(f"Fan  {'ON ' if fan_on else 'OFF'}  (mean {t_mean:.2f} °C, on above {FAN_ON_ABOVE}, off below {FAN_OFF_BELOW})")
            print(f"Pump {'ON ' if pump_on else 'OFF'}  (soil {s:.1f} %, on below {PUMP_ON_BELOW}, off above {PUMP_OFF_ABOVE})")

            # ---- 7. Log the decisions: actuator points, state as an integer 0/1
            now = datetime.now(timezone.utc)
            reasons = {"fan": f"mean {t_mean:.2f} C", "pump": f"soil {s:.1f} %"}
            events = [
                Point("actuator").tag("site", SITE).tag("node", NODE).tag("device", device)
                .field("state", int(on)).field("reason", reasons[device]).time(now)
                for device, on in (("fan", fan_on), ("pump", pump_on))
            ]
            write_api.write(bucket=BUCKET, org=ORG, record=events)
            print(f"Logged {len(events)} actuator events")

            # ---- 8. Read them back: the database now holds the control history
            stored = {t.records[0].values["device"]: t.records[0].get_value()
                      for t in query_api.query(flux_actuator_state(), org=ORG)}
            for device in sorted(stored):
                print(f"  stored: {device:<4} state={stored[device]}")
    finally:
        if fan is not None:                     # release the pins whatever happened
            fan.cleanup()


if __name__ == "__main__":
    main()
labs/python/lab43/telegraf.confDownload source
Source file · inspect, do not paste in Bash
# ------------------------------------------------------------
# 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"
labs/python/lab43/device_simulator.pyDownload source
Source file · inspect, do not paste in Bash
# ------------------------------------------------------------
# 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/my_device_history.pyDownload source
Source file · inspect, do not paste in Bash
# ------------------------------------------------------------
# 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/lab44/influxdb.yamlDownload source
Source file · inspect, do not paste in Bash
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Grafana data source: InfluxDB 2 with the Flux query language
# Grafana reads this file at start-up. $INFLUX_TOKEN comes from the environment.
apiVersion: 1
datasources:
  - name: InfluxDB greenhouse
    uid: influx-greenhouse            # dashboards refer to the data source by this uid
    type: influxdb
    access: proxy                     # Grafana's server queries InfluxDB, not the browser
    url: http://localhost:8086
    isDefault: true
    jsonData:
      version: Flux
      organization: psut
      defaultBucket: greenhouse
    secureJsonData:
      token: $INFLUX_TOKEN            # stored encrypted, never sent to the browser
labs/python/lab44/provision.shDownload source
Source file · inspect, do not paste in Bash
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
: "${INFLUX_READ_TOKEN:?Export INFLUX_READ_TOKEN first}"
[[ "$INFLUX_READ_TOKEN" =~ ^[A-Za-z0-9_=-]+$ ]] || { echo 'Unexpected token format'; exit 1; }
sudo install -m 0644 influxdb.yaml /etc/grafana/provisioning/datasources/influxdb.yaml
sudo install -m 0644 greenhouse-provider.yaml /etc/grafana/provisioning/dashboards/greenhouse-provider.yaml
sudo install -d /var/lib/grafana/dashboards
sudo install -m 0644 greenhouse.json /var/lib/grafana/dashboards/greenhouse.json
sudo install -d -m 0755 /etc/systemd/system/grafana-server.service.d
sudo install -m 0600 /dev/null /etc/grafana/psut-token.env
printf 'INFLUX_TOKEN=%s\n' "$INFLUX_READ_TOKEN" | sudo tee /etc/grafana/psut-token.env >/dev/null
printf '[Service]\nEnvironmentFile=/etc/grafana/psut-token.env\n' | sudo tee /etc/systemd/system/grafana-server.service.d/psut.conf >/dev/null
sudo systemctl daemon-reload
sudo systemctl restart grafana-server
curl -fsS http://127.0.0.1:3000/api/health
labs/python/lab44/greenhouse.jsonDownload source
Source file · inspect, do not paste in Bash
{
  "uid": "psut-greenhouse",
  "title": "Greenhouse",
  "description": "© 2026/2027 Dr. Mohammad Alja'afreh · PSUT IoT Engineering Learning Platform · Lab 44",
  "tags": [
    "psut",
    "iot"
  ],
  "timezone": "browser",
  "schemaVersion": 39,
  "version": 1,
  "time": {
    "from": "now-1h",
    "to": "now"
  },
  "refresh": "10s",
  "editable": true,
  "templating": {
    "list": [
      {
        "name": "node",
        "label": "Node",
        "type": "query",
        "datasource": {
          "type": "influxdb",
          "uid": "influx-greenhouse"
        },
        "refresh": 1,
        "query": "import \"influxdata/influxdb/schema\"\nschema.tagValues(bucket: \"greenhouse\", tag: \"node\")",
        "current": {
          "text": "pi-01",
          "value": "pi-01"
        },
        "sort": 1
      }
    ]
  },
  "panels": [
    {
      "id": 1,
      "type": "stat",
      "title": "Temperature now",
      "description": "Newest reading; orange from 28 °C, red from 30 °C (the fan thresholds).",
      "datasource": {
        "type": "influxdb",
        "uid": "influx-greenhouse"
      },
      "gridPos": {
        "x": 0,
        "y": 0,
        "w": 6,
        "h": 5
      },
      "targets": [
        {
          "refId": "A",
          "datasource": {
            "type": "influxdb",
            "uid": "influx-greenhouse"
          },
          "query": "from(bucket: \"greenhouse\")\n  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n  |> filter(fn: (r) => r._measurement == \"environment\" and r._field == \"temperature\" and r.node == \"${node}\")\n  |> last()"
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "celsius",
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              },
              {
                "color": "orange",
                "value": 28
              },
              {
                "color": "red",
                "value": 30
              }
            ]
          },
          "color": {
            "mode": "thresholds"
          },
          "decimals": 1
        },
        "overrides": []
      },
      "options": {
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": false
        },
        "colorMode": "background",
        "graphMode": "none",
        "textMode": "value"
      }
    },
    {
      "id": 2,
      "type": "stat",
      "title": "Humidity now",
      "description": "",
      "datasource": {
        "type": "influxdb",
        "uid": "influx-greenhouse"
      },
      "gridPos": {
        "x": 6,
        "y": 0,
        "w": 6,
        "h": 5
      },
      "targets": [
        {
          "refId": "A",
          "datasource": {
            "type": "influxdb",
            "uid": "influx-greenhouse"
          },
          "query": "from(bucket: \"greenhouse\")\n  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n  |> filter(fn: (r) => r._measurement == \"environment\" and r._field == \"humidity\" and r.node == \"${node}\")\n  |> last()"
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "percent",
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "orange",
                "value": null
              },
              {
                "color": "green",
                "value": 40
              },
              {
                "color": "orange",
                "value": 80
              }
            ]
          },
          "color": {
            "mode": "thresholds"
          },
          "decimals": 1
        },
        "overrides": []
      },
      "options": {
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": false
        },
        "colorMode": "background",
        "graphMode": "none",
        "textMode": "value"
      }
    },
    {
      "id": 3,
      "type": "gauge",
      "title": "Soil moisture",
      "description": "Pump switches ON below 35 % and OFF above 45 %.",
      "datasource": {
        "type": "influxdb",
        "uid": "influx-greenhouse"
      },
      "gridPos": {
        "x": 12,
        "y": 0,
        "w": 6,
        "h": 5
      },
      "targets": [
        {
          "refId": "A",
          "datasource": {
            "type": "influxdb",
            "uid": "influx-greenhouse"
          },
          "query": "from(bucket: \"greenhouse\")\n  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n  |> filter(fn: (r) => r._measurement == \"environment\" and r._field == \"soil_moisture\" and r.node == \"${node}\")\n  |> last()"
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "percent",
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "red",
                "value": null
              },
              {
                "color": "orange",
                "value": 35
              },
              {
                "color": "green",
                "value": 45
              }
            ]
          },
          "color": {
            "mode": "thresholds"
          },
          "min": 0,
          "max": 100,
          "decimals": 1
        },
        "overrides": []
      },
      "options": {
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": false
        },
        "showThresholdMarkers": true
      }
    },
    {
      "id": 4,
      "type": "timeseries",
      "title": "Temperature (mean per interval)",
      "description": "",
      "datasource": {
        "type": "influxdb",
        "uid": "influx-greenhouse"
      },
      "gridPos": {
        "x": 0,
        "y": 5,
        "w": 12,
        "h": 9
      },
      "targets": [
        {
          "refId": "A",
          "datasource": {
            "type": "influxdb",
            "uid": "influx-greenhouse"
          },
          "query": "from(bucket: \"greenhouse\")\n  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n  |> filter(fn: (r) => r._measurement == \"environment\" and r._field == \"temperature\" and r.node == \"${node}\")\n  |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)"
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "celsius",
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              },
              {
                "color": "orange",
                "value": 28
              },
              {
                "color": "red",
                "value": 30
              }
            ]
          },
          "color": {
            "mode": "palette-classic"
          },
          "custom": {
            "drawStyle": "line",
            "lineWidth": 2,
            "pointSize": 4,
            "showPoints": "auto",
            "thresholdsStyle": {
              "mode": "line+area"
            }
          }
        },
        "overrides": []
      },
      "options": {
        "legend": {
          "displayMode": "list",
          "placement": "bottom"
        },
        "tooltip": {
          "mode": "single"
        }
      }
    },
    {
      "id": 5,
      "type": "timeseries",
      "title": "Soil moisture (mean per interval)",
      "description": "",
      "datasource": {
        "type": "influxdb",
        "uid": "influx-greenhouse"
      },
      "gridPos": {
        "x": 12,
        "y": 5,
        "w": 12,
        "h": 9
      },
      "targets": [
        {
          "refId": "A",
          "datasource": {
            "type": "influxdb",
            "uid": "influx-greenhouse"
          },
          "query": "from(bucket: \"greenhouse\")\n  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n  |> filter(fn: (r) => r._measurement == \"environment\" and r._field == \"soil_moisture\" and r.node == \"${node}\")\n  |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)"
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "percent",
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "red",
                "value": null
              },
              {
                "color": "orange",
                "value": 35
              },
              {
                "color": "green",
                "value": 45
              }
            ]
          },
          "color": {
            "mode": "palette-classic"
          },
          "custom": {
            "drawStyle": "line",
            "lineWidth": 2,
            "pointSize": 4,
            "showPoints": "auto",
            "thresholdsStyle": {
              "mode": "line+area"
            }
          }
        },
        "overrides": []
      },
      "options": {
        "legend": {
          "displayMode": "list",
          "placement": "bottom"
        },
        "tooltip": {
          "mode": "single"
        }
      }
    },
    {
      "id": 6,
      "type": "state-timeline",
      "title": "Fan and pump",
      "description": "Each controller decision from Lab 42.",
      "datasource": {
        "type": "influxdb",
        "uid": "influx-greenhouse"
      },
      "gridPos": {
        "x": 18,
        "y": 0,
        "w": 6,
        "h": 5
      },
      "targets": [
        {
          "refId": "A",
          "datasource": {
            "type": "influxdb",
            "uid": "influx-greenhouse"
          },
          "query": "from(bucket: \"greenhouse\")\n  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n  |> filter(fn: (r) => r._measurement == \"actuator\" and r._field == \"state\" and r.node == \"${node}\")\n  |> keep(columns: [\"_time\", \"_value\", \"device\"])"
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "",
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "blue",
                "value": null
              }
            ]
          },
          "color": {
            "mode": "fixed"
          },
          "mappings": [
            {
              "type": "value",
              "options": {
                "0": {
                  "text": "OFF",
                  "color": "blue"
                },
                "1": {
                  "text": "ON",
                  "color": "red"
                }
              }
            }
          ]
        },
        "overrides": []
      },
      "options": {
        "showValue": "auto",
        "mergeValues": true,
        "rowHeight": 0.8
      }
    }
  ]
}
tools/analytics_preview.pyDownload source
Source file · inspect, do not paste in Bash
#!/usr/bin/env python3
"""Optional loopback-only, read-only website server and InfluxDB preview.
Run from WSL; the token is requested in the terminal, not stored in the website.
This is a single-user lab helper, NOT a multi-user web deployment server.
"""
import argparse, csv, getpass, io, json, math, os, re
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit, unquote

FIELDS = ('temperature', 'humidity', 'soil_moisture')
NODES = ('pi-01', 'python-sim', 'esp32-01')

def query_for(node, session):
    if node not in NODES or not re.fullmatch(r'(lab-local|demo-[0-9a-f]{16})', session):
        raise ValueError('Invalid node or session')
    tag = '' if node == 'pi-01' else f' and exists r.student and r.student == "{session}"'
    return f'''from(bucket: "greenhouse")
  |> range(start: -1h)
  |> filter(fn: (r) => r._measurement == "environment" and r.node == "{node}"{tag})
  |> filter(fn: (r) => r._field == "temperature" or r._field == "humidity" or r._field == "soil_moisture")
  |> group(columns: ["_field"])
  |> sort(columns: ["_time"], desc: true)
  |> limit(n: 60)'''

def parse_csv(body):
    header = None; rows = {k: [] for k in FIELDS}
    for row in csv.reader(io.StringIO(body)):
        if not row or row[0].startswith('#'): continue
        if '_time' in row and '_value' in row and '_field' in row:
            header = row; continue
        if not header or len(row) != len(header): continue
        r = dict(zip(header, row)); key = r.get('_field')
        if key not in rows: continue
        try: value = float(r['_value'])
        except (ValueError, KeyError, TypeError): continue
        if not math.isfinite(value): continue
        rows[key].append({'time': r['_time'], 'value': value})
    return {k: sorted(v, key=lambda x: x['time'])[-60:] for k,v in rows.items()}

def fetch_history(token, node, session):
    req = Request('http://127.0.0.1:8086/api/v2/query?org=psut', data=query_for(node, session).encode(),
                  headers={'Authorization': 'Token '+token, 'Content-Type': 'application/vnd.flux', 'Accept': 'application/csv'}, method='POST')
    with urlopen(req, timeout=8) as response:
        data = response.read(2_000_001)
    if len(data) > 2_000_000: raise ValueError('Response too large')
    return parse_csv(data.decode('utf-8'))

def make_handler(site, token, session):
    class Handler(SimpleHTTPRequestHandler):
        def __init__(self,*args,**kwargs): super().__init__(*args,directory=str(site),**kwargs)
        def log_message(self,fmt,*args): pass
        def send_json(self,status,payload):
            b=json.dumps(payload,allow_nan=False).encode(); self.send_response(status); self.send_header('Content-Type','application/json'); self.send_header('Cache-Control','no-store'); self.send_header('X-Content-Type-Options','nosniff'); self.send_header('Content-Length',str(len(b))); self.end_headers(); self.wfile.write(b)
        def permitted(self):
            # Restrict host and Origin to the local endpoint; do not enable CORS.
            if self.headers.get('Host') not in ('127.0.0.1:8765','localhost:8765'): return False
            origin=self.headers.get('Origin'); return origin in (None,'http://127.0.0.1:8765','http://localhost:8765') and self.headers.get('Sec-Fetch-Site') not in ('cross-site',)
        def do_GET(self):
            if not self.permitted(): self.send_error(403); return
            path=unquote(urlsplit(self.path).path)
            if path.startswith('/api/history/'):
                node=path.rsplit('/',1)[1]
                if node not in NODES: self.send_json(400,{'error':'Unknown device'}); return
                try: self.send_json(200,{'node':node,'session':session,'series':fetch_history(token,node,session),'source':'InfluxDB query'})
                except HTTPError as e: self.send_json(502,{'error':f'InfluxDB HTTP {e.code}; check read permission, org and bucket.'})
                except (OSError, ValueError, URLError): self.send_json(502,{'error':'InfluxDB query unavailable; check service and configuration.'})
                return
            # Only serve explicit website paths; never list directories or serve credential files.
            if path=='/': self.path='/index.html'; path='/index.html'
            rel=Path(path.lstrip('/')); target=(site/rel).resolve()
            if '..' in rel.parts or any(p.startswith('.') for p in rel.parts) or not target.is_relative_to(site) or not target.is_file(): self.send_error(404); return
            if not (rel.suffix in ('.html','.js','.css','.txt','.md','.zip','.py','.sh','.json','.toml','.ini','.cpp','.ino','.yaml','.conf','.service','.vue','.sql','.cmd') and (len(rel.parts)==1 or rel.parts[0] in ('assets','labs','psut-wsl','tests')) and not any('token' in p.lower() or p.endswith('.env') for p in rel.parts)):
                self.send_error(404); return
            super().do_GET()
        def do_HEAD(self): self.send_error(405)
    return Handler

def main():
    ap=argparse.ArgumentParser(description=__doc__); ap.add_argument('--site-root',required=True,type=Path); ap.add_argument('--session',default=os.getenv('STUDENT_ID','lab-local')); a=ap.parse_args(); site=a.site_root.expanduser().resolve()
    if not (site/'analytics.html').is_file() or not (site/'index.html').is_file(): ap.error('Choose the extracted Version 4 website root')
    query_for('python-sim',a.session)
    token=getpass.getpass('InfluxDB greenhouse READ-ONLY token: ').strip()
    if not token: ap.error('A read-only token is required')
    with ThreadingHTTPServer(('127.0.0.1',8765),make_handler(site,token,a.session)) as server:
        print('Open http://localhost:8765/analytics.html in Windows. Ctrl+C stops. Local only; no authentication, do not expose.');
        try: server.serve_forever()
        except KeyboardInterrupt: pass
if __name__=='__main__': main()

Reference documentation

Installation and teaching choices follow the supplied toolkit; the service concepts have been cross-checked with the official documentation.

Integrated IoT System Studio

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

Open integrated system workbench →