Example #1
0
    elif color == "blue":
        b.lights[2].state(on=True, bri=250, sat=250, hue=45000)
    else:
        b.lights[2].state(on=False)


rootCAPath = "<ROOT_CA_PATH>"
certificatePath = "<CERT_PATH>"
privateKeyPath = "<PRIVATE_KEY_PATH"
host = "<AWS_IOT_CORE_ENDPOINT>"
port = 8883
clientId = "bulb1"
topic = "bulb/color"

bulbMQTTClient = AWSIoTMQTTClient(clientId)
bulbMQTTClient.configureEndpoint(host, port)
bulbMQTTClient.configureCredentials(rootCAPath, privateKeyPath,
                                    certificatePath)

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

bulbMQTTClient.connect()

bulbMQTTClient.subscribe(topic, 1, bulbCallback)
while True:
    time.sleep(1)
Example #2
0
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
GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(button_pin, GPIO.RISING)
GPIO.add_event_callback(button_pin, callback=on_push_down)

# Turn off the LED
GPIO.output(led_pin, GPIO.LOW)

# Initialize MQTT
awsIoTClient = AWSIoTMQTTClient(
    "my_raspberry_pi_ID")  #clientId can be anything
awsIoTClient.configureEndpoint(host, port)
awsIoTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

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

#Connect and subscribe to AWS IoT
awsIoTClient.connect()
awsIoTClient.subscribeAsync("my_pi/led", 1, ackCallback=on_subscribe)
while True:
    try:
        time.sleep(2)
    except KeyboardInterrupt:
        GPIO.cleanup()
Example #4
0
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()
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    requests.put(philips_hue_local_url, data=json.dumps(data), headers=headers)


def lampUpdateCallback(client, userdata, message):
    '''This method will be called whenever the lamp color needs to be updated.'''
    hue_post(json.loads(message.payload))


# Client initialization
client = AWSIoTMQTTClient("PhilipsHue")
client.configureEndpoint(host, 8883)
client.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# Connection configuration
client.configureAutoReconnectBackoffTime(1, 32, 20)
client.configureConnectDisconnectTimeout(10)
client.configureMQTTOperationTimeout(5)

# Connect to the AWS IoT platform
client.connect()

# Subscribe to all lamp color update requests using their common MQTT topic
client.subscribe("iot/raspberrypi/brightness/update", 1, lampUpdateCallback)

# Initially, turn on the lamp and set it to white
hue_post({'on': True, 'sat': 0, 'bri': 255, 'hue': 0})

try:
    while True:
        pass
class AwsIotClient:
    # Initialize
    def __init__(self):
        self.host = os.getenv('ENDPOINT',
                              'xxxxxxxxxxxxxxxx.ap-northeast-1.amazonaws.com')
        self.bcoreMac = os.getenv('BCORE_MAC', 'xx:xx:xx:xx:xx:xx')
        self.rootCAPath = "/home/pi/root-CA.crt"
        self.certificatePath = "/home/pi/certificate.pem.crt"
        self.privateKeyPath = "/home/pi/private.pem.key"
        self.clientId = "MyRaspberryPi"
        self.topic = "robot/+"
        self.cmd = '/home/pi/motion.bash'
        self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.clientId)
        self.myAWSIoTMQTTClient.configureEndpoint(self.host, 8883)
        self.myAWSIoTMQTTClient.configureCredentials(self.rootCAPath,
                                                     self.privateKeyPath,
                                                     self.certificatePath)
        self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout(30)  # 30 sec
        self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(30)  # 30 sec
        self.myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 128, 20)

    # Connect and subscribe to AWS IoT
    # AWS_IoTへ接続
    def connect(self):
        print("connect")
        self.myAWSIoTMQTTClient.connect()

    # Custom MQTT message callback
    # 1秒ごとにsubし続けているときにトピックからなにかしら受け取ったら呼ばれる関数
    def customCallback(self, client, userdata, message):
        topic = str(message.topic)
        print(topic)
        if (topic == "robot/walk"):
            self.walkIntent()
        elif (topic == "robot/wink"):
            self.winkIntent()
        elif (topic == "robot/light"):
            self.lightIntent()
        else:
            print("none")

    # 前進するBLEの処理
    def walkIntent(self):
        print("walk")
        cmd = "bash %s %s %s" % (self.cmd, self.bcoreMac, "walk")
        os.system(cmd)

    # ウィンクするBLEの処理
    def winkIntent(self):
        print("wink")
        cmd = "bash %s %s %s" % (self.cmd, self.bcoreMac, "wink")
        os.system(cmd)

    # 目を光らせるBLEの処理
    def lightIntent(self):
        print("light")
        cmd = "bash %s %s %s" % (self.cmd, self.bcoreMac, "light")
        os.system(cmd)

    # 1秒ごとにサブスクライブし続ける(ctrl+Cで終了する)
    def subscribe(self):
        while True:
            self.myAWSIoTMQTTClient.subscribe(self.topic, 1,
                                              self.customCallback)
    except Exception as err:
        print("Error occured while publishing - error: {}".format(err))
        return False


