"""RS-485 Hardware DE/RE, DMX512 Lighting & Filtered CAN OBD-II — PylotOS Wired C HAL.

Demonstrates:
- Hardware DE/RE `hal.rs485` half-duplex UART for zero-jitter Modbus RTU & DMX512
- `hal.rs485.tx_break(92, 12)` ANSI E1.11 DMX512 break + MAB + `pylotos.wired.pack_dmx512_frame()`
- `hal.can` unified TWAI/MCP2515 API with acceptance filter (`0x7E8`, mask `0x7F8`)
- `pylotos.wired.decode_obd2_pid()` & `format_can_frame()` zero-copy reception

Run locally:
    pylotos-sim examples/rs485_modbus_and_dmx512.py --board m5stack_core2
"""

import hal
import pylotos.modbus as modbus
import pylotos.ui as ui
import pylotos.wired as wired

st = ui.State(
    dmx_ch1=180,
    dmx_ch2=96,
    dmx_frames=0,
    rtu_bytes=0,
    obd_rpm=0,
    obd_speed=0,
    last_can="---",
    status="Wired fieldbuses initialized",
)

_rx_rs485 = bytearray(64)
_rx_can = bytearray(64)


def init_buses():
    hal.rs485.open(uart=1, tx=17, rx=16, de=21, baudrate=250000, stop_bits=2, port="grove_c")
    hal.can.open("twai", tx=26, rx=36, bitrate=500000, port="grove_b")
    hal.can.set_filter(0x7E8, 0x7F8)


def send_dmx_frame():
    frame = wired.pack_dmx512_frame([int(st.dmx_ch1), int(st.dmx_ch2), 255, 64])
    hal.rs485.tx_break(92, 12)
    written = hal.rs485.write(frame, 50)
    st.dmx_frames = int(st.dmx_frames) + 1
    st.status = "DMX512 TX %d B (CH1=%d, CH2=%d)" % (written, int(st.dmx_ch1), int(st.dmx_ch2))
    app.notify("DMX512 universe refreshed", level="ok")


def poll_modbus_rtu():
    pdu = modbus.build_read_holding_pdu(0x0010, 4)
    req = modbus.build_rtu_frame(1, 0x03, pdu)
    hal.rs485.write(req, 50)
    got = hal.rs485.read_into(_rx_rs485, 20)
    st.rtu_bytes = int(st.rtu_bytes) + got
    st.status = "RS-485 Modbus RTU loopback %d B" % got


def poll_obd2_can():
    # Simulated ECU Mode 0x01 responses on 0x7E8: RPM=2450 ((0x26<<8|0x48)//4) & Speed=84 km/h
    hal.can.send(0x7E8, bytes((4, 0x41, 0x0C, 0x26, 0x48, 0, 0, 0)))
    hal.can.send(0x7E8, bytes((3, 0x41, 0x0D, 84, 0, 0, 0, 0)))
    # Non-matching CAN ID 0x123 is dropped by the 0x7E8/0x7F8 acceptance filter
    hal.can.send(0x123, bytes((1, 2, 3, 4)))

    while True:
        res = hal.can.recv_into(_rx_can, 0)
        if res is None:
            break
        aid, n, ext = res
        payload = bytes(_rx_can[:n])
        st.last_can = wired.format_can_frame(aid, payload, ext)
        if aid == 0x7E8 and n >= 4:
            dec = wired.decode_obd2_pid(payload)
            if dec["name"] == "engine_rpm":
                st.obd_rpm = dec["value"]
            elif dec["name"] == "vehicle_speed":
                st.obd_speed = dec["value"]
    st.status = "CAN OBD-II: %d rpm / %d km/h" % (int(st.obd_rpm), int(st.obd_speed))


dmx_screen = ui.Screen(
    "RS-485 & DMX512",
    [
        ui.Slider("DMX Ch1 (Warm)", st.bind("dmx_ch1"), 0, 255, step=15),
        ui.Slider("DMX Ch2 (Cool)", st.bind("dmx_ch2"), 0, 255, step=15),
        ui.Grid(
            [
                ui.Metric("DMX Frames", st.bind("dmx_frames"), accent="gold"),
                ui.Metric("RTU Bytes", st.bind("rtu_bytes"), accent="cyan"),
            ],
            cols=2,
        ),
        ui.Row(
            [
                ui.Button("Send DMX512", send_dmx_frame, shortcut="1"),
                ui.Button("Poll RTU", poll_modbus_rtu, shortcut="2"),
            ]
        ),
        ui.StatusBadge("Bus", st.bind("status"), tone="ok"),
    ],
)

can_screen = ui.Screen(
    "CAN OBD-II",
    [
        ui.Grid(
            [
                ui.Gauge("Engine RPM", st.bind("obd_rpm"), 0, 6000, unit="rpm"),
                ui.Gauge("Speed", st.bind("obd_speed"), 0, 200, unit="km/h"),
            ],
            cols=2,
        ),
        ui.KeyValue("Last Frame", st.bind("last_can")),
        ui.Button("Poll OBD-II (0x7E8 Filter)", poll_obd2_can, shortcut="3"),
    ],
)

app = ui.App("RS-485 / DMX / CAN", [dmx_screen, can_screen], state=st)
init_buses()
poll_obd2_can()


async def run(cv):
    await app.run_async(cv)
