Exemplo n.º 1
0
def _main():
    global lasttime
    api = ConnectAPI()
    api.start_notifications()
    # calling start_notifications is required for getting/setting resource synchronously
    devices = api.list_connected_devices().data
    if not devices:
        raise Exception("No connected devices registered. Aborting")
    #selecting latest device for listening for data
    mainDevice = devices[-1]
    isActive = True
    lasttime = time.time()
    Subscribe(api, mainDevice)
    #creating threads
    # thread t: used to start the flask api which serves the phone app
    t = threading.Thread(target=StartAPI)
    t.start()
    # thread t2: used to sum up and guess dominant movement for minute
    t2 = threading.Thread(target=MinuteToDB)
    t2.start()

    #Resubscribe to pelion device if connection appear to be lost (no valid data for 3)
    while True:
        time.sleep(1.5)
        if time.time() - lasttime > 3:
            #print("Attempt reconnect!")
            Subscribe(api, mainDevice)
Exemplo n.º 2
0
 def test_config_invalid_host(self):
     # regression check - give a sane error for invalid hosts
     api = ConnectAPI(dict(host='invalid'))
     with mock.patch('urllib3.PoolManager.request') as mocked:
         mocked.side_effect = RuntimeError
         with self.assertRaises(RuntimeError):
             api.list_connected_devices().next()
Exemplo n.º 3
0
 def test_autostart_enabled(self):
     with mock.patch('urllib3.PoolManager.request') as mocked:
         mocked.return_value = mock.MagicMock()
         mocked.return_value.status = 200
         a = ConnectAPI(dict(autostart_notification_thread=True))
         self.assertFalse(a.has_active_notification_thread)
         a.get_resource_value_async('abc123', '/3/4/5')
         self.assertTrue(a.has_active_notification_thread)
    def test_list_connected(self):
        # an example: list devices in Pelion Device Management
        from mbed_cloud import ConnectAPI
        api = ConnectAPI()

        # Print all devices
        for device in api.list_connected_devices(order='asc', max_results=900):
            print(device.id, device.state)
Exemplo n.º 5
0
 def Init(self):
     print("Pelion sync initializing start")
     self.api = ConnectAPI()
     self.api.start_notifications()
     self.devices = api.list_connected_devices().data
     if not self.devices:
         return False
     return True
Exemplo n.º 6
0
 def test_config_singleton(self):
     # check two different api configs don't clobber each other
     a = ConnectAPI(dict(api_key='apple'))
     b = ConnectAPI(dict(api_key='banana'))
     api_key = EndpointsApi
     self.assertEqual(a.apis[api_key].api_client.configuration.api_key,
                      {'Authorization': 'apple'})
     self.assertEqual(b.apis[api_key].api_client.configuration.api_key,
                      {'Authorization': 'banana'})
Exemplo n.º 7
0
 def test_autostart_disabled(self):
     with mock.patch('urllib3.PoolManager.request') as mocked:
         mocked.return_value = mock.MagicMock()
         mocked.return_value.status = 200
         a = ConnectAPI(dict(autostart_notification_thread=False))
         self.assertFalse(a.has_active_notification_thread)
         with self.assertRaises(CloudUnhandledError) as e:
             a.get_resource_value_async('abc123', '/3/4/5')
         self.assertFalse(a.has_active_notification_thread)
         self.assertIn('notifications thread', str(e.exception))
def _main():
    api = ConnectAPI()
    # calling start_notifications is required for getting/setting resource synchronously
    api.start_notifications()
    devices = api.list_connected_devices().data
    if not devices:
        raise Exception("No connected devices registered. Aborting")

    # Synchronously get the initial/current value of the resource
    while True:
        value = api.get_resource_value(devices[0].id, BUTTON_RESOURCE)
        _current_val(value)
        val1 = value.encode()
        e1 = f.encrypt(val1)

        os.system("mosquitto_pub -h localhost -t temp -m " + str(e1) +
                  " -u \"roy\" -P \"roy\"")
        value2 = api.get_resource_value(devices[0].id, BUTTON_RESOURCE2)
        _current_val2(value2)

        val2 = value2.encode()

        e2 = f.encrypt(val2)
        os.system("mosquitto_pub -h localhost -t heart -m " + str(e2) +
                  " -u \"roy\" -P \"roy\"")
        a = [[float(value), float(value2)]]
        predict_from_joblib = joblib.load('/home/roy/disco/predict.pkl')
        b = predict_from_joblib.predict(a)
        pre = b[0]
        print(pre)
        os.system("mosquitto_pub -h localhost -t predict -m " + str(pre))

    # Register a subscription for new values
    api.add_resource_subscription_async(devices[0].id, BUTTON_RESOURCE,
                                        _subscription_handler)
 def test(self):
     api = ConnectAPI()
     device = api.list_connected_devices().first()
     start = threading.Event()
     threads = []
     for i in range(20):
         t = threading.Thread(target=worker,
                              args=(i, start, api, device, 100))
         t.daemon = True
         t.start()
         threads.append(t)
     start.set()
     [t.join() for t in threads]
