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")
ucIoTDeviceClient = None # initialize var ucIoTDeviceClient = AWSIoTMQTTClient( deviceId ) # The client class that connects to and accesses AWS IoT over MQTT v3.1/3.1.1. ucIoTDeviceClient.configureEndpoint( ucIoTCustomEndpoint, 8883) # MQTT Broker host address and default port (TLS) ucIoTDeviceClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # certs and key # Configure Urbanova Cloud IoT Device Client Connection Settings (reference: https://s3.amazonaws.com/aws-iot-device-sdk-python-docs/sphinx/html/index.html) ucIoTDeviceClient.configureAutoReconnectBackoffTime(1, 32, 20) ucIoTDeviceClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing ucIoTDeviceClient.configureDrainingFrequency(2) # Draining: 2 Hz ucIoTDeviceClient.configureConnectDisconnectTimeout(10) # 10 sec ucIoTDeviceClient.configureMQTTOperationTimeout(5) # 5 sec # Connect to Urbanova Cloud IoT ucIoTDeviceClient.connect() time.sleep(2) # Publish `Hello Sensor ${sensorID}`to Urbanova Cloud once per second loopCount = 0 while True: message = {} # init empty message obj message['message'] = 'Hello Sensor ' + deviceId # add `message` element message['sequence'] = loopCount # add `sequence` element messageJson = json.dumps(message) # convert to json ucIoTDeviceClient.publish(deviceId, messageJson, 1) # publish to urbanova cloud
#while True: GPIO.setwarnings(False) setup() #AwsReyna connection myMQTTClient = AWSIoTMQTTClient("ReynaPI") myMQTTClient.configureEndpoint( "a3te7fgu4kv468-ats.iot.us-west-1.amazonaws.com", 8883) myMQTTClient.configureCredentials( "/home/pi/Certificates/rootCA.pem", "/home/pi/Certificates/d626c8c838-private.pem.key", "/home/pi/Certificates/d626c8c838-certificate.pem.crt") myMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myMQTTClient.configureOfflinePublishQueueing(-1) myMQTTClient.configureDrainingFrequency(2) myMQTTClient.configureConnectDisconnectTimeout(10) myMQTTClient.configureMQTTOperationTimeout(5) myMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) #connect and subscribe myMQTTClient.connect() humidity = 0 while True: myMQTTClient.subscribe("ryan_pi/data", 1, callback) except KeyboardInterrupt: stop() destroy()
def main(): import time import sys import argparse global myAWSIoTMQTTClient global host global tag parser = argparse.ArgumentParser() parser.add_argument('-host', action='store',help='MAC of BT device', default='68:C9:0B:06:44:09') parser.add_argument('-n', action='store', dest='count', default=0, type=int, help="Number of times to loop data") parser.add_argument('-t',action='store',type=float, default=1.0, help='time between polling') parser.add_argument('-T','--temperature', action="store_true",default=False) parser.add_argument('-A','--accelerometer', action='store_true', default=False) parser.add_argument('-H','--humidity', action='store_true', default=False) parser.add_argument('-M','--magnetometer', action='store_true', default=False) parser.add_argument('-B','--barometer', action='store_true', default=False) parser.add_argument('-G','--gyroscope', action='store_true', default=False) parser.add_argument('-K','--keypress', action='store_true', default=False) parser.add_argument('-L','--light', action='store_true', default=False) parser.add_argument('--all', action='store_true', default=True) arg = parser.parse_args(sys.argv[1:]) # Setup AWS IOT connection myAWSIoTMQTTClient = None myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSub") myAWSIoTMQTTClient.configureEndpoint(awsEndPoint, 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("SensorTag/data", 1, customCallback) while True: tag = None try: host = arg.host print('Connecting to ' + host) tag = SensorTag(arg.host) print("After sensor tag call") # Enabling selected sensors tag.IRtemperature.enable() tag.humidity.enable() tag.barometer.enable() tag.accelerometer.enable() tag.magnetometer.enable() tag.gyroscope.enable() tag.keypress.enable() tag.setDelegate(KeypressDelegate()) tag.lightmeter.enable() # Some sensors (e.g., temperature, accelerometer) need some time for initialization. # Not waiting here after enabling a sensor, the first read value might be empty or incorrect. time.sleep(2.0) counter=1 while True: print ("Running cycle " + str(counter)) publish_readings() #client.disconnect() if counter >= arg.count and arg.count != 0: myAWSIoTMQTTClient.disconnect() break counter += 1 tag.waitForNotifications(0.5) time.sleep(10.0) except: print "Unexpected error:", sys.exc_info()[0] # if tag is not None: # tag.disconnect() del tag time.sleep(4.0) tag.disconnect() del tag
def main(): signal.signal(signal.SIGINT, signal_handler) print(device_id) ######################## ### #AWS IoT MQTT client setup global mqttClient mqttClient = AWSIoTMQTTClient(device_id) #Setup del client mqtt di aws iot mqttClient.disableMetricsCollection() mqttClient.configureEndpoint(endpoint, 8883) mqttClient.configureCredentials( rootCAPath, privateKeyPath, certificatePath, ) # Backoff per riconnessione in caso di mancanza di connessione mqttClient.configureAutoReconnectBackoffTime(1, 32, 20) # Coda dei messaggi in caso di mancanza di connessione # Infinite offline Publish queueing mqttClient.configureOfflinePublishQueueing(-1) mqttClient.configureDrainingFrequency(10) # Draining: 2 Hz mqttClient.configureConnectDisconnectTimeout(10) # 10 sec mqttClient.configureMQTTOperationTimeout(5) # 5 sec #callback in caso di mancanza di connessione mqttClient.onOffline = disconnessoAInternet ############################# #### DEVICE SHADOW setup global shadowClient shadow = AWSIoTMQTTShadowClient(shadow_clientId, awsIoTMQTTClient=mqttClient) shadowClient = shadow.createShadowHandlerWithName(thingName, True) shadowClient.shadowRegisterDeltaCallback(shadowDeltaCallback) ############################# connect() #avvia il tentativo di connessione (ASYNC) #iscrizione al topic di richiesta info mqttClient.subscribe("pcTelemetry/{}/infoRequest".format(device_id), 1, infoRequest) ## Avvia 3 thread: # - uno pubblica una misurazione ogni 10s # - uno pubblica un array di 30 misurazioni. Con una misurazione ogni secondo # - uno pubblica una misurazione ogni 2 min. Misurazioni possibili: batteria, spazio Disco t1 = threading.Thread(target=detailData, args=(parametri, 1)) t2 = threading.Thread(target=liveData, args=(parametri, 10)) t3 = threading.Thread(target=slowUpdateData, args=(parametri, 120)) t1.setDaemon(True) t2.setDaemon(True) t3.setDaemon(True) t1.start() t2.start() t3.start() while True: time.sleep(1)
CHECK_SPAN = int(os.environ.get('CHECK_SPAN', '30')) ENDPOINT = os.environ.get('AWSIOT_ENDPOINT') ROOTCA = os.environ.get('AWSIOT_ROOTCA') CERT = os.environ.get('AWSIOT_CERT') PRIVATE = os.environ.get('AWSIOT_PRIVATE') THING_NAME = os.environ.get('THING_NAME') client = AWSIoTMQTTClient(THING_NAME) client.configureEndpoint(ENDPOINT, 8883) client.configureCredentials(ROOTCA, PRIVATE, CERT) client.configureAutoReconnectBackoffTime(1, 32, 20) client.configureOfflinePublishQueueing(-1) client.configureDrainingFrequency(2) client.configureConnectDisconnectTimeout(300) client.configureMQTTOperationTimeout(5) if __name__ == '__main__': from logging import StreamHandler logger.addHandler(StreamHandler(stream=sys.stdout)) client.connect(250) # main loop while True: try: shadow = { "state": { "reported": { "temperature":
from rpi_lcd import LCD def customCallback(client, userdata, message): print("Received a new message: ") print(message.payload) print("from topic: ") print(message.topic) print("--------------\n\n") #Amazon AWS configuration and connections host = "ac9yfl5owv3oq.iot.ap-southeast-1.amazonaws.com" rootCAPath = "rootca.pem" certificatePath = "certificate.pem.crt" privateKeyPath = "private.pem.key" my_rpi = AWSIoTMQTTClient("basicPubSub") my_rpi.configureEndpoint(host, 8883) my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath) my_rpi.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing my_rpi.configureDrainingFrequency(2) # Draining: 2 Hz my_rpi.configureConnectDisconnectTimeout(10) # 10 sec my_rpi.configureMQTTOperationTimeout(5) # 5 sec my_rpi.connect() my_rpi.subscribe("sensors/rfid", 1, customCallback) sleep(2) while True: sleep(1)
class AWSInterface(): def __init__(self): parser = ConfigParser() parser.read('config_files/device.conf') self.host = parser.get('device', 'host') self.port = int(parser.get('device', 'port')) self.clientId = parser.get('device', 'deviceId') self.userId = parser.get('device', 'userId') self.topic = parser.get('device', 'topic') self.rootCAPath = parser.get('device', 'rootCAPath') self.privateKeyPath = parser.get('device', 'privateKeyPath') self.certificatePath = parser.get('device', 'certificatePath') self.growId = parser.get('grow', 'growId') parser.read('config_files/plant.conf') self.growStartDate = None self.growStartDate = None self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.clientId) self.myAWSIoTMQTTClient.configureEndpoint(self.host, self.port) self.myAWSIoTMQTTClient.configureCredentials(self.rootCAPath, self.privateKeyPath, self.certificatePath) self.myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) # Infinite offline Publish queueing self.myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) self.myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec cwd = os.getcwd() parent_dir = os.path.dirname(cwd) self.logger = logger_variable(__name__, 'log_files/AWSData.log') while True: try: self.logger.debug('Trying to connect to aws..') self.myAWSIoTMQTTClient.connect() except Exception as e: self.logger.warning('Not connected to aws..') self.logger.warning(e) print(e) print("Not connected...") print("retrying in 5 seconds....") time.sleep(5) continue else: self.logger.debug('connected to aws..') print("connected...") break def receiveData(self, topic, func): self.logger.debug( 'subscribed to topic -- %s, activated callback function %s', topic, func) self.myAWSIoTMQTTClient.subscribe(topic, 1, func) def sendData(self, data): packet = self.makePacket(data) try: self.logger.debug('Trying to send data to aws..') self.myAWSIoTMQTTClient.publish(self.topic, packet, 1) except Exception as e: self.logger.warning('packet send to aws failed..') self.logger.warning(e) self.logger.debug('packet sending into queue here after') print(e) print("packet sending failed...") print("packet sending into queue here after....") else: self.logger.debug('packet sent to aws sucessfull') print("packet sent successfully...") def makePacket(self, data): packet = {} packet['device_id'] = self.clientId packet['user_id'] = self.userId packet['time_stamp'] = str(datetime.datetime.now()) packet['sensor_data'] = data['sensor'] packet['grow_id'] = self.growId packet['time_from_start'] = str(datetime.date.today() - self.growStartDate) packet['actuator_data'] = data['actuator'] iotPacket = json.dumps(packet) return iotPacket def sendCameraData(self): img = open('sample.jpg', 'rb').read() payload = { 'user_id': self.userId, 'device_id': self.clientId, 'device_type': "aeroasis_device", 'media': base64.b64encode(img).decode() } url = "https://r65hlx6e9a.execute-api.us-west-2.amazonaws.com/beta/upload-image" r = requests.post(url, data=json.dumps(payload)) response = r.json() if response['statusCode'] == 200: self.logger.debug(response['status']) self.logger.debug('uploaded image name %s', response['image_name']) else: self.logger.error('Image upload failed') self.logger.error(response) return def strtoDate(date): ''':type date: str :rtype: status: datetime.timedelta''' date = [int(x) for x in date.split('-')] formatted_date = datetime.date(date[0], date[1], date[2]) return formatted_date
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(10) # 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) #TIME_STAMP = np.rand(100000) #for i in range(25000): # TIME_STAMP[i] = 1/100000 * i # Publish to the same topic in a loop forever def main():
class BpiController: def __init__(self): self.__host = 'axt811sti1q4w-ats.iot.us-east-2.amazonaws.com' self.__rootCA = '../certs/root-CA.crt' self.__certPem = '../certs/bpiController.cert.pem' self.__privateKey = '../certs/bpiController.private.key' self.__port = 8883 self.__clientId = 'bpiControllerDevice' self.__thingName = 'bpiController' self.__thingType = 'Gateway' self.mqttClient = None self.basicMqttClient = None self.deviceShadowHandler = None # 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 AWSIoTMQTTShadowClient self.mqttClient = AWSIoTMQTTShadowClient(self.__clientId) self.mqttClient.configureEndpoint(self.__host, self.__port) self.mqttClient.configureCredentials(self.__rootCA, self.__privateKey, self.__certPem) # AWSIoTMQTTShadowClient configuration self.mqttClient.configureAutoReconnectBackoffTime(1, 32, 20) self.mqttClient.configureConnectDisconnectTimeout(10) # 10 sec self.mqttClient.configureMQTTOperationTimeout(5) # 5 sec def mqttConnect(self): # Connect to AWS IoT self.mqttClient.connect() # Create a deviceShadow with persistent subscription self.deviceShadowHandler = self.mqttClient.createShadowHandlerWithName(self.__thingName, True) return self.deviceShadowHandler def shadowUpdate(self, json_data): self.deviceShadowHandler.shadowUpdate(json.dumps({ 'state': { 'reported': json_data } }), self.shadowUpdateCallback, 5) def reportHistory(self, json_data): if not isinstance(self.basicMqttClient, AWSIoTMQTTClient): print('Create AWSIoTMQTTClient') self.basicMqttClient = AWSIoTMQTTClient('bpiControllerReporter') self.basicMqttClient.configureEndpoint(self.__host, self.__port) self.basicMqttClient.configureCredentials(self.__rootCA, self.__privateKey, self.__certPem) self.basicMqttClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing self.basicMqttClient.configureDrainingFrequency(2) # Draining: 2 Hz self.basicMqttClient.configureConnectDisconnectTimeout(10) # 10 sec self.basicMqttClient.configureMQTTOperationTimeout(5) # 5 sec self.basicMqttClient.connect() topic = '@sensor.live/thing_types/%s/things/%s/history' % (self.__thingType, self.__thingName) self.basicMqttClient.publish(topic, json.dumps(json_data), 0) # Shadow callback def shadowUpdateCallback(self, payload, responseStatus, token): # payload is a JSON string ready to be parsed using json.loads(...) # in both Py2.x and Py3.x if responseStatus == 'timeout': print('Update request ' + token + ' time out!') if responseStatus == 'accepted': payloadDict = json.loads(payload) print('~~~~~~~~~~~~~~~~~~~~~~~') print('Update request with token: ' + token + ' accepted!') # print('property: ' + str(payloadDict)) print('~~~~~~~~~~~~~~~~~~~~~~~\n\n') if responseStatus == 'rejected': print('Update request ' + token + ' rejected!') # Shadow delete callback def shadowDeleteCallback(self, payload, responseStatus, token): if responseStatus == 'timeout': print('Delete request ' + token + ' time out!') if responseStatus == 'accepted': print('~~~~~~~~~~~~~~~~~~~~~~~') print('Delete request with token: ' + token + ' accepted!') print('~~~~~~~~~~~~~~~~~~~~~~~\n\n') if responseStatus == 'rejected': print('Delete request ' + token + ' rejected!') # Listen on deltas def listenDeltaCallback(self, callback): if self.deviceShadowHandler is not None: self.deviceShadowHandler.shadowRegisterDeltaCallback(callback) else: raise Exception('deviceShadowHandler is None')
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 AWSIoTUpdater(object): def __init__(self, config): self.root_ca = config['aws_iot']['certs']['root_ca'] self.priv_key = config['aws_iot']['certs']['priv_key'] self.cert = config['aws_iot']['certs']['cert'] self.endpoint = config['aws_iot']['endpoint'] self.client_id = config['aws_iot']['client'] self.topic = config['aws_iot']['topic'] self.room = config['sensor_location'] self.measurement = config['aws_iot']['measurement_name'] self.client = None self.queue = Queue.Queue() self.process_thread = threading.Thread(target=self.process) self.halt_event = threading.Event() # Counter - only take the 10th reading self.discard_count = 0 self.discard_every = 10 def process(self): while not self.halt_event.isSet(): try: reading = self.queue.get(timeout=1) self.discard_count += 1 # Only send every 10th message if self.discard_count > self.discard_every: self.discard_count = 0 payload = {"room": self.room, self.measurement: reading} logger.info("Deliver: %s", payload) try: result = self._publish(payload) logger.info("Delivery result: %s", result) except Exception, ex: print ex except Queue.Empty: pass def connect(self): self.client = AWSIoTMQTTClient(self.client_id) self.client.configureCredentials(self.root_ca, self.priv_key, self.cert) self.client.configureEndpoint(self.endpoint, 8883) # Setup params self.client.configureAutoReconnectBackoffTime(1, 32, 20) self.client.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing self.client.configureDrainingFrequency(2) # Draining: 2 Hz self.client.configureConnectDisconnectTimeout(10) # 10 sec self.client.configureMQTTOperationTimeout(5) # 5 sec # Connect self.client.connect() def _publish(self, payload): outgoing_payload = json.dumps(payload) return self.client.publish(self.topic, outgoing_payload, 1) def disconnect(self): self.client.disconnect() def prepare(self): self.connect() self.process_thread.start() def stop(self): self.halt_event.set() self.process_thread.join() self.disconnect()
class Notify: def __init__(self, config): self.clientId = "Waterer" self.__host = config['host'] self.__port = config['port'] self.__rootCAPath = config['rootCAPath'] self.__privateKeyPath = config['privateKeyPath'] self.__certificatePath = config['certificatePath'] self.topic = "water" self.pumpIsEnabled = True self.sequence = 0 # initialize self.client = AWSIoTMQTTClient(self.clientId) self.client.configureEndpoint(self.__host, self.__port) self.client.configureCredentials(self.__rootCAPath, self.__privateKeyPath, self.__certificatePath) # AWSIoTMQTTClient connection configuration self.client.configureAutoReconnectBackoffTime(1, 32, 20) # Infinite offline Publish queueing self.client.configureOfflinePublishQueueing(-1) self.client.configureDrainingFrequency(2) # Draining: 2 Hz self.client.configureConnectDisconnectTimeout(10) # 10 sec self.client.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT def waterCallback(self, client, userdata, message): print("Received a new message: ") print(message.payload) print("from topic: ") print(message.topic) print("--------------\n\n") # TODO - disable pump from MQTT message def connect(self): self.client.connect() self.client.subscribe(self.topic, 1, self.waterCallback) # Publish def notifyDry(self): print("Sending dry notification to cloud.") message = {} message['message'] = "Dry" message['time'] = datetime.now().__str__() message['sequence'] = self.sequence self.sequence += 1 messageJson = json.dumps(message) self.client.publish(self.topic, messageJson, 1) def notifyWatering(self): print("Sending watering notification to cloud.") message = {} message['message'] = "Watering" message['time'] = datetime.now().__str__() message['sequence'] = self.sequence self.sequence += 1 messageJson = json.dumps(message) self.client.publish(self.topic, messageJson, 1) def disablePump(self, reason): print("Sending pump disabled notification to cloud for reason: ", reason, ".") self.pumpIsEnabled = False message = {} message['message'] = "Pump Disabled" message['reason'] = reason message['time'] = datetime.now().__str__() message['sequence'] = self.sequence self.sequence += 1 messageJson = json.dumps(message) self.client.publish(self.topic, messageJson, 1) def enablePump(self): print("Sending pump enabled notification to cloud.") self.pumpIsEnabled = True message = {} message['message'] = "Pump Enabled" message['time'] = datetime.now().__str__() message['sequence'] = self.sequence self.sequence += 1 messageJson = json.dumps(message) self.client.publish(self.topic, messageJson, 1)
def configure(topic="sdk/test/Python"): """AWS configuration """ AllowedActions = ['both', 'publish', 'subscribe'] # Read in command-line parameters parser = argparse.ArgumentParser() parser.add_argument("-e", "--endpoint", action="store", required=True, dest="host", help="Your AWS IoT custom endpoint") parser.add_argument("-r", "--rootCA", action="store", required=True, dest="rootCAPath", help="Root CA file path") parser.add_argument("-c", "--cert", action="store", dest="certificatePath", help="Certificate file path") parser.add_argument("-k", "--key", action="store", dest="privateKeyPath", help="Private key file path") parser.add_argument("-p", "--port", action="store", dest="port", type=int, help="Port number override") parser.add_argument("-w", "--websocket", action="store_true", dest="useWebsocket", default=False, help="Use MQTT over WebSocket") parser.add_argument("-id", "--clientId", action="store", dest="clientId", default="basicPubSub", help="Targeted client id") parser.add_argument("-t", "--topic", action="store", dest="topic", default="sdk/test/Python", help="Targeted topic") parser.add_argument("-m", "--mode", action="store", dest="mode", default="both", help="Operation modes: %s" % str(AllowedActions)) parser.add_argument("-M", "--message", action="store", dest="message", default="Hello World!", help="Message to publish") args = parser.parse_args() host = args.host rootCAPath = args.rootCAPath certificatePath = args.certificatePath privateKeyPath = args.privateKeyPath port = args.port useWebsocket = args.useWebsocket clientId = args.clientId # topic = args.topic topic = topic if args.mode not in AllowedActions: parser.error("Unknown --mode option %s. Must be one of %s" % (args.mode, str(AllowedActions))) exit(2) if args.useWebsocket and args.certificatePath and args.privateKeyPath: parser.error( "X.509 cert authentication and WebSocket are mutual exclusive. Please pick one." ) exit(2) if not args.useWebsocket and (not args.certificatePath or not args.privateKeyPath): parser.error("Missing credentials for authentication.") exit(2) # Port defaults if args.useWebsocket and not args.port: # When no port override for WebSocket, default to 443 port = 443 if not args.useWebsocket and not args.port: # When no port override for non-WebSocket, default to 8883 port = 8883 # Configure logging logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) # Init AWSIoTMQTTClient myAWSIoTMQTTClient = None if useWebsocket: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect() if args.mode == 'both' or args.mode == 'subscribe': myAWSIoTMQTTClient.subscribe(topic, 1, Argument.customCallback) time.sleep(2) return args, myAWSIoTMQTTClient, topic
# -*- 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)
import signal import time continue_reading = True myclient = AWSIoTMQTTClient("harry") myclient.configureEndpoint("a3t3pe4wp4iz6-ats.iot.us-east-1.amazonaws.com", 8883) myclient.configureCredentials( "/home/pi/Desktop/final-project/aws_new/AmazonRootCA1.pem", "/home/pi/Desktop/final-project/aws_new/818af5f799-private.pem.key", "/home/pi/Desktop/final-project/aws_new/818af5f799-certificate.pem.crt") myclient.configureAutoReconnectBackoffTime(1, 32, 20) myclient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myclient.configureDrainingFrequency(2) # Draining: 2 Hz myclient.configureConnectDisconnectTimeout(10) # 10 sec myclient.configureMQTTOperationTimeout(5) # 5 sec def end_read(signal, frame): global continue_reading print("Ctrl+C captured, ending read.") continue_reading = False GPIO.cleanup() # Hook the SIGINT signal.signal(signal.SIGINT, end_read) # Create an object of the class MFRC522 TAGRead = MFRC522.MFRC522()
def main(): logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) args = parse_args() if args.region: region_name = args.region else: region_name = get_region() if args.domain: domain_name = args.domain else: domain_name = "prod" if args.cp_endpoint_url: cp_endpoint_url = args.cp_endpoint_url else: cp_endpoint_url = get_cp_endpoint_url(domain=domain_name, region=region_name) session = boto3.session.Session(region_name=region_name) if args.name: client_id = args.name else: client_id = ( get_client_id() ) # This will set the client-id based on the ec2 instance id if not client_id: logging.info("Failed to determine client_id, quitting") exit(1) logging.info( "Running agent with domain: {}, region: {}, clientId: {}, cp_endpoint_url: {}".format( domain_name, region_name, client_id, cp_endpoint_url ) ) ca_cert_file = get_root_ca() if args.mqtt_endpoint: mqtt_endpoint = args.mqtt_endpoint else: logging.info("Attempting to retrieve Mqtt endpoint") mqtt_endpoint = get_mqtt_endpoint(session, cp_endpoint_url) logging.info("Using Mqtt endpoint: {}".format(mqtt_endpoint)) iot_client = AWSIoTMQTTClient(client_id, useWebsocket=True) iot_client.configureEndpoint(mqtt_endpoint, 443, region_name) credentials = session.get_credentials() iot_client.configureCredentials(ca_cert_file.name) iot_client.configureIAMCredentials( credentials.access_key, credentials.secret_key, credentials.token ) # AWSIoTMQTTClient connection configuration iot_client.configureAutoReconnectBackoffTime(1, 32, 20) iot_client.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing iot_client.configureDrainingFrequency(2) # Draining: 2 Hz iot_client.configureConnectDisconnectTimeout(30) iot_client.configureMQTTOperationTimeout(20) # 5 sec # Connect and subscribe to AWS IoT iot_client.connect() sleep(2) topic = "$aws/things/{}/defender/metrics/{}".format(client_id, "json") # Subscribe to the accepted/rejected topics to indicate status of published metrics reports # topic=subscribe_to_topic, callback=callback, QoS=1, iot_client.subscribe( topic="{}/accepted".format(topic), callback=ack_callback, QoS=1 ) iot_client.subscribe( topic="{}/rejected".format(topic), callback=ack_callback, QoS=1 ) start_metrics_collection( region_name=region_name, cp_endpoint_url=cp_endpoint_url, client_id=client_id, iot_client=iot_client, topic=topic, sample_rate=300, ) ca_cert_file.close()
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)
print('blinkers') myMQTT.publish('to_robot', send_to_robot('blinkers'), 1) else: pass return '', 204 @app.route('/response', methods=["POST"]) def response(): global response_from_robot if flask.request.form['button'] == 'voltage': print('voltage') myMQTT.publish('to_robot', send_to_robot('voltage'), 1) while response_from_robot == '': pass print('robot responded') response_from_robot = response_from_robot + ' volts' return flask.render_template('index.html', voltage=response_from_robot) response_from_robot = '' myMQTT = AWSIoTMQTTClient('Web') myMQTT.configureEndpoint('a111amujev1y9r.iot.us-west-2.amazonaws.com', 8883) myMQTT.configureCredentials('root-CA.crt', 'Web.private.pem.key', 'Web.certificate.pem.crt') myMQTT.configureOfflinePublishQueueing(-1) myMQTT.configureDrainingFrequency(2) myMQTT.configureConnectDisconnectTimeout(10) myMQTT.connect() myMQTT.subscribe('from_robot', 1, from_robot)
def startServer(muteoutput): global tv_listings_dict global tv_channels global tv_dict global mute mute = muteoutput if os.path.isfile('helpers/lineup.json'): with open('helpers/lineup.json') as json_data: tv_json = json.load(json_data) for chan in tv_json: tv_channels.append(chan[0]) tv_channels.append(chan[1]) tv_listings_dict[chan[0]] = chan tv_listings_dict[chan[1]] = chan else: tv_channels = [] tv_listings_dict = {} if 'wpvi' in tv_channels: tv_channels.append('abc') tv_listings_dict['abc'] = tv_listings_dict['wpvi'] if 'wtxf' in tv_channels: tv_channels.append('fox') tv_listings_dict['fox'] = tv_listings_dict['wtxf'] for tv in tvconfig.tvs: tv_dict[tv['tv_mac_address']] = tv clientid = prefHelper.deviceUUID() myMQTTClient = AWSIoTMQTTClient(clientid) myMQTTClient.configureEndpoint("afkx1f9takwol.iot.us-east-1.amazonaws.com", 8883) myMQTTClient.configureCredentials(".auth/root.pem", ".auth/private.pem.key", ".auth/certificate.pem.crt") myMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec print('starting server...') myMQTTClient.connect() myMQTTClient.subscribe("power/" + clientid, 1, power) myMQTTClient.subscribe("channel/" + clientid, 1, channel) myMQTTClient.subscribe("speaker/" + clientid, 1, speaker) myMQTTClient.subscribe("playback/" + clientid, 1, playback) #myMQTTClient.unsubscribe("myTopic") #myMQTTClient.disconnect() print('server running. Pres CTRL + C to stop') counter = 0 while True: time.sleep(1) if counter == 0: payload = {"uuid": prefHelper.deviceUUID()} headers = { 'content-type': 'application/json', 'jwt': prefHelper.deviceToken() } try: response = requests.post('https://alexasmarttv.tk/api/v1/ping', data=json.dumps(payload), headers=headers) except: print('failed to ping') counter += 1 counter = counter % 900
class CommunicationHandler(): """ This class handles the communication to AWS. Attributes: -mqtt_client - the client used to connect to AWS -initalized - used for testing """ def __init__(self, ENDPOINT, CA, CERT, PRIVATE_KEY): """ This method initializes the CommunicationHandler class with the MQTT client and handles errors on client creation. Args: -self -ENDPOINT - The endpoint for AWS Connection for IOT -CA - Certification Info for AWS -CERT - Certificate details for AWS -PRIVATE KEY - Private Key for AWS """ try: print("test") self.mqtt_client = AWSIoTMQTTClient("client") self.mqtt_client.configureEndpoint(ENDPOINT, 8883) self.mqtt_client.configureCredentials(CA, PRIVATE_KEY, CERT) self.mqtt_client.configureOfflinePublishQueueing(-1) self.mqtt_client.configureDrainingFrequency(2) self.mqtt_client.configureConnectDisconnectTimeout(10) self.mqtt_client.configureMQTTOperationTimeout(5) self.initilized = True except FailedToCreateMQTTConnection: print("Error: MQTTClient Construction Failed.") self.initilized = False def send_payload(self, data): """ Handles the sending of the data to AWS in a Json format. Args: -self - this object -data - the object that is to be formated into a json (will be gps data) Attributes: -PAYLOAD - the json object that is sent to aws """ if data in("", '', None): print("Error: Message Empty.") return False payload = {"deviceid": getSerial(), "data":data} try: self.mqtt_client.connect() self.mqtt_client.publish("pi", payload, 0) print("Publish Success.") return True except FailedToSendError: print("Publish Failed.") return False ##https://www.raspberrypi-spy.co.uk/2012/09/getting-your-raspberry-pi-serial-number-using-python/ def getSerial(): cpuserial = "0000000000000000" try: f = open('/proc/cpuinfo','r') for line in f: if line[0:6]=='Serial': cpuserial = line[10:26] f.close() except: cpuserial = "ERROR000000000"
def main(): parser = argparse.ArgumentParser() AllowedActions = ['both', 'publish', 'subscribe'] parser.add_argument("-l", "--logging", action="store", dest="logging_level", help="Set logging level for MQ", default="info") parser.add_argument( "-b", "--batch_messages", action="store", dest="batch_messages", help= "Set batching of messages instead of sending single lines. Give batch size in bytes", default="0") parser.add_argument("-e", "--endpoint", action="store", required=True, dest="host", help="Your AWS IoT custom endpoint") parser.add_argument("-r", "--rootCA", action="store", required=True, dest="rootCAPath", help="root_ca.pem") parser.add_argument("-c", "--cert", action="store", dest="certificatePath", help="aa6562034b-certificate.pem.crt") parser.add_argument("-k", "--key", action="store", dest="privateKeyPath", help="aa6562034b-private.pem.key") parser.add_argument("-p", "--port", action="store", dest="port", type=int, help="Port number override") parser.add_argument("-id", "--clientId", action="store", dest="clientId", default="serial-data-simulator", help="Targeted client id") parser.add_argument( "-t", "--topic", action="store", dest="topic", default="rules/DataToDynamo/teknoware/telemetry/RaspberryPI3", help="Targeted topic") parser.add_argument("-m", "--mode", action="store", dest="mode", default="both", help="Operation modes: %s" % str(AllowedActions)) args = parser.parse_args() if not args.certificatePath or not args.privateKeyPath: parser.error("Missing credentials for authentication.") exit(2) level = LEVELS.get(args.logging_level, logging.NOTSET) logging.basicConfig(level=level) logging.debug('Using debug logging ...') logging.info('Using info logging ...') AWSIotClient = AWSIoTMQTTClient(args.clientId) AWSIotClient.configureEndpoint(args.host, args.port) AWSIotClient.configureCredentials(args.rootCAPath, args.privateKeyPath, args.certificatePath) AWSIotClient.configureAutoReconnectBackoffTime(1, 32, 20) AWSIotClient.configureOfflinePublishQueueing( 4, 0) # Infinite offline Publish queueing AWSIotClient.configureDrainingFrequency(2) # Draining: 2 Hz AWSIotClient.configureConnectDisconnectTimeout(10) # 10 sec AWSIotClient.configureMQTTOperationTimeout(5) # 5 sec serialData = SerialData() serialDataConsumer = SerialDataConsumer( amqp_url='amqp://*****:*****@localhost:5672/%2F', iot_client=AWSIotClient, target_topic=args.topic, serial_data=serialData, batch_messages=args.batch_messages) try: logging.info('Establishing AWS IoT Connection ...') AWSIotClient.connect() if args.mode == 'both' or args.mode == 'subscribe': AWSIotClient.subscribe( args.topic, 1, serialDataConsumer.on_iot_client_message_received) time.sleep(2) # TODO: ensure the connection by using callbacks serialDataConsumer.run() except KeyboardInterrupt: serialDataConsumer.stop()
print("--------------\n\n") # Init AWSIoTMQTTClient # aws_mqtt_client = None aws_mqtt_client = AWSIoTMQTTClient(client_id) aws_mqtt_client.configureEndpoint(iot_endpoint, port) aws_mqtt_client.configureCredentials( root_ca_path, private_key_path, certificate_path) # AWSIoTMQTTClient connection configuration aws_mqtt_client.configureAutoReconnectBackoffTime(1, 32, 20) # Infinite offline Publish queueing aws_mqtt_client.configureOfflinePublishQueueing(-1) aws_mqtt_client.configureDrainingFrequency(2) # Draining: 2 Hz aws_mqtt_client.configureConnectDisconnectTimeout(10) # 10 sec aws_mqtt_client.configureMQTTOperationTimeout(5) # 5 sec # # Connect and subscribe to AWS IoT aws_mqtt_client.connect() # aws_mqtt_client.subscribe(topic_name, 1, customCallback) # time.sleep(2) def random_measure(max, min, current): var = round(random.uniform(-1, 1), 2) value = round(current + var, 2) if value >= max: value = value - 0.5
mqtt_config = config['MQTT'] mqtt.configureEndpoint(mqtt_config.get('Host'), mqtt_config.getint('Port')) mqtt.configureCredentials(mqtt_config['Root Certificate'], mqtt_config['Private Key Path'], mqtt_config['Certificate Path']) # Set MQTT Configuration mqtt.configureAutoReconnectBackoffTime( 1, 32, 20) # 1 Second (Auto Reconnect), 32 Seconds (Back-off), 20 (Stable) mqtt.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing mqtt.configureDrainingFrequency(2) # Draining: 2 Hz mqtt.configureConnectDisconnectTimeout(10) # 10 sec mqtt.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT mqtt.connect() mqtt.subscribe(actionsTopic, 1, actions_callback) print('Connected to MQTT') # Start Alarm Thread alarm.start() print('Started Alarm Thread') # Open Driver File to set Task IOCTL_TASK_SET = ord('a') << (4 * 2) | 0 file = open('/dev/door_device', "r") fcntl.ioctl(file, IOCTL_TASK_SET, 0)
class MQTTClient: myAWSIoTMQTTClient = None def __init__(self, clientId, topic, host, rootCA, crtPath, privateKey, port): self.clientId = clientId self.topic = topic self.host = host self.rootCA = rootCA self.crtPath = crtPath self.privateKey = privateKey self.port = port # Custom MQTT message callback def customCallback(client, userdata, message): print("Received a new message: ") print(message.payload) print("from topic: ") print(message.topic) print("--------------\n\n") def ConfigureLogging(): logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) def InitClient(self): self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.clientId) self.myAWSIoTMQTTClient.configureEndpoint(self.host, self.port) self.myAWSIoTMQTTClient.configureCredentials(self.rootCA, self.privateKey, self.crtPath) # AWSIoTMQTTClient connection configuration self.myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) self.myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing self.myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT self.myAWSIoTMQTTClient.connect() time.sleep(2) def PublishJsonPayload(self, payload): self.myAWSIoTMQTTClient.publish(self.topic, payload, 1) print('Published topic %s: %s\n' % (self.topic, payload)) def StartPublish(self): # Publish to the same topic in a loop forever loopCount = 0 while True: message = {} message['device'] = "window_lars" message['timestamp'] = str(int(round(time.time() * 1000))) message['aq'] = "2" messageJson = json.dumps(message) self.myAWSIoTMQTTClient.publish(self.topic, messageJson, 1) print('Published topic %s: %s\n' % (self.topic, messageJson)) loopCount += 1 time.sleep(1)
class PingService(): def __init__(self): # Read in command-line parameters parser = argparse.ArgumentParser() parser.add_argument( "-e", "--endpoint", action="store", default="a3cezb6rg1vyed-ats.iot.us-west-2.amazonaws.com", dest="host", help="Your AWS IoT custom endpoint") parser.add_argument("-r", "--rootCA", action="store", default="{}/root-CA.crt".format(PATH_TO_HOME), dest="rootCAPath", help="Root CA file path") parser.add_argument( "-c", "--cert", action="store", default="{}/PL-student.cert.pem".format(PATH_TO_HOME), dest="certificatePath", help="Certificate file path") parser.add_argument( "-k", "--key", action="store", default="{}/PL-student.private.key".format(PATH_TO_HOME), dest="privateKeyPath", help="Private key file path") parser.add_argument("-p", "--port", action="store", dest="port", type=int, help="Port number override") parser.add_argument("-w", "--websocket", action="store_true", dest="useWebsocket", default=False, help="Use MQTT over WebSocket") parser.add_argument("-id", "--clientId", action="store", dest="clientId", default="pl19-99", help="Targeted client id") parser.add_argument("-t", "--topic", action="store", dest="topic", default="pl19/event", help="Event topic") parser.add_argument("-m", "--mode", action="store", dest="mode", default="both", help="Operation modes: %s" % str(AllowedActions)) parser.add_argument("-M", "--message", action="store", dest="message", default="Hello World!", help="Message to publish") args = parser.parse_args() self.host = args.host self.rootCAPath = args.rootCAPath self.certificatePath = args.certificatePath self.privateKeyPath = args.privateKeyPath self.port = args.port self.useWebsocket = args.useWebsocket self.clientId = args.clientId self.topic = args.topic if args.mode not in AllowedActions: parser.error("Unknown --mode option %s. Must be one of %s" % (args.mode, str(AllowedActions))) exit(2) if args.useWebsocket and args.certificatePath and args.privateKeyPath: parser.error( "X.509 cert authentication and WebSocket are mutual exclusive. Please pick one." ) exit(2) if not args.useWebsocket and (not args.certificatePath or not args.privateKeyPath): parser.error("Missing credentials for authentication.") exit(2) # Port defaults if args.useWebsocket and not args.port: # When no port override for WebSocket, default to 443 self.port = 443 if not args.useWebsocket and not args.port: # When no port override for non-WebSocket, default to 8883 self.port = 8883 # Configure logging streamHandler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) # Init AWSIoTMQTTClient self.mqtt_client = None self.mqtt_client = AWSIoTMQTTClient(self.clientId) self.mqtt_client.configureEndpoint(self.host, self.port) self.mqtt_client.configureCredentials(self.rootCAPath, self.privateKeyPath, self.certificatePath) # AWSIoTMQTTClient connection configuration self.mqtt_client.configureAutoReconnectBackoffTime(1, 32, 20) self.mqtt_client.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing self.mqtt_client.configureDrainingFrequency(2) # Draining: 2 Hz self.mqtt_client.configureConnectDisconnectTimeout(10) # 10 sec self.mqtt_client.configureMQTTOperationTimeout(5) # 5 sec def start(self): self.mqtt_client.connect() self.mqtt_client.subscribe("pl19/notification", 1, self.customCallback) time.sleep(2) while True: time.sleep(5) def replyToPing(self, sequence): pingData = {} pingData['sequence'] = sequence pingData['message'] = "Ping response." message = {} message['device_mac'] = "b8:27:eb:f1:96:c4" message['timestamp'] = str(datetime.datetime.now()) message['event_id'] = 1 message['event'] = pingData messageJson = json.dumps(message) self.mqtt_client.publishAsync("pl19/event", messageJson, 1) print('Published topic %s: %s\n' % (self.topic, messageJson)) # Custom MQTT message callback def customCallback(self, client, userdata, message): print("Received a new message: ") messageContent = json.loads(message.payload.decode('utf-8')) messageData = messageContent['event'] print(messageContent) print(messageData['message']) print("Sequence ", messageData['sequence']) print("from topic: ") print(message.topic) print("--------------\n\n") if messageContent['event_id'] == 0: self.replyToPing(messageData['sequence'])
logger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) # AWS IoT client initialization ... thing = AWSIoTMQTTClient(config['client_id']) thing.configureEndpoint(config['endpoint'], config['port']) thing.configureCredentials(config['root_ca_path'], config['private_key_path'], config['cert_path']) thing.configureOfflinePublishQueueing(-1) thing.configureDrainingFrequency(2) thing.configureConnectDisconnectTimeout(10) thing.configureMQTTOperationTimeout(5) try: thing.connect() thing.subscribe(config['topic'], 1, doors_callback) while True: """ I'm loop """ except KeyboardInterrupt: print("Cleaning up GPIO") GPIO.cleanup() thing.unsubscribe(config['topic']) finally:
class subscriber_actor: iot_mqtt_client = None QOS_LEVEL = 1 def __init__(self): self.iot_mqtt_client = AWSIoTMQTTClient(pfc_conf.PFC_AWS_IOT_CLIENT_ID) self.iot_mqtt_client.configureEndpoint(pfc_mqtt_topic.AWS_ENDPOINT, 8883) self.iot_mqtt_client.configureCredentials(pfc_conf.CA_PATH, pfc_conf.PRIVATE_KEY_PATH, pfc_conf.CERTIFICATE_PATH) self.iot_mqtt_client.configureAutoReconnectBackoffTime(1, 32, 20) self.iot_mqtt_client.configureOfflinePublishQueueing(-1) self.iot_mqtt_client.configureDrainingFrequency(2) self.iot_mqtt_client.configureConnectDisconnectTimeout(10) self.iot_mqtt_client.configureMQTTOperationTimeout(5) def msg_callback(self, client, userdata, message): mes_pld = message.payload mes_tpc = message.topic 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 try: sensor_proc = subprocess.Popen( shlex.split("python " + command_pfc_sensor), stdout=subprocess.PIPE, stderr=subprocess.PIPE) timer = Timer(30, kill_proc, [sensor_proc]) timer.start() stdout, stderr = sensor_proc.communicate() except: f = open(pfc_conf.LOG_DIR_PATH + '/aws_subscribe.log', 'a+') f.write("[Sensor-PROCESS] Exception Occured") f.write('\n') f.close() 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()) } try: 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]) timer.start() stdout, stderr = pub_proc.communicate() except: f = open(pfc_conf.LOG_DIR_PATH + '/aws_subscribe.log', 'a+') f.write("[Sensor-Data-PROCESS] Exception Occured") f.write('\n') f.close() 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 try: actuator_proc = subprocess.Popen( shlex.split("python " + command_pfc_actuator), stdout=subprocess.PIPE, stderr=subprocess.PIPE) timer = Timer(30, kill_proc, [actuator_proc]) timer.start() stdout, stderr = actuator_proc.communicate() except: f = open(pfc_conf.LOG_DIR_PATH + '/aws_subscribe.log', 'a+') f.write("[Actuator-PROCESS] Exception Occured") f.write('\n') f.close() finally: timer.cancel() actuator_data = { 'DATA': stdout, 'PFC_SERIAL': str(pfc_conf.PFC_AWS_IOT_SERIAL), 'DEVICE_DT': str(datetime.now()) } try: 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]) timer.start() stdout, stderr = pub_proc.communicate() except: f = open(pfc_conf.LOG_DIR_PATH + '/aws_subscribe.log', 'a+') f.write("[Actuator-Data-PROCESS] Exception Occured") f.write('\n') f.close() finally: timer.cancel() else: print( "'TARGET' or 'ORDER' is not exists on the command_mapper") elif om_type == 'LOCAL_IP': try: pub_proc = subprocess.Popen( shlex.split( "python " + command_mapper.LOCAL_IP['LOCAL_IP']['LOCAL_IP'])) timer = Timer(30, kill_proc, [pub_proc]) timer.start() stdout, stderr = pub_proc.communicate() finally: timer.cancel() elif om_type == 'HEARTBEAT': try: pub_proc = subprocess.Popen( shlex.split( "python " + command_mapper.LOCAL_IP['HEARTBEAT']['BEATING'])) timer = Timer(30, kill_proc, [pub_proc]) 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'] try: pub_proc = subprocess.Popen( shlex.split("python " + command_pfc_data_lake)) timer = Timer(600, kill_proc, [pub_proc]) 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()) } try: 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]) timer.start() stdout, stderr = pub_proc.communicate() finally: timer.cancel() def subscribe_mqtt_broker(self): self.iot_mqtt_client.connect() self.iot_mqtt_client.subscribe(pfc_mqtt_topic.SUBSCRIBE_DEV, self.QOS_LEVEL, self.msg_callback) print("Subscribing topic : " + str(pfc_mqtt_topic.SUBSCRIBE_DEV)) while True: time.sleep(1) def logging(self): None
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
time.sleep(0.2) explorerhat.motor.stop() # Init AWSIoTMQTTClient awsClient = AWSIoTMQTTClient(clientId) awsClient.configureEndpoint(host, port) awsClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration awsClient.configureAutoReconnectBackoffTime(1, 32, 20) awsClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing awsClient.configureDrainingFrequency(2) # Draining: 2 Hz awsClient.configureConnectDisconnectTimeout(10) # 10 sec awsClient.configureMQTTOperationTimeout(5) # 5 sec awsClient.onMessage = handleMessage # Connect and subscribe to AWS IoT awsClient.connect() # Note that we are not putting a message callback here. We are using the general message notification callback. awsClient.subscribeAsync(topic, 1) time.sleep(2) # Start the Kinesis Video Gstreamer Sample App using IoT Credentials runKinesisVideoStream() time.sleep(1) while True: time.sleep(0.2)
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
qttClient.publish("arm/data", msg, 0) return 'sucess' else: return '?' @app.route('/rpt', methods=['POST']) def rpt(): req = request.values logging.info(str(req[0])) return 'Hello from POST!' import traceback PORT=9000 if __name__ == '__main__': try: qttClient = AWSIoTMQTTClient("PI_Ireland") endpoint = "a2mxpvymzj1qjd.iot.eu-west-1.amazonaws.com" qttClient.configureEndpoint(endpoint, 8883) root_ca = 'keys/root-CA.crt' p_key = 'keys/PI-Ireland-private.key' cert = 'keys/PI-Ireland-cert.pem' qttClient.configureCredentials(root_ca, p_key, cert) qttClient.configureConnectDisconnectTimeout(1000) # 1000 sec qttClient.connect() #qttClient.subscribe("AWS/Aarhus/traffic/alert", 0, customCallback) #app.run(debug=True, port=int(PORT)) app.run(debug=True, host='0.0.0.0', port=int(PORT)) except: traceback.print_exc()
# Init AWSIoTMQTTClient myAWSIoTMQTTClient = None if useWebsocket: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect() if args.mode == 'both' or args.mode == 'subscribe': myAWSIoTMQTTClient.subscribe(topic, 1, customCallback) time.sleep(2) # Publish to the same topic in a loop forever loopCount = 0 while True: if args.mode == 'both' or args.mode == 'publish': message = {} message['message'] = args.message message['sequence'] = loopCount
ROOT_CA_PATH = './AmazonRootCA1.pem' PRIVATE_KEY_PATH = './private.pem.key' CERTIFICATE_PATH = './certificate.pem.crt' # Create and Configure the IoT Client IoTclient = AWSIoTMQTTClient(CLIENT_NAME) IoTclient.configureEndpoint(BROKER_PATH, 8883) IoTclient.configureCredentials(ROOT_CA_PATH, PRIVATE_KEY_PATH, CERTIFICATE_PATH) # Allow the device to queue infinite messages IoTclient.configureOfflinePublishQueueing(-1) # Number of messages to send after a connection returns IoTclient.configureDrainingFrequency(2) # 2 requests/second # How long to wait for a [dis]connection to complete (in seconds) IoTclient.configureConnectDisconnectTimeout(10) # How long to wait for publish/[un]subscribe (in seconds) IoTclient.configureMQTTOperationTimeout(5) IoTclient.connect() IoTclient.publish(TOPIC, "connected", 0) # Create and Send Payloads to the IoT Topic def create_payload(): payload = json.dumps({ "id": int(time.time()), "read_date": str((datetime.now() - timedelta(hours=5)).strftime("%Y-%m-%d %H:%M:%S")),