def device_method_callback(method_name, payload, user_context): global DEVICE_METHOD_USER_CONTEXT global DEVICE_CLIENT_RESPONSE global DEVICE_METHOD_CALLBACK_COUNTER print ( "Method callback called with:" ) print ( " methodName = {0}".format(method_name) ) print ( " payload = {0}".format(payload) ) print ( " context = {0}".format(user_context) ) device_method_return_value = DeviceMethodReturnValue() if method_name == DEVICE_METHOD_NAME and user_context == DEVICE_METHOD_USER_CONTEXT: DEVICE_CLIENT_RESPONSE = DEVICE_METHOD_RESPONSE_PREFIX + "{0}".format(uuid.uuid4()) device_method_return_value.response = "{ \"Response\": \"" + DEVICE_CLIENT_RESPONSE + "\" }" device_method_return_value.status = 200 else: device_method_return_value.response = "{ \"Response\": \"\" }" device_method_return_value.status = 500 print ( "" ) DEVICE_METHOD_CALLBACK_COUNTER += 1 print ( "Total calls received: {0}".format(DEVICE_METHOD_CALLBACK_COUNTER) ) print ( "" ) DEVICE_METHOD_EVENT.set() return device_method_return_value
def device_method_callback(method_name, payload, user_context): global METHOD_CALLBACKS print ( "\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (method_name, payload, user_context) ) METHOD_CALLBACKS += 1 print ( "Total calls confirmed: %d\n" % METHOD_CALLBACKS ) device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{ \"Response\": \"This is the response from the device\" }" device_method_return_value.status = 200 return device_method_return_value
def device_method_callback(method_name, payload, user_context): global DEVICE_METHOD_USER_CONTEXT global DEVICE_CLIENT_RESPONSE print ( "\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (method_name, payload, user_context) ) device_method_return_value = DeviceMethodReturnValue() if method_name == DEVICE_METHOD_NAME and user_context == DEVICE_METHOD_USER_CONTEXT: DEVICE_CLIENT_RESPONSE = DEVICE_METHOD_RESPONSE_PREFIX + "{0}".format(uuid.uuid4()) device_method_return_value.response = "{ \"Response\": \"" + DEVICE_CLIENT_RESPONSE + "\" }" device_method_return_value.status = 200 else: device_method_return_value.response = "{ \"Response\": \"\" }" device_method_return_value.status = 500 print ( "" ) DEVICE_METHOD_EVENT.set() return device_method_return_value
def device_method_callback(method_name, payload, user_context): device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{\"Response\": \"This is the response from the device\" }" device_method_return_value.status = 200 if (method_name == "softwareUpdate"): if (globalvar.softwareVersion == 1): print("Updating software") globalvar.softwareVersion = 2 filename = '/home/pi/Desktop/project/static/css/main.css' r = requests.get("https://raw.githubusercontent.com/manchejs0/jnjDIAB/master/webPageConfig.txt") thing = str(r.content, 'utf-8') f = open(filename, 'w') f.write(thing) f.close() else: globalvar.softwareVersion = 1 print("Updating software") filename = '/home/pi/Desktop/project/static/css/main.css' r = requests.get("https://raw.githubusercontent.com/manchejs0/jnjDIAB/master/webPageConfig2.txt") thing = str(r.content, 'utf-8') f = open(filename, 'w') f.write(thing) f.close() elif (method_name == "logUpload"): logFile.upload_file(content, "helloworld", contentType, contentLength) else: pass return device_method_return_value
def device_method_callback(method_name, payload, user_context): global METHOD_CALLBACKS print( "\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (method_name, payload, user_context)) METHOD_CALLBACKS += 1 print("Total calls confirmed: %d\n" % METHOD_CALLBACKS) device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{ \"Response\": \"This is the response from the device\" }" device_method_return_value.status = 200 return device_method_return_value
def device_method_callback(method_name, payload, user_context): global INTERVAL print("\nMethod callback called with:\nmethodName = %s\npayload = %s" % (method_name, payload)) device_method_return_value = DeviceMethodReturnValue() if method_name == "SetTelemetryInterval": try: INTERVAL = int(payload) # Build and send the acknowledgment. device_method_return_value.response = "{ \"Response\": \"Executed direct method %s\" }" % method_name device_method_return_value.status = 200 except ValueError: # Build and send an error response. device_method_return_value.response = "{ \"Response\": \"Invalid parameter\" }" device_method_return_value.status = 400 else: # Build and send an error response. device_method_return_value.response = "{ \"Response\": \"Direct method not defined: %s\" }" % method_name device_method_return_value.status = 404 return device_method_return_value
def device_method_callback(method_name, payload, user_context): global MESSAGE_STATUS, myTimer, status_msg device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{\"Response\": \"OK\" }" device_method_return_value.status = 200 data = json.loads(payload) logger.info("Received event: %s", method_name) device_method_return_value.response = event_handler(method_name, data) logger.debug("Ending callback with event: %s, and response: %s", method_name, device_method_return_value.response) return device_method_return_value
def module_method_callback(method_name, payload, user_context): print( "\nMethod callback called with:\nmethodName = {}\npayload = {}".format( method_name, payload)) if ( method_name == "switch_led_on" ): #Attention: if you change the method name you've to change it also in the alexa function blink_led() retval = DeviceMethodReturnValue() retval.status = 200 retval.response = "{\"key\":\"value\"}" return retval
def method_callback(method_name, payload, user_context): global DISPLAY_MANAGER print('received method call:') print('\tmethod name:', method_name) print('\tpayload:', str(payload)) if (method_name == "ShowText"): DISPLAY_MANAGER.displayImage(str(payload)) retval = DeviceMethodReturnValue() retval.status = 200 retval.response = "{\"ShowText\":\"done\"}" return retval
def device_method_callback(method_name, payload, user_context): global DEVICE_METHOD_USER_CONTEXT global DEVICE_CLIENT_RESPONSE print( "\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (method_name, payload, user_context)) device_method_return_value = DeviceMethodReturnValue() if method_name == DEVICE_METHOD_NAME and user_context == DEVICE_METHOD_USER_CONTEXT: DEVICE_CLIENT_RESPONSE = DEVICE_METHOD_RESPONSE_PREFIX + "{0}".format( uuid.uuid4()) device_method_return_value.response = "{ \"Response\": \"" + DEVICE_CLIENT_RESPONSE + "\" }" device_method_return_value.status = 200 else: device_method_return_value.response = "{ \"Response\": \"\" }" device_method_return_value.status = 500 print("") DEVICE_METHOD_EVENT.set() return device_method_return_value
def module_method_callback(method_name, payload, hubManager): print("Received method [%s]" % (method_name)) message_str = "Module [FilterModule] is Running" heart_beat_messsage = IoTHubMessage(message_str) prop_map = heart_beat_messsage.properties() prop_map.add("MessageType", HEART_BEAT) hubManager.forward_event_to_output(HEART_BEAT, heart_beat_messsage, 0) print("Sent method response via event [%s]" % HEART_BEAT) device_method_return_value = DeviceMethodReturnValue() device_method_return_value.status = 200 device_method_return_value.response = "{ \"Response\": \"This is the response from the device\" }" return device_method_return_value
def device_method_callback(method_name, payload, user_context): global METHOD_CALLBACKS print ( "\nMethod callback called with:") print (" Method Name = %s" % method_name) print (" Payload = %s" % payload) print (" Context = %s" % user_context) METHOD_CALLBACKS += 1 print ( "Total calls confirmed: %d\n" % METHOD_CALLBACKS ) device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{ \"methodName\":\"%s\" }" % method_name device_method_return_value.status = 200 if method_name == "display_message": display_message(payload) elif method_name == "update_device": update_device() else: print ("Method not found") device_method_return_value.status = 404 return device_method_return_value
def device_method_callback(method_name, payload, user_context): if method_name == "firmwareUpdate": print("Starting firmware update.") image_url = payload thr = threading.Thread(target=simulate_download_image, args=([payload]), kwargs={}) thr.start() device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{ \"Response\": \"Firmware update started\" }" device_method_return_value.status = 200 return device_method_return_value
def method_callback(method_name, payload, user_context): global lidar, servo print('received method call:') print('\tmethod name:', method_name) print('\tpayload:', str(payload)) retval = DeviceMethodReturnValue() retval.status = 200 msg = { 'type': 'lidar', 'servo_angle': servo.angle, 'distance': lidar.measure() } retval.response = json.dumps(msg) return retval
def processcomand(self, action, payload, hardwares): try: # Action is present in list of available actions self.logger.info("try to process command") if action in self.hardware_actions: # Execute the action for device specified in payload # convert payload to object self.logger.info("initialize jason object") json_obj = json.loads(payload) self.logger.info( "creating cloudcommandpayload() class object ") cloudpayload = cloudcommandpayload(json_obj) # call the specific action self.hardware_actions[action](self, cloudpayload.hardware, hardwares) self.logger.info( "returning the status of DeviceMethodReturnValue() ") # Return the Status devicereturn = DeviceMethodReturnValue() devicereturn.response = '{ "Status": "Success","Message":"Action completed succesfully"}' devicereturn.status = 200 return devicereturn self.logger.info("return success") except: e = sys.exc_info()[0] self.logger.error("exception in processcomand() Method" + str(e)) #Raise exception event self.events.hardware_exception(e) # Return the Status devicereturn = DeviceMethodReturnValue() devicereturn.response = '{ "Status": "Failure","Message":"Action failed"}' devicereturn.status = 0 return devicereturn
def device_method_callback(method_name, payload, user_context): global METHOD_CALLBACKS print ( "\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (method_name, payload, user_context) ) METHOD_CALLBACKS += 1 print ( "Total calls confirmed: %d\n" % METHOD_CALLBACKS ) device_method_return_value = DeviceMethodReturnValue() if method_name == "ExecCmd" : jsonCommand = json.loads(payload) cmd = jsonCommand["Command"] proc = subprocess.Popen( shlex.split(cmd), stdout=subprocess.PIPE) (out, err) = proc.communicate() jsonOut = json.dumps(out) print(jsonOut) #test = os.system(payload) print("Payload: {0}".format(out)) device_method_return_value.response = jsonOut device_method_return_value.status = 200 else : device_method_return_value.response = "{ \"Response\": \"This is the response from the device\" }" device_method_return_value.status = 400 return device_method_return_value
def device_method_callback(method_name, payload, user_context): global gSendMessage print ( "\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (method_name, payload, user_context) ) device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{ \"Response\": \"This is the response from the device\" }" device_method_return_value.status = 200 if method_name == "start": gSendMessage = True print ( "Start sending message\n" ) device_method_return_value.response = "{ \"Response\": \"Successfully started\" }" return device_method_return_value if method_name == "stop": gSendMessage = False print ( "Stop sending message\n" ) device_method_return_value.response = "{ \"Response\": \"Successfully stopped\" }" return device_method_return_value return device_method_return_value
def device_method_callback(method_name, payload, user_context): global METHOD_CALLBACKS print( "\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (method_name, payload, user_context)) METHOD_CALLBACKS += 1 print("Total calls confirmed: %d\n" % METHOD_CALLBACKS) device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{ \"Response\": \"This is the response from the device\" }" device_method_return_value.status = 200 if method_name == "takeOff": print("Invoking Direct method...\n") launchMambo() device_method_return_value.response = "{ \"Response\": \"Successfully invoked direct method\" }" print("Successfully invoked direct method!") return device_method_return_value return device_method_return_value
def device_method_callback(self, method_name, payload, user_context): print( "Method callback called with: methodName = {}, payload = {}, context = {}" .format(method_name, payload, user_context)) msg = json.loads(payload) try: if method_name == 'list': response = self.hardware.list_methods() elif method_name == 'cancel': self.queue.cancel() response = "ok" else: method_payload = msg['payload'] if 'payload' in msg else {} self.queue.append("invoke_method", { "method": method_name, "payload": method_payload, }) response = "ok" status = 200 except NotImplementedError: response = 'Method not defined' status = 404 except ValueError as inst: response = inst.args status = 400 except queue.Full: response = "Too many items in queue" status = 503 except Exception as inst: response = inst.args status = 500 return_value = DeviceMethodReturnValue() return_value.status = status return_value.response = json_dumps({'Response': response}) return return_value
def device_method_callback( method_name, payload, user_context): #Hanterar mogganing av Method samt payload method = "" global METHOD_CALLBACKS print( "\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (method_name, payload, user_context)) METHOD_CALLBACKS += 1 print("Total calls confirmed: %d\n" % METHOD_CALLBACKS) if method_name == "Start": print("Starting Service") elif method_name == "Stop": print("Stopping Service") device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{ \"Response\": \"This is the response from the device\" }" device_method_return_value.status = 200 return device_method_return_value
def device_method_callback(method_name, payload, user_context): global METHOD_CALLBACKS,MESSAGE_SWITCH print ( "\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (method_name, payload, user_context) ) METHOD_CALLBACKS += 1 print ( "Total calls confirmed: %d\n" % METHOD_CALLBACKS ) device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{ \"Response\": \"This is the response from the device\" }" device_method_return_value.status = 200 if method_name == "start": MESSAGE_SWITCH = True print ( "Start sending message\n" ) device_method_return_value.response = "{ \"Response\": \"Successfully started\" }" return device_method_return_value if method_name == "stop": MESSAGE_SWITCH = False print ( "Stop sending message\n" ) device_method_return_value.response = "{ \"Response\": \"Successfully stopped\" }" return device_method_return_value return device_method_return_value
def device_method_callback(self, method_name, payload, user_context): global METHOD_CALLBACKS if method_name == "DeviceConfig": logging.debug( "Waiting for Configuration..." ) if payload is not None: print ("Payload Received: {0}".format(payload)) # Parse the Payload right here configuration = json.loads(payload) for key, value in dict.items(configuration): print("Key and Value from Azure: {0} and {1}".format(key, value)) if isinstance(value, str): if key == "predictionThreshold": self.prediction_threshold = float(value) elif key == "captureRate": self.capture_rate = float(value) elif key == "cameraResolutionLength": self.camera_res_len = int(value) elif key == "cameraResolutionWidth": self.camera_res_wid = int(value) elif key == "captureLength": self.video_capture_length = int(value) elif key == "capturePreroll": self.video_preroll = int(value) elif isinstance(value, bool): if key == "captureVideo": self.capture_video = bool(value) else: logging.debug("The value was a string") current_time = str(datetime.now().isoformat()) reported_state = "{\"rebootTime\":\"" + current_time + "\"}" CLIENT.send_reported_state(reported_state, len(reported_state), self.send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT) else: print("Another Method was called") # Azure IoT Hub Response device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{ \"Response\": \"Successful Config\" }" device_method_return_value.status = 200 return device_method_return_value
def device_method_callback(method_name, payload, user_context): global METHOD_CALLBACKS,MESSAGE_SWITCH print ( "\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (method_name, payload, user_context) ) METHOD_CALLBACKS += 1 print ( "Total calls confirmed: %d\n" % METHOD_CALLBACKS ) device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{ \"Response\": \"This is the response from the device\" }" device_method_return_value.status = 200 if method_name == "start": MESSAGE_SWITCH = True print ( "Start sending message\n" ) device_method_return_value.response = "{ \"Response\": \"Successfully started\" }" return device_method_return_value if method_name == "stop": MESSAGE_SWITCH = False print ( "Stop sending message\n" ) device_method_return_value.response = "{ \"Response\": \"Successfully stopped\" }" return device_method_return_value return device_method_return_value
def method_callback(method_name, payload, user_context): global messageSending global sense print('received method call:') print('\tmethod name:', method_name) print('\tpayload:', str(payload)) if "start" == method_name: print('\tStarting sendind measures') messageSending = True elif "stop" == method_name: print('\tStoping sendind measures') messageSending = False elif "alert" == method_name: print('\tAlert recieved') sense.show_message("Alert") else: print('\tUnknown method') retval = DeviceMethodReturnValue() retval.status = 200 retval.response = "{\"Message received\":\"value\"}" return retval
def device_method_callback(method_name, payload, user_context): method = "" method_response = "" global METHOD_CALLBACKS print( "\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (method_name, payload, user_context)) METHOD_CALLBACKS += 1 print("Total calls confirmed: %d\n" % METHOD_CALLBACKS) if method_name == "Start": startService() method_response = "Service Started" elif method_name == "Stop": stopService() method_response = "Service Stopped" device_method_return_value = DeviceMethodReturnValue() #Response to service appplication. device_method_return_value.response = "{ \"Response\": \"%s\" }" % ( method_response) device_method_return_value.status = 200 return device_method_return_value
def device_method_callback(method_name, payload, user_context): global METHOD_CALLBACKS if method_name == "rebootDevice": print("Rebooting device...") time.sleep(20) print("Device rebooted.") current_time = str(datetime.datetime.now()) reported_state = "{\"rebootTime\":\"" + current_time + "\"}" CLIENT.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT) print("Updating device twins: rebootTime") device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{ \"Response\": \"This is the response from the device\" }" device_method_return_value.status = 200 return device_method_return_value
def device_method_callback(method_name, payload, user_context): global METHOD_CALLBACKS if method_name == "LED_red": blink_red() #onDeviceMethod_red_off(payload) if method_name == "yellow_off": onDeviceMethod_yellow_off(payload) if method_name == "LED_green": onDeviceMethod_green_off(payload) print( "\n\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (method_name, payload, user_context)) METHOD_CALLBACKS += 1 print("Total calls confirmed: %d\n" % METHOD_CALLBACKS) device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{ \"Response\": \"This is the response from the device\" }" device_method_return_value.status = 200 return device_method_return_value
def device_method_callback(method_name, payload, user_context): global METHOD_CALLBACKS, MESSAGE_SWITCH, MESSAGE_COUNT, sensor, relays, logger, remoteRelay, AC_MODE print( "\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (method_name, payload, user_context)) METHOD_CALLBACKS += 1 print("Total calls confirmed: %d\n" % METHOD_CALLBACKS) device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{ \"Response\": \"This is the response from the device\" }" device_method_return_value.status = 200 if method_name == "start": MESSAGE_SWITCH = True print("Start sending message\n") device_method_return_value.response = "{ \"Response\": \"Successfully started\" }" return device_method_return_value if method_name == "stop": MESSAGE_SWITCH = False print("Stop sending message\n") device_method_return_value.response = "{ \"Response\": \"Successfully stopped\" }" return device_method_return_value if method_name == "setACmode": if 'mode' in payload: if payload['mode'] == "standby": AC_MODE = "standby" if payload['mode'] == "operating": AC_MODE == "operating" statusText = readDeviceData(sensor, relays, remoteRelay, logger) device_method_return_value.response = statusText else: device_method_return_value.response = "{ \"Response\": \"Mode change unsuccessful, bad payload\" }" return device_method_return_value if method_name == "modeSTB": AC_MODE = "standby" statusText = readDeviceData(sensor, relays, remoteRelay, logger) device_method_return_value.response = statusText return device_method_return_value if method_name == "modeOPR": AC_MODE = "operating" statusText = readDeviceData(sensor, relays, remoteRelay, logger) device_method_return_value.response = statusText return device_method_return_value if method_name == "send": print("Sending message") message = composeMessage(sensor, relays) client.send_event_async(message, send_confirmation_callback, MESSAGE_COUNT) print( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % MESSAGE_COUNT) status = client.get_send_status() print("Send status: %s" % status) MESSAGE_COUNT += 1 device_method_return_value.response = "{ \"Response\": \"Message sent\" }" if method_name == "status": statusText = readDeviceData(sensor, relays, remoteRelay, logger) device_method_return_value.response = statusText if method_name == "heatOn": print("Switching heating ON") relays.dining.on() relays.bath.on() remoteRelay.relay1On() remoteRelay.relay2On() statusText = readDeviceData(sensor, relays, remoteRelay, logger) device_method_return_value.response = statusText if method_name == "heatOff": print("Switching heating OFF") relays.dining.off() relays.bath.off() remoteRelay.relay1Off() remoteRelay.relay2Off() statusText = readDeviceData(sensor, relays, remoteRelay, logger) device_method_return_value.response = statusText if method_name == "waterOn": print("Switching water heating ON") relays.waterHeater.on() statusText = readDeviceData(sensor, relays, remoteRelay, logger) device_method_return_value.response = statusText if method_name == "waterOff": print("Switching water heating OFF") relays.waterHeater.off() statusText = readDeviceData(sensor, relays, remoteRelay, logger) device_method_return_value.response = statusText if method_name == "update": subprocess.call("/home/pi/PyIOT/update.sh") device_method_return_value.response = "{ \"Response\": \"Updating\" }" return device_method_return_value