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 42 · IoT time-series data with InfluxDB
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Python & IoT / P42
IoT Programming and Applications

Lab 42 · IoT time-series data with InfluxDB

Ask Dr. Mohammad · P42 →

InfluxDB 2 installs on Ubuntu exactly as on Raspberry Pi OS (the same InfluxData repository); uname -m prints x86_64 instead of aarch64 .

Design experiment & verify evidence →
P42 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingP42 · IoT time-series data with InfluxDB
Readiness checksRevision deckEngineering workspaceRecord evidence

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

P42 · Academic orientation

Scope and objectives

Scope of the experiment

Generate line-protocol records and calculate a selected time-window query, including duplicate series/timestamp overwrite.

The focus of this experiment is to distinguish InfluxDB measurements, tags, fields and timestamps. Students then trace a sensor reading into a time-series write and query, and verify records and identify type, timestamp or retention mismatches. 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

  • Distinguish InfluxDB measurements, tags, fields and timestamps.
  • Trace a sensor reading into a time-series write and query.
  • Verify records and identify type, timestamp or retention mismatches.
  • 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 distinguish InfluxDB measurements, tags, fields and timestamps, trace a sensor reading into a time-series write and query, and verify records and identify type, timestamp or retention mismatches.

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 records and identify type, timestamp or retention mismatches. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 43 · MQTT → Telegraf → InfluxDB.

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.

P42 / 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 onboarding for organization psut and bucket greenhouse; create a scoped read/write token. Verify a query after the write. Stop optional live producer with Ctrl+C; keep token private.

CONCEPTS / ACTIVE RECALL

Understand the experiment

InfluxDB · point identity and query

Measurement + tag set + timestamp define identity in the modeled write semantics
Measurement + tag set + timestamp define identity in the modeled write semantics

Scientific architecture · InfluxDB points, tags and time-window aggregation

InfluxDB identity and window — Measurement / climate; Tag set / device=pi01; Timestamp / t0; Field set / temp=25, hum=55; Same identity update / query window mean
Scientific concept map: Sensor point — Measurement, tag, field; Line protocol — Timestamp; InfluxDB — Time-series storage; Window query — Select interval; Aggregation — Mean / count.

Scientific foundations and analytical reasoning

InfluxDB point identity is measurement, tag set and timestamp. Fields can be updated for a matching identity; query windows select timestamps.

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 · Time-series point identity

A time-series database organizes measurements by time, with tags typically used for indexed dimensions and fields for values. InfluxDB point identity in this lab is measurement, tag set and timestamp; another write with identical identity can merge or replace field values. Distinct timestamp or tag set forms a distinct point.

Worked example and engineering interpretation

Two temperature writes with measurement room, tag device=A and identical timestamp describe one point identity, not two independent samples. A window average of 20,22,24 is 22. Compare time bounds, tag filtering and field selection before attributing a query discrepancy to missing data.

Engineering principles · additional worked teaching example

A time-series point is identified by measurement, tag set and timestamp; fields contain values. A window's endpoint inclusion changes count. Given timestamps 2,4,6,8,10 and inclusive [4,8], include 4,6,8 (three); in [4,8) only 4,6.

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 42 · IoT time-series data with InfluxDB

InfluxDB identifies a point by measurement, tag set and timestamp; a repeated point can update fields. A range query selects points by time. This in-memory model teaches point identity and window membership; it does not emulate the full database.

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: Write and query InfluxDB records using the configured credentials.

  1. Create three points for node a with different temperatures. Record line protocol and timestamps.
  2. Reuse the last timestamp and change temperature; confirm existing point update. Switch node and repeat to observe distinct identity.
  3. In the independent window instrument generate samples, reduce query window and calculate the selected mean by hand.
  4. Execute the existing actual InfluxDB write/query procedure using your authorized token.

Reference check:

Model boundary:

Independent task and submission evidence

Hold node and end time fixed; compare 20 s and 4 s windows. Record membership and mean, then add a different node at the same timestamp and explain identity. Use the WSL procedure to test actual InfluxDB.

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: Points generated = 8; Interval (s) = 5; Query window (s) = 20; Overwrite last timestamp = false. In the classroom model, Stored points = 8; Query points = 5; Query mean = 30 °C. The local teaching query includes both time endpoints; actual Flux range stop is exclusive. 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 42 · IoT time-series data with InfluxDB: progressive data plot2526.7528.530.2532Stored temperatureQuery member0350

