def test_awsiotmqtt_shadow_client_connect(mock_connect, mock_disconnect):
    client = AWSIoTMQTTShadowClient("myClientID",
                                    useWebsocket=False,
                                    hostName="YOUR.ENDPOINT",
                                    portNumber=8883)
    with client:
        client.createShadowHandlerWithName("Bot", True)
    mock_connect.assert_called_once_with(600)
    mock_disconnect.assert_called_once_with()
class IoTCommunicator(object):
    def __init__(self, device):
        self.mqttc = AWSIoTMQTTShadowClient(thingName)
        self.mqttc.configureEndpoint(
            'a2soq6ydozn6i0-ats.iot.us-west-2.amazonaws.com', 8883)
        self.mqttc.configureCredentials(
            './certificates/AmazonRootCA1.pem',
            './certificates/' + thingName + '.private.key',
            './certificates/' + thingName + '.cert.pem')
        self.mqttc.configureConnectDisconnectTimeout(10)
        self.mqttc.configureMQTTOperationTimeout(5)
        self.device_shadow = self.mqttc.createShadowHandlerWithName(
            thingName, True)
        self.device_shadow = self.mqttc.createShadowHandlerWithName(
            thingName, True)
        self.device_shadow.on_message = self.on_message
        self.device_shadow.json_encode = self.json_encode
        self.device = device

    def json_encode(self, string):
        return json.dumps(string)

    def on_message(self, message, response, token):
        print(message)

    def on_delta(self, message, response, token):
        print("delta %s" % message)
        loaded_message = json.loads(message)
        new_state = loaded_message["state"]["state"]
        self.device.set_light(new_state)
        self.send_shadow_update()

    def start_communication(self):
        print("About to connect")
        self.mqttc.connect()
        print('Connected')
        self.device_shadow.shadowRegisterDeltaCallback(self.on_delta)

        loop_count = 0
        while True:
            self.send_shadow_update()
            loop_count += 1
            time.sleep(5)

    def send_shadow_update(self):
        message = {"state": {"reported": {"state": self.device.light_state}}}
        message_json = json.dumps(message)
        self.device_shadow.shadowUpdate(message_json, self.on_message, 5)
        print('Shadow Update Sent')
        print('Published state %s\n' % message_json)
Ejemplo n.º 3
0
def update_shadow(endpoint, thingName, kinesisStreamName, rootCAPath):

    port = 8883

    certificatePath = "./principals/" + thingName + ".cert.pem"
    privateKeyPath = "./principals/" + thingName + ".private.key"

    clientId = thingName

    myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
    myAWSIoTMQTTShadowClient.configureEndpoint(endpoint, port)
    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()

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

    # Delete shadow JSON doc
    deviceShadowHandler.shadowDelete(customShadowCallback_Delete, 5)

    JSONPayload = '{"state":{"desired":{"property": "iot-analyzer"}}}'
    deviceShadowHandler.shadowUpdate(JSONPayload, customShadowCallback_Update, 5)

    JSONPayload = '{"state":{"reported":{"property": "iot-analyzer", "kinesis_stream": "' + kinesisStreamName + '"}}}'
    deviceShadowHandler.shadowUpdate(JSONPayload, customShadowCallback_Update, 5)
Ejemplo n.º 4
0
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
Ejemplo n.º 5
0
def main():
    setupPins()
    # For certificate based connection
    myShadowClient = AWSIoTMQTTShadowClient(os.environ['AWS_CLIENT_ID'])
    # For Websocket connection
    # myShadowClient = AWSIoTMQTTClient("myClientID", useWebsocket=True)
    # Configurations
    # For TLS mutual authentication
    myShadowClient.configureEndpoint(os.environ['AWS_ENDPOINT'], 8883)
    # For Websocket
    # myShadowClient.configureEndpoint("YOUR.ENDPOINT", 443)
    myShadowClient.configureCredentials(os.environ['AWS_ROOTCA'], os.environ['AWS_PRIVATE_KEY'], os.environ['AWS_CERTIFICATE'])
    # For Websocket, we only need to configure the root CA
    # myShadowClient.configureCredentials("YOUR/ROOT/CA/PATH")
    myShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
    myShadowClient.configureMQTTOperationTimeout(5)  # 5 sec

    myShadowClient.connect()
    # Create a device shadow instance using persistent subscription
    Bot = myShadowClient.createShadowHandlerWithName("Bot", True)

    # Delete shadow JSON doc
    Bot.shadowDelete(customShadowCallback_Delete, 5)

    # PUT ALL your code for handling buttons and such in here.
    while True:
        input_state = GPIO.input(17)
        if input_state == True:
            print('Button Pressed')
            JSONPayload = '{"state":{"desired":{"property":"' + str(os.environ['WEBCAM_LINK']) + '"}}}'
            print JSONPayload
            Bot.shadowUpdate(JSONPayload, customShadowCallback_Update, 5)
       	    time.sleep(1)
	time.sleep(0.2)
def AWS_SHADOW_Initialize():  #TODO Test this
    try:
        subprocess.call('./copyCertificates.sh')
    except:
        CA_CERTIFICATE = "Certificates/root-CA.crt"
        PRIVATE_KEY = "Certificates/device-private.pem.key"
        DEVICE_CERTIFICATE = "Certificates/device-certificate.pem.crt"
    # AWS IoT certificate based connection---------------------------------------
    myShadowClient = AWSIoTMQTTShadowClient(
        CLIENT)  #this can be any arbitrary string
    myShadowClient.configureEndpoint(AWS_SERVER,
                                     PORT)  #endpoint and port number
    myShadowClient.configureCredentials(
        CA_CERTIFICATE, PRIVATE_KEY, DEVICE_CERTIFICATE
    )  #root ca and certificate used for secure connection

    myShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
    myShadowClient.configureMQTTOperationTimeout(5)  # 5 sec

    #connect, subscribe and publish----------------------------------------------------------
    myShadowClient.connect()
    shadowHandler = myShadowClient.createShadowHandlerWithName(
        THING_NAME, True)
    myMQTTClient = myShadowClient.getMQTTConnection()
    AWS_MQTT_subscribe(myMQTTClient, None)
    return (shadowHandler, myMQTTClient)
Ejemplo n.º 7
0
    def _iotConnect(self, endpoint, thingName, rootCAPath, certificatePath,
                    privateKeyPath, region):
        ''' Establish connection to the AWS IOT service '''
        # Init AWSIoTMQTTShadowClient
        myAWSIoTMQTTShadowClient = None
        myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient('pyASHdenTV')
        myAWSIoTMQTTShadowClient.configureEndpoint(endpoint, 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()

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

        # Delete shadow JSON doc
        deviceShadowHandler.shadowDelete(self._deleteCallback, 5)

        # Listen on deltas
        deviceShadowHandler.shadowRegisterDeltaCallback(self._deltaCallback)

        return deviceShadowHandler
Ejemplo n.º 8
0
def main():
    try:
        config = readConfigFile()

        awsShadowClient = AWSIoTMQTTShadowClient(clientId)
        awsShadowClient.configureEndpoint(host, 8883)
        awsShadowClient.configureCredentials(rootCAPath, privateKeyPath,
                                             certificatePath)

        awsShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
        awsShadowClient.configureConnectDisconnectTimeout(10)
        awsShadowClient.configureMQTTOperationTimeout(5)

        awsShadowClient.connect()
        deviceShadowHandler = awsShadowClient.createShadowHandlerWithName(
            thingName, True)
        deviceShadowHandler.shadowDelete(customShadowCallback_Delete, 5)

        client.begin()
        if config is not None:
            sendConfigData(config, None)
        while True:
            config = loop(config, deviceShadowHandler)
    except (KeyboardInterrupt):
        print('Interrupt received')
    except (RuntimeError):
        print('Snap! Bye Bye')
    finally:
        cleanup(config)
 def __init__(self,
              host,
              rootCAPath,
              certPath,
              privateKeyPath,
              clientId,
              deviceName,
              port=8883,
              useWebsocket=False):
     super().__init__(host, rootCAPath, certPath, privateKeyPath, clientId,
                      port, useWebsocket)
     __shadow = AWSIoTMQTTShadowClient(self.clientId)
     __shadow.configureEndpoint(self.host,
                                self.port)  # Setting URL-ENDPOINT & Port
     __shadow.configureCredentials(
         self.rootCAPath, self.privateKeyPath,
         self.certificatePath)  # Cert file setting
     __shadow.configureConnectDisconnectTimeout(
         10)  # CONNACK wait time (sec)
     __shadow.configureMQTTOperationTimeout(5)  # QoS1 publish (sec)
     print('start connct shadow')
     __shadow.connect()
     print('shadow connect')
     self.shadowHandler = __shadow.createShadowHandlerWithName(
         deviceName, True)
     return
Ejemplo n.º 10
0
def main():

    endpoint = os.environ.get("IOT_ENDPOINT", None)
    thing_name = os.environ.get("THING_NAME", None)
    ble_address = os.environ.get("BLE_ADDRESS", None)
    pretend = os.environ.get("BLE_PRETEND", "false").lower() == "true"

    if endpoint is None:
        raise Exception("IOT_ENDPOINT env not set")
    if thing_name is None:
        raise Exception("THING_NAME env not set")
    if ble_address is None:
        raise Exception("BLE_ADDRESS env not set")

    ble = sertaBLEController(ble_address, pretend)

    client = AWSIoTMQTTShadowClient(thing_name)
    client.configureEndpoint(endpoint, 8883)
    client.configureCredentials("root-CA.crt", "device-key.pem", "device.pem")

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

    client.connect()

    shadow = client.createShadowHandlerWithName(thing_name, True)
    shadowCallbackContainer_IoTBed = shadowCallbackContainer(shadow, ble)
    shadow.shadowRegisterDeltaCallback(
        shadowCallbackContainer_IoTBed.customShadowCallback_Delta)

    # Loop forever
    while True:
        time.sleep(0.1)
Ejemplo n.º 11
0
class DeviceShadowClient(object):
    def __init__(self, deviceName):
        self.clientId = deviceName
        self.rootCAPath = "devices/config/root-CA.crt"
        self.privateKeyPath = "devices/config/" + deviceName + ".private.key"
        self.certificatePath = "devices/config/" + deviceName + ".cert.pem"
        self.host = "a3w259c8e2kscd-ats.iot.us-east-1.amazonaws.com"
        self.port = 8883

        self.shadowClient = AWSIoTMQTTShadowClient(self.clientId)
        self.shadowClient.configureEndpoint(self.host, self.port)
        self.shadowClient.configureCredentials(self.rootCAPath,
                                               self.privateKeyPath,
                                               self.certificatePath)

        self.shadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
        self.shadowClient.configureConnectDisconnectTimeout(10)
        self.shadowClient.configureMQTTOperationTimeout(5)

        self.shadowClient.connect()

        self.handler = self.shadowClient.createShadowHandlerWithName(
            self.clientId, True)

    def updateShadow(self, jsonPayload):
        self.handler.shadowUpdate(jsonPayload, onResponse, 5)

    def getShadow(self, callback):
        self.handler.shadowGet(callback, 5)
Ejemplo n.º 12
0
def init_device_shadow_handler(args):
    host = args.get("host")
    rootCAPath = args.get("rootCAPath")
    certificatePath = args.get("certificatePath")
    privateKeyPath = args.get("privateKeyPath")
    port = args.get("port")
    useWebsocket = args.get("useWebsocket")
    thingName = args.get("thingName")
    clientId = args.get("clientId")

    if not clientId:  # Use thingName as clientId if not provided separately
        clientId = thingName

    if useWebsocket and certificatePath and privateKeyPath:
        print(
            "X.509 cert authentication and WebSocket are mutual exclusive. Please pick one."
        )
        exit(2)

    if not useWebsocket and (not certificatePath or not privateKeyPath):
        print("Missing credentials for authentication.")
        exit(2)

    # Port defaults
    if useWebsocket and not port:  # When no port override for WebSocket, default to 443
        port = 443
    if not useWebsocket and not port:  # When no port override for non-WebSocket, default to 8883
        port = 8883

    # Init AWSIoTMQTTShadowClient
    myAWSIoTMQTTShadowClient = None
    if useWebsocket:
        myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId,
                                                          useWebsocket=True)
        myAWSIoTMQTTShadowClient.configureEndpoint(host, port)
        myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath)
    else:
        myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
        myAWSIoTMQTTShadowClient.configureEndpoint(host, port)
        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()

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

    # Delete existing shadow JSON doc
    deviceShadowHandler.shadowDelete(shadow_delete_callback, 5)

    return deviceShadowHandler
