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)
```