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_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.º 3
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.º 5
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)
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
Exemplo n.º 7
0
def _run_synchronized():
    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:
        # Will get the resource value for button and block the thread whilst doing it
        # See the async example for details on what the 'sync' flag does in the background.
        # Note this will raise a CloudAsyncError if something goes wrong, which we're not catching
        # here for simplicity.
        new_value = api.get_resource_value(devices[0].id, BUTTON_RESOURCE)

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

            # Save new current value
            current_value = new_value
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)
Exemplo n.º 9
0
# python 2.7.x
import time
from datetime import datetime
from time import sleep
from mbed_cloud import ConnectAPI

connect_api = ConnectAPI()

device_id = "<< Your Device ID >>"

start_time = time.time()
period = 5

while True:
    now = datetime.now().strftime("%H:%M:%S")
    resource_value = connect_api.get_resource_value(device_id, "/3200/0/5501")
    print(now + ' btn=' + resource_value)
    time.sleep(period - ((time.time() - start_time) % period))