예제 #1
0
def main():
    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = MyManagerListener()
        manager.add_listener(manager_listener)

        while True:
            # Synchronous discovery of Bluetooth devices.
            print('Scanning Bluetooth devices...\n')
            manager.discover(False, SCANNING_TIME_s)

            for device in manager.get_nodes():

                # Connecting to the device.
                node_listener = MyNodeListener()
                device.add_listener(node_listener)
                print('\nConnecting to %s...' % (device.get_name()))
                device.connect()

                features = device.get_features()

                for feature in features:
                    feature_listener = MyFeatureListener()
                    feature.add_listener(feature_listener)
                    device.enable_notifications(feature)

    except BTLEException as e:
        print(e)
        # Exiting.
        print('Exiting...\n')
        sys.exit(0)
예제 #2
0
def main(argv):

    # Printing intro.
    #print_intro()
    MAC = 'c0:86:4b:31:28:48'
    #MAC2 = 'c0:86:4e:30:49:4d'
    #n = 0

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = MyManagerListener()
        manager.add_listener(manager_listener)

        # Synchronous discovery of Bluetooth devices.
        print('Scanning Bluetooth devices...\n')
        manager.discover(SCANNING_TIME_s)

        # Getting discovered devices.
        discovered_devices = manager.get_nodes()

        # Selecting devices to connect.
        selected_devices = []
        for device in discovered_devices:
            if device.get_tag() == MAC:
                print('Device were found')
                selected_devices.append(device)
                break
                '''n+=1
            if device.get_tag() == MAC2:
                print('Device 2 were found')
                selected_devices.append(device)
                n+=1
            if n == 2:
                break'''

        DeviceThread(selected_devices[0]).start()
        #DeviceThread2(selected_devices[1]).start()

    except KeyboardInterrupt:
        try:
            # Exiting.
            print('\nExiting...\n')
            #csv_update2(name)
            sys.exit(0)
        except SystemExit:
            os._exit(0)
예제 #3
0
 def connect_to_device(self):
     manager = Manager.instance()
     manager_listener = MyManagerListener()
     manager.add_listener(manager_listener)
     print('Scanning Bluetooth devices...\n')
     # Synchronous
     manager.discover(SCANNING_TIME_s)
     discovered_devices = manager.get_nodes()
     if not discovered_devices:
         print('No Bluetooth devices found. Exiting...\n')
         sys.exit(0)
     self._device = self.find_device(discovered_devices)
     if self._device == ERROR:
         print('Device not found.\n')
         sys.exit(0)
     print('Connecting to %s...' % (self._device.get_name()))
     if not self._device.connect():
         print('Connection failed.\n')
         sys.exit(0)
def main(argv):

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = ble_interfaces.MyManagerListener()
        manager.add_listener(manager_listener)

        while True:
            # Synchronous discovery of Bluetooth devices.
            print('\nScanning Bluetooth devices...\n')
            manager.discover(SCANNING_TIME_s)

            # Getting discovered devices.
            discovered_devices = manager.get_nodes()

            # Listing discovered devices.
            if not discovered_devices:
                print('No Bluetooth devices found. Exiting...\n')
                sys.exit(0)
            print('Available Bluetooth devices:')
            i = 1
            for device in discovered_devices:
                print('%d) %s: [%s]' %
                      (i, device.get_name(), device.get_tag()))
                i += 1

            # Exiting.
            manager.remove_listener(manager_listener)
            print('\nExiting...\n')
            sys.exit(0)

    except KeyboardInterrupt:
        try:
            # Exiting.
            print('\nExiting...\n')
            sys.exit(0)
        except SystemExit:
            os._exit(0)
예제 #5
0
def main(argv):

    # Printing intro.
    print_intro()

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = MyManagerListener()
        manager.add_listener(manager_listener)

        while True:
            discovered_devices_once = []
            no_connect = True
            no_feature_select = True
            feature_selected = []

            # Asynchronous discovery of Bluetooth devices.
            print('[+] Scanning Bluetooth devices...\n')
            manager.start_discovery()
            timeout = time.time() + SCANNING_TIME_s
            while no_connect:
                time.sleep(0.01)

                # Getting discovered devices.
                discovered_devices = manager.get_nodes()

                i = 1
                for device in discovered_devices:
                    if device.get_tag() not in discovered_devices_once:
                        print('[+] %s: [%s]' %
                              (device.get_name(), device.get_tag()))
                        discovered_devices_once.append(device.get_tag())
                        # Autoconnection management
                        if device.get_tag() == MAC_AUTO_CONNEXION:
                            print('[+] Device MAC address match')
                            no_connect = False
                            choice = i
                        i += 1
                # Timeout management
                if time.time() > timeout:
                    break
            manager.stop_discovery()

            # Selecting a device.
            while no_connect:
                print('[+] Available Bluetooth devices:')
                i = 1
                for device in discovered_devices:
                    print('[+] %d) %s: [%s]' %
                          (i, device.get_name(), device.get_tag()))
                    i += 1
                choice = int(
                    input("\nSelect a device to connect to (\'0\' to quit): "))
                if choice >= 0 and choice <= len(discovered_devices):
                    no_connect = False
            if choice == 0:
                # Exiting.
                manager.remove_listener(manager_listener)
                print('[+] Exiting...\n')
                sys.exit(0)
            device = discovered_devices[choice - 1]
            node_listener = MyNodeListener()
            device.add_listener(node_listener)

            # Connecting to the device.
            print('[+] Connecting to %s...' % (device.get_name()))
            if not device.connect():
                print('[+] Connection failed.\n')
                continue

            while True:
                # Getting features.
                features = device.get_features()
                print('\n[+] Features:')
                i = 1
                for feature in features:
                    if feature.get_name() in FEATURE_AUTO_START:
                        print('[+] Feature matching - %s' %
                              (feature.get_name()))
                        choice = i
                        feature_selected.append(i)
                        no_feature_select = False

                    if isinstance(feature, FeatureAudioADPCM):
                        audio_feature = feature
                        print('[+] %d,%d) %s' % (i, i + 1, "Audio & Sync"))
                        i += 1
                    elif isinstance(feature, FeatureAudioADPCMSync):
                        audio_sync_feature = feature
                    else:
                        print('[+] %d) %s' % (i, feature.get_name()))
                        i += 1

                # Selecting a feature.
                while no_feature_select:
                    choice = int(
                        input('\nSelect a feature '
                              '(\'0\' to disconnect): '))
                    if choice >= 0 and choice <= len(features):
                        feature_selected.append(choice)
                        no_feature_select = False

                if len(feature_selected) == 0:
                    # Disconnecting from the device.
                    print('\n[+] Disconnecting from %s...' %
                          (device.get_name()))
                    if not device.disconnect():
                        print('[+] Disconnection failed.\n')
                        continue
                    device.remove_listener(node_listener)
                    # Resetting discovery.
                    manager.reset_discovery()
                    # Going back to the list of devices.
                    break

                for feature_id in feature_selected:
                    feature = features[feature_id - 1]
                    # Enabling notifications.
                    feature_listener = MyFeatureListener()
                    feature.add_listener(feature_listener)
                    device.enable_notifications(feature)

                # Handling audio case (both audio features have to be enabled).
                if isinstance(feature, FeatureAudioADPCM):
                    audio_sync_feature_listener = MyFeatureListener()
                    audio_sync_feature.add_listener(
                        audio_sync_feature_listener)
                    device.enable_notifications(audio_sync_feature)
                elif isinstance(feature, FeatureAudioADPCMSync):
                    audio_feature_listener = MyFeatureListener()
                    audio_feature.add_listener(audio_feature_listener)
                    device.enable_notifications(audio_feature)

                # Getting notifications.
                while True:
                    device.wait_for_notifications(10)
                    #TODO break management

                # TODO : clean disabling (array of feature/feature_listener)
                # Disabling notifications.
                device.disable_notifications(feature)
                feature.remove_listener(feature_listener)

                # Handling audio case (both audio features have to be disabled).
                if isinstance(feature, FeatureAudioADPCM):
                    device.disable_notifications(audio_sync_feature)
                    audio_sync_feature.remove_listener(
                        audio_sync_feature_listener)
                elif isinstance(feature, FeatureAudioADPCMSync):
                    device.disable_notifications(audio_feature)
                    audio_feature.remove_listener(audio_feature_listener)

    except KeyboardInterrupt:
        try:
            # Exiting.
            print('\n[+] Exiting...\n')
            sys.exit(0)
        except SystemExit:
            os._exit(0)
