コード例 #1
0
class AwsIotMqtt(IotProvider):
    """
    Child class containing implementations of IotProvider specific to Amazon Web Services.
    """
    def onmsg(self, msg):
        # Wraps core event handler for incoming messages
        msg_payload = msg.payload
        super().onmsg(msg_payload)

    def connect(self):
        # A connection to iot is established at the beginning and if publish fails
        self.aws_iot_mqtt_comm = AWSIoTMQTTClient(f"{self.sm_name}_xqtive")
        self.aws_iot_mqtt_comm.onMessage = self.onmsg
        self.aws_iot_mqtt_comm.configureEndpoint(self.iot_broker,
                                                 self.iot_port)
        self.aws_iot_mqtt_comm.configureCredentials(self.iot_ca_cert_path,
                                                    self.iot_client_key_path,
                                                    self.iot_client_cert_path)
        self.aws_iot_mqtt_comm.connect()
        self.aws_iot_mqtt_comm.subscribe(self.subscribe_topic, 1, None)

    def disconnect(self):
        self.aws_iot_mqtt_comm.disconnect()

    def publish(self, publish_topic, msg_str, qos):
        self.aws_iot_mqtt_comm.publish(publish_topic, msg_str, QoS=qos)
コード例 #2
0
def sendMessage():
    while True :
        print("Send message")
        # For certificate based connection
        myMQTTClient = AWSIoTMQTTClient("dragon")
        # For Websocket connection
        # myMQTTClient = AWSIoTMQTTClient("myClientID", useWebsocket=True)
        # Configurations
        # For TLS mutual authentication
        myMQTTClient.configureEndpoint("a8mgf2amxmior.iot.us-east-2.amazonaws.com", 8883)
        # For Websocket
        # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443)
        myMQTTClient.configureCredentials("/home/linaro/Desktop/awsConnect/root-CA.crt", "/home/linaro/Desktop/awsConnect/dragon.private.key", "/home/linaro/Desktop/awsConnect/dragon.cert.pem")
        # For Websocket, we only need to configure the root CA
        # myMQTTClient.configureCredentials("YOUR/ROOT/CA/PATH")
        myMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
        myMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
        myMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
        myMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

        myMQTTClient.connect()
        myMQTTClient.publish("temp", readTempSense(), 0)
        myMQTTClient.publish("light", readLighSense(), 0)
        myMQTTClient.publish("earthquake", hasEarthQuake(), 0)            
        myMQTTClient.disconnect()
        sleep(5)
コード例 #3
0
class publisher_local_ip:
    iot_mqtt_client = None
    QOS_LEVEL = 1
    DEVICE_IP_ADDR = None

    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(20)

    def publish_mqtt_broker(self, messageJson, interval_sec=0):
        self.iot_mqtt_client.connect()
        if messageJson == None:
            print("Message Json not passed.")
            sys.exit()

        self.iot_mqtt_client.publish(pfc_mqtt_topic.PUBLISH_LOCAL_IP,
                                     messageJson, self.QOS_LEVEL)
        self.iot_mqtt_client.disconnect()

    def get_ip_addr(self, network):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.DEVICE_IP_ADDR = socket.inet_ntoa(
            fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',
                                                        network[:15]))[20:24])
        return self.DEVICE_IP_ADDR
コード例 #4
0
class publisher_sensor_data:
    IOT_MQTT_CLIENT = None
    QOS_LEVEL = 1

    def __init__(self, QOS_LEVEL=1):
        self.QOS_LEVEL = QOS_LEVEL
        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(20)

    def publish_mqtt_broker(self, topic, messageJson):
        if messageJson == None:
            print("Message is none.")
            sys.exit()
        elif "PFC_SERIAL" not in messageJson or "DEVICE_DT" not in messageJson:
            print("PFC_SERIAL, DEVICE_DT is a demandable.")
            sys.exit()

        mqtt_topic = pfc_mqtt_topic.PUBLISH_SENSOR

        self.IOT_MQTT_CLIENT.connect()
        self.IOT_MQTT_CLIENT.publish(mqtt_topic, messageJson, self.QOS_LEVEL)
        self.IOT_MQTT_CLIENT.disconnect()
        print("Published MQTT topic : " + str(topic))
コード例 #5
0
def broadcast(state):
    myMQTTClient = AWSIoTMQTTClient("Linux-laptop")

    myMQTTClient.configureEndpoint("avvvr84optu81.iot.us-west-2.amazonaws.com",
                                   8883)

    root_ca_path = "/home/akshat/.local/aws_device_cert/root-CA.crt"
    private_key_path = "/home/akshat/.local/aws_device_cert/Linux-laptop.private.key"
    certificate_path = "/home/akshat/.local/aws_device_cert/Linux-laptop.cert.pem"
    myMQTTClient.configureCredentials(root_ca_path, private_key_path,
                                      certificate_path)

    myMQTTClient.configureOfflinePublishQueueing(-1)
    myMQTTClient.configureDrainingFrequency(2)
    myMQTTClient.configureConnectDisconnectTimeout(10)
    myMQTTClient.configureMQTTOperationTimeout(5)

    def customCallback(client, userdata, message):
        print("Received a new message: ")
        print(message.payload)
        print("from topic: ")
        print(message.topic)
        print("--------------\n\n")

    myMQTTClient.connect()
    myMQTTClient.subscribe("spot/state", 1, customCallback)
    if (state == 0):
        data = {"state": {"reported": {"spot": "constant"}}}
    elif (state == 1):
        data = {"state": {"reported": {"spot": "entering"}}}
    elif (state == 2):
        data = {"state": {"reported": {"spot": "leaving"}}}
    myMQTTClient.publish("spot/state", json.dumps(data), 0)
    myMQTTClient.unsubscribe("ubuntu/clicker")
    myMQTTClient.disconnect()
