Exemplo n.º 1
0
def main():
    device = initBle()
    initDrone()

    # Once connected do everything else in a try/finally to make sure the device
    # is disconnected when done.
    try:
        # Wait for service discovery to complete for the UART service.  Will
        # time out after 60 seconds (specify timeout_sec parameter to override).
        print('Discovering services...')
        UART.discover(device)

        # Once service discovery is complete create an instance of the service
        # and start interacting with it.
        uart = UART(device)

        # Write a string to the TX characteristic.
        #uart.write(b'Hello world!\r\n')
        #print("Sent 'Hello world!' to the device.")

        # Now wait up to one minute to receive data from the device.
        while True:
            #print('Waiting up to 60 seconds to receive data from the device...')
            received = uart.read(timeout_sec=60)
            if received is not None:
                # Received data, print it out.
                print('Received: {0}'.format(received))
            else:
                # Timeout waiting for data, None is returned.
                print('Received no data!')
            sendCommandDrone(received)
    finally:
        # Make sure device is disconnected on exit.
        device.disconnect()
Exemplo n.º 2
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.º 3
0
def main():
    ble.clear_cached_data()
    global device
    adapter = ble.get_default_adapter()
    adapter.power_on()
    print('Using adapter: {0}'.format(adapter.name))
    print('Searching for UART device...')
    try:
        adapter.start_scan()
        device = UART.find_device()
        if device is None:
            raise RuntimeError('Failed to find UART device!')
    finally:
        adapter.stop_scan()

    print('Connecting to device...')
    device.connect()

    print('Discovering services...')    
    UART.discover(device)
    uart = UART(device)

    line = ''
    timer = time.time()
    
    while True:
        received = uart.read(timeout_sec=1)
        if received is not None:
            timer = time.time()
            line = ''.join([line, received])
        else:
            if (time.time() - timer) > 1 and line != '':
                print('{0} {1}'.format('line is: ', line))
                line = ''
def main():
    # Clear any cached data because both bluez and CoreBluetooth have issues with
    # caching data and it going stale.
    ble.clear_cached_data()

    # Get the first available BLE network adapter and make sure it's powered on.
    adapter = ble.get_default_adapter()
    adapter.power_on()
    print('Using adapter: {0}'.format(adapter.name))

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

    # Scan for UART devices.
    print('Searching for UART device...')
    try:
        adapter.start_scan()
        # Search for the first UART device found (will time out after 60 seconds
        # but you can specify an optional timeout_sec parameter to change it).
        device = UART.find_device()
        if device is None:
            raise RuntimeError('Failed to find UART device!')
    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.º 5
0
def main():
    ble.clear_cached_data()
    global device
    adapter = ble.get_default_adapter()
    adapter.power_on()
    print('Using adapter: {0}'.format(adapter.name))
    print('Searching for UART device...')
    try:
        adapter.start_scan()
        device = UART.find_device()
        if device is None:
            raise RuntimeError('Failed to find UART device!')
    finally:
        adapter.stop_scan()

    print('Connecting to device...')
    device.connect()

    print('Discovering services...')
    UART.discover(device)
    uart = UART(device)

    line = ''
    timer = time.time()

    while True:
        received = uart.read(timeout_sec=1)
        if received is not None:
            timer = time.time()
            line = ''.join([line, received])
        else:
            if (time.time() - timer) > 1 and line != '':
                print('{0} {1}'.format('line is: ', line))
                line = ''
def main():
    ble.clear_cached_data()
    adapter = ble.get_default_adapter()
    adapter.power_on()
    print('Using : {0}'.format(adapter.name))
    ble.disconnect_devices([UART_SERVICE])
    adapter.start_scan()
    time.sleep(5)

    devices = ble.find_devices(service_uuids=[UART_SERVICE])
    time.sleep(5)

    gong = None
    for device in devices:
        print('Found device: {0}, id: {1}'.format(device.name, device.id))
        if device.name == 'BLEGong':
            print 'Found gong', device.id,
            gong = device
            adapter.stop_scan()
            break

    gong.connect()
    print ('Gong Connected')

    UART.discover(gong)
    print 'Gong Discovered'

    gong_uart = UART(gong)

    adapter.power_off()
    print 'Disconnected'
Exemplo n.º 7
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.º 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
Exemplo n.º 9
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.º 10
0
    def __init__(self, device, index):
        self.device = device
        self.osc = OSC.OSCClient()
        self.osc.connect(("127.0.0.1", BASE_PORT + index))

        device.connect()
        UART.discover(self.device)

        self.uart = UART(self.device)
        self.index = index
