Ejemplo n.º 1
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 = ''
Ejemplo n.º 2
0
def initBle():
    # Clear any cached data because both bluez and CoreBluetooth have issues with
    # caching data and it going stale.
    ble.clear_cached_data()

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

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

    # Scan for UART devices.
    print('Searching for UART device...')
    try:
        adapter.start_scan()
        # Search for the first UART device found (will time out after 60 seconds
        # but you can specify an optional timeout_sec parameter to change it).
        device = UART.find_device()
        if device is None:
            raise RuntimeError('Failed to find UART device!')
    finally:
        # Make sure scanning is stopped before exiting.
        adapter.stop_scan()

    print('Connecting to device...')
    device.connect(
    )  # Will time out after 60 seconds, specify timeout_sec parameter
    # to change the timeout.
    return device
Ejemplo 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()
Ejemplo n.º 5
0
def connectDevice():
    '''
    Connects to the Adafruit Bluefruit Module and return the object for that device
    '''
    #clear any cached data
    ble.clear_cached_data()
    #get BLE adapter
    adapter = ble.get_default_adapter()
    adapter.power_on()
    print("[ Using adapter: {0} ]".format(adapter.name))

    #disconnet any connected UART devices
    UART.disconnect_devices()

    #scan for UART devices
    print("Scanning for UART devices...")
    try:
        adapter.start_scan()
        device = UART.find_device()
        if device is None:
            raise RuntimeError("Failed to find any UART device!")
    finally:
        adapter.stop_scan()

    print("Connecting to device...")
    device.connect()
    return device
def main():
    # Clear any cached data because both bluez and CoreBluetooth have issues with
    # caching data and it going stale.
    ble.clear_cached_data()

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

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

    # Scan for UART devices.
    print('Searching for UART device...')
    try:
        adapter.start_scan()
        # Search for the first UART device found (will time out after 60 seconds
        # but you can specify an optional timeout_sec parameter to change it).
        device = UART.find_device()
        if device is None:
            raise RuntimeError('Failed to find UART device!')
        else:
            print 'uart device is gevonden'
    finally:
        # Make sure scanning is stopped before exiting.
        adapter.stop_scan()

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

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

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

        # Print out the DIS characteristics.
        print('Manufacturer: {0}'.format(dis.manufacturer))
        print('Model: {0}'.format(dis.model))
        print('Serial: {0}'.format(dis.serial))
        print('Hardware Revision: {0}'.format(dis.hw_revision))
        print('Software Revision: {0}'.format(dis.sw_revision))
        print('Firmware Revision: {0}'.format(dis.fw_revision))
        print('System ID: {0}'.format(dis.system_id))
        print('Regulatory Cert: {0}'.format(dis.regulatory_cert))
        print('PnP ID: {0}'.format(dis.pnp_id))
    finally:
        # Make sure device is disconnected on exit.
        device.disconnect()