コード例 #6
0
class pimqttClient:
    def __init__(self, mqttClient, endPoint):
        self.mqttClient = AWSIoTMQTTClient(mqttClient)
        self.mqttClient.configureEndpoint(endPoint, 8883)
        print("pimqttClient Initialization successfull ")

    def mqttConfigureCertificates(self):
        self.mqttClient.configureCredentials(
            "/home/pi/iot/python/root-CA.crt",
            "/home/pi/iot/python/pla_hackathon_raspberry_generic.private.key",
            "/home/pi/iot/python/pla_hackathon_raspberry_generic.cert.pem")

    def mqttConfiguration(self):
        self.mqttClient.configureOfflinePublishQueueing(
            -1)  # Infinite offline Publish queueing
        self.mqttClient.configureDrainingFrequency(2)  # Draining: 2 Hz
        self.mqttClient.configureConnectDisconnectTimeout(10)  # 10 sec
        self.mqttClient.configureMQTTOperationTimeout(5)  # 5 sec

    def mqttConnect(self):
        self.mqttClient.connect()
        print("pimqttClient Connection successfully ")

    def mqttSubscribe(self, topic, customCallback):
        self.mqttClient.subscribe(topic, 1, customCallback)

    def mqttunSubscribe(self, topic):
        self.mqttClient.unsubscribe(topic)

    def mqttPublish(self, topic, payload):
        self.mqttClient.publish(topic, payload, 0)

    def mqttDisconnect(self):
        self.mqttClient.disconnect()
        print("pimqttClient Disconnected successfully ")
コード例 #7
0
def publish(path):
    print("path is:" + path)
    print('start')
    # For certificate based connection
    myMQTTClient = AWSIoTMQTTClient(client)

    # For Websocket connection
    # myMQTTClient = AWSIoTMQTTClient("myClientID", useWebsocket=True)
    # Configurations
    # For TLS mutual authentication
    myMQTTClient.configureEndpoint(endpoint, 8883)
    # For Websocket
    # myShadowClient.configureEndpoint("YOUR.ENDPOINT", 443)

    myMQTTClient.configureCredentials(rootCA_path, private_path,
                                      certificate_path)
    # For Websocket, we only need to configure the root CA
    # myMQTTClient.configureCredentials("YOUR/ROOT/CA/PATH")

    myMQTTClient.configureOfflinePublishQueueing(
        -1)  # Infinite offline Publish queueing
    myMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
    myMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
    myMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

    print('connect')
    myMQTTClient.connect()
    print('cned')
    msg = "{\"url\":\"" + path + "\"}"
    print(msg)
    myMQTTClient.publish("test/pub", msg, 0)
    #print('pass')
    #myMQTTClient.subscribe("myTopic", 1, customCallback)
    #myMQTTClient.unsubscribe("myTopic")
    myMQTTClient.disconnect()
コード例 #8
0
def force_disconnect(client_id):
    print 'Attempting to force disconnect on client {}'.format(client_id)
    endpoint, endpoint_port = registration_shared.get_endpoint_and_port('WEBSOCKET')

    print 'Using endpoint {}:{}'.format(endpoint, endpoint_port)

    iot_client = AWSIoTMQTTClient(client_id, useWebsocket=True)
    iot_client.configureEndpoint(endpoint, endpoint_port)
    iot_client.configureConnectDisconnectTimeout(20)
    iot_client.configureMQTTOperationTimeout(5)
    iot_client.configureCredentials('AWSIoTPythonSDK/certs/rootCA.pem')

    access_key = os.environ.get('AWS_ACCESS_KEY_ID')
    secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
    session_token = os.environ.get('AWS_SESSION_TOKEN')
    iot_client.configureIAMCredentials(AWSAccessKeyID=access_key, AWSSecretAccessKey=secret_key, AWSSessionToken=session_token)

    print 'Configured credentials, attempting connect...'
    response = iot_client.connect()

    print 'Connect returns {}'.format(response)

    if response:
        print 'Disconnecting..'
        iot_client.disconnect()
コード例 #9
0
class pimqttClient:
    def __init__(self, mqttClient, endPoint):
        self.mqttClient = AWSIoTMQTTClient(mqttClient)
        self.mqttClient.configureEndpoint(endPoint, 8883)
        print("pimqttClient Initialization successfull ")

    def mqttConfigureCertificates(self, certpath):
        self.mqttClient.configureCredentials(
            "{}root-ca.pem".format(certpath),
            "{}cloud.pem.key".format(certpath),
            "{}cloud.pem.crt".format(certpath))

    def mqttConfiguration(self):
        self.mqttClient.configureOfflinePublishQueueing(
            -1)  # Infinite offline Publish queueing
        self.mqttClient.configureDrainingFrequency(2)  # Draining: 2 Hz
        self.mqttClient.configureConnectDisconnectTimeout(10)  # 10 sec
        self.mqttClient.configureMQTTOperationTimeout(5)  # 5 sec

    def mqttConnect(self):
        self.mqttClient.connect()
        print("pimqttClient Connection successfully ")

    def mqttSubscribe(self, topic, customCallback):
        self.mqttClient.subscribe(topic, 1, customCallback)

    def mqttunSubscribe(self, topic):
        self.mqttClient.unsubscribe(topic)

    def mqttPublish(self, topic, payload):
        self.mqttClient.publish(topic, payload, 0)

    def mqttDisconnect(self):
        self.mqttClient.disconnect()
        print("pimqttClient Disconnected successfully ")
