"""Lab Monitor: read sensor lines from a microcontroller over a serial port.

The board sends one line per reading, for example:

    T:23.5;L:512

T is the temperature in degrees Celsius, L is the light level (0-1023 from a 10-bit ADC).
The program checks every line, keeps a moving average, and switches the board's LED on
when the room is too warm, by writing "LED:1\n" back to the board.

It works with any object that has readline() and write(), so the same code runs on:
  - a real board:      serial.Serial("COM3", 9600, timeout=1)   (pip install pyserial)
  - no hardware:       SimulatedBoard() from simulated_board.py
"""

from collections import deque

TEMP_LIMIT = 28.0      # degrees Celsius: above this the LED is switched on
WINDOW = 5             # how many readings the moving average uses


def parse_reading(raw):
    """Turn b"T:23.5;L:512\\r\\n" into {"T": 23.5, "L": 512}. Returns None for a bad line."""
    try:
        text = raw.decode("ascii").strip()
    except (UnicodeDecodeError, AttributeError):
        return None
    if not text:
        return None
    values = {}
    for part in text.split(";"):
        key, sep, value = part.partition(":")
        if sep != ":" or key not in ("T", "L"):
            return None
        try:
            values[key] = float(value) if key == "T" else int(value)
        except ValueError:
            return None
    if set(values) != {"T", "L"}:
        return None
    if not -40.0 <= values["T"] <= 125.0 or not 0 <= values["L"] <= 1023:
        return None   # outside what the sensors can measure: a corrupted line
    return values


class LabMonitor:
    def __init__(self, port, temp_limit=TEMP_LIMIT, window=WINDOW):
        self.port = port
        self.temp_limit = temp_limit
        self.temps = deque(maxlen=window)
        self.led_on = False
        self.bad_lines = 0

    def average(self):
        return sum(self.temps) / len(self.temps) if self.temps else None

    def set_led(self, on):
        if on != self.led_on:
            self.port.write(b"LED:1\n" if on else b"LED:0\n")
            self.led_on = on

    def step(self):
        """Read one line and react to it. Returns the reading, or None if the line was bad."""
        reading = parse_reading(self.port.readline())
        if reading is None:
            self.bad_lines += 1
            return None
        self.temps.append(reading["T"])
        self.set_led(self.average() > self.temp_limit)
        return reading

    def run(self, readings):
        for _ in range(readings):
            reading = self.step()
            if reading is None:
                print("skipped a bad line")
                continue
            print(f"T={reading['T']:.1f} C  L={reading['L']:4d}  "
                  f"avg={self.average():.2f} C  LED={'ON' if self.led_on else 'off'}")
        print(f"done: {len(self.temps)} readings kept, {self.bad_lines} bad lines")


if __name__ == "__main__":
    from simulated_board import SimulatedBoard
    LabMonitor(SimulatedBoard(seed=4)).run(16)