Ejemplo n.º 7
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()
Ejemplo n.º 8
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()
Ejemplo n.º 9
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
Ejemplo n.º 10
0
    def __setup_thread(self):
        # Service and Character UUID's
        UART_SERVICE_UUID = uuid.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')
        TX_CHAR_UUID = uuid.UUID('6E400002-B5A3-F393-E0A9-E50E24DCCA9E')
        RX_CHAR_UUID = uuid.UUID('6E400003-B5A3-F393-E0A9-E50E24DCCA9E')

        SENSE_SERVICE_UUID = uuid.UUID('00006969-6969-6969-6969-696969696969')
        RSSI_CHAR_UUID = uuid.UUID('00000420-0000-1000-8000-00805f9b34fb')
        TEMP_CHAR_UUID = uuid.UUID('00000421-0000-1000-8000-00805f9b34fb')
        PRESS_CHAR_UUID = uuid.UUID('00000422-0000-1000-8000-00805f9b34fb')
        HUM_CHAR_UUID = uuid.UUID('00000423-0000-1000-8000-00805f9b34fb')
        GAS_CHAR_UUID = uuid.UUID('00000424-0000-1000-8000-00805f9b34fb')
        ALT_CHAR_UUID = uuid.UUID('00000425-0000-1000-8000-00805f9b34fb')

        self.ble.clear_cached_data()

        # get adapter and power on
        adapter = self.ble.get_default_adapter()
        adapter.power_on()

        # Disconnect currently connected devices
        self.ble.disconnect_devices()

        # Connect to UART device
        try:
            print('Scanning for devices...')
            adapter.start_scan()
            self.device = UART.find_device()
            if self.device is None:
                raise RuntimeError('Failed to find UART device!')
        finally:
            adapter.stop_scan()

        self.device.connect()
        # Discover Services and Characteristics
        print('Discovering...')
        self.device.discover([SENSE_SERVICE_UUID], [
            RSSI_CHAR_UUID, TEMP_CHAR_UUID, PRESS_CHAR_UUID, HUM_CHAR_UUID,
            GAS_CHAR_UUID, ALT_CHAR_UUID
        ])

        # Find Services and Characteristics
        print('Finding services...')
        sensors = self.device.find_service(SENSE_SERVICE_UUID)
        self.chars = {
            "rssi": sensors.find_characteristic(RSSI_CHAR_UUID),
            "temp": sensors.find_characteristic(TEMP_CHAR_UUID),
            "pressure": sensors.find_characteristic(PRESS_CHAR_UUID),
            "humidity": sensors.find_characteristic(HUM_CHAR_UUID),
            "gas": sensors.find_characteristic(GAS_CHAR_UUID),
            "alt": sensors.find_characteristic(ALT_CHAR_UUID)
        }
        file = open("rfOutput.csv", "w")
        file.write(
            'RSSI (dB),TEMP (*C),PRESSURE (hPa),HUMIDITY (%),GAS (KOhms),ALT (m)\n'
        )
        file.close()
        print('rf setup')
def main():
    # Clear any cached data because both bluez and CoreBluetooth have issues with
    # caching data and it going stale.
    ble.clear_cached_data()

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

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

    # Scan for UART devices.
    print('Searching for UART device...')
    try:
        adapter.start_scan()
        # Search for the first UART device found (will time out after 60 seconds
        # but you can specify an optional timeout_sec parameter to change it).
        device = UART.find_device()
        if device is None:
            raise RuntimeError('Failed to find UART device!')
    finally:
        # Make sure scanning is stopped before exiting.
        adapter.stop_scan()

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

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

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

        # Print out the DIS characteristics.
        print('Manufacturer: {0}'.format(dis.manufacturer))
        print('Model: {0}'.format(dis.model))
        print('Serial: {0}'.format(dis.serial))
        print('Hardware Revision: {0}'.format(dis.hw_revision))
        print('Software Revision: {0}'.format(dis.sw_revision))
        print('Firmware Revision: {0}'.format(dis.fw_revision))
        print('System ID: {0}'.format(dis.system_id))
        print('Regulatory Cert: {0}'.format(dis.regulatory_cert))
        print('PnP ID: {0}'.format(dis.pnp_id))
    finally:
        # Make sure device is disconnected on exit.
        device.disconnect()