예제 #6
0
def main(protocol):
    try:
        print("\nPython %s\n" % sys.version)
        print("IoT Hub Client for Python")

        hub_manager = HubManager(protocol)

        print("Starting the IoT Hub Python sample using protocol %s..." %
              hub_manager.client_protocol)
        print(
            "The sample is now waiting for messages and will indefinitely.  Press Ctrl-C to exit. "
        )

        try:
            # Creating Bluetooth Manager.
            manager = Manager.instance()
            manager_listener = MyManagerListener()
            manager.add_listener(manager_listener)

            while True:
                # Synchronous discovery of Bluetooth devices.
                print('Scanning Bluetooth devices...\n')
                manager.discover(False, SCANNING_TIME_s)

                # Getting discovered devices.
                devices = manager.get_nodes()

                # Listing discovered devices.
                if not devices:
                    print('\nNo Bluetooth devices found.')
                    continue  # Scan Again!
                print('\nAvailable Bluetooth devices:')
                i = 1
                device_found = False
                for device in devices:
                    device_name = device.get_name()
                    print('%d) %s: [%s]' %
                          (i, device.get_name(), device.get_tag()))
                    if device_name is "IOT_DEVICE":
                        device_found = True
                    i += 1

                # Selecting a device.
                if device_found is True:
                    # Connecting to the device.
                    node_listener = MyNodeListener()
                    device.add_listener(node_listener)
                    print('\nConnecting to %s...' % (device.get_name()))
                    device.connect()
                    print('Connection done.')
                else:
                    # Exiting.
                    manager.remove_listener(manager_listener)
                    print('Exiting...\n')
                    sys.exit(0)

                while True:
                    # Getting features.
                    print('\nFeatures:')
                    i = 1
                    features = device.get_features()

                    audioFeature = None
                    audioSyncFeature = None

                    for feature in features:
                        if not feature.get_name(
                        ) == FeatureAudioADPCMSync.FEATURE_NAME:
                            if feature.get_name(
                            ) == FeatureAudioADPCM.FEATURE_NAME:
                                audioFeature = feature
                                print('%d,%d) %s' % (i, i + 1, "Audio & Sync"))
                            else:
                                print('%d) %s' % (i, feature.get_name()))
                            i += 1
                        else:
                            audioSyncFeature = feature
                    # # Selecting a feature.
                    # while True:
                    #     choice = int(input('\nSelect a feature '
                    #                     '(\'0\' to disconnect): '))
                    #     if choice >= 0 and choice <= len(features):
                    #         break
                    # if choice == 0:
                    #     # Disconnecting from the device.
                    #     print('\nDisconnecting from %s...' % (device.get_name()))
                    #     device.disconnect()
                    #     print('Disconnection done.')
                    #     device.remove_listener(node_listener)
                    #     # Reset discovery.
                    #     manager.reset_discovery()
                    #     # Going back to the list of devices.
                    #     break
                    choice = 7
                    feature = features[choice - 1]

                    # Enabling notifications.
                    feature_listener = MyFeatureListener()
                    feature.add_listener(feature_listener)
                    device.enable_notifications(feature)

                    if feature.get_name() == FeatureAudioADPCM.FEATURE_NAME:
                        audioSyncFeature_listener = MyFeatureListener()
                        audioSyncFeature.add_listener(
                            audioSyncFeature_listener)
                        device.enable_notifications(audioSyncFeature)
                    elif feature.get_name(
                    ) == FeatureAudioADPCMSync.FEATURE_NAME:
                        audioFeature_listener = MyFeatureListener()
                        audioFeature.add_listener(audioFeature_listener)
                        device.enable_notifications(audioFeature)

                    # Getting notifications.
                    n = 0
                    while n < NOTIFICATIONS:
                        if device.wait_for_notifications(0.05):
                            n += 1

                    # Disabling notifications.
                    device.disable_notifications(feature)
                    feature.remove_listener(feature_listener)

                    if feature.get_name() == FeatureAudioADPCM.FEATURE_NAME:
                        device.disable_notifications(audioSyncFeature)
                        audioSyncFeature.remove_listener(
                            audioSyncFeature_listener)
                    elif feature.get_name(
                    ) == FeatureAudioADPCMSync.FEATURE_NAME:
                        device.disable_notifications(audioFeature)
                        audioFeature.remove_listener(audioFeature_listener)

        except BTLEException as e:
            print(e)
            # Exiting.
            print('Exiting...\n')
            sys.exit(0)
        except KeyboardInterrupt:
            try:
                # Exiting.
                print('\nExiting...\n')
                sys.exit(0)
            except SystemExit:
                os._exit(0)

        while True:
            time.sleep(1)

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubModuleClient sample stopped")
예제 #7
0
def main(argv):

    global nIdx

    ###Audio Stream#####################################################
    global stream
    ###Audio Stream#####################################################
    ###Save Audio File##################################################
    global audioFile
    global saveAudioFlag
    ###Save Audio File##################################################

    global audioFeature
    global audioSyncFeature

    # Printing intro.
    print_intro()

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = MyManagerListener()
        manager.add_listener(manager_listener)

        while True:
            # Synchronous discovery of Bluetooth devices.
            print('Scanning Bluetooth devices...\n')
            manager.discover(False, SCANNING_TIME_s)

            # Getting discovered devices.
            devices = manager.get_nodes()

            # Listing discovered devices.
            if not devices:
                print('\nNo Bluetooth devices found.')
                sys.exit(0)
            print('\nAvailable Bluetooth devices:')
            i = 1
            for device in devices:
                print('%d) %s: [%s]' %
                      (i, device.get_name(), device.get_tag()))
                i += 1

            # Selecting a device.
            while True:
                choice = int(input("\nSelect a device (\'0\' to quit): "))
                if choice >= 0 and choice <= len(devices):
                    break
            if choice == 0:
                # Exiting.
                manager.remove_listener(manager_listener)
                print()
                sys.exit(0)
            device = devices[choice - 1]

            hasAudioFeats = [False, False]

            i = 1
            features = device.get_features()
            for feature in features:
                if feature.get_name() == FeatureAudioADPCM.FEATURE_NAME:
                    audioFeature = feature
                    hasAudioFeats[0] = True
                elif feature.get_name() == FeatureAudioADPCMSync.FEATURE_NAME:
                    audioSyncFeature = feature
                    hasAudioFeats[1] = True
                i += 1

            if all(hasAudioFeats):
                # Connecting to the device.
                node_listener = MyNodeListener()
                device.add_listener(node_listener)
                print('\nConnecting to %s...' % (device.get_name()))
                device.connect()
                print('Connection done.')

                while True:

                    saveAudioFlag = raw_input(
                        '\nDo you want to save the audio stream?'
                        '\'y\' - Yes, \'n\' - No (\'0\' to quit): ')

                    if saveAudioFlag == 'y' or saveAudioFlag == 'Y' or saveAudioFlag == 'n' or saveAudioFlag == 'N':
                        if saveAudioFlag == 'y' or saveAudioFlag == 'Y':
                            ts = time.time()
                            st = datetime.datetime.fromtimestamp(ts).strftime(
                                '%Y-%m-%d_%H-%M-%S')
                            if not os.path.exists(AUDIO_DUMPS_PATH):
                                os.makedirs(AUDIO_DUMPS_PATH)
                            fileName = AUDIO_DUMPS_PATH + st + AUDIO_DUMP_SUFFIX
                            audioFile = open(fileName, "w+")

                        nOfSeconds = int(
                            input('\nHow many seconds do you want to stream?'
                                  ' Value must be > 0 (\'0\' to quit): '))

                        nOfNotifications = nOfSeconds * NPS

                        if nOfSeconds > 0:
                            print("Streaming Started")

                            ###Audio Stream#####################################
                            stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK,
                                                   alsaaudio.PCM_NONBLOCK,
                                                   'default')
                            stream.setformat(alsaaudio.PCM_FORMAT_S16_LE)
                            stream.setchannels(CHANNELS)
                            stream.setrate(SAMPLING_FREQ)
                            ###Audio Stream#####################################

                            #Enabling Notifications
                            audioFeature_listener = MyFeatureListener()
                            audioFeature.add_listener(audioFeature_listener)
                            device.enable_notifications(audioFeature)
                            audioSyncFeature_listener = MyFeatureListenerSync()
                            audioSyncFeature.add_listener(
                                audioSyncFeature_listener)
                            device.enable_notifications(audioSyncFeature)

                            nIdx = 0
                            while nIdx < nOfNotifications:
                                device.wait_for_notifications(0.05)

                            print("End of Streaming")
                            # Disabling notifications.
                            device.disable_notifications(audioFeature)
                            audioFeature.remove_listener(audioFeature_listener)
                            device.disable_notifications(audioSyncFeature)
                            audioSyncFeature.remove_listener(
                                audioSyncFeature_listener)
                            ###Save Audio File##################################
                            if saveAudioFlag == 'y' or saveAudioFlag == 'Y':
                                audioFile.close()
                            ###Save Audio File##################################
                            ###Audio Stream#####################################
                            stream.close()
                            ###Audio Stream#####################################
                        elif nOfSeconds == 0:
                            # Disabling notifications.
                            if audioFeature.is_notifying():
                                device.disable_notifications(audioFeature)
                                audioFeature.remove_listener(
                                    audioFeature_listener)
                            if audioSyncFeature.is_notifying():
                                device.disable_notifications(audioSyncFeature)
                                audioSyncFeature.remove_listener(
                                    audioSyncFeature_listener)
                            ###Save Audio File##################################
                            if saveAudioFlag == 'y' or saveAudioFlag == 'Y':
                                audioFile.close()
                            ###Save Audio File##################################
                            # Disconnecting from the device.
                            print('\nDisconnecting from %s...' %
                                  (device.get_name()))
                            device.disconnect()
                            print('Disconnection done.')
                            device.remove_listener(node_listener)
                            # Reset discovery.
                            manager.reset_discovery()
                            # Going back to the list of devices.
                            break
                    elif saveAudioFlag == '0':
                        # Disconnecting from the device.
                        print('\nDisconnecting from %s...' %
                              (device.get_name()))
                        device.disconnect()
                        print('Disconnection done.')
                        device.remove_listener(node_listener)
                        # Reset discovery.
                        manager.reset_discovery()
                        # Going back to the list of devices.
                        break
            else:
                print("No Audio Features are Exposed from your BLE Node!")
                while True:
                    restartDiscovery = int(
                        input(
                            '\nPress \'1\' to restart scanning for BLE devices '
                            '(\'0\' to quit): '))
                    if restartDiscovery == 1:
                        # Reset discovery.
                        manager.reset_discovery()
                        break
                    elif restartDiscovery == 0:
                        # Exiting.
                        print('\nExiting...\n')
                        sys.exit(0)

    except BTLEException as e:
        print(e)
        # Exiting.
        print('Exiting...\n')
        sys.exit(0)
    except KeyboardInterrupt:
        try:
            # Exiting.
            print('\nExiting...\n')
            sys.exit(0)
        except SystemExit:
            os._exit(0)
