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()
Exemplo n.º 3
0
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
Exemplo n.º 4
0
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
Exemplo n.º 5
0
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()
Exemplo n.º 6
0
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()
Exemplo n.º 7
0
 def close(self):
     self.stoprequest.set()
     try:
         UART.disconnect_devices()
         # self.device.disconnect()
         logger.info('connection lost')
     except:
         print('mimsy')
Exemplo n.º 8
0
	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()
Exemplo n.º 10
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))

    # 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
Exemplo n.º 11
0
    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()
Exemplo n.º 12
0
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
Exemplo n.º 13
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))
    # 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())
Exemplo n.º 14
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()
Exemplo n.º 15
0
 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.')
Exemplo n.º 16
0
        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()
Exemplo n.º 17
0
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()
Exemplo n.º 18
0
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
Exemplo n.º 19
0
def bleinit():
    global uart
    print('-----Wireless Voltage Test-----')
    print('Start searching')
    ble.clear_cached_data()

    global adapter, devices, uart
    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 "done!"
    # get all the connected devices
    devices = connect_ble_devices()

    print('**************************')
    print('discovering UART service'),
    while True:
        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(devices[0], timeout_sec=2)
            if len(devices) == 2:
                UART.discover(devices[1], timeout_sec=2)

            # Once service discovery is complete create an instance of the service
            # and start interacting with it.
            uart = list()
            uart.append(UART(devices[0]))
            if len(devices) == 2:
                uart.append(UART(devices[1]))
            break
        except:
            print "FAILED!!!"
            raise
    print "done!"
Exemplo n.º 20
0
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}
Exemplo n.º 21
0
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()
Exemplo n.º 22
0
    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)
Exemplo n.º 23
0
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()
Exemplo n.º 24
0
  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)
Exemplo n.º 25
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))

    # 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()
Exemplo n.º 26
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))

    # 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()
Exemplo n.º 27
0
    def main(self):
        self.ble.clear_cached_data()
        print("Finding adapter...")
        self.adapter = self.ble.get_default_adapter()
        if (self.adapter == None):
            print("No bluetooth adapter found! STOPPING!!")
            return None

        # Power on adapter
        self.adapter.power_on()

        # Disconnect currently connected devices
        UART.disconnect_devices()

        # Scan for available devices
        if (self.scantime is None):  # If not set by command line
            inptstr = "Enter scan time in seconds [{}]:".format(
                DEFAULT_SCANTIME)
            inpt = raw_input(inptstr)
            try:
                self.scantime = int(inpt)
            except ValueError:
                self.scantime = DEFAULT_SCANTIME
        self.scan(self.scantime)
        if (len(self.found_devices) == 0):
            print("No UARTS found! STOPPING!!")
            return None

        print("\r\nFound Devices: ")
        self.show_devices()
        inptstr = "Select device (by index) [{}]:".format(DEFAULT_DEV_INDEX)
        inpt = raw_input(inptstr)
        try:
            i = int(inpt)
        except ValueError:
            i = DEFAULT_DEV_INDEX
        self.device = self.found_devices[i]

        print("Opening logs...")
        self.log_open()
        print("Logs opened.")
        print("Opening Input...")
        self.input_open()
        print("Input opened.")
        try:
            print("Connecting to device...")
            self.device.connect()
            if (self.device.is_connected):
                print("Device Connected Successfully.")
            else:
                print("Device did not connect!!!")
                raise KeyboardInterrupt

            self.init_uart()
            self.uart_start_read()

            rxstr = ""
            print("Entering Main Loop.")
            while True:
                throttle = True
                # Build string until it has a newline,
                #  then log it.
                if (len(self.rxbuf) > 0):
                    rxstr = self.rxbuf.pop()
                    #                    print(repr(rxstr))
                    #if (rxstr.endswith("\n")):
                    #    self.log(rxstr)
                    #    rxstr = ""
                    self.log(rxstr)
                    throttle = False

                line = self.input_read()
                if (line != None):
                    print("Input: " + line)
                    self.txbuf.insert(0, line)
                    throttle = False

                good = True
                while ((len(self.txbuf) > 0) and good):
                    line = self.txbuf[-1]
                    good = self.output_send(line)  # set good False if bad
                    if (good):
                        self.txbuf.pop()
                    throttle = False

                if (not self.device.is_connected):
                    self.device.connect()
                    throttle = False

        except KeyboardInterrupt:
            self.cleanup()