Ejemplo n.º 13
0
def makeAWSConnections():
	global myAWSIoTMQTTClient, myAWSIoTMQTTShadowClient, deviceShadowHandler, myAWSIoTMQTTClientVibration, \
		myAWSIoTMQTTShadowClientVibration, myAWSIoTMQTTClientLoad, myAWSIoTMQTTShadowClientLoad, \
		myAWSIoTMQTTClientTemp, myAWSIoTMQTTShadowClientTemp, myOnOfflineCallback, myOnOnlineCallback, batteryStatus
	
	myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId, useWebsocket=True)
	myAWSIoTMQTTShadowClient.configureEndpoint(host, 443)
	myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath)
	# AWSIoTMQTTShadowClient configuration
	myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
	myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
	myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)  # 5 sec
	myAWSIoTMQTTShadowClient.onOffline = myOnOfflineCallback
	myAWSIoTMQTTShadowClient.onOnline = myOnOnlineCallback
	# Connect and subscribe to AWS IoT
	myAWSIoTMQTTShadowClient.connect(60)
	myAWSIoTMQTTClient = myAWSIoTMQTTShadowClient.getMQTTConnection()
	
	
	myAWSIoTMQTTShadowClientVibration = AWSIoTMQTTShadowClient(clientId + "Vibration", useWebsocket=True)
	myAWSIoTMQTTShadowClientVibration.configureEndpoint(host, 443)
	myAWSIoTMQTTShadowClientVibration.configureCredentials(rootCAPath)
	# AWSIoTMQTTShadowClient configuration
	myAWSIoTMQTTShadowClientVibration.configureAutoReconnectBackoffTime(1, 32, 20)
	myAWSIoTMQTTShadowClientVibration.configureConnectDisconnectTimeout(10)  # 10 sec
	myAWSIoTMQTTShadowClientVibration.configureMQTTOperationTimeout(5)  # 5 sec
	# Connect and subscribe to AWS IoT
	myAWSIoTMQTTShadowClientVibration.connect(60)
	myAWSIoTMQTTClientVibration = myAWSIoTMQTTShadowClientVibration.getMQTTConnection()
	
	
	myAWSIoTMQTTShadowClientLoad = AWSIoTMQTTShadowClient(clientId + "Load", useWebsocket=True)
	myAWSIoTMQTTShadowClientLoad.configureEndpoint(host, 443)
	myAWSIoTMQTTShadowClientLoad.configureCredentials(rootCAPath)
	# AWSIoTMQTTShadowClient configuration
	myAWSIoTMQTTShadowClientLoad.configureAutoReconnectBackoffTime(1, 32, 20)
	myAWSIoTMQTTShadowClientLoad.configureConnectDisconnectTimeout(10)  # 10 sec
	myAWSIoTMQTTShadowClientLoad.configureMQTTOperationTimeout(5)  # 5 sec
	# Connect and subscribe to AWS IoT
	myAWSIoTMQTTShadowClientLoad.connect(60)
	myAWSIoTMQTTClientLoad = myAWSIoTMQTTShadowClientLoad.getMQTTConnection()
	
	
	myAWSIoTMQTTShadowClientTemp = AWSIoTMQTTShadowClient(clientId + "Temp", useWebsocket=True)
	myAWSIoTMQTTShadowClientTemp.configureEndpoint(host, 443)
	myAWSIoTMQTTShadowClientTemp.configureCredentials(rootCAPath)
	
	# AWSIoTMQTTShadowClient configuration
	myAWSIoTMQTTShadowClientTemp.configureAutoReconnectBackoffTime(1, 32, 20)
	myAWSIoTMQTTShadowClientTemp.configureConnectDisconnectTimeout(10)  # 10 sec
	myAWSIoTMQTTShadowClientTemp.configureMQTTOperationTimeout(5)  # 5 sec
	# Connect and subscribe to AWS IoT
	myAWSIoTMQTTShadowClientTemp.connect(60)
	myAWSIoTMQTTClientTemp = myAWSIoTMQTTShadowClientTemp.getMQTTConnection()
	
	# Create a deviceShadow with persistent subscription
	deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName("aircraftEngine", True)
	deviceShadowHandler.shadowUpdate(json.dumps(shadowObject), customShadowCallback_Update, 5) # 5 sec
	deviceShadowHandler.shadowRegisterDeltaCallback(customShadowCallback_Delta) # Updates motor thrust
Ejemplo n.º 14
0
class shadowClient:
    def __init__(self, certDir, logLevel=logging.WARNING, clientID=None):

        if clientID == None:
            clientID = platform.node() + '.' + str(os.getpid())

        self.clientID = clientID

        self.client = AWSIoTMQTTShadowClient(clientID)

        self.configureLogging(logLevel)

        self.configureConnection(certDir)

    def configureConnection(self, certDir):

        configPath = uniqglob(certDir + '*config.json')
        with open(configPath) as json_data:
            endpoint = json.load(json_data)

            port = 8883

            if 'host' in endpoint:
                host = endpoint['host']
            else:
                sys.exit("host not defined in %s" % (configPath))

            if 'port' in endpoint:
                port = int(endpoint['port'])

            self.client.configureEndpoint(host, port)

        rootCAPath = uniqglob(certDir + '*rootCA*')
        prvKeyPath = uniqglob(certDir + '*.private.key*')
        certPath = uniqglob(certDir + '*.cert.*')

        self.client.configureCredentials(rootCAPath, prvKeyPath, certPath)

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

    def configureLogging(self, logLevel):
        logger = logging.getLogger('AWSIoTPythonSDK.core')
        logger.setLevel(logLevel)

        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        streamHandler = logging.StreamHandler()
        streamHandler.setFormatter(formatter)
        logger.addHandler(streamHandler)

    def connect(self):
        return self.client.connect()

    def createShadow(self, name):
        isPersistent = True  # for better performance (?!)
        return self.client.createShadowHandlerWithName(name, isPersistent)