Ejemplo n.º 12
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
Ejemplo n.º 13
0
    def __setup_thread(self):
        # Bluetooth UUIDs
        SENSE_SERVICE_UUID = uuid.UUID('00006969-6969-6969-6969-696969696969')
        RSSI_CHAR_UUID    = uuid.UUID('00000420-0000-1000-8000-00805f9b34fb')
        TEMP_CHAR_UUID    = uuid.UUID('00000421-0000-1000-8000-00805f9b34fb')
        PRESS_CHAR_UUID   = uuid.UUID('00000422-0000-1000-8000-00805f9b34fb')
        HUM_CHAR_UUID     = uuid.UUID('00000423-0000-1000-8000-00805f9b34fb')
        GAS_CHAR_UUID     = uuid.UUID('00000424-0000-1000-8000-00805f9b34fb')
        ALT_CHAR_UUID     = uuid.UUID('00000425-0000-1000-8000-00805f9b34fb')

        self.ble.clear_cached_data()

        adapter = self.ble.get_default_adapter()
        adapter.power_on()

        self.ble.disconnect_devices()

        try:
            print('Scanning for devices...')
            adapter.start_scan()
            self.device = UART.find_device()
            if self.device is None:
                 raise RuntimeError('Failed to find UART device!')

        finally:
            adapter.stop_scan()

        self.device.connect()

        # Discover Bluetooth services and characteristics
        self.device.discover([SENSE_SERVICE_UUID], [RSSI_CHAR_UUID,
                              TEMP_CHAR_UUID, PRESS_CHAR_UUID,
                              HUM_CHAR_UUID, GAS_CHAR_UUID, ALT_CHAR_UUID])

        # Find Bluetooth services and characteristics
        sensors = self.device.find_service(SENSE_SERVICE_UUID)
        self.chars = {
	    "rssi":     sensors.find_characteristic(RSSI_CHAR_UUID),
	    "temp":     sensors.find_characteristic(TEMP_CHAR_UUID),
	    "pressure": sensors.find_characteristic(PRESS_CHAR_UUID),
	    "humidity": sensors.find_characteristic(HUM_CHAR_UUID),
	    "gas":      sensors.find_characteristic(GAS_CHAR_UUID),
	    "alt":      sensors.find_characteristic(ALT_CHAR_UUID)
	}

        # Setup rfOutput.csv
        output_file = open("rfOutput.csv", "w")
        output_file.write('RSSI (dB),TEMP (*C),PRESSURE (hPa),HUMIDITY (%),GAS (KOhms),ALT (m)\n')
        output_file.close()
Ejemplo 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()
Ejemplo n.º 15
0
def main():
    ble.clear_cached_data()
    adapter = ble.get_default_adapter()
    adapter.power_on()
    print('Using adapter: {0}'.format(adapter.name))

    print('Disconnecting any connected UART devices...')
    UART.disconnect_devices()

    print('Searching for UART device...')
    try:
        adapter.start_scan()
        device = UART.find_device()
        if device is None:
            raise RuntimeError('Failed to find UART device!')
    finally:
        adapter.stop_scan()

    print("Connecting to a UART device...")
    device.connect()
    print("Connected to " + device.name + "!")

    # call method to launch gui, implement later
    # getch library for sending stuff
    # launchGUI()

    try:
        print('Discovering services...')
        DeviceInformation.discover(device)
        dis = DeviceInformation(device)

        # Print out the DIS characteristics.
        print('Manufacturer: {0}'.format(dis.manufacturer))
        print('Model: {0}'.format(dis.model))
        print('Serial: {0}'.format(dis.serial))
        print('Hardware Revision: {0}'.format(dis.hw_revision))
        print('Software Revision: {0}'.format(dis.sw_revision))
        print('Firmware Revision: {0}'.format(dis.fw_revision))
        print('System ID: {0}'.format(dis.system_id))
        print('Regulatory Cert: {0}'.format(dis.regulatory_cert))
        print('PnP ID: {0}'.format(dis.pnp_id))
    finally:
        device.disconnect()
Ejemplo n.º 16
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
Ejemplo n.º 17
0
def main():
    ble.clear_cached_data()
    adapter = ble.get_default_adapter()
    adapter.power_on()
    print('Using adapter: {0}'.format(adapter.name))
    print('Disconnecting any connected UART devices...')
    UART.disconnect_devices()
    print('Searching for UART device...')
    try:
        adapter.start_scan()
        device = UART.find_device()
        if device is None:
            raise RuntimeError('Failed to find UART device!')
    finally:
        adapter.stop_scan()

    print('Connecting to 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()
Ejemplo n.º 18
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)
Ejemplo n.º 19
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)
Ejemplo 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()
Ejemplo n.º 21
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()
Ejemplo n.º 22
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(device.name)
    print('Connecting to device...')
    # how do I connect to a specific device (out of my two?)
    device.connect(
    )  # Will time out after 60 seconds, specify timeout_sec parameter
    # to change the timeout.

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

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

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

        while True:
            # Write a string to the TX characteristic.
            message_string = create_packet()
            # we send a regular VESC packet of bytes over the BLE UART
            uart.write(message_string)
            print('write complete')
            time.sleep(4.0)

    finally:
        # Make sure device is disconnected on exit.
        device.disconnect()