Exemplo n.º 10
0
def _main():
    api = ConnectAPI()

    # Print devices that matches filter
    filters = {
        'created_at': {
            '$gte': datetime.datetime(2017, 1, 1),
            '$lte': datetime.datetime(2017, 12, 31)
        }
    }
    devices = api.list_connected_devices(order='asc', filters=filters)
    for idx, device in enumerate(devices):
        print(device)
 def test_subscribe_resources(self):
     import logging
     logging.basicConfig(level=logging.DEBUG)
     # an example: subscribing to resource value changes
     # creates an Observer listening to resource value changes for devices
     # whose id starts with `016` and resource paths start with `/3/0/`
     from mbed_cloud import ConnectAPI
     api = ConnectAPI()
     # prepare a channel
     channel = api.subscribe.channels.ResourceValues(device_id='016*', resource_path='/3/0/*')
     # start listening for updates
     observer = api.subscribe(channel)
     # on the first update for the channel, block for the specified timeout
     print(observer.next().block(timeout=120000))
    def test_get_and_set_resource_value(self):
        # an example: get and set a resource value
        from mbed_cloud.foundation import Device
        from mbed_cloud import ApiFilter
        from mbed_cloud.foundation.enums import DeviceStateEnum
        from mbed_cloud import ConnectAPI

        # Use the Foundation interface to find a registered device.
        api_filter = ApiFilter()
        api_filter.add_filter("state", "eq", DeviceStateEnum.REGISTERED)
        device = Device().list(max_results=2, filter=api_filter).next()

        # Use the Legacy interface to find resources
        connect_api = ConnectAPI()

        # Find an observable resource
        for resource in connect_api.list_resources(device.id):
            if resource.observable:
                break

        # Set a resource value
        connect_api.set_resource_value(device.id, resource.path, "12")

        # Get a resource value
        value = connect_api.get_resource_value(device.id, resource.path)
        print("Device %s, path %s, current value: %s" %(device.id, resource.path, value))
        # end of example

        connect_api.stop_notifications()
Exemplo n.º 13
0
def _main():
    api = ConnectAPI()
    devices = api.list_connected_devices().data
    if len(devices) == 0:
        raise Exception("No endpints registered. Aborting")
    # Delete device subscriptions
    api.delete_device_subscriptions(devices[0].id)
    # First register to webhook
    api.update_webhook("https://mbed-iot.herokuapp.com/webhook/")
    time.sleep(2)
    api.add_resource_subscription(devices[0].id, BUTTON_RESOURCE)
Exemplo n.º 14
0
 def setUpClass(cls):
     cls.api = ConnectAPI()
     # some arbitrary period
     cls.metrics = cls.api.list_metrics(
         start=start,
         end=end,
     )
    def setup(self):
        # Check if API key is in environmental vars
        if 'MBED_CLOUD_SDK_API_KEY' in os.environ:
            api_key = (os.environ[str('MBED_CLOUD_SDK_API_KEY')])
        else:
            api_key = self.config.get("api_key")

        if not api_key.startswith('ak_'):
            raise TestStepFail(
                "No API key in MBED_CLOUD_SDK_API_KEY or in pelion.tc_cfg")

        self.device_id = self.config.get("device_id")
        host = self.config.get("host")
        self.test_config = {"api_key": api_key, "host": host}
        self.account_api = AccountManagementAPI(self.test_config)
        self.connect_api = ConnectAPI(self.test_config)
        self.device_api = DeviceDirectoryAPI(self.test_config)

        # Additional parameters for handling REST requests without SDK
        self.rest_headers = {'Authorization': 'Bearer ' + api_key}
        self.rest_address = self.config.get("host")

        # Init delay due to internal usage of PULL notification in SDK. Notications might be lost between
        # tests.
        # TODO: Remove workaround after limitation in SDK has been fixed.
        self.delay(5)
