"""Industrial Modbus RTU/TCP (`pylotos.modbus`) & CAN 2.0B / TWAI Gateway.

Demonstrates Phase 4C industrial automation protocols:
- Building CRC-16 verified Modbus RTU Function `0x03` Holding Register requests
- Transmitting & receiving CAN 2.0B / TWAI frames zero-copy (`hal.can_send` / `can_recv_into`)

Run locally:
    pylotos-sim examples/modbus_plc_and_can_gateway.py --board m5stack_core2 --port 8080
"""

import struct

import hal
import pylotos.ui as ui
from pylotos import modbus

_can_buf = bytearray(8)
hal.can_init(tx_gpio=26, rx_gpio=36, bitrate_bps=500000)

st = ui.State(
    unit_id=1,
    reg_addr=16,
    reg_count=2,
    rtu_hex="(none)",
    can_id=0x180,
    can_frames=0,
    can_rx_str="(waiting)",
)


def _build_modbus():
    pdu = modbus.build_read_holding_pdu(int(st.reg_addr), int(st.reg_count))
    frame = modbus.build_rtu_frame(int(st.unit_id), 0x03, pdu)
    st.rtu_hex = " ".join("{:02X}".format(b) for b in frame)
    app.notify("RTU CRC-16 frame ready ({} B)".format(len(frame)), level="ok", icon="terminal")


def _send_can_pdo():
    data = struct.pack(">HHHH", int(st.unit_id), int(st.reg_addr), int(st.reg_count), st.can_frames + 1)
    hal.can_send(int(st.can_id), data)
    st.can_frames = st.can_frames + 1
    rx = hal.can_recv_into(_can_buf)
    if rx is not None:
        arb_id, dlc, _ext = rx
        st.can_rx_str = "0x{:03X} ({}B)".format(arb_id, dlc)


app = ui.App(
    "Modbus & CAN",
    state=st,
    screens=[
        ui.Screen(
            "Modbus RTU",
            icon="terminal",
            children=[
                ui.Card(
                    "FC 0x03 Read Holding",
                    children=[
                        ui.KeyValue("RTU Frame", st.bind("rtu_hex")),
                        ui.NumberField("Slave Unit ID", st.bind("unit_id"), min=1, max=247, step=1),
                        ui.NumberField("Start Register", st.bind("reg_addr"), min=0, max=9999, step=1),
                        ui.Button("Build CRC-16 Frame", on_click=_build_modbus, shortcut="b"),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "CAN / TWAI",
            icon="cpu",
            children=[
                ui.Metric("CAN PDO TX", st.bind("can_frames"), accent="gold"),
                ui.Card(
                    "500 kbps TWAI Bus",
                    children=[
                        ui.KeyValue("Last Loopback", st.bind("can_rx_str")),
                        ui.Button("Transmit CAN PDO", on_click=_send_can_pdo, shortcut="c"),
                    ],
                ),
            ],
        ),
    ],
)

_build_modbus()


async def run(cv):
    try:
        await app.run_async(cv)
    finally:
        hal.can_deinit()
