コード例 #1
0
ファイル: common.py プロジェクト: rveshovda/pifog
def setup_aws_shadow_client(host, rootCAPath, privateKeyPath, certificatePath, device_name):
    # Configure logging
    logger = logging.getLogger("AWSIoTPythonSDK.core")
    logger.setLevel(logging.INFO)
    streamHandler = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    streamHandler.setFormatter(formatter)
    logger.addHandler(streamHandler)

    # Init AWSIoTMQTTShadowClient
    shadow = AWSIoTMQTTShadowClient(device_name + "-client")
    shadow.configureEndpoint(host, 8883)
    shadow.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

    # AWSIoTMQTTShadowClient configuration
    shadow.configureAutoReconnectBackoffTime(1, 32, 20)
    shadow.configureConnectDisconnectTimeout(10)  # 10 sec
    shadow.configureMQTTOperationTimeout(5)  # 5 sec

    #Last Will
    shadow.configureLastWill('my/things/' + device_name + '/update', '{"state":{"reported":{"connected":"false"}}}', 1)

    # Connect to AWS IoT
    shadow.connect()

    # Create a deviceShadow with persistent subscription
    client = shadow.createShadowHandlerWithName(device_name, True)

    return shadow, client
コード例 #2
0
def make_shadow():
    p = argparse.ArgumentParser()
    p.add_argument("-e",
                   "--endpoint",
                   action="store",
                   required=True,
                   dest="host",
                   help="Your AWS IoT custom endpoint")
    p.add_argument("-r",
                   "--rootCA",
                   action="store",
                   required=True,
                   dest="rootCAPath",
                   help="Root CA file path")
    p.add_argument("-c",
                   "--cert",
                   action="store",
                   dest="certificatePath",
                   help="Certificate file path")
    p.add_argument("-k",
                   "--key",
                   action="store",
                   dest="privateKeyPath",
                   help="Private key file path")
    p.add_argument("-n",
                   "--thingName",
                   action="store",
                   dest="thingName",
                   default="ExamIoTLED",
                   help="Targeted thing name")
    p.add_argument("-id",
                   "--clientId",
                   action="store",
                   dest="clientId",
                   default="examIoTLedDevice",
                   help="Targeted client id")
    a = p.parse_args()
    s = AWSIoTMQTTShadowClient(a.clientId)
    s.configureEndpoint(a.host, 8883)
    s.configureCredentials(a.rootCAPath, a.privateKeyPath, a.certificatePath)
    s.configureAutoReconnectBackoffTime(1, 32, 20)
    s.configureConnectDisconnectTimeout(10)  # 10 sec
    s.configureMQTTOperationTimeout(5)  # 5 sec
    print('Configuring last will message with the following payload ...')
    s.configureLastWill("my/things/{}/update".format(a.thingName),
                        ShadowPayload.encode(0, 0, 0, 0), 0)
    s.connect()
    return s.createShadowHandlerWithName(a.thingName, True)
コード例 #3
0
    def setup(self):
        self.log(">setup")

        mqtt_shadow_client = AWSIoTMQTTShadowClient(self.name)
        mqtt_shadow_client.disableMetricsCollection()

        # Configurations
        # For TLS mutual authentication
        mqtt_shadow_client.configureEndpoint(self.endpoint, self.mqtt_port)
        mqtt_shadow_client.configureCredentials("/tmp/rootCA.pem", "/tmp/key",
                                                "/tmp/cert")

        self._mqtt_client = mqtt_shadow_client.getMQTTConnection()
        self._mqtt_client.configureOfflinePublishQueueing(
            -1)  # Infinite offline Publish queueing
        self._mqtt_client.configureDrainingFrequency(2)  # Draining: 2 Hz
        self._mqtt_client.configureConnectDisconnectTimeout(10)  # 10 sec
        self._mqtt_client.configureMQTTOperationTimeout(5)  # 5 sec

        if self._lwt_topic:
            self.log(" setup - Setting LWT... '{}' / '{}'".format(
                self._lwt_topic, self._lwt_message))
            mqtt_shadow_client.configureLastWill(self._lwt_topic,
                                                 self._lwt_message, 1)

        if not self.connect(mqtt_shadow_client):
            return

        # Create a deviceShadow with persistent subscription
        #deviceShadowHandler = myMQTTShadowClient.createShadowHandlerWithName(client_id, True)
        #shadowCallbackContainer_Bot = shadowCallbackContainer(deviceShadowHandler)

        time.sleep(2)

        #JOBS
        self.setup_jobs_callbacks(self.name)

        #SHADOW TOPICS
        self.setup_shadow_callbacks(self.name)

        #COMMAND / REPLY PATTERN
        self._mqtt_client.subscribe("cmd/ac/{}/req".format(self.name), 0,
                                    self.handle_cmd_reply_callback)

        return