def main():
    while True:
        # 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('RetTemp!')
            # print("Sent 'Command' to the device.")

            # Now wait up to one minute to receive data from the device.
            received = uart.read(timeout_sec=5)
            ProximityStatus = received[0]                  //The First Byte (0 index) of Data has Proximity status
            LCStatus = received[1]                         //LC status is in second byte
            LightStatus = received[2]                      //Ambient Light Status is in 3rd byte
            SecurityStatus = received[3]                   //Security status is in 4th byte
            Temperature = received[4] + received[5] + received[6] + received[7] + received[8] //Temperature comes as +/-XX.X. So it takes total 5 bytes
       	    if received is not None:
            # Received data, print it out.
            print('Received: {0}'.format(received))
            print('Proximity status:{0} '.format(ProximityStatus))
            print('LC status:{0} '.format(LCStatus))
            print('Security  status:{0} '.format(SecurityStatus))
            print('Temperature:{0} '.format(Temperature))
            ProximityStatus = ConvStatus(ProximityStatus)
            LCStatus = ConvStatus(LCStatus)
            SecurityStatus = ConvStatus(SecurityStatus)
		    
		##################### #Text Alerts Using Twilio #######################
		from twilio.rest import TwilioRestClient
		# put your own credentials here
		ACCOUNT_SID = "AC5494daeb03b2d70d515fbb3368686579"
		AUTH_TOKEN = "4e22ad671980b60b21b425be4b23e9ee"
		client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
		if Temperature >= +30:
			print "Temperature is above set max"
			client.messages.create(
			        to="+17609107488",
			        from_="+17608002048",
			        body="Temperature is above set max",
			)
                if Temperature <= +15:
			print "Temperature is below set min"
                        client.messages.create(
                                to="+17609107488",
                                from_="+17608002048",
                                body="Temperature is below set min",
                        )
		if ProximityStatus == 1:
			print "Intrusion detected"
                        client.messages.create(
                                to="+17609107488",
                                from_="+17608002048",
                                body="Intrusion Detected",
                        )
		#########################################################################
        
        ######################Uploading Data to ThingSpeak#######################

     	        import httplib, urllib
	        params = urllib.urlencode({'field1': Temperature,'field2':SecurityStatus,'field3':ProximityStatus,'field4':LCStatus,'key':'4I4Q3U288NEQ5TDV'})     # use your API key generated in the thingspeak channels for the value of 'key'
                # temp is the data you will be sending to the thingspeak channel for plotting the graph. You can add more than one channel and plot more graphs
                headers = {"Content-typZZe": "application/x-www-form-urlencoded","Accept": "text/plain"}
     	        conn = httplib.HTTPConnection("api.thingspeak.com:80")                
                try:
               	    conn.request("POST", "/update", params, headers)
               	    response = conn.getresponse()
               	    print Temperature
               	    print response.status, response.reason
               	    data = response.read()
               	    conn.close()
                except:
               	    print "connection failed"
        #########################################################################
        
	    else:
             # Timeout waiting for data, None is returned.
                 print('Received no data!')
        finally:
            # Make sure device is disconnected on exit.
            device.disconnect()
	    time.sleep(10) //Repeat this every 10 seconds.