Ejemplo n.º 23
0
                def run(self):
                    while not self.stoprequest.isSet():
                        self.ble = Adafruit_BluefruitLE.get_provider()
                        self.ble.initialize()

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

                        # Get the first available BLE network adapter and make sure it's powered on.
                        adapter = self.ble.get_default_adapter()
                        adapter.power_on()
                        print('Using adapter: {0}'.format(adapter.name))
                        # Disconnect any currently connected UART devices.  Good for cleaning up and
                        # starting from a fresh state.
                        print('Disconnecting any connected UART devices...')
                        UART.disconnect_devices()

                        # Scan for UART devices.
                        print('Searching for UART device...')
                        try:
                            adapter.start_scan()
                            # Search for the first UART device found (will time out after 60 seconds
                            # but you can specify an optional timeout_sec parameter to change it).
                            self.device = UART.find_device()
                            if self.device is None:
                                raise RuntimeError(
                                    'Failed to find UART device!')
                        finally:
                            # Make sure scanning is stopped before exiting.
                            adapter.stop_scan()

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

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

                            # return uart, device
                            # dis = DeviceInformation(device)
                            # Write a string to the TX characteristic.
                            # uart.write('Hello world!\r\n')
                            # print("Sent 'Hello world!' to the device.")
                            # print (dir(device))
                            def handle_line(data):

                                b = data.decode()  # change it to a string
                                if 'magnitudes' in b:
                                    print('packet start')
                                    self.get_line_lock = 1

                                # with self._recording_lock:
                                #     if self._recording:
                                #         logger.info("this is within handle line serialhandler._recording")
                                #         self._record_file.write(line + "\n")

                                if self.get_line_lock == 1:
                                    self.ble_line = self.ble_line + b

                                    # parse line based on different input data types.
                                    if self._data_type == 'a':
                                        res = parse_timeseries(self.ble_line)
                                    elif self._data_type == 'b':
                                        res = parse_bis_line(self.ble_line)
                                    else:
                                        res = parse_ble_line(self.ble_line)

                                    if res is not None:
                                        self.ble_line = ''
                                        self._queue.put(res)

                            while self.device.is_connected:
                                # Now wait up to one minute to receive data from the device.
                                newdata = uart.read(timeout_sec=1)
                                if newdata is not None:
                                    handle_line(newdata)
                                else:
                                    break

                        finally:
                            logger.info('device disconnecting')
                            try:
                                self.device.disconnect()
                                # Make sure device is disconnected on exit.
                                UART.disconnect_devices()
                            except:
                                print('p disconnecting')
Ejemplo n.º 24
0
def main():

    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)

		# 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('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)
		uart.write(speed)
		sleep(1)

		 # send "y" when have not yet found the best path
		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()
		# #
		# # fl = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
		# # fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK)
		# #
		# # lines = F.readlines()
		# 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

		while True:
			current_path = uart.read(timeout_sec = 60)
			# 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 : ", 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)

			# # First time running the program to get the initial values
			# if ((ord(current_path) <= (ASCII_A + 12)) & (firstSweep == 0)):
			# 	print("enter first loop")
			# 	initial_value[ord(current_path) - 1 - ASCII_A] = txCurrent
            #
			# 	if (ord(current_path) == (ASCII_A + 12)):
			# 		firstSweep = 1
			# 		reset = 1
			# 		print(initial_value)
            #
            #
			# if (firstSweep == 1 and reset == 0):
			# 	if (txCurrent > initial_value[ord(current_path) - 1 - ASCII_A] + 0.3):
			# 		#(receivedVoltage > initial_value[ord(current_path) - 1 - ASCII_A] - 2)):
			# 		#initial_value[current_path - 1 - 'a'] = receiveVoltage
			# 		if (pathChange != 1):
			# 			pathChange = 1;
			# 			uart.write('x')
			# 			print("enter x step, receive V : ", txCurrent, "current path : ", ord(current_path) - ASCII_A)
			# 			#sleep(5)
			# 			uart.write(current_path)
			# 			sleep(5)
            #
			# 	elif (pathChange == 1):
			# 		print("enter y step, receive V : ", txCurrent, "current path : ", ord(current_path) - ASCII_A)
			# 		uart.write('y')
			# 		pathChange = 0
			# 		firstSweep = 0
			# else:
			# 	reset = 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:
		# 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.
        
        print("Motor control test start")
        
        print("FORWARD!!!")
        # Press forward button
        uart.write('!B51')
        time.sleep(5)
        
        print("HALT!!!")
        # Release forward button
        uart.write('!B50')
        time.sleep(5)
    
        print("FALL BACK!!!")
        # Press backward button
        uart.write('!B61')
        time.sleep(5)

        print("HALT!!!")
        # Release forward button
        uart.write('!B60')
        time.sleep(5)

        print("TURN LEFT!!!")
        # Press left button
        uart.write('!B71')
        time.sleep(5)
    
        print("HALT!!!")
        # Release left button
        uart.write('!B70')
        time.sleep(5)
    
        print("TURN RIGHT!!!")
        # Press right button
        uart.write('!B81')
        time.sleep(5)
    
        print("HALT!!!")
        # Release right button
        uart.write('!B80')
        time.sleep(5)
    
        print("Motor control test concluded")

    finally:
        # Make sure device is disconnected on exit.
        device.disconnect()
        print("Device disconnected")
