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.
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 →
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--versionpython-mpip check
ps -p1-ocomm=
✓ Expected: systemd should be printed for the service-based workflow.Expected result for each action (5)
cd ~/psut-wslNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
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.
python--versionThe installed version is printed. For this toolkit InfluxDB must be 2.x; version numbers otherwise depend on installation.
python-mpip checkNo broken requirements found. Resolve any reported conflicts before continuing.
ps -p1-ocomm=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)
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.
influxd versionThe installed version is printed. For this toolkit InfluxDB must be 2.x; version numbers otherwise depend on installation.
telegraf versionThe installed version is printed. For this toolkit InfluxDB must be 2.x; version numbers otherwise depend on installation.
systemctl is-active influxdbAn active line is expected for each required running service; inactive/failed requires investigation.
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.
✓ 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)
mkdir-p ~/.config/psut-wslNormally silent. The requested directory exists afterward; verify with ls -d.
chmod700 ~/.config/psut-wslNormally silent. Verify with ls -l or stat; a private directory should be 700 and a private credential file 600 where specified.
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.
(umask077;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.
unset tokenUsually silent. The named variable is removed from the current shell, not from existing files or external services.
chmod600 ~/.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.
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.
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)
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.
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.
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.
python greenhouse_node.pyThe program writes 30 historical points using the configured token and bucket; inspect errors and query history separately.
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.
✓ 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.
✓ 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)
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.
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.
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.
✓ 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)
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.
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.
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.
✓ 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)
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.
mosquitto_sub-h"$MQTT_HOST"-p"$MQTT_PORT"-t"$GREENHOUSE_TOPIC"-q1-vThe subscriber remains open. Once a matching publisher sends data, topic and JSON payload appear; an initially blank screen is normal.
✓ 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)
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.
mosquitto_sub-h"$MQTT_HOST"-p"$MQTT_PORT"-t"$GREENHOUSE_TOPIC"-q1-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)
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.
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.
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.
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.
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)
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.
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.
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.
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.
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=5PERIOD=2python 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)
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.
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.
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.
MESSAGES=5PERIOD=2python 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=5PERIOD=2python 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)
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.
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.
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.
MESSAGES=5PERIOD=2python 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.
✓ 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)
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.
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.
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.
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.
sleep 5No output; execution pauses for the specified time, then continues. This is not evidence of delivery.
python my_device_history.pyStored records matching the configured session and time window are displayed if ingestion succeeded. An empty result requires investigation.
✓ 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)
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.
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.
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.
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.
sleep 5No output; execution pauses for the specified time, then continues. This is not evidence of delivery.
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.
✓ Expected: Grafana health JSON reports database ok when healthy; datasource queries still require independent verification.Expected result for each action (7)
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.
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.
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.
export INFLUX_READ_TOKENUsually silent. The variable is inherited by child processes launched from this terminal; never print a secret to verify it.
bash provision.shGrafana provisioning completes and restarts the service; check the health endpoint and datasource query.
unset INFLUX_READ_TOKENUsually silent. The named variable is removed from the current shell, not from existing files or external services.
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)
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.
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.
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)
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.
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.
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.
✓ Expected: The toolkit reports checks for the installed components. Review any FAIL or unavailable optional service before continuing.Expected result for each action (3)
python3 ~/psut-wsl/tools/test_static.pyThe corresponding test program reports its checks and returns; investigate any failed assertion or error.
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.
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.
#!/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.
"""importargparse,csv,getpass,io,json,math,os,refromhttp.serverimportSimpleHTTPRequestHandler,ThreadingHTTPServerfrompathlibimportPathfromurllib.requestimportRequest,urlopenfromurllib.errorimportHTTPError,URLErrorfromurllib.parseimporturlsplit,unquoteFIELDS=('temperature','humidity','soil_moisture')NODES=('pi-01','python-sim','esp32-01')defquery_for(node,session):ifnodenotinNODESornotre.fullmatch(r'(lab-local|demo-[0-9a-f]{16})',session):raiseValueError('Invalid node or session')tag=''ifnode=='pi-01'elsef' and exists r.student and r.student == "{session}"'returnf'''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)'''defparse_csv(body):header=None;rows={k:[]forkinFIELDS}forrowincsv.reader(io.StringIO(body)):ifnotroworrow[0].startswith('#'):continueif'_time'inrowand'_value'inrowand'_field'inrow:header=row;continueifnotheaderorlen(row)!=len(header):continuer=dict(zip(header,row));key=r.get('_field')ifkeynotinrows:continuetry:value=float(r['_value'])except(ValueError,KeyError,TypeError):continueifnotmath.isfinite(value):continuerows[key].append({'time':r['_time'],'value':value})return{k:sorted(v,key=lambdax:x['time'])[-60:]fork,vinrows.items()}deffetch_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')withurlopen(req,timeout=8)asresponse:data=response.read(2_000_001)iflen(data)>2_000_000:raiseValueError('Response too large')returnparse_csv(data.decode('utf-8'))defmake_handler(site,token,session):classHandler(SimpleHTTPRequestHandler):def__init__(self,*args,**kwargs):super().__init__(*args,directory=str(site),**kwargs)deflog_message(self,fmt,*args):passdefsend_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)defpermitted(self):# Restrict host and Origin to the local endpoint; do not enable CORS.ifself.headers.get('Host')notin('127.0.0.1:8765','localhost:8765'):returnFalseorigin=self.headers.get('Origin');returnoriginin(None,'http://127.0.0.1:8765','http://localhost:8765')andself.headers.get('Sec-Fetch-Site')notin('cross-site',)defdo_GET(self):ifnotself.permitted():self.send_error(403);returnpath=unquote(urlsplit(self.path).path)ifpath.startswith('/api/history/'):node=path.rsplit('/',1)[1]ifnodenotinNODES:self.send_json(400,{'error':'Unknown device'});returntry:self.send_json(200,{'node':node,'session':session,'series':fetch_history(token,node,session),'source':'InfluxDB query'})exceptHTTPErrorase: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.ifpath=='/':self.path='/index.html';path='/index.html'rel=Path(path.lstrip('/'));target=(site/rel).resolve()if'..'inrel.partsorany(p.startswith('.')forpinrel.parts)ornottarget.is_relative_to(site)ornottarget.is_file():self.send_error(404);returnifnot(rel.suffixin('.html','.js','.css','.txt','.md','.zip','.py','.sh','.json','.toml','.ini','.cpp','.ino','.yaml','.conf','.service','.vue','.sql','.cmd')and(len(rel.parts)==1orrel.parts[0]in('assets','labs','psut-wsl','tests'))andnotany('token'inp.lower()orp.endswith('.env')forpinrel.parts)):self.send_error(404);returnsuper().do_GET()defdo_HEAD(self):self.send_error(405)returnHandlerdefmain():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()ifnot(site/'analytics.html').is_file()ornot(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()ifnottoken:ap.error('A read-only token is required')withThreadingHTTPServer(('127.0.0.1',8765),make_handler(site,token,a.session))asserver:print('Open http://localhost:8765/analytics.html in Windows. Ctrl+C stops. Local only; no authentication, do not expose.');try:server.serve_forever()exceptKeyboardInterrupt:passif__name__=='__main__':main()
Reference documentation
Installation and teaching choices follow the supplied toolkit; the service concepts have been cross-checked with the official documentation.