コード例 #10
0
class MQTTClient:
    def __init__(self, client_id, host, root_ca, cert, key):
        self._client = AWSIoTMQTTClient(client_id)
        self._client.configureEndpoint(host, 8883)
        self._client.configureCredentials(root_ca, key, cert)
        self._client.configureAutoReconnectBackoffTime(1, 32, 20)
        self._client.configureOfflinePublishQueueing(-1)
        self._client.configureDrainingFrequency(2)
        self._client.configureConnectDisconnectTimeout(10)
        self._client.configureMQTTOperationTimeout(5)

    def subscribe(self, topic, callback):
        self._client.connect()
        self._client.subscribe(topic, 1, callback)

    def unsubscribe(self, topic):
        self._client.unsubscribe(topic)
        self._client.disconnect()

    def publish(self, topic, message):
        self._client.connect()
        message_d = {}
        message_d['message'] = message
        self._client.publish(topic, json.dumps(message_d), 1)
        self._client.disconnect()
コード例 #11
0
class IotConnection:
    def __init__(self):
        self.config = self._load_config('.vscode/config.json')

        self.logger = logging.getLogger('IotConnection')
        self.logger.setLevel(logging.DEBUG)
        self.myMQTTClient = AWSIoTMQTTClient(self.config['thingName'])
        self.myMQTTClient.configureEndpoint(self.config['hostUrl'], 8883)
        self.myMQTTClient.configureCredentials(
            self.config['caFilePath'], self.config['privateKeyFilePath'],
            self.config['certFilePath'])
        self.myMQTTClient.configureOfflinePublishQueueing(-1)
        self.myMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
        self.myMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
        self.myMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec
        self.myMQTTClient.connect()
        self.logger.debug('connection success')

    def publish(self, message):
        self.myMQTTClient.publish('iotCarTopic', json.dumps(message), 0)
        self.logger.debug('publish complete')

    def _load_config(self, config_file_path):
        with open(config_file_path) as f:
            config = json.load(f)

        return config

    def clean(self):
        self.logger.debug('clean START')
        self.myMQTTClient.disconnect()
        self.logger.debug('clean END')
コード例 #12
0
def sendMQTT(topicIndex, lightStatus):
    #Setting up MQTT Client
    myMQTTClient = AWSIoTMQTTClient("piPythonClientID")
    myMQTTClient.configureEndpoint("a1hd20ncaxgeuh.iot.us-east-1.amazonaws.com", 8883)
    myMQTTClient.configureCredentials("certs/piKeys/VeriSign-Class 3-Public-Primary-Certification-Authority-G5.pem",
                                        "certs/piKeys/12d0293db7-private.pem.key", "certs/piKeys/12d0293db7-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

    #get info from arguments to determine whether to turn on/off light and on which board
    topicIndex =  topicIndex          #int(sys.argv[1])
    lightStatus = lightStatus          #int(sys.argv[2]) % 2
    topics = ["mbed/put/mbed-endpoint/43e34372-64af-4946-a448-546905a29b88/311/0/5850","sdk/test"]
    topic = topics[topicIndex]
    topicEndpoints = ["43e34372-64af-4946-a448-546905a29b88/311/0/5850","43e34372-64af-4946-a448-546905a29b88"]

    payload = {}
    payload['path'] = "/311/0/5850"
    payload['ep'] = topicEndpoints[1]
    payload['new_value'] = lightStatus
    payload['coap_verb'] = 'put'
    payloadJson = json.dumps(payload)
    #print(payloadJson)

    #Connecting to MQTT Server
    myMQTTClient.connect()
    myMQTTClient.publish(topic, payloadJson, 1)
    myMQTTClient.disconnect()
    print("Sent MQTT Message")
コード例 #13
0
def publishAndWaitForResponse(request):
    global tempData
    tempData = json.dumps(ENDPOINT_UNREACHABLE)

    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)

    client = None
    client = AWSIoTMQTTClient(clientId)
    client.configureEndpoint(host, 8883)
    client.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

    client.configureAutoReconnectBackoffTime(1, 32, 20)
    client.configureOfflinePublishQueueing(-1)
    client.configureDrainingFrequency(2)
    client.configureConnectDisconnectTimeout(10)
    client.configureMQTTOperationTimeout(5)

    client.connect()
    client.subscribe("things/" + clientId + "/response", 1, responseCallback)
    client.publish("things/" + clientId, json.dumps(request),
                   0)  # Replace test text with request
    time.sleep(0.75)
    client.disconnect()
    return tempData