def main(argv):

    # Global variables.
    global endpoint, root_ca_path
    global iot_device_1_client, iot_device_2_client
    global iot_device_1, iot_device_2
    global iot_device_1_feature_switch, iot_device_2_feature_switch
    global iot_device_1_status, iot_device_2_status
    global iot_device_1_act_flag, iot_device_2_act_flag

    # Initial state.
    iot_device_1_status = SwitchStatus.OFF
    iot_device_2_status = SwitchStatus.OFF
    iot_device_1_act_flag = False
    iot_device_2_act_flag = False

    # Configure logging.
    configure_logging()

    # Printing intro.
    print_intro()

    # Reading input.
    read_input(argv)

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = MyManagerListener()
        manager.add_listener(manager_listener)

        # Synchronous discovery of Bluetooth devices.
        print('Scanning Bluetooth devices...\n')
        manager.discover(SCANNING_TIME_s)

        # Getting discovered devices.
        discovered_devices = manager.get_nodes()
        if not discovered_devices:
            print('\nNo Bluetooth devices found. Exiting...\n')
            sys.exit(0)

        # Checking discovered devices.
        devices = []
        for discovered in discovered_devices:
            if discovered.get_tag() == IOT_DEVICE_1_MAC:
                iot_device_1 = discovered
                devices.append(iot_device_1)
            elif discovered.get_tag() == IOT_DEVICE_2_MAC:
                iot_device_2 = discovered
                devices.append(iot_device_2)
            if len(devices) == 2:
                break
        if len(devices) < 2:
            print('\nBluetooth setup incomplete. Exiting...\n')
            sys.exit(0)

        # Connecting to the devices.
        for device in devices:
            device.add_listener(MyNodeListener())
            print('Connecting to %s...' % (device.get_name()))
            device.connect()
            print('Connection done.')

        # Getting features.
        print('\nGetting features...')
        iot_device_1_feature_switch = \
            iot_device_1.get_feature(feature_switch.FeatureSwitch)
        iot_device_2_feature_switch = \
            iot_device_2.get_feature(feature_switch.FeatureSwitch)

        # Resetting switches.
        print('Resetting switches...')
        iot_device_1_feature_switch.write_switch_status(
            iot_device_1_status.value)
        iot_device_2_feature_switch.write_switch_status(
            iot_device_2_status.value)

        # Bluetooth setup complete.
        print('\nBluetooth setup complete.')

        # Initializing Edge Computing.
        print('\nInitializing Edge Computing...\n')
        edge = AWSGreengrass(endpoint, root_ca_path)
        edge.add_listener(MyAWSGreengrassListener())

        # Getting AWS MQTT clients.
        iot_device_1_client = edge.get_client(IOT_DEVICE_1_NAME, \
            IOT_DEVICE_1_CERTIF_PATH, IOT_DEVICE_1_PRIV_K_PATH)
        iot_device_2_client = edge.get_client(IOT_DEVICE_2_NAME, \
            IOT_DEVICE_2_CERTIF_PATH, IOT_DEVICE_2_PRIV_K_PATH)

        # Connecting clients to the cloud.
        iot_device_1_client.add_listener(MyClientListener())
        iot_device_2_client.add_listener(MyClientListener())
        iot_device_1_client.connect()
        iot_device_2_client.connect()

        # Setting subscriptions.
        iot_device_1_client.subscribe(MQTT_IOT_DEVICE_SWITCH_ACT_TOPIC, \
            MQTT_QOS_1, iot_device_1_callback)
        iot_device_2_client.subscribe(MQTT_IOT_DEVICE_SWITCH_ACT_TOPIC, \
            MQTT_QOS_1, iot_device_2_callback)

        # Resetting shadow states.
        state_json_str = '{"state":{"desired":{"switch_status":' \
            + str(iot_device_1_status.value) + '}}}'
        iot_device_1_client.update_shadow_state(state_json_str,
                                                custom_shadow_callback_update,
                                                SHADOW_CALLBACK_TIMEOUT_s)
        state_json_str = '{"state":{"desired":{"switch_status":' \
            + str(iot_device_2_status.value) + '}}}'
        iot_device_2_client.update_shadow_state(state_json_str,
                                                custom_shadow_callback_update,
                                                SHADOW_CALLBACK_TIMEOUT_s)

        # Edge Computing Initialized.
        print('\nEdge Computing Initialized.')

        # Handling sensing of devices.
        iot_device_1_feature_switch.add_listener(
            MyFeatureSwitchListener(iot_device_1_client,
                                    MQTT_IOT_DEVICE_SWITCH_SENSE_TOPIC))
        iot_device_2_feature_switch.add_listener(
            MyFeatureSwitchListener(iot_device_2_client,
                                    MQTT_IOT_DEVICE_SWITCH_SENSE_TOPIC))

        # Enabling notifications.
        print('\nEnabling Bluetooth notifications...')
        iot_device_1.enable_notifications(iot_device_1_feature_switch)
        iot_device_2.enable_notifications(iot_device_2_feature_switch)

        # Demo running.
        print('\nDemo running (\"CTRL+C\" to quit)...\n')

        # Infinite loop.
        while True:

            # Getting notifications.
            if iot_device_1.wait_for_notifications(0.05) \
                or iot_device_2.wait_for_notifications(0.05):
                continue

            # Handling actuation of devices.
            if iot_device_1_act_flag:
                iot_device_act(iot_device_1, iot_device_1_feature_switch,
                               iot_device_1_status, iot_device_1_client)
                iot_device_1_act_flag = False
            elif iot_device_2_act_flag:
                iot_device_act(iot_device_2, iot_device_2_feature_switch,
                               iot_device_2_status, iot_device_2_client)
                iot_device_2_act_flag = False

    except (BTLEException, EdgeSTInvalidOperationException) as e:
        print(e)
        print('Exiting...\n')
        sys.exit(0)
    except KeyboardInterrupt:
        try:
            # Exiting.
            print('\nExiting...\n')
            sys.exit(0)
        except SystemExit:
            os._exit(0)