def lambda_handler(event, context):
    global myAWSIoTMQTTShadowClient, myDeviceShadow
    """ Route the incoming request based on type (LaunchRequest, IntentRequest,
    etc.) The JSON body of the request is provided in the event parameter.
    """
    #print ('RECEIVED EVENT: ' + json.dumps(event, separators=(',', ':')))
    if 'session' in event:
        print("event.session.application.applicationId=" +
              event['session']['application']['applicationId'])
        """
        Uncomment this if statement and populate with your skill's application ID to
        prevent someone else from configuring a skill that sends requests to this
        function.
        """
        # if (event['session']['application']['applicationId'] !=
        #     "amzn1.ask.skill.b2d37e60-ecae-4beb-aed0-adf69fe456a4"):
        #     raise ValueError("Invalid Application ID")
        if event['session']['new'] and 'requestId' in event['request']:
            on_session_started({'requestId': event['request']['requestId']},
                               event['session'])
        if 'request' in event:
            # Init AWSIoTMQTTClient
            myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(
                shadowName + "_Lambda_" + event['request']['requestId'][-12:])
            myAWSIoTMQTTShadowClient.configureEndpoint(host, 8883)
            myAWSIoTMQTTShadowClient.configureCredentials(
                rootCAPath, privateKeyPath, certificatePath)

            # AWSIoTMQTTClient connection configuration
            myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(
                1, 32, 20)
            myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(
                10)  # 10 sec
            myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)  # 5 sec
            # Connect to AWS IoT Shadow
            myAWSIoTMQTTShadowClient.connect()
            myDeviceShadow = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(
                shadowName, True)
            myDeviceShadow.shadowGet(IoTShadowCallback_Get, 5)
            # JSONPayload = '{ "state" : {'+\
            # '"desired": {'+\
            # '"LivingRoomLight":"", '+\
            # '"BedRoomLight": "", '+\
            # '"KitchenLight": "" '+\
            # '} '+\
            # '} '+\
            # '}'
            # myDeviceShadow.shadowUpdate(JSONPayload, IoTShadowCallback_Update, 5)
            while GetStatus == "":
                ready = ""
            if event['request']['type'] == "LaunchRequest":
                return on_launch(event['request'], event['session'])
            elif event['request']['type'] == "IntentRequest":
                return on_intent(event['request'], event['session'])
            elif event['request']['type'] == "SessionEndedRequest":
                return on_session_ended(event['request'], event['session'])
Ejemplo n.º 16
0
def connectTurbineIoTAttempt(ep, port, rootca, key, cert, timeoutSec,
                             retryLimit):
    global awsIoTMQTTClient, awsShadowClient, turbineDeviceShadow

    awsShadowClient = AWSIoTMQTTShadowClient(cfgThingName)
    awsShadowClient.configureEndpoint(ep, int(port))
    awsShadowClient.configureCredentials(rootca, key, cert)
    awsIoTMQTTClient = awsShadowClient.getMQTTConnection()

    # AWSIoTMQTTClient connection configuration
    awsIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
    awsIoTMQTTClient.configureOfflinePublishQueueing(
        -1)  # Infinite offline Publish queueing
    awsIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
    awsIoTMQTTClient.configureConnectDisconnectTimeout(timeoutSec)  #seconds
    awsIoTMQTTClient.configureMQTTOperationTimeout(timeoutSec)  #seconds
    awsIoTMQTTClient.configureConnectDisconnectTimeout(timeoutSec)
    awsIoTMQTTClient.configureMQTTOperationTimeout(timeoutSec)
    awsIoTMQTTClient.onOnline = awsIoTClientOnConnectCallback
    awsIoTMQTTClient.onOffline = awsIoTClientOnDisconnectCallback

    # Attempt to connect
    for attempt in range(0, retryLimit):
        try:
            awsIoTMQTTClient.connect()
        except Exception as e:
            print(str(e))
            continue
        break

    # Shadow config
    awsShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
    awsShadowClient.configureConnectDisconnectTimeout(timeoutSec)
    awsShadowClient.configureMQTTOperationTimeout(timeoutSec)

    for attempt in range(0, retryLimit):
        try:
            if awsShadowClient.connect():
                print("AWS IoT shadow topic subscribed")
        except Exception as e:
            print(str(e))
            continue
        break

    turbineDeviceShadow = awsShadowClient.createShadowHandlerWithName(
        cfgThingName, True)
    turbineDeviceShadow.shadowRegisterDeltaCallback(shadowCallbackDelta)

    # Subscribe to the command topics
    cmdTopic = str("cmd/windfarm/turbine/" + cfgThingName + "/#")
    awsIoTMQTTClient.subscribe(cmdTopic, 1, customCallbackCmd)
    print("AWS IoT Command Topic Subscribed: " + cmdTopic)

    return True
Ejemplo n.º 17
0
	def connection_AWS_IOT(self):
		shadow_host = "a1wxijaxbxg469.iot.ap-northeast-2.amazonaws.com"
		myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(pfc_conf.PFC_AWS_IOT_CLIENT_ID)
		myAWSIoTMQTTShadowClient.configureEndpoint(shadow_host, 8883)
		myAWSIoTMQTTShadowClient.configureCredentials(pfc_conf.CA_PATH, pfc_conf.PRIVATE_KEY_PATH, pfc_conf.CERTIFICATE_PATH)
		myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(30)
		myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(30)
		myAWSIoTMQTTShadowClient.connect()
		mc = myAWSIoTMQTTShadowClient.getMQTTConnection()
		mc.configureOfflinePublishQueueing(-1)
		self.IOT_SHADOW_CLIENT = myAWSIoTMQTTShadowClient
		self.PFC_SHADOW = myAWSIoTMQTTShadowClient.createShadowHandlerWithName("PFC_v_0001", True)
Ejemplo n.º 18
0
def start():
    print("Connecting IoT, endpoint:" + str(config.iot_endpoint))
    logging.info("----- START OF THE IoT LOG -----")
    try:
        dir = os.path.dirname(os.path.realpath(__file__))

        rootCAPath = dir + "/root-CA.crt"
        certificatePath = dir + "/" + config.name +".cert.pem"
        privateKeyPath = dir + "/" + config.name + ".private.key"

        streamHandler = logging.StreamHandler()
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        streamHandler.setFormatter(formatter)

        global myAWSIoTMQTTClient
        myAWSIoTMQTTClient = AWSIoTMQTTShadowClient(config.name)
        myAWSIoTMQTTClient.configureEndpoint(config.iot_endpoint, 8883)
        myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
        
        # AWSIoTMQTTClient connection configuration
        myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
        myAWSIoTMQTTClient.configureConnectDisconnectTimeout(30)  # 30 sec
        myAWSIoTMQTTClient.configureMQTTOperationTimeout(10)  # 5 sec
        

        # Connect and subscribe to AWS IoT
        myAWSIoTMQTTClient.connect(10)
        
        print("Creating shadows")
        global deviceShadowHandler

        deviceShadowHandler = myAWSIoTMQTTClient.createShadowHandlerWithName(config.name, True)
        
        global Connection
        Connection = myAWSIoTMQTTClient.getMQTTConnection()
        Connection.configureAutoReconnectBackoffTime(1, 32, 20)
        Connection.configureDrainingFrequency(2)  # Draining: 2 Hz
        Connection.configureConnectDisconnectTimeout(30)  # 30 sec
        Connection.configureMQTTOperationTimeout(10)  # 10 sec
          
        Connection.subscribe("global", 1, customCallback)
        
        
        SendMSG('{"to": "server", "client-id": "1", "info": "start-up"}')
        
        control.update_status()
        
    except Exception as e:
        logging.exception("Error IoT: " + str(e))
        print("Error IoT: ", e)
        import traceback
        traceback.print_exc()
def local_shadow_connect(device_name, config_file, root_ca, certificate,
                         private_key, group_ca_dir):
    cfg = GroupConfigFile(config_file)
    ggd_name = cfg['devices'][device_name]['thing_name']
    iot_endpoint = cfg['misc']['iot_endpoint']

    dip = DiscoveryInfoProvider()
    dip.configureEndpoint(iot_endpoint)
    dip.configureCredentials(caPath=root_ca,
                             certPath=certificate,
                             keyPath=private_key)
    dip.configureTimeout(10)  # 10 sec
    logging.info(
        "[shadow_connect] Discovery using CA:{0} cert:{1} prv_key:{2}".format(
            root_ca, certificate, private_key))
    gg_core, discovery_info = discover_configured_core(
        config_file=config_file,
        dip=dip,
        device_name=ggd_name,
    )
    if not gg_core:
        raise EnvironmentError("[core_connect] Couldn't find the Core")

    ca_list = discovery_info.getAllCas()
    core_list = discovery_info.getAllCores()
    group_id, ca = ca_list[0]
    core_info = core_list[0]
    logging.info("Discovered Greengrass Core:{0} from Group:{1}".format(
        core_info.coreThingArn, group_id))
    group_ca_file = save_group_ca(ca, group_ca_dir, group_id)

    # local Greengrass Core discovered
    # get a shadow client to receive commands
    mqttsc = AWSIoTMQTTShadowClient(ggd_name)

    # now connect to Core from this Device
    logging.info("[core_connect] gca_file:{0} cert:{1}".format(
        group_ca_file, certificate))
    mqttsc.configureCredentials(group_ca_file, private_key, certificate)

    mqttc = mqttsc.getMQTTConnection()
    mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)
    if not mqtt_connect(mqttsc, gg_core):
        raise EnvironmentError("connection to Master Shadow failed.")

    # create and register the shadow handler on delta topics for commands
    # with a persistent connection to the Master shadow
    master_shadow = mqttsc.createShadowHandlerWithName(
        cfg['misc']['master_shadow_name'], True)

    return mqttc, mqttsc, master_shadow, ggd_name