#-------------------- MQTT setup ---------------------
endpoint = 'endpoint...'
topic = 'testTopic/testClient'
qos = 1

myMQTTClinet = AWSIoTMQTTClient('testClient')
myMQTTClinet.disableMetricsCollection()
myMQTTClinet.configureEndpoint(endpoint, 8883)
myMQTTClinet.configureCredentials('cert/rootCA.pem', 'cert/priv.pem.key',
                                  'cert/cert.pem.crt')
myMQTTClinet.configureAutoReconnectBackoffTime(15, 180, 30)
myMQTTClinet.configureOfflinePublishQueueing(-1)
myMQTTClinet.configureConnectDisconnectTimeout(10)
myMQTTClinet.configureDrainingFrequency(1)
myMQTTClinet.configureMQTTOperationTimeout(5)
myMQTTClinet.onOnline = _onOnline
myMQTTClinet.onOffline = _onOffline

#-------------------- Other setup -------------------

#logging.getLogger("AWSIoTPythonSDK.core").setLevel("DEBUG")
#logging.getLogger("AWSIoTPythonSDK.core").addHandler(logging.StreamHandler())
totalMsgToSend = 20

#-------------------- Main code ----------------------
message = 'message number (from 100): {}'  #for have a message number different from the id generated when publish
class BasicPubSub(object):
    def __init__(self, host = None, rootCAPath = None, certificatePath = None, privateKeyPath = None, port = None, useWebsocket = None, clientId = None, topic = None, mode = None, message = None):

        self.host = host
        self.rootCAPath = rootCAPath
        self.certificatePath = certificatePath
        self.privateKeyPath = privateKeyPath
        self.port = port
        self.useWebsocket = useWebsocket
        self.clientId = clientId
        self.topic = topic
        self.mode = mode
        self.message = message

        # Port defaults
        if self.useWebsocket and not self.port:  # When no port override for WebSocket, default to 443
            port = 443
        if not self.useWebsocket and not self.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
        self.myAWSIoTMQTTClient = None
        if useWebsocket:
            self.myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True)
            self.myAWSIoTMQTTClient.configureEndpoint(host, port)
            self.myAWSIoTMQTTClient.configureCredentials(rootCAPath)
        else:
            self.myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
            self.myAWSIoTMQTTClient.configureEndpoint(host, port)
            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
        
    # 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")

    # Connect and subscribe to AWS IoT
    def suscribeMQTT(self):
        self.myAWSIoTMQTTClient.connect()
        if self.mode == 'both' or self.mode == 'subscribe':
            self.myAWSIoTMQTTClient.subscribe(self.topic, 1, self.customCallback)
        time.sleep(2)

    def publicMQTT(self, action = None, action_prob = None):
        if self.mode == 'both' or self.mode == 'publish':
            message = {}
            message['timestamp'] = time.time()*1000
            message['action'] = action
            message['action_prob'] = action_prob
            messageJson = json.dumps(message)
            self.myAWSIoTMQTTClient.publish(self.topic, messageJson, 1)
            if self.mode == 'publish':
                print('Published topic %s: %s\n' % (self.topic, messageJson))
        #time.sleep(1)
