예제 #1
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)
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)
예제 #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)
예제 #4
0
    def __create_shadow_client(self):
        max_offline_queue_size = int(
            (60 / self.__update_interval_secs) * 24 * 10)  # 10 Days worth
        client = AWSIoTMQTTShadowClient(self.__client_id)
        client.configureEndpoint(AWS_IOT_ENDPOINT, 8883)
        client.configureCredentials(
            CAFilePath="certs/AmazonRootCA1.pem",
            KeyPath="certs/device/private.pem.key",
            CertificatePath="certs/device/certificate.pem.crt")
        client.configureConnectDisconnectTimeout(30)
        client.configureMQTTOperationTimeout(30)
        client.configureAutoReconnectBackoffTime(1, 128, 20)

        # Shared connection with shadow
        mqtt_client = client.getMQTTConnection()
        mqtt_client.configureOfflinePublishQueueing(
            max_offline_queue_size, AWSIoTPythonSDK.MQTTLib.DROP_OLDEST)
        mqtt_client.configureDrainingFrequency(2)  # Draining: 2 Hz

        logger.debug('Connecting to IOT Cloud MQTT Server....')
        client.connect()
        self.__shadow_client = client
        self.__mqtt_client = mqtt_client

        for reader in self.__readers:
            shadow = self.__shadow_client.createShadowHandlerWithName(
                reader.name, True)
            shadow.shadowGet(self.__shadow_cb, 60)
            shadow.shadowRegisterDeltaCallback(self.__shadow_cb)
            self.__shadows[reader.name] = shadow

        logger.info('Connected to IOT Cloud, shadows created')
        return client
예제 #5
0
파일: main.py 프로젝트: Dacode45/hodoor
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 __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
예제 #7
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
예제 #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)
예제 #9
0
파일: AVM20.py 프로젝트: dhrone/pyASH
    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
예제 #10
0
파일: iot-bed.py 프로젝트: igeeks/iot-bed
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)
예제 #11
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
예제 #12
0
def createIoT():
    iot = AWSIoTMQTTShadowClient('AWSHome', useWebsocket=True)
    iot.configureEndpoint('a236biar7596mr.iot.us-east-1.amazonaws.com', 443)
    iot.configureCredentials(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'root-CA.pem'))
    iot.configureConnectDisconnectTimeout(10)  # 10 sec
    iot.configureMQTTOperationTimeout(5)  # 5 sec
    iot.connect()
    return iot
예제 #13
0
def createIoT():
    iot = AWSIoTMQTTShadowClient('RaspberryPi',
                                 useWebsocket=True)  # I think the first arg is the name of the IoT thing in aws
    iot.configureEndpoint('a3lujo7s13ykr5.iot.us-east-1.amazonaws.com', 443)  # REST endpoint
    iot.configureCredentials(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'root-CA.pem'))  # CA certificate
    iot.configureConnectDisconnectTimeout(10)  # 10 sec
    iot.configureMQTTOperationTimeout(5)  # 5 sec
    iot.connect()
    return iot
예제 #14
0
def create_iot():
    iot = AWSIoTMQTTShadowClient(clientId, useWebsocket=True)
    iot.configureEndpoint(host, port)
    iot.configureCredentials(rootCAPath)
    iot.configureAutoReconnectBackoffTime(1, 32, 20)
    iot.configureConnectDisconnectTimeout(10)
    iot.configureMQTTOperationTimeout(5)
    iot.connect()
    return iot
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'])
예제 #16
0
def shadow_connect():
	global myShadowClient
	myShadowClient = AWSIoTMQTTShadowClient(thingName)
	myShadowClient.configureEndpoint(host, 8883)
	myShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
	myShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
	myShadowClient.configureConnectDisconnectTimeout(10)
	myShadowClient.configureMQTTOperationTimeout(5)

	myShadowClient.connect()
예제 #17
0
def shadow_connect(): #連接shadow
	global myShadowClient
	# read GGC Host Address from file
	myShadowClient = AWSIoTMQTTShadowClient(clientId2)
	myShadowClient.configureEndpoint(host, 8883)
	myShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
	myShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
	myShadowClient.configureConnectDisconnectTimeout(10)
	myShadowClient.configureMQTTOperationTimeout(5)

	myShadowClient.connect()
    def connect_to_shadow_service(self, groupCAPath, coreInfo):
        shadowClient = AWSIoTMQTTShadowClient(self.CLIENT_ID)
        shadowClient.configureCredentials(groupCAPath, self.PRIVATE_KEY_PATH, self.CERTIFICATE_PATH)

        connectivityInfo = coreInfo.connectivityInfoList[0]
        ggcHost = connectivityInfo.host
        ggcPort = connectivityInfo.port

        shadowClient.configureEndpoint(ggcHost, ggcPort)
        shadowClient.connect()
        return shadowClient
예제 #19
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)
예제 #20
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()
예제 #21
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
예제 #22
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)
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)
예제 #24
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
예제 #25
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)
예제 #26
0
 def createMqttClients(self, iotConfig):
     mqShadowClient = AWSIoTMQTTShadowClient(iotConfig['thingName'])
     mqShadowClient.configureEndpoint(iotConfig["iotHost"],
                                      iotConfig["iotPort"])
     mqShadowClient.configureCredentials(iotConfig["rootCert"],
                                         iotConfig["thingPrivateKey"],
                                         iotConfig["thingCert"])
     mqShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
     mqShadowClient.configureConnectDisconnectTimeout(10)
     mqShadowClient.configureMQTTOperationTimeout(10)
     mqShadowClient.connect()
     mqClient = mqShadowClient.getMQTTConnection()
     self._logger.info("mqtt client connected to iot host {}".format(
         iotConfig["iotHost"]))
     return (mqShadowClient, mqClient)
예제 #27
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)
예제 #29
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)
예제 #30
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)
예제 #31
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)
예제 #32
0
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
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)
예제 #33
0
파일: thermo.py 프로젝트: mcmspark/thermo
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
예제 #34
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
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()
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)