Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(integration): uAgents IoT Connector (MQTT connection using ESP32, AWS IoT and Fetch.ai) #540

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions integrations/uAgent-IoT-Connector/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# uAgent_IoT_Connector
Made by: [Aleen Dhar](https://www.linkedin.com/in/aleendhar/)

The uAgent IoT Connector bridges several powerful technologies to create a robust, real-time interaction framework between an ESP32 microcontroller, AWS EC2 instances, and Fetch.ai's DeltaV platform. The architecture is designed to facilitate data collection, processing, and control for sensors and GPS modules integrated into the ESP32. It uses MQTT, a lightweight messaging protocol, ensuring efficient, scalable, and low-latency communication for real-time applications.



## Architecture Design

![image](https://github.com/user-attachments/assets/b464731e-3f7e-4274-bcb5-03f260a5dab1)


## Key Components:
1. ESP32 Microcontroller: At the heart of this system, ESP32 is responsible for collecting sensor data from connected modules, including the MPU6050 (a motion-tracking device) and the Ublox Neo-6m GPS (for location tracking). The data is then transmitted via MQTT for further analysis or control operations.

2. AWS EC2 MQTT Broker: The communication backbone relies on an AWS EC2 instance running a Mosquitto MQTT Broker. This broker enables efficient and secure bidirectional communication between the ESP32 microcontroller and various clients, including a web-based frontend and the Fetch.ai platform. The broker facilitates the publish-subscribe model, allowing clients to either publish data or subscribe to relevant topics. [Setup Guide](https://aws.amazon.com/blogs/iot/how-to-bridge-mosquitto-mqtt-broker-to-aws-iot/)

3. Node.js Socket Server & Next.js Frontend: A Node.js Socket server enables real-time communication between a Next.js frontend and the ESP32 via MQTT. This server sends requests and receives data, providing a user-friendly interface for monitoring sensor outputs or controlling the ESP32. The frontend acts as a control dashboard, visualizing real-time data and enabling actions on the ESP32 device. [Checkout the Template here](https://github.com/AleenDhar/Ground_station)

4. Fetch.ai uAgent Integration: Fetch.ai’s uAgent communicates with the ESP32 system by subscribing to specific topic. I have created 2 agents one who can directly control(by publishing data to AWS EC2 mqtt broker) the ESP32 from DeltaV and one that is subscribed to the topic where ESP32 is publishing the Sensor data.

5. Sensor Modules:
- MPU6050: A motion tracking device that captures accelerometer and gyroscope data, providing key metrics for movement or orientation-based applications.
- Ublox Neo-6m GPS: A GPS module that provides accurate location data, which is transmitted via the ESP32 for tracking purposes.

## Communication Flow:
1. Sensor Data Collection: The ESP32 collects real-time data from the MPU6050 motion sensor and the Ublox GPS module.

2. MQTT Publish/Subscribe:
- The ESP32 publishes sensor data to topics on the MQTT broker hosted on AWS EC2.
- Multiple clients, including the Next.js frontend, Node.js socket server, and Fetch.ai uAgent, subscribe to the ESP32’s data streams.
- The MQTT broker ensures efficient routing of messages to all subscribed clients.

3. Frontend Communication: The Node.js Socket server handles communication between the MQTT broker and the Next.js frontend, ensuring real-time data visualization and control capabilities.

4. Fetch.ai uAgent: The uAgent listens for specific events or requests and interacts with the ESP32 accordingly, leveraging the Fetch.ai DeltaV platform for additional computational or decision-making tasks.


## Working on DeltaV





https://github.com/user-attachments/assets/ead8fd2b-f193-4985-aa89-e49f885ec9bd


## Applications:
1. Drone or Robotics Control: The system's integration of sensors (MPU6050) and GPS modules (Ublox Neo-6m) makes it ideal for drone navigation, real-time tracking, and motion analysis.
2. Remote Monitoring: With the Next.js dashboard and real-time data communication through AWS, users can remotely monitor and control their devices over the cloud.
3. Decentralized Data Management: By leveraging Fetch.ai's DeltaV and uAgent, the system supports decentralized, intelligent decision-making for automated processes.


## Conclusion:
This system architecture is a powerful example of how modern IoT solutions can integrate cloud platforms, microcontrollers, and decentralized agents to deliver scalable, efficient, and intelligent solutions. From sensor data collection to remote control via web and decentralized intelligence, this design is suitable for a variety of advanced applications including robotics, monitoring, and automation.


## Setup
1. In the main directory install all dependencies

```bash

pip install uagents
pip install paho-mqtt
```


98 changes: 98 additions & 0 deletions integrations/uAgent-IoT-Connector/agents/publisher_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import paho.mqtt.client as mqtt
import random
from uagents import Agent, Context, Model,Protocol
from ai_engine import UAgentResponse, UAgentResponseType
import time
import websockets
import asyncio

argsuments={
"endpoint": "***.amazonaws.com",
"ca": "rootCA.pem",
"certificate": "cert.crt",
"key": "private.key" ,
"pubTopic": "esp32/sub",
"subTopic": "esp32/pub",
}

mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
mqttc.tls_set(
ca_certs=argsuments["ca"],
certfile=argsuments["certificate"],
keyfile=argsuments["key"],
tls_version=2)


def on_connect(mqttc, userdata, flags, rc, properties=None):
print("connected to endpoint %s with result code %s", argsuments["endpoint"], rc)
print("userdata: {userdata}, flags: {flags} properties: {properties}")
mqttc.is_connected = True

# def on_message(mqttc, userdata, msg):
# print('received message: topic: %s payload: %s', msg.topic, msg.payload.decode())
# print("sending data to topic: %s", argsuments["pubTopic"])

def on_publish():
print("published")


def publish():
mqttc.loop_start()
for i in range(2):
print("publishing")
mqttc.publish(argsuments["pubTopic"], "{\"message\":\"Hello form the python pub\"}",qos=0, retain=False)
time.sleep(1)
mqttc.loop_stop()

mqttc.on_connect = on_connect
# mqttc.on_message = on_message
mqttc.connect(argsuments["endpoint"], 8883)
# mqttc.on_publish = on_publish





simples = Protocol(name="simples", version="1.1")
class Message(Model):
message: str


# First generate a secure seed phrase (e.g. https://pypi.org/project/mnemonic/)
SEED_PHRASE = "something randum"

# Copy the address shown below
# print(f"Your agent's address is: {Agent(seed=SEED_PHRASE).address}")

AGENT_MAILBOX_KEY = ""

# Now your agent is ready to join the agentverse!
agent = Agent(
name="alice",
seed=SEED_PHRASE,
mailbox=f"{AGENT_MAILBOX_KEY}@https://agentverse.ai",
)


@agent.on_event("startup")
async def introduce_agent(ctx: Context):
publish()
ctx.logger.info(f"Hello, I'm agent {agent.name} and my address is {agent.address}.")



@simples.on_message(model=Message, replies={UAgentResponse})
async def handle_message(ctx: Context, sender: str, msg: Message):

publish()
ctx.logger.info(f"Received message from {sender}: {msg.message}")

await ctx.send(sender, UAgentResponse(message=(f"The Result Summary:\n {msg.message} "), type=UAgentResponseType.FINAL))


agent.include(simples)



if __name__ == "__main__":
agent.run()
65 changes: 65 additions & 0 deletions integrations/uAgent-IoT-Connector/agents/subscriber_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import paho.mqtt.client as mqtt
import random
from uagents import Agent, Context, Model,Protocol



argsuments={
"endpoint": "***.amazonaws.com",
"ca": "rootCA.pem",
"certificate": "cert.crt",
"key": "private.key" ,
"pubTopic": "esp32/sub",
"subTopic": "esp32/pub",
}

mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
mqttc.tls_set(
ca_certs=argsuments["ca"],
certfile=argsuments["certificate"],
keyfile=argsuments["key"],
tls_version=2)

def pub_and_sub():
mqttc.publish(argsuments["pubTopic"], "{\"message\":\"Hello World\"}")


def on_connect(mqttc, userdata, flags, rc, properties=None):
global TOPIC_ALIAS_MAX
print("connected to endpoint %s with result code %s", argsuments["endpoint"], rc)
print("userdata: %s, flags: %s properties: %s", userdata, flags, properties)
# print("topic_alias_maximum: %s", properties.TopicAliasMaximum)
# TOPIC_ALIAS_MAX = properties.TopicAliasMaximum
mqttc.is_connected = True

print('subscribing to topic: %s', argsuments["subTopic"])
mqttc.subscribe(argsuments["subTopic"], qos=0, options=None, properties=None)
# topic_alias = random.SystemRandom().randint(0,TOPIC_ALIAS_MAX)
# pub_and_sub()


def on_message(mqttc, userdata, msg):
print('received message: topic: %s payload: %s', msg.topic, msg.payload.decode())
print("sending data to topic: %s", argsuments["pubTopic"])
pub_and_sub()


mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.connect(argsuments["endpoint"], 8883)


def hello():
mqttc.loop_forever()

agent = Agent(name="alice")


@agent.on_event("startup")
async def introduce_agent(ctx: Context):
# asyncio.run(hello())
ctx.logger.info(f"Hello, I'm agent {agent.name} and my address is {agent.address}.")
hello()

if __name__ == "__main__":
agent.run()
Loading
Loading