Example #9
0
class Mqtt(metaclass=Singleton):
    OnMessageCallback = Callable[[str, dict], None]

    def __init__(self):
        self.port: Optional[int] = None
        self.host: Optional[str] = None
        self.thing_name: Optional[str] = None
        self.client_id: Optional[str] = None
        self.root_ca_path: Optional[str] = None
        self.certificate_path: Optional[str] = None
        self.private_key_path: Optional[str] = None
        self.myAWSIoTMQTTClient: Optional[AWSIoTMQTTClient] = None
        self.topic: Optional[str] = None
        self.callbacks: List[Mqtt.OnMessageCallback] = []

        self._init_loggers()

    def _init_loggers(self):
        # # Configure logging
        # iotcore_logger = logging.getLogger("AWSIoTPythonSDK.core")
        # iotcore_logger.setLevel(logging.DEBUG)
        # stream_handler = logging.StreamHandler()
        # stream_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
        # iotcore_logger.addHandler(stream_handler)

        self.logger = logging.getLogger(__name__)

    def connect(self, configs):
        # TODO - Configs should be initialized from "configs" argument
        certs_dir = "device/certs"
        self.port = 8883
        self.host = "a21uta8yahkocj-ats.iot.us-east-1.amazonaws.com"
        self.thing_name = "raspberrypi_edi"
        self.client_id = "basicPubSub"  # clientId should be permitted in the Thing's policy
        self.root_ca_path = f"{certs_dir}/root-CA.crt"
        self.certificate_path = f"{certs_dir}/{self.thing_name}.cert.pem"
        self.private_key_path = f"{certs_dir}/{self.thing_name}.private.key"
        self.topic = configs['topic']

        # Init AWSIoTMQTTClient
        self.myAWSIoTMQTTClient = AWSIoTMQTTClient(self.client_id)
        self.myAWSIoTMQTTClient.configureEndpoint(self.host, self.port)
        self.myAWSIoTMQTTClient.configureCredentials(self.root_ca_path,
                                                     self.private_key_path,
                                                     self.certificate_path)

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

        # Subscribe to topics
        self.logger.info(f"Subscribing to topic {self.topic}")
        self.myAWSIoTMQTTClient.subscribe(self.topic, 1, self._callback)
        self.logger.info("Finished subscribing")

    def register_callback(self, callback: OnMessageCallback):
        self.callbacks.append(callback)

    def _callback(self, client, userdata, message):
        self.logger.info(
            f"Received a new message on topic {message.topic}: {message.payload}"
        )

        msg_dict = json.loads(message.payload)
        for callback in self.callbacks:
            callback(message.topic, msg_dict)

    def send(self, topic, msg):
        message_json = json.dumps(msg)
        self.myAWSIoTMQTTClient.publish(topic, message_json, 1)
        self.logger.info(f'Published topic "{topic}": {message_json}\n')
Example #10
0
def aws_mqtt_node():
    # init node
    rospy.init_node('aws_mqtt_node', anonymous=True, log_level=rospy.DEBUG)

    # load parameters
    params = rospy.get_param("~", {})
    mqtt_params = params.pop("mqtt", {})
    bridge_params = params.pop("bridge", {})

    host = mqtt_params.pop("host", "")
    rootCAPath = mqtt_params.pop("rootCAPath", "")
    certificatePath = mqtt_params.pop("certificatePath", "")
    privateKeyPath = mqtt_params.pop("privateKeyPath", "")
    clientId = mqtt_params.pop("clientId", "")

    # Init AWSIoTMQTTClient
    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
    myAWSIoTMQTTClient.configureEndpoint(host, 8883)
    try:
        myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath,
                                                certificatePath)
    except:
        raise IOError("Cannot load certificates...")
    else:
        # 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

        # dependency injection
        config = create_config(myAWSIoTMQTTClient)
        inject.configure(config)

        # Connect to AWS IoT
        try:
            myAWSIoTMQTTClient.connect()
        except:
            raise IOError("Cannot connect to AWS IoT...")
        else:
            # configure bridges
            bridges = []
            # setup publishing bridge
            bridges.append(create_publish_bridge())
            # setup subscribing bridges
            for bridge_args in bridge_params:
                try:
                    bridges.append(create_subscribe_bridge(**bridge_args))
                except Exception, e:
                    rospy.logerr(str(e))
                    rospy.logerr("Cannot subscribe to the topic %s" %
                                 (bridge_args.pop("topic_from", "")))

            rospy.loginfo(rospy.get_caller_id() + " All settings are ready!")

            # spin() simply keeps python from exiting until this node is stopped
            for bridge in bridges:
                rospy.on_shutdown(bridge.on_shutdown)
            rospy.on_shutdown(myAWSIoTMQTTClient.disconnect)
            rospy.spin()