Exemplo n.º 11
0
    def setup_uart(self, device):
        print('Discovering services...')
        #   Discover the services and create a uart object
        UART.discover(device)

        # Once service discovery is complete create an instance of the service
        # and start interacting with it.
        uart = UART(device)

        return uart
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():

    adapter = ble.get_default_adapter()
    adapter.power_on()
    print('Using adapter: {0}'.format(adapter.name))

    adapter.start_scan()

    atexit.register(adapter.stop_scan)

    device_found = False
    device = None

    print('Searching for UART devices...')
    while not device_found:
        found = set(UART.find_devices())
        for d in found:
            print('Found UART: {0} [{1}]'.format(d.name, d.id))
            if d.name == args.name:
                device = d
                device_found = True
                break
        time.sleep(1)

    if device_found:
        print('connecting to: {0} [{1}]'.format(device.name, device.id))
        device.connect()
        try:
            print('UART connecting...')
            UART.discover(device)
            uart = UART(device)
            print('Creating speech recognizer...')
            recognizer = speech.create_recognizer()
            while True:
                phrase = speech.listen_and_recognize(recognizer)
                for word in phrase.split():
                    word = word.strip()
                    word = word.lower()
                    print("word: ", word)
                    if word in blue_words:
                        uart.write(b'blue\r\n')
                    elif word in orange_words:
                        uart.write(b'orange\r\n')
                    elif word in off_words:
                        uart.write(b'off\r\n')

        finally:
            device.disconnect()
Exemplo n.º 14
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.º 15
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.º 16
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.º 17
0
def app(list_joysticks, list_bluetooth, joy, device):
    if list_joysticks:
        joystick.init()
        print('Joysticks:')
        for i in range(joystick.get_count()):
            j = joystick.Joystick(i)
            print(j.get_id(), j.get_name())

    if list_bluetooth:
        ble = Adafruit_BluefruitLE.get_provider()
        ble.initialize()
        ble.run_mainloop_with(lambda: list_bluetooth_devices(ble))

    if device is not None:
        ble = Adafruit_BluefruitLE.get_provider()
        ble.initialize()
        ble.run_mainloop_with(lambda: get_device(ble, device))
        return
        bluetooth = get_device(ble, device)
        bluetooth.connect()
        atexit.register(bluetooth.disconnect)
        UART.discover(bluetooth)
        uart = UART(bluetooth)

    if joy is not None:
        os.environ['SDL_VIDEODRIVER'] = 'dummy'
        pygame.init()
        joystick.init()
        j = joystick.Joystick(joy)
        j.init()
        print('Axes:', j.get_numaxes())
        while True:
            pygame.event.get()
            for i in range(j.get_numaxes()):
                if bluetooth and uart:
                    uart.write('{}{}\n'.format(i, j.get_axis(i)))

            print('   '.join(
                [str(j.get_axis(i)) for i in range(j.get_numaxes())]),
                  end='\r')
            time.sleep(0.05)
Exemplo n.º 18
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.º 19
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.º 20
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.º 21
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.º 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():
    # Clear any cached data because both bluez and CoreBluetooth have issues with
    # caching data and it going stale.
    #ble.clear_cached_data() #enabling this will means any BLE devices get disconnected from computer

    # 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...')
    connect_to = "yourUniqueName"
    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()

    # make sure we connect to the device we want
    if device.name == connect_to:
        print('Connecting to device...' + device.name)
        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)

            # packets are documented here https://learn.adafruit.com/bluefruit-le-connect/controller
            # color_packet_blue = b'!C\x00I\xffS'
            # color_packet_red = b'!C\xff\x02\x08\x92'
            light_value = 0
            while True:
                # build a random color
                if light_value > 10000:
                    print("BRIGHT " + str(light_value))
                    color_packet = ColorPacket((255, 0, 0))
                else:
                    print("DIM " + str(light_value))
                    color_packet = ColorPacket(
                        (randint(0, 255), randint(0, 255), 255))
                uart.write(color_packet.to_bytes())
                print("Sent color packet to the device.")
                time.sleep(0.2)
                print(
                    'Waiting up to 4 seconds to receive data from the device...'
                )
                received = uart.read(timeout_sec=4)
                if received is not None:
                    # Received data, print it out.
                    light_value = int(received)
                else:
                    # Timeout waiting for data, None is returned.
                    print('Received no data!')
        finally:
            # Make sure device is disconnected on exit.
            device.disconnect()
    else:
        print("Not connecting to first device found: " + device.name)
