"""
This modul implements a simple serial connection to the ZS-040 and will echo out to the console
any messages it receives. This board is a Bluetooth SPP (Serial Port Protocol) module.

When powered on the device will broadcast as BT-05 by default. Default passwords are usually 1234 or 0000.
"""
from select import select
from machine import Pin, UART


class ZS040:
    def __init__(
        self,
        uart_id,
        tx_pin,
        rx_pin,
        state_pin,
        baudrate=38400,
        bits=8,
        stop=1,
        parity=None,
    ):
        self.uart = UART(
            uart_id,
            baudrate=baudrate,
            bits=bits,
            stop=stop,
            parity=parity,
        )
        self.state_pin = Pin(state_pin, Pin.IN)

    def read(self, nbytes=None):
        return self.uart.read(nbytes)

    def readline(self):
        return self.uart.readline()

    def write(self, buf):
        self.uart.write(buf)

    def any(self):
        return self.uart.any()

    @property
    def state(self):
        return self.state_pin.value()

    @classmethod
    def from_config(cls, pin_config):
        return cls(
            uart_id=pin_config["bluetooth"]["uart_id"],
            tx_pin=pin_config["bluetooth"]["tx_pin"],
            rx_pin=pin_config["bluetooth"]["rx_pin"],
            state_pin=pin_config["bluetooth"]["state_pin"],
        )


# while True:
#     if BT_STATE_PIN.value():
#         if uart.any():
#             data = uart.read(1)
#             print(data.decode("utf8"))
#         else:
#             print("No data. Sleeping")
#     else:
#         print("No Bluetooth device paired.")
#     sleep_ms(500)
