コード例 #1
0
    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
コード例 #2
0
    def device_twin_callback(self, update_state, payload, user_context):
        log = logger.getLogger()
        log.info("Twin callback called with:")
        log.info("updateStatus: {0}".format(update_state))
        log.info("context: {0}".format(user_context))
        log.info("payload: {0}".format(payload))
        deviceState.incDesiredCount()
        log.info("Total calls confirmed: {0}\n".format(
            deviceState.getDirectCount()))

        # twin patch received
        if update_state == iothub_client.IoTHubTwinUpdateState.PARTIAL:
            params = json.loads(payload, object_pairs_hook=OrderedDict)
            propertyName = list(params)[0]
            if propertyName.upper() in self.desiredCallbackList:
                status = self.desiredCallbackList[propertyName.upper()](
                    params[propertyName])
                self.echoBackReported(propertyName, params, status)
            deviceState.patchLastTwin(payload, True)

        # full twin update received
        elif update_state == iothub_client.IoTHubTwinUpdateState.COMPLETE:
            complete = json.loads(payload, object_pairs_hook=OrderedDict)
            for desired in complete["desired"]:
                if desired != "$version" and desired in complete["reported"]:
                    if complete["desired"]["$version"] != complete["reported"][
                            desired]["desiredVersion"]:
                        if complete["reported"][desired]["value"] != complete[
                                "desired"][desired]["value"]:
                            if desired.upper() in self.desiredCallbackList:
                                status = self.desiredCallbackList[
                                    desired.upper()](
                                        complete["desired"][desired])
                                self.echoBackReported(desired,
                                                      complete["desired"],
                                                      status)
                        else:
                            status = (200, "completed")
                            self.echoBackReported(desired, complete["desired"],
                                                  status)

            deviceState.setLastTwin(payload)
コード例 #3
0
    def do_GET(self):
        if self.path.upper() == "/START" or self.path.upper() == "/":
            self.set_headers(200, "text/html; charset=utf-8")
            content = open("../content/start.html").read()

            # modify content to reflect config state
            content = content.replace(
                "{{connstr}}", configState.config["hubConnectionString"]
                if configState.config["hubConnectionString"] != "" else "")
            for key, value in configState.config["sendData"].items():
                content = content.replace("{{" + key + "Check}}",
                                          "checked" if value else "")
            content = content.replace(
                "{{interval}}",
                "5" if configState.config["telemetryInterval"] < 5 else str(
                    configState.config["telemetryInterval"]))
            content = content.replace(
                "{{debug}}", "checked" if configState.config["debug"] else "")
            content = content.replace(
                "{{simulate}}",
                "checked" if configState.config["simulateSenseHat"] else "")
            content = content.replace(
                "{{showIp}}",
                "checked" if configState.config["showIp"] else "")

            self.wfile.write(bytes(content, "utf-8"))
        elif self.path.upper() == "/STATS":
            self.set_headers(200, "text/html; charset=utf-8")
            content = open("../content/stats.html").read()

            # replace {{blah-blah-blah}} with values
            content = content.replace("{{deviceName}}", deviceState.getName())
            content = content.replace("{{firmware}}",
                                      deviceState.getFirmwareVersion())
            content = content.replace("{{deviceState}}",
                                      deviceState.getDeviceState())
            if deviceState.getDeviceState() == "NORMAL":
                color = "green"
            elif deviceState.getDeviceState() == "CAUTION":
                color = "yellow"
            elif deviceState.getDeviceState() == "DANGER":
                color = "red"
            elif deviceState.getDeviceState() == "EXTREME_DANGER":
                color = "blue"
            content = content.replace("{{deviceStateColor}}", color)
            content = content.replace("{{sent}}",
                                      str(deviceState.getSentCount()))
            content = content.replace("{{errors}}",
                                      str(deviceState.getErrorCount()))
            content = content.replace("{{desired}}",
                                      str(deviceState.getDesiredCount()))
            content = content.replace("{{reported}}",
                                      str(deviceState.getReportedCount()))
            content = content.replace("{{direct}}",
                                      str(deviceState.getDirectCount()))
            content = content.replace("{{c2d}}",
                                      str(deviceState.getC2dCount()))
            content = content.replace("{{timestamp}}",
                                      str(deviceState.getLastSend()))
            content = content.replace("{{payload}}",
                                      deviceState.getLastPayload())
            content = content.replace("{{twin}}", deviceState.getLastTwin())
            content = content.replace(
                "{{interval}}",
                str(configState.config["telemetryInterval"] * 1000))

            self.wfile.write(bytes(content, "utf-8"))
        elif self.path.upper() == "/STYLE.CSS":
            self.set_headers(200, "text/css")
            content = open("../content/style.css").read()
            self.wfile.write(bytes(content, "utf-8"))
        else:
            self.set_headers(404, "text/html; charset=utf-8")