Exemplo n.º 16
0
 def test_no_config_default(self):
     with TempConf(dict(api_key=self.dummy_key)):
         # when we get a config object, force it not to look at existing paths (to see what it defaults to)
         with mock.patch.object(Config, attribute='paths') as mocked:
             mocked.return_value = [os.environ.get("MBED_CLOUD_SDK_CONFIG")]
             a = ConnectAPI(dict(api_key=self.dummy_key))
         self.assertIn('api.us-east-1',
                       a.apis[EndpointsApi].api_client.configuration.host)
def _main():
    api = ConnectAPI()

    # Print all devices
    for idx, device in enumerate(
            api.list_connected_devices(order='desc', limit=10)):
        resources = api.list_resources(device.id)

        # Print endpoint name header
        header = device.id
        print(header)
        print(len(header) * "-")

        for r in resources:
            print("\t- %s (%s / Observable: %s)" %
                  (r.path, r.type if r.type else "-", r.observable))

        # Space between endpoints
        print("")
 def test_subscribe_device_state(self):
     # an example: subscribing to device state changes
     # creates an Observer listening to device state changes for devices
     # whose id starts with `016`
     from mbed_cloud import ConnectAPI
     api = ConnectAPI()
     # prepare a channel
     channel = api.subscribe.channels.DeviceStateChanges(
         device_id='016*',
         # here, `channel` refers to the filterable device state received from
         # the notification system
         channel=[
             api.subscribe.channels.ChannelIdentifiers.registrations,
             api.subscribe.channels.ChannelIdentifiers.registrations_expired
         ]
     )
     # start listening for updates
     observer = api.subscribe(channel)
     # on the first update for the channel, block for the specified timeout
     print(observer.next().block(timeout=120000))
    def test_subscribe(self):
        # an example: subscribe to resource values
        from mbed_cloud import ConnectAPI

        # Create an instance of the Connect API
        connect_api = ConnectAPI()

        # Configure a subscription to receive resource value changes on all devices
        channel = connect_api.subscribe.channels.ResourceValues(device_id="*")

        # Contact Pelion Device Management to actually make the configured subscription
        observer = connect_api.subscribe(channel)

        # Print the subscription notifications received
        while True:
            print(observer.next().block())

        # end of example
            break

        connect_api.subscribe.unsubscribe_all()
Exemplo n.º 20
0
def _main():
    api = ConnectAPI()
    header = "Get statistics from the last 30 days in 1 day interval"
    print("%s\n%s" % (header, len(header) * "-"))
    metrics = list(api.list_metrics(interval="1d", period="30d"))
    for idx, metric in enumerate(metrics):
        print(metric)

    header = "Get statistics from the last 2 days in 3 hours interval"
    print("%s\n%s" % (header, len(header) * "-"))
    metrics = list(api.list_metrics(interval="3h", period="2d"))
    for idx, metric in enumerate(metrics):
        print(metric)

    header = "Get statistics from 1 March 2017 to 1 April 2017"
    print("%s\n%s" % (header, len(header) * "-"))
    start = datetime(2017, 3, 1, 0, 0, 0)
    end = datetime(2017, 4, 1, 0, 0, 0)
    metrics = list(api.list_metrics(interval="1d", start=start, end=end))
    for idx, metric in enumerate(metrics):
        print(metric)
Exemplo n.º 21
0
    def test_config_file_from_env(self):
        # fully define a config at a custom location, and verify it is loaded
        with TempConf(dict(api_key=self.dummy_key, host=self.dummy_host)):
            c = Config()
            self.assertEqual(self.dummy_key, c.get('api_key'))
            self.assertIn('dummy_host_url', c['host'])

            # verify custom config reaches the internal api
            a = ConnectAPI()
            self.assertIn(
                self.dummy_key,
                str(a.apis[EndpointsApi].api_client.configuration.api_key))
Exemplo n.º 22
0
def _run_async():
    api = ConnectAPI()
    api.start_notifications()
    devices = api.list_connected_devices().data
    if not devices:
        raise Exception("No devices registered. Aborting")

    current_value = None
    while True:
        async_resp = api.get_resource_value_async(devices[0].id,
                                                  BUTTON_RESOURCE)

        # Busy wait - block the thread and wait for the response to finish.
        while not async_resp.is_done:
            time.sleep(0.1)

        # Check if we have a async error response, and abort if it is.
        if async_resp.error:
            raise Exception("Got async error response: %r" % async_resp.error)

        # Get the value from the async response, as we know it's done and it's not
        # an error.
        new_value = async_resp.value

        # Print new value to user, if it has changed.
        if current_value != new_value:
            print("Current value: %r" % (new_value, ))

            # Save new current value
            current_value = new_value
