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 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
def __init__(self, host, rootCAPath, certificatePath, privateKeyPath, thingName, clientId, useWebsocket=False): self.host = host self.rootCAPath = rootCAPath self.certificatePath = certificatePath self.privateKeyPath = privateKeyPath self.useWebsocket = useWebsocket self.thingName = thingName self.clientId = clientId 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) # 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 self.myAWSIoTMQTTShadowClient = None if useWebsocket: self.myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId, useWebsocket=True) self.myAWSIoTMQTTShadowClient.configureEndpoint(host, 443) self.myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath) else: self.myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId) self.myAWSIoTMQTTShadowClient.configureEndpoint(host, 8883) self.myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTShadowClient configuration self.myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20) self.myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10) # 10 sec self.myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5) # 5 sec # Connect to AWS IoT self.myAWSIoTMQTTShadowClient.connect() # Create a deviceShadow with persistent subscription self.deviceShadowHandler = self.myAWSIoTMQTTShadowClient.createShadowHandlerWithName(thingName, True) self.shadowCallbackContainer_Bot = ShadowCallbackContainer(self.deviceShadowHandler) # Listen on deltas self.deviceShadowHandler.shadowRegisterDeltaCallback(self.shadowCallbackContainer_Bot.customShadowCallbackDelta) # Create the initial State self._desired_state = {} self._reported_state = {} self._devices = []
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 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 __init__(self): self.__host = 'axt811sti1q4w-ats.iot.us-east-2.amazonaws.com' self.__rootCA = '../certs/root-CA.crt' self.__certPem = '../certs/bpiController.cert.pem' self.__privateKey = '../certs/bpiController.private.key' self.__port = 8883 self.__clientId = 'bpiControllerDevice' self.__thingName = 'bpiController' self.__thingType = 'Gateway' self.mqttClient = None self.basicMqttClient = None self.deviceShadowHandler = None # 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 self.mqttClient = AWSIoTMQTTShadowClient(self.__clientId) self.mqttClient.configureEndpoint(self.__host, self.__port) self.mqttClient.configureCredentials(self.__rootCA, self.__privateKey, self.__certPem) # AWSIoTMQTTShadowClient configuration self.mqttClient.configureAutoReconnectBackoffTime(1, 32, 20) self.mqttClient.configureConnectDisconnectTimeout(10) # 10 sec self.mqttClient.configureMQTTOperationTimeout(5) # 5 sec
def __init__(self, clientId, endpoint, endpoint_port, root_ca, private_key, device_cert): self.clientId = clientId self.endpoint = endpoint self.endpoint_port = endpoint_port self.root_ca = root_ca self.private_key = private_key self.device_cert = device_cert self.state = {} # initalize shadow client self.shadow_client = AWSIoTMQTTShadowClient(self.clientId) self.shadow_client.configureEndpoint(self.endpoint, self.endpoint_port) self.shadow_client.configureCredentials(self.root_ca, self.private_key, self.device_cert) # For Websocket, we only need to configure the root CA # myShadowClient.configureCredentials("YOUR/ROOT/CA/PATH") self.shadow_client.configureConnectDisconnectTimeout(10) # 10 sec self.shadow_client.configureMQTTOperationTimeout(5) # 5 sec self.shadow_client.connect() # Create a device shadow instance using persistent subscription self.device_shadow = self.shadow_client.createShadowHandlerWithName( clientId, True) # Shadow operations self.device_shadow.shadowGet(self.__get_shadow_callback, 5) # device_shadow.shadowUpdate(myJSONPayload, customCallback, 5) # Listen on deltas self.device_shadow.shadowRegisterDeltaCallback( self.__shadow_delta_callback)
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 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__(self, cfg, vehicle, delta_callback=None): self.vehicle = vehicle self.model_num = 0 self._shadow_client = AWSIoTMQTTShadowClient(cfg.CLIENT_NAME) self._shadow_client.configureEndpoint(cfg.IOT_ENDPOINT, 8883) self._shadow_client.configureCredentials(cfg.ROOT_CERT_PATH, cfg.PRIVATE_KEY_PATH, cfg.CERT_PATH_PATH) self._shadow_client.configureConnectDisconnectTimeout(10) # 10 sec self._shadow_client.configureMQTTOperationTimeout(5) # 5 sec if not self._shadow_client.connect(): print("Cannot connect to IoT. This is bad.") self.shadow_handler = self._shadow_client.createShadowHandlerWithName( cfg.THING_NAME, True) # Delete any existing shadow and create a fresh one self.shadow_handler.shadowDelete(self._delete_callback, 5) self.shadow = { "state": { "reported": { "location": 0, "destination": 0, "current_order": "0", } } } self.shadow_handler.shadowUpdate(json.dumps(self.shadow), self._update_callback, 5) # Create subscription to shadow delta topic to receive delivery requests if delta_callback: self.shadow_handler.shadowRegisterDeltaCallback(delta_callback) else: self.shadow_handler.shadowRegisterDeltaCallback( self._delta_callback)
def connectIoTAttempt(ep, port, rootca, key, cert, timeoutSec, retryLimit): global awsIoTMQTTClient, awsShadowClient, weatherDeviceShadow awsShadowClient = AWSIoTMQTTShadowClient(cfgThingName) awsShadowClient.configureEndpoint(ep, 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) awsIoTMQTTClient.configureMQTTOperationTimeout(timeoutSec) #Attempt to connect for attempt in range(0, retryLimit): try: if awsIoTMQTTClient.connect(): print("AWS IoT connected") ledOn("green") except Exception, e: print str(e) continue break
def connectDeviceShadow(self): #host = "a30rsz8andmfjk.iot.ap-southeast-2.amazonaws.com" #rootCAPath = "private/root-CA.crt" #host = "192.168.3.214" #host = "127.0.0.1" host = "HappyHomeGroup_Core" rootCAPath = "private/core/dev.crt" print(self._shadowName) self._shadowClient = AWSIoTMQTTShadowClient(self._shadowName) self._shadowClient.configureEndpoint(host, 8883) self._shadowClient.configureCredentials(rootCAPath, self._privateKeyPath, self._certificatePath) # AWSIoTMQTTShadowClient configuration self._shadowClient.configureAutoReconnectBackoffTime(5, 250, 20) self._shadowClient.configureConnectDisconnectTimeout(10) # 10 sec self._shadowClient.configureMQTTOperationTimeout(25) # 5 sec self._shadowClient.connect() self._deviceShadow = self._shadowClient.createShadowHandlerWithName( self._shadowName, True) self._deviceShadow.shadowRegisterDeltaCallback( lambda payload, responseStatus, token: self. shadowDeltaChangeHandler(payload, responseStatus, token)) print("device connected")
def __init__(self): # Cofigure logging self.logger = logging.getLogger("AWSIoTPythonSDK.core") self.logger.setLevel(logging.DEBUG) self.streamHandler = logging.StreamHandler() self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') self.streamHandler.setFormatter(self.formatter) self.logger.addHandler(self.streamHandler) self.awsiotHost = "a130ba174k0fld-ats.iot.us-west-2.amazonaws.com" self.awsiotPort = 8883 self.rootCAPath = "/home/pi/Mirror/VeriSign-Class3-Public-Primary-Certification-Authority-G5.pem" self.privateKeyPath = "/home/pi/Mirror/f31485c816-private.pem.key" self.certificatePath = "/home/pi/Mirror/f31485c816-certificate.pem.crt" self.myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient("RPI_RULE") self.myAWSIoTMQTTShadowClient.configureEndpoint(self.awsiotHost, self.awsiotPort) self.myAWSIoTMQTTShadowClient.configureCredentials(self.rootCAPath, self.privateKeyPath, self.certificatePath) self.myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20) self.myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10) # 10sec self.myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(10) #5sec self.myAWSIoTMQTTShadowClient._AWSIoTMQTTClient.configureOfflinePublishQueueing(5, AWSIoTPythonSDK.core.util.enums.DropBehaviorTypes.DROP_OLDEST) #connect to AWS IoT self.myAWSIoTMQTTShadowClient.connect() #create a devcie Shadow with persistent subscription self.thingName = "SNS_service" self.deviceShadowHandler = self.myAWSIoTMQTTShadowClient.createShadowHandlerWithName(self.thingName, True) self.window_status = "False" self.people_status = "True" self.face_status = "False"
def __init__(self): path = os.path.abspath(os.path.dirname(__file__)) self._shadowC = AWSIoTMQTTShadowClient("shadow") self._shadowC.configureEndpoint( "a1g1flllk3y7ps.iot.ap-northeast-1.amazonaws.com", 8883) self._shadowC.configureCredentials( os.path.join(path, "credentials/aws/aws-root.pem"), os.path.join(path, "credentials/device/private.pem.key"), os.path.join(path, "./credentials/device/certificate.pem.crt")) self._shadowC.configureConnectDisconnectTimeout(10) self._shadowC.configureMQTTOperationTimeout(5) # For certificate based connection self._mqttC = AWSIoTMQTTClient("regular") self._mqttC.configureEndpoint( "a1g1flllk3y7ps.iot.ap-northeast-1.amazonaws.com", 8883) self._mqttC.configureCredentials( os.path.join(path, "credentials/aws/aws-root.pem"), os.path.join(path, "credentials/device/private.pem.key"), os.path.join(path, "./credentials/device/certificate.pem.crt")) self._mqttC.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing self._mqttC.configureDrainingFrequency(2) # Draining: 2 Hz self._mqttC.configureConnectDisconnectTimeout(10) # 10 sec self._mqttC.configureMQTTOperationTimeout(5) # 5 sec
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 __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(): 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 assign_shadow_certificates(): # assign the certificates for the connection to the device shadow on the IoT core. shadowclient = AWSIoTMQTTShadowClient("client id") shadowclient.configureEndpoint("your endpoint", 8883) shadowclient.configureCredentials("rootCA.pem", "private key", "certificate") return shadowclient
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 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)
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 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 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 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 cert_assignment(): MQTTclient = AWSIoTMQTTClient("rasp_pi_sub") Shadowclient = AWSIoTMQTTShadowClient("rasp_pi_sub_shadow") MQTTclient.configureEndpoint("endpoint", 8883) Shadowclient.configureEndpoint("endpoint", 8883) MQTTclient.configureCredentials("rootCA.pem", "private key", "certificate") Shadowclient.configureCredentials("rootCA.pem", "private key", "certificate") return MQTTclient, Shadowclient
def connect(self): self.log.info('init(): connecting to AWS Shadow') self.client = AWSIoTMQTTShadowClient("iota") self.client.configureEndpoint(self.thingEndpoint, 8883) self.client.configureCredentials(*self.credentialFiles) self.client.configureConnectDisconnectTimeout(10) # 10 sec self.client.configureMQTTOperationTimeout(5) # 5 sec self.client.connect() self.log.info('init(): connected to AWS Shadow')
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 test_awsiotmqtt_shadow_client_connect(mock_connect, mock_disconnect): client = AWSIoTMQTTShadowClient("myClientID", useWebsocket=False, hostName="YOUR.ENDPOINT", portNumber=8883) with client: client.createShadowHandlerWithName("Bot", True) mock_connect.assert_called_once_with(600) mock_disconnect.assert_called_once_with()
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