Riccardo Gobbato
Published © MIT

Build an IoT infrastructure with RIOT-OS, MQTT and AWS

Connect the Thing and AWS with MQTT Bridge. Use Rules, DynamoDB and Lambda to manage the data. Make a site with Api Gateway and Amplify.

IntermediateFull instructions provided701
Build an IoT infrastructure with RIOT-OS, MQTT and AWS

Things used in this project

Story

Read more

Code

MQTT Bridge

Python
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import paho.mqtt.client as mqtt
import json
import signal

def on_message(_client, _userdata, message):

    payload = json.loads(message.payload)
    
    topic = MQTT_PUB_TOPIC

    success = myMQTTClient.publish(topic, json_payload, 0)

    time.sleep(5)
    if(success):
        print("published",json_payload)

    
# On connect subscribe to topic
def on_connect(_client, _userdata, _flags, result):
    """Subscribe to input topic"""

    myMQTTClient.publish(MQTT_PUB_TOPIC, "Connection", 0)
    print("Connection Done")

    MQTT_CLIENT.subscribe(MQTT_SUB_TOPIC)
    print('Subscribed to ' + MQTT_SUB_TOPIC)

# Disconnect function
def disconnect_clients(signum, frame):
    MQTT_CLIENT.loop_stop()
    MQTT_CLIENT.disconnect()
    myMQTTClient.disconnect()
    print("Disconntection")
    exit(0)

signal.signal(signal.SIGINT, disconnect_clients)

MQTT_BROKER_ADDR = "YOUR IP ADDRES"
MQTT_BROKER_PORT = 1883
MQTT_BROKER_CLIENT_ID = "broker"
AWS_IOT_ENDPOINT ="YOUR AWS_IOT_ENDPOINT"
AWS_IOT_PORT = 8883
AWS_IOT_CLIENT_ID = "basicPubSub"
AWS_IOT_ROOT_CA = "YOUR AWS_IOT_ROOT_CA"
AWS_IOT_PRIVATE_KEY = "YOUR AWS_IOT_PRIVATE_KEY"
AWS_IOT_CERTIFICATE = "YOYR AWS_IOT_CERTIFICATE"

# For certificate based connection
myMQTTClient = AWSIoTMQTTClient(AWS_IOT_CLIENT_ID)
myMQTTClient.configureEndpoint(AWS_IOT_ENDPOINT, 8883)
myMQTTClient.configureCredentials(AWS_IOT_ROOT_CA, AWS_IOT_PRIVATE_KEY, AWS_IOT_CERTIFICATE)
myMQTTClient.configureOfflinePublishQueueing(-1)
myMQTTClient.configureDrainingFrequency(2)
myMQTTClient.configureConnectDisconnectTimeout(10)
myMQTTClient.configureMQTTOperationTimeout(5)
MQTT_SUB_TOPIC = "YOUR MQTT_SUB_TOPIC"
MQTT_PUB_TOPIC = "YOUR MQTT_PUB_TOPIC"
MQTT_CLIENT = mqtt.Client(client_id=MQTT_BROKER_CLIENT_ID)

# MQTT callback function
def main():
    MQTT_CLIENT.on_connect = on_connect
    MQTT_CLIENT.on_message = on_message
    MQTT_CLIENT.connect(MQTT_BROKER_ADDR, MQTT_BROKER_PORT)
    myMQTTClient.connect()
    MQTT_CLIENT.loop_forever() #

if __name__ == '__main__':
    main()

FireSensorTakeFunction

Python
import json
import boto3
import calendar
from datetime import datetime
import time

# Create a DynamoDB object using the AWS SDK
dynamodb = boto3.resource('dynamodb')

# Use the DynamoDB object to select our tables
table_fire = dynamodb.Table('FireSensorTable')

# Define the handler function that the Lambda service will use
def lambda_handler(event, context):
 # Generate a timestamp for the event
    time_now = datetime.now().strftime('%d/%m/%Y %H:%M:%S')

    current_GMT = time.gmtime()
    timestamp = calendar.timegm(current_GMT)

    # Write payload and time to the DynamoDB table using the object we instantiated and save response in a variable
    response = table_fire.put_item(
    Item={
        'Timestamp': timestamp,
        'Datetime': event['Datetime'],
        'Flame': event['Flame'],
        'CO': event['CO'],
        'Temp': event['Temp']

    })

    return {
       'statusCode': 200
    }

FireSensorMonitorFunction

Python
import json

# import the AWS SDK
import boto3

from decimal import Decimal

# Funtion to sort by numeric timestamp
def sort_by_key(list):
    return list['Timestamp']

# Define the handler function that the Lambda service will use
def lambda_handler(event, context):

    # Create a DynamoDB object using the AWS SDK
    dynamodb = boto3.resource('dynamodb')

    # Use the DynamoDB object to select our tables
    table_fire = dynamodb.Table('FireSensorTable')

    # Retrieve tuples of our tables to return
    response_fire = table_fire.scan()

    output_fire = response_fire['Items']

    # Convert numeric values to strings
    for fire_json in output_fire:
        fire_json['Timestamp'] = str(fire_json['Timestamp'])

    # Sort by timestamp
    output_fire = sorted(output_fire, key=sort_by_key)


    return {
       'statusCode': 200,
       'body_fire': json.dumps(output_fire)
    }

GitHub Repository

Credits

Riccardo Gobbato
4 projects • 5 followers
Computer Engineer

Comments