Example #11
0
def customCallback(client, userdata, message):
    print("Received a new message: ")
    print(message.payload)
    print("from topic: ")
    print(message.topic)
    print("--------------\n\n")


#starting service
robot = AWSIoTMQTTClient(host)
robot.configureEndpoint(host, 8883)
robot.configureCredentials(root_cert, key_file, cert_file)

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

# Connect and subscribe to AWS IoT

robot.connect()
time.sleep(1)

#robot.subscribe(sendtopic, 1, customCallback)

#robot.loop()
time.sleep(1)
for x in range(0, 10):
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)

### Init Urbanova Cloud IoT MQTT Client using TLSv1.2 Mutual Authentication
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)
# .........................................................................................

# .......................... Connect to each Sensor of the Node ...........................

import board
import busio
class Sensor:
    ID = 0

    def __init__(self, name, deltatime):
        self._id = Sensor.ID
        Sensor.ID += 1
        self.id = str(name)
        self.geo_cords = near_location(50.059624, 19.916025, 50)
        self.date_n_time = None
        self.temperature = None
        self.humidity = None
        self.PM10 = None
        self.data = None
        self.deltatime = deltatime

        # MQTT Settings
        self.mqttc = None
        self.MQTT_Topic = f"cloud2020/sensors/{self.id}"
        self.AWSClientName = "AWSPython"
        self.AWSPort = 8883
        self.endpoint = "a2uqa59mml9h3u-ats.iot.us-east-1.amazonaws.com"
        self.basePathToCerts = r"C:\Users\szymo\OneDrive\Pulpit\SemestrIII\ChmuryObliczeniowe"
        self.rootCAPath = self.basePathToCerts + r"\rootca.txt"
        self.privateKeyPath = self.basePathToCerts + r"\7d6e952451-private.pem.key"
        self.certificatePath = self.basePathToCerts + r"\7d6e952451-certificate.pem.crt"

    def update_data(self):
        temp = dict()
        temp['id'] = self._id
        temp['sensorID'] = self.id
        temp['cords'] = self.geo_cords
        temp['datetime'] = self.date_n_time
        temp['temperature'] = self.temperature
        temp['humidity'] = self.humidity
        temp['PM10'] = self.PM10
        self.data = temp

        self.date_n_time = None
        self.temperature = None
        self.humidity = None
        self.PM10 = None

    def generate_data(self):
        self.date_n_time = (datetime.today()).strftime("%d-%b-%Y %H:%M:%S:%f")
        self.temperature = f'{20 + (random.random() - .5) * 20:.2f}'  # 20 +-10
        self.humidity = f'{50 + (random.random() - .5) * 80:.2f}'  # 50 +-40
        self.PM10 = f'{abs(25 + (random.random() - .5) * 100):.2f}'  # 25 +-50

        self.update_data()

    def reset_data_buffer(self):
        self.data = None

    def publish_To_Topic(self, topic, message):
        self.mqttc.publish(topic, message, 1)
        print("Published: " + str(message) + " " + "on MQTT Topic: " +
              str(topic))

    def create_json(self):
        print(f'Publishing fake data...')
        print(self.data)
        return json.dumps(self.data)

    def connect_sensor(self):
        self.mqttc = AWSIoTMQTTClient(self.AWSClientName)
        self.mqttc.configureEndpoint(self.endpoint, self.AWSPort)
        self.mqttc.configureCredentials(self.rootCAPath, self.privateKeyPath,
                                        self.certificatePath)

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

        self.mqttc.connect()
        print('Connected')

        self.mqttc.subscribe(self.MQTT_Topic, 1, customCallback)

        time.sleep(2)

    def publish_Fake_Sensor_Values_to_MQTT(self):
        threading.Timer(self.deltatime,
                        self.publish_Fake_Sensor_Values_to_MQTT).start()
        self.generate_data()
        self.publish_To_Topic(self.MQTT_Topic, self.create_json())
        self.reset_data_buffer()