Exemplo n.º 23
0
def _main():

    # Setup API config
    #try:
    #    result = subprocess.check_output(["mbed", "config", "--list"], stderr=subprocess.STDOUT)
    #except Exception:
    #    self.logger.prn_err("ERROR: CLOUD_SDK_API_KEY global config is not set. ")
    #    return -1
    #
    #match = re.search(b'CLOUD_SDK_API_KEY=(.*)\n', result)
    #if match == None:
    #    self.logger.prn_err("ERROR: CLOUD_SDK_API_KEY global config is not set.")
    #    return -1
    #
    #api_key_val = match.group(1).strip()
    #api_config = {"api_key" : api_key_val, "host" : "https://api.us-east-1.mbedcloud.com"}
    #
    #print(api_config)
    #
    # Instantiate Device and Connect API
    api = ConnectAPI()

    # Print all devices
    for idx, device in enumerate(
            api.list_connected_devices(order='desc', limit=10)):
        resources = api.list_resources(device.id)

        # Print endpoint name header
        header = device.id
        print(header)
        print(len(header) * "-")

        for r in resources:
            print("\t- %s (%s / Observable: %s)" %
                  (r.path, r.type if r.type else "-", r.observable))

        # Space between endpoints
        print("")
Exemplo n.º 24
0
class PelionSync():
    devices = None
    api = None
    value = dict()

    def Init(self):
        print("Pelion sync initializing start")
        self.api = ConnectAPI()
        self.api.start_notifications()
        self.devices = api.list_connected_devices().data
        if not self.devices:
            return False
        return True

    def Query(self):
        self.devices = api.list_connected_devices().data
        for device in devices:
            try:
                hat = Hat.objects.get(device_id=device.id)
            except:
                print("New device id!:{}\nAdd new hat!".format(device.id))
                hat = Hat.objects.create(device_id=device.id)
            sv = SensorValue.objects.create(owner = hat,\
                temperature = api.get_resource_value(device.id, "/3303/0/5700"),\
                humid = api.get_resource_value(device.id, "/3304/0/5700"), \
                accelX = api.get_resource_value(device.id, "/3313/0/5702"), \
                accelY = api.get_resource_value(device.id, "/3313/0/5703"), \
                accelZ = api.get_resource_value(device.id, "/3313/0/5704"), \
                pressure = api.get_resource_value(device.id, "/3323/0/5700"), \
                distance = api.get_resource_value(device.id, "/3330/0/5700"), \
                gyroX = api.get_resource_value(device.id, "/3334/0/5702"), \
                gyroY = api.get_resource_value(device.id, "/3334/0/5703"), \
                gyroZ = api.get_resource_value(device.id, "/3334/0/5704"), \
                gps_lat = api.get_resource_value(device.id, "/3336/0/5702"), \
                gps_lng = api.get_resource_value(device.id, "/3336/0/5703"), \
                gps_alt = api.get_resource_value(device.id, "/3336/0/5704"), \
                voc = api.get_resource_value(device.id, "/10313/0/5700"), \
                air_quality = api.get_resource_value(device.id, "/10313/0/5701"))
Exemplo n.º 25
0
def _main():
    api = ConnectAPI()
    api.start_notifications()
    devices = api.list_connected_devices().data
    if not devices:
        raise Exception("No connected devices registered. Aborting")

    value = api.get_resource_value(devices[0].id, POPUP_IOT_RESOURCE)
    queue = api.add_resource_subscription(devices[0].id, POPUP_IOT_RESOURCE)
    while True:
        print("Current value: %r" % (value, ))
        value = queue.get(timeout=30)
