# ble_scan_v0d.py

from ubluetooth import BLE


# Funktionen:

def find_adv(adv_type, data): 
    i = 0
    while i + 1 < len(data): 
        ad_structure_len = data[i]  
        ad_structure_type = data[i + 1] 
        ad_structure_payload = data[i + 2: i + ad_structure_len + 1] 
        if ad_structure_type == adv_type: 
            return ad_structure_payload 
        i += ad_structure_len + 1 
    return None


def find_adv_name(data):
    n = find_adv(9, data)   
    if n: # wenn n nicht None
        return str(n, 'UTF-8') # Text
    return None


def find_adv_power(data):
    n = find_adv(10, data)   
    if n:
        dBm = n[0]
        if dBm > 127:
            dBm = dBm - 256
        return dBm # Zahl 
    return None


def bt_irq_handler(event, data):
  if event == 5: # Advertiser-Datenpaket erhalten
    addr_type, addr, adv_type, rssi, adv_data = data
    print('Address-Type: ', addr_type)
    print('Address: ', [hex(n) for n in addr])
    print('ADV-Type: ', adv_type)
    print('RSSI in dBm: ', rssi)
    print('ADV-Data: ', [hex(n) for n in adv_data])
    print('ADV-Data (Name): ', find_adv_name(adv_data))
    print('ADV_Data (TX_Power in dBm): ', find_adv_power(adv_data))
    print()
  elif event == 6: # Scan beendet
    print('-----------------------------------------------------------')
    print('scan complete')


# Hauptprogramm:

bt = BLE()
bt.active(True)
bt.irq(bt_irq_handler)
bt.gap_scan(5000, 100000, 25000)