Ejemplo n.º 20
0
def local_shadow_connect(device_name, config_file, root_ca, certificate,
                         private_key, group_ca_dir):
    cfg = GroupConfigFile(config_file)
    ggd_name = cfg['devices'][device_name]['thing_name']
    iot_endpoint = cfg['misc']['iot_endpoint']

    dip = DiscoveryInfoProvider()
    dip.configureEndpoint(iot_endpoint)
    dip.configureCredentials(
        caPath=root_ca, certPath=certificate, keyPath=private_key
    )
    dip.configureTimeout(10)  # 10 sec
    logging.info(
        "[shadow_connect] Discovery using CA:{0} cert:{1} prv_key:{2}".format(
            root_ca, certificate, private_key
    ))
    gg_core, discovery_info = discover_configured_core(
        config_file=config_file, dip=dip, device_name=ggd_name,
    )
    if not gg_core:
        raise EnvironmentError("[core_connect] Couldn't find the Core")

    ca_list = discovery_info.getAllCas()
    core_list = discovery_info.getAllCores()
    group_id, ca = ca_list[0]
    core_info = core_list[0]
    logging.info("Discovered Greengrass Core:{0} from Group:{1}".format(
        core_info.coreThingArn, group_id)
    )
    group_ca_file = save_group_ca(ca, group_ca_dir, group_id)

    # local Greengrass Core discovered
    # get a shadow client to receive commands
    mqttsc = AWSIoTMQTTShadowClient(ggd_name)

    # now connect to Core from this Device
    logging.info("[core_connect] gca_file:{0} cert:{1}".format(
        group_ca_file, certificate))
    mqttsc.configureCredentials(group_ca_file, private_key, certificate)

    mqttc = mqttsc.getMQTTConnection()
    mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)
    if not mqtt_connect(mqttsc, gg_core):
        raise EnvironmentError("connection to Master Shadow failed.")

    # create and register the shadow handler on delta topics for commands
    # with a persistent connection to the Master shadow
    master_shadow = mqttsc.createShadowHandlerWithName(
        cfg['misc']['master_shadow_name'], True)

    return mqttc, mqttsc, master_shadow, ggd_name
Ejemplo n.º 21
0
def shadowUpdate(body):
    # Create, configure, and connect a shadow client.
    myShadowClient = AWSIoTMQTTShadowClient(SHADOW_CLIENT)
    myShadowClient.configureEndpoint(HOST_NAME, 8883)
    myShadowClient.configureCredentials(ROOT_CA, PRIVATE_KEY, CERT_FILE)
    myShadowClient.configureConnectDisconnectTimeout(10)
    myShadowClient.configureMQTTOperationTimeout(5)
    myShadowClient.connect()

    # Create a programmatic representation of the shadow.
    myDeviceShadow = myShadowClient.createShadowHandlerWithName(
        SHADOW_HANDLER, True)

    myDeviceShadow.shadowUpdate(body, myShadowUpdateCallback, 5)
Ejemplo n.º 22
0
def ConnectAWS():
    myAWSIoTMQTTShadowClient = None
    myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient("RaspberryPi")
    myAWSIoTMQTTShadowClient.configureEndpoint(host, 443)
    myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath,
                                                  certificatePath)
    myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
    myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
    myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)  # 5 sec
    myAWSIoTMQTTShadowClient.connect()
    deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(
        thingName, True)

    return deviceShadowHandler
Ejemplo n.º 23
0
def switch(onoff):
    host = "a2gwyx8959iy18.ats.iot.cn-north-1.amazonaws.com.cn"
    thingName = "kmplc01"
    rootCAPath = "cert/root-CA.crt"
    certificatePath = "cert/certificate.pem.crt"
    privateKeyPath = "cert/private.pem.key"
    clientId = "randomID1" + str(random.randint(10000, 99999))
    port = 443
    useWebsocket = True

    # Configure logging
    logger = logging.getLogger("AWSIoTPythonSDK.core")
    logger.setLevel(logging.DEBUG)
    streamHandler = logging.StreamHandler()
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    streamHandler.setFormatter(formatter)
    logger.addHandler(streamHandler)

    # Init AWSIoTMQTTShadowClient
    myAWSIoTMQTTShadowClient = None
    if useWebsocket:
        myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId,
                                                          useWebsocket=True)
        myAWSIoTMQTTShadowClient.configureEndpoint(host, port)
        myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath)
    else:
        myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
        myAWSIoTMQTTShadowClient.configureEndpoint(host, port)
        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()

    deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(
        thingName, True)

    # Update shadow in a loop
    JSONPayload = '{"state":{"desired":{"status":' + "\"" + onoff + "\"" + '}}}'
    print(JSONPayload)
    deviceShadowHandler.shadowUpdate(JSONPayload, customShadowCallback_Update,
                                     5)
Ejemplo n.º 24
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)
def setClient(answers):
  try:
    shadowClient = AWSIoTMQTTShadowClient(answers['name']+"Thing")
    shadowClient.configureCredentials(answers['root_ca'], answers['private_key'], answers['cert_file'])
  except FileNotFoundError as fnf_error:
    print('File not found.',fnf_error)
  else: 
    try:
      shadowClient.configureEndpoint(answers['host_name'], 8883)
      shadowClient.configureConnectDisconnectTimeout(10)
      shadowClient.configureMQTTOperationTimeout(5)
      shadowClient.connect()
      # Create a programmatic representation of the shadow.
      return shadowClient.createShadowHandlerWithName(answers['name']+"Thing", True)
    except AssertionError as error:
      print(error)
Ejemplo n.º 26
0
 def connection_AWS_IOT(self):
     myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(
         pfc_mqtt_topic.AWS_SHADOW_THING_NAME)
     myAWSIoTMQTTShadowClient.configureEndpoint(pfc_mqtt_topic.AWS_ENDPOINT,
                                                8883)
     myAWSIoTMQTTShadowClient.configureCredentials(
         pfc_conf.CA_PATH, pfc_conf.PRIVATE_KEY_PATH,
         pfc_conf.CERTIFICATE_PATH)
     myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(30)
     myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(30)
     myAWSIoTMQTTShadowClient.connect()
     mc = myAWSIoTMQTTShadowClient.getMQTTConnection()
     mc.configureOfflinePublishQueueing(-1)
     self.IOT_SHADOW_CLIENT = myAWSIoTMQTTShadowClient
     self.PFC_SHADOW = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(
         pfc_mqtt_topic.AWS_SHADOW_THING_NAME, True)
Ejemplo n.º 27
0
def switch(onoff):
    host = ""
    thingName = ""
    rootCAPath = "cert/root-CA.crt"
    certificatePath = "cert/certificate.pem.crt"
    privateKeyPath = "cert/private.pem.key"
    clientId = "randomID1" + str(random.randint(10000, 99999))
    port = 443
    useWebsocket = True

    # Configure logging
    logger = logging.getLogger("AWSIoTPythonSDK.core")
    logger.setLevel(logging.DEBUG)
    streamHandler = logging.StreamHandler()
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    streamHandler.setFormatter(formatter)
    logger.addHandler(streamHandler)

    # Init AWSIoTMQTTShadowClient
    myAWSIoTMQTTShadowClient = None
    if useWebsocket:
        myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId,
                                                          useWebsocket=True)
        myAWSIoTMQTTShadowClient.configureEndpoint(host, port)
        myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath)
    else:
        myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
        myAWSIoTMQTTShadowClient.configureEndpoint(host, port)
        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()

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

    getDeviceStatus(deviceShadowHandler)
Ejemplo n.º 28
0
def init_shadow_handler(ats_iot_host, ats_iot_port, shadow_name):
    shadow_handler = None

    try:
        shadow_client = AWSIoTMQTTShadowClient(SHADOW_CLIENT_NAME)
        shadow_client.configureEndpoint(ats_iot_host, ats_iot_port)
        shadow_client.configureCredentials(ROOT_CA, PRIVATE_KEY, CERT_FILE)
        shadow_client.configureConnectDisconnectTimeout(10)
        shadow_client.configureMQTTOperationTimeout(5)
        shadow_client.connect()

        shadow_handler = shadow_client.createShadowHandlerWithName(
            shadow_name, True)

        logging.info('AWS IoT shadow handler initialized')
    except Exception as e:
        logging.error("unable to initialize shadow handler: %s" % e)

    return shadow_handler
Ejemplo n.º 29
0
def awsiot_loop():
    prctl.set_name("awsiot_loop")

    logger.info('Starting AWS IoT loop...')

    awsiot = AWSIoTMQTTShadowClient(DEVICE_NAME)
    awsiot.configureEndpoint(awsiot_endpoint, 8883)
    awsiot.configureCredentials(awsiot_ca, awsiot_key, awsiot_cert)
    awsiot.configureConnectDisconnectTimeout(10)
    awsiot.configureMQTTOperationTimeout(5)

    awsiot.connect()
    shadow = awsiot.createShadowHandlerWithName(DEVICE_NAME, True)

    while True:
        time.sleep(0.1)

        if awsiot_shutdown:
            break

        try:
            packet = awsiot_queue.get(timeout = 0.1)

            o = msgpack.unpackb(packet)

            doc = {
                "state": {
                    "reported": {
                        "temperature": o[b't'],
                        "humidity": o[b'h']
                    }
                }
            }

            s = json.dumps(doc)

            shadow.shadowUpdate(s, None, 5)
        except Empty:
            pass
        except Exception:
            logger.exception("Failed to push sensor packet to AWS IoT")

    awsiot.disconnect()
