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")
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
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) # Task1 : Configure AWSIotMQTTCLIent, connect and subscribe laptop to AWS IoT myAWSIoTMQTTClient = None myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) myAWSIoTMQTTClient.configureDrainingFrequency(2) myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) myAWSIoTMQTTClient.configureMQTTOperationTimeout(30) myAWSIoTMQTTClient.connect() # Task2 : Send message to the console. while True: message = {} message['test-key'] = "Current weather: Raining" message['sequence'] = loopCount messageJson = json.dumps(message) myAWSIoTMQTTClient.publish(topic, messageJson, 0) print('Published topic %s: %s\n' % (topic, messageJson)) loopCount += 1 time.sleep(5)
logger = logging.getLogger("DirectMethodLambdaFunction") logger.setLevel(logging.INFO) clientId = 'directMethod_' + str(uuid.uuid4()) iotEndpoint = os.environ.get('IOT_ENDPOINT', None) if not iotEndpoint: raise ValueError('IOT_ENDPOINT env variable is empty or missing!') myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True) myAWSIoTMQTTClient.configureEndpoint(iotEndpoint, 443) myAWSIoTMQTTClient.configureCredentials('AmazonRootCA1.pem') # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing( 0) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect() REQUEST_TOPIC_FORMAT = 'device/%s/methods/%s/%s' RESPONSE_TOPIC_FORMAT = 'device/methods/res/+/%s' def generateCallback(apiResponse, responseTopic, deviceResponded): def customCallback(client, userdata, message): myAWSIoTMQTTClient.unsubscribeAsync(responseTopic) statusCode = int(message.topic.split('/')[-2])
class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(441, 449) MainWindow.setStyleSheet("background-color: rgb(170, 170, 255);") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(70, 50, 101, 21)) self.label.setObjectName("label") self.comboBox = QtWidgets.QComboBox(self.centralwidget) self.comboBox.setGeometry(QtCore.QRect(180, 50, 151, 31)) self.comboBox.setObjectName("comboBox") self.comboBox.addItem("Select item") self.comboBox.addItem("A") self.comboBox.addItem("B") self.comboBox.addItem("C") self.comboBox.activated[str].connect(self.selectionFunc) self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(80, 120, 101, 31)) self.pushButton.setObjectName("pushButton") self.pushButton.clicked.connect(self.add_val) self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_2.setGeometry(QtCore.QRect(220, 120, 101, 31)) self.pushButton_2.setObjectName("pushButton_2") self.pushButton_2.clicked.connect(self.send_val) self.label_3 = QtWidgets.QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(80, 180, 241, 21)) self.label_3.setObjectName("label_3") self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit_2.setGeometry(QtCore.QRect(80, 220, 221, 33)) self.lineEdit_2.setStyleSheet("background-color: rgb(255, 255, 255);") self.lineEdit_2.setReadOnly(True) self.lineEdit_2.setObjectName("lineEdit_2") self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_3.setGeometry(QtCore.QRect(140, 310, 101, 31)) self.pushButton_3.setObjectName("pushButton_3") self.pushButton_3.clicked.connect(self.get_image) self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(100, 280, 191, 21)) self.label_2.setObjectName("label_2") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 441, 27)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.label.setText(_translate("MainWindow", "Object Name:")) self.pushButton.setText(_translate("MainWindow", "Add")) self.pushButton_2.setText(_translate("MainWindow", "Done")) self.label_3.setText( _translate("MainWindow", "You have following items in cart:")) self.pushButton_3.setText(_translate("MainWindow", "Get image")) self.label_2.setText( _translate("MainWindow", "Current warehouse image:")) def selectionFunc(self, text): self.new_val = text print(self.new_val) def add_val(self, Mainwindow): new_choice = None _translate = QtCore.QCoreApplication.translate print("Add-val") if (self.new_val is not None): valueArray.append(self.new_val) print(valueArray) self.lineEdit_2.setText(_translate("MainWindow", ', '.join(valueArray))) time_date_value = QtCore.QDateTime.currentDateTime().toString() connection = sqlite3.connect("user.db") connection.execute("INSERT INTO DATA VALUES(?,?)", (self.new_val, time_date_value)) connection.commit() #connection.close() curs = connection.cursor() curs.execute("SELECT ITEM FROM DATA") for reading in curs.fetchall(): print(str(reading[0])) connection.close() ## pydict = {'Object': self.new_val} ## jsondict = json.dumps(pydict) ## self.myAWSIoTMQTTClient.publish('robotarm', jsondict, 1) def send_val(self, Mainwindow): _translate = QtCore.QCoreApplication.translate print("Done") message_queue = str(self.lineEdit_2.text()) self.lineEdit_2.setText(_translate("MainWindow", "")) del valueArray[:] ## client = mqtt.Client("RobotArm") ## client.connect("iot.eclipse.org") ## client.publish("Robot/test",self.message_queue) ## client.disconnect() pydict = {'Objects': message_queue} jsondict = json.dumps(pydict) self.myAWSIoTMQTTClient.publish('myrobot', jsondict, 1) def get_image(self): image = Image.open("myimage.jpeg") image.show() def mqttSetup(self): self.myAWSIoTMQTTClient = AWSIoTMQTTClient("clientId") self.myAWSIoTMQTTClient.configureEndpoint( "a1hfsu5g939d5k-ats.iot.us-east-2.amazonaws.com", 8883) self.myAWSIoTMQTTClient.configureCredentials( "/home/pi/Desktop/SuperProject_Anay/Certs2/root-CA.crt", "/home/pi/Desktop/SuperProject_Anay/Certs2/f143328a3c-private.pem.key", "/home/pi/Desktop/SuperProject_Anay/Certs2/f143328a3c-certificate.pem.crt" ) 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 self.myAWSIoTMQTTClient.connect() print("MQTT Conn Success") self.myAWSIoTMQTTClient.subscribe('myrobot', 1, None)
class IoTClientWrapper(object): """ IoTClientWrapper Wrapper around the AWS Iot Python SDK. Sets common parameters based on the SDK's Basic PubSub sample https://github.com/aws/aws-iot-device-sdk-python/blob/master/samples/basicPubSub/basicPubSub.py """ def __init__(self, endpoint, root_ca_path, certificate_path, private_key_path, client_id): self.host = endpoint self.root_ca_path = root_ca_path self.certificate_path = certificate_path self.private_key_path = private_key_path if not args.client_id: self.client_id = gethostname() else: self.client_id = args.client_id self.iot_client = None def publish(self, publish_to_topic, payload): """Publish to MQTT""" self.iot_client.publish(topic=publish_to_topic, payload=payload, QoS=0) def subscribe(self, subscribe_to_topic, callback): """Subscribe to MQTT""" self.iot_client.subscribe( topic=subscribe_to_topic, callback=callback, QoS=1, ) def connect(self): """Connect to AWS IoT""" if not self.certificate_path or not self.private_key_path: print("Missing credentials for authentication.") exit(2) # Configure logging logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.INFO) stream_handler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) self.iot_client = AWSIoTMQTTClient(self.client_id) self.iot_client.configureEndpoint(self.host, 8883) self.iot_client.configureCredentials(self.root_ca_path, self.private_key_path, self.certificate_path) # AWSIoTMQTTClient connection configuration self.iot_client.configureAutoReconnectBackoffTime(1, 32, 20) self.iot_client.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing self.iot_client.configureDrainingFrequency(2) # Draining: 2 Hz self.iot_client.configureConnectDisconnectTimeout(60) self.iot_client.configureMQTTOperationTimeout(60) # 5 sec # Connect and subscribe to AWS IoT self.iot_client.connect() sleep(2)
def awsProxy(): import socks from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient import logging import time import argparse import json import random from pathlib import Path AllowedActions = ['both', 'publish', 'subscribe'] # 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") # 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 = "a2on3hwushji1e-ats.iot.us-east-2.amazonaws.com" rootCAPath = Path("../static/certificates/awsDevice/root-CA.crt") certificatePath = Path( "../static/certificates/awsDevice/testDevice.cert.pem") privateKeyPath = Path( "../static/certificates/awsDevice/testDevice.private.key") port = 443 useWebsocket = False clientId = "basicPubSub" deviceName = "awsDevice" frequency = 5 timeInterval = 10 minRange = 10 maxRange = 100 topic = "simulator/test" mode = "publish" if mode not in AllowedActions: parser.error("Unknown --mode option %s. Must be one of %s" % (mode, str(AllowedActions))) exit(2) if useWebsocket and certificatePath and privateKeyPath: parser.error( "X.509 cert authentication and WebSocket are mutual exclusive. Please pick one.") exit(2) if not useWebsocket and (not certificatePath or not privateKeyPath): parser.error("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 # 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) proxy_config = {"proxy_addr": "http://127.0.0.1", "proxy_port": 5000, "proxy_type": 3} # create anonymous function to handle socket creation def socket_factory(): return socks.create_connection((host, port), **proxy_config) myAWSIoTMQTTClient.configureSocketFactory(socket_factory) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials( rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # AWSIoTMQTTClient socket configuration # import pysocks to help us build a socket that supports a proxy configuration # set proxy arguments (for SOCKS5 proxy: proxy_type=2, for HTTP proxy: proxy_type=3) # 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)) # loopCount += 1 # time.sleep(1) def valueGen(): a = random.randint(minRange, maxRange) return a loopCount = 0 print("Frequency === ", frequency) while loopCount < frequency: if mode == 'both' or mode == 'publish': print("Coming here ...1") message = {} value = valueGen() message['value'] = value messageJson = json.dumps(message) print("Coming here ...2") myAWSIoTMQTTClient.publish(topic, messageJson, 1) print("Coming here ...3") if mode == 'publish': print('Published topic %s: %s\n' % (topic, messageJson)) loopCount += 1 time.sleep(timeInterval)
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
class AWS_ROS_Comm: def __init__(self): self.robot_control_pub = rospy.Publisher(ROS_ROBOT_TOPIC, String) useWebsocket = False host = "" rootCAPath = "" certificatePath = "" privateKeyPath = "" host_file_addr = rospy.get_param("~aws_service_location") rootCAPath = rospy.get_param("~aws_service_root_CA") certificatePath = rospy.get_param("~aws_service_cert") privateKeyPath = rospy.get_param("~aws_service_private_key") useWebsocket = False host_file = open(host_file_addr, 'r') host = host_file.readline()[:-1] # try: # opts, args = getopt.getopt(sys.argv[1:], "hwe:k:c:r:", ["help", "endpoint=", "key=","cert=","rootCA=", "websocket"]) # if len(opts) == 0: # raise getopt.GetoptError("No input parameters!") # for opt, arg in opts: # if opt in ("-h", "--help"): # print(helpInfo) # exit(0) # if opt in ("-e", "--endpoint"): # host = arg # if opt in ("-r", "--rootCA"): # rootCAPath = arg # if opt in ("-c", "--cert"): # certificatePath = arg # if opt in ("-k", "--key"): # privateKeyPath = arg # if opt in ("-w", "--websocket"): # useWebsocket = True # except getopt.GetoptError: # exit(1) # missingConfiguration = False # if not host: # print("Missing '-e' or '--endpoint'") # missingConfiguration = True # if not rootCAPath: # print("Missing '-r' or '--rootCA'") # missingConfiguration = True # if not useWebsocket: # if not certificatePath: # print("Missing '-c' or '--cert'") # missingConfiguration = True # if not privateKeyPath: # print("Missing '-k' or '--key'") # missingConfiguration = True # if missingConfiguration: # exit(2) # 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 self.myAWSIoTMQTTClient = None if useWebsocket: self.myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSub", useWebsocket=True) self.myAWSIoTMQTTClient.configureEndpoint(host, 443) self.myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: self.myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSub") self.myAWSIoTMQTTClient.configureEndpoint(host, 8883) 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 # Connect and subscribe to AWS IoT self.myAWSIoTMQTTClient.connect() self.myAWSIoTMQTTClient.subscribe(AWS_CALLBACK_TOPIC, 1, self.customCallback) print 'here' time.sleep(2) def customCallback(self, client, userdata, message): print("Received a new message: ") print(message.payload) print("from topic: ") print(message.topic) ## convert aws msg to a string command #command_str = self.decode_json(message.payload) aws_fake_msg = '{"x":1, "y":0, "z":0}' command_str = self.decode_json(aws_fake_msg) self.robot_control_pub.publish(command_str) print("--------------\n\n") def decode_json(self, msg): ## parse aws string dict_msg = ast.literal_eval(msg) linear_direction = [ dict_msg['x'], dict_msg['y'], dict_msg['z'], 0, 0, 0 ] linear_speed = [0.04 * l for l in linear_direction] command = 'speedl(' + str(linear_speed) + ', 0.1)' return command def run(self): while True and not rospy.is_shutdown(): print('waiting for message ...') ros_msg = rospy.wait_for_message(ROS_TOPIC_NAME, JointState) json_msg = self.ros2json(ros_msg) #print json_msg #self.myAWSIoTMQTTClient.publish('aws_iot_test', json_msg, 1) self.myAWSIoTMQTTClient.publish(AWS_SEND_TOPIC, json_msg, 1) time.sleep(1) def ros2json(self, msg): return convert_ros_message_to_json(msg) def json2ros(self, rosmsg_type, msg): return convert_json_to_ros_message(rosmsg_type, msg)
class Ui_DHT22SensorData(object): #Initialization variables def __init__(self): self.maximumtemperature = 0 self.minimumtemperature = 50 self.maximumhumidity = 0 self.minimumhumidity = 50 self.temperaturesum = 0 self.humiditysum = 0 self.count = 1 myAWSIoTMQTClient = None self.mqttSetup() #Setting up MQTT for data transfer to AWS, Connecting and Subscribing to Topic/Thing def mqttSetup(self): self.myAWSIoTMQTTClient = AWSIoTMQTTClient("clientId") self.myAWSIoTMQTTClient.configureEndpoint( "a31pa84ob6kseu-ats.iot.us-east-1.amazonaws.com", 8883) self.myAWSIoTMQTTClient.configureCredentials( "/home/pi/EID-Fall-2018_Project3/Certificates/CA-cert.pem", "/home/pi/EID-Fall-2018_Project3/Certificates/a4ce7d3179-private.pem.key", "/home/pi/EID-Fall-2018_Project3/Certificates/a4ce7d3179-certificate.pem.crt" ) 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 self.myAWSIoTMQTTClient.connect() print("MQTT Conn Success") self.myAWSIoTMQTTClient.subscribe('EIDProject3', 1, None) #UI Parameters def setupUi(self, DHT22SensorData): DHT22SensorData.setObjectName("DHT22SensorData") DHT22SensorData.resize(547, 400) DHT22SensorData.setStyleSheet( "background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(128, 138, 0, 255), stop:1 rgba(255, 255, 255, 255));" ) self.centralwidget = QtWidgets.QWidget(DHT22SensorData) self.centralwidget.setObjectName("centralwidget") self.Background = QtWidgets.QLabel(self.centralwidget) self.Background.setGeometry(QtCore.QRect(-30, -50, 551, 440)) self.Background.setText("") self.Background.setPixmap(QtGui.QPixmap("main-image.jpg")) self.Background.setObjectName("Background") self.label_7 = QtWidgets.QLabel(self.centralwidget) self.label_7.setGeometry(QtCore.QRect(20, 250, 141, 21)) self.label_7.setObjectName("label_7") self.label_8 = QtWidgets.QLabel(self.centralwidget) self.label_8.setGeometry(QtCore.QRect(20, 310, 141, 21)) self.label_8.setObjectName("label_8") self.TempPlotPushButton = QtWidgets.QPushButton(self.centralwidget) self.TempPlotPushButton.setGeometry(QtCore.QRect(20, 280, 81, 21)) self.TempPlotPushButton.setObjectName("TempPlotPushButton") self.HumidityPlotPushButton = QtWidgets.QPushButton(self.centralwidget) self.HumidityPlotPushButton.setGeometry(QtCore.QRect(20, 340, 81, 21)) self.HumidityPlotPushButton.setObjectName("HumidityPlotPushButton") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(20, 190, 111, 21)) self.label.setObjectName("label") self.SensorState = QtWidgets.QLabel(self.centralwidget) self.SensorState.setGeometry(QtCore.QRect(20, 220, 131, 21)) self.SensorState.setText("") self.SensorState.setObjectName("SensorState") self.Datelabel = QtWidgets.QLabel(self.centralwidget) self.Datelabel.setGeometry(QtCore.QRect(20, 110, 121, 21)) self.Datelabel.setObjectName("Datelabel") self.Timelabel = QtWidgets.QLabel(self.centralwidget) self.Timelabel.setGeometry(QtCore.QRect(20, 140, 180, 40)) self.Timelabel.setText("") self.Timelabel.setObjectName("Timelabel") self.Humidity = QtWidgets.QLabel(self.centralwidget) self.Humidity.setGeometry(QtCore.QRect(390, 20, 44, 41)) self.Humidity.setText("") self.Humidity.setPixmap(QtGui.QPixmap("rsz_1humidity.jpg")) self.Humidity.setObjectName("Humidity") self.Temp = QtWidgets.QLabel(self.centralwidget) self.Temp.setGeometry(QtCore.QRect(200, 20, 21, 61)) self.Temp.setText("") self.Temp.setPixmap(QtGui.QPixmap("rsz_therm.jpg")) self.Temp.setObjectName("Temp") self.label_6 = QtWidgets.QLabel(self.centralwidget) self.label_6.setGeometry(QtCore.QRect(20, 10, 131, 91)) self.label_6.setStyleSheet("font: 75 18pt \"PibotoLt\";") self.label_6.setObjectName("label_6") self.CelciusRadioButton = QtWidgets.QRadioButton(self.centralwidget) self.CelciusRadioButton.setGeometry(QtCore.QRect(220, 80, 101, 21)) self.CelciusRadioButton.setObjectName("CelciusRadioButton") self.FarenheitRadioButton = QtWidgets.QRadioButton(self.centralwidget) self.FarenheitRadioButton.setGeometry(QtCore.QRect(220, 100, 101, 21)) self.FarenheitRadioButton.setObjectName("FarenheitRadioButton") self.layoutWidget = QtWidgets.QWidget(self.centralwidget) self.layoutWidget.setGeometry(QtCore.QRect(220, 190, 77, 50)) self.layoutWidget.setObjectName("layoutWidget") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.layoutWidget) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setObjectName("verticalLayout_2") self.Datelabel_3 = QtWidgets.QLabel(self.layoutWidget) self.Datelabel_3.setObjectName("Datelabel_3") self.verticalLayout_2.addWidget(self.Datelabel_3) self.TempMaxValue = QtWidgets.QLabel(self.layoutWidget) self.TempMaxValue.setText("") self.TempMaxValue.setObjectName("TempMaxValue") self.verticalLayout_2.addWidget(self.TempMaxValue) self.layoutWidget_2 = QtWidgets.QWidget(self.centralwidget) self.layoutWidget_2.setGeometry(QtCore.QRect(220, 250, 77, 50)) self.layoutWidget_2.setObjectName("layoutWidget_2") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.layoutWidget_2) self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.verticalLayout_3.setObjectName("verticalLayout_3") self.Datelabel_4 = QtWidgets.QLabel(self.layoutWidget_2) self.Datelabel_4.setObjectName("Datelabel_4") self.verticalLayout_3.addWidget(self.Datelabel_4) self.TempMinValue = QtWidgets.QLabel(self.layoutWidget_2) self.TempMinValue.setText("") self.TempMinValue.setObjectName("TempMinValue") self.verticalLayout_3.addWidget(self.TempMinValue) self.layoutWidget_3 = QtWidgets.QWidget(self.centralwidget) self.layoutWidget_3.setGeometry(QtCore.QRect(220, 320, 77, 50)) self.layoutWidget_3.setObjectName("layoutWidget_3") self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.layoutWidget_3) self.verticalLayout_4.setContentsMargins(0, 0, 0, 0) self.verticalLayout_4.setObjectName("verticalLayout_4") self.Datelabel_5 = QtWidgets.QLabel(self.layoutWidget_3) self.Datelabel_5.setObjectName("Datelabel_5") self.verticalLayout_4.addWidget(self.Datelabel_5) self.TempAverageValue = QtWidgets.QLabel(self.layoutWidget_3) self.TempAverageValue.setText("") self.TempAverageValue.setObjectName("TempAverageValue") self.verticalLayout_4.addWidget(self.TempAverageValue) self.layoutWidget_4 = QtWidgets.QWidget(self.centralwidget) self.layoutWidget_4.setGeometry(QtCore.QRect(370, 130, 77, 50)) self.layoutWidget_4.setObjectName("layoutWidget_4") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.layoutWidget_4) self.verticalLayout_5.setContentsMargins(0, 0, 0, 0) self.verticalLayout_5.setObjectName("verticalLayout_5") self.Datelabel_6 = QtWidgets.QLabel(self.layoutWidget_4) self.Datelabel_6.setObjectName("Datelabel_6") self.verticalLayout_5.addWidget(self.Datelabel_6) self.HumLastValue = QtWidgets.QLabel(self.layoutWidget_4) self.HumLastValue.setText("") self.HumLastValue.setObjectName("HumLastValue") self.verticalLayout_5.addWidget(self.HumLastValue) self.layoutWidget_5 = QtWidgets.QWidget(self.centralwidget) self.layoutWidget_5.setGeometry(QtCore.QRect(370, 190, 77, 50)) self.layoutWidget_5.setObjectName("layoutWidget_5") self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.layoutWidget_5) self.verticalLayout_6.setContentsMargins(0, 0, 0, 0) self.verticalLayout_6.setObjectName("verticalLayout_6") self.Datelabel_7 = QtWidgets.QLabel(self.layoutWidget_5) self.Datelabel_7.setObjectName("Datelabel_7") self.verticalLayout_6.addWidget(self.Datelabel_7) self.HumMaxValue = QtWidgets.QLabel(self.layoutWidget_5) self.HumMaxValue.setText("") self.HumMaxValue.setObjectName("HumMaxValue") self.verticalLayout_6.addWidget(self.HumMaxValue) self.layoutWidget_6 = QtWidgets.QWidget(self.centralwidget) self.layoutWidget_6.setGeometry(QtCore.QRect(370, 250, 77, 50)) self.layoutWidget_6.setObjectName("layoutWidget_6") self.verticalLayout_7 = QtWidgets.QVBoxLayout(self.layoutWidget_6) self.verticalLayout_7.setContentsMargins(0, 0, 0, 0) self.verticalLayout_7.setObjectName("verticalLayout_7") self.Datelabel_8 = QtWidgets.QLabel(self.layoutWidget_6) self.Datelabel_8.setObjectName("Datelabel_8") self.verticalLayout_7.addWidget(self.Datelabel_8) self.HumMinValue = QtWidgets.QLabel(self.layoutWidget_6) self.HumMinValue.setText("") self.HumMinValue.setObjectName("HumMinValue") self.verticalLayout_7.addWidget(self.HumMinValue) self.layoutWidget_7 = QtWidgets.QWidget(self.centralwidget) self.layoutWidget_7.setGeometry(QtCore.QRect(370, 320, 77, 50)) self.layoutWidget_7.setObjectName("layoutWidget_7") self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.layoutWidget_7) self.verticalLayout_8.setContentsMargins(0, 0, 0, 0) self.verticalLayout_8.setObjectName("verticalLayout_8") self.Datelabel_9 = QtWidgets.QLabel(self.layoutWidget_7) self.Datelabel_9.setObjectName("Datelabel_9") self.verticalLayout_8.addWidget(self.Datelabel_9) self.HumAverageValue = QtWidgets.QLabel(self.layoutWidget_7) self.HumAverageValue.setText("") self.HumAverageValue.setObjectName("HumAverageValue") self.verticalLayout_8.addWidget(self.HumAverageValue) self.widget = QtWidgets.QWidget(self.centralwidget) self.widget.setGeometry(QtCore.QRect(220, 130, 77, 50)) self.widget.setObjectName("widget") self.verticalLayout = QtWidgets.QVBoxLayout(self.widget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.Datelabel_2 = QtWidgets.QLabel(self.widget) self.Datelabel_2.setObjectName("Datelabel_2") self.verticalLayout.addWidget(self.Datelabel_2) self.TempLastValue = QtWidgets.QLabel(self.widget) self.TempLastValue.setText("") self.TempLastValue.setObjectName("TempLastValue") self.verticalLayout.addWidget(self.TempLastValue) DHT22SensorData.setCentralWidget(self.centralwidget) #Functions self.retranslateUi(DHT22SensorData) self.getTime() self.CelciusRadioButton.click() self.FarenheitRadioButton.clicked.connect(self.getDataFahrenheit) self.CelciusRadioButton.clicked.connect(self.getDataCelcius) self.timer = QTimer() self.timer.timeout.connect(self.getDataCelcius) self.timer.start(5000) self.TempPlotPushButton.clicked.connect(self.plotGraph) self.HumidityPlotPushButton.clicked.connect(self.plotGraph) QtCore.QMetaObject.connectSlotsByName(DHT22SensorData) def retranslateUi(self, DHT22SensorData): _translate = QtCore.QCoreApplication.translate DHT22SensorData.setWindowTitle( _translate("DHT22SensorData", "DHT22 Sensor Data ")) self.label_7.setText(_translate("DHT22SensorData", "Temperature Graph")) self.label_8.setText(_translate("DHT22SensorData", "Humidity Graph")) self.TempPlotPushButton.setText(_translate("DHT22SensorData", "PLOT!")) self.HumidityPlotPushButton.setText( _translate("DHT22SensorData", "PLOT!")) self.label.setText(_translate("DHT22SensorData", "Sensor State : ")) self.Datelabel.setText(_translate("DHT22SensorData", "Date and Time:")) self.label_6.setText(_translate("DHT22SensorData", "Welcome!")) self.CelciusRadioButton.setText( _translate("DHT22SensorData", "Celcius")) self.FarenheitRadioButton.setText( _translate("DHT22SensorData", "Farenheit")) self.Datelabel_3.setText(_translate("DHT22SensorData", "Maximum")) self.Datelabel_4.setText(_translate("DHT22SensorData", "Minimum")) self.Datelabel_5.setText(_translate("DHT22SensorData", "Average")) self.Datelabel_6.setText(_translate("DHT22SensorData", "Last value:")) self.Datelabel_7.setText(_translate("DHT22SensorData", "Maximum")) self.Datelabel_8.setText(_translate("DHT22SensorData", "Minimum")) self.Datelabel_9.setText(_translate("DHT22SensorData", "Average")) self.Datelabel_2.setText(_translate("DHT22SensorData", "Last value:")) #Function to get current humidity and temperature data (in celcius), send them to AWS in json format via MQTT Publish, calculate max,min,avg, and write them to a csv file def getDataCelcius(self): global count humidity, temperature = Adafruit_DHT.read(22, 4) if humidity and temperature is None: self.SensorState.setText("Disconnected") if humidity and temperature is not None: self.SensorState.setText("Connected") temp_data = '{0:.2f}'.format(temperature) humid_data = '{0:.2f}'.format(humidity) pydict = {'Temperature': temp_data, 'Humidity': humid_data} jsondict = json.dumps(pydict) self.myAWSIoTMQTTClient.publish('EIDProject3', jsondict, 1) self.TempLastValue.setText(temp_data) self.HumLastValue.setText(humid_data + '%') self.humiditysum += float(humidity) self.temperaturesum += float(temperature) averagehumidity = (self.humiditysum / float(self.count)) averagetemperature = (self.temperaturesum / float(self.count)) average_humid_data = '{0:.2f}'.format(averagehumidity) average_temp_data = '{0:.2f}'.format(averagetemperature) self.HumAverageValue.setText('{0:.2f}'.format(averagehumidity) + '%') self.TempAverageValue.setText('{0:.2f}'.format( (averagetemperature)) + 'degC') self.count += 1 if (temperature > self.maximumtemperature): self.maximumtemperature = temperature if (humidity > self.maximumhumidity): self.maximumhumidity = humidity if (temperature < self.minimumtemperature): self.minimumtemperature = temperature if (humidity < self.minimumhumidity): self.minimumhumidity = humidity max_temp_data = '{0:.2f}'.format(self.maximumtemperature) min_temp_data = '{0:.2f}'.format(self.minimumtemperature) max_humid_data = '{0:.2f}'.format(self.maximumhumidity) min_humid_data = '{0:.2f}'.format(self.minimumhumidity) self.TempMaxValue.setText('{0:.2f}'.format( (self.maximumtemperature)) + 'degC') self.HumMaxValue.setText('{0:.2f}'.format(self.maximumhumidity) + '%') self.TempMinValue.setText('{0:.2f}'.format( (self.minimumtemperature)) + 'degC') self.HumMinValue.setText('{0:.2f}'.format(self.minimumhumidity) + '%') with open('data.csv', 'a', newline='') as datafile: file_write = csv.writer(datafile, delimiter=',') file_write.writerow([ temp_data, max_temp_data, min_temp_data, average_temp_data, humid_data, max_humid_data, min_humid_data, average_humid_data, self.getTime() ]) else: with open('data.csv', 'a', newline='') as datafile: file_write = csv.writer(datafile, delimiter=',') file_write.writerow([0, 0, 0, 0, 0, 0, 0, 0, self.getTime()]) print("No Data Sensed") #Function to get current humidity and temperature data (in fahrenheit), send them to AWS in json format via MQTT Publish, calculate max,min,avg and write them to a csv file def getDataFahrenheit(self): global count humidity, temperature = Adafruit_DHT.read(22, 4) if humidity and temperature is None: self.SensorState.setText("Disconnected") if humidity and temperature is not None: self.SensorState.setText("Connected") tempf = (float(temperature) * (9 / 5.0)) + 32 temp_data = '{0:.2f}'.format(tempf) humid_data = '{0:.2f}'.format(humidity) pydict = {'Temperature': temp_data, 'Humidity': humid_data} jsondict = json.dumps(pydict) self.myAWSIoTMQTTClient.publish('EIDProject3', jsondict, 1) self.TempLastValue.setText(temp_data) self.HumLastValue.setText(humid_data + '%') self.humiditysum += float(humidity) self.temperaturesum += float(tempf) averagehumidity = (self.humiditysum / float(self.count)) averagetemperature = (self.temperaturesum / float(self.count)) average_humid_data = '{0:.2f}'.format(averagehumidity) average_temp_data = '{0:.2f}'.format(averagetemperature) self.HumAverageValue.setText('{0:.2f}'.format(averagehumidity) + '%') self.TempAverageValue.setText('{0:.2f}'.format( (averagetemperature)) + 'degF') self.count += 1 if (tempf > self.maximumtemperature): self.maximumtemperature = tempf if (humidity > self.maximumhumidity): self.maximumhumidity = humidity if (tempf < self.minimumtemperature): self.minimumtemperature = tempf if (humidity < self.minimumhumidity): self.minimumhumidity = humidity max_temp_data = '{0:.2f}'.format(self.maximumtemperature) min_temp_data = '{0:.2f}'.format(self.minimumtemperature) max_humid_data = '{0:.2f}'.format(self.maximumhumidity) min_humid_data = '{0:.2f}'.format(self.minimumhumidity) self.TempMaxValue.setText('{0:.2f}'.format( (self.maximumtemperature)) + 'degF') self.HumMaxValue.setText('{0:.2f}'.format(self.maximumhumidity) + '%') self.TempMinValue.setText('{0:.2f}'.format( (self.minimumtemperature)) + 'degF') self.HumMinValue.setText('{0:.2f}'.format(self.minimumhumidity) + '%') with open('data.csv', 'a', newline='') as datafile: file_write = csv.writer(datafile, delimiter=',') file_write.writerow([ temp_data, max_temp_data, min_temp_data, average_temp_data, humid_data, max_humid_data, min_humid_data, average_humid_data, self.getTime() ]) else: with open('data.csv', 'a', newline='') as datafile: file_write = csv.writer(datafile, delimiter=',') file_write.writerow([0, 0, 0, 0, 0, 0, 0, 0, self.getTime()]) print("No Data Sensed") #Function to get timestamp value def getTime(self): currenttime = datetime.datetime.now() now = currenttime.strftime("%m/%d/%Y %H:%M") self.Timelabel.setText(now) return now #Function to plot temperature and humidity graphs based on readings from csv file def plotGraph(self): x = [] y = [] with open('data.csv', 'r') as csvfile: plots = csv.reader(csvfile, delimiter=',') for row in plots: x.append(float(row[0])) y.append(float(row[1])) i = range(0, len(x)) fig1 = plt.figure(1) plt.plot(i, x, 'b') plt.title('Humidity Variation Graph') fig1.savefig('humidgraph.jpg') fig2 = plt.figure(2) plt.plot(i, y, 'r') plt.title('Temperature Variation Graph') fig2.savefig('tempgraph.jpg')
def setupMQTT(): # Usage usageInfo = """Usage: Use certificate based mutual authentication: python basicPubSub.py -e <endpoint> -r <rootCAFilePath> -c <certFilePath> -k <privateKeyFilePath> Use MQTT over WebSocket: python basicPubSub.py -e <endpoint> -r <rootCAFilePath> -w Type "python basicPubSub.py -h" for available options. """ # Help info helpInfo = """-e, --endpoint Your AWS IoT custom endpoint -r, --rootCA Root CA file path -c, --cert Certificate file path -k, --key Private key file path -w, --websocket Use MQTT over WebSocket -h, --help Help information """ # Read in command-line parameters useWebsocket = False host = "a19zzgl8s6zfsq.iot.us-east-1.amazonaws.com" rootCAPath = "rootCA.crt" certificatePath = "88df1a0b0b-certificate.pem.crt" privateKeyPath = "88df1a0b0b-private.pem.key" try: opts, args = getopt.getopt(sys.argv[1:], "hwe:k:c:r:", ["help", "endpoint=", "key=","cert=","rootCA=", "websocket"]) #if len(opts) == 0: #raise getopt.GetoptError("No input parameters!") for opt, arg in opts: if opt in ("-h", "--help"): print(helpInfo) exit(0) if opt in ("-e", "--endpoint"): host = arg if opt in ("-r", "--rootCA"): rootCAPath = arg if opt in ("-c", "--cert"): certificatePath = arg if opt in ("-k", "--key"): privateKeyPath = arg if opt in ("-w", "--websocket"): useWebsocket = True except getopt.GetoptError: print(usageInfo) exit(1) # Missing configuration notification missingConfiguration = False if not host: print("Missing '-e' or '--endpoint'") missingConfiguration = True if not rootCAPath: print("Missing '-r' or '--rootCA'") missingConfiguration = True if not useWebsocket: if not certificatePath: print("Missing '-c' or '--cert'") missingConfiguration = True if not privateKeyPath: print("Missing '-k' or '--key'") missingConfiguration = True if missingConfiguration: exit(2) # 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 global myAWSIoTMQTTClient if useWebsocket: myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSub", useWebsocket=True) myAWSIoTMQTTClient.configureEndpoint(host, 443) myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSub") myAWSIoTMQTTClient.configureEndpoint(host, 8883) 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() myAWSIoTMQTTClient.subscribe("sensor_data/temperature/", 1, customCallback) myAWSIoTMQTTClient.subscribe("sensor_data/sonar/", 1, customCallback) myAWSIoTMQTTClient.subscribe("sensor_data/gas/", 1, customCallback) myAWSIoTMQTTClient.subscribe("sensor_data/flame/", 1, customCallback)
class database(): def __init__(self): try: self.records_list = [] self.LOG = log() self.config = confi() self.localdb = pw.SqliteDatabase(self.config.DATABASE_PATH) md.proxy.initialize(self.localdb) md.devicedata.create_table(True) self.data = md.devicedata() self.myMQTTClient = AWSIoTMQTTClient(self.config.DEVICE_ID) print("INITIALIZING DEVICE ON AWS SERVER") self.myMQTTClient.configureEndpoint(self.config.AWS_ARN, self.config.AWS_PORT) print("CONNECTED WITH AWS ENDPOINT WITH VALID PORT ") except: e = sys.exc_info()[0] self.LOG.ERROR("FAILLED TO INIT AWS IOT" + str(os.path.basename(__file__)) + str(e)) # error logs print("EXCEPTION IN INIT AWS IOT CHECK INTERNET CONNECTIVITY - " + str(e)) pass def Save_In_DataBase(self, payload, date, time, devicetype): try: self.data.timestamp = time self.data.datestamp = date self.data.payload = payload self.data.id = uuid.uuid4() self.data.devicetype = devicetype self.data.deviceid = self.config.DEVICE_ID self.data.orgid = self.config.ORG_ID self.data.save(force_insert=True) except: e = sys.exc_info()[0] self.LOG.ERROR("FAILLED TO SAVE DATA IN DATABASE ,DATABASE ERROR" + str(os.path.basename(__file__)) + str(e)) # error logs print("EXCEPTION IN SAVE DATA IN DATABSE CHECK DATABASE MODELS- " + str(e)) pass def load_credential(self): try: self.certRootPath = self.config.CERT_PATH self.myMQTTClient.configureCredentials( "{}root-ca.pem".format(self.certRootPath), "{}cloud.pem.key".format(self.certRootPath), "{}cloud.pem.crt".format(self.certRootPath)) print("APPLYING CERTIFICATE") except: e = sys.exc_info()[0] self.LOG.ERROR("FAILLED TO LOAD AWS CERTFICATE.." + str(os.path.basename(__file__)) + str(e)) # error logs print("EXCEPTION IN LOADING CERTIFICATE IN AWS IOT" + str(e)) pass def connect_server(self): try: self.myMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) self.myMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing self.myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz self.myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec self.myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec print("CONNECTING MQQT AWS SERVER") self.myMQTTClient.connect() print("CONNECTED TO MQQT IOT AWS") except: e = sys.exc_info()[0] self.LOG.ERROR("FAILLED TO CONNECT TO THE SERVER" + str(os.path.basename(__file__)) + str(e)) # error logs print("EXCEPTION IN CONNECTING AWS SERVER - " + str(e)) pass def update_synced(self, msg_id): try: query = md.devicedata.update(synced=1).where( (md.devicedata.id == msg_id)) query.execute() except: e = sys.exc_info()[0] self.LOG.ERROR("FAILLED TO UPDATE SYNCED DATA TO 0---1" + str(os.path.basename(__file__)) + str(e)) # error logs print("EXCEPTION IN UPDATING SYNCED DATA- " + str(e)) pass def send_AWS(self, topic_path): try: records = self.check_data_base() if records < 25: for data in md.devicedata().select().order_by( md.devicedata.datestamp.desc() and md.devicedata.timestamp.asc()).where( md.devicedata.synced == 0).limit(5): try: self.myMQTTClient.publish( topic_path, json.dumps(model_to_dict(data)), self.config.QOS) print("PUBLISHING DATA TO AWS-:" + str(model_to_dict(data))) msg_id = data.id print(msg_id) self.update_synced(msg_id) except: e = sys.exc_info()[0] self.LOG.ERROR("FAILLED TO SEND DATA TO THE SERVER" + str(os.path.basename(__file__)) + str(e)) # error logs print("EXCEPTION IN SENDING DATA TO AWS SERVER - " + str(e)) continue if records > 25 and records < 50: for data in md.devicedata().select().order_by( md.devicedata.datestamp.desc() and md.devicedata.timestamp.asc()).where( md.devicedata.synced == 0).limit(15): try: self.myMQTTClient.publish( topic_path, json.dumps(model_to_dict(data)), self.config.QOS) print("PUBLISHING DATA TO AWS-:" + str(model_to_dict(data))) msg_id = data.id print(msg_id) self.update_synced(msg_id) except: e = sys.exc_info()[0] self.LOG.ERROR("FAILLED TO SEND DATA TO THE SERVER" + str(os.path.basename(__file__)) + str(e)) # error logs print("EXCEPTION IN SENDING DATA TO AWS SERVER - " + str(e)) continue if records > 50 and records < 75: for data in md.devicedata().select().order_by( md.devicedata.datestamp.desc() and md.devicedata.timestamp.asc()).where( md.devicedata.synced == 0).limit(25): try: self.myMQTTClient.publish( topic_path, json.dumps(model_to_dict(data)), self.config.QOS) print("PUBLISHING DATA TO AWS-:" + str(model_to_dict(data))) msg_id = data.id print(msg_id) self.update_synced(msg_id) except: e = sys.exc_info()[0] self.LOG.ERROR("FAILLED TO SEND DATA TO THE SERVER" + str(os.path.basename(__file__)) + str(e)) # error logs print("EXCEPTION IN SENDING DATA TO AWS SERVER - " + str(e)) continue if records > 75: for data in md.devicedata().select().order_by( md.devicedata.datestamp.desc() and md.devicedata.timestamp.asc()).where( md.devicedata.synced == 0).limit(50): try: self.myMQTTClient.publish( topic_path, json.dumps(model_to_dict(data)), self.config.QOS) print("PUBLISHING DATA TO AWS-:" + str(model_to_dict(data))) msg_id = data.id print(msg_id) self.update_synced(msg_id) except: e = sys.exc_info()[0] self.LOG.ERROR("FAILLED TO SEND DATA TO THE SERVER" + str(os.path.basename(__file__)) + str(e)) # error logs print("EXCEPTION IN SENDING DATA TO AWS SERVER - " + str(e)) continue except: e = sys.exc_info()[0] self.LOG.ERROR("FAILLED TO SEND DATA TO AWS IOT" + str(os.path.basename(__file__)) + str(e)) # error logs print("EXCEPTION IN SENDING DATA TO AWS - " + str(e)) pass def check_data_base(self): for data in md.devicedata().select().order_by( md.devicedata.datestamp.desc() and md.devicedata.timestamp.asc()).where( md.devicedata.synced == 0): self.records_list.append(data) return len(self.records_list)
import falcon from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient mqttClient = AWSIoTMQTTClient("im920-arduino-yun-gps") mqttClient.configureEndpoint("xxxxxxxxxxxxxx.iot.ap-northeast-1.amazonaws.com", 8883) mqttClient.configureCredentials("root-CA.crt", "private.pem.key", "certificate.pem.crt") mqttClient.configureOfflinePublishQueueing(-1) mqttClient.configureDrainingFrequency(2) mqttClient.configureConnectDisconnectTimeout(10) mqttClient.configureMQTTOperationTimeout(5) class PublishResource(object): def on_post(self, req, resp): if req.host == "localhost": mqttClient.publish("im920/location", req.stream.read(), 1) resp.body = "OK" else: resp.body = "NG" app = falcon.API() app.add_route("/publish", PublishResource()) if __name__ == "__main__": mqttClient.connect() from wsgiref import simple_server httpd = simple_server.make_server("127.0.0.1", 8000, app) httpd.serve_forever()
class subscriber_order: 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 print("[Get the message] " + str(datetime.now()) + ' / ' + str(mes_tpc)) 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_ORDER,self.QOS_LEVEL, self.msg_callback) print("Subscribing topic : " + str(pfc_mqtt_topic.SUBSCRIBE_ORDER)) while True: time.sleep(1) def logging(self): None
#pub_topic = "$aws/things/Parking1/shadow/update" #sub_topic = "$aws/things/Parking1/shadow/update/+" topicList = [ "$aws/things/Parking{}/shadow/update".format(i + 1) for i in range(MAX_DEVICES) ] # client configuration aws_mqtt_client = AWSIoTMQTTClient(clientId) aws_mqtt_client.configureEndpoint(host, port) aws_mqtt_client.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # connection configuration aws_mqtt_client.configureAutoReconnectBackoffTime(1, 32, 20) aws_mqtt_client.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing aws_mqtt_client.configureDrainingFrequency(2) # Draining: 2 Hz aws_mqtt_client.configureConnectDisconnectTimeout(10) # 10 sec aws_mqtt_client.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT aws_mqtt_client.connect() for topic in topicList: aws_mqtt_client.subscribe(topic, 1, mqtt_callback) time.sleep(2) # Publish to the same topic in a loop forever loopCount = 0 node_status = 5 # '8266 restarted' message status_param = 0 distance = 0
class IoT(object): # Class to handle AWS IoT SDK connections and commands def __init__(self, host, rootCAPath, certificatePath, privateKeyPath, clientId, useWebsocket=False, mode='both'): self.AllowedActions = ['both', 'publish', 'subscribe'] self.host = host self.rootCAPath = rootCAPath self.certificatePath = certificatePath self.privateKeyPath = privateKeyPath self.clientId = clientId self.useWebsocket = useWebsocket self.mode = mode # Configure logging self.logger = logging.getLogger("AWSIoTPythonSDK.core") self.logger.setLevel(logging.ERROR) streamHandler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) self.logger.addHandler(streamHandler) self.connect_client() self.connect_shadow_client() def connect_client(self): # Init AWSIoTMQTTClient self.myAWSIoTMQTTClient = None if self.useWebsocket: self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.clientId, useWebsocket=True) self.myAWSIoTMQTTClient.configureEndpoint(self.host, 443) self.myAWSIoTMQTTClient.configureCredentials(self.rootCAPath) else: self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.clientId) self.myAWSIoTMQTTClient.configureEndpoint(self.host, 8883) self.myAWSIoTMQTTClient.configureCredentials( self.rootCAPath, self.privateKeyPath, self.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 # Connect and subscribe to AWS IoT self.myAWSIoTMQTTClient.connect() def connect_shadow_client(self, clientId_suffix='_shadow'): # Init AWSIoTMQTTShadowClient clientId = self.clientId + clientId_suffix self.myAWSIoTMQTTShadowClient = None if self.useWebsocket: self.myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient( clientId, useWebsocket=True) self.myAWSIoTMQTTShadowClient.configureEndpoint(self.host, 443) self.myAWSIoTMQTTShadowClient.configureCredentials(self.rootCAPath) else: self.myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId) self.myAWSIoTMQTTShadowClient.configureEndpoint(self.host, 8883) self.myAWSIoTMQTTShadowClient.configureCredentials( self.rootCAPath, self.privateKeyPath, self.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() def shadow_handler(self, thingName): # Create a deviceShadow with persistent subscription self.deviceShadowHandler = self.myAWSIoTMQTTShadowClient.createShadowHandlerWithName( thingName, True) def shadow_get(self, callback): try: # Get shadow JSON doc return self.deviceShadowHandler.shadowGet(callback, 5) except Exception as e: logger.exception(e) def shadow_update(self, json_payload, callback): # Update shadow JSON doc self.deviceShadowHandler.shadowUpdate(json_payload, callback, 5)
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
class IoTManager(): #Initializes device details and creates IoT Core MQTT connection def __init__(self, main): self.main = main self.iot_details = {} self.thing_name = 'BarBot' self.disabled = False #TODO: load this from the settings file schedule.every(30).seconds.do(self.ping) alive_thread = threading.Thread(target=self.keep_alive, daemon=True) alive_thread.start() if not path.exists('./certs/iotDetails.json'): self.disabled = True print('IoT files don\'t exist') return #Load AWS IoT Core details from json file with open('./certs/iotDetails.json', 'r') as file: self.iot_details = json.load(file) self.mqtt_client = AWSIoTMQTTClient('barbot') self.mqtt_client.configureEndpoint(self.iot_details['endpoint'], 8883) self.mqtt_client.configureCredentials( './certs/root-CA.crt', './certs/BarBot-private.pem.key', './certs/BarBot-certificate.pem.crt') self.mqtt_client.configureOfflinePublishQueueing(-1) self.mqtt_client.configureDrainingFrequency(2) self.mqtt_client.configureConnectDisconnectTimeout(15) self.mqtt_client.configureMQTTOperationTimeout(5) try: self.mqtt_client.connect() self.mqtt_client.subscribe('barbot-main', 0, self.parse_message) print('Connected to AWS IoT Core!') #Setup Shadow handler self.shadow_client = AWSIoTMQTTShadowClient('barbot-shadow') self.shadow_client.configureEndpoint(self.iot_details['endpoint'], 8883) self.shadow_client.configureCredentials( './certs/root-CA.crt', './certs/BarBot-private.pem.key', './certs/BarBot-certificate.pem.crt') self.shadow_client.configureAutoReconnectBackoffTime(1, 32, 20) self.shadow_client.configureConnectDisconnectTimeout(10) self.shadow_client.configureMQTTOperationTimeout(5) self.shadow_client.connect() print("Connected to BarBot's IoT Shadow") self.shadow_handler = self.shadow_client.createShadowHandlerWithName( self.thing_name, True) except Exception as e: print(e) self.disabled = True #Parses incoming message from MQTT topic and routes to proper function def parse_message(self, client, userdata, message): print('PARSE MESSAGE') if (self.disabled): return try: real_message = json.loads(message.payload) action = real_message['action'] print('Received MQTT message with action: ' + str(action)) if ('data' in real_message): data = real_message['data'] time_recv = real_message['time'] time_delay = int(datetime.utcnow().replace( tzinfo=timezone.utc).timestamp()) - time_recv if (time_delay > 5): print('Message took too long to receive') return if (action == 'makeCocktail'): #print('Making cocktail: ' + str(data.lower())) self.main.make_cocktail(data.lower()) elif (action == 'alcoholMode'): if (data == True or data == False): self.main.set_alcohol_mode(data) else: print('Not a valid alcoholMode setting!') elif (action == 'getMenu'): cocktail_array = self.main.get_cocktail_list() ret_package = {'state': {'desired': {'menu': cocktail_array}}} #Update the shadow self.update_shadow(ret_package) elif (action == 'message'): print(data) elif (action == 'pumpOn'): self.main.pump_on(int(data)) elif (action == 'pumpOff'): self.main.pump_off(int(data)) except Exception as e: print(e) #Updates BarBot's IoT shadow def update_shadow(self, json_data): if (self.disabled): return self.shadow_handler.shadowUpdate(json.dumps(json_data), self.update_callback, 5) #Callback function for BarBot's IoT def update_callback(self, payload, response_status, token): if (self.disabled): return if (response_status == 'timeout'): print('There was a timeout updating the shadow') elif (response_status == 'accepted'): print("Successfully updated barbot's shadow") elif (response_status == 'rejected'): print("Shadow update was rejected") print(payload) #Send a message to response MQTT topic def send_response(self, data): self.mqtt_client.publish('barbot-res', json.dumps(data), 0) print('Sending ping') def ping(self): data = {"action": "ping"} self.send_response(data) def keep_alive(self): while (True): schedule.run_pending() time.sleep(15)
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
HIGHEST_READS_TO_DISCARD = 3 SECONDS_BETWEEN_READS = 1 # Configure AWS IoT SDK settings AWS_IOT_MQTT_CLIENT = AWSIoTMQTTClient("basicPubSub") PORT = 8883 HOST = "azhkicv1gj9gc-ats.iot.us-east-2.amazonaws.com" ROOT_CA_PATH = "./certs/AmazonRootCA1.pem" PRIVATE_KEY_PATH = "./certs/19ecbe119d-private.pem.key" CERTIFICATE_PATH = "./certs/19ecbe119d-certificate.pem.crt" AWS_IOT_MQTT_CLIENT.configureEndpoint(HOST, PORT) AWS_IOT_MQTT_CLIENT.configureCredentials(ROOT_CA_PATH, PRIVATE_KEY_PATH, CERTIFICATE_PATH) AWS_IOT_MQTT_CLIENT.configureAutoReconnectBackoffTime(1, 32, 20) AWS_IOT_MQTT_CLIENT.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing AWS_IOT_MQTT_CLIENT.configureDrainingFrequency(2) # Draining: 2 Hz AWS_IOT_MQTT_CLIENT.configureConnectDisconnectTimeout(10) # 10 sec AWS_IOT_MQTT_CLIENT.configureMQTTOperationTimeout(5) # 5 sec AWS_IOT_MQTT_CLIENT.connect() bus = smbus.SMBus(1) # I2C bus GPIO.setmode(GPIO.BCM) GPIO_TRIGGER = 24 GPIO_ECHO = 23 GPIO_RAIN = 7 GPIO.setup(GPIO_TRIGGER, GPIO.OUT) GPIO.setup(GPIO_ECHO, GPIO.IN)
ip = info['ID'] ssh_reboot.sshAndReboot(ip, location).judgements() def offline(): print('aws iot is offline.') # Init AWSIoTMQTTClient device = AWSIoTMQTTClient(clientId) device.configureEndpoint(host, 80) device.configureCredentials(caPath, keyPath, certPath) # AWSIoTMQTTClient connection configuration device.configureAutoReconnectBackoffTime(1, 32, 20) device.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing device.configureDrainingFrequency(2) # Draining: 2 Hz device.configureConnectDisconnectTimeout(10) # 10 sec device.configureMQTTOperationTimeout(5) # 5 sec device.onOffline = offline # Connect and subscribe to AWS IoT try: print('AWS IoT connecting...') device.connect(1200) print('AWS IoT connected') device.subscribe(iotConfig.controlSubscribeTo, 1, customCallback) device.subscribe("rebootCommandguyi", 1, customCallback) device.subscribe("controlsignal", 1, customCallback) # publish to AWS IoT status = {"status": 'connected'}
mycount = 1 myAWSIoTMQTTClient = None if useWebsocket: myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSub", useWebsocket=True) myAWSIoTMQTTClient.configureEndpoint(host, 443) myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSub") myAWSIoTMQTTClient.configureEndpoint(host, 8883) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)#auto-reconnect backoff to start with 1 second and use 32 seconds as maximum back off time. Connection over 20 second is considered stable. #configure the offline queue for publish requests to be 20 in size and drop the oldest request when the queue is full myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing (0 is disable) myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz #used to configure the time in seconds to wait for a connect or a disconnect to complete myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT #myAWSIoTMQTTClient.connect() #while True: #myAWSIoTMQTTClient.subscribe("sdk/test/Python", 1, customCallback) #time.sleep(2) ############### sensehat inputs ##################
class MQTTClient(PluginInterface): options = [ 'sensorid', 'topicid', 'topic_pfx', 'endpoint', 'rootca', 'prikey', 'devcert', 'batch', 'interval', 'fields', 'datafmt' ] topic_pfx = 'gravity' endpoint = None rootca = 'root-CA.crt' prikey = 'iot.private.key' devcert = 'iot.cert.pem' interval = 1 fields = ['gravity', 'long', 'cross', 'latitude', 'longitude', 'datetime'] datafmt = 'marine' # Ordered list of marine fields _marine_fieldmap = [ 'header', 'gravity', 'long', 'cross', 'beam', 'temp', 'pressure', 'etemp', 'vcc', 've', 'al', 'ax', 'status', 'checksum', 'latitude', 'longitude', 'speed', 'course', 'datetime' ] _airborne_fieldmap = [] # Defaults to integer cast if not specified here _field_casts = { 'header': str, 'gravity': float, 'latitude': float, 'longitude': float, 'speed': float, 'course': float, 'datetime': convert_time } def __init__(self): super().__init__() # Set AWSIoTPythonSDK logger level from default logging.getLogger('AWSIoTPythonSDK').setLevel(logging.WARNING) self.client = None self.tick = 0 self.sensorid = None self._errcount = 0 @classmethod def extract_fields(cls, data: str, fieldmap=_marine_fieldmap): extracted = {} data = data.split(',') for i, field in enumerate(fieldmap): if field.lower() in cls.fields: try: extracted[field] = cls._field_casts.get( field.lower(), int)(data[i]) except ValueError: extracted[field] = data[i] return extracted @staticmethod def consumer_type() -> set: return {str} # def _batch_process(self): # # TODO: Implement batch publish feature, perhaps collect items in a queue until a limit is reached # # then publish as a list of json maps # sendqueue = [] # limit = 10 def configure_client(self): if self.endpoint is None: raise ValueError("No endpoint provided for MQTT Plugin.") try: self.sensorid = getattr(self, 'sensorid', str(uuid4())[0:8]) topicid = getattr(self, 'topicid', self.sensorid) self.client = AWSIoTMQTTClient(self.sensorid, useWebsocket=False) self.client.configureEndpoint(self.endpoint, 8883) self.client.configureOfflinePublishQueueing(10000) self.client.configureConnectDisconnectTimeout(10) self.client.configureCredentials(join_cfg(self.rootca), join_cfg(self.prikey), join_cfg(self.devcert)) self.client.configureDrainingFrequency(2) self.client.configureMQTTOperationTimeout(5) self.client.connect() topic = '/'.join([self.topic_pfx, topicid]) except AttributeError: LOG.exception( "Missing attributes from configuration for MQTT plugin.") raise return topic def run(self): topic = self.configure_client() while not self.exiting: item = self.get(block=True, timeout=None) self.tick += 1 if item is None or item == "" or self.tick % self.interval: self.task_done() continue else: try: self.tick = 0 # reset tick count fields = item.split(',') timestamp = convert_time(fields[-1]) if not len(fields): continue data_dict = self.extract_fields(item) item_json = json.dumps({ 'd': self.sensorid, 't': timestamp, 'v': data_dict }) self.client.publish(topic, item_json, 0) self.task_done() except: LOG.exception( "Exception occured in mqtt-run loop. Item value: %s", item) self._errcount += 1 if self._errcount > 10: # Terminate MQTT if errors accumulate raise self.client.disconnect()
print(message.payload) print("from topic: ") print(message.topic) print("--------------\n\n") host = "a329f39y597dke-ats.iot.us-east-1.amazonaws.com" rootCAPath = "rootca.txt" certificatePath = "certificate.pem.crt" privateKeyPath = "private.pem.key" my_rpi = AWSIoTMQTTClient("basicPubSub") 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("data/timein/class2", 1, customCallback) my_rpi.subscribe("data/timeout/class2", 1, customCallback) my_rpi.subscribe("data/student/class2", 1, customCallback) sleep(2) loopCount = 0 while continue_reading: bz.off()
def aws_mqtt_node(): # init node rospy.init_node('aws_mqtt_node', anonymous=True) #, log_level=rospy.DEBUG) # load parameters params = rospy.get_param("~", {}) print(params) mqtt_params = params.pop("mqtt", {}) bridge_params = params.pop("bridge", {}) host = mqtt_params.pop("host", "") rootCAPath = mqtt_params.pop("rootCAPath", "") certificatePath = mqtt_params.pop("certificatePath", "") privateKeyPath = mqtt_params.pop("privateKeyPath", "") clientId = mqtt_params.pop("clientId", "") # Init AWSIoTMQTTClient myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureEndpoint(host, 8883) try: myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) except: raise IOError("Cannot load certificates...") else: # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing( 0) # -1:Infinite offline Publish queueing. 0:no queue myAWSIoTMQTTClient.configureDrainingFrequency(50) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # dependency injection config = create_config(myAWSIoTMQTTClient) inject.configure(config) # Connect to AWS IoT try: myAWSIoTMQTTClient.connect() except: raise IOError("Cannot connect to AWS IoT...") else: # configure bridges bridges = [] # setup publishing bridge bridges.append(create_publish_bridge()) # setup subscribing bridges for bridge_args in bridge_params: try: bridges.append(create_subscribe_bridge(**bridge_args)) except Exception, e: rospy.logerr(str(e)) rospy.logerr("Cannot subscribe to the topic %s" % (bridge_args.pop("topic_from", ""))) rospy.loginfo(rospy.get_caller_id() + " All settings are ready!") # spin() simply keeps python from exiting until this node is stopped for bridge in bridges: rospy.on_shutdown(bridge.on_shutdown) rospy.on_shutdown(myAWSIoTMQTTClient.disconnect) rospy.spin()
def startServer(muteoutput): global tv_listings_dict global tv_channels global tv_dict global mute mute = muteoutput if os.path.isfile('helpers/lineup.json'): with open('helpers/lineup.json') as json_data: tv_json = json.load(json_data) for chan in tv_json: tv_channels.append(chan[0]) tv_channels.append(chan[1]) tv_listings_dict[chan[0]] = chan tv_listings_dict[chan[1]] = chan else: tv_channels = [] tv_listings_dict = {} if 'wpvi' in tv_channels: tv_channels.append('abc') tv_listings_dict['abc'] = tv_listings_dict['wpvi'] if 'wtxf' in tv_channels: tv_channels.append('fox') tv_listings_dict['fox'] = tv_listings_dict['wtxf'] for tv in tvconfig.tvs: tv_dict[tv['tv_mac_address']] = tv clientid = prefHelper.deviceUUID() myMQTTClient = AWSIoTMQTTClient(clientid) myMQTTClient.configureEndpoint("afkx1f9takwol.iot.us-east-1.amazonaws.com", 8883) myMQTTClient.configureCredentials(".auth/root.pem", ".auth/private.pem.key", ".auth/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 print('starting server...') myMQTTClient.connect() myMQTTClient.subscribe("power/" + clientid, 1, power) myMQTTClient.subscribe("channel/" + clientid, 1, channel) myMQTTClient.subscribe("speaker/" + clientid, 1, speaker) myMQTTClient.subscribe("playback/" + clientid, 1, playback) #myMQTTClient.unsubscribe("myTopic") #myMQTTClient.disconnect() print('server running. Pres CTRL + C to stop') counter = 0 while True: time.sleep(1) if counter == 0: payload = {"uuid": prefHelper.deviceUUID()} headers = { 'content-type': 'application/json', 'jwt': prefHelper.deviceToken() } try: response = requests.post('https://alexasmarttv.tk/api/v1/ping', data=json.dumps(payload), headers=headers) except: print('failed to ping') counter += 1 counter = counter % 900
class ProvisioningHandler: def __init__(self, file_path): """Initializes the provisioning handler Arguments: file_path {string} -- path to your configuration file """ # Logging logging.basicConfig(level=logging.ERROR) self.logger = logging.getLogger(__name__) # Load configuration settings from config.ini config = Config(file_path) self.config_parameters = config.get_section('SETTINGS') self.secure_cert_path = self.config_parameters['SECURE_CERT_PATH'] self.iot_endpoint = self.config_parameters['IOT_ENDPOINT'] self.template_name = self.config_parameters[ 'PROVISIONING_TEMPLATE_NAME'] self.claim_cert = self.certFullPath( self.config_parameters['CLAIM_CERT']) self.secure_key = self.certFullPath( self.config_parameters['SECURE_KEY']) self.root_cert = self.certFullPath(self.config_parameters['ROOT_CERT']) self.machine_config = self.config_parameters['MACHINE_CONFIG_PATH'] self.error = '' with open(self.machine_config) as json_file: data = json.load(json_file) self.serial_num = data['serial_num'] self.model_type = data['model_type'] # ------------------------------------------------------------------------------ # -- PROVISIONING HOOKS EXAMPLE -- # Provisioning Hooks are a powerful feature for fleet provisioning. Most of the # heavy lifting is performed within the cloud lambda. However, you can send # device attributes to be validated by the lambda. An example is show in the line # below (.hasValidAccount could be checked in the cloud against a database). # Alternatively, a serial number, geo-location, or any attribute could be sent. # # -- Note: This attribute is passed up as part of the register_thing method and # will be validated in your lambda's event data. # ------------------------------------------------------------------------------ if not os.path.exists(self.claim_cert): self.error = '### Bootstrap cert non-existent. Official cert may already be in place.' else: self.hasValidAccount = True self.primary_MQTTClient = AWSIoTMQTTClient( "fleet_provisioning_demo") self.primary_MQTTClient.onMessage = self.on_message_callback self.callback_returned = False self.message_payload = {} def certFullPath(self, cert): return "{}/{}".format(self.secure_cert_path, cert) def core_connect(self): """ Method used to connect to connect to AWS IoTCore Service. Endpoint collected from config. """ self.primary_MQTTClient.configureEndpoint(self.iot_endpoint, 8883) self.primary_MQTTClient.configureCredentials(self.root_cert, self.secure_key, self.claim_cert) self.primary_MQTTClient.configureOfflinePublishQueueing(-1) self.primary_MQTTClient.configureDrainingFrequency(2) self.primary_MQTTClient.configureConnectDisconnectTimeout(10) self.primary_MQTTClient.configureMQTTOperationTimeout(3) self.logger.info('##### CONNECTING WITH PROVISIONING CLAIM CERT #####') print('##### CONNECTING WITH PROVISIONING CLAIM CERT #####') self.primary_MQTTClient.connect() def enable_error_monitor(self): """ Subscribe to pertinent IoTCore topics that would emit errors """ self.primary_MQTTClient.subscribe( "$aws/provisioning-templates/{}/provision/json/rejected".format( self.template_name), 1, callback=self.basic_callback) self.primary_MQTTClient.subscribe( "$aws/certificates/create/json/rejected", 1, callback=self.basic_callback) def get_official_certs(self, callback): """ Initiates an async loop/call to kick off the provisioning flow. Triggers: on_message_callback() providing the certificate payload """ return asyncio.run(self.orchestrate_provisioning_flow(callback)) async def orchestrate_provisioning_flow(self, callback): # Connect to core with provision claim creds self.core_connect() # Monitor topics for errors self.enable_error_monitor() # Make a publish call to topic to get official certs self.primary_MQTTClient.publish("$aws/certificates/create/json", "{}", 0) # Wait the function return until all callbacks have returned # Returned denoted when callback flag is set in this class. while not self.callback_returned: await asyncio.sleep(0) return callback(self.message_payload) def on_message_callback(self, message): """ Callback Message handler responsible for workflow routing of msg responses from provisioning services. Arguments: message {string} -- The response message payload. """ json_data = json.loads(message.payload) # A response has been recieved from the service that contains certificate data. if 'certificateId' in json_data: self.logger.info('##### SUCCESS. SAVING KEYS TO DEVICE! #####') print('##### SUCCESS. SAVING KEYS TO DEVICE! #####') self.assemble_certificates(json_data) # A response contains acknowledgement that the provisioning template has been acted upon. elif 'deviceConfiguration' in json_data: self.logger.info( '##### CERT ACTIVATED AND THING {} CREATED #####'.format( json_data['thingName'])) print('##### CERT ACTIVATED AND THING {} CREATED #####'.format( json_data['thingName'])) self.rotate_certs() else: self.logger.info(json_data) def assemble_certificates(self, payload): """ Method takes the payload and constructs/saves the certificate and private key. Method uses existing AWS IoT Core naming convention. Arguments: payload {string} -- Certifiable certificate/key data. Returns: ownership_token {string} -- proof of ownership from certificate issuance activity. """ # Cert ID cert_id = payload['certificateId'] self.new_key_root = cert_id[0:10] self.new_cert_name = '{}-certificate.pem.crt'.format(self.new_key_root) # Create certificate f = open('{}/{}'.format(self.secure_cert_path, self.new_cert_name), 'w+') f.write(payload['certificatePem']) f.close() # Create private key self.new_key_name = '{}-private.pem.key'.format(self.new_key_root) f = open('{}/{}'.format(self.secure_cert_path, self.new_key_name), 'w+') f.write(payload['privateKey']) f.close() # Extract/return Ownership token self.ownership_token = payload['certificateOwnershipToken'] # register newly aquired cert self.register_thing(self.serial_num, self.ownership_token) def register_thing(self, serial, token): """Calls the fleet provisioning service responsible for acting upon instructions within device templates. Arguments: serial {string} -- unique identifer for the thing. Specified as a property in provisioning template. token {string} -- The token response from certificate creation to prove ownership/immediate possession of the certs. Triggers: on_message_callback() - providing acknowledgement that the provisioning template was processed. """ self.logger.info('##### CREATING THING ACTIVATING CERT #####') print('##### CREATING THING ACTIVATING CERT #####') register_template = { "certificateOwnershipToken": token, "parameters": { "SerialNumber": self.serial_num, "ModelType": self.model_type, "hasValidAccount": self.hasValidAccount } } # Register thing / activate certificate self.primary_MQTTClient.publish( "$aws/provisioning-templates/{}/provision/json".format( self.template_name), json.dumps(register_template), 0) def rotate_certs(self): """Responsible for (re)connecting to IoTCore with the newly provisioned/activated certificate - (first class citizen cert) """ self.logger.info('##### CONNECTING WITH OFFICIAL CERT #####') print('##### CONNECTING WITH OFFICIAL CERT #####') self.cert_validation_test() self.new_cert_pub_sub() print("##### ACTIVATED AND TESTED CREDENTIALS ({}, {}). #####".format( self.new_key_name, self.new_cert_name)) print("##### FILES SAVED TO {} #####".format(self.secure_cert_path)) self.remove_bootstrap_certs() print("##### REMOVED BOOTSTRAP CREDENTIALS #####".format( self.secure_cert_path)) def cert_validation_test(self): self.test_MQTTClient = AWSIoTMQTTClient(self.serial_num) self.test_MQTTClient.configureEndpoint(self.iot_endpoint, 8883) self.test_MQTTClient.configureCredentials( self.root_cert, self.certFullPath(self.new_key_name), self.certFullPath(self.new_cert_name)) # Infinite offline Publish queueing self.test_MQTTClient.configureOfflinePublishQueueing(-1) self.test_MQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz self.test_MQTTClient.configureConnectDisconnectTimeout(10) # 10 sec self.test_MQTTClient.configureMQTTOperationTimeout(3) # 5 sec self.test_MQTTClient.connect() def basic_callback(self, client, userdata, msg): """Method responding to the openworld publish attempt. Demonstrating a successful pub/sub with new certificate. """ self.logger.info(msg.payload.decode()) self.message_payload = msg.payload.decode() self.callback_returned = True def new_cert_pub_sub(self): """Method testing a call to the 'openworld' topic (which was specified in the policy for the new certificate) """ self.test_MQTTClient.subscribe("dt/{}/test".format(self.serial_num), 1, self.basic_callback) self.test_MQTTClient.publish( "dt/{}/test".format(self.serial_num), str({ "service_response": "##### YOUR INDIVIDUALIZED PRODUCTION CERTS HAVE BEEN SUCCESSFULLY ACTIVATED AND ADDED TO THE /certs FOLDER #####" }), 0) def remove_bootstrap_certs(self): try: os.remove("{}/bootstrap-private.pem.key".format( self.secure_cert_path)) os.remove("{}/bootstrap-certificate.pem.crt".format( self.secure_cert_path)) except OSError: pass
# Broker path is under AWS IoT > Settings (at the bottom left) BROKER_PATH = "YOUR_BROKER_PATH" # RSA 2048 bit key: Amazon Root CA 1 found here: # https://docs.aws.amazon.com/iot/latest/developerguide/managing-device-certs.html ROOT_CA_PATH = './AmazonRootCA1.pem' PRIVATE_KEY_PATH = './YOUR_CERT-private.pem.key' CERTIFICATE_PATH = './YOUR_CERT-certificate.pem.crt' IoTclient = AWSIoTMQTTClient(CLIENT_NAME) IoTclient.configureEndpoint(BROKER_PATH, 8883) IoTclient.configureCredentials(ROOT_CA_PATH, PRIVATE_KEY_PATH, CERTIFICATE_PATH) # Allow the device to queue infinite messages IoTclient.configureOfflinePublishQueueing(-1) # Number of messages to send after a connection returns IoTclient.configureDrainingFrequency(2) # 2 requests/second # How long to wait for a [dis]connection to complete (in seconds) IoTclient.configureConnectDisconnectTimeout(10) # How long to wait for publish/[un]subscribe (in seconds) IoTclient.configureMQTTOperationTimeout(5) IoTclient.connect() IoTclient.publish(TOPIC, "connected", 0) with open('sensor-data.csv', newline='') as csvfile: csv.reader(csvfile, delimiter=',', quotechar='"')
class Client: client = None def __init__(self, client_id, end_point, root_ca, private_key, certificate): """ :param client_id: :param end_point: :param root_ca: :param private_key: :param certificate: """ self.client = AWSIoTMQTTClient(client_id) self.client.configureEndpoint(end_point, 8883) self.client.configureCredentials(root_ca, private_key, certificate) self.client.configureAutoReconnectBackoffTime(2, 32, 20) self.client.configureOfflinePublishQueueing(-1) self.client.configureDrainingFrequency(2) self.client.configureConnectDisconnectTimeout(10) self.client.configureMQTTOperationTimeout(5) def connect(self): """ 接続処理 :return: 結果(True:成功、False:失敗) """ return self.client.connect() def publish(self, topic, payload): """ Publish処理 :param topic: トピック名 :param payload: 送信データ :return: 結果(True:成功、False:失敗) """ return self.client.publish(topic, payload, 1) def subscribe(self, topic, cb): """ Subscribe処理 :param topic: トピック名 :param cb: コールバック関数 :return: 結果(True:成功、False:失敗) """ return self.client.subscribe(topic, 1, cb) def unsubscribe(self, topic): """ Unsubscribe処理 :param topic: トピック名 :return: 結果(True:成功、False:失敗) """ return self.client.unsubscribe(topic) def disconnect(self): """ 切断処理 :return: 結果(True:成功、False:失敗) """ return self.client.disconnect()
#Create an accelerometer object try: bridge = Bridge() except RuntimeError as e: print("Runtime Exception: %s" % e.details) print("Exiting....") exit(1) #Connect to the cloud myMQTTClient = AWSIoTMQTTClient(client) myMQTTClient.configureEndpoint("ap6thgx18rs03.iot.us-west-2.amazonaws.com", 8883) myMQTTClient.configureCredentials(path+'CA.pem' , path+'edadfb6205-private.pem.key', path+'edadfb6205-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 time.sleep(2) #wait for 2 secs deviceNames = ['Ruche01', 'Ruche02', 'Ruche03', 'Ruche04', 'Ruche05'] temperatureDeviceNames = ['Matrice01', 'Matice02', 'Matrice03', 'Matrice04', 'Matrice05'] #Matrice = la valeur moyenne de la température entre les 2 cadres connecting_time = time.time() + 10 if time.time() < connecting_time: #try connecting to AWS for 10 seconds myMQTTClient.connect() myMQTTClient.publish(topic, "connected", 0)
) #Configura el puerto 27 como de entrada con estado inicial de alto voltaje global count #Crea una variable global llamada count para el conteo de los pulsos enviados por el sensor count = 0 #Inicializa la variable en Cero (0) # AWS IoT certificate based connection myMQTTClient = AWSIoTMQTTClient( "123afhlss456") #Crear un nombre para el cliente MQTT myMQTTClient.configureEndpoint("a3cmxruztsldcp.iot.us-west-2.amazonaws.com", 8883) #Punto de enlace de API REST myMQTTClient.configureCredentials( "/home/pi/AWS_Certs/root_ca.pem", "/home/pi/AWS_Certs/cloud-private.pem.key", "/home/pi/AWS_Certs/cloud-certificate.pem.crt" ) #Indica la ubicacion de los certificados digitales necesarios para la autenticacion del dispositivo myMQTTClient.configureOfflinePublishQueueing( -1) # Define una cola de "Publish" infinita myMQTTClient.configureDrainingFrequency(2) # 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec #connect and publish myMQTTClient.connect() #Metodo de conexion del cliente MQTT hacia el Broker myMQTTClient.publish("thing/info", "connected", 0) def countPulse( channel): #Metodo para el conteo de pulsos enviados por el sensor global count if start_counter == 1: count = count + 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
class MqttManager: def __init__(self): """ Constructor for Mqtt Manager, create logger, connect to AWS mqtt client and grab the list of IoT devices that are available :param self: """ self.awsDeviceList = [] """This of aws profiles of the supported IoT devices, used during discovery request to advertise available devices""" self.iotObjList = iot_object.IOT_OBJ_LIST """List of IoT mcu that this backend can talk to to fulfill Alexa request, it will also advertise this list to Alexa using Discovery Directives""" self.createLogger() self.createAWSClient() def createLogger(self): """ Create a logger to log mqtt messages :param self: instance of MqttManager """ # Configure logging self._logger = logging.getLogger("AWSIoTPythonSDK.core") self._logger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) self._logger.addHandler(streamHandler) def createAWSClient(self): """ Connect to AWS mqtt server using credentials included with the lambda deployment package, most settings are stored in the mqtt_constant module :param self: instance of MqttManager """ # configure AWS client with credentials and connection info with open(mqtt_constant.ENDPT_FILE_PATH, 'r') as idFile: iotID = idFile.read().replace('\n', '') self._myAWSIoTMQTTClient = None self._myAWSIoTMQTTClient = AWSIoTMQTTClient(mqtt_constant.CLIENT_ID) self._myAWSIoTMQTTClient.configureEndpoint( iotID + mqtt_constant.AWS_ENDPOINT, mqtt_constant.MQTT_PORT) self._myAWSIoTMQTTClient.configureCredentials( mqtt_constant.AUTHORITY_CERT_PATH, mqtt_constant.PRIVATE_KEY_PATH, mqtt_constant.CERTIFICATE_PATH) # AWSIoTMQTTClient connection configuration self._myAWSIoTMQTTClient.configureAutoReconnectBackoffTime( mqtt_constant.INITIAL_BACKOFF_TIME, mqtt_constant.MAX_BACKOFF_TIME, mqtt_constant.STABLE_TIME) self._myAWSIoTMQTTClient.configureOfflinePublishQueueing( mqtt_constant.OFFLINE_PUB_QUEUE, DROP_OLDEST) self._myAWSIoTMQTTClient.configureDrainingFrequency( mqtt_constant.DRAINING_FREQ) self._myAWSIoTMQTTClient.configureConnectDisconnectTimeout( mqtt_constant.CONNECT_DISCONNECT_TIMEOUT) # 10 sec self._myAWSIoTMQTTClient.configureMQTTOperationTimeout( mqtt_constant.OPERATION_TIMEOUT) while False == self._myAWSIoTMQTTClient.connect(mqtt_constant.KEEP_ALIVE_SECONDS): pass # AWS subscription configuration for iotObject in iot_object.IOT_OBJ_LIST: self._myAWSIoTMQTTClient.subscribe( iotObject.pubTopic, mqtt_constant.SUB_QOS, lambda_master_handler.MasterHandler.subCallBack) self.awsDeviceList.append(iotObject.awsObjectProfile) def mqttPub(self, package, pubTopic): """ Publish the given package to the supplied mqtt topic :param self: instance of MqttManager :param package: json dict to be published :param pubTopic: topic to publish to """ message = {} # check if we are in debug mode, if not, proceed normally if "Alexa.Debug" == package["namespace"]: message["properties"] = [] message["properties"].append(package) else: message = package messageJson = json.dumps(message) self._myAWSIoTMQTTClient.publish( pubTopic, messageJson, mqtt_constant.PUB_QOS)
# -*- 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 security_gateway: def __init__(self, deviceId, endpoint, rootCAPath, privateKeyPath, certificatePath): # Configure logging self.logger = logging.getLogger("AWSIoTPythonSDK.core") self.logger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) self.logger.addHandler(streamHandler) self.reported = {} self.reported['owner'] = "none" self.reported['status'] = "inactive" self.reported['mode'] = "none" self.desired = None self.delta = None self.__initIotClient(deviceId, endpoint, rootCAPath, privateKeyPath, certificatePath) def __initIotClient(self, devieId, endpoint, rootCAPath, privateKeyPath, certificatePath): # Init AWSIoTMQTTClient self.iot_client = None self.client_id=str(deviceId) self.iot_client = AWSIoTMQTTClient(self.client_id) self.iot_client.configureEndpoint(endpoint, 8883) self.iot_client.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration self.iot_client.configureAutoReconnectBackoffTime(1, 128, 20) self.iot_client.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing self.iot_client.configureDrainingFrequency(2) # Draining: 2 Hz self.iot_client.configureConnectDisconnectTimeout(10) # 10 sec self.iot_client.configureMQTTOperationTimeout(30) # 30 sec self.update_topic = "$aws/things/" + self.client_id + "/shadow/update" self.get_topic = "$aws/things/" + self.client_id + "/shadow/get" self.client_state = "INIT" self.logger.info(self.client_state) def connect(self): # Connect and subscribe to AWS IoT self.client_state = "CONNECT" self.logger.info(self.client_state) self.logger.info(self.client_id) self.iot_client.connect() time.sleep(2) update_accepted_topic="$aws/things/" + self.client_id + "/shadow/update/accepted" update_rejected_topic="$aws/things/" + self.client_id + "/shadow/update/rejected" get_accepted_topic="$aws/things/" + self.client_id + "/shadow/get/accepted" get_rejected_topic="$aws/things/" + self.client_id + "/shadow/get/rejected" update_delta_topic="$aws/things/" + self.client_id + "/shadow/update/delta" update_documents_topic="$aws/things/" + self.client_id + "/shadow/update/documents" self.iot_client.subscribe(update_documents_topic, 1, self.updateDocumentsCallback) self.iot_client.subscribe(update_delta_topic, 1, self.updateDeltaCallback) self.iot_client.subscribe(update_rejected_topic, 1, self.updateRejectedCallback) self.iot_client.subscribe(update_accepted_topic, 1, self.updateAcceptedCallback) self.iot_client.subscribe(get_rejected_topic, 1, self.getRejectedCallback) self.iot_client.subscribe(get_accepted_topic, 1, self.getAcceptedCallback) def getState(self): self.client_state = "GET_PENDING" self.logger.info(self.client_state) self.iot_client.publish(self.get_topic, "", 1) def reportState(self): msg = {} state={} state['reported']=self.reported msg['state']=state json_msg = json.dumps(msg) self.client_state = "UPDATE_PENDING" self.logger.info(self.client_state) self.logger.info(json_msg) self.iot_client.publish(self.update_topic, json_msg, 1) def load_msg(self, message): # older versions of python json does not load bytes if isinstance(message, bytes): message = message.decode('utf-8') return json.loads(message) def updateDeltaCallback(self, client, userdata, message): try: msg=message.payload self.handleUpdateDeltaMessage(msg) self.client_state = "DELTA" self.logger.info(self.client_state) except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=20, file=sys.stdout) def updateDocumentsCallback(self, client, userdata, message): try: msg=message.payload self.handleUpdateDocumentsMessage(msg) except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=20, file=sys.stdout) def getRejectedCallback(self, client, userdata, message): try: msg=message.payload self.handleGetRejectedMessage(msg) if self.client_state == "GET_PENDING": self.client_state = "GET_REJECTED" self.logger.info(self.client_state) except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=20, file=sys.stdout) def getAcceptedCallback(self, client, userdata, message): try: msg=message.payload self.handleGetAcceptedMessage(msg) if self.client_state == "GET_PENDING": self.client_state = "GET_ACCEPTED" self.logger.info(self.client_state) except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=20, file=sys.stdout) def updateRejectedCallback(self, client, userdata, message): try: msg=message.payload self.handleUpdateRejectedMessage(msg) if self.client_state == "UPDATE_PENDING": self.client_state = "UPDATE_REJECTED" self.logger.info(self.client_state) except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=20, file=sys.stdout) def updateAcceptedCallback(self, client, userdata, message): try: msg=message.payload self.handleUpdateAcceptedMessage(msg) if self.client_state == "UPDATE_PENDING": self.client_state = "UPDATE_ACCEPTED" self.logger.info(self.client_state) except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=20, file=sys.stdout) def getAttrValue(self, dict, key): value = None try: value = dict[key] except KeyError: pass return value def handleUpdateRejectedMessage(self, message): self.logger.info("Enter handleUpdateRejectedMessage") try: msg=self.load_msg(message) self.logger.info(msg) except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=20, file=sys.stdout) finally: self.logger.info("Exit handleUpdateRejectedMessage") def handleUpdateAcceptedMessage(self, message): self.logger.info("Enter handleUpdateAcceptedMessage") try: msg=self.load_msg(message) self.logger.info(msg) except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=20, file=sys.stdout) finally: self.logger.info("Exit handleUpdateAcceptedMessage") def handleGetRejectedMessage(self, message): self.logger.info("Enter handleGetRejectedMessage") try: self.logger.info(self.client_state) msg=self.load_msg(message) self.logger.info(msg) if msg['code'] == 404: self.reportState() except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=20, file=sys.stdout) finally: self.logger.info("Exit handleGetRejectedMessage") def handleGetAcceptedMessage(self, message): self.logger.info("Enter handleGetAcceptedMessage") try: msg=self.load_msg(message) state = msg['state'] self.reported = self.getAttrValue(state, "reported") self.desired = self.getAttrValue(state, "desired") self.delta = self.getAttrValue(state, "delta") except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=20, file=sys.stdout) finally: self.logger.info("Exit handleGetAcceptedMessage") def handleUpdateDocumentsMessage(self, message): self.logger.info("Enter handleUpdateDocumentsMessage") try: self.logger.info(self.client_state) msg=self.load_msg(message) self.logger.info( msg) current = msg["current"] state = current["state"] self.reported = self.getAttrValue(state, "reported") self.desired = self.getAttrValue(state, "desired") except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=20, file=sys.stdout) finally: self.logger.info("Exit handleUpdateDocumentsMessage") def handleUpdateDeltaMessage(self, message): self.logger.info("Enter handleUpdateDeltaMessage") try: self.logger.info(self.client_state) msg=self.load_msg(message) self.logger.info(msg) self.delta = msg['state'] self.logger.info(self.delta) except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=20, file=sys.stdout) finally: self.logger.info("Exit handleUpdateDeltaMessage") def processDelta(self): self.logger.info("Enter processDelta") try: if self.delta: if self.reported: for key in self.delta: self.reported[key] = self.delta[key] else: self.reported = self.delta self.reportState() else: self.logger.info("No delta to apply") self.client_state = "SYNCED" self.logger.info(self.client_state) self.logger.info("Exit processDelta") except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=20, file=sys.stdout) finally: self.logger.info("Exit handleUpdateDeltaMessage") def doSecurityChecks(self): # dummy sleep time.sleep(2) def start(self): self.connect() self.getState() while self.client_state != "GET_ACCEPTED": time.sleep(2) self.processDelta() while True: self.doSecurityChecks() if self.client_state == "DELTA": self.processDelta()
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, 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 = {}
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, endpoint, credentials): # client... self.__client = AWSIoTMQTTClient(credentials.name) # configuration... self.__client.configureEndpoint(endpoint.endpoint_host, self.__PORT) self.__client.configureCredentials(credentials.root_ca_file_path, credentials.private_key_path, credentials.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