# Heart Beat GATT: ble_hr_0.py

# ggf. TTGO resetten
# Programm starten
# nRF APP starten -> CONNECT -> Heart Rate "öffnen"


# Konstanten:

from micropython import const 
_ADV_TYP_NAME = const(9)
_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_FLAG_READ = const(2)


# Bluetooth-Klasse MyBLEServer:

import ubluetooth

class MyBLEServer():

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

        self.ble.irq(self.my_ble_irq)
        self.register()
        self.advertiser()
        
        self.conn = False


    def my_ble_irq(self, event, data):
        
        if event == _IRQ_CENTRAL_CONNECT:
            print('Central connected')
            self.conn = True
        
        elif event == _IRQ_CENTRAL_DISCONNECT:
            print('Central disconnected')
            self.conn = False
            self.advertiser()
            
    def register(self):
        
        # Heart Rate (HR)
        HR_UUID = ubluetooth.UUID(0x180D)  # Service-ID von HR -> Declaration.value
        HR_CHAR = (ubluetooth.UUID(0x2A37), _FLAG_READ)
        HR_SERVICE = (HR_UUID, (HR_CHAR,)) # ges. Service als Tupel, ggf. mit mehreren CHAR-Values...
        SERVICES = (HR_SERVICE, )
        ((self.hr,),) = self.ble.gatts_register_services(SERVICES) # self.hr ist ein value handle (verweist das auf char.value.value?)


    def write(self, data):
        
        self.ble.gatts_write(self.hr, data)
        

    def advertiser(self):
        
        adv_data = b'\x02\x01\x06'
        name = bytes(self.name, 'UTF-8')
        adv_data = adv_data +  bytearray((len(name) + 1, _ADV_TYP_NAME)) + name
        self.ble.gap_advertise(200000, adv_data, connectable=True)   # 200 ms Adv_Antervall 
        print('advertising')


# Hauptprogramm:

ble = MyBLEServer("ESP32-HR")

while not ble.conn: # warten, bis Verbindung besteht
    pass

bpm = 63 # HR-Wert (kleiner als 256)
bpm = bytes([0, bpm]) # Erstes Byte (0) signalisiert, dass der bpm_Wert nur aus einem 1 Byte besteht.
ble.write(bpm)