Ejemplo n.º 30
0
def weather_station(event, context):
    """
  Create an AWS IoT shadow client for a specific remote sensor station.
  Collect sensor data from the station via an Internet endpoint.  Update the
  shadow client with the desired subset of available sensor station data.

  Args (supplied by AWS Lambda service)
    event: information about who/what invoked the Lambda function
    context: information about the Lambda function's runtime environment
  
  Returns: 
    { 'statusCode': <int value>,
      'body': <status string> }  
  """
    shadow_client = AWSIoTMQTTShadowClient(SHADOW_CLIENT)
    shadow_client.configureEndpoint(HOST_NAME, MQTT_PORT)
    shadow_client.configureCredentials(ROOT_CA, PRIVATE_KEY, CERT_FILE)
    shadow_client.configureConnectDisconnectTimeout(10)
    shadow_client.configureMQTTOperationTimeout(5)

    if (shadow_client.connect()):
        #Create access point for AWS IoT shadow document
        device_shadow = shadow_client.createShadowHandlerWithName(
            SHADOW_HANDLER, True)
        sensor_data = _extract_sensor_data()

        if (sensor_data):
            # specific format required; ' "state" : {"reported" : {....... '
            update_string = '{"state":{"reported":'
            update_string += json.dumps(sensor_data)
            update_string += '}}'

            # result of updating shadow document; set in _my_shadow_update_callback()
            device_shadow.shadowUpdate(update_string,
                                       _my_shadow_update_callback, 5)
        else:
            return_value['statusCode'] = 400
            return_value[
                'body'] = 'Error connecting to sensor or with sensor data.'
    else:
        return_value['statusCode'] = 500
        return_value['body'] = 'Could not connect to IoT shadow.'
    return (return_value)
Ejemplo n.º 31
0
def lambda_handler(event, context):
    global myAWSIoTMQTTShadowClient, myDeviceShadow
    """ Route the incoming request based on type (LaunchRequest, IntentRequest,
    etc.) The JSON body of the request is provided in the event parameter.
    """
    print ('RECEIVED EVENT: ' + json.dumps(event, separators=(',', ':')))
    if 'session' in event:
        print("event.session.application.applicationId=" + event['session']['application']['applicationId'])

        """
        Uncomment this if statement and populate with your skill's application ID to
        prevent someone else from configuring a skill that sends requests to this
        function.
        """
        if (event['session']['application']['applicationId'] !=
            "amzn1.ask.skill.*********"):
            raise ValueError("Invalid Application ID")

        if event['session']['new'] and 'requestId' in event['request']:
            on_session_started({'requestId': event['request']['requestId']},event['session'])

        if 'request' in event:
            # Init AWSIoTMQTTClient
            myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(shadowName+"_Lambda_"+event['request']['requestId'][-12:])
            myAWSIoTMQTTShadowClient.configureEndpoint(host, 8883)
            myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

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

            # Connect to AWS IoT Shadow
            myAWSIoTMQTTShadowClient.connect()
            myDeviceShadow = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(shadowName, True)
            
            if event['request']['type'] == "LaunchRequest":
                return on_launch(event['request'], event['session'])
            elif event['request']['type'] == "IntentRequest":
                return on_intent(event['request'], event['session'])
            elif event['request']['type'] == "SessionEndedRequest":
                return on_session_ended(event['request'], event['session'])
Ejemplo n.º 32
0
def _get_device_shadow_client(location):
  """
  Each vineyard sensor station is set up in IoT Core as a 'Thing' with
  its own 'shadow document.'  In order to push data into AWS, for a 
  sensor, you update its shadow document.  To do this you use a 'shadow
  client' to place a message, containing the incoming sensor data, on 
  the message queue assigned to the sensor/thing/shadow document.  Each
  IoT shadow document is assigned its own shadow client.  Shadow 
  clients are created by this module, on demand, and exist for the 
  duration of this module's execution.  Shadow clients will be reused 
  (for the duration of this module's execution) in cases where multiple 
  data sensor records are processed for the same sensor station.  Reuse 
  of shadow clients is possible because of the 'True' flag in the 
  createShadowHandlerWithName() call.
  
  Returns
    None           if a device shadow could not be retrieved/created
    device_shadow  if a device shadow could be retrieved/created
  """
  global device_shadows
  a_device_shadow = None
  if(location in device_shadows):
    a_device_shadow = device_shadows[location]
  else:
    a_client = AWSIoTMQTTShadowClient(location)
    a_client.configureEndpoint(MQTT_VALUES['host_name'], 
                               MQTT_VALUES['mqtt_port'])
    a_client.configureCredentials(SHADOW_SECURITY[location]['root_ca'],
                                  SHADOW_SECURITY[location]['private_key'],
                                  SHADOW_SECURITY[location]['cert_file'])
    a_client.configureConnectDisconnectTimeout(10)
    a_client.configureMQTTOperationTimeout(5)
    
    if(not a_client.connect()):
      sl.log_message('15', ERROR, 'Could not connect to shadow document' +
                     ' for location: ' + location, '')
    else:
      a_device_shadow = a_client.createShadowHandlerWithName(
                          SHADOW_SECURITY[location]['handler'], True)
      device_shadows[location] = a_device_shadow
  return(a_device_shadow)
Ejemplo n.º 33
0
# Init AWSIoTMQTTShadowClient
myAWSIoTMQTTShadowClient = None
if useWebsocket:
	myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient("ThingShadowEcho", useWebsocket=True)
	myAWSIoTMQTTShadowClient.configureEndpoint(host, 443)
	myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath)
else:
	myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient("ThingShadowEcho")
	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()

# Create a deviceShadow with persistent subscription
Bot = myAWSIoTMQTTShadowClient.createShadowHandlerWithName("Pi_Py_SDK", True)
shadowCallbackContainer_Bot = shadowCallbackContainer(Bot)

# Listen on deltas
Bot.shadowRegisterDeltaCallback(shadowCallbackContainer_Bot.customShadowCallback_Delta)

# Loop forever
while True:
	pass
logger.addHandler(streamHandler)

# Init AWSIoTMQTTShadowClient
myAWSIoTMQTTShadowClient = None
if useWebsocket:
	myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient("basicShadowDeltaListener", useWebsocket=True)
	myAWSIoTMQTTShadowClient.configureEndpoint(host, 443)
	myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath)
else:
	myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient("basicShadowDeltaListener")
	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()

# Create a deviceShadow with persistent subscription
Bot = myAWSIoTMQTTShadowClient.createShadowHandlerWithName("Bot", True)

# Listen on deltas
Bot.shadowRegisterDeltaCallback(customShadowCallback_Delta)

# Loop forever
while True:
	pass
