def _main(): api = ConnectAPI() devices = api.list_connected_devices().data if not devices: raise Exception("No connected devices registered. Aborting") # get list of presubscriptions presubscriptions = api.list_presubscriptions() print("List of presubscriptions: %r" % presubscriptions) device_id = devices[0].id # Get list of resources on a device resources = api.list_resources(device_id) # Get observable resource resource_uri = filter(lambda r: r.observable, resources)[0].path # Set new presubscription api.update_presubscriptions([{ "device_id": device_id, "resource_paths": [resource_uri] }]) # Subscription will be automatically set when a device with this id and resource path # will be connected # List presubscriptions presubscriptions = api.list_presubscriptions() print("List of presubscriptions after adding new presubscription: %r" % presubscriptions) # Delete presubscription api.delete_presubscriptions() presubscriptions = api.list_presubscriptions() print("List of presubscriptions after deleting all presubscriptions: %r" % presubscriptions)
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()
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() # 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 _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("")