コード例 #14
0
class EventProcessor:
    def __init__(self):
        self._measured = False
        self.done = False
        self._measureCnt = 0
        self._events = range(WEIGHT_SAMPLES)
        self.bottles = 0
        self.weightprevious = 0
        self._bottlesPrev = -1
        self.setIOT()

    def setIOT(self):
        self.myMQTTClient = AWSIoTMQTTClient(CLIENT_ID)
        self.myMQTTClient.configureEndpoint(END_POINT, 8883)
        # For Websocket
        # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443)
        self.myMQTTClient.configureCredentials(CA_PATH, PRIVATE_PATH,
                                               CERT_PATH)
        # For Websocket, we only need to configure the root CA
        # myMQTTClient.configureCredentials("YOUR/ROOT/CA/PATH")
        self.myMQTTClient.configureOfflinePublishQueueing(
            -1)  # Infinite offline Publish queueing
        self.myMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
        self.myMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
        self.myMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

    def mass(self, event):
        if (event.totalWeight > 1):
            self._events[self._measureCnt] = event.totalWeight * 2.20462
            self._measureCnt += 1
            if self._measureCnt == WEIGHT_SAMPLES:
                self._sum = 0
                for x in range(0, WEIGHT_SAMPLES - 1):
                    self._sum += self._events[x]
                self._weight = self._sum / WEIGHT_SAMPLES
                self._measureCnt = 0
                print str(self._weight) + " lbs"
                if (self.weightprevious != 0):
                    self.sendBeerChange(self._weight, self.weightprevious)
                else:
                    self.weightprevious = self._weight
            if not self._measured:
                self._measured = True

    def sendBeerChange(self, weight, weightprevious):
        self._message = "{\"weight\":" + str(
            weight) + ",\"weightprevious\":" + str(weightprevious) + "}"
        print "Beer Change" + str(self._message)
        self.myMQTTClient.connect()
        self.myMQTTClient.publish(TOPIC, self._message, 0)
        self.myMQTTClient.disconnect()

    @property
    def weight(self):
        if not self._events:
            return 0
        histogram = collections.Counter(round(num, 1) for num in self._events)
        return histogram.most_common(1)[0][0]
コード例 #15
0
class AwsIotMessage:

    # client connection instance
    myAWSIoTMQTTClient = None

    # Custom MQTT message callback
    def customCallback(self, client, userdata, message):
        print("Received a new message: ")
        print(message.payload)
        print("from topic: ")
        print(message.topic)
        print("--------------\n\n")

    def connect(self):
        # Configure logging
        '''
        logger = logging.getLogger("AWSIoTPythonSDK.core")
        logger.setLevel(logging.INFO)
        streamHandler = logging.StreamHandler()
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        streamHandler.setFormatter(formatter)
        vlogger.addHandler(streamHandler)
        '''
        # Init AWSIoTMQTTClient
        endpoint = conf.endpoint
        connectDevicePackageDir = conf.connect_device_package_dir
        rootCAPath = connectDevicePackageDir + conf.root_ca_file_name
        privateKeyPath = connectDevicePackageDir + conf.private_key_file_name
        certificatePath = connectDevicePackageDir + conf.certificate_file_name

        self.myAWSIoTMQTTClient = None
        self.myAWSIoTMQTTClient = AWSIoTMQTTClient(conf.client_id)
        self.myAWSIoTMQTTClient.configureEndpoint(endpoint, 8883)
        self.myAWSIoTMQTTClient.configureCredentials(rootCAPath,
                                                     privateKeyPath,
                                                     certificatePath)

        # AWSIoTMQTTClient connection configuration
        self.myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
        self.myAWSIoTMQTTClient.configureOfflinePublishQueueing(
            -1)  # Infinite offline Publish queueing
        self.myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
        self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
        self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

        # Connect and subscribe to AWS IoT
        return self.myAWSIoTMQTTClient.connect()

    def subscribe(self):
        #myAWSIoTMQTTClient.subscribe(conf.topic, 1, self.customCallback) # arg2 "1" is QoS1
        return

    def publish(self, payload):
        return self.myAWSIoTMQTTClient.publish(conf.topic, payload,
                                               1)  # arg3 "1" is QoS1

    def disconnect(self):
        self.myAWSIoTMQTTClient.disconnect()
コード例 #16
0
ファイル: aws.py プロジェクト: Bakhoj/lora_master
class AWS():
    __host = "a3867rpfz9hgy1.iot.eu-central-1.amazonaws.com"
    __rootCAPath = "deviceSDK/root_CA.pem"
    __privateKeyPath = "deviceSDK/private_key.pem.key"
    __certificatePath = "deviceSDK/certificate.pem.crt"

    def __init__(self):
        self.client = None
        self.master_id = '123456783245'

    def connect(self, verbose=False):
        if verbose:
            print("Connecting...")
        try:
            self.client = AWSIoTMQTTClient("RaspPiTest_01")
            self.client.configureEndpoint(AWS.__host, 8883)
            self.client.configureCredentials(AWS.__rootCAPath,
                                             AWS.__privateKeyPath,
                                             AWS.__certificatePath)
            #self.client.configureAutoReconnectBackoffTime(1, 32, 20)
            self.client.configureOfflinePublishQueueing(-1)
            self.client.configureDrainingFrequency(2)
            self.client.configureConnectDisconnectTimeout(10)
            self.client.configureMQTTOperationTimeout(5)
            self.client.connect()
            time.sleep(2)
        except Exception:
            if verbose:
                print("Connection failed")

    def publish_sensor_data(self, data_pack: DataPack, verbose=False):
        #timestamp = time.time()

        topic = 'RaspPiTest_01/sensor_data'
        dataID = "SD_{}_{}_{}".format(data_pack.time.to_float_time(),
                                      self.master_id, data_pack.station_id)

        msg = '"dataID": "{:s}", "timestamp": "{}", "stationID": "{}", "masterID": "{}"'.format(
            dataID, data_pack.time.to_float_time(), data_pack.station_id,
            self.master_id)

        data_pack.buildDict()
        for key, value in data_pack.dict.items():
            msg += ', "{:s}": "{}"'.format(key, value)
        msg = '{' + msg + '}'

        if verbose: print("Sending Data...")

        self.client.publish(topic, msg, 1)

        if verbose: print("Data send")

    def disconnect(self, verbose=False):
        self.client.disconnect()