Ejemplo n.º 35
0
class ThermoApp(App):
	DEVICE = '/dev/ttyAMA0'
	BAUD = 9600
	TIMEOUT = 5
	ipaddr=''
	lastGPUTempRead=0.0
	lastWeatherRead=0.0
	lastTempPressHumidRead=0.0
	lastShadowUpdate=0.0
	lastSetAlerts=0.0
	ui = ObjectProperty(None)
	zones = ObjectProperty(None)
	zonemap=['','17','27','22']
	zoneData={
		'1':ThermoZone(1,17),
		'2':ThermoZone(2,27),
		'3':ThermoZone(3,22)
	}
	furnace=Furnace()
	currentZone=1
	dataFeed = deque()
	
	deviceData={
		'AA':ThermoDevice('AA',2,'master'),
		'AB':ThermoDevice('AB',2,'tess'),
		'AC':ThermoDevice('AC',2,'kate'),
		'AD':ThermoDevice('AD',3,'girls'),
		'AE':ThermoDevice('AE',1,'snug'),
		'AF':ThermoDevice('AF',1,'living'),
		'AG':ThermoDevice('AG',0,'porch'),
		'AH':ThermoDevice('AH',1,'ground'),
		'BM':ThermoDevice('BM',0,'thermo'),
		'AW':ThermoDevice('AW',0,'weather'),
		'PI':ThermoDevice('PI',0,'GPU')}
	ser = serial.Serial(DEVICE, BAUD)
	
	voltage = 0.0
	tempvale = 0.0
	pressure = 0.0
	weather = []
	sensor = BME280(mode=BME280_OSAMPLE_8)
	host='a2pveb84akyryv.iot.us-east-1.amazonaws.com'
	rootCAPath='rootca.key'
	privateKeyPath='bdca28f300.private.key'
	certificatePath='bdca28f300.cert.pem'
	# -e a2pveb84akyryv.iot.us-east-1.amazonaws.com -r rootca.key -c bdca28f300.cert.pem -k bdca28f300.private.key

	def show_config(self):
		App.open_settings(self)
		Window.request_keyboard(self.keyboard_close, self)
	
	def keyboard_close(self):
		#print "close"
		return

	def build_config(self, config):
		config.setdefaults('startup', {
	    		'weatherText': 'foobar',
	    		'picSource': 'weather/1.jpg'
		})
		self.config=config

	def build_settings(self, settings):
		jsondata = """[
			{ "type": "title",
			"title": "Thermo application" },
			{ "type": "options",
			"title": "Initial Weather",
			"desc": "Weather Pic",
			"section": "startup",
			"key": "picSource",
			"options": ["weather/1.jpg", "weather/images.jpg", "weather/part_coudy.jpg"] },
			{ "type": "string",
			"title": "Weather Title",
			"desc": "Weather Text",
			"section": "startup",
			"key": "weatherText" }]"""
		settings.add_json_panel('Thermo application', self.config, data=jsondata)

	def build(self):
		self.ui=ThermoWidget()
		self.ui.weatherText='ThermoWidget'
		self.ui.picSource='weather/1.jpg'
		self.ui.tempDataText="temps"
		self.ui.setPointText="0.0"
		self.ui.ipAddressText="192.168.0.0"
		self.ui.averageTempText="0.0"
		self.ui.zoneAlertsText="Loading..."
		btn=self.ui.ids['increase']
		btn.bind(on_release=self.increaseSetPoint)
		btn=self.ui.ids['decrease']
		btn.bind(on_release=self.decreaseSetPoint)
		self.zones=self.ui.ids['zones']
		for z in range(0,4):
			btnstate='down' if self.currentZone==z else 'normal'
			btn = ToggleButton(
				allow_no_selection=False,
				text=str(z), 
				group='zonegroup', 
				size_hint=(None, None),
				halign='center',
				state=btnstate,
				background_normal='normal.png',
				background_down='down.png')
    			btn.bind(on_release=self.switch_zone)
    			self.zones.add_widget(btn)
		self.ui.weatherText=self.config.get('startup', 'weatherText')
		temp = subprocess.check_output(["ifconfig","wlan0"],universal_newlines=True)
		pos1=temp.find("inet addr:")
		pos2=temp.find(" Bcast:")
		self.ui.ipAddressText=temp[pos1+10:pos2]
		self.connectMQTT()
		Clock.schedule_interval(self.mainLoop, 10.0)
		return self.ui

	def switch_zone(self,toggle):
		self.currentZone=int(toggle.text)
		self.updateDisplay()
		pass

	def increaseSetPoint(self,instance):
		self.zoneData[str(self.currentZone)].setPoint+=5.0/9.0
		self.takeAction()
		self.updateDisplay()
		pass

	def decreaseSetPoint(self,instance):
		self.zoneData[str(self.currentZone)].setPoint-=5.0/9.0
		self.takeAction()
		self.updateDisplay()
		pass

	def loadConfig(self):
		# read config file into memory vars
		return

	def avgZone(self,zonenum):
		tot=0.0
		cnt=0
		for i in self.deviceData:
			device=self.deviceData[i]
			if(device.zone==zonenum):
				tot+=float(device.temp)
				if(device.temp>0.0):
					cnt+=1
		if cnt==0:
			cnt=1
		return tot/cnt
	
	def connectMQTT(self):
		self.myShadowClient = AWSIoTMQTTShadowClient("thermo")
    		#self.myAWSIoTMQTTClient = AWSIoTMQTTClient("thermo")

		self.myShadowClient.configureEndpoint(self.host, 8883)
		self.myShadowClient.configureCredentials(self.rootCAPath, self.privateKeyPath, self.certificatePath)

		# myShadowClient connection configuration
		self.myShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
		
		self.myShadowClient.connect()

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

		# Connect and subscribe to AWS IoT
		#self.myAWSIoTMQTTClient.connect()
		# myAWSIoTMQTTClient.subscribe("thermo", 1, customCallback)
		# self.myAWSIoTMQTTClient.publish("thermo", "[[\'"+(strftime(DATE_FORMAT,localtime())+"\','TT','START','1']]", 1)
		# Create a device shadow instance using persistent subscription
		self.myDeviceShadow = self.myShadowClient.createShadowHandlerWithName("mythermo", True)
		return

	def updateDeviceShadow(self):
		if(time()-self.lastShadowUpdate > 300):
			thingState={
				"state" : {
					"reported" : {
						"sensors" : {
						},
						"zones" : {
						},
						"furnace" : {
						}
					}
				}
			}
			for i in self.deviceData:
				device=self.deviceData[i]
				thingState["state"]["reported"]["sensors"][device.id]={"temp":tformat(device.temp),"location":device.location,"batt":device.batt,"alert":device.alert,"lastupdate":device.lastupdate,"press":device.press,"humid":device.humid}
			for i in self.zoneData:
    				zone=self.zoneData[i]
				thingState["state"]["reported"]["zones"][zone.id]={"status":zone.status, "average":tformat(zone.average), "setPoint":tformat(zone.setPoint), "triggertemp":tformat(zone.triggertemp), "alert":zone.alert}
			thingState["state"]["reported"]["furnace"]={"onSeconds":self.furnace.onSeconds,"offSeconds":self.furnace.offSeconds,"maxBurnSeconds":self.furnace.maxBurnSeconds,"maxRestSeconds":self.furnace.maxRestSeconds,"status":self.furnace.status,"lastupdate":self.furnace.lastupdate}
			self.myDeviceShadow.shadowUpdate(json.dumps(thingState), None, 5)
			self.lastShadowUpdate=time()
		return	
		
	def updateDisplay(self):
		# draw everything
		# if click then show subpanel or change config
		self.ui.setPointText="{:2.0f}".format(self.zoneData[str(self.currentZone)].setPoint*9/5+32.0)
		self.ui.averageTempText=tformat(self.avgZone(self.currentZone))
		self.ui.tempDataText=''
		zonealerts='Alerts:'
		for i in self.deviceData:
			device=self.deviceData[i]
			thisDeviceText=tformat(device.temp)
			thisDeviceText+=" "+device.location+" "+device.alert
			self.ui.tempDataText+=thisDeviceText+'\n'
		for i in self.zoneData:
    			zone=self.zoneData[i]
			if(len(zone.alert)>0):
				zonealerts+=" Zone"+str(zone.id)+" "+zone.alert
		self.ui.zoneAlertsText=zonealerts
		return
	
	def readSensors(self):
		# get data from serial RF sensors
		# get data from remote PI
		# all data in memory only in this function
		# get temperature
		# messages are 12chars aIDTYPEVALUE aIDAWAKE---- or aIDSLEEPING-
		# returns -100 on error, or the temperature as a float
		
		fim = time()+ self.TIMEOUT
		
		voltage = 0
		tempvalue = -100
		deviceid = ''
		while (time()<fim) and (tempvalue == -100):
			n = self.ser.inWaiting()
			if n != 0:
				data = self.ser.read(n)
				nb_msg = len(data) / 12
				for i in range (0, nb_msg):
					msg = data[i*12:(i+1)*12]
		
					deviceid = msg[1:3]
					if self.deviceData.has_key(deviceid):
						device=self.deviceData[deviceid]
						device.lastupdate=strftime(DATE_FORMAT,localtime())
			
						if msg[3:7] == "TEMP":
							tempvalue = msg[7:]
							device.temp=tempvalue
							self.dataFeed.append((strftime(DATE_FORMAT,localtime()), deviceid, "TEMP", tempvalue))

						if msg[3:7] == "BATT":
							voltage = msg[7:11]
							if voltage == "LOW":
								voltage = 0.1
							device.batt=voltage
							self.dataFeed.append((strftime(DATE_FORMAT,localtime()), deviceid+'B', "BATT", voltage))

			else:
				sleep(5)
		return

	def getPiSensorData(self):
		if(time()-self.lastGPUTempRead > 60):
			temp = ""
			temp = subprocess.check_output(["/opt/vc/bin/vcgencmd","measure_temp"],universal_newlines=True)
			temp = temp[5 : -3]
			device=self.deviceData['PI']
			device.lastupdate=strftime(DATE_FORMAT,localtime())
			device.temp=temp
			self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "PI", "TEMP", temp))
			self.lastGPUTempRead = time()
		return

	def getConnectedSensorData(self):
		if(time()-self.lastTempPressHumidRead > 60):
			# get BME280 data
			temp=self.sensor.read_temperature()-1.0
			press=self.sensor.read_pressure()
			humid=self.sensor.read_humidity()
			self.pressure=press
			device=self.deviceData['BM']
			device.lastupdate=strftime(DATE_FORMAT,localtime())
			device.temp=temp
			device.press=press
			device.humid=humid
			self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "BM", "TEMP", temp))
			self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "BP", "PRESS", press))
			self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "BH", "HUMID", humid))
			self.lastTempPressHumidRead = time()

	def getWeather(self):
		if(time()-self.lastWeatherRead > 1800):
			# get and parse AccuWeather data
			cur = re.compile('Currently: (.*)<')
			link = "http://rss.accuweather.com/rss/liveweather_rss.asp?metric=0&locCode=US|44022"
			f = urllib.urlopen(link)
			myfile = f.read()
			tempvalue = cur.search(myfile).group(1)
			temp=tempvalue[-4:-1]
			pos=tempvalue.find(":")
			description=tempvalue[0:-5] if pos<0 else tempvalue[0:pos]
			description=description.replace(" ","_").lower()
			# print("description = [" + description +"]")
			device=self.deviceData['AW']
			device.lastupdate=strftime(DATE_FORMAT,localtime())
			device.temp=(float(temp)-32)*5/9
			if device.desc<>description :
				self.ui.picSource='weather/'+description+'.jpg' if 6 < localtime()[3] < 18 else 'weather/'+description+'_dark.jpg'
			device.desc=description
			self.ui.weatherText = tempvalue
			self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "AW", "NEWS", tempvalue))
						
			self.lastWeatherRead = time()
		return
	def setAlerts(self):
		# Reasons for alerts:
		# sensor battery level below 2.3
		# sensor not reporting ( sensor data age > 5x reporting )
		# temperature not under control = falling when attempting to raise
		#    alert if temp not correct direction for 10 minutes
		#    need control switch date time 
		if(time()-self.lastSetAlerts > 1800):
			for i in self.deviceData:
    				device=self.deviceData[i]
				device.alert=""
				if (not device.batt is None) & (device.batt<2.5):
    					device.alert="LOW"
					self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "ALERT", "LOW Battery in "+device.location, device.batt))
					self.lastSetAlerts = time()
				if (len(device.lastupdate)>0) & (device.id!='AW'): 
					age = datetime.datetime.strptime(strftime(DATE_FORMAT,localtime()),DATE_FORMAT) - datetime.datetime.strptime(device.lastupdate,DATE_FORMAT)
					#print "{} {}".format(device.location,age.seconds)
					if ( age.seconds > 600 ):
						device.alert="OLD"
						self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "ALERT", "NO Response in "+device.location, age.seconds))
						self.lastSetAlerts = time()
			for i in self.zoneData:
    				zone=self.zoneData[i]
				zone.alert=""
				if (zone.status):
					age = datetime.datetime.strptime(strftime(DATE_FORMAT,localtime()),DATE_FORMAT) - datetime.datetime.strptime(zone.lastupdate,DATE_FORMAT)
					if (age.seconds>600):
						zone.alert="OOC"
						self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "ALERT", "OOC in zone "+str(zone.id), tformat(zone.average)))
						self.lastSetAlerts = time()
		return

	def uploadData(self):
		# put the data in the cloud or cache in a file until sucess
		# add it to the memory deque
		# if the deque > 10 try to upload it and any pending updates
		# else throw a flag for pending updates and write to a file
		if len(self.dataFeed)>10:
    			try:
				# write to a file
				#print "  write to file"
				with open("Output.txt", "a") as text_file:
					for record in self.dataFeed:
						text_file.write("{},{},{},{}\r\n".format(record[0],record[1],record[2],record[3]))
				# write to cloud
				#print "  write to cloud"

				self.myAWSIoTMQTTClient.publish("thermo", json.dumps(list(self.dataFeed)), 1)
				# clear the deque
				self.dataFeed.clear()
			except:
				print("Unexpected error in uploadData:", sys.exc_info()[0])
		return
		
	def downloadRequests(self):
		# get cloud data or web requests
		return
		
	def controlZone(self,zone,on,avg):
		zoneentry=self.zoneData[str(zone)]
		subprocess.call(["gpio", "-g", "write", str(zoneentry.port), "1" if on else "0"])
    		furnaceWasOn=False
		for i in self.zoneData:
			furnaceWasOn|=self.zoneData[i].status
		if(zoneentry.status != on):
			zoneentry.status=on
			furnaceIsOn=False
			for i in self.zoneData:
				furnaceIsOn|=self.zoneData[i].status
			if(furnaceIsOn!=furnaceWasOn):
				self.furnace.status=furnaceIsOn
				if (len(self.furnace.lastupdate)>0):
					age = datetime.datetime.strptime(strftime(DATE_FORMAT,localtime()),DATE_FORMAT) - datetime.datetime.strptime(self.furnace.lastupdate,DATE_FORMAT)
					# if it is now on  - age is how long it was off
					if(furnaceIsOn):
						self.furnace.offSeconds+=age.seconds
						if(age.seconds>self.furnace.maxRestSeconds):
							self.furnace.maxRestSeconds=age.seconds
					# if it is now off - age is how long it was on
					else:
						self.furnace.onSeconds+=age.seconds
						if(age.seconds>self.furnace.maxBurnSeconds):
							self.furnace.maxBurnSeconds=age.seconds
				self.furnace.lastupdate=strftime(DATE_FORMAT,localtime())
			zoneentry.lastupdate=strftime(DATE_FORMAT,localtime())
			zoneentry.triggertemp=avg
		return

	def takeAction(self):
		# contains all rules to make decisions based on data 
		for i in self.zoneData:
			zone=self.zoneData[i]
			zone.average=self.avgZone(zone.id)
			if(zone.average<10.0):
				self.controlZone(zone.id,False,zone.average)
				return
			#print "average in zone {} is {}".format(zone.id,zone.average)
    			if(zone.average<zone.setPoint-0.5):
    				self.controlZone(zone.id,True,zone.average)
    				#turn it on
			if(zone.average>zone.setPoint):
				self.controlZone(zone.id,False,zone.average)
    				#turn it off
		return
	
	def mainLoop(self,args):
		try:
			#print 'config'
			self.loadConfig()
			#print 'getWeather'
			self.getWeather()
			#print 'getPI'
			self.getPiSensorData()
			#print 'getBME'
			self.getConnectedSensorData()
			#print 'read'
			self.readSensors()
			#print 'alerts'
			self.setAlerts()
			#print 'update'
			self.updateDisplay()
			#print 'update shadow'
			self.updateDeviceShadow()
			#print 'upload'
			self.uploadData()
			#print 'download'
			self.downloadRequests()
			#print 'action'
			self.takeAction()
		except:
			type_, value_, traceback_ = sys.exc_info()
			print "EXCEPTION {}\r\n{}\r\n{}".format(type_, value_, traceback.format_tb(traceback_))
			self.dataFeed.append(value_)
		return
