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()
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() 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 _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 _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
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)
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)
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)
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 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]
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 _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() 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("http://python.requestcatcher.com/") time.sleep(2) api.add_resource_subscription(devices[0].id, BUTTON_RESOURCE) while True: print("Webhook registered. Listening to button updates for 10 seconds...") time.sleep(10) break api.delete_webhook() print("Deregistered and unsubscribed from all resources. Exiting.")
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(): 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, ))
def _main(): api = ConnectAPI() api.start_notifications() devices = api.list_connected_devices().data if not devices: raise Exception("No connected devices registered. Aborting") device_id = "015e9a938ff100000000000100100019" api.delete_device_subscriptions(device_id) api.list_presubscriptions() api.add_resource_subscription_async(device_id, INCRIMENTAL_RESOURCE, _callback_fn) api.add_resource_subscription_async(device_id, VOLTAGE_RESOURCE, _callback_fn) api.add_resource_subscription_async(device_id, CURRENT_RESOURCE, _callback_fn) api.add_resource_subscription_async(device_id, POWER_RESOURCE, _callback_fn) while True: time.sleep(0.1)
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)
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("")
def _run_async(): api = ConnectAPI() api.start_notifications() devices = api.list_connected_devices().data if not devices: raise Exception("No devices registered. Aborting") gyro_cur = acceler_cur = None while True: gyro_resp = api.get_resource_value_async(devices[0].id, GYRO_RESOURCE) acceler_resp = api.get_resource_value_async(devices[0].id, ACCELERO_RESOURCE) # Busy wait - block the thread and wait for the response to finish. while not gyro_resp.is_done: time.sleep(0.1) while not acceler_resp.is_done: time.sleep(0.1) # Check if we have a async error response, and abort if it is. if gyro_resp.error: continue raise Exception("Got async error response: %r" % gyro_resp.error) if acceler_resp.error: continue raise Exception("Got async error response: %r" % acceler_resp.error) # Get the value from the async response, as we know it's done and it's not # an error. gyro_new_value = gyro_resp.value acceler_new_value = acceler_resp.value # Print new value to user, if it has changed. if gyro_cur != gyro_new_value and acceler_cur != acceler_new_value: current_time = datetime.datetime.now() timestamp = current_time.strftime("%Y-%m-%d %H-%M-%S-%f") hour = current_time.hour minutes = current_time.minute seconds = current_time.second microsecond = current_time.microsecond accX, accY, accZ = acceler_new_value.values() accX, accY, accZ = (float(accX) / 1000), (float(accY) / 1000), (float(accZ) / 1000) gyroX, gyroY, gyroZ = gyro_new_value.values() gyroX, gyroY, gyroZ = ((float(gyroX) / 1000) * (pi / 180)), ((float(gyroY) / 1000) * (pi / 180)), ( (float(gyroZ) / 1000) * (pi / 180)) # pred = clf.predict([[accX, accY, accZ, gyroX, gyroY, gyroZ, hour, minutes, seconds, microsecond]]) start = time.time() pred = clf.predict([[accX, accY, accZ, gyroX, gyroY, gyroZ]]) stop = time.time() print(f"classifying time: {stop - start}") # print(accX, accY, accZ) # print(gyroX, gyroY, gyroZ) # print("gyro {}".format(gyro_new_value)) # print("accelero{}".format(acceler_new_value)) if pred[0] == 0: classification = 'walking' else: classification = 'running' with conn.cursor() as cursor: cursor.execute(add_row, (timestamp, classification)) if classification == 'walking': cursor.execute(add_walking) else: cursor.execute(add_running) conn.commit() print(classification) print("row added") # Save new current value gyro_cur = gyro_new_value acceler_cur = acceler_new_value
import os import pprint from mbed_cloud import ConnectAPI TOKEN = "YOUR_ACCESS_KEY" # set up the Python SDK config = {} config['api_key'] = os.getenv('TOKEN') or TOKEN config['host'] = 'https://api.us-east-1.mbedcloud.com' api = ConnectAPI(config) api.start_notifications() devices = list(api.list_connected_devices(filters={'device_type': 'default'})) print("Found %d devices" % (len(devices)), [c.id for c in devices]) for device in devices: def pir_callback(device_id, path, distance): print("Distance changed at %s, new value is %s" % (device_id, distance)) api.add_resource_subscription_async(device.id, '/3330/0/5700', pir_callback) print("subscribed to resource") api.execute_resource(device.id, '/3201/0/5850', '1') print("blinked LED of %s" % device.id) # Run forever