Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Connected Networks StudioNetworking and CommunicationExperimentsWorkspaces
ENGINEERING WORKSPACE
Home/WSL Laboratories/Lab 44 · Grafana dashboard for IoT data
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Python & IoT / P44
IoT Programming and Applications

Lab 44 · Grafana dashboard for IoT data

Ask Dr. Mohammad · P44 →

Grafana reads the greenhouse bucket using a dedicated read-only token.

Design experiment & verify evidence →
P44 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingP44 · Grafana dashboard for IoT data
Readiness checksRevision deckEngineering workspaceRecord evidence

Related course access: Networking and Communication · Machine Learning and Edge AI — same laboratory, notebook and completion record.

P44 · Academic orientation

Scope and objectives

Scope of the experiment

Calculate the dashboard’s last refresh, visible points and age of information.

The focus of this experiment is to connect Grafana queries, time ranges and panels to stored IoT observations. Students then interpret aggregation and missing intervals without inventing samples, and verify dashboard values against the underlying time-series query. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.

Learning objectives

  • Connect Grafana queries, time ranges and panels to stored IoT observations.
  • Interpret aggregation and missing intervals without inventing samples.
  • Verify dashboard values against the underlying time-series query.
  • Record the relevant inputs, intermediate states and final verification result before changing the reference configuration.
  • Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.

Expected learning outcomes

On completion, students can connect Grafana queries, time ranges and panels to stored IoT observations, interpret aggregation and missing intervals without inventing samples, and verify dashboard values against the underlying time-series query.

Required deliverables

Submit the derivation or state trace for the named operation, the exact reference and changed configurations, the associated simulator or practical evidence, and a short validation statement addressing verify dashboard values against the underlying time-series query. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 1 · Board architecture & setup.

Environment and experimental methodology

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

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

P44 / PREPARE

Before starting

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

Ubuntu WSL setup →
Before you run / verification gate

Complete P42 or P43 storage first. Provision with a scoped read token; ensure datasource health and choose a time range containing real stored samples. Do not reset an existing admin password to a default.

CONCEPTS / ACTIVE RECALL

Understand the experiment

Dashboard sampling and refresh

Samples and display refresh run on different clocks
Samples and display refresh run on different clocks

Scientific architecture · Grafana query, refresh and dashboard freshness

Dashboard refresh versus acquisition — Sensor sample / every 2 s; Store records / independent cadence; Query window / select stored samples; Refresh / every 5 s; Dashboard / displayed value can be stale
Scientific concept map: Time-series store — Timestamped sensor data; Grafana datasource — Query interval; Panel aggregation — Select field; Refresh scheduler — Display update; Dashboard — Freshness vs query age.

Scientific foundations and analytical reasoning

Dashboard refresh and sampling clocks are independent; displayed data can be stale even when the datasource continues to collect.

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

Scientific theory · Dashboard freshness and aggregation

Grafana queries a data source on refresh; it does not itself acquire sensor readings. A panel's time range, aggregation, refresh rate and data-source configuration determine what is displayed. A stale chart may indicate a query or refresh issue even if writes continue.

Worked example and engineering interpretation

If sampling is every 2 s and the panel refreshes every 10 s, five scheduled samples may arrive between refreshes. A last-sample display and a window mean answer different questions. Compare stored record IDs and the panel's last refresh timestamp.

Engineering principles · additional worked teaching example

A Grafana dashboard queries stored records at refresh times; refresh does not resample sensors. With acquisitions every 3 s and refresh every 10 s, at wall time 24 s the latest completed refresh is 20 s, and latest displayed point is 18 s assuming instantaneous querying.

From theory to experiment

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

How to investigate Lab 44 · Grafana dashboard for IoT data

Configure Grafana queries and verify the corresponding stored records.

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

Experiment-specific guided practice

Objective: Configure Grafana queries and verify the corresponding stored records.

  1. Set sampling 5 s, refresh 15 s and query window 20 s; step three times.
  2. Change temperature and sample before next refresh. Compare stored history and displayed snapshot age.
  3. Advance to refresh; then disable datasource and repeat. Observe stale snapshot.
  4. Follow actual provisioning instructions and compare panel refresh and query range.

Reference check:

Model boundary:

Independent task and submission evidence