コード例 #17
0
ファイル: NewApp.py プロジェクト: Afonia27/FY-ML-Project
class AWS(object):
    def __init__(self):
        self.jsonError = """
        {
            "state" : {
                "reported" : {
                    "y_rotation" : "red"
                 }
             }
        }
        """
        self.jsonOK = """
        {
            "state" : {
                "reported" : {
                    "y_rotation" : "white"
                 }
             }
        }
        """
        # For certificate based connection
        self.myMQTTClient = AWSIoTMQTTClient("AfAWS")
        # For Websocket connection
        # myMQTTClient = AWSIoTMQTTClient("myClientID", useWebsocket=True)
        # Configurations
        # For TLS mutual authentication
        self.myMQTTClient.configureEndpoint(
            "a3tjcvi6tnbsej-ats.iot.eu-west-2.amazonaws.com", 8883)
        # For Websocket
        # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443)
        # For TLS mutual authentication with TLS ALPN extension
        # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443)
        self.myMQTTClient.configureCredentials(
            "/Users/AfanasiChihaioglo/Desktop/Project/Sumerian IoT/New/AmazonRootCA1.pem",
            "/Users/AfanasiChihaioglo/Desktop/Project/Sumerian IoT/New/d7078f9608-private.pem.key",
            "/Users/AfanasiChihaioglo/Desktop/Project/Sumerian IoT/New/d7078f9608-certificate.pem.crt"
        )
        # For Websocket, we only need to configure the root CA
        # myMQTTClient.configureCredentials("YOUR/ROOT/CA/PATH")
        self.myMQTTClient.configureOfflinePublishQueueing(
            -1)  # Infinite offline Publish queueing
        self.myMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
        self.myMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
        self.myMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

    def Sumerian(self, mode=1):
        self.myMQTTClient.connect()
        if mode == 1:
            self.myMQTTClient.publish("$aws/things/box/shadow/update",
                                      self.jsonError, 0)
        elif mode == 0:
            self.myMQTTClient.publish("$aws/things/box/shadow/update",
                                      self.jsonOK, 0)
        self.myMQTTClient.disconnect()
コード例 #18
0
def publisher(topic, message):
    server_mqtt = AWSIoTMQTTClient("monicamMQTT_pub" + rand_str_gen())
    server_mqtt.configureEndpoint(host, 8883)
    server_mqtt.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
    server_mqtt.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
    server_mqtt.configureDrainingFrequency(2)  # Draining: 2 Hz
    server_mqtt.configureConnectDisconnectTimeout(10)  # 10 sec
    server_mqtt.configureMQTTOperationTimeout(5)  # 5 sec
    server_mqtt.connect()
    server_mqtt.publish(topic , json.dumps(message), 1)
    sleep(2)
    server_mqtt.disconnect()
コード例 #19
0
ファイル: awsiot.py プロジェクト: ymtomoyk/smarthome
class MyAWSIoTClient:
    def __init__(self, args):
        self.args = args
        self.client = AWSIoTMQTTClient(args.clientId)

        # Configure logging
        logger = logging.getLogger('AWSIoTPythonSDK.core')
        logger.setLevel(logging.DEBUG)
        streamHandler = logging.StreamHandler()
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        streamHandler.setFormatter(formatter)
        logger.addHandler(streamHandler)

        # Init AWSIoTMQTTClient
        self.client.configureEndpoint(self.args.host, MQTT_PORT)
        self.client.configureCredentials(self.args.rootCAPath,
                                         self.args.privateKeyPath,
                                         self.args.certificatePath)

        # AWSIoTMQTTClient connection configuration
        self.client.configureAutoReconnectBackoffTime(1, 32, 20)
        self.client.configureOfflinePublishQueueing(
            -1)  # Infinite offline Publish queueing
        self.client.configureDrainingFrequency(2)  # Draining: 2 Hz
        self.client.configureConnectDisconnectTimeout(100)  # 10 sec
        self.client.configureMQTTOperationTimeout(5)  # 5 sec

    def __message_handler(self, client, userdata, message):
        print('Received a new message: ')
        print(message.payload)
        print('from topic: ' + message.topic)
        try:
            self.callback(message.payload)
        finally:
            print("--------------\n\n")

    def subscribe(self, callback):
        self.callback = callback
        self.client.connect()
        self.client.subscribe(self.args.topicReq, 1, self.__message_handler)

    def publish(self, message):
        print message
        self.client.publishAsync(self.args.topicRes, message, 1)

    def __del__(self):
        self.client.disconnect()

    # to call __del__() explicitly
    def delete(self):
        self.__del__()
        del self
コード例 #20
0
def subscriber(topic):
    server_mqtt = AWSIoTMQTTClient("monicamMQTT_sub" + rand_str_gen())
    server_mqtt.configureEndpoint(host, 8883)
    server_mqtt.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
    server_mqtt.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
    server_mqtt.configureDrainingFrequency(2)  # Draining: 2 Hz
    server_mqtt.configureConnectDisconnectTimeout(10)  # 10 sec
    server_mqtt.configureMQTTOperationTimeout(5)  # 5 sec
    server_mqtt.connect()
    server_mqtt.subscribe(topic, 1, customCallback)
    sleep(2)
    server_mqtt.unsubscribe(topic)
    server_mqtt.disconnect()