Ejemplo n.º 26
0
def main():

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

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

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

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

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

    # Scan for UART devices.
    print('Searching for UART device...')
    try:
        adapter.start_scan()
        # Search for the first UART device found (will time out after 60 seconds
        # but you can specify an optional timeout_sec parameter to change it).
        device = UART.find_device()
        if device is None:
            raise RuntimeError('Failed to find UART device!')
    finally:
        # Make sure scanning is stopped before exiting.
        adapter.stop_scan()

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

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

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

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

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

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

        print "enter regular mode"

        # continue sweeping
        uart.write('y')

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

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

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

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

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

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

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

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

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

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

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

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

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

        # Now wait up to one minute to receive data from the device.

        # print('Waiting up to 60 seconds to receive data from the device...')
        # received = uart.read(timeout_sec=60)
        # if received is not None:
        #     # Received data, print it out.
        #     print('Received: {0}'.format(received))
        # else:
        #     # Timeout waiting for data, None is returned.
        #     print('Received no data!')
    finally:
        # book.save("path1-twopath.xls") # saving in excel
        # Make sure device is disconnected on exit.
        device.disconnect()
def main():
    # Clear any cached data because both bluez and CoreBluetooth have issues with
    # caching data and it going stale.
    ble.clear_cached_data()

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

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

    # Scan for UART devices.
    print('Searching for UART device...')
    try:
        adapter.start_scan()
        # Search for the first UART device found (will time out after 60 seconds
        # but you can specify an optional timeout_sec parameter to change it).
        device = UART.find_device()
        if device is None:
            raise RuntimeError('Failed to find UART device!')
    finally:
        # Make sure scanning is stopped before exiting.
        adapter.stop_scan()

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

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

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

        # Write a string to the TX characteristic.
        # uart.write('3')
        # print("Sent '3' to the device (high speed).")
        #
        # print("delay for 5 second...")
        # sleep(5)   # Delay for 1 minute (60 seconds).
        #
        # uart.write('2')
        # print("Sent '2' to the device (low speed).")
        #
        # print("delay for 5 second...")
        # sleep(5)   # Delay for 1 minute (60 seconds).
        #
        # uart.write('1')
        # print("Sent '1' to the device (pause).")
        # print("delay for 5 second...")
        # sleep(5)
        # print("done")

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

        uart.write('y')

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

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

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

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

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

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

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

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

            F.truncate()
            F.close()

        # Now wait up to one minute to receive data from the device.

        # print('Waiting up to 60 seconds to receive data from the device...')
        # received = uart.read(timeout_sec=60)
        # if received is not None:
        #     # Received data, print it out.
        #     print('Received: {0}'.format(received))
        # else:
        #     # Timeout waiting for data, None is returned.
        #     print('Received no data!')
    finally:
        # Make sure device is disconnected on exit.
        device.disconnect()