2. Change temperature and sample before next refresh. Compare stored history and displayed snapshot age. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat.

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

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

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

Worked engineering reasoning and boundary conditions

Engineering reference configuration: Observation time (s) = 60; Sensor interval (s) = 5; Dashboard refresh (s) = 15; Display window (s) = 20; Datasource query succeeds = true. In the classroom model, Last refresh = 60 s; Displayed points = 5; Displayed age = 0 s. Inclusive browser query window; compare actual Grafana query semantics. A closed, deterministic browser model. The existing practical instructions and source files provide independent execution; browser results are not hardware measurements.

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

Concept animation · progressive data plot

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

Lab 44 · Grafana dashboard for IoT data: progressive data plot2727.2527.527.7528Dashboard tempera…406040

Step 1 of 5 · Observation 40

Observation 40

Dashboard temperature
27

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

Recall the concept before revealing its explanation.

0 / 3 revealed
P44 · 01 / 08Why use a read-only token?Reveal explanation
Engineering explanation

Grafana requires query access, not permission to modify measurements.

P44 · 02 / 08What if a dashboard is empty?Reveal explanation
Engineering explanation

Check actual stored points, datasource, node filter and time range separately.

P44 · 03 / 08Which Grafana datasource and query prerequisites must be verified?Reveal explanation
Engineering explanation

Complete P42 or P43 storage first. Provision with a scoped read token; ensure datasource health and choose a time range containing real stored samples. Do not reset an existing admin password to a default.

P44 · 04 / 08Why align Grafana query time range with stored timestamps?Reveal explanation
Engineering reasoning

A valid stored point can be outside the dashboard window and therefore invisible.

P44 · 05 / 08Why inspect the underlying query results?Reveal explanation
Engineering reasoning

A graph alone may aggregate or omit points; query output establishes which values actually feed the visualization.

P44 · 06 / 08A Grafana panel shows no data. Select every technically valid statement. A. Check time range and query filters. B. Verify the underlying database contains matching records. C. An empty panel proves the sensor is disconnected. D. Grafana rendering establishes sensor accuracy.Reveal explanation
Applied scenario

Correct: A. Check time range and query filters.; B. Verify the underlying database contains matching records.

P44 · 07 / 08In Grafana dashboard for IoT data, which command or code executes Provision dashboard?Reveal explanation
Implementation recall

source ~/psut-wsl/activate.sh 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

P44 · 08 / 08For Grafana dashboard for IoT data, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Finish P42/P43 and verify stored records before Grafana. Install/start Grafana, check /api/health, obtain a read-only InfluxDB token scoped to greenhouse, provision from the lab directory. Open localhost:3000, select the configured datasource/dashboard, use a time range covering the recorded points and correct device/source. A reachable port alone does not prove dashboard data. Avoid exposing tokens in screenshots.

Time-series deployment center

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

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

Network performance laboratory

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

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

Live experimental workstations

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

Configure Grafana queries and verify the corresponding stored records.

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

Interactive engineering workbenchP44 · Existing model

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

01 / Explore

Interactive lab simulation

Browser model
P44 · Model-linked instrumentation

Visual observation lens

Back to controls ↑

Original virtual instrument; model signals and execution trace.

Loading instrument…

Awaiting model display.

Experimental instrumentation · A/B

Compare two model conditions

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

Open simulation view
Baseline A
Not captured
Comparison B
Not captured

Capture a baseline to begin.

Evidence portfolio →
V19.0 · Contextual AI workspace

Ask your engineering assistants

P44 · current context

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

Dr. Mohammad · offline
Dr. Mohammad

Offline curriculum-grounded assistance.

Open local tutor
Lab 44 · Grafana dashboard for IoT data

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

Prepare a contextual AI prompt

0 characters

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

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

Run & verify — acceptance checklist

Build verification: Provisioning/configuration reviewed; actual Grafana pending.

Finish P42/P43 and verify stored records before Grafana. Install/start Grafana, check /api/health, obtain a read-only InfluxDB token scoped to greenhouse, provision from the lab directory. Open localhost:3000, select the configured datasource/dashboard, use a time range covering the recorded points and correct device/source. A reachable port alone does not prove dashboard data. Avoid exposing tokens in screenshots.

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

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

Independent theoretical exercises

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

01 · Predict and derive using the given inputs