예제 #9
0
def main(argv):

    # Printing intro.
    print_intro()

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = MyManagerListener()
        manager.add_listener(manager_listener)

        while True:
            # Synchronous discovery of Bluetooth devices.
            print('Scanning Bluetooth devices...\n')
            manager.discover(SCANNING_TIME_s)

            # Alternative 1: Asynchronous discovery of Bluetooth devices.
            #manager.discover(SCANNING_TIME_s, True)

            # Alternative 2: Asynchronous discovery of Bluetooth devices.
            #manager.start_discovery()
            #time.sleep(SCANNING_TIME_s)
            #manager.stop_discovery()

            # Getting discovered devices.
            discovered_devices = manager.get_nodes()

            # Listing discovered devices.
            if not discovered_devices:
                print('No Bluetooth devices found. Exiting...\n')
                sys.exit(0)
            print('Available Bluetooth devices:')
            i = 1
            for device in discovered_devices:
                print('%d) %s: [%s]' %
                      (i, device.get_name(), device.get_tag()))
                i += 1

            # Selecting a device.
            while True:
                choice = int(
                    input("\nSelect a device to connect to (\'0\' to quit): "))
                if choice >= 0 and choice <= len(discovered_devices):
                    break
            if choice == 0:
                # Exiting.
                manager.remove_listener(manager_listener)
                print('Exiting...\n')
                sys.exit(0)
            device = discovered_devices[choice - 1]
            node_listener = MyNodeListener()
            device.add_listener(node_listener)

            # Connecting to the device.
            print('Connecting to %s...' % (device.get_name()))
            if not device.connect():
                print('Connection failed.\n')
                continue

            while True:
                # Getting features.
                features = device.get_features()
                print('\nFeatures:')
                i = 1
                for feature in features:
                    if isinstance(feature, FeatureAudioADPCM):
                        audio_feature = feature
                        print('%d,%d) %s' % (i, i + 1, "Audio & Sync"))
                        i += 1
                    elif isinstance(feature, FeatureAudioADPCMSync):
                        audio_sync_feature = feature
                    else:
                        print('%d) %s' % (i, feature.get_name()))
                        i += 1

                # Selecting a feature.
                while True:
                    choice = int(
                        input('\nSelect a feature '
                              '(\'0\' to disconnect): '))
                    if choice >= 0 and choice <= len(features):
                        break
                if choice == 0:
                    # Disconnecting from the device.
                    print('\nDisconnecting from %s...' % (device.get_name()))
                    if not device.disconnect():
                        print('Disconnection failed.\n')
                        continue
                    device.remove_listener(node_listener)
                    # Resetting discovery.
                    manager.reset_discovery()
                    # Going back to the list of devices.
                    break
                feature = features[choice - 1]

                # Enabling notifications.
                feature_listener = MyFeatureListener()
                feature.add_listener(feature_listener)
                device.enable_notifications(feature)

                # Handling audio case (both audio features have to be enabled).
                if isinstance(feature, FeatureAudioADPCM):
                    audio_sync_feature_listener = MyFeatureListener()
                    audio_sync_feature.add_listener(
                        audio_sync_feature_listener)
                    device.enable_notifications(audio_sync_feature)
                elif isinstance(feature, FeatureAudioADPCMSync):
                    audio_feature_listener = MyFeatureListener()
                    audio_feature.add_listener(audio_feature_listener)
                    device.enable_notifications(audio_feature)

                # Getting notifications.
                notifications = 0
                while notifications < NOTIFICATIONS:
                    if device.wait_for_notifications(0.05):
                        notifications += 1

                # Disabling notifications.
                device.disable_notifications(feature)
                feature.remove_listener(feature_listener)

                # Handling audio case (both audio features have to be disabled).
                if isinstance(feature, FeatureAudioADPCM):
                    device.disable_notifications(audio_sync_feature)
                    audio_sync_feature.remove_listener(
                        audio_sync_feature_listener)
                elif isinstance(feature, FeatureAudioADPCMSync):
                    device.disable_notifications(audio_feature)
                    audio_feature.remove_listener(audio_feature_listener)

    except KeyboardInterrupt:
        try:
            # Exiting.
            print('\nExiting...\n')
            sys.exit(0)
        except SystemExit:
            os._exit(0)
예제 #10
0
def main(argv):

    printPresentationMessage()

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = MyManagerListener()
        manager.add_listener(manager_listener)

        while True:
            # Synchronous discovery of Bluetooth devices.
            print('Scanning Bluetooth devices...\n')
            manager.discover(SCANNING_TIME_IN_SECONDS)

            # Getting discovered devices.
            discovered_devices = manager.get_nodes()

            # Listing discovered devices.
            if not discovered_devices:
                print('\nNo Bluetooth devices found.')
                sys.exit(0)

            print('\nAvailable Bluetooth devices:')
            i = 1
            for device in discovered_devices:
                print('%d) %s: [%s]' % (i, device.get_name(), device.get_tag()))
                i += 1

            # Selecting a device.
            while True:
                choice = int(input("\nSelect a device (\'0\' to quit): "))
                if choice >= 0 and choice <= len(discovered_devices):
                    break
            if choice == 0:
                # Exiting.
                manager.remove_listener(manager_listener)
                print('Exiting...\n')
                sys.exit(0)

            device = discovered_devices[choice - 1]
            
            # Connecting to the device.
            node_listener = MyNodeListener()
            device.add_listener(node_listener)
            print('\nConnecting to %s...' % (device.get_name()))
            device.connect()
            print('Connection done.')

            # Getting features.
            i = 0
            features = device.get_features()
            temperatureIndex = None
            humidityIndex = None

            for feature in features:
              if feature.get_name() == FeatureTemperature.FEATURE_NAME:
                print("Temperature feature found")
                temperatureIndex = i
              elif feature.get_name() == FeatureHumidity.FEATURE_NAME:
                print("Humidity feature found")
                humidityIndex = i
              i+=1

            if temperatureIndex is None and humidityIndex is None:
              print("No temperature or humidity feature found")
              # Disconnecting from the device.
              print('\nDisconnecting from %s...' % (device.get_name()))
              device.disconnect()
              print('Disconnection done.')
              device.remove_listener(node_listener)
              # Reset discovery.
              manager.reset_discovery()
              # Going back to the list of devices.
              break

            # Enabling notifications for temperature data
            if temperatureIndex is not None:
              temperatureFeature = features[temperatureIndex]
              temperatureListener = TemperatureFeatureListener()
              temperatureFeature.add_listener(temperatureListener)
              device.enable_notifications(temperatureFeature)
            
            # Enabling notifications for humidity data
            if humidityIndex is not None:
              humidityFeature = features[humidityIndex]
              humidityListener = HumidityFeatureListener()
              humidityFeature.add_listener(humidityListener)
              device.enable_notifications(humidityFeature)

            # Getting notifications.
            print('\nStart getting notifications\n')
            while True:
              device.wait_for_notifications(0.05)

    except BTLEException as e:
        print(e)
        # Exiting.
        print('Exiting...\n')
        sys.exit(0)
    except KeyboardInterrupt:
        try:
            # Exiting.
            print('\nExiting...\n')
            sys.exit(0)
        except SystemExit:
            os._exit(0)
def main(argv):

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = ble_interfaces.MyManagerListener()
        manager.add_listener(manager_listener)

        # Synchronous discovery of Bluetooth devices.
        print('Scanning Bluetooth devices...\n')
        manager.discover(SCANNING_TIME_s)

        # Getting discovered devices.
        discovered_devices = manager.get_nodes()
        if not discovered_devices:
            print('No Bluetooth devices found. Exiting...\n')
            sys.exit(0)

        sensortile_index = -1
        for device in discovered_devices:
            if device.get_tag() == SENSORTILE_MAC_ADDRESS:
                sensortile_index = discovered_devices.index(device)
                break

        # Exiting.
        if sensortile_index == -1:
            manager.remove_listener(manager_listener)
            print('Exiting...\n')
            sys.exit(0)

        device = discovered_devices[sensortile_index]
        node_listener = ble_interfaces.MyNodeListener()
        device.add_listener(node_listener)

        # Connecting to the device.
        print('Connecting to %s [%s]...' %
              (device.get_name(), device.get_tag()))
        if not device.connect():
            print('Connection failed... Try again!\n')
            print('Exiting...\n')
            sys.exit(0)

        # Getting features.
        feature_listener = ble_interfaces.MyFeatureListener()
        features = device.get_features()
        for feature in features:
            if feature.get_name() == "Accelerometer":
                # Enabling notifications.
                feature.add_listener(feature_listener)
                device.enable_notifications(feature)

        # Getting notifications.
        while True:
            if device.wait_for_notifications(0.05):
                print(feature_listener._acc_coordinates)

        for feature in features:
            if feature.get_name() == "Accelerometer":
                # Disabling notifications.
                device.disable_notifications(feature)
                feature.remove_listener(feature_listener)

    except KeyboardInterrupt:
        try:
            # Disconnecting from the device.
            print('\nDisconnecting from %s [%s]...' %
                  (device.get_name(), device.get_tag()))
            if not device.disconnect():
                print('Disconnection failed.\n')

            # Exiting.
            print('\nExiting...\n')
            sys.exit(0)
        except SystemExit:
            os._exit(0)
