def PublishMQTT(mailType, timeString="", timeStringCritical=""): ConnectWLAN(True) # Config MQTT mqttClient = AWSIoTMQTTClient(clientID) mqttClient.configureEndpoint(awsHost, awsPort) mqttClient.configureCredentials(awsRootCA, awsPrivateKey, awsClientCert) mqttClient.configureOfflinePublishQueueing(offlineQueueSize) mqttClient.configureConnectDisconnectTimeout(connectDisconnectTimeout) # Connect if mqttClient.connect(): print("MQTT connected") # Publish topic, AWS Lambda Python code uses the json to create mail title and body. mqttClient.publish( topic, json.dumps({ "mailType": str(mailType), "timeString": timeString, "timeStringCritical": timeStringCritical }), 0) # Disconnect if mqttClient.disconnect(): print("MQTT disconnected") ConnectWLAN(False) # Save variables to be loaded when waking up from deep sleep. Save() machine.deepsleep(deepSleepTime)
class AWS(object): """ AWS IoT communication with Pycom provided libraries """ def __init__(self): """ Initialization of AWS Class """ self.client = None self.is_connected = False def connect(self): """ Connect AWS IoT """ if self.client is None: # Configure the MQTT client self.client = AWSIoTMQTTClient(config.AWS_IOT_CLIENT_ID) self.client.configureEndpoint(config.AWS_IOT_HOST, config.AWS_IOT_PORT) self.client.configureCredentials(config.AWS_IOT_ROOT_CA, config.AWS_IOT_PRIVATE_KEY, config.AWS_IOT_CLIENT_CERT) self.client.configureOfflinePublishQueueing(config.AWS_IOT_OFFLINE_QUEUE_SIZE) self.client.configureDrainingFrequency(config.AWS_IOT_DRAINING_FREQ) self.client.configureConnectDisconnectTimeout(config.AWS_IOT_CONN_DISCONN_TIMEOUT) self.client.configureMQTTOperationTimeout(config.AWS_IOT_MQTT_OPER_TIMEOUT) # Connect to MQTT Host if self.client.connect(): self.is_connected = True log.info('AWS IoT connection succeeded') else: raise socket.error('AWS IoT connection failed') def publish(self, msg=None): """ Publish message """ log.info('Publish [{}]', json.dumps(msg)) self.client.publish(config.AWS_IOT_TOPIC, json.dumps(msg), 1) def disconnect(self): """ Disconnect AWS IoT """ if self.client: if self.client.disconnect(): log.info('AWS IoT disconnected') self.is_connected = False self.client = None