Exemplo n.º 29
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))

    # 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('3')
        # print("Sent '3' to the device (high speed).")
        #
        # print("delay for 5 second...")
        # sleep(5)   # Delay for 1 minute (60 seconds).
        #
        # uart.write('2')
        # print("Sent '2' to the device (low speed).")
        #
        # print("delay for 5 second...")
        # sleep(5)   # Delay for 1 minute (60 seconds).
        #
        # uart.write('1')
        # print("Sent '1' to the device (pause).")
        # print("delay for 5 second...")
        # sleep(5)
        # print("done")

        print('PC should decide speed mode first.')
        print("    type '1': regular mode")
        print("    type '2': slow mode")
        print("    type '3': slow mode")
        speed = raw_input('-> ')
        print('you type ',speed)
        uart.write(speed)
        sleep(1)

        uart.write('y')

        # # open the file
        # try:
        #     F = open("/Users/cloelee/Documents/Capstone-LVAD/PathFinder/dummyFile.txt", "r+")
        # except IOError:
        #     print "Could not read file:"
        #     sys.exit()
        #
        # lines = F.readlines()

        idx = 0
        firstSweep = 0
        pathChange = 0
        initial_value = [0] * 12
        # receivedVoltage = 0

        while True:
            current_path = uart.read(timeout_sec=60)

            # file.read(2) read the first two characters and return it as a string
            # if (idx == len(lines)):
            #     idx = 0

            # Listen for data from UDP
            print("Waiting for packet...")
            data, addr = serverSocket.recvfrom(2048)
            print("Packet received!")
            txInfoJSON = json.loads(data.decode("utf-8"))
            txPowerLevel = txInfoJSON["txPowerLevel"]
            txVoltage = txInfoJSON["txVoltage"]
            txCurrent = txInfoJSON["txCurrent"]
            txPower = txInfoJSON["txPower"]

            print(" current_path : ", current_path, ord(current_path) - ASCII_A)
            if ((pathChange != 0) & (txCurrent > 0.5)):
                uart.write('x')
                uart.write(current_path)
                print("enter x step, receive V : ", txCurrent, "current path : ", ord(current_path) - ASCII_A)
                pathChange = 1
                sleep(5)
            # # idx+=1
            # label .end
            # F.truncate()
            # F.close()
            print(" current_path : ", current_path, ord(current_path) - ASCII_A)
        # 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()
Exemplo n.º 30
0
def main():
    # Clear any cached data because both bluez and CoreBluetooth have issues with
    # caching data and it going stale.

    mysock = MySocket()
    if DEBUG: print("Connecting ips socket")
    # mysock.connect()
    # mysock.mysend()

    # i = 0

    # while True:
    #     mysock.mysend(str(i))
    #     i += 1

    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()
    if DEBUG: print('Using adapter: {0}'.format(adapter.name))

    # Disconnect any currently connected UART devices.  Good for cleaning up and
    # starting from a fresh state.
    if DEBUG: print('Disconnecting any connected UART devices...')
    UART.disconnect_devices()

    # Scan for UART devices.
    if DEBUG: 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).
        if DEBUG: 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.

        while True:
            uart.write('T  ')
            # 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.
                if (received[0] is 'T'):
                    bin_array = map(bin,bytearray(received))

                    # print(bin_array)

                    if DEBUG: print("Probe 1: " + str(((int(bin_array[1], 2) << 8) + int(bin_array[2], 2)) / 100.0) + "\tProbe 2: " + str(((int(bin_array[3], 2) << 8) + int(bin_array[4], 2)) / 100.0))
                    mysock.mysend(str((int(bin_array[1], 2) << 8) + int(bin_array[2], 2)) + "," + str((int(bin_array[3], 2) << 8) + int(bin_array[4], 2)))

            else:
                # Timeout waiting for data, None is returned.
                if DEBUG: print('Received no data!')

            # sleep(1)

    finally:
        # Make sure device is disconnected on exit.
        device.disconnect()