def main(argv):

    # Number of notifications to get before disabling them.
    NOTIFICATIONS = 10

    # Printing intro.
    print_intro()

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = MyManagerListener()
        manager.add_listener(manager_listener)

        # Synchronous discovery of Bluetooth devices.
        print('Scanning Bluetooth devices...\n')
        # Synchronous discovery.
        #manager.discover(False, SCANNING_TIME_s)
        # Asynchronous discovery.
        manager.start_discovery(False, SCANNING_TIME_s)
        time.sleep(SCANNING_TIME_s)
        manager.stop_discovery()

        # Getting discovered devices.
        discovered_devices = manager.get_nodes()
        if not discovered_devices:
            print('\nNo Bluetooth devices found. Exiting...\n')
            sys.exit(0)

        # Checking discovered devices.
        iot_device = None
        for discovered in discovered_devices:
            if discovered.get_tag() == IOT_DEVICE_MAC:
                iot_device = discovered
                break
        if not iot_device:
            print('\nBluetooth setup incomplete. Exiting...\n')
            sys.exit(0)

        # Connecting to the devices.
        node_listener = MyNodeListener()
        iot_device.add_listener(node_listener)
        print('Connecting to %s...' % (iot_device.get_name()))
        iot_device.connect()
        print('Connection done.')

        # Getting features.
        print('\nGetting features...')
        iot_device_feature_stepper_motor = \
            iot_device.get_feature(feature_stepper_motor.FeatureStepperMotor)
        print('\nStepper motor feature found.')

        # Managing feature.
        iot_device_feature_stepper_motor.write_motor_command(
            feature_stepper_motor.StepperMotorCommands.
            MOTOR_STOP_RUNNING_WITHOUT_TORQUE)
        print('\nStepper motor status:')
        print(iot_device_feature_stepper_motor.read_motor_status())
        print('\nStepper motor moving...')
        iot_device_feature_stepper_motor.write_motor_command(
            feature_stepper_motor.StepperMotorCommands.
            MOTOR_MOVE_STEPS_FORWARD, 3000)
        print('\nStepper motor status:')
        print(iot_device_feature_stepper_motor.read_motor_status())

        # Disconnecting from the device.
        print('\nDisconnecting from %s...' % (iot_device.get_name()))
        iot_device.disconnect()
        print('Disconnection done.')
        iot_device.remove_listener(node_listener)
        print('\nExiting...\n')

    except BTLEException as e:
        print(e)
        # Exiting.
        print('Exiting...\n')
        sys.exit(0)
    except KeyboardInterrupt:
        try:
            # Exiting.
            print('\nExiting...\n')
            sys.exit(0)
        except SystemExit:
            os._exit(0)
예제 #13
0
def main(argv):

    # Global variables.
    global iot_device_1, iot_device_2
    global iot_device_1_feature_switch, iot_device_2_feature_switch
    global iot_device_1_status, iot_device_2_status

    # Initial state.
    iot_device_1_status = SwitchStatus.OFF
    iot_device_2_status = SwitchStatus.OFF

    # Printing intro.
    print_intro()

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = MyManagerListener()
        manager.add_listener(manager_listener)

        # Synchronous discovery of Bluetooth devices.
        print('Scanning Bluetooth devices...\n')
        manager.discover(SCANNING_TIME_s)

        # Getting discovered devices.
        discovered_devices = manager.get_nodes()
        if not discovered_devices:
            print('\nNo Bluetooth devices found. Exiting...\n')
            sys.exit(0)

        # Checking discovered devices.
        devices = []
        for discovered in discovered_devices:
            if discovered.get_tag() == IOT_DEVICE_1_MAC:
                iot_device_1 = discovered
                devices.append(iot_device_1)
            elif discovered.get_tag() == IOT_DEVICE_2_MAC:
                iot_device_2 = discovered
                devices.append(iot_device_2)
            if len(devices) == 2:
                break
        if len(devices) < 2:
            print('\nBluetooth setup incomplete. Exiting...\n')
            sys.exit(0)

        # Connecting to the devices.
        for device in devices:
            device.add_listener(MyNodeListener())
            print('Connecting to %s...' % (device.get_name()))
            device.connect()
            print('Connection done.')

        # Getting features.
        print('\nGetting features...')
        iot_device_1_feature_switch = iot_device_1.get_feature(
            feature_switch.FeatureSwitch)
        iot_device_2_feature_switch = iot_device_2.get_feature(
            feature_switch.FeatureSwitch)

        # Resetting switches.
        print('Resetting switches...')
        iot_device_1_feature_switch.write_switch_status(
            iot_device_1_status.value)
        iot_device_2_feature_switch.write_switch_status(
            iot_device_2_status.value)

        # Handling sensing and actuation of switch devices.
        iot_device_1_feature_switch.add_listener(
            MyFeatureSwitchDevice1Listener())
        iot_device_2_feature_switch.add_listener(
            MyFeatureSwitchDevice2Listener())

        # Enabling notifications.
        print('Enabling Bluetooth notifications...')
        iot_device_1.enable_notifications(iot_device_1_feature_switch)
        iot_device_2.enable_notifications(iot_device_2_feature_switch)

        # Bluetooth setup complete.
        print('\nBluetooth setup complete.')

        # Demo running.
        print('\nDemo running (\"CTRL+C\" to quit)...\n')

        # Infinite loop.
        while True:

            # Getting notifications.
            if iot_device_1.wait_for_notifications(
                    0.05) or iot_device_2.wait_for_notifications(0.05):
                continue

    except InvalidOperationException as e:
        print(e)
    except BTLEException as e:
        print(e)
        print('Exiting...\n')
        sys.exit(0)
    except KeyboardInterrupt:
        try:
            # Exiting.
            print('\nExiting...\n')
            sys.exit(0)
        except SystemExit:
            os._exit(0)
