#!/usr/bin/env python3
"""Reads gateway log lines on stdin and prints a live uplink/downlink table.

Understands both forwarders a Dragino gateway can run:
  - Semtech UDP (fwd): logread lines carrying the JSON sent to the server ({"rxpk": ...} / {"txpk": ...})
  - Basic Station: /var/iot/station.log RX/TX lines
"""
import base64
import json
import os
import re
import sys

RX = re.compile(
    r"^(?P<ts>\S+ \S+) station\[S2E:VERB\] RX (?P<freq>[\d.]+)MHz (?P<dr>DR\d+) (?P<sf>SF\d+/BW\d+) "
    r"snr=(?P<snr>-?[\d.]+) rssi=(?P<rssi>-?\d+) xtime=\S+ - (?P<rest>.*)$"
)
TX = re.compile(
    r"^(?P<ts>\S+ \S+) station\[S2E:INFO\] TX .*dntxed: (?P<freq>[\d.]+)MHz (?P<pwr>[\d.]+)dBm "
    r"\S+ (?P<dr>DR\d+) (?P<sf>SF\d+/BW\d+) frame=(?P<frame>\S+) \((?P<len>\d+) bytes\)"
)
FIELD = re.compile(r"(DevAddr|FCnt|DevEui|JoinEui)=(\S+)")
LOGTIME = re.compile(r"\b(\d{2}:\d{2}:\d{2})\b")
MTYPES = ["JoinReq", "JoinAcc", "UnconfUp", "UnconfDn", "ConfUp", "ConfDn", "Rejoin", "Propr"]
# Data rate per SF/BW; US915 above 900 MHz, EU868 below
DR_US = {"SF10BW125": 0, "SF9BW125": 1, "SF8BW125": 2, "SF7BW125": 3, "SF8BW500": 4,
         "SF12BW500": 8, "SF11BW500": 9, "SF10BW500": 10, "SF9BW500": 11, "SF7BW500": 13}
DR_EU = {"SF12BW125": 0, "SF11BW125": 1, "SF10BW125": 2, "SF9BW125": 3, "SF8BW125": 4,
         "SF7BW125": 5, "SF7BW250": 6}
HEADER = f"{'TIME':<12} {'DIR':<3} {'FREQ MHz':>8} {'DR':<4} {'SF/BW':<10} {'RSSI':>5} {'SNR':>5}  {'SIGNAL':<10} DETAILS"

def bar(rssi):
    # -120 dBm (weak) .. -60 dBm (strong), 10 cells
    cells = max(0, min(10, round((rssi + 120) / 6)))
    return ("█" * cells).ljust(10, "·")

def eui(b):
    return b[::-1].hex().upper()

def decode(data):
    """Describes a LoRaWAN PHYPayload from its unencrypted headers."""
    try:
        b = base64.b64decode(data)
    except ValueError:
        return "undecodable"
    if not b:
        return "empty"
    mtype = MTYPES[b[0] >> 5]
    if mtype == "JoinReq" and len(b) >= 23:
        return f"{mtype} JoinEui={eui(b[1:9])} DevEui={eui(b[9:17])} {len(b)}B"
    if mtype in ("UnconfUp", "UnconfDn", "ConfUp", "ConfDn") and len(b) >= 12:
        fopts = b[5] & 0x0F
        port = f" FPort={b[8 + fopts]}" if len(b) > 12 + fopts else ""
        return (f"{mtype} DevAddr={eui(b[1:5])} FCnt={int.from_bytes(b[6:8], 'little')}"
                f"{port} {len(b)}B")
    return f"{mtype} {len(b)}B"

def datarate(freq, datr):
    table = DR_US if freq > 900 else DR_EU
    return f"DR{table[datr]}" if datr in table else ""

def sfbw(datr):
    return datr.replace("BW", "/BW") if isinstance(datr, str) else str(datr)

def print_up(ts, freq, dr, sf, rssi, snr, details):
    print(f"{ts:<12} \033[32mUP\033[0m  {freq:>8} {dr:<4} {sf:<10} "
          f"{rssi:>5} {snr:>5}  {bar(rssi)} {details}", flush=True)

def print_down(ts, freq, dr, sf, details):
    print(f"{ts:<12} \033[33mDN\033[0m  {freq:>8} {dr:<4} {sf:<10} "
          f"{'':>5} {'':>5}  {'':<10} {details}", flush=True)

def udp_line(line):
    """Handles a logread line from the Semtech UDP forwarder; returns False if it carries no packets."""
    start = line.find("{")
    if start < 0 or ("rxpk" not in line and "txpk" not in line):
        return False
    try:
        msg = json.loads(line[start:])
    except ValueError:
        return False
    t = LOGTIME.search(line[:start])
    ts = t.group(1) if t else ""
    for p in msg.get("rxpk", []):
        if p.get("modu") != "LORA" or p.get("stat", 1) != 1:
            continue  # FSK or bad CRC
        freq = float(p.get("freq", 0))
        rssi = int(p.get("rssi", 0))
        print_up(ts, f"{freq:.1f}", datarate(freq, p.get("datr")), sfbw(p.get("datr")),
                 rssi, p.get("lsnr", ""), decode(p.get("data", "")))
    tx = msg.get("txpk")
    if tx:
        freq = float(tx.get("freq", 0))
        print_down(ts, f"{freq:.1f}", datarate(freq, tx.get("datr")), sfbw(tx.get("datr")),
                   f"{tx.get('powe', '')}dBm {decode(tx.get('data', ''))}")
    return True

def main():
    print(HEADER)
    print("-" * len(HEADER), flush=True)
    for line in sys.stdin:
        line = line.strip()
        if udp_line(line):
            continue
        m = RX.match(line)
        if m:
            rest = m["rest"]
            kind = rest.split(" ", 1)[0]
            fields = " ".join(f"{k}={v}" for k, v in FIELD.findall(rest))
            size = re.search(r"\((\d+) bytes\)", rest)
            details = f"{kind} {fields} {size.group(1) + 'B' if size else ''}".strip()
            print_up(m["ts"][11:23], m["freq"], m["dr"], m["sf"], int(m["rssi"]), m["snr"], details)
            continue
        m = TX.match(line)
        if m:
            print_down(m["ts"][11:23], m["freq"], m["dr"], m["sf"], f"{m['pwr']}dBm {m['len']}B")

if __name__ == "__main__":
    if sys.stdin.isatty():
        # Run directly: start the SSH feed, which pipes the log back into this script
        script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "monitor-lorawan.sh")
        os.execv(script, [script] + sys.argv[1:])
    try:
        main()
    except KeyboardInterrupt:
        pass