For samples every 5 s from 0 to 60 s and refreshes every 15 s, list refresh times and samples available by t=32 s. Identify latest displayed timestamp assuming instant queries.

02 · Compare or justify using evidence

For a 20 s inclusive query window at t=45 s, list sample timestamps. Explain what happens when the next query fails.

03 · Data interpretation

Data interpretation · Independent work

Samples at 0,4,…,40 s; refresh at 0,12,… . At time 35 s what is the latest displayed sample and its age? What if query has a 5 s processing delay?

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

Expanded independent theoretical exercise bank

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

Intermediate · Explain a changed-input result

Independent theoretical exercise · P44-01

Use the reference configuration (Observation time (s) = 60; Sensor interval (s) = 5; Dashboard refresh (s) = 15; Display window (s) = 20; Datasource query succeeds = true), but change Observation time (s) = 62. The model reports Displayed age = 2 s. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · P44-02

Two model observations of Displayed age are 0 s (reference) and 2 s (changed condition). Compute signed change and, when the reference is nonzero, percentage change. Explain why units matter.

Intermediate · Interpret a technical trace

Independent theoretical exercise · P44-03

For Sensor interval (s) = 7, the model supplies this excerpt from Visible series: Time (s) · Temperature 42 · 27.1 49 · 27.45 56 · 27.8 Compute the range (maximum minus minimum) of the Temperature column in these rows. Identify the maximum observation. Do not extrapolate beyond these rows.

Advanced · Reverse reasoning

Independent theoretical exercise · P44-04

An observation is Displayed points = 3. Candidate A uses Observation time (s) = 60; Sensor interval (s) = 5; Dashboard refresh (s) = 15; Display window (s) = 20; Datasource query succeeds = true. Candidate B changes the listed settings (Sensor interval (s) = 7) and keeps the remaining settings fixed. Which is consistent with the observation? If both can explain it, say what additional evidence is required.

Advanced · Diagnose a reported mismatch

Independent theoretical exercise · P44-05

A student configures Dashboard refresh (s) = 17 while preserving all other reference settings, but copies the reference report of Last refresh = 60 s. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · P44-06

Design a controlled comparison for Lab 44 · Grafana dashboard for IoT data using reference Observation time (s) = 60; Sensor interval (s) = 5; Dashboard refresh (s) = 15; Display window (s) = 20; Datasource query succeeds = true and test Observation time (s) = 62. Specify the changed setting(s), measured metric Displayed age, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Live simulation · Grafana refresh

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

  1. Set sampling 5 s, refresh 15 s and query window 20 s; step three times.
  2. Change temperature and sample before next refresh. Compare stored history and displayed snapshot age.
  3. Advance to refresh; then disable datasource and repeat. Observe stale snapshot.
  4. Follow actual provisioning instructions and compare panel refresh and query range.

Evidence

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

Step-by-step experimental procedure

Calculate the dashboard’s last refresh, visible points and age of information.

1 · Reference workbench configuration

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

Observation time (s)60
Sensor interval (s)5
Dashboard refresh (s)15
Display window (s)20
Datasource query succeedsYes

2 · Perform the investigation in order

  1. At t=60 s, sample every 5 s and refresh every 15 s; inspect the inclusive window.
  2. Move observation time to 64 s, then 74 s and compare dashboard age.
  3. Disable datasource query; distinguish no data from a zero sensor value.
  4. Compare with the actual Grafana notebook/dashboard: query time range, refresh setting, and newest database timestamp.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
ReferenceUse reference inputs aboveDisplayed points: 5; Displayed age: 0Record actual result
Between refreshesObservation time (s) = 64Displayed age: 4Record actual result
Datasource errorDatasource query succeeds = NoDisplayed points: 0Record actual result

4 · Analyze and report

Dashboard freshness is not equivalent to sensor sampling rate.

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

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

Loading laboratory-specific procedure…

Python / Google Colab notebook

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

Download NotebookOpen Google ColabAll Python notebooksFull service setup and acceptance

Independent implementation sequence

  1. Install Grafana
  2. Create a read-only token
  3. Provision dashboard
  4. Open Grafana dashboard
02 / Implement

Step-by-step instructions

Before you run / verification gate