예제 #14
0
def main(argv):
    global firmware_upgrade_completed

    # Printing intro.
    print_intro()

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = MyManagerListener()
        manager.add_listener(manager_listener)

        while True:
            # Synchronous discovery of Bluetooth devices.
            print('Scanning Bluetooth devices...\n')
            manager.discover(SCANNING_TIME_s)

            # Getting discovered devices.
            discovered_devices = manager.get_nodes()
            if not discovered_devices:
                print('No Bluetooth devices found. Exiting...\n')
                sys.exit(0)

            # Checking discovered devices.
            device = None
            for discovered in discovered_devices:
                if discovered.get_name() == IOT_DEVICE_NAME:
                    device = discovered
                    break
            if not device:
                print('Bluetooth setup incomplete. Exiting...\n')
                sys.exit(0)

            # Connecting to the devices.
            node_listener = MyNodeListener()
            device.add_listener(node_listener)
            print('Connecting to %s...' % (device.get_name()))
            if not device.connect():
                print('Connection failed.\n')
                print('Bluetooth setup incomplete. Exiting...\n')
                sys.exit(0)
            print('Connection done.')

            # Getting features.
            print('\nFeatures:')
            i = 1
            features = []
            for desired_feature in [
                    feature_audio_scene_classification.
                    FeatureAudioSceneClassification,
                    feature_activity_recognition.FeatureActivityRecognition
            ]:
                feature = device.get_feature(desired_feature)
                if feature:
                    features.append(feature)
                    print('%d) %s' % (i, feature.get_name()))
                    i += 1
            if not features:
                print('No features found.')
            print('%d) Firmware upgrade' % (i))

            # Selecting an action.
            while True:
                choice = int(input('\nSelect an action ' '(\'0\' to quit): '))
                if choice >= 0 and choice <= len(features) + 1:
                    break

            if choice == 0:
                # Disconnecting from the device.
                print('\nDisconnecting from %s...' % (device.get_name()))
                device.disconnect()
                print('Disconnection done.')
                device.remove_listener(node_listener)
                # Exiting.
                manager.remove_listener(manager_listener)
                print('Exiting...\n')
                sys.exit(0)

            elif choice == i:
                try:
                    # Selecting firmware.
                    i = 1
                    for filename in FIRMWARE_FILENAMES:
                        print('%d) %s' % (i, filename))
                        i += 1
                    while True:
                        choice = int(
                            input("\nSelect a firmware (\'0\' to cancel): "))
                        if choice >= 0 and choice <= len(FIRMWARE_FILENAMES):
                            break

                    # Upgrading firmware.
                    if choice != 0:
                        print('\nUpgrading firmware...')
                        upgrade_console = FirmwareUpgradeNucleo.get_console(
                            device)
                        upgrade_console_listener = MyFirmwareUpgradeListener()
                        upgrade_console.add_listener(upgrade_console_listener)
                        firmware = FirmwareFile(FIRMWARE_FOLDER +
                                                FIRMWARE_FILENAMES[choice -
                                                                   1] +
                                                FIRMWARE_EXTENSION)
                        upgrade_console.upgrade_firmware(firmware)

                        # Getting notifications about firmware upgrade process.
                        while not firmware_upgrade_completed:
                            if device.wait_for_notifications(0.05):
                                continue

                except (OSError, ValueError) as e:
                    print(e)

                finally:
                    # Disconnecting from the device.
                    if 'upgrade_console' in locals():
                        upgrade_console.remove_listener(
                            upgrade_console_listener)
                    print('\nDisconnecting from %s...' % (device.get_name()))
                    device.disconnect()
                    print('Disconnection done.')
                    device.remove_listener(node_listener)
                    print('\nDevice is rebooting...\n')
                    time.sleep(20)

            else:
                # Testing features.
                feature = features[choice - 1]

                # Enabling notifications.
                feature_listener = MyFeatureListener()
                feature.add_listener(feature_listener)
                device.enable_notifications(feature)

                # Getting notifications.
                n = 0
                while n < NOTIFICATIONS:
                    if device.wait_for_notifications(0.05):
                        n += 1

                # Disabling notifications.
                device.disable_notifications(feature)
                feature.remove_listener(feature_listener)

                # Disconnecting from the device.
                print('\nDisconnecting from %s...' % (device.get_name()))
                device.disconnect()
                print('Disconnection done.\n')
                device.remove_listener(node_listener)

    except KeyboardInterrupt:
        try:
            # Exiting.
            print('\nExiting...\n')
            sys.exit(0)
        except SystemExit:
            os._exit(0)
예제 #15
0
def main(argv):

    global n_idx
    ###Audio Stream#####################################################
    global stream
    ###Audio Stream#####################################################
    ###Save Audio File##################################################
    global audioFile
    global save_audio_flag
    global beamforming_flag
    ###Save Audio File##################################################

    global audio_feature
    global audio_sync_feature
    global beamforming_feature

    # Printing intro.
    print_intro()

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = MyManagerListener()
        manager.add_listener(manager_listener)

        while True:
            # Synchronous discovery of Bluetooth devices.
            print('Scanning Bluetooth devices...\n')
            manager.discover(SCANNING_TIME_s)

            # Getting discovered devices.
            devices = manager.get_nodes()

            # Listing discovered devices.
            if not devices:
                print('No Bluetooth devices found. Exiting...\n')
                sys.exit(0)
            print('Available Bluetooth devices:')
            i = 1
            for device in devices:
                print('%d) %s: [%s]' %
                      (i, device.get_name(), device.get_tag()))
                i += 1

            # Selecting a device.
            while True:
                choice = int(
                    input("\nSelect a device to connect to (\'0\' to quit): "))
                if choice >= 0 and choice <= len(devices):
                    break
            if choice == 0:
                # Exiting.
                manager.remove_listener(manager_listener)
                print()
                sys.exit(0)
            device = devices[choice - 1]

            # Connecting to the device.
            node_listener = MyNodeListener()
            device.add_listener(node_listener)
            print('Connecting to %s...' % (device.get_name()))
            if not device.connect():
                print('Connection failed.\n')
                continue
            print('Connection done.')

            has_audio_adpcm_features = [False, False]
            has_audio_opus_features = [False, False]
            has_beamforming_feature = False

            i = 1
            features = device.get_features()
            for feature in features:
                if isinstance(feature, FeatureAudioADPCM):
                    audio_feature = feature
                    has_audio_adpcm_features[0] = True
                elif isinstance(feature, FeatureAudioADPCMSync):
                    audio_sync_feature = feature
                    has_audio_adpcm_features[1] = True
                elif isinstance(feature, FeatureAudioOpus):
                    audio_feature = feature
                    has_audio_opus_features[0] = True
                elif isinstance(feature, FeatureAudioOpusConf):
                    audio_sync_feature = feature
                    has_audio_opus_features[1] = True
                elif isinstance(feature, FeatureBeamforming):
                    beamforming_feature = feature
                    has_beamforming_feature = True
                i += 1

            if all(has_audio_adpcm_features) or all(has_audio_opus_features):
                while True:
                    save_audio_flag = input(
                        '\nDo you want to save the audio stream?'
                        '\'y\' - Yes, \'n\' - No (\'0\' to quit): ')

                    if save_audio_flag == 'y' or save_audio_flag == 'Y' or \
                        save_audio_flag == 'n' or save_audio_flag == 'N':
                        if save_audio_flag == 'y' or save_audio_flag == 'Y':
                            ts = time.time()
                            st = datetime.datetime.fromtimestamp(ts).strftime(
                                '%Y-%m-%d_%H-%M-%S')
                            if not os.path.exists(AUDIO_DUMPS_PATH):
                                os.makedirs(AUDIO_DUMPS_PATH)
                            if all(has_audio_adpcm_features):
                                fileName = AUDIO_DUMPS_PATH + st + ADPCM_TAG + AUDIO_DUMP_SUFFIX
                            elif all(has_audio_opus_features):
                                fileName = AUDIO_DUMPS_PATH + st + OPUS_TAG + AUDIO_DUMP_SUFFIX
                            audioFile = open(fileName, "wb+")

                        if (has_beamforming_feature):
                            beamforming_flag = input(
                                '\nDo you want to enable beamforming?'
                                '\'y\' - Yes, \'n\' - No (\'0\' to quit): ')

                        number_of_seconds = int(
                            input('\nHow many seconds do you want to stream?'
                                  ' Value must be > 0 (\'0\' to quit): '))

                        if all(has_audio_adpcm_features):
                            number_of_notifications = number_of_seconds * NPS_ADPCM
                        elif all(has_audio_opus_features):
                            number_of_notifications = number_of_seconds * NPS_OPUS

                        if number_of_seconds > 0:
                            print("Streaming Started")

                            if all(has_audio_adpcm_features):
                                ###Audio Stream#####################################
                                stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK,
                                                       alsaaudio.PCM_NONBLOCK,
                                                       'default')
                                stream.setformat(alsaaudio.PCM_FORMAT_S16_LE)
                                stream.setchannels(CHANNELS)
                                stream.setrate(SAMPLING_FREQ_ADPCM)
                                ###Audio Stream#####################################

                                #Enabling Notifications
                                audio_feature_listener = MyFeatureListener()
                                audio_feature.add_listener(
                                    audio_feature_listener)
                                device.enable_notifications(audio_feature)
                                audio_sync_feature_listener = MyFeatureListenerSync(
                                )
                                audio_sync_feature.add_listener(
                                    audio_sync_feature_listener)
                                device.enable_notifications(audio_sync_feature)
                            elif all(has_audio_opus_features):
                                ###Audio Stream#########################################
                                stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK,
                                                       alsaaudio.PCM_NORMAL,
                                                       'default')
                                stream.setformat(alsaaudio.PCM_FORMAT_S16_LE)
                                stream.setchannels(CHANNELS)
                                stream.setrate(SAMPLING_FREQ_OPUS)
                                stream.setperiodsize(160)
                                ###Audio Stream#########################################

                                #Enabling Notifications
                                audio_sync_feature_listener = MyFeatureListenerSync(
                                )
                                audio_sync_feature.add_listener(
                                    audio_sync_feature_listener)
                                device.enable_notifications(audio_sync_feature)
                                audio_feature_listener = MyFeatureListener()
                                audio_feature.add_listener(
                                    audio_feature_listener)
                                device.enable_notifications(audio_feature)

                            if beamforming_flag == 'y' or beamforming_flag == 'Y' or \
                                beamforming_flag == 'n' or beamforming_flag == 'N':
                                if beamforming_flag == 'y' or beamforming_flag == 'Y':
                                    beamforming_feature_listener = MyFeatureListenerBeam(
                                    )
                                    beamforming_feature.add_listener(
                                        beamforming_feature_listener)
                                    device.enable_notifications(
                                        beamforming_feature)
                                    device.send_command(
                                        b"\x00\x00\x08\x00\xAA\x01")
                                    print("Beamforming Enabled")

                            n_idx = 0
                            while n_idx < number_of_notifications:
                                device.wait_for_notifications(0.05)

                            print("End of Streaming")
                            # Disabling notifications.
                            device.disable_notifications(audio_feature)
                            audio_feature.remove_listener(
                                audio_feature_listener)
                            device.disable_notifications(audio_sync_feature)
                            audio_sync_feature.remove_listener(
                                audio_sync_feature_listener)
                            if beamforming_flag == 'y' or beamforming_flag == 'Y':
                                device.send_command(
                                    b"\x00\x00\x08\x00\xAA\x00")
                                print("Beamforming Disabled")
                                device.disable_notifications(
                                    beamforming_feature)
                                beamforming_feature.remove_listener(
                                    beamforming_feature_listener)
                            ###Save Audio File##################################
                            if save_audio_flag == 'y' or save_audio_flag == 'Y':
                                audioFile.close()
                            ###Save Audio File##################################
                            ###Audio Stream#####################################
                            stream.close()
                            ###Audio Stream#####################################
                        elif number_of_seconds == 0:
                            # Disabling notifications.
                            if audio_feature.is_notifying():
                                device.disable_notifications(audio_feature)
                                audio_feature.remove_listener(
                                    audio_feature_listener)
                            if audio_sync_feature.is_notifying():
                                device.disable_notifications(
                                    audio_sync_feature)
                                audio_sync_feature.remove_listener(
                                    audio_sync_feature_listener)
                            if beamforming_flag == 'y' or beamforming_flag == 'Y':
                                if beamforming_feature.is_notifying():
                                    device.disable_notifications(
                                        beamforming_feature)
                                    beamforming_feature.remove_listener(
                                        beamforming_feature_listener)
                            ###Save Audio File##################################
                            if save_audio_flag == 'y' or save_audio_flag == 'Y':
                                audioFile.close()
                            ###Save Audio File##################################
                            # Disconnecting from the device.
                            print('\nDisconnecting from %s...' %
                                  (device.get_name()))
                            device.disconnect()
                            print('Disconnection done.')
                            device.remove_listener(node_listener)
                            # Reset discovery.
                            manager.reset_discovery()
                            # Going back to the list of devices.
                            break
                    elif save_audio_flag == '0':
                        # Disconnecting from the device.
                        print('\nDisconnecting from %s...' %
                              (device.get_name()))
                        device.disconnect()
                        print('Disconnection done.')
                        device.remove_listener(node_listener)
                        # Reset discovery.
                        manager.reset_discovery()
                        # Going back to the list of devices.
                        break
            else:
                print("No Audio Features are Exposed from your BLE Node!")
                while True:
                    restartDiscovery = int(
                        input(
                            '\nPress \'1\' to restart scanning for BLE devices '
                            '(\'0\' to quit): '))
                    if restartDiscovery == 1:
                        # Reset discovery.
                        manager.reset_discovery()
                        break
                    elif restartDiscovery == 0:
                        # Exiting.
                        print('\nExiting...\n')
                        sys.exit(0)

    except KeyboardInterrupt:
        try:
            # Exiting.
            print('\nExiting...\n')
            sys.exit(0)
        except SystemExit:
            os._exit(0)
