# ------------------------------------------------------------
# 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()
