Skip to content
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
37 changes: 37 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# EdgeBrain Examples

This directory contains example scripts demonstrating how to integrate various Edge AI and machine learning tasks with the EdgeBrain platform.

The examples simulate edge devices processing data (like images, webcam feeds, or text) and securely transmitting the extracted insights (inferences) to the EdgeBrain backend via MQTT.

## Available Examples

1. **`image_classification.py`**
Simulates a Raspberry Pi capturing an image, running a lightweight classification model, and publishing the inferred class and confidence score to EdgeBrain.

2. **`object_detection.py`**
Simulates processing a live webcam feed using an object detection model (e.g., YOLO) to count the number of detected persons in a room, sending the count to EdgeBrain.

3. **`sentiment_analysis.py`**
Demonstrates how non-hardware AI tasks can be integrated. It performs sentiment analysis on a text stream and sends a sentiment score (-1.0 to 1.0) to EdgeBrain.

## Prerequisites

To run these examples, ensure you have the required dependencies installed. You can install the MQTT client library using pip:

```bash
pip install paho-mqtt
```

*Note: In a real-world scenario, you would also need the respective ML libraries (e.g., `opencv-python`, `tensorflow`, `torch`, `transformers`) depending on the actual models you choose to deploy.*

## Usage

1. Ensure the EdgeBrain platform (including the MQTT broker) is running. By default, the scripts attempt to connect to `localhost:1883`.
2. Run any of the example scripts:

```bash
python image_classification.py
```

3. Open the EdgeBrain dashboard or query the REST API to see the live data flowing from the simulated edge devices!
75 changes: 75 additions & 0 deletions examples/image_classification.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""
Example: Image Classification on Raspberry Pi

This script demonstrates how an edge device like a Raspberry Pi can run
an image classification model and report the results to EdgeBrain.
It classifies an image and sends a confidence score or label to the system.

Requirements:
- paho-mqtt

Usage:
python image_classification.py
"""

import time
import json
import random
import paho.mqtt.client as mqtt

# Configuration for EdgeBrain MQTT Broker
MQTT_BROKER = "localhost"
MQTT_PORT = 1883
MQTT_TOPIC = "edgebrain/devices/rpi_cam_01/data"

CLASSES = ["cat", "dog", "person", "car", "unknown"]

def classify_image():
"""
Simulates capturing an image on a Raspberry Pi and running a lightweight
classification model (e.g., TensorFlow Lite).
"""
detected_class = random.choice(CLASSES)
confidence = random.uniform(0.5, 0.99)
return detected_class, confidence

def main():
client = mqtt.Client(client_id="rpi_classifier_01")

try:
client.connect(MQTT_BROKER, MQTT_PORT, 60)
except ConnectionRefusedError:
print(f"Error: Could not connect to MQTT broker at {MQTT_BROKER}:{MQTT_PORT}")
return

print("Starting Raspberry Pi Image Classifier...")

try:
while True:
label, conf = classify_image()

# EdgeBrain expects a numerical value as the primary metric.
# We can use confidence as the value, and pass the label in 'extra'.
payload = {
"device_id": "rpi_cam_01",
"device_type": "rpi_camera",
"value": conf,
"unit": "confidence",
"room": "garage",
"extra": {
"detected_class": label
}
}

client.publish(MQTT_TOPIC, json.dumps(payload))
print(f"Classified image as '{label}' (conf: {conf:.2f}). Published to EdgeBrain.")

time.sleep(5)

except KeyboardInterrupt:
print("Shutting down classifier.")
finally:
client.disconnect()

if __name__ == "__main__":
main()
86 changes: 86 additions & 0 deletions examples/object_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
"""
Example: Object Detection with Webcam

This script demonstrates how to integrate a webcam object detection model
with EdgeBrain. It captures frames from a camera, runs a simulated object
detection model, and publishes the number of detected persons to the
EdgeBrain system via MQTT.

Requirements:
- paho-mqtt
- opencv-python (for actual camera usage)

