# Heart Beat GATT: ble_hr_0d.py
# wie ble_hr_0c.py, allerdings mit eigenen UUIDs

# ggf. TTGO resetten
# Programm starten
# nRF APP starten -> CONNECT -> Unknown Service "öffnen"


# Zufallszahlen:
from random import randint

# Pausen:
from time import sleep

# Bluetooth-Klasse BLE:
from micropython import const 
_ADV_TYP_NAME = const(9)
_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_FLAG_NOTIFY = const(16)

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):
        
        S_UUID = 'b46dfbb4-00fb-4bb8-85c5-773ca0c21a00' # generiert mit https://www.uuidgenerator.net/
        C_UUID = '58589d08-632c-497f-930b-14d0c28d2aee'
        
        # Heart Rate (HR)
        HR_UUID = ubluetooth.UUID(S_UUID)  
        HR_CHAR = (ubluetooth.UUID(C_UUID), _FLAG_NOTIFY)
        HR_SERVICE = (HR_UUID, (HR_CHAR,)) 
        SERVICES = (HR_SERVICE, )
        ((self.hr,),) = self.ble.gatts_register_services(SERVICES) 


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


    def notify(self, data):
        
        self.ble.gatts_notify(0, 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')


# main:
ble = MyBLEServer("ESP32-HR")

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

while True:
    sleep(3)
    bpm = randint(50, 65) # simulierter bpm-Wert zwischen 50 und 65
    print(bpm)
    bpm = bytes([0, bpm])
    ble.notify(bpm)