BLE read data
-
I've cobbled this code together from several examples and postings, and have it nearly operational. I can verify that LoPy pairs reliably and receives what I send it. I can also read from it, but what I have been unable to glean is how to control what it sends--currently it sends whatever the last thing I sent to it.
I've tried setting chr.value('text') as well as an otherwise undocumented chr.write (which my Pycom MicroPython 1.18.2.r4 [v1.8.6-849-ba178ae] claims doesn't exist) but can't find any other documentation or example where the LoPy code sends back specific data in response to a read. I assume there's some method for this, but the documentation on the Bluetooth is so scant that days of searching and experimentation have so far failed to enlighten me.
This is the code...
from network import Bluetooth import time bluetooth = Bluetooth() bluetooth.init() bluetooth.set_advertisement(name='MJJ_BTLE', manufacturer_data = 'OTTO', service_data = b'19950922' ,service_uuid=b'1000000010000000') def conn_cb (bt_o): events = bt_o.events() # this method returns the flags and clears the internal registry if events & Bluetooth.CLIENT_CONNECTED: print("Client connected") bt_o.advertise(False) elif events & Bluetooth.CLIENT_DISCONNECTED: print("Client disconnected") bt_o.advertise(True) bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=conn_cb) #start advertise bluetooth.advertise(True) #Create a new service on the internal GATT server. Returns a object of type BluetoothServerService. #bluetooth.service(uuid, *, isprimary=True, nbr_chars=1, start=True) srv1 = bluetooth.service(uuid=b'1000000010000000', isprimary=True, nbr_chars=1, start = True) chr1 = srv1.characteristic(uuid = b'ab34567890123456', properties = (Bluetooth.PROP_READ | Bluetooth.PROP_WRITE), value=99999)#, permissions = (1 << 0) | (1 << 4)) def char1_cb_handler(chr): global tx_str events = chr.events() if events & Bluetooth.CHAR_WRITE_EVENT: print("Write request with value = {}".format(chr.value())) else: print('Read request on char 1') ########################################################## # Not sure if I call something here or set it separately # ########################################################## char1_cb = chr1.callback(trigger=Bluetooth.CHAR_WRITE_EVENT | Bluetooth.CHAR_READ_EVENT, handler=char1_cb_handler) while True: pass
Thanks for any hints or suggestions.
-
It worked like a charm! I wasn't using that example, but the one I did rip off may have been based on it. Thanks!
-
@aliubi The documentation is indeed quite scant, but from the example at https://docs.pycom.io/firmwareapi/pycom/network/bluetooth/gattscharacteristic.html (which I believe you derived your code from), I would guess that you are actually supposed to
return
the value you want to send in the callback.Let us know if that works.