# ble_UART_0b.py
# NUS (Nordic UART SERVICE) wie ble_UART_0.py, aber jetzt können Zeichenketten mit einer Länge von bis zu 200 Zeichen
# empfangen und (mit write, statt mit notify) auch gesendet werden.

# Empfang der Sonderzeichen funktioniert, das Senden auch; aber der input-Befehl arbeitet nicht korrekt mit Sonderzeichen!!!
# Deswegen zum Testen: die vom TTGO empfangene Zeichenkette wird mit write wieder an das Handy zurückgesendet. 

# ggf. TTGO resetten
# Programm starten
# App nRF Connect starten und verbinden 

# oberer Taster:

from machine import Pin
taster0 = Pin(0, Pin.IN, Pin.PULL_UP) # interner Pullup; parallel zum Taster 100 nF


# Bluetooth-Klasse MyBLEServer:

import ubluetooth
from micropython import const 
_ADV_TYP_NAME = const(9)
_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_GATTS_WRITE = const(3)
_FLAG_READ = const(2)
_FLAG_WRITE = const(8)
_FLAG_NOTIFY = const(16)

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()
            
        elif event == _IRQ_GATTS_WRITE:
            buffer = self.ble.gatts_read(self.rx)
            message = buffer.decode('UTF-8')
            print('Received: ', message)
            self.write(buffer)
            print('Returned: ', message)


    def register(self):
        
        # Nordic UART Service (NUS)
        
        NUS_UUID = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
        RX_UUID = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E'
        TX_UUID = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E'
            
        BLE_NUS = ubluetooth.UUID(NUS_UUID)
        BLE_RX = (ubluetooth.UUID(RX_UUID), _FLAG_WRITE)
        BLE_TX = (ubluetooth.UUID(TX_UUID), _FLAG_READ)
        BLE_UART = (BLE_NUS, (BLE_TX, BLE_RX,))
        SERVICES = (BLE_UART, )
        ((self.tx, self.rx,), ) = self.ble.gatts_register_services(SERVICES)
        self.ble.gatts_set_buffer(self.tx, 200, True)
        self.ble.gatts_set_buffer(self.rx, 200, True)

    def notify(self, data):
        
        self.ble.gatts_notify(self.conn_handle, self.tx, data)
        
    
    def write(self, data):
        
        self.ble.gatts_write(self.tx, 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-UART')


        
