# ble_GATT_2_Services_1.py
# Service 1: Heart Rate mit simulierten bmp-Werten (als Bytes-Objekt) (eigene UUIDs)
# Service 2: Device Information (UUID(0x180A)

# ggf. TTGO resetten
# Programm starten
# nRF APP starten -> CONNECT ESP32-HR-DI -> "Unknown Service" und/oder "Device Information" ö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)
_FLAG_READ = const(2)


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.ble.gatts_write(self.di_id, self.get_my_addr())
        self.ble.gatts_write(self.di_mod,'TTGO T-DISPLAY')
        
        self.advertiser()        
        self.conn = False
        

    def get_my_addr(self):
        return self.ble.config('mac')[1]


    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 1 
        HR_CHAR = (ubluetooth.UUID(0x2A37), _FLAG_NOTIFY)
        HR_SERVICE = (HR_UUID, (HR_CHAR,))        
        
        # Device Information (DI)
        DI_UUID = ubluetooth.UUID(0x180A) # Service 2
        DI_CHAR_SYSTEM_ID = (ubluetooth.UUID(0x2A23), _FLAG_READ)
        DI_CHAR_MODEL = (ubluetooth.UUID(0x2A24), _FLAG_READ)
        DI_SERVICE = (DI_UUID, (DI_CHAR_SYSTEM_ID, DI_CHAR_MODEL))
        
        SERVICES = (HR_SERVICE, DI_SERVICE)
        ((self.hr,),(self.di_id, self.di_mod)) = 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')


# Hauptprogramm:
ble = MyBLEServer("ESP32-HR-DI")

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)