Complete P42 or P43 storage first. Provision with a scoped read token; ensure datasource health and choose a time range containing real stored samples. Do not reset an existing admin password to a default.

Complete one-time setup first. Copy one command block at a time into the indicated environment. Do not copy prompt characters. Open new terminals where named; variables are terminal-specific. Ctrl+C stops a running foreground command.

01

Install Grafana

Complete Lab 42 first and optionally Lab 43.

WSL · Bash
bash ~/psut-wsl/setup_wsl.sh --grafana
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 (2)
  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. curl -fsS http://127.0.0.1:3000/api/healthGrafana health JSON reports database ok when healthy; datasource queries still require independent verification.
Checkpoint database: ok.
02

Create a read-only token

Open InfluxDB at localhost:8086 → Load Data → API Tokens → custom token → read permission on greenhouse only. Copy token. Do not use a write token for Grafana.

Checkpoint Complete the action before continuing.
03

Provision dashboard

In WSL, paste the read-only token at the hidden prompt.

WSL · Bash
source ~/psut-wsl/activate.sh
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
✓ Expected: Grafana provisioning completes and restarts the service; check the health endpoint and datasource query.
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. 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.
Checkpoint Health JSON indicates database OK. Provisioning writes one root-only token file, not repeated default entries.
04

Open Grafana dashboard

In Windows browser open http://localhost:3000/d/psut-greenhouse/greenhouse. First login on fresh install: admin/admin; change password when asked. Select Last 1 hour. If empty run Lab 42 or 43 and refresh.

Checkpoint Temperature, humidity and soil time series; choose the correct node/filter.
Node-RED alternative / parallel view: Lab 43 sends the same MQTT readings to Node-RED without requiring Grafana. Follow dual-broker dashboards. Grafana still shows stored InfluxDB history; Node-RED shows live messages.

Experimental notebook

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

03 / Inspect

Source code and method

labs/python/lab44/greenhouse-provider.yamlDownload source
YAML · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Grafana dashboard provider: load every *.json dashboard from one folder
apiVersion: 1
providers:
  - name: psut-greenhouse
    folder: PSUT IoT                  # folder shown in Grafana → Dashboards
    type: file
    allowUiUpdates: true              # you may edit in the UI (save a copy to keep changes)
    options:
      path: /var/lib/grafana/dashboards
labs/python/lab44/greenhouse.jsonDownload source
JSON · source file
{
  "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
      }
    }
  ]
}
labs/python/lab44/influxdb.yamlDownload source
YAML · source file
# ------------------------------------------------------------
# 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/install_grafana.shDownload source
SH · source file
#!/usr/bin/env bash
set -euo pipefail
bash "$HOME/psut-wsl/setup_wsl.sh" --grafana
curl -fsS http://127.0.0.1:3000/api/health
labs/python/lab44/provision.shDownload source
SH · source file
#!/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
04 / Verify

Evidence of completion

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

Integrated IoT System Studio

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

Open integrated system workbench →

Python / Google Colab laboratory

P44 · 15 notebook cells · 5 executable Python cells

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

How to execute

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

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