Step 1 of 7 · Observation 0

Observation 0

Stored temperature
25

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

Recall the concept before revealing its explanation.

0 / 3 revealed
P42 · 01 / 08What is a time-series bucket?Reveal explanation
Engineering explanation

InfluxDB storage for timestamped measurements.

P42 · 02 / 08Does a healthy service prove writes?Reveal explanation
Engineering explanation

No: organization, bucket, token scope and query must also be correct.

P42 · 03 / 08Which InfluxDB service and write prerequisites must be verified?Reveal explanation
Engineering explanation

Complete onboarding for organization psut and bucket greenhouse; create a scoped read/write token. Verify a query after the write. Stop optional live producer with Ctrl+C; keep token private.

P42 · 04 / 08What identifies a point in an InfluxDB time series?Reveal explanation
Engineering reasoning

Measurement, tag set and timestamp identify the series point; fields contain observed values.

P42 · 05 / 08Why query after writing?Reveal explanation
Engineering reasoning

A successful client call must be reconciled with the expected measurement, time range and actual stored field values.

P42 · 06 / 08An InfluxDB write is attempted. Select every technically valid statement. A. Verify stored records with a query. B. Keep token and organization settings aligned with the configured database. C. An HTTP connection proves every measurement was persisted. D. A token is safe to embed in all public HTML.Reveal explanation
Applied scenario

Correct: A. Verify stored records with a query.; B. Keep token and organization settings aligned with the configured database.

P42 · 07 / 08In IoT time-series data with InfluxDB, which command or code executes Optional live data?Reveal explanation
Implementation recall

sed 's/LIVE = False/LIVE = True/; s/LIVE_PERIOD = 60/LIVE_PERIOD = 10/' greenhouse_node.py > live_node.py python live_node.py

P42 · 08 / 08For IoT time-series data with InfluxDB, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

After setup --influx, check /health, initialize InfluxDB UI if needed, create org psut and bucket greenhouse, then obtain a scoped read/write token. Source influx.env before running the node and controller in that same terminal. Historical node writes 30 minute-spaced mock points; repeating within a five-minute time bin may overwrite identical series/timestamps. Query node pi-01/source mock, rather than counting all bucket records. The live variant writes continuously; stop it after observing new timestamps.

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 InfluxDB 2. 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.
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

Write and query InfluxDB records using the configured credentials.

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 workbenchP42 · Existing model
01 / Explore

Interactive lab simulation

Browser model
P42 · 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

P42 · 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 42 · IoT time-series data with InfluxDB

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

Prepare a contextual AI prompt

0 characters

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

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

Run & verify — acceptance checklist

Build verification: Source and configuration checked; actual InfluxDB pending.

After setup --influx, check /health, initialize InfluxDB UI if needed, create org psut and bucket greenhouse, then obtain a scoped read/write token. Source influx.env before running the node and controller in that same terminal. Historical node writes 30 minute-spaced mock points; repeating within a five-minute time bin may overwrite identical series/timestamps. Query node pi-01/source mock, rather than counting all bucket records. The live variant writes continuously; stop it after observing new timestamps.

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

Eight points at 0,5,…,35 s are queried over the inclusive last 20 s. List included timestamps and count.

02 · Compare or justify using evidence

Compare inserting a new field at the same identity with inserting at a new timestamp. Explain why changing a tag changes the identity.

03 · Calculation

Calculation · Independent work

A data source has times 0,4,8,12,16,20. Compare [8,20] with [8,20) and explain the effect of writing the same measurement/tag/time identity.

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 · P42-01

Use the reference configuration (Points generated = 8; Interval (s) = 5; Query window (s) = 20; Overwrite last timestamp = false), but change Points generated = 10. The model reports Stored points = 10. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · P42-02

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

Intermediate · Interpret a technical trace

Independent theoretical exercise · P42-03

For Interval (s) = 7, the model supplies this excerpt from Point table: Timestamp (s) · Value · Selected 0 · 25 · No 7 · 26 · No 14 · 27 · No 21 · 28 · No 28 · 29 · No Compute the range (maximum minus minimum) of the Value column in these rows. Identify the maximum observation. Do not extrapolate beyond these rows.

Advanced · Reverse reasoning

Independent theoretical exercise · P42-04

