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 INTERVAL global initialized global on_or_off print("\nMethod callback called with:\nmethodName = %s\npayload = %s" % (method_name, payload)) device_method_return_value = DeviceMethodReturnValue() if method_name == "lockDoor": try: INTERVAL = int(payload) # Build and send the acknowledgment. if not initialized: device_method_return_value.response = "{ \"Response\": \"Could not initialize GrovePi\" }" device_method_return_value.status = 500 else: on_or_off = not on_or_off digitalWrite(PIN, on_or_off) device_method_return_value.response = "{{ \"Response\": \"Executed direct method {}, {}, {}\" }}".format( method_name, initialized, on_or_off) 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(self, method_name, payload, user_context): log = logger.getLogger() log.info( "\nMethod callback called with:\nmethodName = {0}\npayload = {1}\ncontext = {2}" .format(method_name, payload, user_context)) deviceState.incDirectCount() log.info("Total calls confirmed: {0}".format( deviceState.getDirectCount())) # message format expected: # { # "methodName": "reboot", # "responseTimeoutInSeconds": 200, # "payload": { # "input1": "someInput", # "input2": "anotherInput" # ... # } # } # lookup if the method has been registered to a function response = None if method_name.upper() in self.methodCallbackList: params = json.loads(payload) response = self.methodCallbackList[method_name.upper()](params) device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{ \"Response\": \"" + response[ 1] + "\" }" device_method_return_value.status = response[0] return device_method_return_value
def device_method_callback(method_name, payload, user_context): global METHOD_CALLBACKS METHOD_CALLBACKS += 1 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 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): if method_name == "CreateSnapshot": with create_snapshot() as stream: request = requests.post(config['apiUrl'], data=stream) 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 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 method_callback(self, method_name, payload, user_context): print("\nCallback method is called: \nMethodName = %s\nPayload = %s" % (method_name, payload)) method_return_value = DeviceMethodReturnValue() result = self.command_manager(method_name) method_return_value.response = "{ \"Response\": \" %s is executed\" }" % method_name method_return_value.status = 200 return 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 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 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 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): 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 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 == "SetLED": try: #INTERVAL = int(payload) if (int(payload) == 1): grovepi.chainableRgbLed_test(pin, numleds, testColorWhite) time.sleep(1) elif (int(payload) == 0): grovepi.chainableRgbLed_test(pin, numleds, testColorBlack) time.sleep(1) # 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 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 __init__(self, log): #Init variables self.isrunning = False self.logger = log self.events = cloudevents() self.device_method_return_value = DeviceMethodReturnValue()
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, MESSAGE_SWITCH, CARS_COUNT 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 == "cars": print("Readings cars\n") device_method_return_value.response = "{ \"Response\": %d }" % CARS_COUNT 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 __init__(self,log): #Init variables self.isrunning = False self.logger = log self.events = cloudevents() self.device_method_return_value = DeviceMethodReturnValue() self.sbs = ServiceBusService('dev-sw-evhb',shared_access_key_name='sender',shared_access_key_value='3B+Q02HNLYHGtBE9QtET2f3temGWtkL/CmDT5Fy/ldU=') self.block_blob_service = BlockBlobService(account_name='devschoolwayzdatastorage', account_key='4+z+7pEC7FQJNEe+UIX+4PRDrqaHWTTDeTXaGOPPqnZGKJRTpi0IDaHhgZLKviC+5HQZKo1H5ZQzMmllIRZjdg==')
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): 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( 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(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 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): 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, 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 if method_name == "TakeVideo": take_video() if method_name == "TakePicture": take_picture() if method_name == "TakeTempHumidity": take_temp_humidity() if method_name == "TakeInternalTemp": read_internal_temp() 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): 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 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