01Instructions · Markdown
# P44 · Lab 44 · Grafana dashboard for IoT data **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction This notebook turns the original laboratory into a repeatable software experiment. Virtual readings and GPIO values are explicitly distinguished from physical measurements. ## How to run 1. In Google Colab choose File → Upload notebook; select this `.ipynb`. A CPU Python runtime is sufficient. 2. Read the goals and select the execution profile in the configuration cell. Run the implementation cells in order or use Runtime → Run all. 3. Compare the measured software output against the stated acceptance criteria. Run the controlled second trial and record differences. 4. Never use physical GPIO, private telemetry, real credentials or identifiable student information on a public broker. Stop the runtime after the lab. **Scope:** Local tests run actual software components using bounded virtual inputs. A successful local trial does not certify external services.
02Instructions · Markdown
## Experiment-specific preparation Configure Grafana queries and verify the corresponding stored records. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Set sampling 5 s, refresh 15 s and query window 20 s; step three times. 2. Change temperature and sample before next refresh. Compare stored history and displayed snapshot age. 3. Advance to refresh; then disable datasource and repeat. Observe stale snapshot. 4. Follow actual provisioning instructions and compare panel refresh and query range. 5. At t=60 s, sample every 5 s and refresh every 15 s; inspect the inclusive window. **Evidence:** **Boundary:**
03Instructions · Markdown
## 1. Goals and architecture - Produce timestamped virtual greenhouse readings and threshold-controlled GPIO17 fan state. - Publish synthetic JSON to a unique HiveMQ topic; Telegraf subscribes and writes to InfluxDB. - Create a genuine Grafana data source, four-panel dashboard and execute a data-source query through its API. **Local mode:** virtual device → real MQTT 3.1.1 TCP packets → restricted loopback teaching peer → subscriber → actual SQLite → plot. **Stack mode:** virtual device → HiveMQ TLS MQTT → Telegraf → InfluxDB 2 → Flux query → Grafana data-source query. Local mode is NOT an InfluxDB/Grafana result. Control the sampling count and threshold; use identical synthetic readings for the two configurations. The local peer supports only exact topics and QoS 1; it is not a full broker.
04Python · executable cell
PYTHON · Code cell
# =====================================================================
# P44 | Code cell 01 | Lab 44 · Grafana dashboard for IoT data
# Purpose: 1. Goals and architecture - Produce timestamped virtual greenhouse readings and threshold-controlled GPIO17 fan state. - Publish synthetic JSON to a unique HiveMQ topic; Telegraf subscribes and writes to Influx
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import contextlib, csv, io, json, math, os, secrets, socket, socketserver, sqlite3, ssl, struct, threading, time, uuid

from pathlib import Path

from urllib.request import Request, urlopen