コード例 #21
0
class HealthMQTT:
    "Common base class for all employees"

    def __init__(self, deviceid, host, topic):
        self.deviceid = deviceid
        self.clientid = deviceid
        self.host = host
        self.topic = topic
        self.sleep_time = 1
        certPath = "certs/{}/".format(deviceid)

        # Init AWSIoTMQTTClient
        self.myAWSIoTMQTTClient = None
        self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.clientid)
        self.myAWSIoTMQTTClient.configureEndpoint(host, 8883)
        self.myAWSIoTMQTTClient.configureCredentials(
            "{}AmazonRootCA1.pem".format(certPath),
            "{}private.pem.key".format(certPath),
            "{}certificate.pem.crt".format(certPath),
        )

        # 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
        self.myAWSIoTMQTTClient.connect()

    def sendmsg(self, message):
        message["sequence"] = 12  # loopCount change this
        message["timestamp"] = int(datetime.datetime.now().timestamp() * 1000)

        messageJson = json.dumps(message)
        repeat = 0
        while True:
            try:
                self.myAWSIoTMQTTClient.publish(self.topic, messageJson, 1)
                print("published", message["sequence"])
                break
            except:
                if repeat > 10:
                    print("bailing out after 10 attempts")
                    sys.exit(1)
                repeat += 1
                print("retrying, error occured while send MQQT")
                time.sleep(2)

    def disconnect(self):
        self.myAWSIoTMQTTClient.disconnect()
コード例 #22
0
class MQTTClient:

    def __init__(self, id):
        self.clientId = id
        self.myMQTTClient = None

    def initMQTTclient(self):
        # For certificate based connection
        self.myMQTTClient = AWSIoTMQTTClient(self.clientId)

        # For Websocket connection
        # myMQTTClient = AWSIoTMQTTClient("myClientID", useWebsocket=True)

        path = "../../Assignment1/keys/"
        values = readFromCSVFile(path + "key.txt")

        # Configurations
        # For TLS mutual authentication
        #self.myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 8883)
        self.myMQTTClient.configureEndpoint(values["clientEndpoint"], 8883)

        # For Websocket
        # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443)

        # For TLS mutual authentication with TLS ALPN extension
        # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443)

        #self.myMQTTClient.configureCredentials("YOUR/ROOT/CA/PATH", "PRIVATE/KEY/PATH", "CERTIFICATE/PATH")
        self.myMQTTClient.configureCredentials(path+values["rootCAFile"], path+values["privateKeyFile"], path+values["certificateFile"])

        # For Websocket, we only need to configure the root CA
        # myMQTTClient.configureCredentials("YOUR/ROOT/CA/PATH")

        self.myMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
        self.myMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
        self.myMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
        self.myMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec
        self.myMQTTClient.connect()

    def publish(self, topic, payload):
        self.myMQTTClient.publish(topic, payload, 0)

    def subscribe(self, topic):
        self.myMQTTClient.subscribe(topic, 1, customCallback)

    def unsubscribe(self, topic):
        self.myMQTTClient.unsubscribe(topic)

    def disconnect(self):
        self.myMQTTClient.disconnect()
コード例 #23
0
class MqttClient(object):

    PUB_TOPIC = config.PUB_TOPIC

    # Set ThingsBoard host to "demo.thingsboard.io" or "localhost"
    THINGSBOARD_HOST = config.THINGSBOARD_HOST
    # Replace YOUR_ACCESS_TOKEN with one from Device details panel.
    ACCESS_TOKEN = config.ACCESS_TOKEN

    def __init__(self):

        # initialize clients
        self.myMQTTClient = AWSIoTMQTTClient(config.MQTT_IDENTITY)

        # For TLS mutual authentication
        self.myMQTTClient.configureEndpoint(config.MQTT_ENDPOINT,
                                            config.MQTT_PORT)
        self.myMQTTClient.configureCredentials(config.CAFILE, config.KEYFILE,
                                               config.CERTFILE)
        self.myMQTTClient.configureOfflinePublishQueueing(
            -1)  # Infinite offline Publish queueing
        self.myMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
        self.myMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
        self.myMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec
        self.connect()
        return

    def connect(self):
        print "Connecting to cloud..."
        self.myMQTTClient.connect()
        print "Connection established"

    def publish(self, payload):
        # print 'Publishing message on {}'.format(self.PUB_TOPIC)
        try:
            self.myMQTTClient.publish(self.PUB_TOPIC, json.dumps(payload), 1)
        except Exception:
            print('Error during publish, measure lost. Reconnecting...')
            self.connect()
        sens_dict = {"temperature": payload['sensorData']['temperature']}
        headers = {'content-type': 'application/json'}
        r = requests.post("http://{url}/api/v1/{token}/telemetry".format(
            url=self.THINGSBOARD_HOST, token=self.ACCESS_TOKEN),
                          data=json.dumps(sens_dict),
                          headers=headers)
        r.raise_for_status()

    def disconnect(self):
        print "Disconnecting from the cloud..."
        self.myMQTTClient.disconnect()
コード例 #24
0
class awsIoTClient():
    def __init__(self, config):
        self.loop = True
        self.certfolder = "certs"
        # self.event_value = 0
        self.myAWSIoTMQTTClient = AWSIoTMQTTClient(config['clientId'])
        # Configure logging
        self.logger = logging.getLogger("AWSIoTPythonSDK.core")
        self.logger.setLevel(logging.ERROR)
        streamHandler = logging.StreamHandler()
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        streamHandler.setFormatter(formatter)
        self.logger.addHandler(streamHandler)

        self.myAWSIoTMQTTClient.configureEndpoint(config['host'],
                                                  config['port'])
        self.myAWSIoTMQTTClient.configureCredentials(
            self.certfolder + "/" + config['rootCAName'],
            self.certfolder + "/" + config['privateKeyName'],
            self.certfolder + "/" + config['certificateName'])

        # 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 to AWS IoT
        self.myAWSIoTMQTTClient.connect()
        self.logger.log(logging.DEBUG, "Connected to host...")

    def publish_message(self, topic, payload):
        # Publish to the topic
        self.myAWSIoTMQTTClient.publish(topic, payload, 1)
        self.logger.log(logging.DEBUG,
                        'Published topic %s: %s\n' % (topic, payload))

    def subscribe(self, topics, callback):
        self.logger.log(logging.DEBUG, "Starting to subscribe...")
        for topic in topics:
            self.myAWSIoTMQTTClient.subscribe(topic, 1, callback)

    def disconnect(self):
        self.loop = False
        self.myAWSIoTMQTTClient.disconnect()
        self.logger.log(logging.DEBUG, "Disconnected...")