Example #14
0
class AWS():
	home_dir = pwd.getpwuid(os.getuid()).pw_dir
	myAWSIoTMQTTClient = None
	AllowedActions = ['both', 'publish', 'subscribe']
	host = None
	rootCAPath = None
	certificatePath = None
	privateKeyPath = None
	port = ''
	useWebsocket = ''
	clientId = ''
	topic = 'print/image/url/response'
	mode = "both"
	message = "Hello World!"
	logger = None
	handler = None
	_settings = None

	def __init__(self, logger, handler, settings):
		self.logger = logger
		self.handler = handler
		self._settings = settings
		logger.info("init!")
		self.host = self._settings.get(["iot_host"])
		self.rootCAPath = self._settings.get(["iot_rootCAPath"])
		self.certificatePath = self._settings.get(["iot_certificatePath"])
		self.privateKeyPath = self._settings.get(["iot_privateKeyPath"])
		if self.mode not in self.AllowedActions:
			# parser.error("Unknown --mode option %s. Must be one of %s" % (mode, str(AllowedActions)))
			exit(2)

		if self.useWebsocket and self.certificatePath and self.privateKeyPath:
			# parser.error("X.509 cert authentication and WebSocket are mutual exclusive. Please pick one.")
			exit(2)

		if not self.useWebsocket and (not self.certificatePath or not self.privateKeyPath):
			# parser.error("Missing credentials for authentication.")
			exit(2)

		# Port defaults
		if self.useWebsocket and not self.port:  # When no port override for WebSocket, default to 443
			port = 443
		if not self.useWebsocket and not self.port:  # When no port override for non-WebSocket, default to 8883
			port = 8883


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

		# AWSIoTMQTTClient connection configuration
		self.myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 128, 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()
		if self.mode == 'both' or self.mode == 'subscribe':
			# self.myAWSIoTMQTTClient.subscribe(self.topic, 1, self.handler)
			self.myAWSIoTMQTTClient.subscribe(self.topic, 1, self.customCallback)
		# time.sleep(2)

	def customCallback(self, client, userdata, message):
		self.logger.info("Received a new message: ")
		self.logger.info(message.payload)
		self.logger.info("from topic: {message.topic} ----\n\n".format(**locals()))
		self.handler(message)

	def pub(self, topic, message):
		outmessage = dict()
		outmessage['message'] = message
		outmessage['sequence'] = datetime.now().microsecond / 10000
		messageJson = json.dumps(outmessage)
		self.myAWSIoTMQTTClient.publish(topic, messageJson, 1)
		self.logger.info("Just published to {topic} this message: {outmessage}".format(**locals()))
Example #15
0
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)
Example #16
0
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
        if cli.append_thing_name:
            self.topic = '{0}/{1}'.format(cli.topic, self.thing_name)
        else:
            self.topic = cli.topic

        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
        eid = uuid.UUID(cfg[elf_id_key])

        # use ELF ID and a random string since we must use unique Client ID per
        # client.
        cid = eid.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
Example #17
0
class IoTClientWrapper(object):
    """
    Wrapper around the AWS Iot Python SDK.

    Sets common parameters based on the AWS Iot Python SDK's `Basic PubSub`_ sample.

    .. _Basic PubSub: https://github.com/aws/aws-iot-device-sdk-python/blob/master/samples/basicPubSub/basicPubSub.py

    """
    def __init__(self, endpoint, root_ca_path, certificate_path,
                 private_key_path, client_id):
        self.host = endpoint
        self.root_ca_path = root_ca_path
        self.certificate_path = certificate_path
        self.private_key_path = private_key_path
        self.client_id = client_id
        self.iot_client = None

    def publish(self, publish_to_topic, payload):
        """Publish to MQTT"""
        self.iot_client.publish(topic=publish_to_topic, payload=payload, QoS=0)

    def subscribe(self, subscribe_to_topic, callback):
        """Subscribe to MQTT"""
        self.iot_client.subscribe(
            topic=subscribe_to_topic,
            callback=callback,
            QoS=1,
        )

    def connect(self):
        """Connect to AWS IoT"""
        if not self.certificate_path or not self.private_key_path:
            print "Missing credentials for authentication."
            exit(2)

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

        self.iot_client = AWSIoTMQTTClient(self.client_id)
        self.iot_client.configureEndpoint(self.host, 8883)
        self.iot_client.configureCredentials(self.root_ca_path,
                                             self.private_key_path,
                                             self.certificate_path)

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

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

        sleep(2)