logger.addHandler(streamHandler)

# Init AWSIoTMQTTShadowClient
myAWSIoTMQTTShadowClient = None
if useWebsocket:
	myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId, useWebsocket=True)
	myAWSIoTMQTTShadowClient.configureEndpoint(host, 443)
	myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath)
else:
	myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
	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()

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

# Listen on deltas
deviceShadowHandler.shadowRegisterDeltaCallback(customShadowCallback_Delta)

# Loop forever
while True:
	time.sleep(1)
class ThermoSimAppGUI:

    _usage = """Usage:

    Make sure that you put all your credentials under: ./certs/
    with the following naming conventions:
    Root CA file: *CA.crt
    Certificate file (not required if using MQTT over WebSocket): *.pem.crt
    Private key file (not required if using MQTT over WebSocket): *.pem.key

    Use X.509 certificate based mutual authentication:
    python ThermostatSimulatorApp -e <endpoint>

    Use MQTT over WebSocket:
    python ThermostatSimulatorApp -e <endpoint> -w

    Type "python ThermostatSimulatorApp -h" for detailed command line options.


    """

    _helpInfo = """Available command line options:
    -e, --endpoint: Your custom AWS IoT custom endpoint
    -w, --websocket: Use MQTT over websocket
    -h, --help: Help infomation


    """

    def __init__(self):
        # Init data members
        # Connection related
        self._endpoint = ""
        self._rootCAFilePathList = ""
        self._certificateFilePathList = ""
        self._privateKeyFilePathList = ""
        self._useWebsocket = False
        self._AWSIoTMQTTShadowClient = None
        self._thermostatSimulatorShadowHandler = None
        # GUI related
        self._tkRootHandler = tkinter.Tk()
        self._reportedDataVariable = None
        self._reportedDataDisplayBox = None
        self._desiredDataVariable = None
        self._desiredDataDisplayBox = None
        self._setTemperatureInputBox = None
        self._setTemperatureButton = None
        # Check command line inputs
        if not self._checkInputs():
            raise ValueError("Malformed/Missing command line inputs.")
        # Create and configure AWSIoTMQTTShadowClient
        self._AWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient("ThermostatSimulatorApp", useWebsocket=self._useWebsocket)
        if self._useWebsocket:
            self._AWSIoTMQTTShadowClient.configureEndpoint(self._endpoint, 443)
            self._AWSIoTMQTTShadowClient.configureCredentials(self._rootCAFilePathList[0])
        else:
            self._AWSIoTMQTTShadowClient.configureEndpoint(self._endpoint, 8883)
            self._AWSIoTMQTTShadowClient.configureCredentials(self._rootCAFilePathList[0], self._privateKeyFilePathList[0], self._certificateFilePathList[0])
        self._AWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 128, 20)
        self._AWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)
        self._AWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)
        # Set keepAlive interval to be 1 second and connect
        # Raise exception if there is an error in connecting to AWS IoT
        self._AWSIoTMQTTShadowClient.connect(5)
        self._thermostatSimulatorShadowHandler = self._AWSIoTMQTTShadowClient.createShadowHandlerWithName("room", True)
        # Generate GUI
        self._packModule()

    # Validate command line inputs
    # Return False there is any malformed inputs
    # Return True if all the necessary inputs have been discovered
    def _checkInputs(self):
        gotEoughInputs = True
        # Check command line inputs
        try:
            opts, args = getopt.getopt(sys.argv[1:], "hwe:", ["endpoint=", "websocket", "help"])
            if len(opts) == 0:
                raise getopt.GetoptError("No input parameters")
            for opt, arg in opts:
                if opt in ("-e", "--endpoint"):
                    self._endpoint = arg
                if opt in ("-w", "--websocket"):
                    self._useWebsocket = True
                if opt in ("-h", "--help"):
                    print(self._helpInfo)
                    gotEoughInputs = False
        except getopt.GetoptError:
            print(self._usage)
            gotEoughInputs = False
        # Check credential files
        if gotEoughInputs:
            self._rootCAFilePathList = glob.glob("./certs/*CA.crt")
            if self._useWebsocket:
                gotEoughInputs = gotEoughInputs and len(self._rootCAFilePathList) != 0
                if not gotEoughInputs:
                    print("Missing rootCA in ./certs/")
            else:
                self._certificateFilePathList = glob.glob("./certs/*.pem.crt")
                self._privateKeyFilePathList = glob.glob("./certs/*.pem.key")
                gotEoughInputs = gotEoughInputs and len(self._rootCAFilePathList) != 0 and len(self._certificateFilePathList) != 0 and len(self._privateKeyFilePathList) != 0
                if not gotEoughInputs:
                    print("Missing rootCA, certificate or private key in ./certs/")
        return gotEoughInputs

    def _packModule(self):
        self._tkRootHandler.title("ThermostatSimulatorApp")
        self._tkRootHandler.geometry("500x250")
        self._tkRootHandler.resizable(width=False, height=False)
        # Pack all frames
        baseFrame = tkinter.Frame(self._tkRootHandler)
        temperatureFrame = tkinter.Frame(baseFrame)
        temperatureFrame.pack(side="top")
        controlPanelFrame = tkinter.Frame(baseFrame)
        controlPanelFrame.pack(side="bottom")
        baseFrame.pack()
        # Pack all modules for temperature frame
        self._reportedDataVariable = tkinter.StringVar()
        self._reportedDataVariable.set("XX.X F")
        reportedDataTag = tkinter.Label(temperatureFrame, text="Reported Temperature:", justify="left")
        self._reportedDataDisplayBox = tkinter.Label(temperatureFrame, textvariable=self._reportedDataVariable, font=("Arial", 55), justify="left")
        #
        self._desiredDataVariable = tkinter.StringVar()
        self._desiredDataVariable.set("XX.X F")
        desiredDataTag = tkinter.Label(temperatureFrame, text="Desired Temperature:", justify="left")
        self._desiredDataDisplayBox = tkinter.Label(temperatureFrame, textvariable=self._desiredDataVariable, font=("Arial", 55), justify="left")
        #
        reportedDataTag.pack()
        self._reportedDataDisplayBox.pack()
        desiredDataTag.pack()
        self._desiredDataDisplayBox.pack()
        # Create a callback pool
        self._callbackPoolHandler = ThermoSimAppCallbackPool(self._tkRootHandler, self._reportedDataDisplayBox, self._thermostatSimulatorShadowHandler, self._reportedDataVariable, self._desiredDataVariable)
        # Pack all modules for control panel frame
        self._setTemperatureInputBox = tkinter.Entry(controlPanelFrame)
        self._setTemperatureInputBox.pack(sid="left")
        self._setTemperatureButton = tkinter.Button(controlPanelFrame, text="SET", command=lambda: self._callbackPoolHandler.buttonCallback(self._setTemperatureInputBox, self._desiredDataVariable))
        self._setTemperatureButton.pack()

    def runApp(self):
        # Start and run the app
        self._tkRootHandler.after(500, self._callbackPoolHandler.sendShadowGetForReportedTemperature)  # per 500ms
        self._tkRootHandler.after(500, self._callbackPoolHandler.updateReportedTemperatureDataVariable)  # per 500ms
        self._tkRootHandler.mainloop()
