class Subscriber(threading.Thread): """A threaded Subscriber object""" def __init__(self, endpoint, root_ca, key, cert, client_id=''): threading.Thread.__init__(self) self.endpoint = endpoint self.client_id = client_id self.root_ca = root_ca self.key = key self.cert = cert self._client = None self.finish = False self.daemon = True self.connected = False def connect(self): self._client = AWSIoTMQTTClient(self.client_id) self._client.configureEndpoint(self.endpoint, 8883) self._client.configureCredentials(self.root_ca, self.key, self.cert) self._client.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing self._client.configureConnectDisconnectTimeout(10) # 10 sec self._client.configureMQTTOperationTimeout(5) # 5 sec self.connected = self._client.connect() def subscribe(self, topic, callback, qos=1): if not self.connected: self.connect() self._client.subscribe(topic, qos, callback) def run(self): while not self.finish: time.sleep(0.001)
class Client(): def __init__(self, iot_client=None, iot_data_client=None, credentials=None, ca_path=None, privkey_path=None, cert_path=None): assert ca_path, "Certificate is required" if not iot_client: iot_client = boto3.client('iot') if not iot_data_client: iot_data_client = boto3.client('iot-data') self.iot_client = iot_client self.iot_data_client = iot_data_client self.cert_path = cert_path self.privkey_path = privkey_path self.ca_path = ca_path self.credentials = credentials self.init_mqtt_client() def init_mqtt_client(self): endpoint = self.iot_client.describe_endpoint() use_websocket = True if self.credentials else False endpoint_port = 443 if use_websocket else 8883 self.mqtt_client = AWSIoTMQTTClient("testo", useWebsocket=use_websocket) self.mqtt_client.configureEndpoint(endpoint['endpointAddress'], endpoint_port) self.mqtt_client.configureOfflinePublishQueueing(-1) self.mqtt_client.configureConnectDisconnectTimeout(10) self.mqtt_client.configureMQTTOperationTimeout(10) self.configure_credentials() log.debug("OpenSSL version {}".format(ssl.OPENSSL_VERSION)) log.debug("Connecting MQTT client to {} on port {}...".format(endpoint['endpointAddress'], endpoint_port)) try: self.mqtt_client.connect() log.debug("MQTT client connected") except connectTimeoutException: log.error("Failed to connect MQTT client - timeout (check policy)") self.mqtt_client = None def configure_credentials(self): if self.credentials: self.mqtt_client.configureIAMCredentials(*(self.credentials.values())) self.mqtt_client.configureCredentials(self.ca_path) elif self.privkey_path and self.cert_path: log.debug("Using %s %s %s", str(self.ca_path), str(self.privkey_path), str(self.cert_path)) self.mqtt_client.configureCredentials(self.ca_path, self.privkey_path, self.cert_path) else: raise Exception("No credentials found")
class 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 IoTClientWrapper(object): """ Wrapper around the AWS Iot Python SDK. Sets common parameters based on the AWS Iot Python SDK's `Basic PubSub`_ sample. .. _Basic PubSub: 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, useWebsocket=True) self.iot_client.configureEndpoint(self.host, 443) 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)
# Hook the SIGINT signal.signal(signal.SIGINT, end_read) # Create an object of the class MFRC522 mfrc522 = MFRC522.MFRC522() lcd = LCD() 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("sensors/parkingdb", 1, customCallback) dynamodb = boto3.resource( 'dynamodb', aws_access_key_id="XXXXXXXXXXXXXXXXXXXX", aws_secret_access_key="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", region_name='us-west-2') # =================================================================== # Main # =================================================================== if __name__ == "__main__":
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)
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
def main(): # AWS IoT Credentials hostEndpoint = "xxxxxxxxxxxxx.iot.us-west-2.amazonaws.com" rootCAPath = "../../cert/VeriSign-Class 3-Public-Primary-Certification-Authority-G5.pem" certificatePath = "../../cert/73d79ad78b-certificate.pem.crt" privateKeyPath = "../../cert/73d79ad78b-private.pem.key" clientId = "python-client-master" mqttPort = 8883 # Subscribed Topics sub_topic_green_led = "secure/led/green/status" sub_topic_blue_led = "secure/led/blue/status" sub_topic_red_led = "secure/led/red/status" # AWS IoT MQTT Broker prepare login esp32AWSIoTMQTTClient = AWSIoTMQTTClient(clientId) esp32AWSIoTMQTTClient.configureEndpoint(hostEndpoint, mqttPort) esp32AWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # 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) # AWSIoTMQTTClient connection configuration esp32AWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) esp32AWSIoTMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing esp32AWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz esp32AWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec esp32AWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect to AWS IoT MQTT Broker if esp32AWSIoTMQTTClient.connect() == True: print("\n " + clientId + " successfully connected to " + hostEndpoint) else: print(" " + clientId + " failed to connect to " + hostEndpoint) exit(2) # Subscribe to topic green led commands if esp32AWSIoTMQTTClient.subscribe(sub_topic_green_led, 1, subscribeCallback) == True: print("\n " + clientId + " successfully subscribed to topic " + sub_topic_green_led) else: print("\n " + clientId + " failed to subscribed to topic " + sub_topic_green_led) exit(2) # Subscribe to topic blue led commands if esp32AWSIoTMQTTClient.subscribe(sub_topic_blue_led, 1, subscribeCallback) == True: print("\n " + clientId + " successfully subscribed to topic " + sub_topic_blue_led) else: print("\n " + clientId + " failed to subscribed to topic " + sub_topic_blue_led) exit(2) # Subscribe to topic red led commands if esp32AWSIoTMQTTClient.subscribe(sub_topic_red_led, 1, subscribeCallback) == True: print("\n " + clientId + " successfully subscribed to topic " + sub_topic_red_led) else: print("\n " + clientId + " failed to subscribed to topic " + sub_topic_red_led) exit(2) # sleep forever blockForever()
myAWSIoTMQTTClient = None if useWebsocket: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True) myAWSIoTMQTTClient.configureEndpoint(host, 443) myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) 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(300) # 5 mins myAWSIoTMQTTClient.configureMQTTOperationTimeout(120) # 2 mins # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect() myAWSIoTMQTTClient.subscribe(topic, 1, customCallback) time.sleep(2) ################################################################################################ # Publish to the same topic in a loop forever def main(): # Set initial sampling time for the temperature sensors sensorSamplingRate = set_sampling_time() print(sensorSamplingRate)
def simulationAWS(connection, deviceName, frequency, timeInterval, minRange, maxRange): # from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient from pathlib import Path import logging import time import argparse import json import random import os AllowedActions = ['both', 'publish', 'subscribe'] # Custom MQTT message callback # deviceName = "awsDevice" # frequency = 1 # timeInterval = 5 # minRange = 10 # maxRange = 100 def customCallback(client, userdata, message): print("Received a new message: ") print(message.payload) print("from topic: ") print(message.topic) print("--------------\n\n") parser = argparse.ArgumentParser() host = connection["endpoint"] rootCAPath = Path("static/certificates/" + deviceName + "/root-CA.crt") certificatePath = Path("static/certificates/" + deviceName + "/" + deviceName + ".cert.pem") privateKeyPath = Path("static/certificates/" + deviceName + "/" + deviceName + ".private.key") print(os.getcwd()) port = None useWebsocket = False clientId = "simulator" topic = connection["topic"] 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) print( "Coming here ..................................................................0" ) # 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) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) 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 mode == 'both' or mode == 'subscribe': myAWSIoTMQTTClient.subscribe(topic, 1, customCallback) time.sleep(2) # Publish to the same topic in a loop forever def valueGen(): a = random.randint(minRange, maxRange) return a loopCount = 0 while loopCount < frequency: if mode == 'both' or mode == 'publish': message = {} value = valueGen() message['value'] = value messageJson = json.dumps(message) myAWSIoTMQTTClient.publish(topic, messageJson, 1) if mode == 'publish': print('Published topic %s: %s\n' % (topic, messageJson)) loopCount += 1 time.sleep(timeInterval)
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient from Drive import * endpoint = os.environ['AWS_IOT_ENDPOINT'] # Set this up in your bash profile # See https://github.com/aws/aws-iot-device-sdk-python/blob/master/samples/basicPubSub/basicPubSub.py createMQTTClient = AWSIoTMQTTClient("TwitchRobotRaspberryPi") createMQTTClient.configureEndpoint(endpoint, 443) createMQTTClient.configureCredentials("/home/pi/TwitchRobot/certs/AmazonRootCA1.crt", "/home/pi/TwitchRobot/certs/TwitchRobot.private.key", "/home/pi/TwitchRobot/certs/TwitchRobot.cert.pem") createMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing createMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz createMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec createMQTTClient.configureMQTTOperationTimeout(5) # 5 sec createMQTTClient.connect() # Initialize the node rospy.init_node('alexa', anonymous=True) drive = Drive() def unsubscribe_topics(): """Unbsubscribes from AWS IoT topics before exiting """ topics = [ '/voice/drive' ] for topic in topics: createMQTTClient.unsubscribe(topic)
if __name__ == '__main__': LOG = setup_logging('door_monitor', logging.INFO) MQTT_LOG = setup_logging('AWSIoTPythonSDK.core', logging.INFO) CLIENT_ID = 'garage_door_opener' ENDPOINT = 'ad4bgf9zw53fx-ats.iot.us-east-1.amazonaws.com' CA_FILE_PATH = '/opt/aws/iot/root-CA.crt' PRIVATE_KEY_PATH = '/opt/aws/iot/garage_door_opener.private.key' CERTIFICATE_PATH = '/opt/aws/iot/garage_door_opener.cert.pem' MQTT_CLIENT = AWSIoTMQTTClient(CLIENT_ID) MQTT_CLIENT.configureEndpoint(ENDPOINT, 8883) MQTT_CLIENT.configureCredentials(CA_FILE_PATH, PRIVATE_KEY_PATH, CERTIFICATE_PATH) MQTT_CLIENT.configureAutoReconnectBackoffTime(1, 32, 20) MQTT_CLIENT.configureOfflinePublishQueueing(-1) MQTT_CLIENT.configureDrainingFrequency(2) MQTT_CLIENT.configureConnectDisconnectTimeout(10) MQTT_CLIENT.configureMQTTOperationTimeout(5) LOG.debug('CONNECT: CAFilePath: %s KeyPath: %s CertificatePath: %s', CA_FILE_PATH, PRIVATE_KEY_PATH, CERTIFICATE_PATH) MQTT_CLIENT.connect() try: print('STARTING DOOR MONITOR') DOOR = Door() while True: time.sleep(60) finally: LOG.info('EXITING, CLEANING UP')
class MQTTClient(object): """ classdocs """ __PORT = 8883 __QUEUE_SIZE = -1 # recommended: infinite __QUEUE_DROP_BEHAVIOUR = MQTTLib.DROP_OLDEST # not required for infinite queue __QUEUE_DRAINING_FREQUENCY = 1 # recommended: 2 (Hz) __RECONN_BASE = 1 # recommended: 1 (sec) __RECONN_MAX = 32 # recommended: 32 (sec) __RECONN_STABLE = 20 # recommended: 20 (sec) __DISCONNECT_TIMEOUT = 30 # recommended: 10 (sec) __OPERATION_TIMEOUT = 30 # recommended: 5 (sec) __PUB_QOS = 1 __SUB_QOS = 1 # ---------------------------------------------------------------------------------------------------------------- def __init__(self, *subscribers): """ Constructor """ self.__client = None self.__subscribers = subscribers # ---------------------------------------------------------------------------------------------------------------- def connect(self, auth): # client... self.__client = AWSIoTMQTTClient(auth.client_id) # configuration... self.__client.configureEndpoint(auth.endpoint, self.__PORT) self.__client.configureCredentials(auth.root_ca_file_path, auth.private_key_path, auth.certificate_path) self.__client.configureAutoReconnectBackoffTime(self.__RECONN_BASE, self.__RECONN_MAX, self.__RECONN_STABLE) self.__client.configureOfflinePublishQueueing(self.__QUEUE_SIZE) self.__client.configureDrainingFrequency(self.__QUEUE_DRAINING_FREQUENCY) self.__client.configureConnectDisconnectTimeout(self.__DISCONNECT_TIMEOUT) self.__client.configureMQTTOperationTimeout(self.__OPERATION_TIMEOUT) # subscriptions... for subscriber in self.__subscribers: self.__client.subscribe(subscriber.topic, self.__SUB_QOS, subscriber.handler) # connect... self.__client.connect() def disconnect(self): self.__client.disconnect() # ---------------------------------------------------------------------------------------------------------------- def publish(self, publication): payload = JSONify.dumps(publication.payload) self.__client.publish(publication.topic, payload, self.__PUB_QOS) # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): subscribers = '[' + ', '.join(str(subscriber) for subscriber in self.__subscribers) + ']' return "MQTTClient:{subscribers:%s}" % subscribers
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)
# -*- 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 Main(QDialog): def __init__(self): super(Main, self).__init__() #integrating the UI self.ui = Ui_SensorInterface() self.ui.setupUi(self) #MQTT setup self.mqttSetup() #global variables global unit, count, tempAvg, humAvg, samples, tempArr, humArr, timerflag, tempLimit, humLimit, tempHigh, tempLow, humHigh, humLow, temp, connection, crsr unit = 1 count, tempAvg, humAvg, samples, timerflag, tempHigh, humHigh = 0, 0, 0, 0, 0, 0, 0 tempLow, humLow = 500, 500 tempArr = [None] * 10 humArr = [None] * 10 tempLimit = 100 humLimit = 100 #initialize database connection = sqlite3.connect("localdht.db") crsr = connection.cursor() #initializing timer self.timer = QtCore.QTimer(self) self.timer.setInterval(5000) self.timer.timeout.connect(self.getTempHum) self.ui.refreshButton.clicked.connect(self.getTempHum) self.ui.celciusButton.clicked.connect(self.celciusTemp) self.ui.fahrenheitButton.clicked.connect(self.fahrenheitTemp) self.ui.timerButton.clicked.connect(self.timerStartStop) self.ui.resetButton.clicked.connect(self.resetAvg) self.ui.graphButton.clicked.connect(self.graphTempHum) self.ui.tempDial.valueChanged.connect(self.setTempLimit) self.ui.humDial.valueChanged.connect(self.setHumLimit) self.ui.cleardatabaseButton.clicked.connect(self.clearDB) #function to setup MQTT using REST API and private and root keys def mqttSetup(self): self.myAWSIoTMQTTClient = AWSIoTMQTTClient("RaspberryPi") self.myAWSIoTMQTTClient.configureEndpoint( "a1mtqpdqvd0l8h-ats.iot.us-east-1.amazonaws.com", 8883) self.myAWSIoTMQTTClient.configureCredentials("root-CA.crt", "pi-private.pem.key", "pi-certificate.pem.crt") 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("DHT22", 1, None) #function to get temp and humidity from the sensor def getTempHum(self): global unit, count, tempAvg, humAvg, tempHigh, tempLow, humHigh, humLow, tempArr, humArr, samples, tempLimit, humLimit, temp, connection, crsr, timerflag humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 4) global temp3, temp4, hum3, hum4 #create table crsr.execute( "CREATE TABLE IF NOT EXISTS DHT_DATA(Timestamp TEXT,Temperature numeric(3,1),Unit TEXT,Average_Temperature numeric(3,1),High_Temperature numeric(3,1),Low_Temperature numeric(3,1),Humidity numeric(3,1),Average_Humidity numeric(3,1),High_Humidity numeric(3,1),Low_Humidity numeric(3,1))" ) #check if sensor is disconnected if humidity is None and temperature is None: self.ui.alertDisplay.setText(" SENSOR DISCONNECTED") self.ui.temperatureDisplay.display("") self.ui.humidityDisplay.display("") self.ui.temperatureAvgDisplay.display("") self.ui.humidityAvgDisplay.display("") self.ui.sensorStatus.setStyleSheet( "background-color: rgb(255, 0, 0);") #update the time of request for tem and humidity values newtime = time.strftime('%m-%d-%y %H:%M:%S') self.ui.timeDisplay.setText(newtime) temp1, tempUnit, temp2, temp3, temp4, hum1, hum2, hum3, hum4time = 0, 0, 0, 0, 0, 0, 0, 0, 0 #update database crsr.execute("INSERT INTO dht_data values(?,?,?,?,?,?,?,?,?,?)", (newtime, temp1, tempUnit, temp2, temp3, temp4, hum1, hum2, hum3, hum4)) connection.commit() else: self.ui.sensorStatus.setStyleSheet( "background-color: rgb(0, 255, 0);") count = count + 1 tempA = '{0:.2f}'.format(temperature) tempUnit = "°C" #conversion from cecius to fahrenheit if unit == 0: temperature = (temperature * 1.8) + 32 tempUnit = "°F" #display current temp and humidity value on LCD Display temp1 = '{0:.2f}'.format(temperature) self.ui.temperatureDisplay.display(temp1) hum1 = '{0:.2f}'.format(humidity) self.ui.humidityDisplay.display(hum1) #Set an alert for high temperautre if temperature > tempLimit: self.ui.alertDisplay.setText(" HIGH TEMPERATURE") elif humidity > humLimit: self.ui.alertDisplay.setText(" HIGH HUMIDITY") else: self.ui.alertDisplay.setText("") #calculating average temperature and humidity continuously for each sample tempAvg = ((tempAvg * (count - 1)) + temperature) / count temp2 = '{0:.2f}'.format(tempAvg) self.ui.temperatureAvgDisplay.display(temp2) humAvg = ((humAvg * (count - 1)) + humidity) / count hum2 = '{0:.2f}'.format(humAvg) self.ui.humidityAvgDisplay.display(hum2) if temperature > tempHigh: tempHigh = temperature temp3 = '{0:.2f}'.format(tempHigh) self.ui.temperatureHighDisplay.display(temp3) if temperature < tempLow: tempLow = temperature temp4 = '{0:.2f}'.format(tempLow) self.ui.temperatureLowDisplay.display(temp4) if humidity > humHigh: humHigh = humidity hum3 = '{0:.2f}'.format(humHigh) self.ui.humidityHighDisplay.display(hum3) if humidity < humLow: humLow = humidity hum4 = '{0:.2f}'.format(humLow) self.ui.humidityLowDisplay.display(hum4) #update the time of request for tem and humidity values newtime = time.strftime('%m-%d-%y %H:%M:%S') self.ui.timeDisplay.setText(newtime) #update database crsr.execute("INSERT INTO dht_data values(?,?,?,?,?,?,?,?,?,?)", (newtime, temp1, tempUnit, temp2, temp3, temp4, hum1, hum2, hum3, hum4)) connection.commit() #publish data to AWS IOT if timerflag == 1: payload = '"timestamp": "{}", "temperature": "{}", "humidity": "{}"'.format( newtime, tempA, hum1) payload = '{' + payload + '}' self.myAWSIoTMQTTClient.publish("DHT22", (payload), 1) #function to create a graph of last 10 temperature values def graphTempHum(self): global tempArr, humArr y = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] plt.subplot(2, 1, 1) plt.title('Temperature and Humidity Plot of last 10 Readings') plt.plot(y, tempArr, label='Temperature') plt.ylabel('Degree Celcius') plt.legend() plt.subplot(2, 1, 2) plt.plot(y, humArr, label='Humidity') plt.xlabel('Sample Number') plt.ylabel('Percent Humidity') plt.legend() plt.savefig('graph.jpg') plt.show() #function to switch from fahrenheit to celcius def celciusTemp(self): global unit, temp, tempAvg, tempHigh, tempLow, tempLimit if unit == 0: unit = 1 tempAvg = (tempAvg - 32) * 0.5556 tempHigh = (tempHigh - 32) * 0.5556 temp = '{0:.2f}'.format(tempHigh) self.ui.temperatureHighDisplay.display(temp) tempLow = (tempLow - 32) * 0.5556 temp = '{0:.2f}'.format(tempLow) self.ui.temperatureLowDisplay.display(temp) tempLimit = (tempLimit - 32) * 0.5556 self.ui.tempThresholdDisplay.display(tempLimit) self.getTempHum() #function to switch from celcius to fahrenheit def fahrenheitTemp(self): global unit, temp, tempAvg, tempHigh, tempLow, tempLimit if unit == 1: unit = 0 tempAvg = (tempAvg * 1.8) + 32 tempHigh = (tempHigh * 1.8) + 32 temp = '{0:.2f}'.format(tempHigh) self.ui.temperatureHighDisplay.display(temp) tempLow = (tempLow * 1.8) + 32 temp = '{0:.2f}'.format(tempLow) self.ui.temperatureLowDisplay.display(temp) tempLimit = (tempLimit * 1.8) + 32 self.ui.tempThresholdDisplay.display(tempLimit) self.getTempHum() #function to start and stop the timer to continuously update values def timerStartStop(self): global timerflag if timerflag == 0: self.ui.timerStatus.setStyleSheet( "background-color: rgb(0, 255, 0);") self.timer.start() timerflag = 1 elif timerflag == 1: self.ui.timerStatus.setStyleSheet( "background-color: rgb(255, 0, 0);") self.timer.stop() timerflag = 0 #function to set the high temperature threshold using dial def setTempLimit(self, value): global tempLimit, unit tempLimit = value if unit == 0: tempLimit = (tempLimit * 1.8) + 32 self.ui.tempThresholdDisplay.display(tempLimit) #function to set the high humidity threshold using dial def setHumLimit(self, value): global humLimit humLimit = value self.ui.humThresholdDisplay.display(humLimit) #function called when reset button is pressed to reset avg values def resetAvg(self): global tempAvg, tempHum, count tempAvg, tempHum, count = 0, 0, 0 self.ui.temperatureAvgDisplay.display("") self.ui.humidityAvgDisplay.display("") #function to clear the local database def clearDB(self): global connection, crsr crsr.execute("DROP TABLE IF EXISTS dht_data")
print(sys.path) # print the system path on the console """Provide a random string to connect to AWSIoT MQTT CLient""" myMQTTClient = AWSIoTMQTTClient("check123mydevice") """Provide your AWS End-point to establish the connection""" myMQTTClient.configureEndpoint("YOUR-ENDPOINT", 8883) """Provide your AWS Credentials such as pem file, certificate for secure connection""" myMQTTClient.configureCredentials("YOUR AWS PEM FILE", "YOUR PRIVATE PEM KEY", "YOUR CERTIFICATE PEM") """Queue to publish message if the device is offline""" myMQTTClient.configureOfflinePublishQueueing(-1) """Draining Frequency""" myMQTTClient.configureDrainingFrequency(2) """Connection Timeout in seconds""" myMQTTClient.configureConnectDisconnectTimeout(10) """Operation Timeout for MQTT Client in seconds""" myMQTTClient.configureMQTTOperationTimeout(5) # 5 seconds """Create an instance for SMTP Client connector""" conn = SmtpClientConnector.SmtpClientConnector() """Connect securely""" myMQTTClient.connect() """Publish the relevant data set""" myMQTTClient.publish("sensor/info", "connected", 0) """Infinitely Publish the Sensor Data to the AWS IoT Cloud Service""" while 1: now = datetime.utcnow() # get the current time in UTC time format now_str = now.strftime( '%Y-%m-%dT%H:%M:%SZ') # format my date-time module as per my needs. instance = SenseHat() # Create an instance of SenseHat result_temp = instance.get_temperature( ) # Get the Temperature from Sensehat result_humd = instance.get_humidity() # Get the Humidity from Sensehat
ap.add_argument('-n', '--name', required=True, dest='name') ap.add_argument('-e', '--endpoint', required=True, dest='endpoint') ap.add_argument('-r', '--rootca', required=True, dest='rootca') ap.add_argument('-k', '--key', required=True, dest='key', help='Path to private key.') ap.add_argument('-c', '--cert', required=True, dest='cert') args = ap.parse_args() # AWS IoTのクライアント作成 client = AWSIoTMQTTClient(args.name) # クライアントの初期設定 client.configureEndpoint(args.endpoint, 8883) client.configureCredentials(args.rootca, args.key, args.cert) client.configureAutoReconnectBackoffTime(1, 32, 20) client.configureOfflinePublishQueueing(-1) client.configureDrainingFrequency(2) client.configureConnectDisconnectTimeout(300) client.configureMQTTOperationTimeout(10) @touchphat.on_release(['Back', 'A', 'B', 'C', 'D', 'Enter']) def handle_touch(event): payload = {"event": event.name} client.publish( topic='button/'+args.name+'/event', payload=json.dumps(payload), QoS=1 ) def main(): client.connect(60) client.publish('button/'+args.name+'/stat', 'connected.', 1) try:
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()
def handle(self, *args, **options): host = options['host'] rootCAPath = options['rootCAPath'] certificatePath = options['certificatePath'] privateKeyPath = options['privateKeyPath'] useWebsocket = options['useWebsocket'] clientId = options['clientId'] topic = options['topic'] print(topic) if options['mode'] not in AllowedActions: parser.error("Unknown --mode option %s. Must be one of %s" % (args.mode, str(AllowedActions))) exit(2) if options['useWebsocket'] and options['certificatePath'] and options[ 'privateKeyPath']: parser.error( "X.509 cert authentication and WebSocket are mutual exclusive. Please pick one." ) exit(2) if not options['useWebsocket'] and (not options['certificatePath'] or not options['privateKeyPath']): parser.error("Missing credentials for authentication.") 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 myAWSIoTMQTTClient = None if useWebsocket: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True) myAWSIoTMQTTClient.configureEndpoint(host, 443) myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) #myAWSIoTMQTTClient = AWSIoTMQTTShadowClient(clientId) 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() #if options['mode'] == 'both' or options['mode'] == 'subscribe': myAWSIoTMQTTClient.subscribe(topic, 1, customCallback) #myDeviceShadow = myAWSIoTMQTTClient.createShadowHandlerWithName("Bot", True) time.sleep(2) # Publish to the same topic in a loop forever loopCount = 0 while True: print('loop') #myDeviceShadow.shadowGet(customCallback, 5) # if options['mode'] == 'both' or options['mode'] == 'publish': # message = {} # message['message'] = options['message'] # message['sequence'] = loopCount # #messageJson = json.dumps(message) # #myAWSIoTMQTTClient.publish(topic, messageJson, 1) # #if options['mode'] == 'publish': # # print('Published topic %s: %s\n' % (topic, messageJson)) # loopCount += 1 time.sleep(10)
class Teleop(): def __init__(self): self._cmd_pub = rospy.Publisher(CMD_VEL_TOPIC, Twist, queue_size=1) self.twist = Twist() self.mqtt_client = self.mqtt_connect() def mqtt_connect(self): """ Initializes the connection to AWS IoT MQTT then connects This is required for the simulation to receive data from the joystick app """ logger.info('Initializing AWS IoT MQTT connection') self.mqtt_client = AWSIoTMQTTClient(CLIENTID) self.mqtt_client.configureEndpoint(ENDPOINT, 8883) self.mqtt_client.configureCredentials(self.path(CAFILE), self.path(KEYFILE), self.path(CERTIFICATEFILE)) self.mqtt_client.configureConnectDisconnectTimeout(10) self.mqtt_client.configureMQTTOperationTimeout(5) logger.info('AWS IoT MQTT Connections status: %s', self.mqtt_client.connect()) return self.mqtt_client def path(self, filename): """ Creates the full path to the certificate files in the ROS application This is needed so the MQTT client can load the certs to authenticate with AWS IoT Core """ rospack = rospkg.RosPack() return os.path.join(rospack.get_path(ROSAPP), 'config', filename) def custom_callback(self, client, userdata, message): """ Will be called each time there is a new message from the joy stick The MQTTClient handles this in the background once this call back is created The JSON message is read from the Teleop.MQTTTOPIC, converted to a Twist message and published to the Teleop.ROSTOPIC """ logger.info('Received from %s, message: %s', TOPIC, message.payload) payload = json.loads(message.payload) self.twist.angular.x = payload["angular"]["x"] self.twist.angular.y = payload["angular"]["y"] self.twist.angular.z = payload["angular"]["z"] self.twist.linear.x = payload["linear"]["x"] self.twist.linear.y = payload["linear"]["y"] self.twist.linear.z = payload["linear"]["z"] self._cmd_pub.publish(self.twist) logger.info('Joystick message published to ROS') return def subscribe_joystick(self): """ Subscribe to the desired topic and register a callback Any new messages will be sent to the callback for processing """ logger.info("Subsribing to topic %s", TOPIC) self.mqtt_client.subscribe(TOPIC, 1, self.custom_callback) return def run_robot(self): """ Starts the subscription and keeps the script running """ self.subscribe_joystick() # this loop is needed to keep the script alive # while the script is running the callback is running # so messages from the topics are processed while True: time.sleep(5) return
class Network(Thread): """Responsible for controlling AWS publishing and subscriber threads, which interfaces with the companion app""" def __init__(self, boppi, run_event): """Ensures AWS is setup properly and dispatches the pub and sub threads""" # Set boppi instance self.boppi = boppi # Init threading event self.run_event = run_event # Setup AWS self.connected = False self.client_id = "BopPi" self.endpoint = "a2qfywdy8ysvgg.iot.eu-west-1.amazonaws.com" self.root_ca_path = os.path.abspath( os.path.join(os.path.realpath(__file__), "../../config/security_certs/root_ca.txt")) self.private_key_path = os.path.abspath( os.path.join(os.path.realpath(__file__), "../../config/security_certs/private.pem.key")) self.certificate_path = os.path.abspath( os.path.join(os.path.realpath(__file__), "../../config/security_certs/certificate.pem.crt")) self.client = AWSIoTMQTTClient(self.client_id) self.client.configureEndpoint(self.endpoint, 8883) self.client.configureCredentials(self.root_ca_path, self.private_key_path, self.certificate_path) self.client.configureDrainingFrequency(2) # Draining: 2 Hz self.client.configureConnectDisconnectTimeout(10) # 10 sec self.client.configureMQTTOperationTimeout(5) # 5 sec # Configure logging logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.ERROR) streamHandler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) # Configure Thread Thread.__init__(self) self.run_event = run_event self.daemon = True def run(self): print("[NETWORK] Started Network thread") print("[NETWORK] Connecting to AWS IoT Core") self.client.connect() print("[NETWORK] Connected to AWS IoT Core") print("[NETWORK] Starting Subscriber Thread") self.sub = Subscriber(self.boppi, self.run_event, self.client) self.sub.start() print("[NETWORK] Starting Publisher Thread") self.pub = Publisher(self.boppi, self.run_event, self.client) self.pub.start() while self.pub.connected is False and self.sub.connected is False: time.sleep(0.1) self.connected = True def stop(self): print("[NETWORK] Stopping thread") self.run_event.clear() self.sub.stop() self.pub.stop() self.sub.join() self.pub.join() self.client.disconnect() print("[NETWORK] Network stopped")
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')
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['PRODUCTION_TEMPLATE'] self.rotation_template = self.config_parameters['CERT_ROTATION_TEMPLATE'] self.claim_cert = self.config_parameters['CLAIM_CERT'] self.secure_key = self.config_parameters['SECURE_KEY'] self.root_cert = self.config_parameters['ROOT_CERT'] # Sample Provisioning Template requests a serial number as a # seed to generate Thing names in IoTCore. Simulating here. #self.unique_id = str(int(round(time.time() * 1000))) self.unique_id = "1234567-abcde-fghij-klmno-1234567abc-TLS350" # ------------------------------------------------------------------------------ # -- 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. # ------------------------------------------------------------------------------ self.primary_MQTTClient = AWSIoTMQTTClient(self.unique_id) self.test_MQTTClient = AWSIoTMQTTClient(self.unique_id) self.primary_MQTTClient.onMessage = self.on_message_callback self.callback_returned = False self.message_payload = {} self.isRotation = False def core_connect(self): """ Method used to connect to connect to AWS IoTCore Service. Endpoint collected from config. """ if self.isRotation: self.logger.info('##### CONNECTING WITH EXISTING CERT #####') print('##### CONNECTING WITH EXISTING CERT #####') self.get_current_certs() else: self.logger.info('##### CONNECTING WITH PROVISIONING CLAIM CERT #####') print('##### CONNECTING WITH PROVISIONING CLAIM CERT #####') self.primary_MQTTClient.configureEndpoint(self.iot_endpoint, 8883) self.primary_MQTTClient.configureCredentials("{}/{}".format(self.secure_cert_path, self.root_cert), "{}/{}".format(self.secure_cert_path, self.secure_key), "{}/{}".format(self.secure_cert_path, self.claim_cert)) self.primary_MQTTClient.configureOfflinePublishQueueing(-1) self.primary_MQTTClient.configureDrainingFrequency(2) self.primary_MQTTClient.configureConnectDisconnectTimeout(10) self.primary_MQTTClient.configureMQTTOperationTimeout(3) self.primary_MQTTClient.connect() def get_current_certs(self): non_bootstrap_certs = glob.glob('{}/[!boot]*.crt'.format(self.secure_cert_path)) non_bootstrap_key = glob.glob('{}/[!boot]*.key'.format(self.secure_cert_path)) #Get the current cert if len(non_bootstrap_certs) > 0: self.claim_cert = os.path.basename(non_bootstrap_certs[0]) #Get the current key if len(non_bootstrap_key) > 0: self.secure_key = os.path.basename(non_bootstrap_key[0]) 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, isRotation=False): """ Initiates an async loop/call to kick off the provisioning flow. Triggers: on_message_callback() providing the certificate payload """ if isRotation: self.template_name = self.rotation_template self.isRotation = True 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: if self.isRotation: self.logger.info('##### ACTIVATION COMPLETE #####') print('##### ACTIVATION COMPLETE #####') else: self.logger.info('##### CERT ACTIVATED AND THING {} CREATED #####'.format(json_data['thingName'])) print('##### CERT ACTIVATED AND THING {} CREATED #####'.format(json_data['thingName'])) self.validate_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.unique_id, 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. """ if self.isRotation: self.logger.info('##### VALIDATING EXPIRY & ACTIVATING CERT #####') print('##### VALIDATING EXPIRY & ACTIVATING CERT #####') else: self.logger.info('##### CREATING THING ACTIVATING CERT #####') print('##### CREATING THING ACTIVATING CERT #####') register_template = {"certificateOwnershipToken": token, "parameters": {"SerialNumber": serial}} #Register thing / activate certificate self.primary_MQTTClient.publish("$aws/provisioning-templates/{}/provision/json".format(self.template_name), json.dumps(register_template), 0) def validate_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)) def cert_validation_test(self): self.test_MQTTClient.configureEndpoint(self.iot_endpoint, 8883) self.test_MQTTClient.configureCredentials("{}/{}".format(self.secure_cert_path, self.root_cert), "{}/{}".format(self.secure_cert_path, self.new_key_name), "{}/{}".format(self.secure_cert_path, self.new_cert_name)) self.test_MQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing 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("openworld", 1, self.basic_callback) self.test_MQTTClient.publish("openworld", str({"service_response": "##### RESPONSE FROM PREVIOUSLY FORBIDDEN TOPIC #####"}), 0)
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() ### section 6 def customCallbackUpdateDocument(client, userdata, message): global currentColor , currentPower payload = json.loads(message.payload) # First we need to know user wants change to which state, so keep the desired data #print(payload) if "desired" in payload["current"]["state"] :
class EventProcessor: def __init__(self): self._measured = False self.done = False self._measureCnt = 0 self._events = range(WEIGHT_SAMPLES) self.bottles = 0 self.weightprevious = 0 self.tempprevious = 0 self._bottlesPrev = -1 self.setIOT() def setIOT(self): self.myMQTTClient = AWSIoTMQTTClient(CLIENT_ID) self.myMQTTClient.configureEndpoint(END_POINT, 8883) # For Websocket # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443) self.myMQTTClient.configureCredentials(CA_PATH, PRIVATE_PATH, CERT_PATH) # For Websocket, we only need to configure the root CA # myMQTTClient.configureCredentials("YOUR/ROOT/CA/PATH") 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 def mass(self, event): if (event.totalWeight > 1): self._events[self._measureCnt] = event.totalWeight * 2.20462 self._measureCnt += 1 if self._measureCnt == WEIGHT_SAMPLES: self._sum = 0 for x in range(0, WEIGHT_SAMPLES - 1): self._sum += self._events[x] self._weight = self._sum / WEIGHT_SAMPLES self._measureCnt = 0 self.temp = self.tempprevious if abs(self.weightprevious - self._weight) > BEER_WEIGHT and self.weightprevious > 0: print str(self._weight) + " lbs" self.temp = readTemp() self.sendBeerChange(self._weight, self.weightprevious, self.temp, self.tempprevious) self.weightprevious = self._weight self.tempprevious = self.temp if not self._measured: self._measured = True def sendBeerChange(self, weight, weightprevious, temp, tempprevious): self._message = "{\"weight\":" + str( weight) + ",\"weightprevious\":" + str( weightprevious) + ",\"temp\":" + str( temp) + ",\"tempprevious\":" + str(tempprevious) + "}" print "Beer Change" + str(self._message) self.myMQTTClient.connect() self.myMQTTClient.publish(TOPIC, self._message, 0) self.myMQTTClient.disconnect() @property def weight(self): if not self._events: return 0 histogram = collections.Counter(round(num, 1) for num in self._events) return histogram.most_common(1)[0][0]
def startServer(muteoutput): global remote global tv_listings_dict global tv_channels global tv_dict global mute remote = SmartCrypto(tvconfig.tvs[0]['host']) 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...') connect(myMQTTClient) 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
def main(event=None, context=None): # Init AWSIoTMQTTClient myMQTTClient = AWSIoTMQTTClient("myClientID1") myMQTTClient.configureEndpoint(endpoint, 8883) myMQTTClient.configureCredentials(rootCAPath, privateKey, deviceCertificate) #AWSIoTMQTTClient connection configuration #myMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sc # Connect to AWS IoT myMQTTClient.connect() def callback(client, userdata, message): print("Information received:") print(message.payload) print("From topic:") print(message.topic) s = (message.payload).decode('UTF-8') datas = json.loads(s) Lamp = (datas["state"]["desired"]["Lamp"]) Time1H = (datas["state"]["desired"]["Time1H"]) Time1M = (datas["state"]["desired"]["Time1M"]) Time2H = (datas["state"]["desired"]["Time2H"]) Time2M = (datas["state"]["desired"]["Time2M"]) Time3H = (datas["state"]["desired"]["Time3H"]) Time3M = (datas["state"]["desired"]["Time3M"]) Time4H = (datas["state"]["desired"]["Time4H"]) Time4M = (datas["state"]["desired"]["Time4M"]) Time5H = (datas["state"]["desired"]["Time5H"]) Time5M = (datas["state"]["desired"]["Time5M"]) Time1B = (datas["state"]["desired"]["Time1B"]) Time2B = (datas["state"]["desired"]["Time2B"]) Time3B = (datas["state"]["desired"]["Time3B"]) Time4B = (datas["state"]["desired"]["Time4B"]) Test1 = (datas["state"]["desired"]["Test1"]) Test2 = (datas["state"]["desired"]["Test2"]) packet = bytearray() packet.append(0x2B) packet.append(0x1E) packet.append(0x01) packet.append(0x3C) packet.append(0xC1) packet.append(0xF6) packet.append(0x04) packet.append(0x00) packet.append(0x00) packet.append(0x00) Lamps = int(str(hex(int(Lamp))), 16) Times1 = int(str(hex(int(Time1H))), 16) Times2 = int(str(hex(int(Time1M))), 16) Times3 = int(str(hex(int(Time2H))), 16) Times4 = int(str(hex(int(Time2M))), 16) Times5 = int(str(hex(int(Time3H))), 16) Times6 = int(str(hex(int(Time3M))), 16) Times7 = int(str(hex(int(Time4H))), 16) Times8 = int(str(hex(int(Time4M))), 16) Times9 = int(str(hex(int(Time5H))), 16) Times10 = int(str(hex(int(Time5M))), 16) Bright1 = int(str(hex(int(Time1B))), 16) Bright2 = int(str(hex(int(Time2B))), 16) Bright3 = int(str(hex(int(Time3B))), 16) Bright4 = int(str(hex(int(Time4B))), 16) Test1 = int(str(hex(int(Test1))), 16) Test2 = int(str(hex(int(Test2))), 16) #int(str(hex(int("70"))),16) packet.append(Lamps) packet.append(0x00) packet.append(0x01) packet.append(0x00) packet.append(0x46) packet.append(Times1) packet.append(Times2) packet.append(Times3) packet.append(Times4) packet.append(Times5) packet.append(Times6) packet.append(Times7) packet.append(Times8) packet.append(Times9) packet.append(Times10) packet.append(Bright1) packet.append(Bright2) packet.append(Bright3) packet.append(Bright4) packet.append(Test1) packet.append(Test2) print(packet) sero.write(packet) myMQTTClient.subscribe("$aws/things/demo/shadow/update", 1, callback) #myMQTTClient.disconnect() #myMQTTClient.unsubscribe("$aws/things/demo/shadow/update") while True: time.sleep(1)
client = None if useWebsocket: client = AWSIoTMQTTClient(clientId, useWebsocket=True) client.configureEndpoint(host, 443) client.configureCredentials(rootCAPath) else: client = AWSIoTMQTTClient(clientId) client.configureEndpoint(host, 8883) client.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration client.configureAutoReconnectBackoffTime(1, 32, 20) client.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing client.configureDrainingFrequency(2) # Draining: 2 Hz client.configureConnectDisconnectTimeout(10) # 10 sec client.configureMQTTOperationTimeout(5) # 5 sec client.onMessage = customOnMessage # Connect and subscribe to AWS IoT client.connect() # Note that we are not putting a message callback here. We are using the general message notification callback. client.subscribeAsync(topic, 1, ackCallback=customSubackCallback) time.sleep(2) if __name__ == '__main__': setup() while True: e1, e2, e3 = on_message() print("msg sent: ", e1.data, e2.data, e3.data) client.publishAsync(e1.topic, "'timestamp':"+str(round(time.time())) + ", 'data' :'" + e1.data + "'", 1)#, ackCallback=customPubackCallback) if e2.data != "spam":
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
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) # Init AWSIoTMQTTClient 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() # Publish to the same topic in a loop forever loopCount = 0 while True: try: payload = {} ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%m-%d-%Y %H:%M:%S') payload['timestamp'] = round(ts) payload['time'] = st # print (time.strftime("%a %b %d %Y %I:%M:%S%p", time.localtime())) #12-hour time if QWIIC_ENABLE:
'a1vgqh9vgvjzyh.iot.us-east-1.amazonaws.com') rootCAPath = os.path.dirname(os.path.abspath(__file__)) + rospy.get_param( "~rootCAPath", '/Certificates/root-CA.crt') certificatePath = os.path.dirname( os.path.abspath(__file__)) + rospy.get_param( "~certificatePath", '/Certificates/Pi.cert.pem') privateKeyPath = os.path.dirname( os.path.abspath(__file__)) + rospy.get_param( "~privateKeyPath", '/Certificates/Pi.private.key') clientId = rospy.get_param("~clientId", 'test_pi') topic = rospy.get_param("~topic", '/Transnavigators/Pi') aws_iot_mqtt_client = AWSIoTMQTTClient(clientId) aws_iot_mqtt_client.configureEndpoint(host, 8883) aws_iot_mqtt_client.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration 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 # Connect to AWS IoT aws_iot_mqtt_client.connect() rospy.loginfo("Connecting to AWS") # run tests rostest.rosrun(package_name, test_name, TestAlexaVoiceControl)
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 = {} message['message'] = args.message message['sequence'] = loopCount messageJson = json.dumps(message)
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient myMQTTClient = AWSIoTMQTTClient("arn:aws:iot:us-east-2:095931297336:thing/Monitor", useWebsocket=True) myMQTTClient.configureEndpoint("a3arleqlv6u4zy-ats.iot.us-east-2.amazonaws.com", 443) myMQTTClient.configureCredentials("root-CA.crt") myMQTTClient.configureOfflinePublishQueueing(-1) myMQTTClient.configureDrainingFrequency(2) myMQTTClient.configureConnectDisconnectTimeout(10) myMQTTClient.configureMQTTOperationTimeout(5) myMQTTClient.connect() myMQTTClient.publish("$aws/things/Monitor/shadow/update", "{'message':'Hello from AWS IoT console'}", 0) myMQTTClient.disconnect() ''' def main(): #Infos CPU_system = psutil.cpu_count() CPU_physical_cores = psutil.cpu_count(logical=False) Controle = input("Qual o consumo desejado?")