def main(): ble.clear_cached_data() adapter = ble.get_default_adapter() adapter.power_on() print('Using : {0}'.format(adapter.name)) ble.disconnect_devices([UART_SERVICE]) adapter.start_scan() time.sleep(5) devices = ble.find_devices(service_uuids=[UART_SERVICE]) time.sleep(5) gong = None for device in devices: print('Found device: {0}, id: {1}'.format(device.name, device.id)) if device.name == 'BLEGong': print 'Found gong', device.id, gong = device adapter.stop_scan() break gong.connect() print ('Gong Connected') UART.discover(gong) print 'Gong Discovered' gong_uart = UART(gong) adapter.power_off() print 'Disconnected'
def main(): ble.clear_cached_data() global device adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) print('Searching for UART device...') try: adapter.start_scan() device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: adapter.stop_scan() print('Connecting to device...') device.connect() print('Discovering services...') UART.discover(device) uart = UART(device) line = '' timer = time.time() while True: received = uart.read(timeout_sec=1) if received is not None: timer = time.time() line = ''.join([line, received]) else: if (time.time() - timer) > 1 and line != '': print('{0} {1}'.format('line is: ', line)) line = ''
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). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') else: print 'uart device is gevonden' 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 DIS service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') DeviceInformation.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. dis = DeviceInformation(device) # Print out the DIS characteristics. print('Manufacturer: {0}'.format(dis.manufacturer)) print('Model: {0}'.format(dis.model)) print('Serial: {0}'.format(dis.serial)) print('Hardware Revision: {0}'.format(dis.hw_revision)) print('Software Revision: {0}'.format(dis.sw_revision)) print('Firmware Revision: {0}'.format(dis.fw_revision)) print('System ID: {0}'.format(dis.system_id)) print('Regulatory Cert: {0}'.format(dis.regulatory_cert)) print('PnP ID: {0}'.format(dis.pnp_id)) 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...') 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). device = UART.find_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('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(b'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...') 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 initBle(): # 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). device = UART.find_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. return device
def connectDevice(): ''' Connects to the Adafruit Bluefruit Module and return the object for that device ''' #clear any cached data ble.clear_cached_data() #get BLE adapter adapter = ble.get_default_adapter() adapter.power_on() print("[ Using adapter: {0} ]".format(adapter.name)) #disconnet any connected UART devices UART.disconnect_devices() #scan for UART devices print("Scanning for UART devices...") try: adapter.start_scan() device = UART.find_device() if device is None: raise RuntimeError("Failed to find any UART device!") finally: adapter.stop_scan() print("Connecting to device...") device.connect() return device
def main(): device = initBle() initDrone() # 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) # Write a string to the TX characteristic. #uart.write(b'Hello world!\r\n') #print("Sent 'Hello world!' to the device.") # Now wait up to one minute to receive data from the device. while True: #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!') sendCommandDrone(received) finally: # Make sure device is disconnected on exit. device.disconnect()
def close(self): self.stoprequest.set() try: UART.disconnect_devices() # self.device.disconnect() logger.info('connection lost') except: print('mimsy')
def __init__(self): # protected region initCode on begin # # 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). device = UART.find_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('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) print('uart = UART(device)') finally: # Make sure device is disconnected on exit. device.disconnect() print('device.disconnect()') # protected region initCode end # pass
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). device = UART.find_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 DIS service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') DeviceInformation.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. dis = DeviceInformation(device) # Print out the DIS characteristics. print('Manufacturer: {0}'.format(dis.manufacturer)) print('Model: {0}'.format(dis.model)) print('Serial: {0}'.format(dis.serial)) print('Hardware Revision: {0}'.format(dis.hw_revision)) print('Software Revision: {0}'.format(dis.sw_revision)) print('Firmware Revision: {0}'.format(dis.fw_revision)) print('System ID: {0}'.format(dis.system_id)) print('Regulatory Cert: {0}'.format(dis.regulatory_cert)) print('PnP ID: {0}'.format(dis.pnp_id)) finally: # Make sure device is disconnected on exit. device.disconnect()
def __init__(self, device, index): self.device = device self.osc = OSC.OSCClient() self.osc.connect(("127.0.0.1", BASE_PORT + index)) device.connect() UART.discover(self.device) self.uart = UART(self.device) self.index = index
def setup_uart(self, device): print('Discovering services...') # Discover the services and create a uart object UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) return uart
def setup(self): # Clear any cached data, prevent from going stale self.ble.clear_cached_data() # Get a BLE network adapter and turn it on self.adapter = self.ble.get_default_adapter() self.adapter.power_on() # Disconnect from any uart devices UART.disconnect_devices()
def BLE(): # 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). device = UART.find_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('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...') 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 ble_main(): global msg ble.clear_cached_data() adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) print('Disconnecting any connected UART devices...') UART.disconnect_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). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() # Connect to first device 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('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) print('Connected') client.loop_background() while True: received = uart.read(3) if received is not None: # Received data, print it out. print('UART received: {0} Writing RED to MQTT'.format(received)) client.publish(FEED_PUB, 'RED') #uart.write('GREEN\r\n') # else: # print('UART got nothing') if msg is not None: print('MQTT received: {0} Writing RED to UART'.format(msg)) uart.write('RED\r\n') msg = None # else: # print('MQTT got nothing') 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() print('Searching for device...') connected_to_peripheral = False test_iteration = 0 devices = scan_for_peripheral(adapter) global total_len, done_xfer, data_service, out for peripheral in devices: try: print("peripheral: ", peripheral.name) peripheral.connect(timeout_sec=10) connected_to_peripheral = True test_iteration += 1 except BaseException as e: print("Connection failed: " + str(e)) time.sleep(1) print("Retrying...") # print(peripheral.list_services()) # print(peripheral.id) # print(peripheral._peripheral.identifier()) peripheral.discover([service_uuid], [count_uuid, rw_uuid, spp_data_uuid]) service = peripheral.find_service(service_uuid) count = service.find_characteristic(count_uuid) rw = service.find_characteristic(rw_uuid) data_service = service.find_characteristic(spp_data_uuid) read_val = rw.read_value() # print(service) # print(service, count, rw) print("rw: ", read_val) count_raw = int.from_bytes(count.read_value(), byteorder='little') print("count: ", count_raw) rw.write_value(b'w') print('rw.read_value()', rw.read_value())
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 start_system(): global sensor_data allowed_ids = [UUID("1c7c996c-79b0-47df-905a-93233d6fdc67")] devices = getDevices(allowed_ids) # dict of uuid: device # uarts are used to read and write data over bluetooth uarts = {device.id: UART(device) for device in devices.values()} packet_len = 20 uart_stream = UARTStream(devices[allowed_ids[0]], uarts[allowed_ids[0]]) # tracker = AccelTracker() try: # start data handlers thread.start_new_thread(userInputHandler, ()) remote_handler = RemoteInputHandler() remote_handler.start() # spin until system is ready while not system_ready(remote_handler): if end_program or remote_handler.received_quit(): break if not end_program and not remote_handler.received_quit(): # onlys start drums if user has not quit start_drums(remote_handler, uart_stream) # returns when received a quit signal #except Exception as e: # print(e) # raise e finally: for device in devices.values(): device.disconnect() # plotSensorData(sensor_data) saveData(sensor_data)
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 start(self): """ Reset any lingering bluetooth state """ # Clear any cached data because both bluez and CoreBluetooth have issues # with caching data and it going stale. PROVIDER.clear_cached_data() # Get the first available BLE network adapter # and make sure it's powered on. self.adapter = PROVIDER.get_default_adapter() self.adapter.power_on() print "Using adapter: {0}".format(self.adapter.name) # Disconnect any currently connected UART devices. # Good for cleaning up and tarting from a fresh state. print "Disconnecting any connected UART devices..." UART.disconnect_devices() self.adapter.start_scan()
def _connect(self, adapter): adapter.power_on() logging.info('Disconnecting any connected UART devices...') UART.disconnect_devices() logging.info('Searching for UART device...') try: adapter.start_scan(timeout_sec=100) self._device = platform.get_provider().find_device(name='BerryMed') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() if not self._device: raise RuntimeError("Couldn't find BerryMed pulse meter.") logging.info('Connecting to device...') logging.info('Device id: %s', str(self._device.id)) self._device.connect() # with default timeout 60 seconds. logging.info('Successfully connected.')
def mainBluetooth(): global sendCommand global confirmation # Clear any cached data ble.clear_cached_data() # Get first available adapter and make sure it is powered on adapter = ble.get_default_adapter() adapter.power_on() print("Using adapter: {0}".format(adapter.name)) # Disconnect any currently connected devices print("Disconnecting any connected UART devices...") UART.disconnect_devices() # Scan for UART devices print("Searching for UART device...") try: adapter.start_scan() device = UART.find_device() if device is None: raise RuntimeError("Failed to find UART device!") finally: adapter.stop_scan() print("Connecting to device...") device.connect() try: print("Discovering services...") UART.discover(device) # Create instance to interact with uart = UART(device) sendCommand = sendCommand.encode() uart.write(b"%b" % (sendCommand)) received = uart.read(timeout_sec=10) if received is not None: print("Received: {0}".format(received)) confirmation = "Received: " + received else: print("Received no data!") confirmation = "Received no data!" finally: 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). device = UART.find_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. print('Discovering services...') UART.discover(device) while True: uart = UART(device) receive = uart.read(timeout_sec=300) # 5min timeout if receive: sd = receive.split(",") print("T: " + sd[0] + " H: " + sd[1] + " Li: " + sd[2] + " Lux: " + sd[3] + " N: " + sd[4] + " HR: " + sd[5]) else: continue if len(sd) == 6: aio.send('Temperature', sd[0]) aio.send('Humidity', sd[1]) aio.send('Light', sd[2]) aio.send('Lux', sd[3]) aio.send('Noise', sd[4]) aio.send('Heart Rate', sd[5]) else: continue
def __setup_thread(self): # Service and Character UUID's UART_SERVICE_UUID = uuid.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E') TX_CHAR_UUID = uuid.UUID('6E400002-B5A3-F393-E0A9-E50E24DCCA9E') RX_CHAR_UUID = uuid.UUID('6E400003-B5A3-F393-E0A9-E50E24DCCA9E') SENSE_SERVICE_UUID = uuid.UUID('00006969-6969-6969-6969-696969696969') RSSI_CHAR_UUID = uuid.UUID('00000420-0000-1000-8000-00805f9b34fb') TEMP_CHAR_UUID = uuid.UUID('00000421-0000-1000-8000-00805f9b34fb') PRESS_CHAR_UUID = uuid.UUID('00000422-0000-1000-8000-00805f9b34fb') HUM_CHAR_UUID = uuid.UUID('00000423-0000-1000-8000-00805f9b34fb') GAS_CHAR_UUID = uuid.UUID('00000424-0000-1000-8000-00805f9b34fb') ALT_CHAR_UUID = uuid.UUID('00000425-0000-1000-8000-00805f9b34fb') self.ble.clear_cached_data() # get adapter and power on adapter = self.ble.get_default_adapter() adapter.power_on() # Disconnect currently connected devices self.ble.disconnect_devices() # Connect to UART device try: print('Scanning for devices...') adapter.start_scan() self.device = UART.find_device() if self.device is None: raise RuntimeError('Failed to find UART device!') finally: adapter.stop_scan() self.device.connect() # Discover Services and Characteristics print('Discovering...') self.device.discover([SENSE_SERVICE_UUID], [ RSSI_CHAR_UUID, TEMP_CHAR_UUID, PRESS_CHAR_UUID, HUM_CHAR_UUID, GAS_CHAR_UUID, ALT_CHAR_UUID ]) # Find Services and Characteristics print('Finding services...') sensors = self.device.find_service(SENSE_SERVICE_UUID) self.chars = { "rssi": sensors.find_characteristic(RSSI_CHAR_UUID), "temp": sensors.find_characteristic(TEMP_CHAR_UUID), "pressure": sensors.find_characteristic(PRESS_CHAR_UUID), "humidity": sensors.find_characteristic(HUM_CHAR_UUID), "gas": sensors.find_characteristic(GAS_CHAR_UUID), "alt": sensors.find_characteristic(ALT_CHAR_UUID) } file = open("rfOutput.csv", "w") file.write( 'RSSI (dB),TEMP (*C),PRESSURE (hPa),HUMIDITY (%),GAS (KOhms),ALT (m)\n' ) file.close() print('rf setup')
def main(): ble.clear_cached_data() adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) print('Disconnecting any connected UART devices...') UART.disconnect_devices() print('Searching for UART device...') try: adapter.start_scan() device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: adapter.stop_scan() print("Connecting to a UART device...") device.connect() print("Connected to " + device.name + "!") # call method to launch gui, implement later # getch library for sending stuff # launchGUI() try: print('Discovering services...') DeviceInformation.discover(device) dis = DeviceInformation(device) # Print out the DIS characteristics. print('Manufacturer: {0}'.format(dis.manufacturer)) print('Model: {0}'.format(dis.model)) print('Serial: {0}'.format(dis.serial)) print('Hardware Revision: {0}'.format(dis.hw_revision)) print('Software Revision: {0}'.format(dis.sw_revision)) print('Firmware Revision: {0}'.format(dis.fw_revision)) print('System ID: {0}'.format(dis.system_id)) print('Regulatory Cert: {0}'.format(dis.regulatory_cert)) print('PnP ID: {0}'.format(dis.pnp_id)) finally: device.disconnect()
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 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 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 connect(self, onFinished): # 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). self.device = UART.find_device() if self.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...') self.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. success = 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(self.device) # Once service discovery is complete create an instance of the service # and start interacting with it. self.uart = UART(self.device) success = True except: traceback.print_exc() self.device.disconnect() self.device = None self.uart = None finally: # Make sure device is disconnected on exit.: onFinished(success)
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(): ble.clear_cached_data() adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) device = None packet_source = PacketSource(config) UART.disconnect_devices() while True: try: print('Connecting to device...') adapter.start_scan() device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') device.connect() UART.discover(device) uart = UART(device) for packet in packet_source.read_packets(): debug('Sending packet: value={0}, metric={1}, timestamp={2}'. format(packet.value, packet.metric, packet.timestamp)) uart.write(packet.to_bytes()) print('Going to sleep for {0} seconds...'.format( config.poll_interval)) sleep(config.poll_interval) print('Disconnecting devices before restarting main loop...') device.disconnect() adapter.stop_scan() except Exception as e: print('Caught exception of type {0} in main loop: {1}'.format( sys.exc_info()[0], str(e))) sleep(5) # bleccchh
def start_system(): global sensor_data allowed_ids = [UUID("1c7c996c-79b0-47df-905a-93233d6fdc67")] devices = getDevices(allowed_ids) # dict of uuid: device # uarts are used to read and write data over bluetooth uarts = {device.id: UART(device) for device in devices.values()} packet_len = 20 uart_stream = UARTStream(devices[allowed_ids[0]], uarts[allowed_ids[0]]) # tracker = AccelTracker() x_pulse_tracker = DrumPulseTracker(-10.0, 0.0, 10, name="x") y_pulse_tracker = DrumPulseTracker(-10.0, 0.0, 10, name="y") z_pulse_tracker = DrumPulseTracker(-10.0, 0.0, 10, name="z") accel_printer = PeriodicPrinter(1.0) audio_player = audio.Audio() try: thread.start_new_thread(userInputHandler, ()) # tracker.start() x_pulse_tracker.start() y_pulse_tracker.start() z_pulse_tracker.start() c = 0 while not end_program: sensor_str = uart_stream.readBetween("[", "]") # print "Received: {}".format(sensor_str) (t, vect) = parseSensorData(sensor_str) x, y, z = vect.toArray() x_pulse_tracker.update(t, x) y_pulse_tracker.update(t, y) if z_pulse_tracker.update(t, z): print "Pulse Detected at time t = {}".format(c) audio_player.queue_sound("kick", 100) collectData(x_pulse_tracker.getAcceleration(), y_pulse_tracker.getAcceleration(), z_pulse_tracker.getAcceleration()) # sensor_data.append(vect.toArray()) # tracker.updateAccel(t, vect) # accel_printer.printVal("Displacement = {}".format(tracker.getDisplacement())) # print "velocity: {}".format(tracker.getVelocity().toArray()) c += 1 #except Exception as e: # print(e) # raise e finally: for device in devices.values(): device.disconnect() # plotSensorData(sensor_data) saveData(sensor_data)
def __setup_thread(self): # Bluetooth UUIDs SENSE_SERVICE_UUID = uuid.UUID('00006969-6969-6969-6969-696969696969') RSSI_CHAR_UUID = uuid.UUID('00000420-0000-1000-8000-00805f9b34fb') TEMP_CHAR_UUID = uuid.UUID('00000421-0000-1000-8000-00805f9b34fb') PRESS_CHAR_UUID = uuid.UUID('00000422-0000-1000-8000-00805f9b34fb') HUM_CHAR_UUID = uuid.UUID('00000423-0000-1000-8000-00805f9b34fb') GAS_CHAR_UUID = uuid.UUID('00000424-0000-1000-8000-00805f9b34fb') ALT_CHAR_UUID = uuid.UUID('00000425-0000-1000-8000-00805f9b34fb') self.ble.clear_cached_data() adapter = self.ble.get_default_adapter() adapter.power_on() self.ble.disconnect_devices() try: print('Scanning for devices...') adapter.start_scan() self.device = UART.find_device() if self.device is None: raise RuntimeError('Failed to find UART device!') finally: adapter.stop_scan() self.device.connect() # Discover Bluetooth services and characteristics self.device.discover([SENSE_SERVICE_UUID], [RSSI_CHAR_UUID, TEMP_CHAR_UUID, PRESS_CHAR_UUID, HUM_CHAR_UUID, GAS_CHAR_UUID, ALT_CHAR_UUID]) # Find Bluetooth services and characteristics sensors = self.device.find_service(SENSE_SERVICE_UUID) self.chars = { "rssi": sensors.find_characteristic(RSSI_CHAR_UUID), "temp": sensors.find_characteristic(TEMP_CHAR_UUID), "pressure": sensors.find_characteristic(PRESS_CHAR_UUID), "humidity": sensors.find_characteristic(HUM_CHAR_UUID), "gas": sensors.find_characteristic(GAS_CHAR_UUID), "alt": sensors.find_characteristic(ALT_CHAR_UUID) } # Setup rfOutput.csv output_file = open("rfOutput.csv", "w") output_file.write('RSSI (dB),TEMP (*C),PRESSURE (hPa),HUMIDITY (%),GAS (KOhms),ALT (m)\n') output_file.close()
def connect_to_device(self): """Connects to the device. Returns: A pair containing the device that we connected to and the UART instance. """ self.ble.clear_cached_data() adapter = self.ble.get_default_adapter() adapter.power_on() print('Using adapter: {}'.format(adapter.name)) print('Disconnecting any connected UART devices...') UART.disconnect_devices() print('Searching for UART device...') try: adapter.start_scan() device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: adapter.stop_scan() print('Connecting to device...') device.connect() try: print('Discovering services...') UART.discover(device) uart = UART(device) except: device.disconnect() raise return (device, uart)
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). device = UART.find_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('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. s.enter(5, 1, check_db, (s, repeatChecker, canReactDB, waitUntil, uart)) s.run() ##should never get here finally: # Make sure device is disconnected on exit. device.disconnect()
def main(): ble.clear_cached_data() UART.disconnect_devices() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() # Find UART device device = find_device(adapter, deviceName) if device is None: raise RuntimeError('Failed to find UART device!') logging.info('connecting to {0} [{1}]'.format(device.name, device.id)) # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. device.connect() try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). UART.discover(device, timeout_sec=5) uart = UART(device) # Read temperature data from the sensor while True: received = uart.read(timeout_sec=5) if received is not None: logging.debug('received {0} bytes: {1}'.format(len(received), received)) t1, t2 = parse_datapoint(received) if not t1 and not t2: continue # Log temperature data to file or stdout if logFile: with open(logFile, 'w') as fp: fp.write('{0},{1}'.format(t1, t2)) else: print('{0},{1}'.format(t1, t2)) else: # Timeout waiting for data, None is returned. break finally: # Make sure device is disconnected on exit. logging.info('disconnected from {0} [{1}]'.format(device.name, device.id)) try: device.disconnect() except: pass
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(): ble.clear_cached_data() adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) print('Disconnecting any connected UART devices...') UART.disconnect_devices() print('Searching for UART device...') try: adapter.start_scan() device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: adapter.stop_scan() print('Connecting to device...') device.connect() try: print('Discovering services...') UART.discover(device) uart = UART(device) while(True): n = randbyte(0, LEDCOUNT) r = randbyte(0, 256) g = randbyte(0, 256) b = randbyte(0, 256) s = b'n'+n+b'r'+r+b'g'+g+b'b'+b+b'\r'+b'\n' print(s) uart.write(s) sleep(1) print('Waiting up to 60 seconds to receive data from the device...') finally: device.disconnect()
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 main(): ble.clear_cached_data() # get bluetooth adapter and turn it on adapter = ble.get_default_adapter() adapter.power_on() # disconnect old UART devices UART.disconnect_devices() try: adapter.start_scan() device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: adapter.stop_scan() device.connect() print('Connected to device...') try: UART.discover(device) uart = UART(device) while True: received = uart.read(timeout_sec=30) if received is not None: print('Received: {0}'.format(received)) print(datetime.datetime.strftime(datetime.datetime.now(), '%H:%M:%S')) stream.add_value(received) else: print('Received no data!') break finally: device.disconnect()
def ble_ain(): #global t # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() print 'ble_main()' # 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). device = UART.find_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('Discovering services...') UART.discover(device,timeout_sec=5) # 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("Send request to device...") #uart.write('r') # Now wait up to one minute to receive data from the device. print('Waiting up to 15 seconds to receive data from the device...') received = uart.read(timeout_sec=15) if received is not None: wd='0x' for i in reversed(received[0:8]): print('Received: {0}'.format(ord(i))) c=hex(ord(i))[2:] if len(c)<2: wd += '0'+c else: wd += c print(wd) t=w.decrypt(int(wd,16)) print(hex(t)) print("t-ul meu este") print(t) t1=hex(t)[2:] a=0 b=2 wsend='' for i in range(int(len(t1)/2)): wsend += str(int(t1[a:b],16)) wsend+=';' a+=2 b+=2 print(wsend) wsSend(wsend) 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...') 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). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Found UART: {0} [{1}]'.format(device.name, device.id)) 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('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) #print("DEVICE FOUND IS 1->"+uart.CHARACTERISTICS) #print("DEVICE FOUND IS 2->" + uart.ADVERTISED) #print("DEVICE FOUND IS 3->" + uart.SERVICES) colors = ['hello','r','g','b','r','g','b','r','g','b','a'] for x in colors: # Write a string to the TX characteristic. uart.write('hello') print("sent--->hello") #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...') received = uart.read(timeout_sec=10) time.sleep(10) if received is not None: # Received data, print it out. print('Received: {0}'.format(received)) #establish connectivity and get an ACK to continue communication print("SENT -->"+x) uart.write(x) 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...') 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). device = UART.find_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('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...') received = uart.read(timeout_sec=60) if received is not None: print received hexd = received.decode("hex") bytearray = array.array('B', hexd) magnetometerX = struct.unpack( '>H', bytearray[0:2] ) magnetometerY = struct.unpack( '>H', bytearray[2:4] ) magnetometerZ = struct.unpack( '>H', bytearray[4:6] ) accX = struct.unpack( '<H', bytearray[6:8] ) accY = struct.unpack( '<H', bytearray[8:10] ) accZ = struct.unpack( '<H', bytearray[10:12] ) gyroX = struct.unpack( '>H', bytearray[12:14] ) gyroY = struct.unpack( '>H', bytearray[14:16] ) gyroZ = struct.unpack( '>H', bytearray[16:18] ) print "MAG: " + str(magnetometerX[0]) + "," + str(magnetometerY[0]) + "," + str(magnetometerZ[0]) print "ACCEL: " + str(accX[0]) + "," + str(accY[0]) + "," + str(accZ[0]) print "GYRO: " + str(gyroX[0]) + "," + str(gyroY[0]) + "," + str(gyroZ[0]) print "-----------------" else: # Timeout waiting for data, None is returned. print('Received no data!') finally: # Make sure device is disconnected on exit. device.disconnect()