Example #18
0
    print(temp)
    print("camera_id: %s" % temp["camera_id"])
    dataReal[temp["camera_id"]] = temp
    print(dataReal)


host = "<END POINT"
rootCAPath = "<ROOT CA PATH>"
certificatePath = "<CERTIFICATE PATH>"
privateKeyPath = "<PRIVATE KEY PATH>"

my_rpi = AWSIoTMQTTClient("kuma-basicPubSub")
my_rpi.configureEndpoint(host, 8883)
my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

my_rpi.configureAutoReconnectBackoffTime(1, 32, 20)
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("kuma/crowdsize", 1, customCallback)
sleep(2)

app = Flask(__name__)


@app.route("/api/lcdDisplay", methods=['POST', 'GET'])
def LCD_publish():
    print("inside method")
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
Example #20
0
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient

from boto3.dynamodb.conditions import Key, Attr
from botocore.exceptions import ClientError

from ask_sdk_model.interfaces.alexa.presentation.apl import (
    RenderDocumentDirective, ExecuteCommandsDirective, SpeakItemCommand,
    AutoPageCommand, HighlightMode)

createMQTTClient = AWSIoTMQTTClient("TwitchRobotController")
createMQTTClient.configureEndpoint(os.environ['AWS_IOT_ENDPOINT'], 8883)
createMQTTClient.configureCredentials('./certs/AmazonRootCA1.crt',
                                      './certs/TwitchRobot.pem.key',
                                      './certs/TwitchRobot.pem.crt')

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

createMQTTClient.connect()

SKILL_NAME = "The Create Robot Controller"
HELP_MESSAGE = "You can tell the robot to move a direction, like move forward, or to spin around."
HELP_REPROMPT = "What can I help you with?"
STOP_MESSAGE = "Goodbye for now!"
FALLBACK_MESSAGE = "Oops! This robot isn't smart enough, yet. Say something like move backwards."
FALLBACK_REPROMPT = 'What can I help you with?'
EXCEPTION_MESSAGE = "Sorry. This robot cannot comply"
Example #21
0
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)
topic = '/Transnavigators/Pi'

def callback(client, userdata, message):
    data_string = message.payload.decode("utf8").replace("'",'"')
    data_json = json.loads(data_string)
    print(json.dumps(data_json, indent=4))


print("Connecting to AWS")

# Init AWSIoTMQTTClient
aws_iot_mqtt_client = AWSIoTMQTTClient(clientId)
aws_iot_mqtt_client.configureEndpoint(host, 8883)
aws_iot_mqtt_client.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

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

# Connect and subscribe to AWS IoT
aws_iot_mqtt_client.connect()
aws_iot_mqtt_client.subscribe(topic, 1, callback)

print("Connected to " + topic)

while True:
    time.sleep(1)
Example #23
0
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')
Example #24
0
def subackCallback(mid, data):
    print("subAck")

def onMessage(message):
    print("onMessage")

# Puback callback
def iotResponse(mid):
    print("Puback")

# Set Up AWS iot
myMQTTClient = AWSIoTMQTTClient(configs['iotDeviceName'])
myMQTTClient.configureEndpoint(configs['iotEndpoint'], configs['iotPort'])
myMQTTClient.configureCredentials(
    configs['iotCACert'], configs['iotPrivCert'], configs['iotCert'])
myMQTTClient.configureAutoReconnectBackoffTime(
    configs['baseReconnectQuietTimeSecond'], configs['maxReconnectQuietTimeSecond'], configs['stableConnectionTimeSecond'])
