2025-09-20 16:50:45 +08:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
"""
|
|
|
|
MQTT Connection Test Example
|
|
|
|
IP: 192.168.189.97
|
|
|
|
Port: 1883
|
|
|
|
"""
|
2025-07-14 10:29:37 +08:00
|
|
|
|
2025-09-20 16:50:45 +08:00
|
|
|
import paho.mqtt.client as mqtt
|
2025-07-14 10:29:37 +08:00
|
|
|
import time
|
2025-09-20 16:50:45 +08:00
|
|
|
import json
|
2025-07-14 10:29:37 +08:00
|
|
|
from datetime import datetime
|
|
|
|
|
2025-09-20 16:50:45 +08:00
|
|
|
|
|
|
|
class MQTTService:
|
|
|
|
def __init__(self, host="192.168.189.97", port=1883, keepalive=60):
|
|
|
|
self.host = host
|
|
|
|
self.port = port
|
|
|
|
self.keepalive = keepalive
|
|
|
|
self.client = mqtt.Client()
|
|
|
|
|
|
|
|
# Set callback functions
|
|
|
|
self.client.on_connect = self.on_connect
|
|
|
|
self.client.on_message = self.on_message
|
|
|
|
self.client.on_disconnect = self.on_disconnect
|
|
|
|
self.client.on_publish = self.on_publish
|
|
|
|
|
|
|
|
def on_connect(self, client, userdata, flags, rc):
|
|
|
|
"""Connection callback"""
|
|
|
|
if rc == 0:
|
|
|
|
print(f"Successfully connected to MQTT server {self.host}:{self.port}")
|
|
|
|
# Subscribe to topics after successful connection
|
|
|
|
self.client.subscribe("vwed/task/status")
|
|
|
|
self.client.subscribe("vwed/device/+/data")
|
|
|
|
print("Subscribed to topics: vwed/task/status, vwed/device/+/data")
|
2025-07-14 10:29:37 +08:00
|
|
|
else:
|
2025-09-20 16:50:45 +08:00
|
|
|
print(f"Connection failed, error code: {rc}")
|
|
|
|
|
|
|
|
def on_message(self, client, userdata, msg):
|
|
|
|
"""Message received callback"""
|
2025-07-14 10:29:37 +08:00
|
|
|
try:
|
2025-09-20 16:50:45 +08:00
|
|
|
topic = msg.topic
|
|
|
|
payload = msg.payload.decode('utf-8')
|
|
|
|
print(f"Received message - Topic: {topic}")
|
|
|
|
print(f"Payload: {payload}")
|
|
|
|
print(f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
|
|
|
print("-" * 50)
|
|
|
|
except Exception as e:
|
|
|
|
print(f"Error processing message: {e}")
|
2025-07-14 10:29:37 +08:00
|
|
|
|
2025-09-20 16:50:45 +08:00
|
|
|
def on_disconnect(self, client, userdata, rc):
|
|
|
|
"""Disconnect callback"""
|
|
|
|
print(f"Disconnected from MQTT server, code: {rc}")
|
|
|
|
|
|
|
|
def on_publish(self, client, userdata, mid):
|
|
|
|
"""Message publish callback"""
|
|
|
|
print(f"Message published successfully, message ID: {mid}")
|
|
|
|
|
|
|
|
def connect(self):
|
|
|
|
"""Connect to MQTT server"""
|
2025-07-14 10:29:37 +08:00
|
|
|
try:
|
2025-09-20 16:50:45 +08:00
|
|
|
print(f"Connecting to MQTT server {self.host}:{self.port}...")
|
|
|
|
self.client.connect(self.host, self.port, self.keepalive)
|
|
|
|
return True
|
|
|
|
except Exception as e:
|
|
|
|
print(f"Connection failed: {e}")
|
|
|
|
return False
|
2025-07-14 10:29:37 +08:00
|
|
|
|
2025-09-20 16:50:45 +08:00
|
|
|
def disconnect(self):
|
|
|
|
"""Disconnect from server"""
|
|
|
|
self.client.disconnect()
|
|
|
|
|
|
|
|
def publish(self, topic, payload, qos=0, retain=False):
|
|
|
|
"""Publish message"""
|
|
|
|
try:
|
|
|
|
if isinstance(payload, dict):
|
|
|
|
payload = json.dumps(payload, ensure_ascii=False)
|
2025-07-14 10:29:37 +08:00
|
|
|
|
2025-09-20 16:50:45 +08:00
|
|
|
result = self.client.publish(topic, payload, qos, retain)
|
|
|
|
if result.rc == mqtt.MQTT_ERR_SUCCESS:
|
|
|
|
print(f"Published message to topic {topic}: {payload}")
|
|
|
|
return True
|
2025-07-14 10:29:37 +08:00
|
|
|
else:
|
2025-09-20 16:50:45 +08:00
|
|
|
print(f"Failed to publish message, error code: {result.rc}")
|
|
|
|
return False
|
|
|
|
except Exception as e:
|
|
|
|
print(f"Error publishing message: {e}")
|
|
|
|
return False
|
2025-07-14 10:29:37 +08:00
|
|
|
|
2025-09-20 16:50:45 +08:00
|
|
|
def subscribe(self, topic, qos=0):
|
|
|
|
"""Subscribe to topic"""
|
|
|
|
try:
|
|
|
|
result = self.client.subscribe(topic, qos)
|
|
|
|
if result[0] == mqtt.MQTT_ERR_SUCCESS:
|
|
|
|
print(f"Successfully subscribed to topic: {topic}")
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
print(f"Failed to subscribe to topic, error code: {result[0]}")
|
|
|
|
return False
|
|
|
|
except Exception as e:
|
|
|
|
print(f"Error subscribing to topic: {e}")
|
|
|
|
return False
|
2025-07-14 10:29:37 +08:00
|
|
|
|
2025-09-20 16:50:45 +08:00
|
|
|
def start_loop(self):
|
|
|
|
"""Start message loop"""
|
|
|
|
self.client.loop_start()
|
|
|
|
|
|
|
|
def stop_loop(self):
|
|
|
|
"""Stop message loop"""
|
|
|
|
self.client.loop_stop()
|
|
|
|
|
|
|
|
|
|
|
|
def test_mqtt_connection():
|
|
|
|
"""Test MQTT connection"""
|
|
|
|
print("=== MQTT Connection Test ===")
|
|
|
|
|
|
|
|
# Create MQTT service instance
|
|
|
|
mqtt_service = MQTTService()
|
|
|
|
|
|
|
|
# Connect to server
|
|
|
|
if mqtt_service.connect():
|
|
|
|
# Start message loop
|
|
|
|
mqtt_service.start_loop()
|
2025-07-14 10:29:37 +08:00
|
|
|
|
2025-09-20 16:50:45 +08:00
|
|
|
# Wait for connection to establish
|
|
|
|
time.sleep(2)
|
2025-07-14 10:29:37 +08:00
|
|
|
|
2025-09-20 16:50:45 +08:00
|
|
|
# Publish test messages
|
|
|
|
test_data = {
|
|
|
|
"device_id": "robot_001",
|
|
|
|
"status": "running",
|
|
|
|
"battery": 85,
|
|
|
|
"position": {"x": 100, "y": 200},
|
|
|
|
"timestamp": datetime.now().isoformat()
|
|
|
|
}
|
2025-07-14 10:29:37 +08:00
|
|
|
|
2025-09-20 16:50:45 +08:00
|
|
|
mqtt_service.publish("vwed/device/robot_001/data", test_data)
|
|
|
|
mqtt_service.publish("vwed/task/status", "Task is running...")
|
2025-07-14 10:29:37 +08:00
|
|
|
|
2025-09-20 16:50:45 +08:00
|
|
|
# Keep connection alive and listen for messages
|
|
|
|
print("Keeping connection alive for 30 seconds, listening for messages...")
|
|
|
|
time.sleep(30)
|
2025-07-14 10:29:37 +08:00
|
|
|
|
2025-09-20 16:50:45 +08:00
|
|
|
# Stop loop and disconnect
|
|
|
|
mqtt_service.stop_loop()
|
|
|
|
mqtt_service.disconnect()
|
|
|
|
print("Test completed")
|
|
|
|
else:
|
|
|
|
print("Unable to connect to MQTT server")
|
2025-07-14 10:29:37 +08:00
|
|
|
|
2025-04-30 16:57:46 +08:00
|
|
|
|
2025-07-14 10:29:37 +08:00
|
|
|
if __name__ == "__main__":
|
2025-09-20 16:50:45 +08:00
|
|
|
test_mqtt_connection()
|