def __init__(self): #Path to AWS IoT Core certificates and keys ROOT_PATH = "/home/franklin/Desktop/Projetos/pgcc008-problem01/web-application/resources/" ROOT_CA_PATH = ROOT_PATH + "certificates/AmazonRootCA1.pem.txt" KEY_PATH = ROOT_PATH + "certificates/a44bf8f189-private.pem.key" CERT_PATH = ROOT_PATH + "certificates/a44bf8f189-certificate.pem.crt" #Configures MQTTClient (server) with AWS MQTT Broker endpoint self.MQTTClient = AWSIoTPyMQTT.AWSIoTMQTTClient( "pgcc008-problem01-server") self.MQTTClient.configureEndpoint( "a18jmvtsiq4e9v-ats.iot.us-east-1.amazonaws.com", 8883) self.MQTTClient.configureCredentials(ROOT_CA_PATH, KEY_PATH, CERT_PATH) #Starts the process of subscribe topics self.MQTTClient.subscribe( "pgcc008/problem01/sensor/internal/temperature", 0, self.dataChangeCallback) self.MQTTClient.subscribe("pgcc008/problem01/sensor/internal/humidity", 0, self.dataChangeCallback) self.MQTTClient.subscribe( "pgcc008/problem01/sensor/internal/air_cond_state", 0, self.dataChangeCallback) self.MQTTClient.subscribe( "pgcc008/problem01/sensor/external/temperature", 0, self.dataChangeCallback)
def run(self): args = { 'client_id': 'jgvnrevnrew', 'endpoint': 'a8jyxx32q2p0a-ats.iot.ap-south-1.amazonaws.com', 'cert': '/home/ec2-user/tayhome/certs/mqtt/certpem/232ef22a93-certificate.pem.crt', 'key': '/home/ec2-user/tayhome/certs/mqtt/privatekey/232ef22a93-private.pem.key', 'root_ca': '/home/ec2-user/tayhome/certs/mqtt/rootCA.pem' } # Create an AWS IoT MQTT Client using TLSv3.1 Mutual Authentication self.myAWSIoTMQTTClient = AWSIoTPyMQTT.AWSIoTMQTTClient( args['client_id'], protocolType=AWSIoTPyMQTT.MQTTv3_1) self.myAWSIoTMQTTClient.configureEndpoint(args['endpoint'], 443) self.myAWSIoTMQTTClient.configureCredentials(args['root_ca'], args['key'], args['cert']) self.myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 128, 20) print('Connecting...') if self.myAWSIoTMQTTClient.connect(1200): print('Connected') while True: pass else: print('Not Connected')
def connect(self, auth, debug): # logging... if debug: self.__assert_logger(logging.DEBUG) # client... self.__client = MQTTLib.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... try: return self.__client.connect(self.__KEEP_ALIVE_INTERVAL) except (connectError, connectTimeoutException) as ex: raise OSError(ex.__class__.__name__)
def setupClient(): try: mqtt_client = AWSIoTMQTTClient.AWSIoTMQTTClient("device_one") mqtt_client.configureEndpoint(IOT_ENDPOINT_ATS, 8883) mqtt_client.configureCredentials(ROOT_CA_PATH, PRIVATE_KEY_PATH, CERTIFICATE_PATH) mqtt_client.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing mqtt_client.configureDrainingFrequency(2) # Draining: 2 Hz mqtt_client.configureConnectDisconnectTimeout(10) # 10 sec mqtt_client.configureMQTTOperationTimeout(5) # 5 sec mqtt_client.connect() return mqtt_client except Exception as e: print("Unexpected error: %s" % e)
def __init__(self): #Path to AWS IoT Core certificates and keys ROOT_PATH = "/home/franklin/Desktop/Projetos/pgcc008-problem02/daemon/" ROOT_CA_PATH = ROOT_PATH + "certificates/AmazonRootCA1.pem.txt" KEY_PATH = ROOT_PATH + "certificates/b4078a262d-private.pem.key" CERT_PATH = ROOT_PATH + "certificates/b4078a262d-certificate.pem.crt" #Configures MQTTClient (device) with AWS MQTT Broker endpoint self.MQTTClient = AWSIoTPyMQTT.AWSIoTMQTTClient( "pgcc008-problem02-daemon") self.MQTTClient.configureEndpoint( "a18jmvtsiq4e9v-ats.iot.us-east-1.amazonaws.com", 8883) self.MQTTClient.configureCredentials(ROOT_CA_PATH, KEY_PATH, CERT_PATH) #Starts the process of subscribe topics self.MQTTClient.subscribe("pgcc008/problem02/status", 0, self.dataChangeCallback) self.MQTTClient.subscribe("pgcc008/problem02/data", 0, self.dataChangeCallback)
def __init__(self): #Path to AWS IoT Core certificates and keys ROOT_PATH = "/home/pi/control-system/" ROOT_CA_PATH = ROOT_PATH + "certificates/AmazonRootCA1.pem.txt" KEY_PATH = ROOT_PATH + "certificates/4d327b67ce-private.pem.key" CERT_PATH = ROOT_PATH + "certificates/4d327b67ce-certificate.pem.crt" #Configures MQTTClient (device) with AWS MQTT Broker endpoint self.MQTTClient = AWSIoTPyMQTT.AWSIoTMQTTClient( "pgcc008-problem01-device") self.MQTTClient.configureEndpoint( "a18jmvtsiq4e9v-ats.iot.us-east-1.amazonaws.com", 8883) self.MQTTClient.configureCredentials(ROOT_CA_PATH, KEY_PATH, CERT_PATH) #Starts the process of subscribe topics self.MQTTClient.subscribe("pgcc008/problem01/limit/max", 0, self.dataChangeCallback) self.MQTTClient.subscribe("pgcc008/problem01/limit/min", 0, self.dataChangeCallback)
def start(): # Make sure that Client ID is unique for each device myAWSIoTMQTTShadowClient = AWSIoTPyMQTT.AWSIoTMQTTShadowClient("IoTPublishDevice") myAWSIoTMQTTShadowClient.configureEndpoint("xxxxxxxxxxxxxxxxxx", 8883) # Enter the endpoint for your thing myAWSIoTMQTTShadowClient.configureCredentials("xxxxxxxxx-root-ca.pem", "xxxxxxxx-private.pem.key", "xxxxxxx.pem.crt") # Enter the path to relevant Key and Root CA print(myAWSIoTMQTTShadowClient.connect()) BotShadow = myAWSIoTMQTTShadowClient.createShadowHandlerWithName("YourThingName",True) #Replace with your thing name payload = {"state":{"reported":{"key1":"value1","key2":"value2","key3":"value3","key4":"value4"}}} try: #Updating Device Shadow print(BotShadow.shadowUpdate(json.dumps(payload), customShadowCallback_Update, 2)) time.sleep(2) except: print("Error Connecting to AWS IOT")
def __init__(self): aws_config_file = "/configuration/aws.json" self.aws_config = configuration.aws_configuration(aws_config_file) print(self.aws_config.get_endpoint()) # Define ENDPOINT, CLIENT_ID, PATH_TO_CERT, PATH_TO_KEY, PATH_TO_ROOT, MESSAGE, TOPIC, and RANGE ENDPOINT = self.aws_config.get_endpoint() CLIENT_ID = self.aws_config.get_client_id() PATH_TO_CERT = self.aws_config.get_path_to_cert() PATH_TO_KEY = self.aws_config.get_path_to_key() PATH_TO_ROOT = self.aws_config.get_path_to_root() #MESSAGE = "Hello World" #TOPIC = "room/temperature" #RANGE = 5 self.myAWSIoTMQTTClient = AWSIoTPyMQTT.AWSIoTMQTTClient(CLIENT_ID) self.myAWSIoTMQTTClient.configureEndpoint(ENDPOINT, 8883) self.myAWSIoTMQTTClient.configureCredentials(PATH_TO_ROOT, PATH_TO_KEY, PATH_TO_CERT) self.myAWSIoTMQTTClient.connect()
valueA = int(s1) valueB = int(s2) #conn.send(s) #index = open("index.html").read().format(p1='', p2='') except Exception as e: print(e) # [TODO] Define ENDPOINT, CLIENT_ID, PATH_TO_CERT, PATH_TO_KEY, PATH_TO_ROOT(done) ENDPOINT = "a2n8nzfjjzpdhv-ats.iot.us-east-2.amazonaws.com" CLIENT_ID = "b0e1f939f3a24ac9bfd952dc7c93ae4a" PATH_TO_CERT = "./af56662380-certificate.pem.crt" PATH_TO_KEY = "./af56662380-private.pem.key" PATH_TO_ROOT = "./root_CA_1.txt" myAWSIoTMQTTClient = AWSIoTPyMQTT.AWSIoTMQTTClient(CLIENT_ID) myAWSIoTMQTTClient.configureEndpoint(ENDPOINT, 8883) myAWSIoTMQTTClient.configureCredentials(PATH_TO_ROOT, PATH_TO_KEY, PATH_TO_CERT) myAWSIoTMQTTClient.connect() # [TODO] subscribe AWS topic(s)(done) myAWSIoTMQTTClient.subscribe("$aws/things/106000266/shadow/update",1,mqttcallback) def on_new_client(clientsocket,addr): global currentRing while True: #signal = get_signal() #print(signal) #if signal and clientsocket is not None: # clientsocket.send()#send signal back to arduino # [TODO] decode message from Arduino and send to AWS(done)
port = 443 if not args.useWebsocket and not args.port: # When no port override for non-WebSocket, default to 8883 port = 8883 # Configure logging streamHandler = logging.StreamHandler() streamHandler.setFormatter( logging.Formatter('%(asctime)s %(name)s %(levelname)s - %(message)s')) logger = logging.getLogger("jd") logger.setLevel(logging.DEBUG) logger.addHandler(streamHandler) # Init AWSIoTMQTTShadowClient shadowClient = None if useWebsocket: shadowClient = mqtt.AWSIoTMQTTShadowClient(clientId, useWebsocket=True) shadowClient.configureEndpoint(host, port) shadowClient.configureCredentials(rootCAPath) else: shadowClient = mqtt.AWSIoTMQTTShadowClient(clientId) shadowClient.configureEndpoint(host, port) shadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTShadowClient configuration shadowClient.configureAutoReconnectBackoffTime(1, 32, 20) shadowClient.configureConnectDisconnectTimeout(10) # 10 sec shadowClient.configureMQTTOperationTimeout(5) # 5 sec mqttClient = shadowClient.getMQTTConnection() mqttClient.configureOfflinePublishQueueing(-1, mqtt.DROP_OLDEST)
def main(): #ensure database is globally accessible global seatList #Use argparse to take in CLI arguments cliArgs = argparse.ArgumentParser() cliArgs.add_argument("-end", action="store", required =True, dest="endpoint", help="AWS IoT Endpoint") cliArgs.add_argument("-root", action="store", required = True, dest = "rootCA", help="AWS Root CA") cliArgs.add_argument("-cert", action="store", required=True, dest = "userCert", help ="Device Certificate") cliArgs.add_argument("-key", action="store", required=True, dest = "privateKey", help ="Device Private Key") cliArgs.add_argument("-id", action="store", required=True, dest = "clientID", help = "Device Client ID") cliArgs.add_argument("-top", action="store", dest="topic", default="studio/seating", help ="Topic Channel to Post") cliArgs.add_argument("-verbose", action="store_true", dest="debug", help="Enable verbose mode") args = cliArgs.parse_args() endpoint = args.endpoint #the endpoint/server that the mqtt connection is made to rootCA = args.rootCA #AWS's root certificate (Class 3 Public Primary) userCert = args.userCert privateKey = args.privateKey clientID = args.clientID topic = args.topic debug = args.debug # AWS MQTT Client Setup #Default port for auth'ed connection is 8883, 443 for websocket however codebase needs to be changed to implement port = 8883 #Client Security config MQTTClient = None MQTTClient = AWSIoTPyMQTT.AWSIoTMQTTClient(clientID) MQTTClient.configureEndpoint(endpoint, port) MQTTClient.configureCredentials(rootCA, privateKey, userCert) #Client Server Connection Settings #Reconnect in event of temporary connection failure. (Initial time to wait before attempting to reconnect, maximum time to wait before attempting to reconnect, time for a connection to be considered stable (resets wait time to minimum)) All given in seconds MQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) #Configure queue size in event of connection offline. (size of queue, action to complete when queue full). #As the server only needs the latest data which will overwrite older data, no need to send older data, risks confusion MQTTClient.configureOfflinePublishQueueing(1, AWSIoTPyMQTT.DROP_OLDEST) #Configure rate at which to send queued messages (per second) MQTTClient.configureDrainingFrequency(2) #Configure time to wait for disconnect to complete (in seconds) MQTTClient.configureConnectDisconnectTimeout(10) #Configure publish, subscribe, unsubscribe operation timeout for QoS 1 service (seconds) MQTTClient.configureMQTTOperationTimeout(10) if debug: print("[NOTICE] MQTT configuration complete") #MQTT CONFIG COMPLETE #MQTT subscribe to check for incoming commands #Connect to MQTT service connectCheck = MQTTClient.connect() #Verbose connection notifiers if debug: if connectCheck: print("[NOTICE] Successfully connected to MQTT") else: print("[ERROR] Unsuccessful connection to MQTT") #subscribe to given topic channel subscribeCheck = MQTTClient.subscribe(topic, 0, dataRX) #Verbose subscription notifiers if debug: if subscribeCheck: print("[NOTICE] Successfully subscribed to %s" %(topic)) else: print("[ERROR] Subscription to %s failed" %(topic)) print("[NOTICE] Started Successfully") #if debug: #seatList["test"] = seat(location = "testLoc", status = "testStatus", date = time.asctime(time.localtime())) #set to automatically request an update upon startup userInput = "update" #progam runs while the user input is not "quit" while (userInput != "quit"): #since python doesn't support switch statements like C, if & elif used for command structure #send update request to remote clients if(userInput == "update"): #create JSON encoded update request messageJSON = json.dumps("update") #push request publishCheck = MQTTClient.publish(topic, messageJSON, 1) #notify user of result if publishCheck: print("[NOTICE] Update request successfully sent") elif not publishCheck: print("[NOTICE] Update request was not sent successfully") #send shutdown request to remote clients elif(userInput == "shutdown"): #create JSON encoded update request messageJSON = json.dumps("stop") #push request publishCheck = MQTTClient.publish(topic, messageJSON, 1) #notify user of result if publishCheck: print("[NOTICE] Shutdown request successfully sent") elif not publishCheck: print("[NOTICE] Shutdown request was not sent successfully") #print list of seats elif(userInput == "seating"): #cant iterate over an empty dict if (len(seatList) == 0): print("[ERROR] Seat Database is currently empty") else: #header print("Seat Location Occupation Timestamp") #for loop w/ formatting for chair in seatList: chair = seatList[chair] print("%-17s%-14s%s" %(chair.location, chair.status, chair.date)) #allows the user to delete the database elif(userInput =="purgedb"): #doublecheck that they actually want this userInput = (raw_input("This will delete the current database, are you sure (y/n)? ")) #nuke database, commit changes, recreate, commit changes if(userInput=="y"): cursor.execute('''DROP TABLE seating''') sqlDB.commit() cursor.execute('''CREATE TABLE seating ( location TEXT PRIMARY KEY, status TEXT NOT NULL, date TEXT NOT NULL)''') sqlDB.commit() seatList = dict() print("DB deleted and recreated") #prints list of commands elif(userInput == "help"): print("\"update\" - sends a request to all remote sensors, requesting an occupancy status update, regardless of whether the occupancy has changed") print("\"shutdown\" - sends a request to all remote sensors to disconnect from MQTT and exit \"client.py\", this will require each remote sensor script to be restarted manually") print("\"seating\" - prints the lastest version of the seating status database") print("\"purgedb\" - deletes the current seating database, THIS CANNOT BE UNDONE") print("\"help\" - prints this menu") print("\"quit\" - disconnects this server from MQTT, and exits the current script") #if the command isnt recognised else: print("[NOTICE] Invalid command, type \"help\" for all commands") #get user input userInput = (raw_input("Enter a command> ")).lower() #user has input quit #disconnect from MQTT MQTTClient.disconnect() #disconnect database sqlDB.commit() sqlDB.close() #notify user, even if not in verbose mode print("[NOTICE] Shutting Down")
rootCA = args.rootCA #AWS's root certificate (Class 3 Public Primary) userCert = args.userCert privateKey = args.privateKey clientID = args.clientID topic = args.topic debug = args.debug seatLocation = args.loc # AWS MQTT Client Setup #Default port for auth'ed connection is 8883, 443 for websocket however codebase needs to be changed to implement port = 8883 #Client Security config MQTTClient = None MQTTClient = AWSIoTPyMQTT.AWSIoTMQTTClient(clientID) MQTTClient.configureEndpoint(endpoint, port) MQTTClient.configureCredentials(rootCA, privateKey, userCert) #Client Server Connection Settings #Reconnect in event of temporary connection failure. (Initial time to wait before attempting to reconnect, maximum time to wait before attempting to reconnect, time for a connection to be considered stable (resets wait time to minimum)) All given in seconds MQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) #Configure queue size in event of connection offline. (size of queue, action to complete when queue full). #As the server only needs the latest data which will overwrite older data, no need to send older data, risks confusion MQTTClient.configureOfflinePublishQueueing(1, AWSIoTPyMQTT.DROP_OLDEST) #Configure rate at which to send queued messages (per second) MQTTClient.configureDrainingFrequency(2) #Configure time to wait for disconnect to complete (in seconds)
command = 'knxtool groupwrite ip: 1/1/{} {}'.format(window_id, color) os.system(command) #print(" ----> WINDOW: {}".format(command)) def send_sensor_data(brightness, temeperature=None): message = '{"temperature": "0", "brightness": %d}' % brightness if myAWSIoTMQTTClient.publish("sensor_data", message, 0): #print(" <- sensor_data: %s" % message) pass else: #print("!!! Error sensor -> AWS IoT") pass # Connect to AWS myAWSIoTMQTTClient = AWSIoTPyMQTT.AWSIoTMQTTClient("RaspberryPi") myAWSIoTMQTTClient.configureEndpoint(HOST_NAME, 8883) myAWSIoTMQTTClient.configureCredentials(ROOT_CA, PRIVATE_KEY, CERT_FILE) myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) myAWSIoTMQTTClient.connect() print("Connection successful!") print("Clearing windows...") for i in range(4, 8): os.system('knxtool groupwrite ip: 1/1/{} 00'.format(i)) # subscribe windows topic callback myAWSIoTMQTTClient.subscribe("windows", 0, windowCallback)
# Custom MQTT message callback def customCallback_02(client, userdata, message): # print("Received a new message: ") # print(message.payload) # print("from topic: ") # print(message.topic) RackActions.GetUpdatedRackState(message) # -------------------------------------------------------------- # -----------MESSAGE BROKER CLIENT ACTIONS---------------------- # -------------------------------------------------------------- # Create an AWS IoT MQTT Client using Websocket SigV4 myAWSIoTMQTTClient = AWSIoTPyMQTT.AWSIoTMQTTClient("raul", useWebsocket=True) myAWSIoTMQTTClient.configureEndpoint( "aj34tk2y4o3ym.iot.eu-central-1.amazonaws.com", 443) myAWSIoTMQTTClient.configureCredentials( "C:\Raul\Desarrollos\Python\Octanis\Rack\certif") myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) myAWSIoTMQTTClient.configureMQTTOperationTimeout(15) myAWSIoTMQTTClient.connect() # https://github.com/aws/aws-iot-device-sdk-python # DOC: https://s3.amazonaws.com/aws-iot-device-sdk-python-docs/sphinx/html/generated/AWSIoTPythonSDK.MQTTLib.html?highlight=subscribe#AWSIoTPythonSDK.MQTTLib.AWSIoTMQTTClient.subscribe myAWSIoTMQTTClient.subscribe(
"fields": { "red": red, "blue": blue, "green": green, "color": color } }) client.write_points(data) print("--------------\n\n") # Create an AWS IoT MQTT Client using TLSv1.2 Mutual Authentication # Make sure that the Client ID is unique for each device myAWSIoTMQTTShadowClient = AWSIoTPyMQTT.AWSIoTMQTTShadowClient("GrafanaClient") myAWSIoTMQTTShadowClient.configureEndpoint( "xxxxxxxxxxxxxxxxxx", 8883) # Enter the endpoint for your thing myAWSIoTMQTTShadowClient.configureCredentials( "xxxxxxxxx-root-ca.pem", "xxxxxxxx-private.pem.key", "xxxxxxx.pem.crt") # Enter the path to relevant Key and Root CA print(myAWSIoTMQTTShadowClient.connect()) BotShadow = myAWSIoTMQTTShadowClient.createShadowHandlerWithName( "YourThingName", True) #Replace with your thing name while True: try: print(BotShadow.shadowGet(customCallback, 2)) time.sleep(2)
def loop(): color = "No Color" GPIO.setmode(GPIO.BCM) GPIO.setup(signal, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(s2, GPIO.OUT) GPIO.setup(s3, GPIO.OUT) # Make sure that Client ID is unique for each device myAWSIoTMQTTShadowClient = AWSIoTPyMQTT.AWSIoTMQTTShadowClient( "RPIColorSensor") myAWSIoTMQTTShadowClient.configureEndpoint("XXXXXXXX.amazonaws.com", 8883) myAWSIoTMQTTShadowClient.configureCredentials("root-ca.pem", "rpi-private.pem.key", "rpi-certificate.pem.crt") print(myAWSIoTMQTTShadowClient.connect()) BotShadow = myAWSIoTMQTTShadowClient.createShadowHandlerWithName( "RPI3", True) print("\n") while (1): print(" --- Reading Values ---") GPIO.output(s2, GPIO.LOW) GPIO.output(s3, GPIO.LOW) time.sleep(0.3) start = time.time() for impulse_count in range(NUM_CYCLES): GPIO.wait_for_edge(signal, GPIO.FALLING) duration = time.time() - start #seconds to run for loop red = NUM_CYCLES / duration #in Hz print("red value - ", red) if (red > 25000): color = "Red" GPIO.output(s2, GPIO.LOW) GPIO.output(s3, GPIO.HIGH) time.sleep(0.3) start = time.time() for impulse_count in range(NUM_CYCLES): GPIO.wait_for_edge(signal, GPIO.FALLING) duration = time.time() - start blue = NUM_CYCLES / duration print("blue value - ", blue) if (blue > 27000): color = "Blue" GPIO.output(s2, GPIO.HIGH) GPIO.output(s3, GPIO.HIGH) time.sleep(0.3) start = time.time() for impulse_count in range(NUM_CYCLES): GPIO.wait_for_edge(signal, GPIO.FALLING) duration = time.time() - start green = NUM_CYCLES / duration print("green value - ", green) if (green > 27000): color = "Green" if (green > 22000 and blue < 25000): color = "Green" if ((red < 19000) and (green < 19000) and (blue < 19000)): color = "NoColor" # Create message payload print(color) payload = { "state": { "reported": { "red": str(red), "blue": str(blue), "green": str(green), "color": str(color) } } } try: #Updating Device Shadow print( BotShadow.shadowUpdate(json.dumps(payload), customShadowCallback_Update, 2)) time.sleep(2) except: print("Error Connecting to AWS IOT")