from urllib.parse import urlencode

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# Execute genuine service path. Raises on any missing component or mismatch.
def actual_stack(use_telegraf=True,use_grafana=True,download=False,count=12,threshold=27):
    """Execute genuine service path. Raises on any missing component or mismatch.
    Virtual readings only; MQTT topic is unique and public. No secret in payload.
    """
    rows=samples(count,threshold);run=rows[0]['run'];topic=f'psut/colab/{run}/telemetry';expected=[r['temperature'] for r in rows]
    # Separate cache directory permits APT's sandbox user to read signing files.
    with tempfile.TemporaryDirectory(prefix='psut-binaries-') as binary_dir,tempfile.TemporaryDirectory(prefix='psut-private-') as private:
        Path(binary_dir).chmod(0o755);root=Path(private);required=['influxd']+(['telegraf'] if use_telegraf else [])+(['grafana'] if use_grafana else []);bins=provision_binaries(Path(binary_dir)/'vendor',required,download)
        base=f'http://127.0.0.1:{free_port()}';token=secrets.token_hex(32);password=secrets.token_urlsafe(24)
        with contextlib.ExitStack() as stack:
            influx=stack.enter_context(service([bins['influxd'],'--http-bind-address',base.removeprefix('http://'),'--bolt-path',root/'influx.bolt','--engine-path',root/'engine','--reporting-disabled'],root))
            await_ready(influx,lambda:jhttp(base,'/health'))
            jhttp(base,'/api/v2/setup',{'username':'psut','password':password,'org':'psut','bucket':'greenhouse','token':token})
            print('InfluxDB setup and health: OK')
            if use_telegraf:
                cfg=root/'telegraf.conf';cfg.write_text(telegraf_config(topic,base));env=dict(os.environ,PSUT_INFLUX_TOKEN=token)
                tg=stack.enter_context(service([bins['telegraf'],'--config',cfg],root,env));time.sleep(4);check(tg.poll() is None,'Telegraf failed to start')
                # Second subscriber verifies public broker delivery independently of Telegraf.
                with MQTT('broker.hivemq.com',8883,True) as sub,MQTT('broker.hivemq.com',8883,True) as pub:
                    sub.subscribe(topic)
                    for r in rows:
                        payload=json.dumps(r,allow_nan=False).encode();pub.publish(topic,payload);t,b=sub.receive();check(t==topic and b==payload,'MQTT delivery mismatch')
            else:
                status,_=http(base,'/api/v2/write?org=psut&bucket=greenhouse&precision=s','\n'.join(map(line_protocol,rows)).encode(),{'Authorization':'Token '+token,'Content-Type':'text/plain; charset=utf-8'});check(status==204,'write not acknowledged')
            q=flux_for(run,'temperature');deadline=time.monotonic()+35;values=[]
            while time.monotonic()<deadline:
                values=influx_values(base,token,q)
                if len(values)>=count:break
                time.sleep(1)
            check(len(values)==count and all(math.isclose(a,b,abs_tol=1e-6) for a,b in zip(values,expected)),'InfluxDB count/value mismatch; no service PASS')
            observed={'temperature':values}
            for field in ('humidity','soil_moisture','fan'):
                actual_field=influx_values(base,token,flux_for(run,field));check(len(actual_field)==count and all(math.isclose(a,b[field],abs_tol=1e-6) for a,b in zip(actual_field,rows)),field+' readback mismatch');observed[field]=actual_field
            print('InfluxDB actual readback:',len(values),'records in each of four fields')
            dashboard=grafana_spec(run);grafana_count=None
            if use_grafana:
                gf=f'http://127.0.0.1:{free_port()}';gp=bins['grafana'];home=gp.parent.parent if (gp.parent.parent/'conf/defaults.ini').exists() else Path('/usr/share/grafana');check((home/'conf/defaults.ini').is_file(),'Grafana homepath missing')
                provision=root/'provisioning';provision.mkdir();env=dict(os.environ,GF_SERVER_HTTP_ADDR='127.0.0.1',GF_SERVER_HTTP_PORT=gf.split(':')[-1],GF_PATHS_DATA=str(root/'grafana-data'),GF_PATHS_LOGS=str(root/'grafana-logs'),GF_PATHS_PLUGINS=str(root/'grafana-plugins'),GF_PATHS_PROVISIONING=str(provision),GF_SECURITY_ADMIN_USER='psut',GF_SECURITY_ADMIN_PASSWORD=password,GF_AUTH_ANONYMOUS_ENABLED='false',GF_ANALYTICS_REPORTING_ENABLED='false',GF_ANALYTICS_CHECK_FOR_UPDATES='false',GF_PLUGINS_PREINSTALL_AUTO_UPDATE='false')
                gfproc=stack.enter_context(service([gp,'server','--homepath',home],root,env));await_ready(gfproc,lambda:jhttp(gf,'/api/health'),75)
                auth={'Authorization':'Basic '+base64.b64encode(('psut:'+password).encode()).decode()}
                ds={'name':'PSUT InfluxDB','type':'influxdb','uid':'psut-influx','access':'proxy','url':base,'jsonData':{'version':'Flux','organization':'psut','defaultBucket':'greenhouse'},'secureJsonData':{'token':token}}
                jhttp(gf,'/api/datasources',ds,auth);jhttp(gf,'/api/dashboards/db',{'dashboard':dashboard,'overwrite':True},auth)
                saved=jhttp(gf,'/api/dashboards/uid/psut-virtual-iot',headers=auth);check(len(saved['dashboard']['panels'])==4,'dashboard readback failed')
                result=jhttp(gf,'/api/ds/query',{'from':'now-1h','to':'now','queries':[{'refId':'A','datasource':{'type':'influxdb','uid':'psut-influx'},'query':q,'maxDataPoints':1000,'intervalMs':1000}]},auth)
                a=result['results']['A'];check(not a.get('error') and a.get('status',200)==200,'Grafana query error');actual=[]
                for frame in a.get('frames',[]):
                    for i,field in enumerate(frame['schema']['fields']):
                        if field.get('type')=='number':actual.extend(frame['data']['values'][i])
                check(len(actual)==count and all(math.isclose(x,y,abs_tol=1e-6) for x,y in zip(actual,expected)),'Grafana query readback mismatch');grafana_count=len(actual);print('Grafana dashboard and datasource query: OK')
            evidence={'schema':'psut-iot-stack-v2077','transport':'HiveMQ TLS / Telegraf' if use_telegraf else 'InfluxDB HTTP','storage':'actual InfluxDB OSS 2','source':'virtual','run':run,'rows':[[r['seq'],r['ts'],values[i],observed['humidity'][i],observed['soil_moisture'][i],observed['fan'][i]] for i,r in enumerate(rows)],'stored':len(values),'grafana_count':grafana_count,'dashboard':dashboard,'status':'passed'}
        # Write only non-secret evidence; local services are stopped before leaving.
        Path('psut-grafana-dashboard.json').write_text(json.dumps(dashboard,indent=2));Path('psut-stack-evidence.json').write_text(json.dumps(evidence,indent=2));return evidence