Ejemplo n.º 38
0
s3.download_file('littercam','device-'+str(mac)+'/devicename.txt', 'devicename.txt')
devicename = open('devicename.txt').readline().split(None, 1)[0]


print(devicename)

ShadowClient = AWSIoTMQTTShadowClient("")

ShadowClient.configureEndpoint("a1oa9tg9lcso0.iot.eu-west-1.amazonaws.com", 8883)
ShadowClient.configureCredentials(get_rootca(),
get_private(),get_cert())
ShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
ShadowClient.configureConnectDisconnectTimeout(30)  # 10 sec
ShadowClient.configureMQTTOperationTimeout(10)  # 5 sec
ShadowClient.connect()
deviceShadowHandler = ShadowClient.createShadowHandlerWithName(devicename, True)
#shadowCallbackContainer_Bot = shadowCallbackContainer(deviceShadowHandler)
#deviceShadowHandler.shadowRegisterDeltaCallback(shadowCallbackContainer_Bot.customShadowCallback_Delta)




# MQTT Connection establishement
myMQTTClient = AWSIoTMQTTClient(devicename)
myMQTTClient.configureEndpoint("a1oa9tg9lcso0.iot.eu-west-1.amazonaws.com", 8883)
myMQTTClient.configureCredentials(get_rootca(),
get_private(),get_cert())


myMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
myMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
Ejemplo n.º 39
0
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient

#for cert based connection
myShadowClient = AWSIoTMQTTShadowClient("raspberry-pi")

myShadowClient.configureEndpoint("a1xugslbalqdxo.iot.us-east-1.amazonaws.com", 8883)

myShadowClient.configureCredentials("/home/pi/python_mqtt/aws-iot-certs/rootCA.pem.crt",
                                    "/home/pi/python_mqtt/aws-iot-certs/c6417d9f55-private.pem.key",
                                    "/home/pi/python_mqtt/aws-iot-certs/c6417d9f55-certificate.pem.crt")

#myShadowClient.configureConnectionDisconnectTimeout(10)
myShadowClient.configureMQTTOperationTimeout(5)

myShadowClient.connect()
myDeviceShadow = myShadowClient.createShadowHandlerWithName("Bot", True)

payload = json.dumps({
    "state":{
        "reported": {
            "this_thing_is_alive": "I am Raspberry"
            }
        }
    })

#myDeviceShadow.shadowGet(customCallback, 5)
#myDeviceShadow.shadowUpdate(payload, shadowUpdate, 5)
myMQTTClient = myShadowClient.getMQTTConnection()
myMQTTClient.publish("topic/raspberry-pi/messages", "Payload message", 1)

Ejemplo n.º 40
0
def initialize(device_name, config_file, root_ca, certificate, private_key,
               group_ca_path):
    global ggd_name

    cfg = GroupConfigFile(config_file)
    local = dict()
    remote = dict()

    # determine heartbeat device's thing name and endpoint for MQTT clients
    ggd_name = cfg['devices'][device_name]['thing_name']
    iot_endpoint = cfg['misc']['iot_endpoint']

    # Discover Greengrass Core
    dip = DiscoveryInfoProvider()
    dip.configureEndpoint(iot_endpoint)
    dip.configureCredentials(
        caPath=root_ca, certPath=certificate, keyPath=private_key
    )
    dip.configureTimeout(10)  # 10 sec
    log.info("Discovery using CA: {0} certificate: {1} prv_key: {2}".format(
        root_ca, certificate, private_key
    ))
    # Now discover the groups in which this device is a member.
    # The arm should only be in two groups. The local and master groups.
    discovered, discovery_info = utils.ggc_discovery(
        ggd_name, dip, retry_count=10, max_groups=2
    )

    # Each group returned has a groupId which can compare to the configured
    # groupId in the config file. If the IDs match, the 'local' Group has been
    # found and therefore local core.
    # If the groupId's do not match, the 'remote' or 'master' group has been
    # found.
    group_list = discovery_info.getAllGroups()
    for g in group_list:
        logging.info("[initialize] group_id:{0}".format(g.groupId))
        if g.groupId == cfg['group']['id']:
            local_cores = g.coreConnectivityInfoList
            local['core'] = local_cores[0]  # just grab first core as local
            local['ca'] = g.caList
        else:
            remote_cores = g.coreConnectivityInfoList
            remote['core'] = remote_cores[0]  # just grab first core as remote
            remote['ca'] = g.caList

    if len(local) > 1 and len(remote) > 1:
        logging.info("[initialize] local_core:{0} remote_core:{1}".format(
            local, remote
        ))
    else:
        raise EnvironmentError("Couldn't find the arm's Cores.")

    # just save one of the group's CAs to use as a CA file later
    local_core_ca_file = utils.save_group_ca(
        local['ca'][0], group_ca_path, local['core'].groupId
    )
    remote_core_ca_file = utils.save_group_ca(
        remote['ca'][0], group_ca_path, remote['core'].groupId
    )

    # Greengrass Cores discovered, now connect to Cores from this Device
    # get a client to send telemetry
    local_mqttc = AWSIoTMQTTClient(ggd_name)
    log.info("[initialize] local gca_file:{0} cert:{1}".format(
        local_core_ca_file, certificate))
    local_mqttc.configureCredentials(
        local_core_ca_file, private_key, certificate
    )
    local_mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)

    if not utils.mqtt_connect(mqtt_client=local_mqttc, core_info=local['core']):
        raise EnvironmentError("Connection to GG Core MQTT failed.")

    # get a shadow client to receive commands
    master_shadow_client = AWSIoTMQTTShadowClient(ggd_name)
    log.info("[initialize] remote ca_file:{0} cert:{1}".format(
        local_core_ca_file, certificate))
    remote_mqttc = master_shadow_client.getMQTTConnection()
    remote_mqttc.configureCredentials(
        remote_core_ca_file, private_key, certificate
    )

    if not utils.mqtt_connect(mqtt_client=master_shadow_client,
                              core_info=remote['core']):
        raise EnvironmentError("Connection to Master Shadow failed.")

    # create and register the shadow handler on delta topics for commands
    # with a persistent connection to the Master shadow
    master_shadow = master_shadow_client.createShadowHandlerWithName(
        cfg['misc']['master_shadow_name'], True)
    log.info("[initialize] created handler for shadow name: {0}".format(
        cfg['misc']['master_shadow_name']
    ))
    token = master_shadow.shadowGet(shadow_mgr, 5)
    log.info("[initialize] shadowGet() tk:{0}".format(token))

    return local_mqttc, remote_mqttc, master_shadow