class Subscriber(threading.Thread): """A threaded Subscriber object""" def __init__(self, endpoint, root_ca, key, cert, client_id=''): threading.Thread.__init__(self) self.endpoint = endpoint self.client_id = client_id self.root_ca = root_ca self.key = key self.cert = cert self._client = None self.finish = False self.daemon = True self.connected = False def connect(self): self._client = AWSIoTMQTTClient(self.client_id) self._client.configureEndpoint(self.endpoint, 8883) self._client.configureCredentials(self.root_ca, self.key, self.cert) self._client.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing self._client.configureConnectDisconnectTimeout(10) # 10 sec self._client.configureMQTTOperationTimeout(5) # 5 sec self.connected = self._client.connect() def subscribe(self, topic, callback, qos=1): if not self.connected: self.connect() self._client.subscribe(topic, qos, callback) def run(self): while not self.finish: time.sleep(0.001)
class Client(): def __init__(self, iot_client=None, iot_data_client=None, credentials=None, ca_path=None, privkey_path=None, cert_path=None): assert ca_path, "Certificate is required" if not iot_client: iot_client = boto3.client('iot') if not iot_data_client: iot_data_client = boto3.client('iot-data') self.iot_client = iot_client self.iot_data_client = iot_data_client self.cert_path = cert_path self.privkey_path = privkey_path self.ca_path = ca_path self.credentials = credentials self.init_mqtt_client() def init_mqtt_client(self): endpoint = self.iot_client.describe_endpoint() use_websocket = True if self.credentials else False endpoint_port = 443 if use_websocket else 8883 self.mqtt_client = AWSIoTMQTTClient("testo", useWebsocket=use_websocket) self.mqtt_client.configureEndpoint(endpoint['endpointAddress'], endpoint_port) self.mqtt_client.configureOfflinePublishQueueing(-1) self.mqtt_client.configureConnectDisconnectTimeout(10) self.mqtt_client.configureMQTTOperationTimeout(10) self.configure_credentials() log.debug("OpenSSL version {}".format(ssl.OPENSSL_VERSION)) log.debug("Connecting MQTT client to {} on port {}...".format(endpoint['endpointAddress'], endpoint_port)) try: self.mqtt_client.connect() log.debug("MQTT client connected") except connectTimeoutException: log.error("Failed to connect MQTT client - timeout (check policy)") self.mqtt_client = None def configure_credentials(self): if self.credentials: self.mqtt_client.configureIAMCredentials(*(self.credentials.values())) self.mqtt_client.configureCredentials(self.ca_path) elif self.privkey_path and self.cert_path: log.debug("Using %s %s %s", str(self.ca_path), str(self.privkey_path), str(self.cert_path)) self.mqtt_client.configureCredentials(self.ca_path, self.privkey_path, self.cert_path) else: raise Exception("No credentials found")
class IOTCore: def __init__(self): config = {} # read the config file try: config_file = open('./config/aws-iot.json') # parse the content into dictionary config = json.loads(config_file.read()) except FileNotFoundError: print("file not found") raise # connect to iot try: self.client = AWSIoTMQTTClient(config["client"]) self.client.configureEndpoint(config["host"], config["port"]) self.client.configureCredentials(config["root-ca"], config["private-key"], config["certificate"]) self.client.connect() except KeyError: print("Key not found") raise except (exception.operationTimeoutException, exception.operationError) as err: print(err) raise except: print("unknown error") def publish(self, key, data): # publish data to iot try: self.client.publish(key, data, 0) except (exception.operationTimeoutException, exception.operationError) as err: print(err) raise except: print("unknown error") def disconnect(self): # disconnect from iot self.client.disconnect()
myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect() if args.mode == 'both' or args.mode == 'subscribe': myAWSIoTMQTTClient.subscribe(topic, 1, customCallback) time.sleep(2) # Publish to the same topic in a loop forever loopCount = 0 while True: if args.mode == 'both' or args.mode == 'publish': message = {} message['message'] = args.message message['sequence'] = loopCount messageJson = json.dumps(message) myAWSIoTMQTTClient.publish(topic, messageJson, 1) if args.mode == 'publish': print('Published topic %s: %s\n' % (topic, messageJson))
# -*- coding:utf8 -*- from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient import os import time def customCallback(client, userdata, message): print('message: ') print(message.payload) print('topic: ') print(message.topic) print('--------------\n\n') myMQTTClient = AWSIoTMQTTClient('python') myMQTTClient.configureEndpoint(os.environ['AWSIOT_HOST'], 8883) myMQTTClient.configureCredentials('keys/G5.pem', 'keys/private.pem.key', 'keys/certificate.pem.crt') myMQTTClient.configureOfflinePublishQueueing(-1) myMQTTClient.configureDrainingFrequency(2) myMQTTClient.configureConnectDisconnectTimeout(10) myMQTTClient.configureMQTTOperationTimeout(5) myMQTTClient.connect() while True: myMQTTClient.subscribe("test", 1, customCallback) time.sleep(1)
class ElfThread(threading.Thread): """ The abstract thread that sets up interaction with AWS IoT Things """ def __init__(self, thing_name, cli, thing, cfg, args=(), kwargs={}): super(ElfThread, self).__init__( name=thing_name, args=args, kwargs=kwargs ) self.thing_name = thing_name self.thing = thing self.root_cert = cli.root_cert self.topic = '{0}/{1}'.format(cli.topic, self.thing_name) self.region = cli.region self.cfg = cfg self.duration = cli.duration self.aws_iot = _get_iot_session(self.region, cli.profile_name) self.message_qos = cli.qos if policy_name_key not in thing.keys(): policy_name, policy_arn = _create_and_attach_policy( self.region, self.topic, self.thing_name, self.thing['certificateArn'], cli ) self.policy_name = policy_name self.policy_arn = policy_arn log.debug("[elf_thread] attached policy on cert:{0}".format( thing['certificateArn'])) else: log.debug("[elf_thread] policy_name:{0} exists.".format( policy_name_key)) self.policy_name = thing[policy_name_key] self.policy_arn = thing[policy_arn_key] # setup MQTT client elf_id = uuid.UUID(cfg[elf_id_key]) # use ELF ID and a random string since we must use unique Client ID per # client. cid = elf_id.urn.split(":")[2] + "_" + make_string(3) self.mqttc = AWSIoTMQTTClient(clientID=cid) t_name = cfg_dir + thing_name_template.format(0) endpoint = self.aws_iot.describe_endpoint() log.info("ELF connecting asynchronously to IoT endpoint:'{0}'".format( endpoint['endpointAddress'])) self.mqttc.configureEndpoint( hostName=endpoint['endpointAddress'], portNumber=AWS_IOT_MQTT_PORT ) self.mqttc.configureCredentials( CAFilePath=self.root_cert, KeyPath=t_name + ".prv", CertificatePath=t_name + ".pem" ) self.mqttc.configureAutoReconnectBackoffTime(1, 128, 20) self.mqttc.configureOfflinePublishQueueing(90, DROP_OLDEST) self.mqttc.configureDrainingFrequency(3) self.mqttc.configureConnectDisconnectTimeout(20) self.mqttc.configureMQTTOperationTimeout(5) self.mqttc.connect() # keepalive default at 30 seconds
# create AWS IoT MQTT client client = AWSIoTMQTTClient(CLIENT_ID) print("Inside python code") print(sys.argv[1]) IOT_ENDPOINT_ADDRESS = json.loads(sys.argv[1])["endpointAddress"] # configure client endpoint / port information & then set up certs client.configureEndpoint(IOT_ENDPOINT_ADDRESS, settings.HOST_PORT) client.configureCredentials(settings.ROOT_CERT, settings.PRIVATE_KEY, settings.DEVICE_CERT) print(IOT_ENDPOINT_ADDRESS) # configure client connection behavior client.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing client.configureDrainingFrequency(2) # Draining: 2 Hz client.configureConnectDisconnectTimeout(10) # 10 sec client.configureMQTTOperationTimeout(5) # 5 sec print("Connecting to endpoint " + IOT_ENDPOINT_ADDRESS) client.connect() # start loop to begin publishing to topic while True: for dev in devs: client.publish("device/" + dev.name + "/devicePayload", dev.get_payload(), settings.QOS_LEVEL) print("Published message on topic " + "device/" + dev.name + "/devicePayload" + " with payload: " + dev.get_payload()) dev.update() # update the device with new data time.sleep(30) # just wait a sec before publishing next message
class AwsProvider(metaclass=Singleton): __config = {} __client = None __shadow = None __shadowHandle = None __instance = None def __init__(self, config): self.__config = config logger.debug("Initialising AWS Provider...") self.__init_shadow() def __init_client(self): self.__client = AWSIoTMQTTClient(self.__config["aws"]["client_id"]) try: self.__client.configureEndpoint(self.__config["aws"]["endpoint"], self.__config["aws"]["port"]) logger.info("Trying to connect to {}:{}".format( self.__config["aws"]["endpoint"], self.__config["aws"]["port"])) self.__client.configureCredentials(self.__config["aws"]["root"], self.__config["aws"]["private"], self.__config["aws"]["cert"]) # Infinite offline Publish queueing self.__client.configureOfflinePublishQueueing(-1) self.__client.configureDrainingFrequency(2) # Draining: 2 Hz self.__client.configureConnectDisconnectTimeout(10) # 10 sec self.__client.configureMQTTOperationTimeout(5) # 5 sec self.__client.connect() except AWSIoTExceptions.connectTimeoutException as error: logger.error("Problem with MQTT configuration: {}".format(error)) logger.debug("Initialised AWS Standard Client...") def __init_shadow(self): self.__shadow = AWSIoTMQTTShadowClient( self.__config["aws"]["client_id"] + "_shadow") try: self.__shadow.configureEndpoint(self.__config["aws"]["endpoint"], self.__config["aws"]["port"]) logger.info("Trying to connect to {}:{}".format( self.__config["aws"]["endpoint"], self.__config["aws"]["port"])) self.__shadow.configureCredentials(self.__config["aws"]["root"], self.__config["aws"]["private"], self.__config["aws"]["cert"]) # Infinite offline Publish queueing self.__shadow.configureAutoReconnectBackoffTime(1, 32, 20) self.__shadow.configureConnectDisconnectTimeout(10) # 10 sec self.__shadow.configureMQTTOperationTimeout(5) # 5 sec self.__shadow.connect() self.__shadowHandle = self.__shadow.createShadowHandlerWithName( self.__config["aws"]["thing_id"], True) except AWSIoTExceptions.connectTimeoutException as error: logger.error("Problem with MQTT configuration: {}".format(error)) logger.debug("Initialised AWS Standard Client...") def get_client(self): if self.__client is None: self.__init_client() return self.__client def get_shadow_handle(self): if self.__shadowHandle is None: self.__init_shadow() return self.__shadowHandle
else: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect() if args.mode == 'both' or args.mode == 'subscribe': myAWSIoTMQTTClient.subscribe(topic, 1, customCallback) time.sleep(2) # Publish to the same topic in a loop forever loopCount = 0 xbee = ZigBee(SERIAL_PORT, escaped=True, callback=handleXBee) os.chdir("/home/pi/sensing_data") try: while True: time.sleep(0.000001) except KeyboardInterrupt: xbee.halt()