def main(): event_loop = asyncio.get_event_loop() # First create and configure a raw socket mysocket = aiobs.create_bt_socket(0) # create a connection with the raw socket - This now requires a STREAM socket. fac = event_loop._create_connection_transport(mysocket, aiobs.BLEScanRequester, None, None) # Start it conn, btctrl = event_loop.run_until_complete(fac) # Attach Tilt processing btctrl.process = tilt_process # Probe for messages btctrl.send_scan_request() try: print("Scanning for Tilts") event_loop.run_forever() except KeyboardInterrupt: print("keyboard interrupt") finally: print("closing event loop") btctrl.stop_scan_request() command = aiobs.HCI_Cmd_LE_Advertise(enable=False) btctrl.send_command(command) conn.close() event_loop.close()
def stop(self, mac_address = None): # Remove mac_address from mac_allowlist so we don't record the same one multiple times if mac_address: del self.mac_allowlist[mac_address] if len(self.mac_allowlist) == 0 or not mac_address: logger.info("Stopping scanner") self.btctrl.stop_scan_request() self.btctrl.send_command(aiobs.HCI_Cmd_LE_Advertise(enable=False)) self.conn.close() try: self.event_loop.stop() self.event_loop.close() except RuntimeError: # This throws a RuntimeError as we're trying to close a running event loop # just ignore it since we're about to shutdown this instance anyway pass logger.info("Stopped")
def stop(self): """ Stop the BLE scanning thread :return: None """ self.btctrl.stop_scan_request() command = aioblescan.HCI_Cmd_LE_Advertise(enable=False) self.btctrl.send_command(command) asyncio.gather(*asyncio.Task.all_tasks()).cancel() for thread in self.threads: self.event_loop.stop() thread.join() self.conn.close() self.event_loop.close() return
ev.show(0) try: mydev = int(sys.argv[1]) except: mydev = 0 event_loop = asyncio.get_event_loop() mysocket = aiobs.create_bt_socket(mydev) fac = event_loop._create_connection_transport(mysocket, aiobs.BLEScanRequester, None, None) conn, btctrl = event_loop.run_until_complete(fac) btctrl.process = my_process if opts.advertise: command = aiobs.HCI_Cmd_LE_Advertise(enable=False) btctrl.send_command(command) command = aiobs.HCI_Cmd_LE_Set_Advertised_Params( interval_min=opts.advertise, interval_max=opts.advertise) btctrl.send_command(command) command = aiobs.HCI_Cmd_LE_Set_Advertised_Msg(msg=EddyStone()) btctrl.send_command(command) command = aiobs.HCI_Cmd_LE_Advertise(enable=True) btctrl.send_command(command) btctrl.send_scan_request() try: event_loop.run_forever() except KeyboardInterrupt: print('keyboard interrupt') finally:
def main(args=None): global opts parser = argparse.ArgumentParser( description="Track BLE advertised packets") parser.add_argument( "-e", "--eddy", action="store_true", default=False, help="Look specificaly for Eddystone messages.", ) parser.add_argument( "-m", "--mac", type=check_mac, action="append", help="Look for these MAC addresses.", ) parser.add_argument( "-r", "--ruuvi", action="store_true", default=False, help="Look only for Ruuvi tag Weather station messages", ) parser.add_argument( "-p", "--pebble", action="store_true", default=False, help="Look only for Pebble Environment Monitor", ) parser.add_argument( "-A", "--atcmi", action="store_true", default=False, help="Look only for ATC_MiThermometer tag messages", ) parser.add_argument( "-R", "--raw", action="store_true", default=False, help="Also show the raw data.", ) parser.add_argument( "-a", "--advertise", type=int, default=0, help= "Broadcast like an EddyStone Beacon. Set the interval between packet in millisec", ) parser.add_argument( "-u", "--url", type=str, default="", help="When broadcasting like an EddyStone Beacon, set the url.", ) parser.add_argument( "-t", "--txpower", type=int, default=0, help="When broadcasting like an EddyStone Beacon, set the Tx power", ) parser.add_argument( "-D", "--device", type=int, default=0, help="Select the hciX device to use (default 0, i.e. hci0).", ) try: opts = parser.parse_args() except Exception as e: parser.error("Error: " + str(e)) sys.exit() event_loop = asyncio.get_event_loop() # First create and configure a raw socket mysocket = aiobs.create_bt_socket(opts.device) # create a connection with the raw socket # This used to work but now requires a STREAM socket. # fac=event_loop.create_connection(aiobs.BLEScanRequester,sock=mysocket) # Thanks to martensjacobs for this fix fac = event_loop._create_connection_transport(mysocket, aiobs.BLEScanRequester, None, None) # Start it conn, btctrl = event_loop.run_until_complete(fac) # Attach your processing btctrl.process = my_process if opts.advertise: command = aiobs.HCI_Cmd_LE_Advertise(enable=False) event_loop.run_until_complete(btctrl.send_command(command)) command = aiobs.HCI_Cmd_LE_Set_Advertised_Params( interval_min=opts.advertise, interval_max=opts.advertise) event_loop.run_until_complete(btctrl.send_command(command)) if opts.url: myeddy = EddyStone(param=opts.url) else: myeddy = EddyStone() if opts.txpower: myeddy.power = opts.txpower command = aiobs.HCI_Cmd_LE_Set_Advertised_Msg(msg=myeddy) event_loop.run_until_complete(btctrl.send_command(command)) command = aiobs.HCI_Cmd_LE_Advertise(enable=True) event_loop.run_until_complete(btctrl.send_command(command)) # Probe event_loop.run_until_complete(btctrl.send_scan_request()) try: # event_loop.run_until_complete(coro) event_loop.run_forever() except KeyboardInterrupt: print("keyboard interrupt") finally: print("closing event loop") event_loop.run_until_complete(btctrl.stop_scan_request()) command = aiobs.HCI_Cmd_LE_Advertise(enable=False) event_loop.run_until_complete(btctrl.send_command(command)) conn.close() event_loop.close()
def get_tilt_readings(open_read_time): readings = {} def my_process(data): ev = aiobs.HCI_Event() xx = ev.decode(data) xx = Tilt().decode(ev) if xx: # debug only, otherwise noisy # print("{}".format(xx)) parsedData = json.loads(xx) color = get_tilt_color(parsedData['uuid']) # extra protection, if no color: that measured thing wasn't a tilt! if color: readings[parsedData['uuid']] = {'rssi': parsedData['rssi'], 'tx_power': parsedData['tx_power'], 'mac': parsedData['mac'], 'major': parsedData['major'], 'minor': parsedData['minor'], 'uuid': parsedData['uuid'], 'color': color} # whoever reads that event_loop voodoo, please don't judge me too hard asyncio.set_event_loop(asyncio.new_event_loop()) event_loop = asyncio.get_event_loop() # First create and configure a raw socket mysocket = aiobs.create_bt_socket(BLE_DEVICE) # create a connection with the raw socket # This used to work but now requires a STREAM socket. # fac=event_loop.create_connection(aiobs.BLEScanRequester,sock=mysocket) # Thanks to martensjacobs for this fix fac = event_loop._create_connection_transport( mysocket, aiobs.BLEScanRequester, None, None) # Start it conn, btctrl = event_loop.run_until_complete(fac) # Attach your processing btctrl.process = my_process # print('Starting acquisition for ' + str(open_read_time) + ' s') btctrl.send_scan_request() async def wait_read_time(future): await asyncio.sleep(open_read_time) future.set_result('Open read time finished!') def got_result(future): event_loop.stop() future = asyncio.Future() asyncio.ensure_future(wait_read_time(future)) future.add_done_callback(got_result) try: event_loop.run_forever() finally: # stop: close event loop # print('Stopping acquisition') btctrl.stop_scan_request() command = aiobs.HCI_Cmd_LE_Advertise(enable=False) btctrl.send_command(command) conn.close() event_loop.close() return readings
def run_ble(hci_dev, QUIT_BLE_EVENT, decoder_q): # TIMING my_timer = helpers.StopWatch() # ------------------------------ event_loop = asyncio.get_event_loop() # Callback process to handle data received from BLE # --------------------------------------------------- def callback_data_handler(data): # data = byte array of raw data received # TIMING my_timer.start() # ------------------------------ if QUIT_BLE_EVENT.is_set(): event_loop.stop() else: # Add message to queue decoder_q.put(data) # TIMING my_timer.split() # ------------------------------ # --------------------------------------------------- # EOF callback_data_handler if int(hci_dev) < 0: print("No device specified, exiting run_ble") return 1 # First create and configure a raw socket mysocket = aiobs.create_bt_socket(hci_dev) # create a connection with the socket fac = event_loop._create_connection_transport( mysocket, aiobs.BLEScanRequester, None, None ) # Start it conn, btctrl = event_loop.run_until_complete(fac) # Attach your processing (callback) btctrl.process = callback_data_handler # Start BLE probe btctrl.send_scan_request() try: event_loop.run_forever() except KeyboardInterrupt: print("\nKeyboard interrupt!") finally: print("Closing ble event loop.") btctrl.stop_scan_request() command = aiobs.HCI_Cmd_LE_Advertise(enable=False) btctrl.send_command(command) conn.close() event_loop.close() # TIMING print(my_timer.get_count(), "ble messages.") print( 1000 * 1000 * my_timer.get_average(), "usec in average per message in run_ble.callback_data_handler().", ) # ------------------------------ print("Exiting run_ble.") return 0