Usage:
python object_detection.py
"""

import time
import json
import random
import paho.mqtt.client as mqtt

# Configuration for EdgeBrain MQTT Broker
MQTT_BROKER = "localhost"
MQTT_PORT = 1883
MQTT_TOPIC = "edgebrain/devices/webcam_01/data"

def simulate_object_detection():
"""
Simulates object detection (e.g., YOLO, MobileNet) returning the count
of people detected in the camera frame.
In a real scenario, you would use cv2.VideoCapture() and a model here.
"""
return random.randint(0, 5)

def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to EdgeBrain MQTT Broker!")
else:
print(f"Failed to connect, return code {rc}")

def main():
client = mqtt.Client(client_id="webcam_detector_01")
client.on_connect = on_connect

try:
client.connect(MQTT_BROKER, MQTT_PORT, 60)
except ConnectionRefusedError:
print(f"Error: Could not connect to MQTT broker at {MQTT_BROKER}:{MQTT_PORT}")
print("Make sure the EdgeBrain infrastructure is running.")
return

client.loop_start()

print("Starting webcam object detection stream...")
try:
while True:
# Run detection (simulated)
person_count = simulate_object_detection()

# Prepare payload for EdgeBrain
payload = {
"device_id": "webcam_01",
"device_type": "camera",
"value": person_count,
"unit": "persons",
"room": "living_room",
"extra": {
"model": "yolov8n",
"confidence": round(random.uniform(0.7, 0.99), 2)
}
}

# Publish to EdgeBrain
client.publish(MQTT_TOPIC, json.dumps(payload))
print(f"Published detection: {person_count} persons detected")

time.sleep(2) # Process a frame every 2 seconds

except KeyboardInterrupt:
print("Stopping object detection.")
finally:
client.loop_stop()
client.disconnect()

if __name__ == "__main__":
main()
86 changes: 86 additions & 0 deletions examples/sentiment_analysis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
"""
Example: Sentiment Analysis on Text

This script demonstrates integrating a text-based AI task with EdgeBrain.
It performs sentiment analysis on incoming text streams (e.g., social media
mentions or customer feedback) and publishes the sentiment score.

Requirements:
- paho-mqtt

Usage:
python sentiment_analysis.py
"""

import time
import json
import random
import paho.mqtt.client as mqtt

# Configuration for EdgeBrain MQTT Broker
MQTT_BROKER = "localhost"
MQTT_PORT = 1883
MQTT_TOPIC = "edgebrain/devices/sentiment_analyzer_01/data"

SAMPLE_TEXTS = [
"The new feature is amazing, I love it!",
"System is completely broken, please fix immediately.",
"It's okay, but could be better.",
"I'm neutral on this change.",
"Absolutely terrible experience today."
]

def analyze_sentiment(text):
"""
Simulates a sentiment analysis model (e.g., HuggingFace transformers).
Returns a sentiment score between -1.0 (negative) and 1.0 (positive).
"""
if "amazing" in text or "love" in text:
return 0.9
elif "broken" in text or "terrible" in text:
return -0.8
elif "better" in text:
return 0.2
else:
return 0.0

def main():
client = mqtt.Client(client_id="sentiment_analyzer_01")

try:
client.connect(MQTT_BROKER, MQTT_PORT, 60)
except ConnectionRefusedError:
print(f"Error: Could not connect to MQTT broker at {MQTT_BROKER}:{MQTT_PORT}")
return

print("Starting Sentiment Analysis stream...")

try:
while True:
text = random.choice(SAMPLE_TEXTS)
score = analyze_sentiment(text)

# Publish to EdgeBrain
payload = {
"device_id": "sentiment_analyzer_01",
"device_type": "text_analyzer",
"value": score,
"unit": "sentiment_score",
"room": "cloud_service",
"extra": {
"source_text": text
}
}

client.publish(MQTT_TOPIC, json.dumps(payload))
print(f"Analyzed text: '{text}' | Score: {score}")

time.sleep(3)

except KeyboardInterrupt:
print("Stopping sentiment analysis.")
finally:
client.disconnect()

if __name__ == "__main__":
main()