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
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)
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 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)
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
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 _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
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
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 configureMQTTClient(self): mqttClient = AWSIoTMQTTShadowClient(self.thingName) mqttClient.configureEndpoint(self.host, self.port) mqttClient.configureCredentials(self.rootCAPath, self.privateKeyPath, self.certificatePath) mqttClient.configureAutoReconnectBackoffTime(1, 32, 20) mqttClient.configureConnectDisconnectTimeout(10) mqttClient.configureMQTTOperationTimeout(5) return mqttClient
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'])
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()
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 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
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 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
def getClient(host, rootCAPath, privateKeyPath, certificatePath, clientId): # Init AWSIoTMQTTShadowClient myAWSIoTMQTTShadowClient = None 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 return myAWSIoTMQTTShadowClient
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)
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
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)
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 buildMQTTShadowClient(configFile): # read config with open(configFile) as f: conf = json.load(f) # init shadow client client = AWSIoTMQTTShadowClient(conf['thingName'] + '_shadow') client.configureEndpoint(conf['endpoint'], int(conf['port'])) client.configureCredentials(conf['rootCA'], conf['key'], conf['cert']) # client config client.configureAutoReconnectBackoffTime(1, 32, 20) client.configureConnectDisconnectTimeout(10) # 10 sec client.configureMQTTOperationTimeout(5) # 5 sec return client, conf
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)
def _init_shadow_client(self): # Assign locations of certificates and keys root_cert = r"certs/root-CA.crt" private_key = r"certs/" + self.thing_name + ".private.key" public_key = r"certs/" + self.thing_name + ".public.key" policy = r"certs/" + self.thing_name + ".cert.pem" # For certificate based connection my_shadow_client = AWSIoTMQTTShadowClient(self.thing_name) # Configurations # For TLS mutual authentication my_shadow_client.configureEndpoint(self.host, 8883) my_shadow_client.configureCredentials(root_cert, private_key, policy) my_shadow_client.configureAutoReconnectBackoffTime(1, 32, 20) my_shadow_client.configureConnectDisconnectTimeout(10) # 10 sec my_shadow_client.configureMQTTOperationTimeout(5) # 5 sec return my_shadow_client
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'])
def _get_shadow_client(self): if self._shadow_client is not None: return self._shadow_client if self.use_websocket: client = AWSIoTMQTTShadowClient(self.client_id, useWebsocket=True) else: client = AWSIoTMQTTShadowClient(self.client_id) client.configureEndpoint(self.endpoint, self.port) if self.use_websocket: client.configureCredentials(self.root_ca) else: client.configureCredentials(self.root_ca, self.private_key, self.certificate) client.configureAutoReconnectBackoffTime(1, 32, 20) #client.configureOfflinePublishQueueing(-1) #client.configureDrainingFrequency(2) client.configureConnectDisconnectTimeout(10) client.configureMQTTOperationTimeout(5) client.clearLastWill() client.connect() self._shadow_client = client return self._shadow_client
def get_myShadowClient(): # Get device configuration details with open('config.json', 'r') as cfg: device = json.load(cfg) thing_uid = device['uid'] # Get keyfile paths key_dir = f'{os.getcwd()}/keys/' if os.path.exists(key_dir): try: with open(f'{key_dir}{thing_uid}.crt', 'r') as r: root_file = f'{key_dir}RootCA.pem' key_file = f'{key_dir}{thing_uid}.private.key' crt_file = f'{key_dir}{thing_uid}.crt' except FileNotFoundError as err: print(f'Issue with filenames in <{key_dir}>') print(str(err)) else: print(f'Path <{key_dir} does not exist; verify working directory') # Certificate based connection myShadowClient = AWSIoTMQTTShadowClient(thing_uid) print(f'Shadow Client: {myShadowClient}') print(f'Shadow Client ID: {thing_uid}') # Configuration for TLS mutual authentication myShadowClient.configureEndpoint(device['endpt'], int(device['prt'])) myShadowClient.configureCredentials(root_file, key_file, crt_file) myShadowClient.configureAutoReconnectBackoffTime(1, 32, 20) myShadowClient.configureConnectDisconnectTimeout(10) # 10 sec myShadowClient.configureMQTTOperationTimeout(5) # 5 sec print('Shadow Client Configured') myShadowClient.connect() print('Shadow Client Connected') return myShadowClient, device
def start(): logging.info("----- START OF THE IoT LOG -----") try: dir = os.path.dirname(os.path.realpath(__file__)) rootCAPath = dir + "/root-CA.crt" certificatePath = dir + "/device.cert.pem" privateKeyPath = dir + "/device.private.key" streamHandler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) global myAWSIoTMQTTClient, host myAWSIoTMQTTClient = AWSIoTMQTTShadowClient("pc") myAWSIoTMQTTClient.configureEndpoint(host, 8883) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureConnectDisconnectTimeout(30) myAWSIoTMQTTClient.configureMQTTOperationTimeout(10) # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect(10) global connection connection = myAWSIoTMQTTClient.getMQTTConnection() connection.configureAutoReconnectBackoffTime(1, 32, 20) connection.configureDrainingFrequency(2) # Draining: 2 Hz connection.configureConnectDisconnectTimeout(30) # 10 sec connection.configureMQTTOperationTimeout(10) # 5 sec connection.subscribe(topic, 1, customCallback) SendMSG('{"to": "server", "client-id": "2", "info": "start-up"}') except Exception as e: logging.exception("Error IoT: " + str(e)) print("Error IoT: " + str(e)) import traceback traceback.print_exc()
def getShadowClient( host=host, port=8883, device=device, clientId=clientId, rootCa='{}/AmazonRootCA1.pem'.format(certPath), private_key='{}/thing_private_key.pem.key'.format(certPath), certificate='{}/thing_cert.pem.crt'.format(certPath)): # Init AWSIoTMQTTClient myAWSIoTMQTTClient = None myAWSIoTMQTTClient = AWSIoTMQTTShadowClient(clientId) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCa, private_key, certificate) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec if not myAWSIoTMQTTClient.connect(): return None return myAWSIoTMQTTClient
class IoTCoreClient: def __init__(self): self._iot = AWSIoTMQTTShadowClient(_CLIENT_ID, useWebsocket=True) self._iot.configureEndpoint(_HOST, _PORT) self._iot.configureCredentials(_ROOT_CA_PATH) self._iot.configureAutoReconnectBackoffTime(1, 32, 20) self._iot.configureConnectDisconnectTimeout(10) self._iot.configureMQTTOperationTimeout(5) self._iot.connect() def create_shadow_handler(self, thing_name, handler): shadow = self._iot.createShadowHandlerWithName(thing_name, True) @logger.log_with(_LOG, device=thing_name) def do_update(state): value = "ON" if state else "OFF" shadow.shadowUpdate( json.dumps({"state": { "reported": { "state": value } }}), None, 5) @logger.log_with(_LOG, device=thing_name) def on_get(payload, response_status, token): state = json.loads(payload)['state']['desired']['state'] if state in ['ON', 'OFF']: handler(state == "ON") @logger.log_with(_LOG, device=thing_name) def on_delta(payload, response_status, token): state = json.loads(payload)['state']['state'] if state in ['ON', 'OFF']: handler(state == "ON") shadow.shadowGet(on_get, 5) shadow.shadowRegisterDeltaCallback(on_delta) return do_update
print (mac) s3 = boto3.client('s3', aws_access_key_id= open('keys.txt').readline().split(None, 1)[0], aws_secret_access_key= open('keys.txt').readlines()[1].split(None, 1)[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())
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()
streamHandler.setFormatter(formatter) 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 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