Skip to content

Instantly share code, notes, and snippets.

@joshbaran
Created February 10, 2023 13:09
Show Gist options
  • Save joshbaran/a37cf1497758827b2b7f5bf1bd6bc635 to your computer and use it in GitHub Desktop.
Save joshbaran/a37cf1497758827b2b7f5bf1bd6bc635 to your computer and use it in GitHub Desktop.
bluezero callback with options test
from bluezero import adapter
from bluezero import peripheral
from bluezero import device
import random
import struct
SERVICE = 'CBBA1804-1D4F-4499-93CD-EFFB94989E94'
OPT_CHAR = '53E648D7-45B6-423A-BED9-D1234C30023F'
NO_OPT_CHAR = '35045198-AB93-4073-95AA-9AFDF761B106'
def on_connect(ble_device: device.Device):
print("Connected to " + str(ble_device.address))
def on_disconnect(adapter_address, device_address):
print("Disconnected from " + device_address)
def getAddress(options):
return ''.join(options['device'].split('_')[1:])
cnts = {}
def cb_with_options(options):
''' Callback with passing options - uses device address from options to keep a running counter of the number of times it was called, and return the count as LE 2-byte int'''
print(f'Calling with options: {options}')
a = getAddress(options)
cnt = cnts.setdefault(a,0)
cnt += 1
cnts[a]=cnt
print(f'returning: {cnt}')
return struct.pack('<h',cnt)
def cb_no_options():
''' Callback without options - just return a random number as LE 2-byte int'''
print('Calling without options')
num = random.randint(0,1000)
print(f'returning: {num}')
return struct.pack('<h',num)
def main(adapter_address):
p = peripheral.Peripheral(adapter_address,local_name='Options Callback Test')
p.add_service(srv_id=1, uuid=SERVICE, primary=True)
p.add_characteristic(
srv_id=1,
chr_id=1,
uuid=OPT_CHAR,
value=[],
notifying=False,
flags=['read'],
read_callback=cb_with_options
)
p.add_characteristic(
srv_id=1,
chr_id=2,
uuid=NO_OPT_CHAR,
value=[],
notifying=False,
flags=['read'],
read_callback=cb_no_options
)
p.on_connect = on_connect
p.on_disconnect = on_disconnect
p.publish()
if __name__ == '__main__':
addr = list(adapter.Adapter.available())[0].address
main(addr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment