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)
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
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 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 create_shadow_client(host, ca_file, private_file, cert_file, thing_name): client = AWSIoTMQTTShadowClient(thing_name) client.configureCredentials(ca_file, private_file, cert_file) client.configureEndpoint(host, 8883) client.configureConnectDisconnectTimeout(10) # 10 sec client.configureMQTTOperationTimeout(5) # 5 sec 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 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 _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 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 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 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
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
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 createIoTShadowClient(endpoint, thingname, keyPath, certPath, rootCaPath): # For certificate based connection myShadowClient = AWSIoTMQTTShadowClient(thingname) # Configurations # For TLS mutual authentication myShadowClient.configureEndpoint(endpoint, config.aws_iot_port()) myShadowClient.configureCredentials(rootCaPath, keyPath, certPath) myShadowClient.configureConnectDisconnectTimeout(10) myShadowClient.configureMQTTOperationTimeout(5) return myShadowClient
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 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)
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 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)
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
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)
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 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 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)
import json 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()
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()
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())
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)