Exemplo n.º 26
0
def pull_resource_values(device_id, database, table):
    import pytd
    import pandas as pd
    from mbed_cloud import ConnectAPI
    from prestodb.exceptions import PrestoUserError

    # see PDM Python client ConnectAPI examples:
    # https://www.pelion.com/docs/device-management/current/mbed-cloud-sdk-python/subscriptions.html
    # https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c2bc539856cc6932e367ed47f7c2e64ef6e3a77a/examples/connect/notifications.py#L25-L45
    api = ConnectAPI({
        'api_key': os.environ.get('PDM_API_KEY'),
        'host': os.environ.get('PDM_HOST')
    })

    # check device existence
    try:
        filters = {'id': {'$eq': device_id}}
        api.list_connected_devices(filters=filters).data
    except Exception:
        raise ValueError('cannot find the device: {}'.format(device_id))

    column_names, row = [], []
    for r in api.list_resources(device_id):
        # observable resources whose values can change over time:
        # https://www.pelion.com/docs/device-management/current/connecting/collecting-resources.html
        if r.type is None or not r.observable:
            continue

        try:
            value = api.get_resource_value(device_id, r.path)
        except Exception as e:
            print('skipped resource path {} due to {}'.format(r.path, e))
            continue
        value = _cast(value)
        row.append(value)

        column_names.append(r.type)

        print('path: {}, type: {}, value: {}'.format(r.path, r.type, value))

    if len(row) == 0:
        sys.exit("no resource values from device: {}".format(device_id))

    client = pytd.Client(apikey=os.environ.get('TD_API_KEY'),
                         endpoint=os.environ.get('TD_API_SERVER'),
                         database=database)
    df = pd.DataFrame(**{'columns': column_names, 'data': [row]})

    try:
        client.load_table_from_dataframe(df, table, writer='insert_into',
                                         if_exists='append')
    except PrestoUserError:
        raise RuntimeError("inserted record does not match to current schema "
                           "of table `{}`. Make sure a list of available "
                           "resources is same as previous execution, or "
                           "change `writer` to `spark` or `bulk_import` to "
                           "take advantage of schemaless record insertion."
                           "".format(table))
def _main():
    api = ConnectAPI()
    # calling start_notifications is required for getting/setting resource synchronously
    api.start_notifications()
    devices = api.list_connected_devices().data
    if not devices:
        raise Exception("No connected devices registered. Aborting")

    # Synchronously get the initial/current value of the resource
    value = api.get_resource_value(devices[0].id, WRITEABLE_RESOURCE)
    print("Current value: %r" % (value, ))

    # Set Resource value. Resource needs to have type == "writable_resource"
    api.set_resource_value(device_id=devices[0].id,
                           resource_path=WRITEABLE_RESOURCE,
                           resource_value='10')

    # Synchronously get the current value of the resource
    value = api.get_resource_value(devices[0].id, WRITEABLE_RESOURCE)
    print("Current value: %r" % (value, ))
Exemplo n.º 28
0
    def test_config_from_envvar(self):
        # fully define a config at a custom location
        # as well as setting config through environment
        with TempConf(dict(api_key='not this one', host=self.dummy_host)):
            os.environ.setdefault(configuration.ENVVAR_API_KEY, self.dummy_key)

            c = Config()
            self.assertEqual(self.dummy_key, c.get('api_key'))
            self.assertIn('dummy_host_url', c['host'])

            # verify custom config reaches the internal api
            a = ConnectAPI()
            self.assertIn(
                self.dummy_key,
                str(a.apis[EndpointsApi].api_client.configuration.api_key))
def _main():
    api = ConnectAPI()
    # calling start_notifications is required for getting/setting resource synchronously
    api.start_notifications()
    devices = api.list_connected_devices().data
    if not devices:
        raise Exception("No connected devices registered. Aborting")

    # Synchronously get the initial/current value of the resource
    value = api.get_resource_value(devices[0].id, BUTTON_RESOURCE)
    _current_val(value)

    # Register a subscription for new values
    api.add_resource_subscription_async(devices[0].id, BUTTON_RESOURCE, _subscription_handler)

    # Run forever
    while True:
        pass
def _main():
    api = ConnectAPI()
    api.start_notifications()
    devices = api.list_connected_devices().data
    if not devices:
        raise Exception("No connected devices registered. Aborting")

    # Synchronously get the initial/current value of the resource
    value = api.get_resource_value(devices[0].id, BUTTON_RESOURCE)

    # Register a subscription for new values
    api.set_resource_value(device_id=devices[0].id,
                           resource_path=WRITEABLE_RESOURCE,
                           resource_value='10')

    queue = api.add_resource_subscription(devices[0].id, BUTTON_RESOURCE)
    while True:
        # Print the current value
        print("Current value: %r" % (value, ))

        # Get a new value, using the subscriptions
        value = queue.get(timeout=30)