コード例 #25
0
def handler(event, context):
    mqttClient = AWSIoTMQTTClient("lambdaApp", cleanSession=False)
    mqttClient.configureEndpoint(os.environ.get('IOT_ENDPOINT'), 443)
    mqttClient.configureConnectDisconnectTimeout(10)
    mqttClient.configureCredentials(os.environ.get('CA_FILE_PATH'),
                                    os.environ.get('CERT_KEY_PATH'),
                                    os.environ.get('CA_FILE_PATH'))
    mqttClient.configureMQTTOperationTimeout(10)
    mqttClient.connect()
    mqttClient.subscribe(os.environ.get('IOT_TOPIC'), 1, callback)
    time.sleep(30)
    mqttClient.disconnect()
    return {
        "message": "Messages received",
    }
コード例 #26
0
def publish(topic,messageDict):
	client = None
	client = AWSIoTMQTTClient(clientId)
	client.configureEndpoint(host, 8883)
	client.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

	client.configureAutoReconnectBackoffTime(1, 32, 20)
	client.configureOfflinePublishQueueing(-1)
	client.configureDrainingFrequency(2)
	client.configureConnectDisconnectTimeout(10)
	client.configureMQTTOperationTimeout(5)

	client.connect()
	client.publish(topic, json.dumps(messageDict), 0) #Replace test text with request
	client.disconnect()
コード例 #27
0
class AWSIoTMQTT(AWSIoT):
    def __init__(self,
                 host,
                 rootCAPath,
                 certPath,
                 privateKeyPath,
                 clientId,
                 port=8883,
                 useWebsocket=False):
        super().__init__(host, rootCAPath, certPath, privateKeyPath, clientId,
                         port, useWebsocket)

        # Init AWSIoTMQTTClient
        self.myAWSIoTMQTTClient = None
        if self.useWebsocket:
            self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.clientId,
                                                       self.useWebsocket)
            self.myAWSIoTMQTTClient.configureEndpoint(self.host, self.port)
            self.myAWSIoTMQTTClient.configureCredentials(self.rootCAPath)
        else:
            self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.clientId)
            self.myAWSIoTMQTTClient.configureEndpoint(self.host, self.port)
            self.myAWSIoTMQTTClient.configureCredentials(
                self.rootCAPath, self.privateKeyPath, self.certificatePath)

        # AWSIoTMQTTClient connection configuration
        self.myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
        self.myAWSIoTMQTTClient.configureOfflinePublishQueueing(
            -1)  # Infinite offline Publish queueing
        self.myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
        self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
        self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

        # Connect and subscribe to AWS IoT
        self.myAWSIoTMQTTClient.connect()

    def subcribe(self, topic):
        self.myAWSIoTMQTTClient.subscribe(topic, 1, customCallback)

    # Publish to the same topic in a loop forever
    def publish(self, topic, **kwarg):
        message = kwarg
        messageJson = json.dumps(message)
        self.myAWSIoTMQTTClient.publish(topic, messageJson, 1)
        print('Published topic %s: %s\n' % (topic, messageJson))

    def dissconnect(self):
        self.myAWSIoTMQTTClient.disconnect()
コード例 #28
0
def heartbeat(config_file, topic, frequency=3):
    # read the config file
    cfg = GroupConfigFile(config_file)

    # determine heartbeat device's thing name and orient MQTT client to GG Core
    heartbeat_name = cfg['devices']['GGD_heartbeat']['thing_name']
    mqttc = AWSIoTMQTTClient(heartbeat_name)
    mqttc.configureEndpoint(ggd_config.master_core_ip,
                            ggd_config.master_core_port)
    mqttc.configureCredentials(
        CAFilePath=dir_path + "/" + ggd_ca_file_path,
        KeyPath=dir_path + "/certs/GGD_heartbeat.private.key",
        CertificatePath=dir_path + "/certs/GGD_heartbeat.certificate.pem.crt")

    mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)

    if mqtt_connect(mqttc):
        # MQTT client has connected to GG Core, start heartbeat messages
        try:
            start = datetime.datetime.now()
            while True:
                hostname = socket.gethostname()

                now = datetime.datetime.now()
                msg = {
                    "version":
                    "2017-07-05",  # YYYY-MM-DD
                    "ggd_id":
                    heartbeat_name,
                    "hostname":
                    hostname,
                    "data": [{
                        "sensor_id": "heartbeat",
                        "ts": now.isoformat(),
                        "duration": str(now - start)
                    }]
                }
                print("[hb] publishing heartbeat msg: {0}".format(msg))
                mqttc.publish(topic, json.dumps(msg), 0)
                time.sleep(random.random() * 10)

        except KeyboardInterrupt:
            log.info("[__main__] KeyboardInterrupt ... exiting heartbeat")
        mqttc.disconnect()
        time.sleep(2)
    else:
        print("[hb] could not connect successfully via mqtt.")
