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(nuimo_uuid): print nuimo_uuid # Clear previously received data from the controller/adapter ble.clear_cached_data() # Connect to the default or first adapter and start scan adapter = ble.get_default_adapter() adapter.power_on() adapter.start_scan() # It needs bit of time to scan the devices. Some Peripherals advertise in different time.sleep(2) # Find all the ble devices with the name nuimo,this filtering part is done by Adafruit # devices -> interfaces/device/bluez-device, properties and method can be found there # id is MAC on Linux and on OSX uuid generated by OSX devices = ble.find_devices() for device in devices: print('Found device: {0}, id: {1}'.format(device.name, device.id)) if device.id == uuid.UUID(nuimo_uuid): device.connect() DeviceInformation.discover(device) dis = DeviceInformation(device) print('Firmware Revision: {0}'.format(dis.fw_revision)) device.disconnect() adapter.power_off()
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 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 _find_pulse_data_characteristic(self): DeviceInformation.discover(self._device) heartbeat_service = None for s in self._device.list_services(): logging.info('Discovered service %s: %s', str(s), s.uuid) if s.uuid == DATA_SERVICE_UUID: logging.info('Found heartbeat GATT service.') heartbeat_service = s if not heartbeat_service: raise RuntimeError("Couldn't find heartbeat service with uuid %s", DATA_SERVICE_UUID) receive_data_characteristic = None for c in heartbeat_service.list_characteristics(): if c.uuid == RECEIVE_CHARACTERISTIC: logging.info('Found "receive" characteristic of heartbeat service.') receive_data_characteristic = c if not receive_data_characteristic: raise RuntimeError("Couldn't find receive data characteristic of heartbeat service (uuid %s)", RECEIVE_CHARACTERISTIC) return receive_data_characteristic
def __init__(self, device): self._service = device.find_service(RS_SERV_UUID) self._char = self._service.find_characteristic(CHAR_UUID) self._char.start_notify(self._data_received) self._responses = { chr(i): Queue.Queue() for i in range(0x41, 0x5a + 1) } self.files = [] self.file_update = False self.file_read = False self.serial = DeviceInformation(device).serial
def uart_service(): # 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) DeviceInformation.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) dis = DeviceInformation(device) print("Conntected to device: name: {}, id: {}".format( device.name, device.id)) # 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...') while (True): received = uart.read(timeout_sec=40) 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: print "Interrupted" device.disconnect()
def main(): target_device_name = u'RN4871-1444' target_device = None # 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 devices...') print('Press Ctrl-C to quit (will take ~30 seconds on OSX).') # Enter a loop and print out whenever a new device is found, and break when target is found. known_uarts = set() while type(target_device) == type(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(DeviceInformation.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 != None and device.id != None): dev_name = unicode(device.name).encode('ascii', 'xmlcharrefreplace') dev_id = unicode(device.id).encode('ascii', 'xmlcharrefreplace') print('Found Device: {0} [{1}]'.format(dev_name, dev_id)) if (dev_name == target_device_name): target_device = device print('Found Target Device!') known_uarts.update(new) if (type(target_device) != type(None)): break # Sleep for a half second and see if new devices have appeared. time.sleep(0.2) print('Connecting to device...') target_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: print('Discovering services...') UART.discover(target_device) print('Service discovery complete') articulate_board = UART(target_device) time.sleep(1.0) print('Reading BT data') received = "" while (received != None): received = articulate_board.read(timeout_sec=10) if received is not None: print(received) else: # Timeout waiting for data, None is returned. print('Received no data in 10s!') except Exception, e: print('Failed with Exception: \'{}\''.format(e))
def main(bt): devices = [] def update_list(current_devices): for device in current_devices: if not device in devices: devices.append(device) print "#{}: {} {} {} {} ".format(devices.index(device), device.name, device.id, device.is_connected, device.advertised) print "Type number of device + enter to connect" bt.scan(update_list) name = int(raw_input()) device = devices[name] scribe = bt.connect_to(device) print ("Connected") print "#{}: {} {} {} {}".format(devices.index(device), device.name, device.id, device.is_connected, device.advertised) while True: cmd = raw_input("> ") if cmd == "q": break elif cmd == "reboot": print "Reboot type : 0 - soft, 1 - hard" r_type = int(raw_input()) scribe.reboot(r_type) #elif cmd == "annotate file": # print "Enter data 1 (32 bit number)" # data_1 = int(raw_input()) # print "Enter data 2 (16 bit number)" # data_2 = int(raw_input()) # print_dict(scribe.annotate_file(data_1, data_2)) # print_dict(scribe.annotate_file(0,1)) elif cmd == "update crc": print "file block size : (16-default)" file_block_size = int(raw_input()) print "file point buffer : (0 - default)" file_point_buffer = int(raw_input()) print_dict(scribe.update_crc_checksum(file_block_size, file_point_buffer)) elif cmd == "load file list": print "0,1 - All files, 2 - undeleted file" files = int(raw_input()) all_files = True if files == 2 : all_files = False files = scribe.load_file_list(all_files) for f in files: print_dict(f) elif cmd == "erase data": print "erase type (1-partial 0,2-chip, 3-deleted, 4-EEPROM/default ): " e_type = int(raw_input()) print "erase bit mask (1-file): " e_bit_mask = int(raw_input()) print_dict(scribe.erase_data(e_type, e_bit_mask)) elif cmd == "DFU mode": scribe.DFU_mode() print "Scribe in DFU mode" elif cmd == "real time polling": print "Enter mode (0 => Accel, 1 => Gyro, 2 => Compass):" mode = int(raw_input()) print_dict(scribe.real_time_polling(mode)) elif cmd == "manufacturing mode": # deep motion sleep print "state : (0 - off, 1 - on)" state = int(raw_input()) print_dict(scribe.manufacturing_mode(state)) elif cmd == "file information": print "Type file index : " file_idx = int(raw_input()) print "File block size (default - 16) : " block_size = int(raw_input()) print_dict(scribe.get_file_info(file_idx, block_size)) elif cmd == "set led color": r = 0 ; g = 0 ; b = 0 print 'Select color (0 - green, 1 - yellow, 2 - blue, 3 - purple): ' color = int(raw_input()) if color == 1 : r = 255 ; g = 255 elif color == 2 : b = 255 elif color == 3 : r = 255 ; b = 255 else : g = 255 r, g, b = scribe.set_led_color(r, g, b) string = 'Red : ' + str(r) + ', Green: ' + str(g) + ', Blue: ' + str(b) print string elif cmd == "get led color": r, g, b = scribe.get_led_color() string = 'Red : ' + str(r) + ', Green: ' + str(g) + ', Blue: ' + str(b) print string elif cmd == "light": print "Mode (13 - connected, 14 - recording, 15 - syncing, 16 - sync_complete, 17 - low battery) :" mode = int(raw_input()) print "cycles (default 1): " cycles = int(raw_input()) print "Red : " r = int(raw_input()) print "Green : " g = int(raw_input()) print "Blue : " b = int(raw_input()) print_dict(scribe.light_led(mode, cycles, r, g, b)) elif cmd == "set mode": print "Command (0 - N/A, 1 - record, 2 - pause, 3 - sync) : " command = int(raw_input()) print "state : (0 - off, 1 - on)" state = int(raw_input()) print_dict(scribe.set_mode(command, state)) elif cmd == "polling status": print_dict(scribe.polling_status()) elif cmd == "stop read data": print_dict(scribe.stop_read_data()) elif cmd == "read data": print "Type file index : " file_idx = int(raw_input()) print "Type file block data point : " data_pt = int(raw_input()) scribe.read_data(file_idx, data_pt) elif cmd == "status": print_dict(scribe.status()) elif cmd == "set time": devicetime = [] for i in range(0,4): print "device time " + str(i) + " : " devicetime.append(int(raw_input())) print_dict(scribe.set_time(devicetime[0], devicetime[1], devicetime[2], devicetime[3])) elif cmd == "read time": print_dict(scribe.read_time()) elif cmd == "read configuration data": print "Enter config point (0xAA01..7): " configpoint = int(raw_input(),16) print "Enter config block size (default - 16 ) : " blocksize = int(raw_input()) print_dict(scribe.read_config_data(configblocksize = blocksize, configpoint = configpoint)) elif cmd == "write configuration data": print "Enter config point (0xAA01..7))" configpoint = int(raw_input(),16) if configpoint == 0xAA01 or configpoint == 0xAA03: print "config block size : " configblocksize = int(raw_input()) bledevice = [] for i in range(0,16) : print "ble device " + str(i) + " : " bledevice.append(int(raw_input())) packet = struct.pack(">BHBBBBBBBBBBBBBBBB", configblocksize, configpoint, bledevice[0], bledevice[1], bledevice[2], bledevice[3], bledevice[4], bledevice[5], bledevice[6], bledevice[7], bledevice[8], bledevice[9], bledevice[10], bledevice[11], bledevice[12], bledevice[13], bledevice[14], bledevice[15]) elif configpoint == 0xAA02: print "config block size : " configblocksize = int(raw_input()) print "led color : " bledevice_ledcolor = int(raw_input()) print "heel/lace : " heel_lace = int(raw_input()) print "right/left : " right_left = int(raw_input()) device_time = [] for i in range(0,4): print "device time " + str(i) + " : " device_time.append(int(raw_input())) print "device sample rate : " device_sample_rate = int(raw_input()) print "sensitivity : " sensitivity = int(raw_input()) print "Timeout : " timeout = int(raw_input()) print "stride rate : " stride_rate = int(raw_input()) print "min conn interval : " min_conn_interval = int(raw_input()) print "max conn interval : " max_conn_interval = int(raw_input()) print "ble slave latency : " ble_slave_latency = int(raw_input()) packet = struct.pack(">BHBBBBBBBBBBBBBB", configblocksize, configpoint, bledevice_ledcolor, heel_lace, right_left, device_time[0], device_time[1], device_time[2], device_time[3], device_sample_rate, sensitivity, timeout, stride_rate, min_conn_interval, max_conn_interval, ble_slave_latency) elif configpoint == 0xAA04: print "config block size : " configblocksize = int(raw_input()) print "heel/lace : " heel_lace = int(raw_input()) print "right/left : " right_left = int(raw_input()) print "Timeout : " timeout = int(raw_input()) print "stride rate : " stride_rate = int(raw_input()) print "scale factor A : " scale_factor_A = int(raw_input()) print "scale factor B : " scale_factor_B = int(raw_input()) print "min recording voltage MSB : " min_recording_voltage_MSB = int(raw_input()) print "min recording voltage LSB : " min_recording_voltage_LSB = int(raw_input()) print "deep sleep voltage MSB : " deep_sleep_voltage_MSB = int(raw_input()) print "deep sleep voltage LSB : " deep_sleep_voltage_LSB = int(raw_input()) print "R : " R = int(raw_input()) print "G : " G = int(raw_input()) print "B : " B = int(raw_input()) packet = struct.pack(">BHBBBBBBBBBBBBB", configblocksize, configpoint, heel_lace, right_left, timeout, stride_rate, scale_factor_A, scale_factor_B, min_recording_voltage_MSB, min_recording_voltage_LSB, deep_sleep_voltage_MSB, deep_sleep_voltage_LSB, R, G, B ) elif configpoint == 0xAA05: print "config block size : " configblocksize = int(raw_input()) print "min conn interval : " min_conn_interval = int(raw_input()) print "max conn interval : " max_conn_interval = int(raw_input()) print "ble slave latency : " ble_slave_latency = int(raw_input()) packet = struct.pack(">BHBBB", configblocksize, configpoint, min_conn_interval, max_conn_interval, ble_slave_latency) elif configpoint == 0xAA06: print "config block size : " configblocksize = int(raw_input()) print "raw data : " raw_data = int(raw_input()) packet = struct.pack(">BHB", configblocksize, configpoint, raw_data) elif configpoint == 0xAA07: print "config block size : " configblocksize = int(raw_input()) print "bettery capacity : " bettery_capacity = int(raw_input()) packet = struct.pack(">BHB", configblocksize, configpoint, bettery_capacity) print_dict(scribe.write_config_data(packet)) elif cmd == "perform diagnostics": print "update Calibration (default 0) : " updateCalibration = int(raw_input()) print_dict(scribe.perform_diagnostics(updateCalibration)) elif cmd == "get diagnostics results": print "packet Offset (default 0) : " packetOffset = int(raw_input()) print_dict(scribe.get_diagnostics_results(packetOffset)) elif cmd == "device information service": 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)) elif cmd == "disconnect": print "Disconecting device " print "#{}: {} {} {} {}".format(devices.index(device), device.name, device.id, device.is_connected, device.advertised) bt.disconnect() bt.end()
def main(): target_device_name = u'RN4871-1444' target_device = None # 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 devices...') print('Press Ctrl-C to quit (will take ~30 seconds on OSX).') # Enter a loop and print out whenever a new device is found, and break when target is found. known_uarts = set() while type(target_device) == type(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(DeviceInformation.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 != None and device.id != None): dev_name = unicode(device.name).encode('ascii', 'xmlcharrefreplace') dev_id = unicode(device.id).encode('ascii', 'xmlcharrefreplace') print('Found Device: {0} [{1}]'.format(dev_name, dev_id)) if (dev_name == target_device_name): target_device = device print('Found Target Device!') known_uarts.update(new) if (type(target_device) != type(None)): break # Sleep for a half second and see if new devices have appeared. time.sleep(0.2) print('Connecting to device...') target_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: print('Discovering services...') UART.discover(target_device) print('Service discovery complete') articulate_board = UART(target_device) time.sleep(1.0) print('Starting a comm test...') # comm test parameters NUM_TRIALS = 20 HEADER_VAL = chr(253) PACKET_SIZE = 40 OVERHEAD = 2 DATA_SIZE = PACKET_SIZE - OVERHEAD MAX_NUM_ERRORS = 10 tripTimes = [] successes = 0 failures = 0 for i in range(0,NUM_TRIALS): print('Trial', i) # generate random string # randomString = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(DATA_SIZE)]) randomString = chr(i+ord('0'))*30+'AAAAAAAA' reversedString = randomString[::-1] # get sum of character values checksum = chr(sum([ord(x) for x in randomString]) % 256) # start timer startTime = time.time() # send bytes articulate_board.write(HEADER_VAL) articulate_board.write(randomString) articulate_board.write(checksum) # wait for reception msg = '' error = 0 while((len(msg) < PACKET_SIZE) and (error < MAX_NUM_ERRORS)): received = articulate_board.read(timeout_sec=1) if received is not None: msg = msg + (received) else: error=error+1 # stop timer endTime = time.time() roundTripTime = endTime - startTime expectedResponse = (HEADER_VAL + reversedString + checksum) success = len(msg) == PACKET_SIZE and msg == expectedResponse successes = successes + (1 if success else 0) failures = failures + (0 if success else 1) if(success): tripTimes.append(roundTripTime) print("Exact success") elif(len(msg) == PACKET_SIZE): print("Received a full packet, but it was invalid.") print("Expected: " + (expectedResponse.decode('cp437'))) print("Received: " + (msg.decode('cp437'))) elif(msg == ''): print("Error: received nothing in " + str(roundTripTime) + " seconds. Checksum was: " + str(ord(checksum))) else: print("Error: didn't receive full packet in time") if(len(tripTimes) > 0): averageTime = sum(tripTimes) / len(tripTimes) else: averageTime = -1 print("Average round trip time was: " + str(averageTime) + " seconds") print("Success rate: " + str(successes) + "/" + str(successes+failures)) # except Exception, e: # print('Failed with Exception: \'{}\''.format(e)) # finally: # Make sure device is disconnected on exit. target_device.disconnect()
def main(): # provider.clear_cached_data() adapter = provider.get_default_adapter() print "Waiting powered on..." adapter.power_on() while not adapter.is_powered: time.sleep(1) print 'Using adapter {0}'.format(adapter.name) device = None try: print 'Start scanning...' adapter.start_scan() device = provider.find_device([], SENSOR_NAME, SCAN_TIMEOUT) finally: adapter.stop_scan() if device is None: print 'SensorTag not found' return try: print 'Connecting...' device.connect(CONNECT_TIMEOUT) except RuntimeError as e: print e return try: print 'Discovering device information...' DeviceInformation.discover(device) di = DeviceInformation(device) print 'Manufacture: {0}'.format(di.manufacturer) print 'Model: {0}'.format(di.model) print 'Serial: {0}'.format(di.serial) print 'Hardware Revision: {0}'.format(di.hw_revision) print 'Software Revision: {0}'.format(di.sw_revision) print 'Firmware Revision: {0}'.format(di.fw_revision) print 'System ID: {0}'.format(di.system_id) print 'Discovering service...' try: device.discover([MOVEMENT_SENSOR_SRV], [ MOVEMENT_SENSOR_CHR_CONFIG, MOVEMENT_SENSOR_CHR_DATA, MOVEMENT_SENSOR_CHR_PERIOD ], DISCOVER_TIMEOUT) except RuntimeError as e: print e return service = device.find_service(MOVEMENT_SENSOR_SRV) if service is None: print 'Service not found' return print 'Setting period...' c_period = service.find_characteristic(MOVEMENT_SENSOR_CHR_PERIOD) if c_period is None: print 'Period Characteristics not found' return c_period.write_value('\x0a') # 100 msec # # Notification callback # def on_notified(data): [gx, gy, gz, ax, ay, az, mx, my, mz] = gam.raw2nineaxis(data) ahrs.update(gam.deg2rad(gx), gam.deg2rad(gy), gam.deg2rad(gz), ax, ay, az, mx, my, mz) roll, pitch, yaw = gam.quaternion2euler(ahrs.quaternion) print '%10.5f %10.5f %10.5f' % ( math.degrees(roll), math.degrees(pitch), math.degrees(yaw)) print 'Subsribing notification...' c_data = service.find_characteristic(MOVEMENT_SENSOR_CHR_DATA) if c_data is None: print 'Data Characteristics not found' return c_data.start_notify(on_notified) print 'Enabling notification...' c_data._device._peripheral.setNotifyValue_forCharacteristic_( True, c_data._characteristic) print 'Enabling sensor...' c_config = service.find_characteristic(MOVEMENT_SENSOR_CHR_CONFIG) if c_config is None: print 'Config Characteristics not found' return c_config.write_value('\x7f\x02') # ACC RANGE 8G print 'Now, sleeping 60 seconds...' time.sleep(60) finally: print 'Disconnecting device...' 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 Timer devices...') TimerService.disconnect_devices() # Scan for devices. print('Searching for Timer device...') try: adapter.start_scan() # Search for the first device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = ble.find_device(name=device_name) if device is None: raise RuntimeError('Failed to find Timer device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() pass 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. # Wait for service discovery to complete for the DIS service. Will # time out after 60 seconds (specify timeout_sec parameter to override). try: 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: {}'.format(dis.manufacturer)) print('Model: {}'.format(dis.model)) print('Serial: {}'.format(dis.serial)) print('Hardware Revision: {}'.format(dis.hw_revision)) print('Software Revision: {}'.format(dis.sw_revision)) print('Firmware Revision: {}'.format(dis.fw_revision)) print('System ID: {}'.format(dis.system_id)) print('Regulatory Cert: {}'.format(dis.regulatory_cert)) print('PnP ID: {}'.format(dis.pnp_id)) print('RSSI: {}'.format(device.rssi)) # loop through services for service in device.list_services(): print("") print("Service: {}".format(service.uuid)) print("Characteristics:") for char in service.list_characteristics(): val = char.read_value() print(" {} - {} - {}".format(char.uuid, val, bytes_to_str(val))) """ print(" Descriptors:") for desc in char.list_descriptors(): try: print(" {} - {}".format(desc.uuid, desc.read_value())) except AttributeError as e: print(" {} - not readable".format(desc.uuid)) """ finally: # Make sure device is disconnected on exit. device.disconnect()