Exemplo n.º 31
0
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()
Exemplo n.º 32
0
def main():

    # create excel spreads
    # book = xlwt.Workbook(encoding="utf-8")
    # sheet1 = book.add_sheet("Sheet 1")
    # for n in range(0,12) :
    # 	sheet1.write(2, n, n + 1)

    serverSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    serverSocket.bind(('localhost', 10000))

    # 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('PC should decide speed mode first.')
        print('you can type ' r' whenever you want to reset.')
        print("    type '1': regular mode")
        print("    type '2': slow mode")
        print("    type '3': fast mode")
        speed = raw_input('-> ')
        # print "you type ",speed

        if speed == '1' or speed == '2' or speed == '3':
            uart.write(speed)

        sleep(1)
        while speed != '1':
            if speed == '2':
                print "enter slow mode"
            elif speed == '3':
                print "enter fast mode"
            else:
                print "Error: you type wrong value"
            speed = raw_input('-> ')
            if speed == '1' or speed == '2' or speed == '3':
                uart.write(speed)

        print "enter regular mode"

        # continue sweeping
        uart.write('y')

        state = 0
        currVal = [0] * 12
        maxCurrPath = 0
        i = 3

        while true:
            # for n in range(0, 400) :
            current_path = uart.read(timeout_sec=60)
            currPath = ord(current_path) - ASCII_A

            # stdin = sys.stdin.read()
            # if ("\n" in stdin or "\r" in stdin):
            # 	idx = 0
            # 	firstSweep = 0 # flag after the first sweep
            # 	pathChange = 0 # flag when found the best path
            # 	initial_value = [0] * 12
            # 	reset = 0 # flag after the first
            # 	break

            # file.read(2) read the first two characters and return it as a string
            # if (idx == len(lines)):
            # 	idx = 0

            # Listen for data from UDP
            # print("Waiting for packet...")
            data, addr = serverSocket.recvfrom(2048)
            print("Packet received!")
            txInfoJSON = json.loads(data.decode("utf-8"))
            txPowerLevel = txInfoJSON["txPowerLevel"]
            txVoltage = txInfoJSON["txVoltage"]
            txCurrent = txInfoJSON["txCurrent"]
            txPower = txInfoJSON["txPower"]

            print "		current_path : ", currPath
            print "		txCurrent	 : ", txCurrent  # currVal #test
            print " "

            # swipe and store state
            if state == 0:
                currVal[currPath - 1] = txCurrent

                # sheet1.write(i, currPath - 1, txCurrent) #saving in excel file

                # if (currPath == 11):
                #print currVal #test
                # if currPath == 1 and currVal[currPath - 1] >= 0.53 and currVal[currPath - 1] <= 0.56 :
                # 	maxCurrPath = currPath
                #  	print "path 1 detected!"
                # 	state = 1
                # elif currPath == 2 and currVal[currPath - 1] >= 0.53 and currVal[currPath - 1] <= 0.58 :
                # 	print "path 2 detected"
                # 	maxCurrPath = currPath
                # 	state = 1
                # # elif currPath == 3 and currVal[currPath - 1] <= 0.52 and currVal[currPath - 1] >= 0.48 :
                # # 	print "path 3 detected"
                # # 	maxCurrPath = currPath
                # # 	state = 1
                # elif currPath == 4 and currVal[currPath - 1] >= 0.42 and currVal[currPath - 1] <= 0.47 :
                # 	print "path 4 detected"
                # 	maxCurrPath = currPath
                # 	state = 1
                # elif currPath == 5 and currVal[currPath - 1] >= 0.5 and currVal[currPath - 1] <= 0.56 :
                # 	print "path 5 detected"
                # 	maxCurrPath = currPath
                # 	state = 1
                # elif currPath == 6 and currVal[currPath - 1] >= 0.45 and currVal[currPath - 1] <= 0.51 :
                # 	print "path 6 detected"
                # 	maxCurrPath = currPath
                # 	state = 1
                # elif currPath == 7 and currVal[currPath - 1] >= 0.51 and currVal[currPath - 1] <= 0.56 :
                # 	print "path 7 detected"
                # 	maxCurrPath = currPath
                # 	state = 1
                if currPath == 12:
                    i = i + 1

            elif state == 1:
                uart.write('x')
                sleep(1)
                # chr(ord('a') + 5)
                uart.write(chr(ASCII_A + maxCurrPath))
                print("enter x state, max path : ", maxCurrPath)  #test
                state = 2

            # pause state
            elif state == 2:
                # print ("old current : ", currVal[currPath - 1], "new current : ", txCurrent) #test
                # if currVal[currPath - 1] > txCurrent + 0.2 :
                # 	print "value got changed!"
                # 	state = 3
                print "max path : ", maxCurrPath, "txCurrent : ", txCurrent  #test
                if maxCurrPath == 1 and txCurrent <= 0.45:
                    print "path 1 detected!"
                    state = 3
                elif maxCurrPath == 2 and txCurrent <= 0.43:
                    print "path 2 detected"
                    state = 3
                elif maxCurrPath == 3 and txCurrent >= 0.57:
                    print "path 3 detected"
                    state = 3
                elif maxCurrPath == 4 and txCurrent <= 0.4:
                    print "path 4 detected"
                    state = 3
                elif maxCurrPath == 5 and txCurrent <= 0.44:
                    print "path 5 detected"
                    state = 3
                elif maxCurrPath == 6 and txCurrent <= 0.43:
                    print "path 6 detected"
                    state = 3
                elif maxCurrPath == 7 and txCurrent <= 0.48:
                    print "path 7 detected"
                    state = 3

            elif state == 3:
                print "value got changed!"
                uart.write('y')
                sleep(2)
                print("enter y state, current : ", txCurrent,
                      "current path : ", currPath)  #test
                state = 0

            # idx += 1
            # F.truncate()
            # F.close()

        # 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:
        # book.save("path1-twopath.xls") # saving in excel
        # 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('3')
        # print("Sent '3' to the device (high speed).")
        #
        # print("delay for 5 second...")
        # sleep(5)   # Delay for 1 minute (60 seconds).
        #
        # uart.write('2')
        # print("Sent '2' to the device (low speed).")
        #
        # print("delay for 5 second...")
        # sleep(5)   # Delay for 1 minute (60 seconds).
        #
        # uart.write('1')
        # print("Sent '1' to the device (pause).")
        # print("delay for 5 second...")
        # sleep(5)
        # print("done")

        print('PC should decide speed mode first.')
        print("    type '1': regular mode")
        print("    type '2': slow mode")
        print("    type '3': slow mode")
        speed = raw_input('-> ')
        print('you type ', speed)
        uart.write(speed)
        sleep(1)

        uart.write('y')

        firstSweep = 0
        pathChange = 0
        initial_value = [0] * 12

        while True:
            F = open(
                "C:\\Users\\thaol\\capstoneLVAD\\BLE_PCtoBrd_Python\\receiver.txt",
                "r+")
            current_path = uart.read(timeout_sec=60)
            if current_path is not None:
                # Received data, print it out.
                print('Received: {0}'.format(current_path))
            else:
                # Timeout waiting for data, None is returned.
                print('Received no data!')
                break

            # file.read(2) read the first two characters and return it as a string
            receivedVoltage = F.read()

            # First time running the program
            if (current_path <= ('a' + 12) and firstSweep == 0):
                initial_value[current_path - 1 - 'a'] = receivedVoltage

                if (current_path == ('a' + 12)):
                    firstSweep = 1

            if (firstSweep == 1):
                if (receiveVoltage > initial_value[current_path - 1 - 'a'] + 2
                        or receiveVoltage <
                        initial_value[current_path - 1 - 'a'] - 2):
                    #                    initial_value[current_path - 1 - 'a'] = receiveVoltage
                    pathChange = 1
                    uart.write('x')
                    print("already found the best path")
                    sleep(5)

                    uart.write(current_path)
                    print("The best path to deliver power is: ", current_path)
                    sleep(5)

                elif (pathChange == 1):
                    uart.write('y')
                    pathChange = 0
                    firstSweep = 0

            F.truncate()
            F.close()

        # 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()
