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)
def core_connect(device_name, config_file, root_ca, certificate, private_key, group_ca_path): global ggd_name, mqttc cfg = GroupConfigFile(config_file) ggd_name = cfg['devices'][device_name]['thing_name'] iot_endpoint = cfg['misc']['iot_endpoint'] dip = DiscoveryInfoProvider() dip.configureEndpoint(iot_endpoint) dip.configureCredentials( caPath=root_ca, certPath=certificate, keyPath=private_key ) dip.configureTimeout(10) # 10 sec logging.info("[button] Discovery using CA:{0} cert:{1} prv_key:{2}".format( root_ca, certificate, private_key )) gg_core, discovery_info = utils.discover_configured_core( device_name=device_name, dip=dip, config_file=config_file, ) if not gg_core: raise EnvironmentError("[button] Couldn't find the Core") ca_list = discovery_info.getAllCas() group_id, ca = ca_list[0] group_ca_file = utils.save_group_ca(ca, group_ca_path, group_id) mqttc = AWSIoTMQTTClient(ggd_name) # local Greengrass Core discovered, now connect to Core from this Device log.info("[button] gca_file:{0} cert:{1}".format( group_ca_file, certificate)) mqttc.configureCredentials(group_ca_file, private_key, certificate) mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST) return mqttc, gg_core
def heartbeat(config_file, topic, frequency=3): # read the config file cfg = GroupConfigFile(config_file) # determine heartbeat device's thing name and orient MQTT client to GG Core heartbeat_name = cfg['devices']['GGD_heartbeat']['thing_name'] mqttc = AWSIoTMQTTClient(heartbeat_name) mqttc.configureEndpoint(ggd_config.inv_arm_ip, ggd_config.inv_arm_port) mqttc.configureCredentials( CAFilePath=dir_path + "/" + ggd_ca_file_path, KeyPath=dir_path + "/certs/GGD_heartbeat.private.key", CertificatePath=dir_path + "/certs/GGD_heartbeat.certificate.pem.crt" ) mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST) if mqtt_connect(mqttc): # MQTT client has connected to GG Core, start heartbeat messages try: start = datetime.datetime.now() while True: hostname = socket.gethostname() now = datetime.datetime.now() msg = { "version": "2017-07-05", # YYYY-MM-DD "ggd_id": heartbeat_name, "hostname": hostname, "data": [ { "sensor_id": "heartbeat", "ts": now.isoformat(), "duration": str(now - start) } ] } print("[hb] publishing heartbeat msg: {0}".format(msg)) mqttc.publish(topic, json.dumps(msg), 0) time.sleep(random.random() * 10) except KeyboardInterrupt: log.info( "[__main__] KeyboardInterrupt ... exiting heartbeat") mqttc.disconnect() time.sleep(2) else: print("[hb] could not connect successfully via mqtt.")
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()
# print identityPoolInfo temporaryIdentityId = cognitoIdentityClient.get_id(IdentityPoolId=identityPoolID) identityID = temporaryIdentityId["IdentityId"] temporaryCredentials = cognitoIdentityClient.get_credentials_for_identity(IdentityId=identityID) AccessKeyId = temporaryCredentials["Credentials"]["AccessKeyId"] SecretKey = temporaryCredentials["Credentials"]["SecretKey"] SessionToken = temporaryCredentials["Credentials"]["SessionToken"] # Init AWSIoTMQTTClient myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True) # AWSIoTMQTTClient configuration myAWSIoTMQTTClient.configureEndpoint(host, 443) myAWSIoTMQTTClient.configureCredentials(rootCAPath) myAWSIoTMQTTClient.configureIAMCredentials(AccessKeyId, SecretKey, SessionToken) 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() myAWSIoTMQTTClient.subscribe(topic, 1, customCallback) time.sleep(2) # Publish to the same topic in a loop forever loopCount = 0 while True:
payload = '{"Temperature": ' + "yessir!" + '}' print("Triggered") myMQTTClient.publish("ryan_pi/data", payload, 0) # initialize GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(21, GPIO.FALLING, callback=event, bouncetime=5000) # AWS IoT certificate based connection myMQTTClient = AWSIoTMQTTClient("myClientID") myMQTTClient.configureEndpoint( "a3te7fgu4kv468-ats.iot.us-west-1.amazonaws.com", 8883) myMQTTClient.configureCredentials( "/home/pi/AWS_certs/Amazon_Root_CA_1.pem", "/home/pi/AWS_certs/1aac3835be-private.pem.key", "/home/pi/AWS_certs/1aac3835be-certificate.pem.crt") myMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec myMQTTClient.connect() while 1: continue
class MqttRos: AllowedActions = ['both', 'publish', 'subscribe'] def __init__(self, config): self.iot_data = config self.thing_name = self.iot_data["thingName"] self.subscribe_topic = self.iot_data["subscribeTopic"] self.publish_topic = self.iot_data["publishTopic"] self.client_id = self.thing_name + '_mqtt' self.init_mqtt_client() self.init_ros_pubs() self.init_ros_subs() self.mqtt_subs() def init_ros_pubs(self): # Place holder publisher into ros space. self.mqttToRosPub = rospy.Publisher('awsiot_to_ros', String, queue_size=1) def init_ros_subs(self): self.rosPubToMqtt = rospy.Subscriber('ros_to_awsiot', String, self.ros_to_mqtt_cb, queue_size=10) def ros_to_mqtt_cb(self, msg): self.ros_to_awsiot_publisher(msg) def ros_to_awsiot_publisher(self, msg): try: self.myAWSIoTMQTTClient.publish(self.publish_topic, msg.data, 1) except Exception as e: rospy.logwarn("MqttRos::ros_to_mqtt_cb got exception") rospy.logwarn(e) def gm_to_awsiot_publisher(self, message): try: self.myAWSIoTMQTTClient.publish('gm_{}'.format(self.publish_topic), str(message), 1) except Exception as e: rospy.logwarn(e) rospy.logwarn("MqttRos::gm_publisher got exception") # MQTT message callback def mqtt_callback(self, client, userdata, message): try: mqttToRosJson = {} mqttToRosJson['payload'] = json.loads(message.payload) mqttToRosJson['topic'] = message.topic self.mqttToRosPub.publish(json.dumps(mqttToRosJson)) except Exception as e: rospy.logwarn("MqttRos::mqtt_callback got exception") def gm_mqtt_callback(self, client, userdata, message): try: payload = json.loads(message.payload) self._game_command_handler(payload) except Exception as e: rospy.logwarn(e) rospy.logwarn("MqttRos::gm_mqtt_callback got exception") def init_mqtt_client(self): # Grab all required info from the parsed data folder_path = self.iot_data['configFilePath'] host = self.iot_data['endpoint'] rootCAPath = os.path.join(folder_path, self.iot_data['rootCAFile']) certificatePath = os.path.join(folder_path, self.iot_data['certFile']) privateKeyPath = os.path.join(folder_path, self.iot_data['privateKeyFile']) useWebsocket = self.iot_data['useWebsocket'] self.mode = self.iot_data['mqttMode'] if self.mode not in MqttRos.AllowedActions: rospy.logwarn("Unknown --mode option %s. Must be one of %s" % (self.mode, str(MqttRos.AllowedActions))) exit(2) if useWebsocket and certificatePath and privateKeyPath: rospy.logwarn( "X.509 cert authentication and WebSocket are mutual exclusive. Please pick one." ) exit(2) if not useWebsocket and (not certificatePath or not privateKeyPath): rospy.logwarn("Missing credentials for authentication.") exit(2) if useWebsocket: port = 443 if not useWebsocket: port = 8883 # Init AWSIoTMQTTClient self.myAWSIoTMQTTClient = None if useWebsocket: self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.client_id, useWebsocket=True) self.myAWSIoTMQTTClient.configureEndpoint(host, port) self.myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.client_id) self.myAWSIoTMQTTClient.configureEndpoint(host, port) self.myAWSIoTMQTTClient.configureCredentials( rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration self.myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) self.myAWSIoTMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing self.myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec def mqtt_subs(self): # Connect and subscribe to AWS IoT self.myAWSIoTMQTTClient.connect() if self.mode == 'both' or self.mode == 'subscribe': self.myAWSIoTMQTTClient.subscribe(self.subscribe_topic, 1, self.mqtt_callback) self.myAWSIoTMQTTClient.subscribe('gm_{}'.format(self.subscribe_topic), 1, self.gm_mqtt_callback) def set_game_command_cb(self, callback): self._game_command_handler = callback
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 if cli.append_thing_name: self.shadow_topic = '{0}/{1}'.format(cli.shadow_topic, self.thing_name) self.audio_topic = '{0}/{1}'.format(cli.audio_topic, self.thing_name) else: self.shadow_topic = cli.shadow_topic self.audio_topic = cli.audio_topic 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.shadow_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 eid = uuid.UUID(cfg[elf_id_key]) # use ELF ID and a random string since we must use unique Client ID per # client. cid = eid.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
# Read and discard the first histogram as per Alphasense guidance data = {} data = opcn3.histogram() # Create local output CSV file now = datetime.datetime.now().strftime("%d%m%Y-%H%M") f = open("/home/pi/outdoor-node/data/node" + str(node_id) + "_" + now + ".csv", 'w+') fnames = ['timestamp', 'node_id', 'temperature', 'humidity', 'pm2_5', 'pm10', 'so2_we', 'so2_ae', 'no2_we', 'no2_ae', 'ox_we', 'ox_ae', 'co_we', 'co_ae', 'no_we', 'no_ae'] writer = csv.DictWriter(f, fieldnames=fnames) writer.writeheader() f.close() # Init AWSIoTMQTTClient myMQTTClient = AWSIoTMQTTClient(client_id) myMQTTClient.configureEndpoint(endpoint, port) myMQTTClient.configureCredentials(root_CA_path, priv_key_path, cert_path) # AWSIoTMQTTClient connection configuration myMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect to AWS IoT myMQTTClient.connect() # Let sensors stabilise for 10 minutes as per Alphasense guidance print "" print "Waiting for sensors to stabilise..." time.sleep(600) print ""
print(host) # 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 AWSIoTMQTTClient myAWSIoTMQTTClient = None 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 to AWS IoT myAWSIoTMQTTClient.connect() time.sleep(2) topic = "raspberry/dht22"
gpio=GPIO) # For certificate based connection myMQTTClient = AWSIoTMQTTClient("recordDrum") # For Websocket connection # myMQTTClient = AWSIoTMQTTClient("myClientID", useWebsocket=True) # Configurations # For TLS mutual authentication myMQTTClient.configureEndpoint( "a3lka4ud7kfmrw-ats.iot.us-east-1.amazonaws.com", 8883) # For Websocket # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443) # For TLS mutual authentication with TLS ALPN extension # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443) myMQTTClient.configureCredentials("/greengrass/certs/root.ca.pem", "/home/pi/.ssh/6acf979319.private.key", "/greengrass/certs/6acf979319.cert.pem") # For Websocket, we only need to configure the root CA # myMQTTClient.configureCredentials("YOUR/ROOT/CA/PATH") myMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 s myMQTTClient.connect() topicValue = "/song/userHit" def blink_drums(pixels, drumList, sessionId="none", voltageDict={}): pixels.clear() tz = pytz.timezone('America/Chicago')
JSONPayload = '{"recordType": "Door","doorStatus":"' + doorStatus + '"}' myAWSIoTMQTTClient.publish("LNH_STATUS/" + thingName, JSONPayload, 1) if (doorStatus == "CLOSE"): stopThread = True else: stopThread = False x = threading.Thread(target=thread_function, args=(int(time.time()), )) x.start() myAWSIoTMQTTClient = AWSIoTMQTTClient(thingName, cleanSession=False) myAWSIoTMQTTClient.configureEndpoint( "a1f18ishzwlosz-ats.iot.ap-southeast-2.amazonaws.com", 8883) myAWSIoTMQTTClient.configureCredentials("./AmazonRootCA1.pem", "./90b9981671-private.pem.key", "./90b9981671-certificate.pem.crt") myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) lastWillPayload = '{"errorType":"Device","deviceID":"' + thingName + '"}' myAWSIoTMQTTClient.configureLastWill("LNH_ALARM", lastWillPayload, 0) myAWSIoTMQTTClient.connect() previous_status = 2 while True: print(GPIO.input(pinNumber)) if (previous_status != GPIO.input(pinNumber)): if (GPIO.input(pinNumber) == 1): print("I am sending message door is open") updateDoorStatus("OPEN") else:
def configure(topic="sdk/test/Python"): """AWS configuration """ AllowedActions = ['both', 'publish', 'subscribe'] # Read in command-line parameters parser = argparse.ArgumentParser() parser.add_argument("-e", "--endpoint", action="store", required=True, dest="host", help="Your AWS IoT custom endpoint") parser.add_argument("-r", "--rootCA", action="store", required=True, dest="rootCAPath", help="Root CA file path") parser.add_argument("-c", "--cert", action="store", dest="certificatePath", help="Certificate file path") parser.add_argument("-k", "--key", action="store", dest="privateKeyPath", help="Private key file path") parser.add_argument("-p", "--port", action="store", dest="port", type=int, help="Port number override") parser.add_argument("-w", "--websocket", action="store_true", dest="useWebsocket", default=False, help="Use MQTT over WebSocket") parser.add_argument("-id", "--clientId", action="store", dest="clientId", default="basicPubSub", help="Targeted client id") parser.add_argument("-t", "--topic", action="store", dest="topic", default="sdk/test/Python", help="Targeted topic") parser.add_argument("-m", "--mode", action="store", dest="mode", default="both", help="Operation modes: %s" % str(AllowedActions)) parser.add_argument("-M", "--message", action="store", dest="message", default="Hello World!", help="Message to publish") args = parser.parse_args() host = args.host rootCAPath = args.rootCAPath certificatePath = args.certificatePath privateKeyPath = args.privateKeyPath port = args.port useWebsocket = args.useWebsocket clientId = args.clientId # topic = args.topic topic = topic if args.mode not in AllowedActions: parser.error("Unknown --mode option %s. Must be one of %s" % (args.mode, str(AllowedActions))) exit(2) if args.useWebsocket and args.certificatePath and args.privateKeyPath: parser.error( "X.509 cert authentication and WebSocket are mutual exclusive. Please pick one." ) exit(2) if not args.useWebsocket and (not args.certificatePath or not args.privateKeyPath): parser.error("Missing credentials for authentication.") exit(2) # Port defaults if args.useWebsocket and not args.port: # When no port override for WebSocket, default to 443 port = 443 if not args.useWebsocket and not args.port: # When no port override for non-WebSocket, default to 8883 port = 8883 # 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 AWSIoTMQTTClient myAWSIoTMQTTClient = None if useWebsocket: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True) 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, Argument.customCallback) time.sleep(2) return args, myAWSIoTMQTTClient, topic
# set up Pi pins GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # AWS host = # retrieve endpoint from IOTCORE/Settings #"a15llkyp1ib6yl-ats.iot.us-east-1.amazonaws.com" certPath = "/home/pi/certificates/" # key, certificate, aws root cert clientId = "osandvold" topic = "online-post-it" # iot topic # Init AWSIoTMQTTClient myAWSIoTMQTTClient = None myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureEndpoint(host, 8883) myAWSIoTMQTTClient.configureCredentials("{}aws-root-cert.pem".format(certPath), "{}private-key.pem.key".format(certPath), "{}iot-cert.pem.crt".format(certPath)) # 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 myAWSIoTMQTTClient.connect() while True: message = {} input_state = GPIO.input(18) if input_state == GPIO.HIGH: message['message'] = "Dash Button Pressed in Room 201 C" messageJson = json.dumps(message)
ENDPOINT = "akbmorjah98q5.iot.ap-southeast-1.amazonaws.com" # Change to your topics here UPDATE_TOPIC = "$aws/things/" + THING_ID + "/shadow/update" DELTA_TOPIC = "$aws/things/" + THING_ID + "/shadow/update/delta" ROOT_CA = CERTIFICATE_PATH + "/rootCA.pem" PRIVATE_KEY = CERTIFICATE_PATH + "/private.key.pem" CERTIFICATE_CRT = CERTIFICATE_PATH + "/certificate.crt.pem" # Configuration for AWS IoT myMQTTClient = AWSIoTMQTTClient(CLIENT_ID) myMQTTClient.configureEndpoint(ENDPOINT, 8883) myMQTTClient.configureCredentials(ROOT_CA, PRIVATE_KEY, CERTIFICATE_CRT) myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec myMQTTClient.enableMetricsCollection() # Connect to MQTT broker connected = myMQTTClient.connect() print("Connected:-", connected) def publish_sensor_data(interval): try:
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 Urbanova Cloud IoT MQTT Client using TLSv1.2 Mutual Authentication ucIoTDeviceClient = None # initialize var ucIoTDeviceClient = AWSIoTMQTTClient( deviceId ) # The client class that connects to and accesses AWS IoT over MQTT v3.1/3.1.1. ucIoTDeviceClient.configureEndpoint( ucIoTCustomEndpoint, 8883) # MQTT Broker host address and default port (TLS) ucIoTDeviceClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # certs and key # Configure Urbanova Cloud IoT Device Client Connection Settings (reference: https://s3.amazonaws.com/aws-iot-device-sdk-python-docs/sphinx/html/index.html) ucIoTDeviceClient.configureAutoReconnectBackoffTime(1, 32, 20) ucIoTDeviceClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing ucIoTDeviceClient.configureDrainingFrequency(2) # Draining: 2 Hz ucIoTDeviceClient.configureConnectDisconnectTimeout(10) # 10 sec ucIoTDeviceClient.configureMQTTOperationTimeout(5) # 5 sec # Connect to Urbanova Cloud IoT ucIoTDeviceClient.connect() time.sleep(2) # Publish `Hello Sensor ${sensorID}`to Urbanova Cloud once per second loopCount = 0
GPIO.output(int(i["pin"]), GPIO.LOW) print("Activating pin: " + str(i["pin"])) # configure loggger 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) # AWS IoT client initialization ... thing = AWSIoTMQTTClient(config['client_id']) thing.configureEndpoint(config['endpoint'], config['port']) thing.configureCredentials(config['root_ca_path'], config['private_key_path'], config['cert_path']) thing.configureOfflinePublishQueueing(-1) thing.configureDrainingFrequency(2) thing.configureConnectDisconnectTimeout(10) thing.configureMQTTOperationTimeout(5) try: thing.connect() thing.subscribe(config['topic'], 1, doors_callback) while True: """ I'm loop """ except KeyboardInterrupt: print("Cleaning up GPIO")
stop() else: go() try: #while True: GPIO.setwarnings(False) setup() #AwsReyna connection myMQTTClient = AWSIoTMQTTClient("ReynaPI") myMQTTClient.configureEndpoint( "a3te7fgu4kv468-ats.iot.us-west-1.amazonaws.com", 8883) myMQTTClient.configureCredentials( "/home/pi/Certificates/rootCA.pem", "/home/pi/Certificates/d626c8c838-private.pem.key", "/home/pi/Certificates/d626c8c838-certificate.pem.crt") myMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myMQTTClient.configureOfflinePublishQueueing(-1) myMQTTClient.configureDrainingFrequency(2) myMQTTClient.configureConnectDisconnectTimeout(10) myMQTTClient.configureMQTTOperationTimeout(5) myMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) #connect and subscribe myMQTTClient.connect() humidity = 0 while True: myMQTTClient.subscribe("ryan_pi/data", 1, callback)
def initialize(device_name, config_file, root_ca, certificate, private_key, group_ca_path): # read the config file cfg = GroupConfigFile(config_file) ggd_name = cfg['devices'][device_name]['thing_name'] iot_endpoint = cfg['misc']['iot_endpoint'] # prep for discovery dip = DiscoveryInfoProvider() dip.configureEndpoint(iot_endpoint) dip.configureCredentials( caPath=pa.root_ca, certPath=pa.certificate, keyPath=pa.private_key ) dip.configureTimeout(10) # 10 sec logging.info("Discovery using CA:{0} cert:{1} prv_key:{2}".format( pa.root_ca, pa.certificate, pa.private_key )) discovered, discovery_info = utils.ggc_discovery( thing_name=ggd_name, discovery_info_provider=dip, max_groups=3 ) local, remote = _find_cores(cfg, discovery_info, iot_endpoint) # Save each group's CAs to use as a CA file later local_core_ca_file = utils.save_group_ca( local['ca'][0], group_ca_path, local['core'].groupId ) for r in remote: remote[r]['ca_file'] = utils.save_group_ca( remote[r]['ca'][0], group_ca_path, remote[r]['core'].groupId ) # create and connect MQTT client pointed toward the Master Greengrass Core mqttc_m = AWSIoTMQTTClient(ggd_name) log.info("[initialize] local gca_file:{0} cert:{1}".format( local_core_ca_file, certificate)) mqttc_m.configureCredentials( local_core_ca_file, private_key, certificate ) mqttc_m.configureOfflinePublishQueueing(10, DROP_OLDEST) log.info("[initialize] Starting connection to Master Core") if utils.mqtt_connect(mqtt_client=mqttc_m, core_info=local['core']): log.info("[initialize] Connected to Master Core") else: log.error("[initialize] could not connect to Master Core") # create and connect MQTT clients pointed toward the remote Greengrass Cores mqttc_list = list() for r in remote: remote_mqttc = AWSIoTMQTTClient(ggd_name) log.info("[initialize] local gca_file:{0} cert:{1}".format( r, certificate)) remote_mqttc.configureCredentials( remote[r]['ca_file'], private_key, certificate) remote_mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST) log.info("[initialize] Starting connection to Remote Core") if utils.mqtt_connect(mqtt_client=remote_mqttc, core_info=remote[r]['core']): log.info("[initialize] Connected to Remote Core:{0}".format( remote[r]['core'].coreThingArn )) mqttc_list.append(remote_mqttc) else: log.error( "[initialize] could not connect to Remote Core:{0}".format( remote[r]['core'].coreThingArn )) return mqttc_m, mqttc_list
class subscriber_actor: iot_mqtt_client = None QOS_LEVEL = 1 def __init__(self): self.iot_mqtt_client = AWSIoTMQTTClient(pfc_conf.PFC_AWS_IOT_CLIENT_ID) self.iot_mqtt_client.configureEndpoint(pfc_mqtt_topic.AWS_ENDPOINT,8883) self.iot_mqtt_client.configureCredentials(pfc_conf.CA_PATH, pfc_conf.PRIVATE_KEY_PATH, pfc_conf.CERTIFICATE_PATH) self.iot_mqtt_client.configureAutoReconnectBackoffTime(1, 32, 20) self.iot_mqtt_client.configureOfflinePublishQueueing(-1) self.iot_mqtt_client.configureDrainingFrequency(2) self.iot_mqtt_client.configureConnectDisconnectTimeout(10) self.iot_mqtt_client.configureMQTTOperationTimeout(5) def msg_callback(self, client, userdata, message): mes_pld = message.payload mes_tpc = message.topic f = open(pfc_conf.LOG_DIR_PATH + '/aws_subscribe.log','a+') f.write(mes_tpc + ' => ' + mes_pld + str(datetime.now())) f.write('\n') f.close() try : messageJson = json.loads(message.payload) except : print("Throw Message JSON Parse Error.") return False om_type = messageJson['TYPE'] om_target = messageJson['TARGET']if 'TARGET' in messageJson else None om_order = messageJson['ORDER'] if 'ORDER' in messageJson else None self.order_callback(om_type, om_target,om_order) def order_callback(self, om_type, om_target, om_order): global Timer kill_proc = lambda p: p.kill() if om_type == 'SENSOR': if om_target in command_mapper.SENSOR and om_order in command_mapper.SENSOR[om_target]: command_pfc_sensor = command_mapper.SENSOR_DIR_PATH +command_mapper.SENSOR[om_target][om_order] print(command_pfc_sensor) # Execute get sensor data python process through subprocess # It has a timeout setting to prevent permanent blocking sensor_proc = subprocess.Popen(shlex.split("python " + command_pfc_sensor), stdout=subprocess.PIPE, stderr=subprocess.PIPE) timer = Timer(30, kill_proc,[sensor_proc]) try : timer.start() stdout,stderr = sensor_proc.communicate() finally: timer.cancel() # Publish sensor data to AWS IOT DEVICE GATEWAY sensor_data = {"DATA" :stdout , "PFC_SERIAL" :str(pfc_conf.PFC_AWS_IOT_SERIAL), "DEVICE_DT" : str(datetime.now())} pub_proc = subprocess.Popen(shlex.split("python publisher_sensor_data.py -t '" + pfc_mqtt_topic.PUBLISH_SENSOR+ "' -m '" +json.dumps(sensor_data) + "'")) timer = Timer(30,kill_proc, [pub_proc]) try : timer.start() stdout,stderr = pub_proc.communicate() finally : timer.cancel() else : print("'TARGET' or 'ORDER' is not exists on the command_mapper") elif om_type == 'ACTUATOR': if om_target in command_mapper.ACTUATOR and om_order in command_mapper.ACTUATOR[om_target]: command_pfc_actuator = command_mapper.ACTUATOR_DIR_PATH + command_mapper.ACTUATOR[om_target][om_order] print(command_pfc_actuator) # Execute get sensor data python process through subprocess # It has a timeout setting to prevent permanent blocking actuator_proc = subprocess.Popen(shlex.split("python " + command_pfc_actuator), stdout=subprocess.PIPE, stderr=subprocess.PIPE) timer = Timer(30, kill_proc,[actuator_proc]) try : timer.start() stdout, stderr = actuator_proc.communicate() finally : timer.cancel() actuator_data = {'DATA':stdout, 'PFC_SERIAL': str(pfc_conf.PFC_AWS_IOT_SERIAL), 'DEVICE_DT' : str(datetime.now())} pub_proc = subprocess.Popen(shlex.split("python publisher_actuator_data.py -t '" + pfc_mqtt_topic.PUBLISH_ACTUATOR + "' -m '" +json.dumps(actuator_data) + "'")) timer = Timer(30,kill_proc, [pub_proc]) try : timer.start() stdout,stderr = pub_proc.communicate() finally : timer.cancel() else : print("'TARGET' or 'ORDER' is not exists on the command_mapper") elif om_type == 'LOCAL_IP' : pub_proc = subprocess.Popen(shlex.split("python " + command_mapper.LOCAL_IP['LOCAL_IP']['LOCAL_IP'])) timer = Timer(30,kill_proc, [pub_proc]) try : timer.start() stdout,stderr = pub_proc.communicate() finally : timer.cancel() elif om_type == 'HEARTBEAT' : pub_proc = subprocess.Popen(shlex.split("python " + command_mapper.LOCAL_IP['HEARTBEAT']['BEATING'])) timer = Timer(30, kill_proc, [pub_proc]) try : timer.start() stdout, stderr = pub_proc.communicate() finally : timer.cancel() elif om_type == 'DATA_LAKE' : command_pfc_data_lake = command_mapper.AWS_IOT_DIR_PATH +command_mapper.DATA_LAKE['S3_UPLOAD']['UPLOAD'] pub_proc = subprocess.Popen(shlex.split("python " + command_pfc_data_lake)) timer = Timer(600, kill_proc, [pub_proc]) try : timer.start() stdout, stderr = pub_proc.communicate() finally : timer.cancel() datalake_data = {'DATA' : stdout, 'PFC_SERIAL' : str(pfc_conf.PFC_AWS_IOT_SERIAL), 'DEVICE_DT' : str(datetime.now())} pub_proc = subprocess.Popen(shlex.split("python publisher_datalake_data.py -t '" + pfc_mqtt_topic.PUBLISH_DATALAKE + "' -m '" + json.dumps(datalake_data) + "'")) timer = Timer(30, kill_proc, [pub_proc]) try : timer.start() stdout,stderr = pub_proc.communicate() finally : timer.cancel() def subscribe_mqtt_broker(self): self.iot_mqtt_client.connect() self.iot_mqtt_client.subscribe(pfc_mqtt_topic.SUBSCRIBE_DEV,self.QOS_LEVEL,self.msg_callback) print("Subscribing topic : " + str(pfc_mqtt_topic.SUBSCRIBE_DEV)) while True: time.sleep(1) def logging(self): None
import sys import ssl from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient import json import time import random import datetime #Setup our MQTT client and security certificates #Make sure your certificate names match what you downloaded from AWS IoT mqttc = AWSIoTMQTTClient("1234") #Make sure you use the correct region! mqttc.configureEndpoint("data.iot.us-west-2.amazonaws.com", 8883) mqttc.configureCredentials("./rootCA.pem", "./ratchet/ratchet.private.key", "./ratchet/ratchet.cert.pem") #Function to encode a payload into JSON def json_encode(string): return json.dumps(string) mqttc.json_encode = json_encode #Connecting to the message broker mqttc.connect() print("Connected") #For loop to generate our data for x in range(0, 100):
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient import RPi.GPIO as GPIO from config import move_pins, aws_mqtt import time # def __init__(): # AWS MQTT myMQTTClient = AWSIoTMQTTClient("PiCar1") myMQTTClient.configureEndpoint(aws_mqtt.MQTT_ENDPOINT_URL, aws_mqtt.MQTT_ENDPOINT_PORT) myMQTTClient.configureCredentials(aws_mqtt.AWS_ROOT_CERT, aws_mqtt.PICAR_CERT_PRIVATE_KEY, aws_mqtt.PICAR_CERT) myMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(move_pins.PIN_MOVE, GPIO.OUT) GPIO.setup(move_pins.PIN_FWD, GPIO.OUT) GPIO.setup(move_pins.PIN_TURN, GPIO.OUT) GPIO.setup(move_pins.PIN_LEFT, GPIO.OUT) GPIO.output(move_pins.PIN_MOVE, 1) GPIO.output(move_pins.PIN_FWD, 1) GPIO.output(move_pins.PIN_TURN, 1) GPIO.output(move_pins.PIN_LEFT, 1)
class RemoteControllIntentHandler(AbstractRequestHandler): """Handler for RemoteControll Intent.""" def __init__(self): # Init AWSIoTMQTTClient For Websocket connection self.myAWSIoTMQTTClient = None self.myAWSIoTMQTTClient = AWSIoTMQTTClient("", useWebsocket=True) self.myAWSIoTMQTTClient.configureEndpoint("a1xfsi89ntz6zn-ats.iot.ap-northeast-1.amazonaws.com", 443) self.myAWSIoTMQTTClient.configureCredentials("rootCA.pem") # AWSIoTMQTTClient connection configuration self.myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing self.myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Init device/action list self.device_list = {"001":"TV","002":"aircon","003":"light"} self.function_list = {"001":"power","002":"volume_up","003":"volume_down"} # topic self.topic = "$aws/things/RaspberryPi/shadow/update" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return ask_utils.is_intent_name("RemoteControllIntent")(handler_input) def handle(self, handler_input): # slots slots = handler_input.request_envelope.request.intent.slots # device_id device_id = "001" # speak_output = "ーーーーー" # create a payload if slots["btn"].resolutions.resolutions_per_authority[0].status.code == StatusCode.ER_SUCCESS_MATCH: btn_id = slots["btn"].resolutions.resolutions_per_authority[0].values[0].value.id if btn_id == "001": action_id = "001" payload = {"state":{"desired":{"{}".format(self.device_list[device_id]):{"{}".format(self.function_list[action_id]):1}}}} elif btn_id == "002": if slots["action"].resolutions.resolutions_per_authority[0].status.code == StatusCode.ER_SUCCESS_MATCH: action_id = slots["action"].resolutions.resolutions_per_authority[0].values[0].value.id num = slots["num"].value if num != None: payload = {"state":{"desired":{"{}".format(self.device_list[device_id]):{"{}".format(self.function_list[action_id]):int(num)}}}} else: payload = {"state":{"desired":{"{}".format(self.device_list[device_id]):{"{}".format(self.function_list[action_id]):1}}}} logger.debug(json.dumps(payload)) # connct to shadow self.myAWSIoTMQTTClient.connect() logger.debug('connect to shadow') self.myAWSIoTMQTTClient.publish(self.topic, json.dumps(payload), 0) logger.debug('update desired') self.myAWSIoTMQTTClient.disconnect() logger.debug('disconnect to shadow') speak_output = "ーーーーー" else: speak_output = "その操作はできません。テレビをつけたい場合は、テレビをつけて、と言ってください。" return ( handler_input.response_builder .speak(speak_output) .ask(speak_output) .response )
# AWS IoT generated for this device, that you # have already saved onto this device. PRIVATE_KEY = "rsp-home.private.key" # The relative path to your certificate file that # AWS IoT generated for this device, that you # have already saved onto this device. CERT_FILE = "rsp-home.cert.pem" # A programmatic shadow handler name prefix. SHADOW_HANDLER = "rsp-home" # AWS IoT certificate based connection myMQTTClient = AWSIoTMQTTClient("123afhlss456") myMQTTClient.configureEndpoint(HOST_NAME, 8883) myMQTTClient.configureCredentials(ROOT_CA, PRIVATE_KEY, CERT_FILE) myMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec #connect and publish myMQTTClient.connect() myMQTTClient.publish("rsp-home/info", "connected", 0) #loop and publish sensor reading while 1: t = round(sense.get_temperature(), 2) p = sense.get_pressure() h = sense.get_humidity()
client_id = "your-thing-name-here" topic = "your-topic-name-here" cert_path = "/home/pi/aws_iot/certs/" root_ca = cert_path + "AmazonRootCA1.pem" certificate = cert_path + "certificate.pem.crt" private_key = cert_path + "private.pem.key" # connect to B-L475E bl475e = HTSensor(bl475e_mac_address) bl475e.connect() # construct the AWS Iot MQTT client #client = None client = AWSIoTMQTTClient(client_id) client.configureEndpoint(host, 8883) client.configureCredentials(root_ca, private_key, certificate) client.configureAutoReconnectBackoffTime(1, 32, 20) client.configureOfflinePublishQueueing(-1) client.configureDrainingFrequency(2) client.configureConnectDisconnectTimeout(10) client.configureMQTTOperationTimeout(5) # connect to AWS Iot Core attempts = 0 connected = 0 while attempts <= 3 and not connected: attempts += 1 try: client.connect() print("Connected to AWS IoT Core.") connected = 1
ser.write("atz\r\n") print(ser.readline()) rpm = 0 speed = 0 temp = 0 initializing = True time.sleep(1) # Import SDK packages from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient myMQTTClient = AWSIoTMQTTClient("myClientID-kombi-rasp-23121231") myMQTTClient.configureEndpoint( "a2p4fyajwx9lux-ats.iot.us-east-1.amazonaws.com", 8883) myMQTTClient.configureCredentials( "/Users/vsenger/Documents/root-CA.crt", "/Users/vsenger/Downloads/a48c4c65d8-private.pem.key", "/Users/vsenger/Downloads/a48c4c65d8-certificate.pem.crt") myMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec myMQTTClient.connect() while initializing: ser.write("010c\r\n") r = ser.readline() if (r.startswith("010c")): initializing = False else: time.sleep(2)
sensor = 16 GPIO.setmode(GPIO.BOARD) GPIO.setup(sensor, GPIO.IN) clientId = "myClientID" thingEndpoint = '' certificatePath = '' privateKeyPath = '' rooCACertPath = '' print "before setup1 ..." myMQTTClient = AWSIoTMQTTClient(clientId) myMQTTClient.configureEndpoint(thingEndpoint, 8883) myMQTTClient.configureCredentials(rooCACertPath, privateKeyPath, certificatePath) myMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myMQTTClient.configureOfflinePublishQueueing( -1 ) # Infinite offline Publish q myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec print "before connection..." myMQTTClient.connect() print "connected" myTopic = "sendButtonClick" message = {}
topic = message.topic logger.info("topic: {}".format(topic)) logger.info("payload: {}".format(payload)) speech_with_polly(payload["speech_text"]) logger.info("done.") except: logging.exception("Caught Exception in on_alexa_control_message()") if __name__ == '__main__': myMQTTClient = AWSIoTMQTTClient(CLIENT_ID) myMQTTClient.configureEndpoint(AWS_IOT_ENDPOINT, 8883) myMQTTClient.configureCredentials(ROOT_CA_CERT, DEV_CERT_PRIV, DEV_CERT) myMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myMQTTClient.configureOfflinePublishQueueing(-1) myMQTTClient.configureDrainingFrequency(2) myMQTTClient.configureConnectDisconnectTimeout(10) myMQTTClient.configureMQTTOperationTimeout(5) myMQTTClient.onOnline = on_online myMQTTClient.onOffline = on_offline myMQTTClient.connect() time.sleep(2) logger.info("connexted to {} as {}".format(AWS_IOT_ENDPOINT, CLIENT_ID))
'ClientToken: {} on {}'.format(self.client_id, datetime.datetime.now().isoformat()) } threading.Thread(target=self.jobs_client.sendJobsStartNext, kwargs={ 'statusDetails': statusDetails }).start() def is_done(self): return self.done mqtt_client = None mqtt_client = AWSIoTMQTTClient(clientId) mqtt_client.configureEndpoint(host, port) mqtt_client.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration mqtt_client.configureAutoReconnectBackoffTime(1, 32, 20) mqtt_client.configureConnectDisconnectTimeout(10) # 10 sec mqtt_client.configureMQTTOperationTimeout(10) # 5 sec jobsClient = AWSIoTMQTTThingJobsClient(clientId, thingName, QoS=1, awsIoTMQTTClient=mqtt_client) print('Connecting to MQTT server and setting up callbacks...') jobsClient.connect() jobsMsgProc = JobsMessageProcessor(jobsClient, clientId) print('Starting to process jobs...')
class MQTTClient(object): """ classdocs """ __PORT = 8883 __QUEUE_SIZE = -1 # recommended: infinite __QUEUE_DROP_BEHAVIOUR = MQTTLib.DROP_OLDEST # not required for infinite queue __QUEUE_DRAINING_FREQUENCY = 1 # recommended: 2 (Hz) __RECONN_BASE = 1 # recommended: 1 (sec) __RECONN_MAX = 32 # recommended: 32 (sec) __RECONN_STABLE = 20 # recommended: 20 (sec) __DISCONNECT_TIMEOUT = 30 # recommended: 10 (sec) __OPERATION_TIMEOUT = 30 # recommended: 5 (sec) __PUB_QOS = 1 __SUB_QOS = 1 # ---------------------------------------------------------------------------------------------------------------- def __init__(self, *subscribers): """ Constructor """ self.__client = None self.__subscribers = subscribers # ---------------------------------------------------------------------------------------------------------------- def connect(self, auth): # client... self.__client = AWSIoTMQTTClient(auth.client_id) # configuration... self.__client.configureEndpoint(auth.endpoint, self.__PORT) self.__client.configureCredentials(auth.root_ca_file_path, auth.private_key_path, auth.certificate_path) self.__client.configureAutoReconnectBackoffTime(self.__RECONN_BASE, self.__RECONN_MAX, self.__RECONN_STABLE) self.__client.configureOfflinePublishQueueing(self.__QUEUE_SIZE) self.__client.configureDrainingFrequency(self.__QUEUE_DRAINING_FREQUENCY) self.__client.configureConnectDisconnectTimeout(self.__DISCONNECT_TIMEOUT) self.__client.configureMQTTOperationTimeout(self.__OPERATION_TIMEOUT) # subscriptions... for subscriber in self.__subscribers: self.__client.subscribe(subscriber.topic, self.__SUB_QOS, subscriber.handler) # connect... self.__client.connect() def disconnect(self): self.__client.disconnect() # ---------------------------------------------------------------------------------------------------------------- def publish(self, publication): payload = JSONify.dumps(publication.payload) self.__client.publish(publication.topic, payload, self.__PUB_QOS) # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): subscribers = '[' + ', '.join(str(subscriber) for subscriber in self.__subscribers) + ']' return "MQTTClient:{subscribers:%s}" % subscribers
except BaseException as e: print("Error in discovery!") print("Type: %s" % str(type(e))) print("Error message: %s" % e.message) retryCount -= 1 print("\n%d/%d retries left\n" % (retryCount, MAX_DISCOVERY_RETRIES)) print("Backing off...\n") backOffCore.backOff() if not discovered: print("Discovery failed after %d retries. Exiting...\n" % (MAX_DISCOVERY_RETRIES)) sys.exit(-1) # Iterate through all connection options for the core and use the first successful one myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureCredentials(groupCA, privateKeyPath, certificatePath) myAWSIoTMQTTClient.onMessage = customOnMessage connected = False for connectivityInfo in coreInfo.connectivityInfoList: currentHost = connectivityInfo.host currentPort = connectivityInfo.port print("Trying to connect to core at %s:%d" % (currentHost, currentPort)) myAWSIoTMQTTClient.configureEndpoint(currentHost, currentPort) try: myAWSIoTMQTTClient.connect() connected = True break except BaseException as e: print("Error in connect!") print("Type: %s" % str(type(e)))
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
def customCallback(client, userdata, message): print("Received a new message: ") print(message.payload) print("from topic: ") print(message.topic) print("--------------\n\n") host = "a254690l1ektgk-ats.iot.us-east-1.amazonaws.com" rootCAPath = "rootca.pem" certificatePath = "certificate.pem.crt" privateKeyPath = "private.pem.key" my_rpi = AWSIoTMQTTClient("PubSub-p1749126") my_rpi.configureEndpoint(host, 8883) my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath) my_rpi.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing my_rpi.configureDrainingFrequency(2) # Draining: 2 Hz my_rpi.configureConnectDisconnectTimeout(10) # 10 sec my_rpi.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT my_rpi.connect() my_rpi.subscribe("sensors/home", 1, customCallback) sleep(2) # Publish to the same topic in a loop forever loopCount = 0 while True: light = round(1024 - (adc.value * 1024))
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()) myMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec #connect and publish myMQTTClient.connect() con = psycopg2.connect("host='litterbugdb.c1ekrfqx70oj.eu-west-1.rds.amazonaws.com' dbname='littering' user='******' password='******'") cur = con.cursor() cur.execute("SELECT id FROM devices where mac_addr='%s'",[mac]) row = cur.fetchone() device_id=row[0]
# -*- 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)
def core_connect(device_name, config_file, root_ca, certificate, private_key, group_ca_path): # read the config file cfg = GroupConfigFile(config_file) # determine heartbeat device's thing name and orient MQTT client to GG Core heartbeat_name = cfg['devices'][device_name]['thing_name'] iot_endpoint = cfg['misc']['iot_endpoint'] local_core = None # Discover Greengrass Core dip = DiscoveryInfoProvider() dip.configureEndpoint(iot_endpoint) dip.configureCredentials( caPath=root_ca, certPath=certificate, keyPath=private_key ) dip.configureTimeout(10) # 10 sec log.info("[hb] Discovery using CA: {0} cert: {1} prv_key: {2}".format( root_ca, certificate, private_key )) # Now discover the groups in which this device is a member. # The heartbeat should only be in one group discovered, discovery_info = utils.ggc_discovery( heartbeat_name, dip, retry_count=10, max_groups=1 ) ca_list = discovery_info.getAllCas() group_id, ca = ca_list[0] group_ca_file = utils.save_group_ca(ca, group_ca_path, group_id) if discovered is False: log.error( "[hb] Discovery failed for: {0} when connecting to " "service endpoint: {1}".format( heartbeat_name, iot_endpoint )) return log.info("[hb] Discovery success") mqttc = AWSIoTMQTTClient(heartbeat_name) # find this device Group's core for group in discovery_info.getAllGroups(): utils.dump_core_info_list(group.coreConnectivityInfoList) local_core = group.getCoreConnectivityInfo(cfg['core']['thing_arn']) if local_core: log.info('[hb] Found the local core and Group CA.') break if not local_core: raise EnvironmentError("[hb] Couldn't find the local Core") # local Greengrass Core discovered, now connect to Core from this Device log.info("[hb] gca_file:{0} cert:{1}".format(group_ca_file, certificate)) mqttc.configureCredentials(group_ca_file, private_key, certificate) mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST) if not utils.mqtt_connect(mqtt_client=mqttc, core_info=local_core): raise EnvironmentError("[hb] Connection to GG Core MQTT failed.") return mqttc, heartbeat_name
# Ratchet_Button Test Client import sys import ssl from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient import json import time import random mqttc = AWSIoTMQTTClient("smartparking_EdgeGatewayDevice") mqttc.configureEndpoint("greengrass-ats.iot.us-west-2.amazonaws.com", 8883) mqttc.configureCredentials("./root.ca.pem", "./private.key", "./cert.pem") #Function to encode a payload into JSON def json_encode(string): return json.dumps(string) mqttc.json_encode = json_encode counter = 0 while True: message = { "timestamp": time.time(), "metrics": [{ "name": "sp-area1-sensor1/scan", "value": 0
except BaseException as e: print("Error in discovery!") print("Type: %s" % str(type(e))) print("Error message: %s" % e.message) retryCount -= 1 print("\n%d/%d retries left\n" % (retryCount, MAX_DISCOVERY_RETRIES)) print("Backing off...\n") backOffCore.backOff() if not discovered: print("Discovery failed after %d retries. Exiting...\n" % (MAX_DISCOVERY_RETRIES)) sys.exit(-1) # Iterate through all connection options for the core and use the first successful one myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureCredentials(groupCA, privateKeyPath, certificatePath) myAWSIoTMQTTClient.onMessage = customOnMessage connected = False for connectivityInfo in coreInfo.connectivityInfoList: currentHost = connectivityInfo.host currentPort = connectivityInfo.port print("Trying to connect to core at %s:%d" % (currentHost, currentPort)) myAWSIoTMQTTClient.configureEndpoint(currentHost, currentPort) try: myAWSIoTMQTTClient.connect() connected = True break except BaseException as e: print("Error in connect!") print("Type: %s" % str(type(e)))
class MQTTClient: myAWSIoTMQTTClient = None def __init__(self, clientId, topic, host, rootCA, crtPath, privateKey, port): self.clientId = clientId self.topic = topic self.host = host self.rootCA = rootCA self.crtPath = crtPath self.privateKey = privateKey self.port = port # Custom MQTT message callback def customCallback(client, userdata, message): print("Received a new message: ") print(message.payload) print("from topic: ") print(message.topic) print("--------------\n\n") def ConfigureLogging(): 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) def InitClient(self): self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.clientId) self.myAWSIoTMQTTClient.configureEndpoint(self.host, self.port) self.myAWSIoTMQTTClient.configureCredentials(self.rootCA, self.privateKey, self.crtPath) # AWSIoTMQTTClient connection configuration self.myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) self.myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing self.myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT self.myAWSIoTMQTTClient.connect() time.sleep(2) def PublishJsonPayload(self, payload): self.myAWSIoTMQTTClient.publish(self.topic, payload, 1) print('Published topic %s: %s\n' % (self.topic, payload)) def StartPublish(self): # Publish to the same topic in a loop forever loopCount = 0 while True: message = {} message['device'] = "window_lars" message['timestamp'] = str(int(round(time.time() * 1000))) message['aq'] = "2" messageJson = json.dumps(message) self.myAWSIoTMQTTClient.publish(self.topic, messageJson, 1) print('Published topic %s: %s\n' % (self.topic, messageJson)) loopCount += 1 time.sleep(1)
class AwsLib: clientId = None hostName = None rootCert = None certKey = None privKey = None topic = None message = None port = None myAWSIoTMQTTClient = None def __init__(self, clientId, hostName, port, rootCert, certKey, privKey): self.clientId = clientId self.hostName = hostName self.rootCert = rootCert self.certKey = certKey self.privKey = privKey self.port = port self.isConnected = False try: # Init AWSIoTMQTTClient self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.clientId) self.myAWSIoTMQTTClient.configureEndpoint(self.hostName, self.port) self.myAWSIoTMQTTClient.configureCredentials( self.rootCert, self.privKey, self.certKey) # AWSIoTMQTTClient connection configuration self.myAWSIoTMQTTClient.configureAutoReconnectBackoffTime( 1, 32, 20) self.myAWSIoTMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing self.myAWSIoTMQTTClient.configureDrainingFrequency( 2) # Draining: 2 Hz self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout( 10) # 10 sec self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec except Exception as e: print(e) def getInfoStatus(self): return self.isConnected def connect(self): if (self.isConnected == False): try: self.myAWSIoTMQTTClient.connect() self.isConnected = True except Exception as e: self.isConnected = False def disconnect(self): if self.isConnected: self.isConnected = False try: self.myAWSIoTMQTTClient.disconnect() except Exception as e: print(e) def subscribe(self, topic, callback): if self.isConnected: try: # self.myAWSIoTMQTTClient.subscribe(topic, 1, self.receiveCallback) self.myAWSIoTMQTTClient.subscribe(topic, 1, callback) except Exception as e: self.isConnected = False print(e) def publish(self, topic, message): if self.isConnected: try: self.myAWSIoTMQTTClient.publish(topic, message, 1) except Exception as e: self.isConnected = False print(e)
def initialize(device_name, config_file, root_ca, certificate, private_key, group_ca_path): global ggd_name cfg = GroupConfigFile(config_file) local = dict() remote = dict() # determine heartbeat device's thing name and endpoint for MQTT clients ggd_name = cfg['devices'][device_name]['thing_name'] iot_endpoint = cfg['misc']['iot_endpoint'] # Discover Greengrass Core dip = DiscoveryInfoProvider() dip.configureEndpoint(iot_endpoint) dip.configureCredentials( caPath=root_ca, certPath=certificate, keyPath=private_key ) dip.configureTimeout(10) # 10 sec log.info("Discovery using CA: {0} certificate: {1} prv_key: {2}".format( root_ca, certificate, private_key )) # Now discover the groups in which this device is a member. # The arm should only be in two groups. The local and master groups. discovered, discovery_info = utils.ggc_discovery( ggd_name, dip, retry_count=10, max_groups=2 ) # Each group returned has a groupId which can compare to the configured # groupId in the config file. If the IDs match, the 'local' Group has been # found and therefore local core. # If the groupId's do not match, the 'remote' or 'master' group has been # found. group_list = discovery_info.getAllGroups() for g in group_list: logging.info("[initialize] group_id:{0}".format(g.groupId)) if g.groupId == cfg['group']['id']: local_cores = g.coreConnectivityInfoList local['core'] = local_cores[0] # just grab first core as local local['ca'] = g.caList else: remote_cores = g.coreConnectivityInfoList remote['core'] = remote_cores[0] # just grab first core as remote remote['ca'] = g.caList if len(local) > 1 and len(remote) > 1: logging.info("[initialize] local_core:{0} remote_core:{1}".format( local, remote )) else: raise EnvironmentError("Couldn't find the arm's Cores.") # just save one of the group's CAs to use as a CA file later local_core_ca_file = utils.save_group_ca( local['ca'][0], group_ca_path, local['core'].groupId ) remote_core_ca_file = utils.save_group_ca( remote['ca'][0], group_ca_path, remote['core'].groupId ) # Greengrass Cores discovered, now connect to Cores from this Device # get a client to send telemetry local_mqttc = AWSIoTMQTTClient(ggd_name) log.info("[initialize] local gca_file:{0} cert:{1}".format( local_core_ca_file, certificate)) local_mqttc.configureCredentials( local_core_ca_file, private_key, certificate ) local_mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST) if not utils.mqtt_connect(mqtt_client=local_mqttc, core_info=local['core']): raise EnvironmentError("Connection to GG Core MQTT failed.") # get a shadow client to receive commands master_shadow_client = AWSIoTMQTTShadowClient(ggd_name) log.info("[initialize] remote ca_file:{0} cert:{1}".format( local_core_ca_file, certificate)) remote_mqttc = master_shadow_client.getMQTTConnection() remote_mqttc.configureCredentials( remote_core_ca_file, private_key, certificate ) if not utils.mqtt_connect(mqtt_client=master_shadow_client, core_info=remote['core']): raise EnvironmentError("Connection to Master Shadow failed.") # create and register the shadow handler on delta topics for commands # with a persistent connection to the Master shadow master_shadow = master_shadow_client.createShadowHandlerWithName( cfg['misc']['master_shadow_name'], True) log.info("[initialize] created handler for shadow name: {0}".format( cfg['misc']['master_shadow_name'] )) token = master_shadow.shadowGet(shadow_mgr, 5) log.info("[initialize] shadowGet() tk:{0}".format(token)) return local_mqttc, remote_mqttc, master_shadow
port = 8883 # 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 AWSIoTMQTTClient myAWSIoTMQTTClient = None if useWebsocket: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True) 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':
db_obj.use_database(cursor, DB_NAME) #create temperature Table db_obj.create_temp_tb(cursor) #create Humidity table db_obj.create_humidity_tb(cursor) # commit the changes db_obj.commit_db(dbase) widget.show() print("SETUP") # AWS IoT Setup mqttClient.configureEndpoint( "au6bjtfll29y2-ats.iot.us-east-1.amazonaws.com", 8883) mqttClient.configureCredentials( "/home/pi/project_03/Amazon_Root_CA_1.pem", "/home/pi/project_03/d770d71751-private.pem.key", "/home/pi/project_03/d770d71751-certificate.pem.crt") mqttClient.configureOfflinePublishQueueing(-1) mqttClient.configureDrainingFrequency(2) mqttClient.configureConnectDisconnectTimeout(10) mqttClient.configureMQTTOperationTimeout(5) # MQTT Connect and Publish mqttClient.connect() mqttClient.publish("thatpithing/lamda/topic", "Hey there! Connected.", 0) # Testing ''' while 1: payload = "temperature = 34" mqttClient.publish("thatpithing/lamda/topic", json.dumps(payload), 0)