예제 #16
0
def main(argv):

    # Printing intro.
    print_intro()

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = MyManagerListener()
        manager.add_listener(manager_listener)

        # Synchronous discovery of Bluetooth devices.
        print('Scanning Bluetooth devices...\n')
        manager.discover(SCANNING_TIME_s)

        # Getting discovered devices.
        discovered_devices = manager.get_nodes()
        if not discovered_devices:
            print('No Bluetooth devices found. Exiting...\n')
            sys.exit(0)

        # Checking discovered devices.
        iot_device = None
        for discovered in discovered_devices:
            if discovered.get_tag() == IOT_DEVICE_MAC:
                iot_device = discovered
                break
        if not iot_device:
            print('Bluetooth setup incomplete. Exiting...\n')
            sys.exit(0)

        # Connecting to the devices.
        node_listener = MyNodeListener()
        iot_device.add_listener(node_listener)
        print('Connecting to %s...' % (iot_device.get_name()))
        if not iot_device.connect():
            print('Connection failed.\n')
            print('Bluetooth setup incomplete. Exiting...\n')
            sys.exit(0)
        print('Connection done.')

        # Getting features.
        print('\nGetting features...')
        iot_device_feature_stepper_motor = \
            iot_device.get_feature(feature_stepper_motor.FeatureStepperMotor)
        print('\nStepper motor feature found.')

        try:
            # Managing feature.
            iot_device_feature_stepper_motor.write_motor_command(
                feature_stepper_motor.StepperMotorCommands.
                MOTOR_STOP_RUNNING_WITHOUT_TORQUE)
            print('\nStepper motor status:')
            print(iot_device_feature_stepper_motor.read_motor_status())
            print('\nStepper motor moving...')
            iot_device_feature_stepper_motor.write_motor_command(
                feature_stepper_motor.StepperMotorCommands.
                MOTOR_MOVE_STEPS_FORWARD, 3000)
            print('\nStepper motor status:')
            print(iot_device_feature_stepper_motor.read_motor_status())
        except (BlueSTInvalidOperationException,
                BlueSTInvalidDataException) as e:
            print(e)
            # Exiting.
            print('Exiting...\n')
            sys.exit(0)

        # Disconnecting from the device.
        print('\nDisconnecting from %s...' % (iot_device.get_name()))
        iot_device.disconnect()
        print('Disconnection done.')
        iot_device.remove_listener(node_listener)
        print('\nExiting...\n')

    except KeyboardInterrupt:
        try:
            # Exiting.
            print('\nExiting...\n')
            sys.exit(0)
        except SystemExit:
            os._exit(0)
예제 #17
0
파일: main.py 프로젝트: terrie9876/COEN143
def bluetooth():
    global s1, s2

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = MyManagerListener()
        manager.add_listener(manager_listener)

        while True:
            # Synchronous discovery of Bluetooth devices.
            print('Scanning Bluetooth devices...\n')
            manager.discover(SCANNING_TIME_s)

            # Alternative 1: Asynchronous discovery of Bluetooth devices.
            # manager.discover(SCANNING_TIME_s, True)

            # Alternative 2: Asynchronous discovery of Bluetooth devices.
            # manager.start_discovery()
            # time.sleep(SCANNING_TIME_s)
            # manager.stop_discovery()

            # Getting discovered devices.
            discovered_devices = manager.get_nodes()

            # Listing discovered devices.
            if not discovered_devices:
                print('\nNo Bluetooth devices found.')
                continue
            print('\nAvailable Bluetooth devices:')
            i = 1
            for device in discovered_devices:
                print('%d) %s: [%s]' %
                      (i, device.get_name(), device.get_tag()))
                i += 1

            # Selecting a device.
            while True:
                choice = int(input("\nSelect a device (\'0\' to quit): "))
                if 0 <= choice <= len(discovered_devices):
                    break
            if choice == 0:
                # Exiting.
                manager.remove_listener(manager_listener)
                print('Exiting...\n')
                sys.exit(0)
            device = discovered_devices[choice - 1]

            # Connecting to the device.
            node_listener = MyNodeListener()
            device.add_listener(node_listener)
            print('\nConnecting to %s...' % (device.get_name()))
            device.connect()
            print('Connection done.')

            if s1 is None:
                s1 = device
                sensor = 's1'
            elif s2 is None:
                s2 = device
                sensor = 's2'
            else:
                return

            # while True:
            # Getting features.
            # i = 1
            features = device.get_features()

            # for feature in features:
            #     print('%d) %s' % (i, feature.get_name()))

            temp_feature = features[2]
            humid_feature = features[3]

            # Enabling notifications.
            feature_listener = TemperatureListener()
            feature_listener.sensor = sensor
            temp_feature.add_listener(feature_listener)
            device.enable_notifications(temp_feature)
            feature_listener = HumidityListener()
            feature_listener.sensor = sensor
            humid_feature.add_listener(feature_listener)
            device.enable_notifications(humid_feature)

            # Getting notifications.
            while True:
                device.wait_for_notifications(1)

            # # Disabling notifications.
            # device.disable_notifications(feature)
            # feature.remove_listener(feature_listener)

    except BTLEException as e:
        print(e)
        # Exiting.
        print('Exiting...\n')
        sys.exit(0)
    except KeyboardInterrupt:
        try:
            # Exiting.
            print('\nExiting...\n')
            sys.exit(0)
        except SystemExit:
            os._exit(0)