Exemplo n.º 24
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.º 25
0
def main():
    global run4ever
    global uart
    print('run4ever: ' + str(run4ever))
    print2Log('run4ever: ' + str(run4ever))

    # Clear any cached data because both bluez and CoreBluetooth have issues with
    # caching data and it going stale.
    ble.clear_cached_data()

    # Get the first available BLE network adapter and make sure it's powered on.
    adapter = ble.get_default_adapter()
    adapter.power_on()
    print('Using adapter: {0}'.format(adapter.name))
    print2Log('Using adapter: {0}'.format(adapter.name))

    # Start scanning with the bluetooth adapter.
    adapter.start_scan()
    # Use atexit.register to call the adapter stop_scan function before quiting.
    # This is good practice for calling cleanup code in this main function as
    # a try/finally block might not be called since this is a background thread.
    atexit.register(adapter.stop_scan)
    print('Searching for UART devices...')
    print('Press Ctrl-C to quit (will take ~30 seconds on OSX).')
    print2Log('Searching for UART devices...')
    print2Log('Press Ctrl-C to quit (will take ~30 seconds on OSX).')
    # Enter a loop and print out whenever a new UART device is found.
    known_uarts = set()
    device = 0
    c = True
    while c:
        # Call UART.find_devices to get a list of any UART devices that
        # have been found.  This call will quickly return results and does
        # not wait for devices to appear.
        found = set(UART.find_devices())
        # Check for new devices that haven't been seen yet and print out
        # their name and ID (MAC address on Linux, GUID on OSX).
        new = found - known_uarts
        for dev in new:
            print('Found UART: {0} [{1}]'.format(dev.name, dev.id))
            print2Log('Found UART: {0} [{1}]'.format(dev.name, dev.id))
            if str(dev.id) == btID:
                #print('Device found')
                print2Log('Device found')
                device = dev
                adapter.stop_scan()
                c = False

        known_uarts.update(new)
        # Sleep for a second and see if new devices have appeared.
        time.sleep(1.0)

    print('Connecting to device...')
    print2Log('Connecting to device...')
    device.connect(
    )  # Will time out after 60 seconds, specify timeout_sec parameter
    # to change the timeout.

    # Once connected do everything else in a try/finally to make sure the device
    # is disconnected when done.
    try:
        # Wait for service discovery to complete for the UART service.  Will
        # time out after 60 seconds (specify timeout_sec parameter to override).
        print('Discovering services...')
        print2Log('Discovering services...')
        UART.discover(device)

        # Once service discovery is complete create an instance of the service
        # and start interacting with it.
        uart = UART(device)

        # Write a string to the TX characteristic.
        #uart.write('Hello world!\r\n')
        #print("Sent 'Hello world!' to the device.")

        # Now wait up to one minute to receive data from the device.
        #print('Waiting up to 60 seconds to receive data from the device...')

        print("Comm loop runing")
        print2Log("Comm loop runing")
        stopChar = '@'
        messageBuffer = ""
        while run4ever:

            received = uart.read(timeout_sec=0.05)
            if received:
                # Received data, print it out.
                print('Received:{0}'.format(received))
                print2Log('Received:{0}'.format(received))
                #else:
                # Timeout waiting for data, None is returned.
                print('Received no data!')
                messageBuffer += received
                while stopChar in messageBuffer:
                    cut = messageBuffer.split(stopChar)
                    finalMessage = cut[0]
                    #print("Final Mesage:"+finalMessage)
                    #print2Log("Final Mesage:"+finalMessage)
                    processInput(finalMessage)
                    messageBuffer = messageBuffer[len(cut[0]) + 1:]

    except Exception as e:
        print(e)

    finally:
        # Make sure device is disconnected on exit.
        while run4ever:
            pass
        device.disconnect()
def 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.º 27
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():
    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))
Exemplo n.º 29
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()
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.º 31
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...')
    num_devices = 2

    # Start scanning with the bluetooth adapter.
    adapter.start_scan()
    # Use atexit.register to call the adapter stop_scan function before quiting.
    # This is good practice for calling cleanup code in this main function as
    # a try/finally block might not be called since this is a background thread.
    atexit.register(adapter.stop_scan)
    # Enter a loop and print out whenever a new UART device is found.
    adafruit_devices = []
    known_uarts = set()
    for i in range(100):
        # Call UART.find_devices to get a list of any UART devices that
        # have been found.  This call will quickly return results and does
        # not wait for devices to appear.
        found = set(UART.find_devices())
        # Check for new devices that haven't been seen yet and print out
        # their name and ID (MAC address on Linux, GUID on OSX).
        new = found - known_uarts
        for device in new:
            if device.name == DEVICE_NAME:
              adafruit_devices.append(device)
              print('Found UART: {0} [{1}]'.format(device.name, device.id))
        known_uarts.update(new)
        # Sleep for a second and see if new devices have appeared.
        time.sleep(0.5)
        if len(adafruit_devices) >= num_devices:
            break
    adapter.stop_scan()

    if len(adafruit_devices) < num_devices:
      print("could not find 2 devices")
      sys.exit(1)

    print('Connecting to device...')
    device_1 = adafruit_devices[0]
    device_1.connect()  
    atexit.register(device_1.disconnect)
    device_2 = adafruit_devices[1]
    device_2.connect()
    atexit.register(device_2.disconnect)
    com_fail = False

    try:
      # Wait for service discovery to complete for the UART service.  Will
      # time out after 60 seconds (specify timeout_sec parameter to override).
      print('Discovering services...')
      UART.discover(device_1)
      UART.discover(device_2)

      # Once service discovery is complete create an instance of the service
      # and start interacting with it.
      uart_1 = UART(device_1)
      uart_2 = UART(device_2)
    except:
      com_fail = True

    if not com_fail:
      print("calling foward_taps")
      thread.start_new_thread( foward_taps, (uart_1, uart_2, device_1, device_2, 5, ))
      time.sleep(1)
      thread.start_new_thread( foward_taps, (uart_2, uart_1, device_2, device_1, 5, ))
      while True:
        pass