An observation is Query points = 3. Candidate A uses Points generated = 8; Interval (s) = 5; Query window (s) = 20; Overwrite last timestamp = false. Candidate B changes the listed settings (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 · P42-05

A student configures Query window (s) = 18 while preserving all other reference settings, but copies the reference report of Query points = 5. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · P42-06

Design a controlled comparison for Lab 42 · IoT time-series data with InfluxDB using reference Points generated = 8; Interval (s) = 5; Query window (s) = 20; Overwrite last timestamp = false and test Points generated = 10. Specify the changed setting(s), measured metric Stored points, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Live simulation · InfluxDB point identity and queries

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

  1. Create three points for node a with different temperatures. Record line protocol and timestamps.
  2. Reuse the last timestamp and change temperature; confirm existing point update. Switch node and repeat to observe distinct identity.
  3. In the independent window instrument generate samples, reduce query window and calculate the selected mean by hand.
  4. Execute the existing actual InfluxDB write/query procedure using your authorized token.

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

Generate line-protocol records and calculate a selected time-window query, including duplicate series/timestamp overwrite.

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.

Points generated8
Interval (s)5
Query window (s)20
Overwrite last timestampNo

2 · Perform the investigation in order

  1. Insert eight sensor points, spacing 5 s; query the inclusive last 20 s.
  2. Overwrite the last point with a different field value at the same series/timestamp; compare stored count and query mean.
  3. Reduce time window to 4 s; inspect membership.
  4. Execute the actual InfluxDB notebook and compare timestamp/tag/field semantics and query boundary conventions.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Recent windowUse reference inputs aboveStored points: 8; Query points: 5Record actual result
Overwrite same keyOverwrite last timestamp = YesStored points: 8Record actual result
Short queryQuery window (s) = 4Query points: 1Record actual result

4 · Analyze and report

Series identity includes measurement and tag set; identical point key can merge/overwrite fields.

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. 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 and check InfluxDB 2
  2. Create organization and bucket
  3. Save the token for future lab terminals
  4. Write and query greenhouse history
  5. Optional live data
02 / Implement

Step-by-step instructions

Before you run / verification gate

Complete onboarding for organization psut and bucket greenhouse; create a scoped read/write token. Verify a query after the write. Stop optional live producer with Ctrl+C; keep token private.

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 and check InfluxDB 2

One time only. Complete base setup before this.

WSL · Bash
bash ~/psut-wsl/setup_wsl.sh --influx
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 (2)
  1. bash ~/psut-wsl/setup_wsl.sh --influxThe installer completes and returns to the prompt. Verify the selected services and run the toolkit self-test; package logs may vary.
  2. 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 Status pass.
02

Create organization and bucket

In the Windows browser open http://localhost:8086. If onboarding appears, choose a unique password, username of your choice, organization psut, bucket greenhouse. If already configured, sign in and create missing organization/bucket. Under Load Data → API Tokens create a custom token with read and write access to greenhouse. Copy it privately. No fixed credentials.

Checkpoint Complete the action before continuing.
03

Save the token for future lab terminals

Paste the token at the hidden prompt. The file is private to your Linux user. Do not share it.

WSL · Bash
mkdir -p ~/.config/psut-wsl
chmod 700 ~/.config/psut-wsl
read -rsp "InfluxDB read/write token: " token; echo
(umask 077; printf 'export INFLUX_TOKEN=%q\n' "$token" > ~/.config/psut-wsl/influx.env)
unset token
chmod 600 ~/.config/psut-wsl/influx.env
source ~/.config/psut-wsl/influx.env
✓ Expected: The private token configuration file is written without displaying its contents. Verify permissions are 600.
Expected result for each action (7)
  1. mkdir -p ~/.config/psut-wslNormally silent. The requested directory exists afterward; verify with ls -d.
  2. chmod 700 ~/.config/psut-wslNormally silent. Verify with ls -l or stat; a private directory should be 700 and a private credential file 600 where specified.
  3. read -rsp "InfluxDB read/write token: " token; echoA secret-entry prompt appears; typing is not echoed. Enter only your local lab credential. Nothing should expose its value.
  4. (umask 077; printf 'export INFLUX_TOKEN=%q\n' "$token" > ~/.config/psut-wsl/influx.env)The private token configuration file is written without displaying its contents. Verify permissions are 600.
  5. unset tokenUsually silent. The named variable is removed from the current shell, not from existing files or external services.
  6. chmod 600 ~/.config/psut-wsl/influx.envNormally silent. Verify with ls -l or stat; a private directory should be 700 and a private credential file 600 where specified.
  7. source ~/.config/psut-wsl/influx.envThe token becomes available to child processes without being printed. Check only whether it is set, then test authorized access.
Checkpoint No token displayed.
04

Write and query greenhouse history

The node uses mathematical sensor data, not actual Pi measurements.

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/python/lab42
source ~/.config/psut-wsl/influx.env
python greenhouse_node.py
python greenhouse_controller.py
✓ Expected: Controller decisions based on stored greenhouse history are printed; the exact counts depend on existing data.
Expected result for each action (5)
  1. source ~/psut-wsl/activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
  2. 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.
  3. source ~/.config/psut-wsl/influx.envThe token becomes available to child processes without being printed. Check only whether it is set, then test authorized access.
  4. python greenhouse_node.pyThe program writes 30 historical points using the configured token and bucket; inspect errors and query history separately.
  5. python greenhouse_controller.pyController decisions based on stored greenhouse history are printed; the exact counts depend on existing data.
Checkpoint 30 history points written; controller prints decisions. Exact event counts depend on previous data.
05

Optional live data

Keep running for Grafana Lab 44; Ctrl+C to stop.

WSL · Bash
sed 's/LIVE = False/LIVE = True/; s/LIVE_PERIOD = 60/LIVE_PERIOD = 10/' greenhouse_node.py > live_node.py
python live_node.py
✓ Expected: Simulated greenhouse points are written periodically (10 s in the specified edited variant). Stop with Ctrl+C; verify stored records.
Expected result for each action (2)
  1. sed 's/LIVE = False/LIVE = True/; s/LIVE_PERIOD = 60/LIVE_PERIOD = 10/' greenhouse_node.py > live_node.pyA separate live_node.py file is created with the edited settings; inspect it before running.
  2. python live_node.pySimulated greenhouse points are written periodically (10 s in the specified edited variant). Stop with Ctrl+C; verify stored records.
Checkpoint New simulated points every 10 seconds.
Live visualization extension: proceed to Lab 43 to view equivalent greenhouse sensor fields in Node-RED alongside InfluxDB. Direct historical writes in Lab 42 do not automatically publish MQTT.

Experimental notebook

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

03 / Inspect

Source code and method

labs/python/lab42/greenhouse-node.serviceDownload source
SERVICE · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- /etc/systemd/system/greenhouse-node.service  (run the node at every boot)
[Unit]
Description=PSUT greenhouse sensor node
After=network-online.target influxdb.service

[Service]
User=pi
Environment=INFLUX_URL=http://localhost:8086 INFLUX_ORG=psut INFLUX_BUCKET=greenhouse
EnvironmentFile=/home/pi/.influx_token          # one line: INFLUX_TOKEN=...
ExecStart=/home/pi/iot-env/bin/python /home/pi/greenhouse_node.py
Restart=on-failure

[Install]
WantedBy=multi-user.target

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

import os
from datetime import datetime, timezone

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


# ---- Connection settings (same as the sensor node)
URL = os.getenv("INFLUX_URL", "http://localhost:8086")
TOKEN = os.environ["INFLUX_TOKEN"]
ORG = os.getenv("INFLUX_ORG", "psut")
BUCKET = os.getenv("INFLUX_BUCKET", "greenhouse")
SITE, NODE = "psut-greenhouse", "pi-01"

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


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

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

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

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

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


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


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

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

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

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

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

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

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


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


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


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


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


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


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


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

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

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

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

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

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

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

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

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


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

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

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


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


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

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


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

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

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

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


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


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

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

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

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

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


if __name__ == "__main__":
    main()
labs/python/lab42/install_influxdb2.shDownload source
SH · source file
#!/usr/bin/env bash
set -euo pipefail
bash "$HOME/psut-wsl/setup_wsl.sh" --influx
curl -fsS http://127.0.0.1:8086/health
labs/python/lab42/real_sensors.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- On the real Pi: replace MockSensors.read() with real sensors
#      pip install adafruit-circuitpython-dht   (and: sudo apt install libgpiod2)
import adafruit_dht, board

dht = adafruit_dht.DHT22(board.D4)              # DHT22 data pin on GPIO4

def read() -> dict:
    return {"temperature": float(dht.temperature),   # float, never int: keep the field type
            "humidity": float(dht.humidity),
            "soil_moisture": read_soil_percent()}    # your ADC code (e.g. ADS1115 over I²C)
labs/python/lab42/setup_python.shDownload source
SH · source file
#!/usr/bin/env bash
# Source this file, do not execute it as a child shell.
source "$HOME/psut-wsl/activate.sh"
source "$HOME/.config/psut-wsl/influx.env"
export INFLUX_URL=http://127.0.0.1:8086 INFLUX_ORG=psut INFLUX_BUCKET=greenhouse
labs/python/lab42/write_one_point.shDownload source
SH · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- One point by hand: POST line protocol to /api/v2/write
curl -i -X POST "http://localhost:8086/api/v2/write?org=psut&bucket=greenhouse&precision=s" \
  -H "Authorization: Token $INFLUX_TOKEN" \
  -H "Content-Type: text/plain; charset=utf-8" \
  --data-binary "environment,node=pi-02,site=psut-greenhouse,zone=B humidity=61.0,soil_moisture=48.5,temperature=25.4 $(date +%s)"
# HTTP/1.1 204 No Content   ← stored (no body)
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.

Python / Google Colab laboratory

P42 · 7 notebook cells · 2 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
# P42 · Lab 42 · IoT time-series data with InfluxDB **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose InfluxDB identifies a point by measurement, tag set and timestamp; a repeated point can update fields. A range query selects points by time. This in-memory model teaches point identity and window membership; it does not emulate the full database. **Execution boundary:** local computational model or loopback as explicitly described; not physical measurements or external service certification. Run cells in order.
02Instructions · Markdown
## 1. Define the experiment mechanism and inputs
03Python · executable cell
PYTHON · Code cell
# =====================================================================
# P42 | Code cell 01 | Lab 42 · IoT time-series data with InfluxDB
# Purpose: 1. Define the experiment mechanism and inputs
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Set points for the next computation or reference condition.
points={}
# Define the reusable operation write; keep its logic separate from the trial.
def write(node,seconds,temp):
    points[('environment',node,seconds)]=temp
    print(f'environment,node={node} temperature={temp} {seconds*10**9}')
# Define the reusable operation query; keep its logic separate from the trial.
def query(node,end,window):
    return [(t,v) for (_,n,t),v in sorted(points.items()) if n==node and end-window<=t<=end]
Ask Dr. Mohammad about this cell
04Instructions · Markdown
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# P42 | Code cell 02 | Lab 42 · IoT time-series data with InfluxDB
# Purpose: 2. Execute the reference and inspect observations
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Repeat the same operation for each configured input so observations are comparable.
for t in range(0,40,5): write('a',t,20+t/5)
print(query('a',35,20))
write('a',35,40)  # Same measurement, tag and time updates one modeled point
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert len(points)==8
# Repeat the same operation for each configured input so observations are comparable.
for w in (20,4):
    rows=query('a',35,w);print(w,rows,sum(v for _,v in rows)/len(rows))
Ask Dr. Mohammad about this cell
06Instructions · Markdown
## Original portal implementation (reference only) These are the actual laboratory snippets. They are retained for comparison; follow the portal setup for WSL, hardware or services. They are **not** executed by Run all. ```bash source ~/psut-wsl/activate.sh cd ~/psut-wsl/labs/python/lab42 source ~/.config/psut-wsl/influx.env python greenhouse_node.py python greenhouse_controller.py ``` ```bash sed 's/LIVE = False/LIVE = True/; s/LIVE_PERIOD = 60/LIVE_PERIOD = 10/' greenhouse_node.py > live_node.py python live_node.py ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- Example 2: greenhouse controller — query InfluxDB, decide, drive GPIO, log # Reads the data that Example 1 stored, asks InfluxDB questions in Flux, # switches a fan (GPIO17) and a water pump (GPIO27) with hysteresis rules, # and writes every decision back to InfluxDB as an "actuator" point. # The GPIO is the mock from Lab 41, so it runs in Google Colab too. import os from datetime import datetime, timezone from influxdb_client import InfluxDBClient, Point from influxdb_client.client.write_api import SYNCHRONOUS # ---- Connection settings (same as the sensor node) URL = os.getenv("INFLUX_URL", "http://localhost:8086") TOKEN = os.environ["INFLUX_TOKEN"] ORG = os.getenv("INFLUX_ORG", "psut") BUCKET = os.getenv("INFLUX_BUCKET", "greenhouse") SITE, NODE = "psut-greenhouse", "pi-01" # ---- Control rules with hysteresis: two thresholds, so the relay does not chatter FAN_ON_ABOVE, FAN_OFF_BELOW = 30.0, 28.0 # °C, mean of the last 10 readings PUMP_ON_BELOW, PUMP_OFF_ABOVE = 35.0, 45.0 # % soil moisture, latest reading SMOOTHING = 10 # readings averaged for the fan rule # ---- Mock RPi.GPIO and the LED class from Lab 41 (an LED stands in for each relay) class MockGPIO: """Stand-in for RPi.GPIO: prints every call instead of driving hardware.""" BCM, OUT, HIGH, LOW = 'BCM', 'OUT', True, False @staticmethod def setmode(mode): print(f"GPIO mode set to {mode}") @staticmethod def setup(pin, mode): print(f"GPIO pin {pin} set up as {mode}") @staticmethod def output(pin, state): print(f"GPIO pin {pin} set to {'HIGH' if state else 'LOW'}") @staticmethod def cleanup(): print("GPIO cleanup") GPIO = MockGPIO # on a real Pi: import RPi.GPIO as GPIO class LED: """One output on one GPIO pin (here: the indicator LED of a relay).""" def __init__(self, pin: int) -> None: self.pin = pin GPIO.setmode(GPIO.BCM) GPIO.setup(self.pin, GPIO.OUT) self.state = GPIO.LOW GPIO.output(self.pin, self.state) # start OFF def turn_on(self) -> None: self.state = GPIO.HIGH GPIO.output(self.pin, self.state) def turn_off(self) -> None: self.state = GPIO.LOW GPIO.output(self.pin, self.state) @staticmethod def check_pin_availability(pin: int) -> bool: return 1 <= pin <= 40 @classmethod def create_led(cls, pin: int) -> 'LED': if cls.check_pin_availability(pin): return cls(pin) raise ValueError("GPIO pin is not available") def cleanup(self) -> None: GPIO.cleanup() # ---- Flux queries: each one is a pipeline of functions joined by |> def flux_latest(field: str) -> str: """The newest value of one field.""" return f'''from(bucket: "{BUCKET}") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "environment" and r._field == "{field}") |> filter(fn: (r) => r.node == "{NODE}") |> last()''' def flux_recent_mean(field: str, n: int) -> str: """The mean of the newest n values of one field (smooths sensor noise).""" return f'''from(bucket: "{BUCKET}") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "environment" and r._field == "{field}") |> filter(fn: (r) => r.node == "{NODE}") |> tail(n: {n}) |> mean()''' def flux_windows(field: str) -> str: """One mean per 5-minute window (what a dashboard graph shows).""" return f'''from(bucket: "{BUCKET}") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "environment" and r._field == "{field}") |> filter(fn: (r) => r.node == "{NODE}") |> aggregateWindow(every: 5m, fn: mean, createEmpty: false)''' def flux_actuator_state() -> str: """The last logged state of every actuator (one table per device tag).""" return f'''from(bucket: "{BUCKET}") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "actuator" and r._field == "state") |> filter(fn: (r) => r.node == "{NODE}") |> last()''' def first_value(query_api, flux: str): """Run a query and return the first value, or None if there is no data.""" tables = query_api.query(flux, org=ORG) if not tables or not tables[0].records: return None return tables[0].records[0].get_value() # ---- Hysteresis: switch on above one threshold, off below another, else keep def decide(is_on: bool, value: float, on_when, off_when) -> bool: if not is_on and on_when(value): return True if is_on and off_when(value): return False return is_on # ---- Main program def main() -> None: fan = pump = None try: with InfluxDBClient(url=URL, token=TOKEN, org=ORG) as client: query_api = client.query_api() write_api = client.write_api(write_options=SYNCHRONOUS) # ---- 1. What is happening now? t = first_value(query_api, flux_latest("temperature")) h = first_value(query_api, flux_latest("humidity")) s = first_value(query_api, flux_latest("soil_moisture")) if t is None: raise SystemExit("No data yet: run Example 1 (greenhouse_node.py) first.") print(f"Latest reading: T={t:.1f} °C RH={h:.1f} % soil={s:.1f} %") # ---- 2. The trend: one mean per 5-minute window, oldest first records = query_api.query(flux_windows("temperature"), org=ORG)[0].records print("Temperature, 5-minute means (oldest first):") for number, rec in enumerate(records, start=1): print(f" window {number} {rec.get_value():5.2f} °C") # rec.get_time() = window end # ---- 3. Smoothed value for the fan rule t_mean = first_value(query_api, flux_recent_mean("temperature", SMOOTHING)) print(f"Mean of the last {SMOOTHING} temperatures: {t_mean:.2f} °C") # ---- 4. Previous actuator states are stored in InfluxDB too (OFF if none yet) previous = {"fan": False, "pump": False} for table in query_api.query(flux_actuator_state(), org=ORG): for rec in table.records: previous[rec.values["device"]] = rec.get_value() == 1 # ---- 5. Decide with hysteresis fan_on = decide(previous["fan"], t_mean, lambda v: v > FAN_ON_ABOVE, lambda v: v < FAN_OFF_BELOW) pump_on = decide(previous["pump"], s, lambda v: v < PUMP_ON_BELOW, lambda v: v > PUMP_OFF_ABOVE) # ---- 6. Act: drive the GPIO pins (fan relay GPIO17, pump relay GPIO27) fan = LED.create_led(17) pump = LED.create_led(27) fan.turn_on() if fan_on else fan.turn_off() pump.turn_on() if pump_on else pump.turn_off() print(f"Fan {'ON ' if fan_on else 'OFF'} (mean {t_mean:.2f} °C, on above {FAN_ON_ABOVE}, off below {FAN_OFF_BELOW})") print(f"Pump {'ON ' if pump_on else 'OFF'} (soil {s:.1f} %, on below {PUMP_ON_BELOW}, off above {PUMP_OFF_ABOVE})") # ---- 7. Log the decisions: actuator points, state as an integer 0/1 now = datetime.now(timezone.utc) reasons = {"fan": f"mean {t_mean:.2f} C", "pump": f"soil {s:.1f} %"} events = [ Point("actuator").tag("site", SITE).tag("node", NODE).tag("device", device) .field("state", int(on)).field("reason", reasons[device]).time(now) for device, on in (("fan", fan_on), ("pump", pump_on)) ] write_api.write(bucket=BUCKET, org=ORG, record=events) print(f"Logged {len(events)} actuator events") # ---- 8. Read them back: the database now holds the control history stored = {t.records[0].values["device"]: t.records[0].get_value() for t in query_api.query(flux_actuator_state(), org=ORG)} for device in sorted(stored): print(f" stored: {device:<4} state={stored[device]}") finally: if fan is not None: # release the pins whatever happened fan.cleanup() if __name__ == "__main__": main() ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- Example 1: smart greenhouse sensor node → InfluxDB 2 (time-series database) # The Raspberry Pi node reads temperature, humidity and soil moisture and stores # every reading as a time-stamped point in the InfluxDB bucket "greenhouse". # The sensors are simulated (same numbers every run), so the program runs in # Google Colab or on a laptop. Needs: pip install influxdb-client import math # sin() gives the readings a natural wobble import os # read the connection settings from the environment import time # sleep() between live samples from datetime import datetime, timedelta, timezone from influxdb_client import InfluxDBClient, Point, WritePrecision from influxdb_client.client.write_api import SYNCHRONOUS # ---- Connection settings: where InfluxDB runs and who we are # Never hard-code a real token in a shared file: set INFLUX_TOKEN in the environment. URL = os.getenv("INFLUX_URL", "http://localhost:8086") # InfluxDB HTTP API TOKEN = os.environ["INFLUX_TOKEN"] # API token with write access ORG = os.getenv("INFLUX_ORG", "psut") # organisation (workspace) BUCKET = os.getenv("INFLUX_BUCKET", "greenhouse") # bucket = database + retention # ---- Who this node is: these become TAGS (indexed text that describes the data) SITE = "psut-greenhouse" # which greenhouse NODE = "pi-01" # which Raspberry Pi ZONE = "A" # which growing zone HISTORY_MINUTES = 30 # simulate the last 30 minutes, one reading per minute LIVE = False # True on the real Pi: keep sampling forever LIVE_PERIOD = 60 # seconds between live readings # ---- Simulated sensors: a warming afternoon and slowly drying soil class MockSensors: """Stand-in for a DHT22 (temperature, humidity) and a soil-moisture probe. On a real Pi, read() would call the sensor libraries instead. The numbers follow a fixed formula, so every run (and every student) sees the same data. """ def __init__(self) -> None: self.i = 0 # sample counter (minutes since the start) def read(self) -> dict: """Return one reading: temperature in °C, humidity and soil moisture in %.""" i = self.i self.i += 1 return { "temperature": round(24.0 + 0.3 * i + 0.4 * math.sin(1.3 * i), 1), # 24 → 33 °C "humidity": round(72.0 - 0.6 * i + 1.2 * math.sin(0.7 * i), 1), # air dries out "soil_moisture": round(60.0 - 1.0 * i + 0.8 * math.sin(0.9 * i), 1), # 60 → 31 % } # ---- One reading → one InfluxDB point (measurement + tags + fields + timestamp) def make_point(reading: dict, when: datetime) -> Point: """Build the point that InfluxDB stores for one reading.""" return ( Point("environment") # measurement: like a table name .tag("site", SITE) # tags: indexed, used in filters and group by .tag("node", NODE) .tag("zone", ZONE) .tag("source", "mock") .field("temperature", reading["temperature"]) # fields: the measured values .field("humidity", reading["humidity"]) .field("soil_moisture", reading["soil_moisture"]) .time(when, WritePrecision.S) # timestamp, stored with 1-second precision ) # ---- Main program: connect, write 30 minutes of history, then (optionally) live data def main() -> None: with InfluxDBClient(url=URL, token=TOKEN, org=ORG) as client: if not client.ping(): # GET /ping: is the server up? raise SystemExit(f"InfluxDB is not reachable at {URL}") print(f"Connected to InfluxDB at {URL}") write_api = client.write_api(write_options=SYNCHRONOUS) # write now and wait for "OK" sensors = MockSensors() # ---- History: 30 readings, one per minute, ending at the last 5-minute mark now = int(time.time()) end = datetime.fromtimestamp(now - now % 300, tz=timezone.utc) # e.g. 10:35:00 start = end - timedelta(minutes=HISTORY_MINUTES) # e.g. 10:05:00 points = [] for k in range(HISTORY_MINUTES): reading = sensors.read() points.append(make_point(reading, start + timedelta(minutes=k))) if k < 3 or k == HISTORY_MINUTES - 1: # print the first three and the last print(f"t-{HISTORY_MINUTES - k:02d} min T={reading['temperature']:4.1f} °C " f"RH={reading['humidity']:4.1f} % soil={reading['soil_moisture']:4.1f} %") elif k == 3: print(" ...") # ---- What actually travels over HTTP: InfluxDB line protocol line = points[0].to_line_protocol() # measurement,tags fields timestamp print("Line protocol of the first point (timestamp hidden):") print(" " + line.rsplit(" ", 1)[0] + " <unix-seconds>") write_api.write(bucket=BUCKET, org=ORG, record=points) # one HTTP request, 30 points print(f"Wrote {len(points)} points to bucket '{BUCKET}'") # ---- Live mode (real Pi): one reading per LIVE_PERIOD seconds, time = now while LIVE: reading = sensors.read() write_api.write(bucket=BUCKET, org=ORG, record=make_point(reading, datetime.now(timezone.utc))) print(f"live T={reading['temperature']:4.1f} °C soil={reading['soil_moisture']:4.1f} %") time.sleep(LIVE_PERIOD) if __name__ == "__main__": main() ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- On the real Pi: replace MockSensors.read() with real sensors # pip install adafruit-circuitpython-dht (and: sudo apt install libgpiod2) import adafruit_dht, board dht = adafruit_dht.DHT22(board.D4) # DHT22 data pin on GPIO4 def read() -> dict: return {"temperature": float(dht.temperature), # float, never int: keep the field type "humidity": float(dht.humidity), "soil_moisture": read_soil_percent()} # your ADC code (e.g. ADS1115 over I²C) ```
07Instructions · Markdown
## Independent investigation and submission Hold node and end time fixed; compare 20 s and 4 s windows. Record membership and mean, then add a different node at the same timestamp and explain identity. Use the WSL procedure to test actual InfluxDB. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.