def get_intelligence(): iot_hub = IoTHub(IOT_HUB_NAME, IOT_HUB_OWNER_KEY) devices = iot_hub.get_device_list() device_ids = [d.deviceId for d in devices] latest_predictions = table_service.query_entities('predictions', filter="PartitionKey eq '_INDEX_'") predictions_by_device = dict([(p.RowKey, (p.Prediction, p.Date)) for p in latest_predictions]) unknown_predictions = dict([(device_id, ('Unknown', None)) for device_id in device_ids if device_id not in predictions_by_device]) combined = {**predictions_by_device, **unknown_predictions} summary = { 'Failure predicted': 0, 'Healthy': 0, 'Need maintenance': 0, 'Unknown': 0 } summary_computed = collections.Counter(['Failure predicted' if v[0].startswith('F') else v[0] for v in combined.values()]) summary.update(summary_computed) payload = { 'predictions': [{ 'deviceId': k, 'prediction': v[0], 'lastUpdated': v[1] } for (k, v) in combined.items()], 'summary': summary } payload_json = json.dumps(payload) resp = Response(payload_json) resp.headers['Content-type'] = 'application/json' return resp
def get_device(device_id): iot_hub = IoTHub(IOT_HUB_NAME, IOT_HUB_OWNER_KEY) twin_data = iot_hub.get_device_twin(device_id) query_filter = "PartitionKey eq '{0}' and Code eq '{1}'".format( device_id, 'SIM_HEALTH') health_history_entities = table_service.query_entities('logs', filter=query_filter) health_history = [] for entity in health_history_entities: timestamp = entity.Timestamp message_json = json.loads(entity.Message) #indices = [x[1] for x in sorted(message_json.items())] health_history.append((timestamp, message_json)) health_history.sort() health_history_by_index = {} for entry in health_history: timestamp = entry[0].replace(tzinfo=None).isoformat() indices_json = entry[1] for k, v in indices_json.items(): if k not in health_history_by_index: health_history_by_index[k] = {'t': [], 'h': []} health_history_by_index[k]['t'].append(timestamp) health_history_by_index[k]['h'].append(v) response_json = { 'twin': json.loads(twin_data), 'health_history': health_history_by_index } resp = Response(json.dumps(response_json)) resp.headers['Content-type'] = 'application/json' return resp
def get_devices(): iot_hub = IoTHub(IOT_HUB_NAME, IOT_HUB_OWNER_KEY) devices = iot_hub.get_device_list() devices.sort(key = lambda x: x.deviceId) device_properties = json.dumps([{ 'deviceId': device.deviceId, 'lastActivityTime': device.lastActivityTime, 'connectionState':str(device.connectionState) } for device in devices]) return Response(device_properties, mimetype='application/json')
def set_desired_properties(device_id): desired_props = {} for key in request.form: if key == 'speed': desired_props[key] = int(request.form[key]) else: desired_props[key] = request.form[key] payload = {'properties': {'desired': desired_props}} payload_json = json.dumps(payload) iot_hub = IoTHub(IOT_HUB_NAME, IOT_HUB_OWNER_KEY) twin_data = iot_hub.update_twin(device_id, payload_json) resp = Response(twin_data) resp.headers['Content-type'] = 'application/json' return resp
def claim_and_run_device(driver_id): iot_hub = IoTHub(IOT_HUB_NAME, IOT_HUB_OWNER_KEY) device, device_twin = iot_hub.claim_device(driver_id) device_twin_json = json.loads(device_twin) device_id = device_twin_json['deviceId'] iothub_device = IoTHubDevice(IOT_HUB_NAME, device_id, device.primaryKey) table_service = TableService(account_name=STORAGE_ACCOUNT_NAME, account_key=STORAGE_ACCOUNT_KEY) table_service.create_table('logs', fail_on_exist=False) def report_state(state): iothub_device.send_reported_state(state) def send_telemetry(data): iothub_device.send_message(data) def log(message, code, level): level_name = logging.getLevelName(level) log_entity = { 'PartitionKey': device_id, 'RowKey': uuid.uuid4().hex, 'Level': level_name, 'Code': code, 'Message': message, '_Driver': driver_id } print(', '.join([driver_id, device_id, str(level_name), str(code), str(message)])) table_service.insert_or_replace_entity('logs', log_entity) if level == logging.CRITICAL: # disable device iot_hub.disable_device(device_id) device_simulator = SimulatorFactory.create('devices.engines.Engine', report_state, send_telemetry, log) if not device_simulator.initialize(device_twin_json): return def device_twin_callback(update_state, payload, user_context): device_simulator.on_update(str(update_state), json.loads(payload)) iothub_device.client.set_device_twin_callback(device_twin_callback, 0) device_simulator.run()
def create_device(): device_id = str.strip(request.form['deviceId']) if not device_id: return error_response('INVALID_ID', 'Device ID cannot be empty.', HTTPStatus.BAD_REQUEST) try: simulation_properties = json.loads(request.form['simulationProperties']) except Exception as e: return error_response('INVALID_PARAMETERS', str(e), HTTPStatus.BAD_REQUEST) iot_hub = IoTHub(IOT_HUB_NAME, IOT_HUB_OWNER_KEY) try: iot_hub.create_device(device_id) except Exception as e: return error_response('INVALID_ID', str(e), HTTPStatus.BAD_REQUEST) tags = { 'simulated': True } tags.update(simulation_properties) twin_properties = { 'tags': tags } try: iot_hub.update_twin(device_id, json.dumps(twin_properties)) except Exception as e: return error_response('INVALID_PARAMETERS', str(e), HTTPStatus.BAD_REQUEST) return Response()
iot_hub.create_device(device_id) tags = {'simulated': True} tags.update(simulation_parameters) twin_properties = {'tags': tags} iot_hub.update_twin(device_id, json.dumps(twin_properties)) if __name__ == "__main__": IOT_HUB_NAME = os.environ['IOT_HUB_NAME'] IOT_HUB_OWNER_KEY = os.environ['IOT_HUB_OWNER_KEY'] iot_hub = IoTHub(IOT_HUB_NAME, IOT_HUB_OWNER_KEY) count = 5 for i in range(count): device_id = 'Machine-{0:03d}'.format(i) h1 = random.uniform(0.8, 0.95) h2 = random.uniform(0.8, 0.95) simulation_parameters = { 'simulator': 'devices.engines.Engine', 'h1': h1, 'h2': h2 } create_device(iot_hub, device_id, simulation_parameters)
def delete_device(device_id): iot_hub = IoTHub(IOT_HUB_NAME, IOT_HUB_OWNER_KEY) iot_hub.delete_device(device_id) resp = Response() return resp