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 _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 _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
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(arguments): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("api_key", help="Mbed Cloud API Key") parser.add_argument("device_id", help="Device ID") parser.add_argument("-H", "--host", help="Mbed Cloud API URL", default="https://api.us-east-1.mbedcloud.com") args = parser.parse_args(arguments) connect_api = ConnectAPI({"api_key": args.api_key, "host": args.host}) connect_api.start_notifications() connect_api.add_resource_subscription_async(args.device_id, "/3200/0/5501", _subscription_handler) 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)
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"))
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
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