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 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)
def setup_session(self): logger.info("Setup session") from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient from AWSIoTPythonSDK.core.protocol.mqttCore import ( connectTimeoutException) client_id, token = self.storage["client_id"], self.storage["token"] if not client_id or not token: raise SystemError("client_id or token error") try: ipaddr, port = self.storage["endpoint"].split(":") except (AttributeError, ValueError): raise SystemError("endpoint error") cafile = self.storage.get_path("certificate_reqs.pem") cert = self.storage.get_path("certificate.pem") key = self.storage.get_path("key.pem") if False in map(lambda p: os.path.exists(p), (cafile, cert, key)): raise SystemError("cafile or cert or key not exist") client = AWSIoTMQTTShadowClient(client_id) client.configureEndpoint(ipaddr, int(port)) client.configureCredentials(cafile, key, cert) client.configureConnectDisconnectTimeout(10) client.configureMQTTOperationTimeout(5) try: client.connect() except SSLError as e: raise RuntimeError("SESSION", "TLS_ERROR", "%s" % e.reason) except (connectTimeoutException, socket.gaierror, socket.error): raise RuntimeError("SESSION", "CONNECTION_ERROR") conn = client.getMQTTConnection() conn.subscribe("device/%s/request/+" % self.storage["token"], 1, self.aws_on_request_callback) self.aws_client = client self.aws_token = token self._notify_topic = "$aws/things/%s/shadow/update" % ( self.storage["client_id"]) self.notify_up(conn) metadata.cloud_hash = os.urandom(32) logger.info("Session ready")
def weather_station(event, context): """ Create an AWS IoT shadow client for a specific remote sensor station. Collect sensor data from the station via an Internet endpoint. Update the shadow client with the desired subset of available sensor station data. Args (supplied by AWS Lambda service) event: information about who/what invoked the Lambda function context: information about the Lambda function's runtime environment Returns: { 'statusCode': <int value>, 'body': <status string> } """ shadow_client = AWSIoTMQTTShadowClient(SHADOW_CLIENT) shadow_client.configureEndpoint(HOST_NAME, MQTT_PORT) shadow_client.configureCredentials(ROOT_CA, PRIVATE_KEY, CERT_FILE) shadow_client.configureConnectDisconnectTimeout(10) shadow_client.configureMQTTOperationTimeout(5) if (shadow_client.connect()): #Create access point for AWS IoT shadow document device_shadow = shadow_client.createShadowHandlerWithName( SHADOW_HANDLER, True) sensor_data = _extract_sensor_data() if (sensor_data): # specific format required; ' "state" : {"reported" : {....... ' update_string = '{"state":{"reported":' update_string += json.dumps(sensor_data) update_string += '}}' # result of updating shadow document; set in _my_shadow_update_callback() device_shadow.shadowUpdate(update_string, _my_shadow_update_callback, 5) else: return_value['statusCode'] = 400 return_value[ 'body'] = 'Error connecting to sensor or with sensor data.' else: return_value['statusCode'] = 500 return_value['body'] = 'Could not connect to IoT shadow.' return (return_value)
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_device_shadow_client(location): """ Each vineyard sensor station is set up in IoT Core as a 'Thing' with its own 'shadow document.' In order to push data into AWS, for a sensor, you update its shadow document. To do this you use a 'shadow client' to place a message, containing the incoming sensor data, on the message queue assigned to the sensor/thing/shadow document. Each IoT shadow document is assigned its own shadow client. Shadow clients are created by this module, on demand, and exist for the duration of this module's execution. Shadow clients will be reused (for the duration of this module's execution) in cases where multiple data sensor records are processed for the same sensor station. Reuse of shadow clients is possible because of the 'True' flag in the createShadowHandlerWithName() call. Returns None if a device shadow could not be retrieved/created device_shadow if a device shadow could be retrieved/created """ global device_shadows a_device_shadow = None if(location in device_shadows): a_device_shadow = device_shadows[location] else: a_client = AWSIoTMQTTShadowClient(location) a_client.configureEndpoint(MQTT_VALUES['host_name'], MQTT_VALUES['mqtt_port']) a_client.configureCredentials(SHADOW_SECURITY[location]['root_ca'], SHADOW_SECURITY[location]['private_key'], SHADOW_SECURITY[location]['cert_file']) a_client.configureConnectDisconnectTimeout(10) a_client.configureMQTTOperationTimeout(5) if(not a_client.connect()): sl.log_message('15', ERROR, 'Could not connect to shadow document' + ' for location: ' + location, '') else: a_device_shadow = a_client.createShadowHandlerWithName( SHADOW_SECURITY[location]['handler'], True) device_shadows[location] = a_device_shadow return(a_device_shadow)
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
def __init__(self): certificatePath, privateKeyPath = self._get_cert_files() settings = self._get_settings() host = settings['host_name'] rootCAPath = "cert/AmazonRootCA1.pem" port = 8883 clientId = "coffee-panic-client" # Init AWSIoTMQTTClient client = AWSIoTMQTTShadowClient(clientId) client.configureEndpoint(host, port) client.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration client.configureAutoReconnectBackoffTime(1, 32, 20) client.configureConnectDisconnectTimeout(10) # 10 sec client.configureMQTTOperationTimeout(5) # 5 sec # Connect to AWS IoT client.connect() self.shadow_handler = client.createShadowHandlerWithName( settings['thing_name'], True)
def get_device_shadow_handler(): congig_json = ThermoUtils.load("aws_iot_config.json") endpoint = congig_json['endpoint'] root_ca_path = congig_json['rootCAPath'] certificate_path = congig_json['certificatePath'] private_key_path = congig_json['privateKeyPath'] thing_name = congig_json['thingName'] client_id = congig_json['clientId'] # Configure logging logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.INFO) stream_handler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) # Init AWSIoTMQTTShadowClient mqtt_shadow_client = AWSIoTMQTTShadowClient(client_id) mqtt_shadow_client.configureEndpoint(endpoint, 8883) mqtt_shadow_client.configureCredentials(root_ca_path, private_key_path, certificate_path) # AWSIoTMQTTShadowClient configuration mqtt_shadow_client.configureAutoReconnectBackoffTime(1, 32, 20) mqtt_shadow_client.configureConnectDisconnectTimeout(10) # 10 sec mqtt_shadow_client.configureMQTTOperationTimeout(5) # 5 sec # Connect to AWS IoT mqtt_shadow_client.connect() # Create a deviceShadow with persistent subscription device_shadow_handler = mqtt_shadow_client.createShadowHandlerWithName( thing_name, True) return device_shadow_handler
logger.addHandler(streamHandler) # Init AWSIoTMQTTShadowClient myAWSIoTMQTTShadowClient = None if useWebsocket: myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId, useWebsocket=True) myAWSIoTMQTTShadowClient.configureEndpoint(host, 443) myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath) else: myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId) myAWSIoTMQTTShadowClient.configureEndpoint(host, 8883) myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTShadowClient configuration myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5) # 5 sec # Connect to AWS IoT myAWSIoTMQTTShadowClient.connect() # Create a deviceShadow with persistent subscription deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(thingName, True) # Listen on deltas deviceShadowHandler.shadowRegisterDeltaCallback(customShadowCallback_Delta) # Loop forever while True: time.sleep(1)
class ThermoSimAppGUI: _usage = """Usage: Make sure that you put all your credentials under: ./certs/ with the following naming conventions: Root CA file: *CA.crt Certificate file (not required if using MQTT over WebSocket): *.pem.crt Private key file (not required if using MQTT over WebSocket): *.pem.key Use X.509 certificate based mutual authentication: python ThermostatSimulatorApp -e <endpoint> Use MQTT over WebSocket: python ThermostatSimulatorApp -e <endpoint> -w Type "python ThermostatSimulatorApp -h" for detailed command line options. """ _helpInfo = """Available command line options: -e, --endpoint: Your custom AWS IoT custom endpoint -w, --websocket: Use MQTT over websocket -h, --help: Help infomation """ def __init__(self): # Init data members # Connection related self._endpoint = "" self._rootCAFilePathList = "" self._certificateFilePathList = "" self._privateKeyFilePathList = "" self._useWebsocket = False self._AWSIoTMQTTShadowClient = None self._thermostatSimulatorShadowHandler = None # GUI related self._tkRootHandler = tkinter.Tk() self._reportedDataVariable = None self._reportedDataDisplayBox = None self._desiredDataVariable = None self._desiredDataDisplayBox = None self._setTemperatureInputBox = None self._setTemperatureButton = None # Check command line inputs if not self._checkInputs(): raise ValueError("Malformed/Missing command line inputs.") # Create and configure AWSIoTMQTTShadowClient self._AWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient("ThermostatSimulatorApp", useWebsocket=self._useWebsocket) if self._useWebsocket: self._AWSIoTMQTTShadowClient.configureEndpoint(self._endpoint, 443) self._AWSIoTMQTTShadowClient.configureCredentials(self._rootCAFilePathList[0]) else: self._AWSIoTMQTTShadowClient.configureEndpoint(self._endpoint, 8883) self._AWSIoTMQTTShadowClient.configureCredentials(self._rootCAFilePathList[0], self._privateKeyFilePathList[0], self._certificateFilePathList[0]) self._AWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 128, 20) self._AWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10) self._AWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5) # Set keepAlive interval to be 1 second and connect # Raise exception if there is an error in connecting to AWS IoT self._AWSIoTMQTTShadowClient.connect(5) self._thermostatSimulatorShadowHandler = self._AWSIoTMQTTShadowClient.createShadowHandlerWithName("room", True) # Generate GUI self._packModule() # Validate command line inputs # Return False there is any malformed inputs # Return True if all the necessary inputs have been discovered def _checkInputs(self): gotEoughInputs = True # Check command line inputs try: opts, args = getopt.getopt(sys.argv[1:], "hwe:", ["endpoint=", "websocket", "help"]) if len(opts) == 0: raise getopt.GetoptError("No input parameters") for opt, arg in opts: if opt in ("-e", "--endpoint"): self._endpoint = arg if opt in ("-w", "--websocket"): self._useWebsocket = True if opt in ("-h", "--help"): print(self._helpInfo) gotEoughInputs = False except getopt.GetoptError: print(self._usage) gotEoughInputs = False # Check credential files if gotEoughInputs: self._rootCAFilePathList = glob.glob("./certs/*CA.crt") if self._useWebsocket: gotEoughInputs = gotEoughInputs and len(self._rootCAFilePathList) != 0 if not gotEoughInputs: print("Missing rootCA in ./certs/") else: self._certificateFilePathList = glob.glob("./certs/*.pem.crt") self._privateKeyFilePathList = glob.glob("./certs/*.pem.key") gotEoughInputs = gotEoughInputs and len(self._rootCAFilePathList) != 0 and len(self._certificateFilePathList) != 0 and len(self._privateKeyFilePathList) != 0 if not gotEoughInputs: print("Missing rootCA, certificate or private key in ./certs/") return gotEoughInputs def _packModule(self): self._tkRootHandler.title("ThermostatSimulatorApp") self._tkRootHandler.geometry("500x250") self._tkRootHandler.resizable(width=False, height=False) # Pack all frames baseFrame = tkinter.Frame(self._tkRootHandler) temperatureFrame = tkinter.Frame(baseFrame) temperatureFrame.pack(side="top") controlPanelFrame = tkinter.Frame(baseFrame) controlPanelFrame.pack(side="bottom") baseFrame.pack() # Pack all modules for temperature frame self._reportedDataVariable = tkinter.StringVar() self._reportedDataVariable.set("XX.X F") reportedDataTag = tkinter.Label(temperatureFrame, text="Reported Temperature:", justify="left") self._reportedDataDisplayBox = tkinter.Label(temperatureFrame, textvariable=self._reportedDataVariable, font=("Arial", 55), justify="left") # self._desiredDataVariable = tkinter.StringVar() self._desiredDataVariable.set("XX.X F") desiredDataTag = tkinter.Label(temperatureFrame, text="Desired Temperature:", justify="left") self._desiredDataDisplayBox = tkinter.Label(temperatureFrame, textvariable=self._desiredDataVariable, font=("Arial", 55), justify="left") # reportedDataTag.pack() self._reportedDataDisplayBox.pack() desiredDataTag.pack() self._desiredDataDisplayBox.pack() # Create a callback pool self._callbackPoolHandler = ThermoSimAppCallbackPool(self._tkRootHandler, self._reportedDataDisplayBox, self._thermostatSimulatorShadowHandler, self._reportedDataVariable, self._desiredDataVariable) # Pack all modules for control panel frame self._setTemperatureInputBox = tkinter.Entry(controlPanelFrame) self._setTemperatureInputBox.pack(sid="left") self._setTemperatureButton = tkinter.Button(controlPanelFrame, text="SET", command=lambda: self._callbackPoolHandler.buttonCallback(self._setTemperatureInputBox, self._desiredDataVariable)) self._setTemperatureButton.pack() def runApp(self): # Start and run the app self._tkRootHandler.after(500, self._callbackPoolHandler.sendShadowGetForReportedTemperature) # per 500ms self._tkRootHandler.after(500, self._callbackPoolHandler.updateReportedTemperatureDataVariable) # per 500ms self._tkRootHandler.mainloop()
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())