Skip to content

Commit f34fa7b

Browse files
committed
server.py added for getting feed from online link
1 parent 8fb2037 commit f34fa7b

File tree

12 files changed

+550
-6
lines changed

12 files changed

+550
-6
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
software/cricket.pt

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,11 @@
11
# Security Camera Team 3
2+
3+
4+
MQTT Message Format:
5+
6+
objects = [{'class': classes[i], 'confidence': confidences[i]} for i in range(len(classes))]
7+
8+
message = {
9+
"objects": objects,
10+
"timestamp": datetime.now().isoformat()
11+
}

software/50epoch.pt

21.5 MB
Binary file not shown.
5.95 KB
Binary file not shown.

software/mqtt_client.py

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
"""
2+
MQTT Client Module for Security Camera
3+
Handles MQTT connection and message publishing for object detection alerts
4+
"""
5+
import paho.mqtt.client as mqtt
6+
import json
7+
from datetime import datetime
8+
import threading
9+
import time
10+
11+
# MQTT Configuration
12+
MQTT_BROKER = "mqtt.a5-p.cn"
13+
MQTT_PORT = 1883
14+
MQTT_USERNAME = "forge"
15+
MQTT_PASSWORD = "zDHRPjrH1G5iETx"
16+
MQTT_TOPIC = "security_camera/detections"
17+
18+
class MQTTClient:
19+
"""MQTT Client for sending detection messages"""
20+
21+
def __init__(self):
22+
self.client = None
23+
self.connected = False
24+
self.connection_lock = threading.Lock()
25+
26+
def setup_connection(self):
27+
"""Setup MQTT client and establish connection"""
28+
try:
29+
self.client = mqtt.Client()
30+
self.client.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD)
31+
32+
# Set up callbacks
33+
self.client.on_connect = self._on_connect
34+
self.client.on_disconnect = self._on_disconnect
35+
self.client.on_publish = self._on_publish
36+
37+
# Connect to broker
38+
self.client.connect(MQTT_BROKER, MQTT_PORT, 60)
39+
self.client.loop_start()
40+
41+
# Wait a moment for connection to establish
42+
time.sleep(1)
43+
return self.connected
44+
45+
except Exception as e:
46+
print(f"❌ Error setting up MQTT connection: {e}")
47+
return False
48+
49+
def _on_connect(self, client, userdata, flags, rc):
50+
"""Callback for when client connects to broker"""
51+
if rc == 0:
52+
self.connected = True
53+
print("✅ Connected to MQTT broker")
54+
else:
55+
self.connected = False
56+
print(f"❌ Failed to connect to MQTT broker. Return code: {rc}")
57+
58+
def _on_disconnect(self, client, userdata, rc):
59+
"""Callback for when client disconnects from broker"""
60+
self.connected = False
61+
print("Disconnected from MQTT broker")
62+
63+
def _on_publish(self, client, userdata, mid):
64+
"""Callback for when message is published"""
65+
print(f"📤 Message published successfully (mid: {mid})")
66+
67+
def send_detection(self, classes, confidences, source="rtmp_stream"):
68+
"""Send object detection message to MQTT broker"""
69+
if not self.connected or self.client is None:
70+
print("❌ MQTT client not connected. Cannot send message.")
71+
return False
72+
73+
objects = [{'class': classes[i], 'confidence': confidences[i]} for i in range(len(classes))]
74+
# Create detection message
75+
message = {
76+
"objects": objects,
77+
"timestamp": datetime.now().isoformat()
78+
}
79+
80+
try:
81+
# Publish message
82+
result = self.client.publish(MQTT_TOPIC, json.dumps(message))
83+
84+
if result.rc == mqtt.MQTT_ERR_SUCCESS:
85+
print(f"📤 Sent detection: {objects}")
86+
return True
87+
else:
88+
print(f"❌ Failed to publish message. Return code: {result.rc}")
89+
return False
90+
91+
except Exception as e:
92+
print(f"❌ Error sending MQTT message: {e}")
93+
return False
94+
95+
def disconnect(self):
96+
"""Disconnect from MQTT broker"""
97+
if self.client:
98+
self.client.loop_stop()
99+
self.client.disconnect()
100+
print("Disconnected from MQTT broker")
101+
102+
# Global MQTT client instance
103+
mqtt_client = MQTTClient()
104+
105+
def initialize_mqtt():
106+
"""Initialize MQTT connection"""
107+
return mqtt_client.setup_connection()
108+
109+
def send_detection_message(class_name, confidence, source="rtmp_stream"):
110+
"""Send detection message using global MQTT client"""
111+
return mqtt_client.send_detection(class_name, confidence, source)
112+
113+
def disconnect_mqtt():
114+
"""Disconnect from MQTT broker"""
115+
mqtt_client.disconnect()
116+
117+
def is_mqtt_connected():
118+
"""Check if MQTT client is connected"""
119+
return mqtt_client.connected

