from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from pprint import pprint

from sx126x import SX126X, Mode, Address


def main():
    ap = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
    ap.add_argument("-p", "--port", default=None, type=str, help="Serial port")
    ap.add_argument("-ra", "--rx-address", default="242.242", type=str, help="RX address")
    ap.add_argument("-c", "--channel", default=1, type=int, help="Channel")
    ap.add_argument("-n", "--net-id", default=1, type=int, help="Network ID")
    ap.add_argument("-d", "--debug", action="store_true", help="Enable debug mode")
    args = ap.parse_args()

    lora = SX126X(
        address=Address.parse(args.rx_address),
        net_id=args.net_id,
        channel=args.channel,
        port=args.port,
        debug=args.debug
    )
    pprint(lora.to_json())

    lora.set_mode(Mode.TRANSMISSION)

    do_run = True

    def lora_cb(address: Address, data: bytes) -> bool:
        print(f"{address}: {data}")
        return do_run

    try:
        print("Receiving...")
        lora.rx_loop(lora_cb)
    except KeyboardInterrupt:
        print("Stopping...")
        do_run = False


if __name__ == '__main__':
    main()