Exemplo n.º 32
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.º 33
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
Exemplo n.º 34
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.º 35
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()
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.º 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()

    # Scan for UART devices.
    print('Searching for UART device...')
    try:
        adapter.start_scan()
        # Search for the first UART device found (will time out after 60 seconds
        # but you can specify an optional timeout_sec parameter to change it).

        condition = True;
        known_uarts = set()
        while condition:
            # Call UART.find_devices to get a list of any UART devices that
            # have been found.  This call will quickly return results and does
            # not wait for devices to appear.
            found = set(UART.find_devices())
            # Check for new devices that haven't been seen yet and print out
            # their name and ID (MAC address on Linux, GUID on OSX).
            new = found - known_uarts

            for device in new:
                print('Found UART: {0} [{1}]'.format(device.name, device.id))
                
            known_uarts.update(new)
            # Sleep for a second and see if new devices have appeared.
            if len(known_uarts) >= 2:
                condition = False;
                
            time.sleep(1.0)
            if len(known_uarts) >= 2:
                condition = False;
                print(condition)
                        
        print('connecting to a device finally!')
        for device in known_uarts:
            print('device in set: {0} [{1}]'.format(device.name, device.id))
            print(len(new))
            if 'C9:79:B6:8F:0B:D4' in device.id:
                asuka_device = device;



        device = asuka_device;

        if device is None:
            raise RuntimeError('Failed to find UART device!')
    finally:


        # Make sure scanning is stopped before exiting.
        adapter.stop_scan()

    print('Connecting to device...')
    device.connect()  # Will time out after 60 seconds, specify timeout_sec parameter
                      # to change the timeout.

    # Once connected do everything else in a try/finally to make sure the device
    # is disconnected when done.
    try:
        # Wait for service discovery to complete for the UART service.  Will
        # time out after 60 seconds (specify timeout_sec parameter to override).
        print('Connected to: {0} {1}'.format(device.name, device.id))
        print('Discovering services...')
        UART.discover(device)

        # Once service discovery is complete create an instance of the service
        # and start interacting with it.
        uart = UART(device)

        # Write a string to the TX characteristic.
        uart.write('on')
        print("Sent 'on' to the device.")

        # Now wait up to one minute to receive data from the device.
        print('Waiting up to 60 seconds to receive data from the device...')
        received = uart.read(timeout_sec=60)
        if received is not None:
            # Received data, print it out.
            print('Received: {0}'.format(received))
        else:
            # Timeout waiting for data, None is returned.
            print('Received no data!')
    finally:
        # Make sure device is disconnected on exit.
        device.disconnect()
def main():
        
    import os
    f = open('data.txt', 'a', os.O_NONBLOCK)
           
    
    # 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...')
        wtr = ""
        while 1:
                received = uart.read(timeout_sec=60)
                if received is not None:
                        # Received data, print it out.
                        inputString = format(received)
                        newData =  inputString.strip().split(',')

                        g = open('value.txt', 'r', os.O_NONBLOCK)
                        gLines = g.readlines()

                        if newData[0] == 'A':
                            if len(newData) == 5:
                                wrt = newData[1] + "," + newData[2] + "," + newData[3] + "," + newData[4] + ","
                                #f.write(wrt)
                                #f.flush()
                        elif newData[0] == 'B':
                            if len(newData) == 4:
                                wrt = wtr + newData[1] + "," + newData[2] + "," + newData[3] + "\n"
                                f.write(wrt)
                                f.flush()

                                gLines[0] = wrt
                                g = open('value.txt', 'w')
                                g.writelines(gLines)
                                g.close()
                        
                        print('Received: {0}'.format(received))
                else:
                        # Timeout waiting for data, None is returned.
                        print('Received no data!')
                        break
    finally:
        # Make sure device is disconnected on exit.
        device.disconnect()