from machine import Pin, Timer
from time import sleep_ms
import ubluetooth

class BLE():
    def __init__(self, name):
        self.name = name
        self.ble = ubluetooth.BLE()
        self.ble.active(True)

        self.led = Pin(2, Pin.OUT)
        self.timer1 = Timer(0)
        self.timer2 = Timer(1)

        self.disconnected()
        self.ble.irq(self.ble_irq)
        self.register()
        self.advertiser()

    def register(self):
        #NUS = Nordic UART Service
        #Dado na aula, procurar e pesquisar por NUS
        NUS_UUID = ''
        RX_UUID = ''
        TX_UUID = ''

        #Definição do UUID do serviço
        BLE_NUS = ubluetooth.UUID(NUS_UUID)

        #Definição das características
        BLE_TX = (ubluetooth.UUID(TX_UUID), ubluetooth.FLAG_NOTIFY)
        BLE_RX = (ubluetooth.UUID(RX_UUID), ubluetooth.FLAG_WRITE)

        #Definição do serviço
        BLE_UART = (BLE_NUS, (BLE_TX, BLE_RX,))

        #Definição de todos os serviços
        SERVICES = (BLE_UART,)

        #Registro dos serviços no profile
        ((self.tx, self,rx), ) = self.ble.gatts_register_services(SERVICES)

    def send(self, data):
        self.ble.gatts_notify(0, self.tx, data + '\n')

    def advertiser(self):
        name = butes(self.name, 'UTF-8')
        self.ble,gap_advertise(100, bytearray('\x02\x01\x02') + bytearray(len(name) + 1, 0x09) + name)

    def connected(self):
        self.timer1.deinit()
        self.timer2.deinit()

    def disconneted(self):
        self.timer1.init(period=1000, mode=Timer.PERIODIC, callback=lambda t: self.led(1))
        sleep_ms(200)
        self.timer1.init(period=1000, mode=Timer.PERIODIC, callback=lambda t: self.led(0))

#test
red led = Pin(2, Pin.OUT)
ble = BLE("ESP32")

#nrfconnect