Ask Dr. Mohammad about this cell
09Instructions · Markdown
## 4. Execute, inspect actual query results and export evidence Reference: 12 readings, 27°C threshold. Local mode additionally injects a duplicate, malformed payload and foreign-topic message; expect exactly 12 unique stored readings, one duplicate, two invalid subscribed payloads and one isolated foreign publication. Stack mode verifies each field in InfluxDB; Grafana lab also checks actual Grafana data-source query output.
10Python · executable cell
PYTHON · Code cell
# =====================================================================
# P44 | Code cell 04 | Lab 44 · Grafana dashboard for IoT data
# Purpose: 4. Execute, inspect actual query results and export evidence Reference: 12 readings, 27°C threshold. Local mode additionally injects a duplicate, malformed payload and foreign-topic message; expect exactly 12 u
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
if MODE == "stack":
    result = actual_stack(use_telegraf=True, use_grafana=True, download=DOWNLOAD_SERVICES, count=COUNT, threshold=THRESHOLD)
else:
    result = local_pipeline('local', COUNT, THRESHOLD)
    assert result['stored'] == COUNT and result['duplicates'] == 1 and result['rejected'] == 2
    dashboard = grafana_spec(result['records'][0]['run'])
    # An exportable definition is NOT a running Grafana dashboard.
    Path('psut-grafana-dashboard.json').write_text(json.dumps(dashboard, indent=2))
    Path('psut-stack-evidence.json').write_text(json.dumps(result, indent=2))
print({k:v for k,v in result.items() if k not in ('rows','records','dashboard')})
plot_pipeline(result)
Ask Dr. Mohammad about this cell
11Instructions · Markdown
## 5. Controlled repeat and interpretation The second local trial changes only the control threshold. The virtual temperature sequence should not change, while the fan activity should decrease. This is a software-control investigation, not a calibrated thermal model. Compare delivery and query counts, describe why duplicate suppression matters, and explain why HiveMQ TLS alone does not authenticate the data producer.
12Python · executable cell
PYTHON · Code cell
# =====================================================================
# P44 | Code cell 05 | Lab 44 · Grafana dashboard for IoT data
# Purpose: 5. Controlled repeat and interpretation The second local trial changes only the control threshold. The virtual temperature sequence should not change, while the fan activity should decrease. This is a software-
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Set low for the next computation or reference condition.
low=local_pipeline("local",COUNT,24)
# Set high for the next computation or reference condition.
high=local_pipeline("local",COUNT,35)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert [r[2] for r in low["rows"]] == [r[2] for r in high["rows"]]
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert sum(r[5] for r in low["rows"]) >= sum(r[5] for r in high["rows"])
print("Fan ON counts:",sum(r[5] for r in low["rows"]),sum(r[5] for r in high["rows"]))
print("LOCAL controlled repeat: PASS; this is independent of live service status")
Ask Dr. Mohammad about this cell
13Instructions · Markdown
## Original portal implementation (reference) Use the original lab P44 for WSL installation and full Grafana UI. ### Original datasource configuration ```yaml # ------------------------------------------------------------ # 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 ``` ### Original dashboard JSON ```json { "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 } } ] } ```
14Instructions · Markdown
## Experimental record and discussion Record your selected profile, configuration, actual outputs and assertions, failures, and conclusions. Distinguish software-observed packet/HTTP/SQL behavior, virtual sensor values, and actual hardware measurements. If a live mode is unavailable, record it as blocked. Do not claim a hosted service or physical experiment passed on the basis of the local reference trial. Export your notebook outputs or the generated JSON evidence.
15Instructions · Markdown
## Guided reasoning and evidence A controlled comparison changes one independent input while keeping the other relevant inputs fixed; the dependent variable is the recorded output. Use this lab’s reference condition above. **Independent task:** 2. Change temperature and sample before next refresh. Compare stored history and displayed snapshot age. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat. | Trial | Input/configuration | Prediction | Observation | Evidence / limitation | |---|---|---|---|---| | A | Reference | | | | | B | Changed input | | | | | A repeat | Reference | | | | A conclusion is supported only when it cites the recorded values or observed states and explains them with the experiment theory.