Exemplo n.º 34
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))

    # 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('Reading from MPU6050 sensor')
        reader = UARTReader(uart)
        inAir = False
        numBounce = 0
        for i in range(1000):
            received = reader.readline()
            if received is not None:
                # Received data, print it out.
                # print('{0}'.format(received))
                data = received.split(",")
                if (len(data) == 3):
                    fsr = int(data[0])
                    pitch = int(data[1])
                    roll = int(data[2])
                    # jumping logic
                    if (fsr > 200 and inAir):
                        inAir = False
                        numBounce += 1
                        print("Bounce %d" % (numBounce))
                    if (fsr < 200 and not inAir):
                        inAir = True
                    if (pitch < -20):
                        print("Right")
                    if (pitch > 20):
                        print("Left")
                    if (roll < -20):
                        print("Forward")
                    if (roll > 20):
                        print("Backward")
                    # print("FSR: %d, Pitch: %d, Roll: %d\n" %(fsr, pitch, roll))
            else:
                # Timeout waiting for data, None is returned.
                print('Received no data!')
    finally:
        # Make sure device is disconnected on exit.
        device.disconnect()
Exemplo n.º 35
0
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():
    # 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()
Exemplo n.º 37
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))

    # 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()
Exemplo n.º 38
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))
    # 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
    while not connected_to_peripheral:
        devices = scan_for_peripheral(adapter)
        for peripheral in devices:
            try:
                print('-- iteration #{} --'.format(test_iteration))
                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...")

            global total_len, done_xfer, data_service, out
            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, count, rw, spp_data_uuid)
            print("rw: ", read_val)
            msg = f"Hello from my mac.\r\n"
            data_service.write_value(msg.encode())
            # num_records = int.from_bytes(count.read_value(), byteorder='little')
            total_len = 0
            done_xfer = False
            out = b''
            def received(data):
                global total_len, done_xfer, data_service, out
                out += data
                packet_len = len(data)
                total_len += packet_len
                print(total_len, out.hex(), data.hex())
                # print('Received {0} bytes total {1}'.format(packet_len, total_len))
                if total_len >= 8:
                    print("Done with xfer")
                    data_service.stop_notify()
                    done_xfer = True

            # Turn on notification of RX characteristics using the callback above.
            print('Subscribing to spp_data characteristic changes...')
            data_service.start_notify(received)
            print("Send command to fetch data")
            start = time.time()
            rw.write_value(b'A')

            while total_len<8:
                # print("not done", done_xfer, total_len)
                time.sleep(0)
            stop = time.time()
            ts = int.from_bytes(out[:4], byteorder='little')
            overflow = int.from_bytes(out[4:], byteorder='little')
            print("ts, overflow: ", ts, overflow)
            print(f"start, stop, dt: {start:.2f}, {stop:.2f}, {stop-start:.3f}")
            mean = (start+stop)/2
            epochtime = int(mean)
            delta = int((mean-epochtime)*1000)
            ts = ts-delta
            print("epoch, ts, ovflw", epochtime, ts, overflow)
            msg_out = epochtime.to_bytes(4, byteorder='little')
            msg_out += ts.to_bytes(4, byteorder='little')
            msg_out += overflow.to_bytes(4, byteorder='little')
            data_service.write_value(msg_out)
            print('msg+out', msg_out, msg_out.hex())
            rw.write_value(b'O')
            read_val = rw.read_value()
            print("rw: ", read_val)