コード例 #4
0
    myAWSIoTMQTTShadowClient.configureEndpoint(host, 8883)
    myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath,
                                                  certificatePath)

# AWSIoTMQTTShadowClient configuration
myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)  # 5 sec

# Connect to AWS IoT
myAWSIoTMQTTShadowClient.connect()
bulbColor = "green"

# Confiugre last will message
JSONPayload = '{"state":{"reported":{"connected": "no"}}}'
myAWSIoTMQTTShadowClient.configureLastWill('bulb/lastwill', JSONPayload, 1)

# Create a deviceShadow with persistent subscription
deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(
    thingName, True)

# Shadow JSON schema:
#
# Name: Bot
# {
#	"state": {
#		"desired":{
#			"color": "green"
#		}
#	}
#}
コード例 #5
0
logger.addHandler(streamHandler)
'''

# Init AWSIoTMQTTShadowClient
ShadowClient = None
ShadowClient = AWSIoTMQTTShadowClient("OpenEvseGate_" + utils.randomword(10))
ShadowClient.configureEndpoint(host, 8883)
ShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTShadowClient configuration
ShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
ShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
ShadowClient.configureMQTTOperationTimeout(5)  # 5 sec
lwttopic = 'my/things/' + shadowName + '/shadow/update'
ShadowClient.configureLastWill(lwttopic,
                               '{"state":{"desired":{"iotconnected":false}}}',
                               0)

# Connect to AWS IoT
ShadowClient.connect()

# Create a deviceShadow with persistent subscription
deviceshadow = ShadowClient.createShadowHandlerWithName(shadowName, True)
evesGate = OpenEvseGateWay(deviceshadow)
deviceshadow.shadowRegisterDeltaCallback(evesGate.ShadowCallback_Delta)

###
deviceshadow.shadowUpdate('{"state":{"desired":{"iotconnected":true}}}', None,
                          5)

### RAPI thread start
コード例 #6
0
#connect to AWS

myAWSIoTMQTTShadowClient = None

#lastWillPayload = {"errorType":"Device"}
lastWillPayload = '{"errorType":"Device","deviceID":"' + thingName + '"}'

myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(thingName)
myAWSIoTMQTTShadowClient.configureEndpoint(
    "a1f18ishzwlosz-ats.iot.ap-southeast-2.amazonaws.com", 8883)
#myAWSIoTMQTTShadowClient.configureCredentials("./AmazonRootCA1.pem", "./f45483b5db-private.pem.key", "./f45483b5db-certificate.pem.crt")
myAWSIoTMQTTShadowClient.configureCredentials(
    "./AmazonRootCA1.pem", "./90b9981671-private.pem.key",
    "./90b9981671-certificate.pem.crt")
myAWSIoTMQTTShadowClient.configureLastWill("LNH_ALARM", lastWillPayload, 1)

#myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
#myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
#myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)  # 5 sec

connected = myAWSIoTMQTTShadowClient.connect(keepAliveIntervalSecond=30)
print("Connection : " + str(connected))
#MQTTClient = myAWSIoTMQTTShadowClient.getMQTTConnection()
#MQTTClient.configureOfflinePublishQueueing(10,0)
# Create a deviceShadow with persistent subscription
deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(
    thingName, True)
#print("preparing to get shadow")

# Update shadow in a loop
コード例 #7
0
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)

# For certificate based connection
shadowClient = AWSIoTMQTTShadowClient(config["clientId"])
shadowClient.configureEndpoint(config["mqttHost"], 8883)
shadowClient.configureCredentials("certs/rootCA.pem", "certs/private.key",
                                  "certs/cert.pem")

# AWSIoTMQTTShadowClient configuration
shadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
shadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
shadowClient.configureMQTTOperationTimeout(5)  # 5 sec
shadowClient.configureLastWill(config["clientId"],
                               '{"state":{"reported":{"connected":false}}}', 1)
shadowClient.connect()

mqttClient = shadowClient.getMQTTConnection()


def shadowUpdateCallback(payload, responseStatus, token):
    logger.info("Shadow Update: " + str(payload))


def shadowGetCallback(payload, responseStatus, token):
    global state

    logger.info("Shadow Get: " + json.dumps(payload))
    if responseStatus == "rejected":
        newPayload = {"state": {"desired": state, "reported": state}}