コード例 #29
0
def heartbeat(config_file, topic, frequency=3):
    # read the config file
    cfg = GroupConfigFile(config_file)

    # determine heartbeat device's thing name and orient MQTT client to GG Core
    heartbeat_name = cfg['devices']['GGD_heartbeat']['thing_name']
    mqttc = AWSIoTMQTTClient(heartbeat_name)
    mqttc.configureEndpoint(ggd_config.inv_arm_ip, ggd_config.inv_arm_port)
    mqttc.configureCredentials(
        CAFilePath=dir_path + "/" + ggd_ca_file_path,
        KeyPath=dir_path + "/certs/GGD_heartbeat.private.key",
        CertificatePath=dir_path + "/certs/GGD_heartbeat.certificate.pem.crt"
    )

    mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)

    if mqtt_connect(mqttc):
        # MQTT client has connected to GG Core, start heartbeat messages
        try:
            start = datetime.datetime.now()
            while True:
                hostname = socket.gethostname()

                now = datetime.datetime.now()
                msg = {
                    "version": "2017-07-05",  # YYYY-MM-DD
                    "ggd_id": heartbeat_name,
                    "hostname": hostname,
                    "data": [
                        {
                            "sensor_id": "heartbeat",
                            "ts": now.isoformat(),
                            "duration": str(now - start)
                        }
                    ]
                }
                print("[hb] publishing heartbeat msg: {0}".format(msg))
                mqttc.publish(topic, json.dumps(msg), 0)
                time.sleep(random.random() * 10)

        except KeyboardInterrupt:
            log.info(
                "[__main__] KeyboardInterrupt ... exiting heartbeat")
        mqttc.disconnect()
        time.sleep(2)
    else:
        print("[hb] could not connect successfully via mqtt.")
コード例 #30
0
ファイル: pubsub.py プロジェクト: isrvamsi/smart-restaurant
def main(host, privateKeyPath, certificatePath, rootCAPath, useWebsocket,
         peoplecount):
    # Configure logging
    logger = logging.getLogger("AWSIoTPythonSDK.core")
    logger.setLevel(logging.DEBUG)
    streamHandler = logging.StreamHandler(sys.stdout)
    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("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()
    TOPIC = "sdk/test/Python"
    # myAWSIoTMQTTClient.subscribe(TOPIC, 1, customCallback)
    # time.sleep(2)

    data = {}
    data['time'] = get_calendar_data()
    data['pi'] = get_pi_data(peoplecount)
    data['weather'] = weather.get_weather_data()
    data['traffic'] = traffic.get_traffic_data()

    myAWSIoTMQTTClient.publish(TOPIC, json.dumps(data), 1)

    myAWSIoTMQTTClient.disconnect()
コード例 #31
0
ファイル: AWSServer.py プロジェクト: alvaromfcunha/smartWECS
class MQTTServer:
    def __init__(self,
                 host,
                 rootca_path,
                 privkey_path,
                 cert_path,
                 client_id,
                 endpoint_port=8883,
                 connect_delay=1,
                 backoff_time=32,
                 stable_time=20,
                 offline_publish=-1,
                 draining_freq=2,
                 con_discon_timeout=10,
                 operation_timeout=5):

        # Init AWSIoTMQTTClient
        self.myAWSIoTMQTTClient = None
        self.myAWSIoTMQTTClient = AWSIoTMQTTClient(client_id)
        self.myAWSIoTMQTTClient.configureEndpoint(host, 8883)
        self.myAWSIoTMQTTClient.configureCredentials(rootca_path, privkey_path,
                                                     cert_path)

        # AWSIoTMQTTClient connection configuration
        self.myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(
            connect_delay, backoff_time, stable_time)
        self.myAWSIoTMQTTClient.configureOfflinePublishQueueing(
            offline_publish)
        self.myAWSIoTMQTTClient.configureDrainingFrequency(draining_freq)
        self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout(
            con_discon_timeout)
        self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(
            operation_timeout)

    def connect(self):
        self.myAWSIoTMQTTClient.connect()

    def publish(self, json_message, topic, qos=1):
        json_message = json.dumps(json_message)
        self.myAWSIoTMQTTClient.publish(topic, json_message, qos)

    def subscribe(self, callback, topic, qos=1):
        self.myAWSIoTMQTTClient.subscribe(topic, qos, callback)

    def disconnect(self):
        self.myAWSIoTMQTTClient.disconnect()
コード例 #32
0
class IOTCore:
    def __init__(self):
        config = {}
        # read the config file
        try:
            config_file = open('./config/aws-iot.json')
            # parse the content into dictionary
            config = json.loads(config_file.read())
        except FileNotFoundError:
            print("file not found")
            raise
        
        # connect to iot
        try:
            self.client = AWSIoTMQTTClient(config["client"])
            self.client.configureEndpoint(config["host"], config["port"])
            self.client.configureCredentials(config["root-ca"], config["private-key"], config["certificate"])
            self.client.connect()
        except KeyError:
            print("Key not found")
            raise
        except (exception.operationTimeoutException, exception.operationError) as err:
            print(err)
            raise
        except:
            print("unknown error")
    
    def publish(self, key, data):
        # publish data to iot
        try:
            self.client.publish(key, data, 0)
        except (exception.operationTimeoutException, exception.operationError) as err:
            print(err)
            raise
        except:
            print("unknown error")
    
    def disconnect(self):
        # disconnect from iot
        self.client.disconnect()