def main(): ble.clear_cached_data() adapter = ble.get_default_adapter() adapter.power_on() print('Adapter: {0}'.format(adapter.name)) adapter.start_scan() atexit.register(adapter.stop_scan) print('Scan for UART devices started, press Ctrl-C to quit...') known_uarts = set() while True: found = set(UART.find_devices()) new = found-known_uarts for device in new: # Under Raspbian there was an error regarding devices with no name, # therefore checking type if isinstance(device.name, dbus.String): print('Found: [{0}] [{1}] {2}'.format(device.name, device.id, device.rssi)) # RSSI of -70 at 1m is a test value for now, calibration will be # implemented later print('Distance: {0}'.format(rssiToDist(device.rssi, -70))) else: print('Found: [{0}] {1}'.format(device.id, device.rssi)) print('Distance: {0}'.format(rssiToDist(device.rssi, -70))) known_uarts.update(new) time.sleep(1.0)
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print("Using adapter: {0}".format(adapter.name)) # Start scanning with the bluetooth adapter. adapter.start_scan() # Use atexit.register to call the adapter stop_scan function before quiting. # This is good practice for calling cleanup code in this main function as # a try/finally block might not be called since this is a background thread. atexit.register(adapter.stop_scan) print("Searching for UART devices...") print("Press Ctrl-C to quit (will take ~30 seconds on OSX).") # Enter a loop and print out whenever a new UART device is found. known_uarts = set() while True: # Call UART.find_devices to get a list of any UART devices that # have been found. This call will quickly return results and does # not wait for devices to appear. found = set(UART.find_devices()) # Check for new devices that haven't been seen yet and print out # their name and ID (MAC address on Linux, GUID on OSX). new = found - known_uarts for device in new: print("Found UART: {0} [{1}]".format(device.name, device.id)) known_uarts.update(new) # Sleep for a second and see if new devices have appeared. time.sleep(1.0)
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Start scanning with the bluetooth adapter. adapter.start_scan() # Use atexit.register to call the adapter stop_scan function before quiting. # This is good practice for calling cleanup code in this main function as # a try/finally block might not be called since this is a background thread. atexit.register(adapter.stop_scan) print('Searching for UART devices...') print('Press Ctrl-C to quit (will take ~30 seconds on OSX).') # Enter a loop and print out whenever a new UART device is found. known_uarts = set() while True: # Call UART.find_devices to get a list of any UART devices that # have been found. This call will quickly return results and does # not wait for devices to appear. found = set(UART.find_devices()) # Check for new devices that haven't been seen yet and print out # their name and ID (MAC address on Linux, GUID on OSX). new = found - known_uarts for device in new: print('Found UART: {0} [{1}]'.format(device.name, device.id)) known_uarts.update(new) # Sleep for a second and see if new devices have appeared. time.sleep(1.0)
def scan(self): # Search for available UART devices try: self.adapter.start_scan() # Make sure we stop scanning after the program is over #atexit.register(self.adapter.stop_scan) # Get the found UART devices self.uarts = set(UART.find_devices()) finally: # Finish scanning self.adapter.stop_scan()
def get_device(ble, id): print('Starting', id) adapter = ble.get_default_adapter() adapter.power_on() adapter.start_scan() atexit.register(adapter.stop_scan) for _ in range(30): found = set(UART.find_devices()) for device in found: if str(device.id) == id: adapter.stop_scan() return device time.sleep(1)
def list_bluetooth_devices(ble): adapter = ble.get_default_adapter() adapter.power_on() adapter.start_scan() atexit.register(adapter.stop_scan) print('Searching for Bluetooth Devices:') known = set() for _ in range(30): found = set(UART.find_devices()) for device in found - known: print(device.id, device.name) known |= found time.sleep(1) adapter.stop_scan()
def main(): adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) adapter.start_scan() atexit.register(adapter.stop_scan) device_found = False device = None print('Searching for UART devices...') while not device_found: found = set(UART.find_devices()) for d in found: print('Found UART: {0} [{1}]'.format(d.name, d.id)) if d.name == args.name: device = d device_found = True break time.sleep(1) if device_found: print('connecting to: {0} [{1}]'.format(device.name, device.id)) device.connect() try: print('UART connecting...') UART.discover(device) uart = UART(device) print('Creating speech recognizer...') recognizer = speech.create_recognizer() while True: phrase = speech.listen_and_recognize(recognizer) for word in phrase.split(): word = word.strip() word = word.lower() print("word: ", word) if word in blue_words: uart.write(b'blue\r\n') elif word in orange_words: uart.write(b'orange\r\n') elif word in off_words: uart.write(b'off\r\n') finally: device.disconnect()
def find_device(adapter, name): logging.info('searching for UART device {0}'.format(name)) try: adapter.start_scan() while True: devices = set(UART.find_devices()) for device in devices: logging.debug('found UART device {0}'.format(device.name)) if device.name == name: return device # Wait for the device to come up time.sleep(1) finally: adapter.stop_scan()
def main(): start_time = time.time() ble.clear_cached_data() adapter = ble.get_default_adapter() adapter.power_on() adapter.start_scan() atexit.register(adapter.stop_scan) known_uarts = {} while True: found = set(UART.find_devices()) for device in found: if device.name not in known_uarts.keys(): known_uarts[device.name] = device.id time.sleep(1.0) if len(known_uarts) == 5: requests.put('localhost:8888/api/',json.dumps(known_uarts)) #Send JSON to SERVER if round(time.time() - start_time) % 10 == 0: break
def scan(self, timeout=30, terminator=False, internaltimeout=5): print("Scanning for UART devices ({}s)".format(timeout)) self.adapter.start_scan(internaltimeout) known = set() stoptime = time.time() + timeout while ((time.time() < stoptime) and (not terminator)): # found = set(UART.find_devices()) #get all found devices # new = found - known #find the new devices as the set difference # for dev in new: # if (hasattr(dev, "name")): # name = str(dev.name) # else: # name = "Name Unknown" # if (hasattr(dev, "id")): # addr = str(dev.id) # else: # addr = "Address Unknown" # print("Found device: {0} [{1}]".format(name, addr)) # known.update(new) #add new devices to the known set time.sleep(1) self.adapter.stop_scan(internaltimeout) found = set(UART.find_devices()) #get all found devices new = found - known #find the new devices as the set difference for dev in new: if (hasattr(dev, "name")): name = str(dev.name) else: name = "Name Unknown" if (hasattr(dev, "id")): addr = str(dev.id) else: addr = "Address Unknown" print("Found device: {0} [{1}]".format(name, addr)) known.update(new) #add new devices to the known set self.found_devices = list(known)
def get_scan_devices(): # global adapter adapter = ble.get_default_adapter() adapter.power_on() # initialize an empty set known_uarts = set() try: # Start scanning with the bluetooth adapter. adapter.start_scan() # Scan for UART devices. print('Searching for UART device(timeout after 5 sec)...'), prev_time = curr_time = time.time() while (curr_time - prev_time) <= 3: # stop scanning if more than 30 seconds # Call UART.find_devices to get a list of any UART devices that # have been found. This call will quickly return results and does # not wait for devices to appear. found = set(UART.find_devices()) # Check for new devices that haven't been seen yet and print out # their name and ID (MAC address on Linux, GUID on OSX). new = found - known_uarts # add new devices to set known_uarts.update(new) # Sleep for a second and see if new devices have appeared. time.sleep(1.0) # update the current time before the conditions ~ curr_time = time.time() finally: # stop the bluetooth adapter when done scanning/discovery devices adapter.stop_scan() print('found!') # return whatever devices we found. return known_uarts
def getDevices(device_ids, timeout=20): # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') to_find = set(device_ids) found = set() try: adapter.start_scan() time_elapsed = 0 while (time_elapsed < timeout and len(found) < len(device_ids)): devices = UART.find_devices() for d in devices: # d.id is a UUID object if d.id in to_find: # check if id in id_set found.add(d) # add device to found time.sleep(1.0) time_elapsed += 1 for device in found: device.connect() print("Discovering UART service for {}".format(device.id)) UART.discover(device) except: for device in found: # Make sure device is disconnected device.disconnect() raise RuntimeError('Error Connecting to devices. Terminating ...') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() return {device.id: device for device in found}
def collectSensorData(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART devices...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). #find all sensing devices devices = set() for i in range(10): found = set(UART.find_devices()) #remove non-bluefruit devices found_filtered = set( filter(lambda x: 'Bluefruit52' in x.name, found)) #found_filtered = found new = found_filtered - devices devices.update(new) sleep(1) print("Found the following devices:") for device in devices: print(device.name, device.id) if devices is None: raise RuntimeError('Failed to find UART device!') except: adapter.stop_scan() return False finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() #collect sensor data every dt interval for device in devices: print('Connecting to device:', device.id) device.connect( ) # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Now wait up to one minute to receive data from the device. print( 'Waiting up to 60 seconds to receive data from the device...') received = uart.read(timeout_sec=60) if received is not None: # Received data, print it out. with open('sensordata', 'a') as sd: sd.write(strftime("%Y-%m-%d %H:%M:%S ") + received + '\n') print('Received: {0}'.format(received)) print(strftime("%Y-%m-%d %H:%M:%S ")) uart.write('good') print('Sent good') else: # Timeout waiting for data, None is returned. print('Received no data!') except: device.disconnect() return False finally: print('done') # Make sure device is disconnected on exit. device.disconnect() return True
def main(): global run4ever global uart print('run4ever: ' + str(run4ever)) print2Log('run4ever: ' + str(run4ever)) # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) print2Log('Using adapter: {0}'.format(adapter.name)) # Start scanning with the bluetooth adapter. adapter.start_scan() # Use atexit.register to call the adapter stop_scan function before quiting. # This is good practice for calling cleanup code in this main function as # a try/finally block might not be called since this is a background thread. atexit.register(adapter.stop_scan) print('Searching for UART devices...') print('Press Ctrl-C to quit (will take ~30 seconds on OSX).') print2Log('Searching for UART devices...') print2Log('Press Ctrl-C to quit (will take ~30 seconds on OSX).') # Enter a loop and print out whenever a new UART device is found. known_uarts = set() device = 0 c = True while c: # Call UART.find_devices to get a list of any UART devices that # have been found. This call will quickly return results and does # not wait for devices to appear. found = set(UART.find_devices()) # Check for new devices that haven't been seen yet and print out # their name and ID (MAC address on Linux, GUID on OSX). new = found - known_uarts for dev in new: print('Found UART: {0} [{1}]'.format(dev.name, dev.id)) print2Log('Found UART: {0} [{1}]'.format(dev.name, dev.id)) if str(dev.id) == btID: #print('Device found') print2Log('Device found') device = dev adapter.stop_scan() c = False known_uarts.update(new) # Sleep for a second and see if new devices have appeared. time.sleep(1.0) print('Connecting to device...') print2Log('Connecting to device...') device.connect( ) # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') print2Log('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. #uart.write('Hello world!\r\n') #print("Sent 'Hello world!' to the device.") # Now wait up to one minute to receive data from the device. #print('Waiting up to 60 seconds to receive data from the device...') print("Comm loop runing") print2Log("Comm loop runing") stopChar = '@' messageBuffer = "" while run4ever: received = uart.read(timeout_sec=0.05) if received: # Received data, print it out. print('Received:{0}'.format(received)) print2Log('Received:{0}'.format(received)) #else: # Timeout waiting for data, None is returned. print('Received no data!') messageBuffer += received while stopChar in messageBuffer: cut = messageBuffer.split(stopChar) finalMessage = cut[0] #print("Final Mesage:"+finalMessage) #print2Log("Final Mesage:"+finalMessage) processInput(finalMessage) messageBuffer = messageBuffer[len(cut[0]) + 1:] except Exception as e: print(e) finally: # Make sure device is disconnected on exit. while run4ever: pass device.disconnect()
def bluetoothDaemon(): # Grab lock before doing anything grab_lock() # get the default adapter adapter = ble.get_default_adapter() # start the adapter adapter.power_on() # clear cached data ble.clear_cached_data() # disconnect previous connections UART.disconnect_devices() # start scanning adapter.start_scan() print("Started Scanning") # keep track of known_devices known_devices = set() while True: # get the devices found found = set(UART.find_devices()) # get difference between current and known new = found - known_devices # add new to known devices known_devices.update(new) # for each new device for device in new: print("Found {0} - {1}".format(device.name, device.id)) # check if the id is the adafruit if device.id == "DE:85:BD:07:6F:29": # if it matches stop scanning adapter.stop_scan() # connect to the device device.connect() # check if it has UART capabilities UART.discover(device) # initialize uart object to talk to the device uart = UART(device) # send the temp command uart.write('cmd:temp') # read response received = uart.read(timeout_sec=60) # if response received if received is not None: # print response print('Received: {0}'.format(received)) # output to file outfile = open('current.temp', 'w') outfile.write(received.split(':')[1]) outfile.write('\n') outfile.write(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())) outfile.close() # disconnect from device UART.disconnect_devices() #device.disconnect() # power down adpater adapter.power_off() # remove lock file os.remove(LOCK_FILE) lock_file_created = False # sleep time.sleep(60) return
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART finalDevices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART finalDevices...') UART.disconnect_devices() # Scan for UART finalDevices. print('Searching for UART finalDevice...') finalDevice = None gotDevice = False adapter.start_scan() while gotDevice is False: try: # Search for the first UART finalDevice found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). finalDevices = set(UART.find_devices()) finally: print("The list of finalDevices found is: ") print(finalDevices) for device in finalDevices: print('Found UART: {0} [{1}]'.format(device.name, device.id)) if device.name == 'Chrestien': finalDevice = device gotDevice = True print('found finalDevice') time.sleep(1.0) adapter.stop_scan() print(finalDevice.name) print('Connecting to finalDevice...') finalDevice.connect( ) # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. print(finalDevice) # Once connected do everything else in a try/finally to make sure the finalDevice # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') print(finalDevice) UART.discover(finalDevice) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(finalDevice) # Write a string to the TX characteristic. #uart.write('Hello world!\r\n') #print("Sent 'Hello world!' to the finalDevice.") # Now wait up to one minute to receive data from the finalDevice. print( 'Waiting up to 60 seconds to receive data from the finalDevice...') received = uart.read(timeout_sec=10) f = open('sketch_180403e/datat.txt', 'w+') f.close() while (True): try: if received is not None: if (received == ' '): continue # Received data, print it out. #print('Received: {0}'.format(received)) print(received) f = open('sketch_180403e/datat.txt', 'a') f.write(received) f.flush() f.close() received = uart.read(timeout_sec=10) else: # Timeout waiting for data, None is returned. print('Received no data!') break except KeyboardInterrupt: print('KeyBoardIntererupt') f.seek(0) f.truncate() finalDevice.disconnect() received = uart.read(timeout_sec=10) finally: f = open('sketch_180403e/datat.txt', 'a') f.seek(0) f.truncate() f.close() # Make sure finalDevice is disconnected on exit. print 'This is the' print finalDevice finalDevice.disconnect()
def main(): # Grab lock before doing anything grab_lock() # get the default adapter adapter = ble.get_default_adapter() # start the adapter adapter.power_on() # clear cached data ble.clear_cached_data() # disconnect previous connections UART.disconnect_devices() # start scanning adapter.start_scan() print("Started Scanning") # keep track of known_devices known_devices = set() while True: # get the devices found found = set(UART.find_devices()) # get difference between current and known new = found - known_devices # add new to known devices known_devices.update(new) # for each new device for device in new: print("Found {0} - {1}".format(device.name, device.id)) # check if the id is the adafruit if device.id == "DE:85:BD:07:6F:29": # if it matches stop scanning adapter.stop_scan() # connect to the device device.connect() # check if it has UART capabilities UART.discover(device) # initialize uart object to talk to the device uart = UART(device) # send the servo command if sys.argv[1] == 'open': # if response received uart.write('cmd:open') if sys.argv[1] == 'close': # if response received uart.write('cmd:close') # read response received = uart.read(timeout_sec=60) if received is not None: # print response print('Received: {0}'.format(received)) # disconnect from device UART.disconnect_devices() # device.disconnect() # power down adpater adapter.power_off() # remove lock file os.remove(LOCK_FILE) # sleep time.sleep(60) return
def main(): # Set up logging logging_format = '%(asctime)s : %(filename)s : %(levelname)s : %(message)s' logging_level = logging.INFO logging.basicConfig(format=logging_format, level=logging_level) logging.info("Running %s", " ".join(sys.argv)) # Declare our serverSocket upon which # we will be listening for UDP messages logging.info('Initializing Mekamon UDP listener on %s:%s' % (config.UDP_IP_ADDRESS, config.UDP_PORT_NO)) serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) serverSock.bind((config.UDP_IP_ADDRESS, config.UDP_PORT_NO)) # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() logging.info('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. logging.info('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. logging.info('Searching for UART devices...') adapter.start_scan() mekamon_device = None time_end = time.time() + 10 # search for x secs while time.time() < time_end and mekamon_device is None: # Call UART.find_devices to get a list of any UART devices that # have been found. This call will quickly return results and does # not wait for devices to appear. found = set(UART.find_devices()) # Check for new devices that haven't been seen yet and logging.info out # their name and ID (MAC address on Linux, GUID on OSX). for device in found: if 'Meka' in device.name: logging.info(' -- Found Mekamon: {0} [{1}]'.format(device.name, device.id)) mekamon_device = device # Sleep for a second and see if new devices have appeared. if mekamon_device is None: time.sleep(1.00) # Make sure scanning is stopped before exiting. logging.info(" -- Stopping scan...") adapter.stop_scan() logging.info('Connecting to Mekamon: {0} [{1}]'.format(mekamon_device.name, mekamon_device.id)) mekamon_device.connect(timeout_sec=10) logging.info(' -- Discovering BLE services') UART.discover(mekamon_device) # Once service discovery is complete create an instance of the service # and start interacting with it. mekamon_uart = UART(mekamon_device) # Set up motion controller and initialize Mekamon motion_controller = MotionController(mekamon_uart) motion_controller.pwn_mekamon() motion_controller.set_height("height,%d" % (config.default_height)) # Setup complete. Start command and control server try: logging.info("Setup complete. Waiting for network control messages...") is_running = True while is_running: data, addr = serverSock.recvfrom(1024) logging.info("Received client message: %s" % (data)) if 'exit' in data.lower(): logging.info("Exiting...") is_running = False elif 'motion' in data.lower(): motion_controller.xyz_motion(data) elif 'height' in data.lower(): motion_controller.set_height(data) elif 'raw' in data.lower(): motion_controller.raw_motion(data) else: motion_controller.turn_motion() motion_controller.stop_motion() finally: logging.info("Disconnecting BLE from Mekamon") mekamon_device.disconnect()
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). condition = True; known_uarts = set() while condition: # Call UART.find_devices to get a list of any UART devices that # have been found. This call will quickly return results and does # not wait for devices to appear. found = set(UART.find_devices()) # Check for new devices that haven't been seen yet and print out # their name and ID (MAC address on Linux, GUID on OSX). new = found - known_uarts for device in new: print('Found UART: {0} [{1}]'.format(device.name, device.id)) known_uarts.update(new) # Sleep for a second and see if new devices have appeared. if len(known_uarts) >= 2: condition = False; time.sleep(1.0) if len(known_uarts) >= 2: condition = False; print(condition) print('connecting to a device finally!') for device in known_uarts: print('device in set: {0} [{1}]'.format(device.name, device.id)) print(len(new)) if 'C9:79:B6:8F:0B:D4' in device.id: asuka_device = device; device = asuka_device; if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Connecting to device...') device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Connected to: {0} {1}'.format(device.name, device.id)) print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. uart.write('on') print("Sent 'on' to the device.") # Now wait up to one minute to receive data from the device. print('Waiting up to 60 seconds to receive data from the device...') received = uart.read(timeout_sec=60) if received is not None: # Received data, print it out. print('Received: {0}'.format(received)) else: # Timeout waiting for data, None is returned. print('Received no data!') finally: # Make sure device is disconnected on exit. device.disconnect()
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') num_devices = 2 # Start scanning with the bluetooth adapter. adapter.start_scan() # Use atexit.register to call the adapter stop_scan function before quiting. # This is good practice for calling cleanup code in this main function as # a try/finally block might not be called since this is a background thread. atexit.register(adapter.stop_scan) # Enter a loop and print out whenever a new UART device is found. adafruit_devices = [] known_uarts = set() for i in range(100): # Call UART.find_devices to get a list of any UART devices that # have been found. This call will quickly return results and does # not wait for devices to appear. found = set(UART.find_devices()) # Check for new devices that haven't been seen yet and print out # their name and ID (MAC address on Linux, GUID on OSX). new = found - known_uarts for device in new: if device.name == DEVICE_NAME: adafruit_devices.append(device) print('Found UART: {0} [{1}]'.format(device.name, device.id)) known_uarts.update(new) # Sleep for a second and see if new devices have appeared. time.sleep(0.5) if len(adafruit_devices) >= num_devices: break adapter.stop_scan() if len(adafruit_devices) < num_devices: print("could not find 2 devices") sys.exit(1) print('Connecting to device...') device_1 = adafruit_devices[0] device_1.connect() atexit.register(device_1.disconnect) device_2 = adafruit_devices[1] device_2.connect() atexit.register(device_2.disconnect) com_fail = False try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device_1) UART.discover(device_2) # Once service discovery is complete create an instance of the service # and start interacting with it. uart_1 = UART(device_1) uart_2 = UART(device_2) except: com_fail = True if not com_fail: print("calling foward_taps") thread.start_new_thread( foward_taps, (uart_1, uart_2, device_1, device_2, 5, )) time.sleep(1) thread.start_new_thread( foward_taps, (uart_2, uart_1, device_2, device_1, 5, )) while True: pass