예제 #18
0
def main(argv):

    # Printing intro.
    print_intro()

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = MyManagerListener()
        manager.add_listener(manager_listener)

        # Synchronous discovery of Bluetooth devices.
        print('Scanning Bluetooth devices...\n')
        manager.discover(SCANNING_TIME_s)

        # Getting discovered devices.
        discovered_devices = manager.get_nodes()

        # Listing discovered devices.
        if not discovered_devices:
            print('No Bluetooth devices found. Exiting...\n')
            sys.exit(0)
        print('Available Bluetooth devices:')
        i = 1
        for device in discovered_devices:
            print('%d) %s: [%s]' % (i, device.get_name(), device.get_tag()))
            i += 1

        # Selecting devices to connect.
        selected_devices = []
        while True:
            while True:
                choice = int(
                    input('\nSelect a device to connect to (\'0\' to finish): '))
                if choice >= 0 and choice <= len(discovered_devices):
                    break

            if choice == 0:
                break
            else:
                device = discovered_devices[choice - 1]
                selected_devices.append(device)
                print('Device %s added.' % (device.get_name()))

        device_threads = []
        if len(selected_devices) > 0:
            # Starting threads.
            print('\nConnecting to selected devices and getting notifications '
                  'from all their features ("CTRL+C" to exit)...\n')
            for device in selected_devices:
                device_threads.append(DeviceThread(device).start())
        else:
            # Exiting.
            manager.remove_listener(manager_listener)
            print('Exiting...\n')
            sys.exit(0)

        # Getting notifications.
        while True:
            pass

    except KeyboardInterrupt:
        try:
            # Exiting.
            print('\nExiting...\n')
            sys.exit(0)
        except SystemExit:
            os._exit(0)
예제 #19
0
def main(argv):

    # Printing intro.
    print_intro()

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = MyManagerListener()
        manager.add_listener(manager_listener)

        while True:
            # Synchronous discovery of Bluetooth devices.
            print('Scanning Bluetooth devices...\n')
            manager.discover(False, SCANNING_TIME_s)

            # Getting discovered devices.
            devices = manager.get_nodes()

            # Listing discovered devices.
            if not devices:
                print('\nNo Bluetooth devices found.')
                sys.exit(0)
            print('\nAvailable Bluetooth devices:')
            i = 1
            for device in devices:
                print('%d) %s: [%s]' %
                      (i, device.get_name(), device.get_tag()))
                i += 1

            # Selecting a device.
            while True:
                choice = int(input("\nSelect a device (\'0\' to quit): "))
                if choice >= 0 and choice <= len(devices):
                    break
            if choice == 0:
                # Exiting.
                manager.remove_listener(manager_listener)
                print('Exiting...\n')
                sys.exit(0)
            device = devices[choice - 1]

            # Connecting to the device.
            node_listener = MyNodeListener()
            device.add_listener(node_listener)
            print('\nConnecting to %s...' % (device.get_name()))
            device.connect()
            print('Connection done.')

            while True:
                # Getting features.
                print('\nFeatures:')
                i = 1
                features = device.get_features()

                audioFeature = None
                audioSyncFeature = None

                for feature in features:
                    if not feature.get_name(
                    ) == FeatureAudioADPCMSync.FEATURE_NAME:
                        if feature.get_name(
                        ) == FeatureAudioADPCM.FEATURE_NAME:
                            audioFeature = feature
                            print('%d,%d) %s' % (i, i + 1, "Audio & Sync"))
                        else:
                            print('%d) %s' % (i, feature.get_name()))
                        i += 1
                    else:
                        audioSyncFeature = feature
                # Selecting a feature.
                while True:
                    choice = int(
                        input('\nSelect a feature '
                              '(\'0\' to disconnect): '))
                    if choice >= 0 and choice <= len(features):
                        break
                if choice == 0:
                    # Disconnecting from the device.
                    print('\nDisconnecting from %s...' % (device.get_name()))
                    device.disconnect()
                    print('Disconnection done.')
                    device.remove_listener(node_listener)
                    # Reset discovery.
                    manager.reset_discovery()
                    # Going back to the list of devices.
                    break
                feature = features[choice - 1]

                # Enabling notifications.
                feature_listener = MyFeatureListener()
                feature_listener.initiate_cloud_client()
                feature.add_listener(feature_listener)
                device.enable_notifications(feature)

                if feature.get_name() == FeatureAudioADPCM.FEATURE_NAME:
                    audioSyncFeature_listener = MyFeatureListener()
                    audioSyncFeature.add_listener(audioSyncFeature_listener)
                    device.enable_notifications(audioSyncFeature)
                elif feature.get_name() == FeatureAudioADPCMSync.FEATURE_NAME:
                    audioFeature_listener = MyFeatureListener()
                    audioFeature.add_listener(audioFeature_listener)
                    device.enable_notifications(audioFeature)

                # Getting notifications.
                n = 0
                while n < NOTIFICATIONS:
                    if device.wait_for_notifications(0.05):
                        n += 1

                # Disabling notifications.
                device.disable_notifications(feature)
                feature.remove_listener(feature_listener)
                feature_listener.disconnect_cloud()

                if feature.get_name() == FeatureAudioADPCM.FEATURE_NAME:
                    device.disable_notifications(audioSyncFeature)
                    audioSyncFeature.remove_listener(audioSyncFeature_listener)
                elif feature.get_name() == FeatureAudioADPCMSync.FEATURE_NAME:
                    device.disable_notifications(audioFeature)
                    audioFeature.remove_listener(audioFeature_listener)

    except BTLEException as e:
        print(e)
        # Exiting.
        print('Exiting...\n')
        sys.exit(0)
    except KeyboardInterrupt:
        try:
            # Exiting.
            print('\nExiting...\n')
            sys.exit(0)
        except SystemExit:
            os._exit(0)
예제 #20
0
def main(argv):

    try:
        # Creating Bluetooth Manager.
        manager = Manager.instance()
        manager_listener = ble_interfaces.MyManagerListener()
        manager.add_listener(manager_listener)

        # Synchronous discovery of Bluetooth devices.
        print('Scanning Bluetooth devices...\n')
        manager.discover(SCANNING_TIME_s)

        # Getting discovered devices.
        discovered_devices = manager.get_nodes()
        if not discovered_devices:
            print('No Bluetooth devices found. Exiting...\n')
            sys.exit(0)

        sensortile_index = -1
        for device in discovered_devices:
            if device.get_tag() == SENSORTILE_MAC_ADDRESS:
                sensortile_index = discovered_devices.index(device)
                break

        # Exiting.
        if sensortile_index == -1:
            manager.remove_listener(manager_listener)
            print('Exiting...\n')
            sys.exit(0)

        device = discovered_devices[sensortile_index]
        node_listener = ble_interfaces.MyNodeListener()
        device.add_listener(node_listener)

        # Connecting to the device.
        print('Connecting to %s [%s] ...' %
              (device.get_name(), device.get_tag()))
        if not device.connect():
            print('Connection failed... Try again!\n')
            print('Exiting...\n')
            sys.exit(0)

        # Getting features.
        features = device.get_features()
        print('\nAvailable Features:')
        i = 1
        for feature in features:
            if isinstance(feature, FeatureAudioADPCM):
                audio_feature = feature
                print('%d,%d) %s' % (i, i + 1, "Audio & Sync"))
                i += 1
            elif isinstance(feature, FeatureAudioADPCMSync):
                audio_sync_feature = feature
            else:
                print('%d) %s' % (i, feature.get_name()))
                i += 1

        # Exiting.
        manager.remove_listener(manager_listener)

        # Disconnecting from the device.
        print('\nDisconnecting from %s [%s] ...' %
              (device.get_name(), device.get_tag()))
        if not device.disconnect():
            print('Disconnection failed.\n')

        device.remove_listener(node_listener)
        print('Exiting...\n')
        sys.exit(0)
    except KeyboardInterrupt:
        try:
            # Exiting.
            print('\nExiting...\n')
            sys.exit(0)
        except SystemExit:
            os._exit(0)