software/server.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import cv2
2+
import argparse
3+
from ultralytics import YOLO
4+
from mqtt_client import initialize_mqtt, send_detection_message, is_mqtt_connected
5+
6+
conversion = ["car", "cat", "dog", "person"]
7+
skip_frames = 3
8+
def score_to_bgr(score: float) -> tuple[int, int, int]:
9+
"""Map score in [0,1] to a BGR color from red (low) to green (high)."""
10+
s = max(0.0, min(1.0, float(score)))
11+
g = int(255 * s)
12+
r = int(255 * (1.0 - s))
13+
b = 0
14+
return (b, g, r)
15+
16+
17+
def run_webcam(model, img_size):
18+
frames = skip_frames
19+
20+
# Initialize MQTT connection
21+
print("🔌 Initializing MQTT connection...")
22+
if initialize_mqtt():
23+
print("✅ MQTT connection established")
24+
else:
25+
print("⚠️ MQTT connection failed, continuing without MQTT")
26+
27+
cap = cv2.VideoCapture("rtmps://live.cloudflare.com:443/live/25f7b82374cb80506bafaa1c45e4e70ek7690d120ab117d3b6e1cbcfc3ab3e758")
28+
if not cap.isOpened():
29+
print("Could not open webcam.")
30+
return
31+
print("Press 'q' to quit.")
32+
while True:
33+
ret, frame = cap.read()
34+
if not ret:
35+
break
36+
if frames > 0:
37+
frames -= 1
38+
continue
39+
else:
40+
frames = skip_frames
41+
results = model(frame, imgsz=img_size)
42+
for r in results:
43+
boxes = r.boxes.xyxy.cpu().numpy()
44+
scores = r.boxes.conf.cpu().numpy()
45+
labels = r.boxes.cls.cpu().numpy().astype(int)
46+
for (x1, y1, x2, y2), score, label in zip(boxes, scores, labels):
47+
if score < 0.6:
48+
continue
49+
color = score_to_bgr(score)
50+
text = f"{conversion[int(model.names[label])]}: {score:.2f}" if hasattr(model, 'names') else f"{label}: {score:.2f}"
51+
52+
# Get class name from model
53+
class_name = model.names[label] if hasattr(model, 'names') and label in model.names else f"class_{label}"
54+
text = f"{class_name}: {score:.2f}"
55+
56+
# Send MQTT message for detected object
57+
if is_mqtt_connected():
58+
send_detection_message(class_name, score, "rtmp_stream")
59+
60+
# draw box
61+
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), color, 2)
62+
# text background for readability
63+
(tw, th), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
64+
tx1 = int(x1)
65+
ty1 = int(y1) - th - 6
66+
ty1 = max(0, ty1)
67+
tx2 = tx1 + tw + 6
68+
ty2 = ty1 + th + 6
69+
cv2.rectangle(frame, (tx1, ty1), (tx2, ty2), color, -1)
70+
cv2.putText(frame, text, (tx1 + 3, ty2 - 4), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)
71+
cv2.imshow('webcam', frame)
72+
if cv2.waitKey(1) & 0xFF == ord('q'):
73+
break
74+
cap.release()
75+
cv2.destroyAllWindows()
76+
77+
if __name__ == '__main__':
78+
parser = argparse.ArgumentParser()
79+
parser.add_argument('--model', default='50epoch.pt')
80+
parser.add_argument('--img-size', type=int, nargs=2, default=(320, 320))
81+
args = parser.parse_args()
82+
model = YOLO(args.model)
83+
run_webcam(model, tuple(args.img_size))
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)