myMQTTClient.configureOfflinePublishQueueing(-1)
myMQTTClient.configureDrainingFrequency(2)
myMQTTClient.configureConnectDisconnectTimeout(configs['iotTimeout'])
myMQTTClient.configureMQTTOperationTimeout(configs['iotOpTimeout'])
myMQTTClient.onMessage = onMessage

# Now lets do connection
myMQTTClient.connect()

myMQTTClient.subscribeAsync("human/" + configs['iotDeviceName'] + "/getConfig", 0, ackCallback=subackCallback)
time.sleep(2)

# Push the config to AWS IoT so its available online to allow checking of config settings
# IoT Platform can then alert to any changes without the need to use a shadow and can push messages
msg = {}
Example #25
0
temporaryCredentials = cognitoIdentityClient.get_credentials_for_identity(
    IdentityId=identityID)
AccessKeyId = temporaryCredentials["Credentials"]["AccessKeyId"]
SecretKey = temporaryCredentials["Credentials"]["SecretKey"]
SessionToken = temporaryCredentials["Credentials"]["SessionToken"]

# Init AWSIoTMQTTClient
myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSub_CognitoSTS",
                                      useWebsocket=True)

# AWSIoTMQTTClient configuration
myAWSIoTMQTTClient.configureEndpoint(host, 443)
myAWSIoTMQTTClient.configureCredentials(rootCAPath)
myAWSIoTMQTTClient.configureIAMCredentials(AccessKeyId, SecretKey,
                                           SessionToken)
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("sdk/test/Python", 1, customCallback)
time.sleep(2)

# Publish to the same topic in a loop forever
loopCount = 0
while True:
    myAWSIoTMQTTClient.publish("sdk/test/Python",
Example #26
0
    "CERTS_LOCATION"]  # This is set by the ROS node, it is not a RoboMaker environment variable
ROOT_CA = CERTS_LOCATION + "AmazonRootCA1.crt"
KEY = CERTS_LOCATION + "WorkshopRobot.private.key"
CERT = CERTS_LOCATION + "WorkshopRobot.cert.pem"
CLIENT_SUFFIX = "".join(
    [random.choice(string.ascii_letters + string.digits) for n in xrange(12)])
CLIENT = "VoiceRoboticsWorkshop-" + CLIENT_SUFFIX

rospy.loginfo("Alexa node created client " + CLIENT)

# Setup and connect to the MQTT Client
WorkshopMQTTClient = None
WorkshopMQTTClient = AWSIoTMQTTClient(CLIENT)
WorkshopMQTTClient.configureEndpoint(ENDPOINT, 8883)
WorkshopMQTTClient.configureCredentials(ROOT_CA, KEY, CERT)
WorkshopMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
WorkshopMQTTClient.configureOfflinePublishQueueing(
    -1)  # Infinite offline Publish queueing
WorkshopMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
WorkshopMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
WorkshopMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec
res = WorkshopMQTTClient.connect()
if res:
    rospy.loginfo("Alexa node connected to MQTT")
else:
    rospy.loginfo("Alexa node could not connect to MQTT")

# Initialize the node
rospy.init_node('alexa', anonymous=True)
rospy.loginfo("Alexa node started loading")
velocity_publisher = rospy.Publisher('/cmd_vel', Twist, queue_size=10)
Example #27
0
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, 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':
Example #28
0
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
mqttClient = None
mqttClient = AWSIoTMQTTClient(clientId)
mqttClient.configureEndpoint(host, 8883)
mqttClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTClient connection configuration
mqttClient.configureAutoReconnectBackoffTime(1, 128, 20)
mqttClient.configureOfflinePublishQueueing(
    -1)  # Infinite offline Publish queueing
mqttClient.configureDrainingFrequency(2)  # Draining: 2 Hz
mqttClient.configureConnectDisconnectTimeout(60)  # sec
mqttClient.configureMQTTOperationTimeout(30)  # sec

# Connect and subscribe to AWS IoT
time.sleep(60)  # lazy way to wait for network interfaces to come up
mqttClient.connect()

# Subscribe to topic
#mqttClient.subscribe(topic, 1, customCallback)

# Sensor interfaces
sens_i2c = SI7021()