Ejemplo n.º 28
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()
Ejemplo n.º 30
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)
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()
Ejemplo n.º 32
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()
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.
Ejemplo n.º 34
0
def main():
    # Clear any cached data because both bluez and CoreBluetooth have issues with
    # caching data and it going stale.
    ble.clear_cached_data()

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

    # Disconnect any currently connected UART devices.  Good for cleaning up and
    # starting from a fresh state.
    #print('Disconnecting any connected UART devices...')
    ble.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...')

        try:
            device.discover([SENSE_SERVICE_UUID], [
                RSSI_CHAR_UUID, TEMP_CHAR_UUID, PRESS_CHAR_UUID, HUM_CHAR_UUID,
                GAS_CHAR_UUID, ALT_CHAR_UUID
            ])
        finally:
            #print('Discovery finished...')
            pass
        # Once service discovery is complete create an instance of the service
        # and start interacting with it.

# Open a file to write to
        file = open("rfOutput.csv", "w")

        try:
            sensors = device.find_service(SENSE_SERVICE_UUID)
            rssi_char = sensors.find_characteristic(RSSI_CHAR_UUID)
            temp_char = sensors.find_characteristic(TEMP_CHAR_UUID)
            pressure_char = sensors.find_characteristic(PRESS_CHAR_UUID)
            humidity_char = sensors.find_characteristic(HUM_CHAR_UUID)
            gas_char = sensors.find_characteristic(GAS_CHAR_UUID)
            alt_char = sensors.find_characteristic(ALT_CHAR_UUID)

        finally:
            #print('Sensors discovered succesfully')
            pass

        def unwrap(val):
            if isinstance(val, (dbus.Array, list, tuple)):
                hex_ans = ''
                #return [unwrap(x) for x in val]
                for x in val:
                    hex_ans = hex_ans + unwrap(x)
                return int(hex_ans, 16)
            if isinstance(val, dbus.Byte):
                hex_string = str(bytes(hex(val)))
                return hex_string.replace('0x', '')
            print('Error: Recieved different type!')
            return val

        timeout = 10  # 10 seconds

        timeout_start = time.time()
        print('RF Experiment has started')
        #print('RSSI:  TEMP:  PRESSURE:  HUMIDITY:  GAS:  ALT: ')
        file.write(
            'RSSI (dB),TEMP (*C),PRESSURE (hPa),HUMIDITY (%),GAS (KOhms),ALT (m)\n'
        )
        while time.time() < timeout_start + timeout:

            rssi = str(unwrap(rssi_char.read_value()))
            temp = str(float(unwrap(temp_char.read_value())) / 100)
            pressure = str(float(unwrap(pressure_char.read_value())))
            humidity = str(float(unwrap(humidity_char.read_value())) / 100)
            gas = str(float(unwrap(gas_char.read_value())) / 100)
            alt = str(float(unwrap(alt_char.read_value())) / 100)

            #print(' ' + rssi + '    ' + temp + '   ' + pressure + '    ' + humidity + '    ' + gas + '    ' + alt)
            file.write(rssi + ',' + temp + ',' + pressure + ',' + humidity +
                       ',' + gas + ',' + alt + '\n')
    finally:
        print('Disconnecting...')
        # Make sure device is disconnected on exit.
        device.disconnect()
        file.close()
Ejemplo 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()
Ejemplo n.º 36
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()
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()
Ejemplo 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).
        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.

    #signal.pause()
    # 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...')
        print(datetime.datetime.now())

        start_ms = int(round(time.time() * 1000))
        buffer = ''
        suffix = '\r\n'
        finished = False

        while finished != True:
            # read data from BLE device
            received = uart.read(timeout_sec=30)

            # if nothing has been received after timeout then close the session
            if (received == None):
                finished = True
            else:
                buffer += received.decode('UTF-8')
                if (buffer.endswith(suffix)):
                    now_ms = str(int(round(time.time() * 1000)))
                    line = now_ms + ',' + buffer
                    myfile.write(line)
                    myfile.flush()
                    buffer = ''

    finally:
        # Make sure device is disconnected on exit.
        device.disconnect()
        myfile.close()