mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
fixed mqtt
This commit is contained in:
parent
7640f98c56
commit
bb279a77e7
6 changed files with 260 additions and 19 deletions
|
|
@ -8,4 +8,4 @@ INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, r
|
||||||
VALUES (121, 'mqtt.port', '1883', 'string', 1, 'MQTT broker port');
|
VALUES (121, 'mqtt.port', '1883', 'string', 1, 'MQTT broker port');
|
||||||
|
|
||||||
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark)
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark)
|
||||||
VALUES (122, 'mqtt.signature_key', 'your-secure-signature-key-here', 'string', 1, 'MQTT signature key for authentication');
|
VALUES (122, 'mqtt.signature_key', 'test-signature-key-12345', 'string', 1, 'MQTT signature key for authentication');
|
||||||
197
add_mqtt_params_railway.py
Normal file
197
add_mqtt_params_railway.py
Normal file
|
|
@ -0,0 +1,197 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
Script to add MQTT configuration parameters to Railway MySQL database
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pymysql
|
||||||
|
import sys
|
||||||
|
import io
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
# Set UTF-8 encoding for Windows console
|
||||||
|
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||||
|
|
||||||
|
# Railway MySQL Database configuration
|
||||||
|
DB_CONFIG = {
|
||||||
|
'host': 'nozomi.proxy.rlwy.net',
|
||||||
|
'port': 25037,
|
||||||
|
'user': 'root',
|
||||||
|
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
|
||||||
|
'database': 'railway',
|
||||||
|
'charset': 'utf8mb4'
|
||||||
|
}
|
||||||
|
|
||||||
|
# MQTT parameters to add
|
||||||
|
MQTT_PARAMS = [
|
||||||
|
{
|
||||||
|
'id': 120,
|
||||||
|
'param_code': 'mqtt.broker',
|
||||||
|
'param_value': '192.168.1.107',
|
||||||
|
'value_type': 'string',
|
||||||
|
'param_type': 1,
|
||||||
|
'remark': 'MQTT broker IP address'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'id': 121,
|
||||||
|
'param_code': 'mqtt.port',
|
||||||
|
'param_value': '1883',
|
||||||
|
'value_type': 'string',
|
||||||
|
'param_type': 1,
|
||||||
|
'remark': 'MQTT broker port'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'id': 122,
|
||||||
|
'param_code': 'mqtt.signature_key',
|
||||||
|
'param_value': 'test-signature-key-12345',
|
||||||
|
'value_type': 'string',
|
||||||
|
'param_type': 1,
|
||||||
|
'remark': 'MQTT signature key for authentication'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
def connect_to_db():
|
||||||
|
"""Connect to the Railway MySQL database"""
|
||||||
|
try:
|
||||||
|
connection = pymysql.connect(**DB_CONFIG)
|
||||||
|
print(f"✅ Connected to Railway MySQL database")
|
||||||
|
return connection
|
||||||
|
except pymysql.Error as e:
|
||||||
|
print(f"❌ Failed to connect to database: {e}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
def check_existing_params(cursor, param_code: str) -> Optional[dict]:
|
||||||
|
"""Check if a parameter already exists"""
|
||||||
|
query = "SELECT * FROM sys_params WHERE param_code = %s"
|
||||||
|
cursor.execute(query, (param_code,))
|
||||||
|
result = cursor.fetchone()
|
||||||
|
return result
|
||||||
|
|
||||||
|
def get_next_available_id(cursor) -> int:
|
||||||
|
"""Get the next available ID for sys_params table"""
|
||||||
|
query = "SELECT MAX(id) as max_id FROM sys_params"
|
||||||
|
cursor.execute(query)
|
||||||
|
result = cursor.fetchone()
|
||||||
|
if result and result['max_id']:
|
||||||
|
return result['max_id'] + 1
|
||||||
|
return 120 # Start from 120 if table is empty
|
||||||
|
|
||||||
|
def insert_or_update_param(cursor, param: dict) -> bool:
|
||||||
|
"""Insert a new parameter or update existing one"""
|
||||||
|
try:
|
||||||
|
# First check if it already exists
|
||||||
|
existing = check_existing_params(cursor, param['param_code'])
|
||||||
|
if existing:
|
||||||
|
print(f"⚠️ Parameter '{param['param_code']}' already exists with value: {existing['param_value']}")
|
||||||
|
|
||||||
|
# Update the existing parameter
|
||||||
|
update_query = """
|
||||||
|
UPDATE sys_params
|
||||||
|
SET param_value = %s, remark = %s
|
||||||
|
WHERE param_code = %s
|
||||||
|
"""
|
||||||
|
cursor.execute(update_query, (param['param_value'], param['remark'], param['param_code']))
|
||||||
|
print(f" ✅ Updated parameter '{param['param_code']}' to: {param['param_value']}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Get next available ID if the specified one is taken
|
||||||
|
check_id_query = "SELECT id FROM sys_params WHERE id = %s"
|
||||||
|
cursor.execute(check_id_query, (param['id'],))
|
||||||
|
if cursor.fetchone():
|
||||||
|
param['id'] = get_next_available_id(cursor)
|
||||||
|
print(f" ℹ️ Using ID {param['id']} for '{param['param_code']}'")
|
||||||
|
|
||||||
|
# Insert new parameter
|
||||||
|
insert_query = """
|
||||||
|
INSERT INTO sys_params (id, param_code, param_value, value_type, param_type, remark)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s)
|
||||||
|
"""
|
||||||
|
cursor.execute(insert_query, (
|
||||||
|
param['id'],
|
||||||
|
param['param_code'],
|
||||||
|
param['param_value'],
|
||||||
|
param['value_type'],
|
||||||
|
param['param_type'],
|
||||||
|
param['remark']
|
||||||
|
))
|
||||||
|
print(f"✅ Added parameter '{param['param_code']}' with value: {param['param_value']}")
|
||||||
|
return True
|
||||||
|
except pymysql.Error as e:
|
||||||
|
print(f"❌ Failed to insert/update '{param['param_code']}': {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def verify_params(cursor):
|
||||||
|
"""Verify that all MQTT parameters are in the database"""
|
||||||
|
print("\n📋 Current MQTT parameters in database:")
|
||||||
|
print("-" * 50)
|
||||||
|
query = "SELECT param_code, param_value, remark FROM sys_params WHERE param_code LIKE 'mqtt.%' ORDER BY param_code"
|
||||||
|
cursor.execute(query)
|
||||||
|
results = cursor.fetchall()
|
||||||
|
|
||||||
|
if results:
|
||||||
|
for row in results:
|
||||||
|
print(f" • {row['param_code']}: {row['param_value']}")
|
||||||
|
print(f" ({row['remark']})")
|
||||||
|
else:
|
||||||
|
print(" No MQTT parameters found")
|
||||||
|
|
||||||
|
return len(results) > 0
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("🔧 Railway MySQL - MQTT Parameter Configuration Tool")
|
||||||
|
print("=" * 60)
|
||||||
|
print(f"📍 Connecting to: {DB_CONFIG['host']}:{DB_CONFIG['port']}")
|
||||||
|
print(f"📦 Database: {DB_CONFIG['database']}")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
# Connect to database
|
||||||
|
connection = connect_to_db()
|
||||||
|
|
||||||
|
try:
|
||||||
|
with connection.cursor(pymysql.cursors.DictCursor) as cursor:
|
||||||
|
print("\n📝 Adding/Updating MQTT parameters...")
|
||||||
|
print("-" * 50)
|
||||||
|
|
||||||
|
# Add each parameter
|
||||||
|
changes_made = False
|
||||||
|
for param in MQTT_PARAMS:
|
||||||
|
if insert_or_update_param(cursor, param):
|
||||||
|
changes_made = True
|
||||||
|
|
||||||
|
# Commit changes
|
||||||
|
if changes_made:
|
||||||
|
connection.commit()
|
||||||
|
print("\n✅ All changes committed to database")
|
||||||
|
else:
|
||||||
|
print("\n⚠️ No changes were made")
|
||||||
|
|
||||||
|
# Verify parameters
|
||||||
|
verify_params(cursor)
|
||||||
|
|
||||||
|
print("\n" + "=" * 60)
|
||||||
|
print("✅ MQTT parameters configuration complete!")
|
||||||
|
print("\n⚠️ IMPORTANT NEXT STEPS:")
|
||||||
|
print(" 1. Restart the manager-api server for changes to take effect")
|
||||||
|
print(" 2. The ESP32 device should now receive MQTT configuration")
|
||||||
|
print(" 3. The Python client should also connect successfully")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ An error occurred: {e}")
|
||||||
|
connection.rollback()
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
print("\n🔌 Database connection closed")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print("\n🚀 This script will configure MQTT parameters in your Railway MySQL database")
|
||||||
|
print(" The following parameters will be added/updated:")
|
||||||
|
print(" • mqtt.broker: 139.59.7.72")
|
||||||
|
print(" • mqtt.port: 1883")
|
||||||
|
print(" • mqtt.signature_key: test-signature-key-12345\n")
|
||||||
|
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\n\n❌ Operation cancelled by user")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"\n❌ Unexpected error: {e}")
|
||||||
39
clear_redis.py
Normal file
39
clear_redis.py
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
import redis
|
||||||
|
|
||||||
|
# Redis connection configuration
|
||||||
|
redis_client = redis.Redis(
|
||||||
|
host='maglev.proxy.rlwy.net',
|
||||||
|
port=16780,
|
||||||
|
password='beVfOKcZjMUCBiZIQnvSMivhpSeijpKP',
|
||||||
|
username='default',
|
||||||
|
db=0,
|
||||||
|
decode_responses=True
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
print("Connecting to Redis...")
|
||||||
|
# Test connection
|
||||||
|
redis_client.ping()
|
||||||
|
print("Successfully connected to Redis!")
|
||||||
|
|
||||||
|
# Get all keys to see what's cached
|
||||||
|
keys = redis_client.keys('*')
|
||||||
|
print(f"Found {len(keys)} keys in Redis:")
|
||||||
|
for key in keys[:10]: # Show first 10 keys
|
||||||
|
print(f" - {key}")
|
||||||
|
|
||||||
|
if len(keys) > 10:
|
||||||
|
print(f" ... and {len(keys) - 10} more keys")
|
||||||
|
|
||||||
|
# Clear all data in current database
|
||||||
|
result = redis_client.flushdb()
|
||||||
|
print(f"Redis cache cleared: {result}")
|
||||||
|
|
||||||
|
# Verify it's cleared
|
||||||
|
keys_after = redis_client.keys('*')
|
||||||
|
print(f"Keys remaining after clear: {len(keys_after)}")
|
||||||
|
|
||||||
|
except redis.exceptions.ConnectionError as e:
|
||||||
|
print(f"Failed to connect to Redis: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error: {e}")
|
||||||
|
|
@ -24,7 +24,7 @@ public class DeviceReportRespDTO {
|
||||||
private Websocket websocket;
|
private Websocket websocket;
|
||||||
|
|
||||||
@Schema(description = "MQTT配置")
|
@Schema(description = "MQTT配置")
|
||||||
private Mqtt mqtt_gateway;
|
private Mqtt mqtt;
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
|
|
|
||||||
|
|
@ -183,7 +183,7 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
||||||
// Always include MQTT credentials for all devices (both registered and unregistered)
|
// Always include MQTT credentials for all devices (both registered and unregistered)
|
||||||
DeviceReportRespDTO.Mqtt mqttCredentials = buildMqttCredentials(macAddress);
|
DeviceReportRespDTO.Mqtt mqttCredentials = buildMqttCredentials(macAddress);
|
||||||
if (mqttCredentials != null) {
|
if (mqttCredentials != null) {
|
||||||
response.setMqtt_gateway(mqttCredentials);
|
response.setMqtt(mqttCredentials);
|
||||||
log.info("Added MQTT credentials to response for device: {}", macAddress);
|
log.info("Added MQTT credentials to response for device: {}", macAddress);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -19,9 +19,9 @@ import opuslib
|
||||||
|
|
||||||
# --- Configuration ---
|
# --- Configuration ---
|
||||||
|
|
||||||
SERVER_IP = "139.59.7.72" # !!! UPDATE with your server's local IP address !!!
|
SERVER_IP = "192.168.1.107" # !!! UPDATE with your server's local IP address !!!
|
||||||
OTA_PORT = 8002
|
OTA_PORT = 8002
|
||||||
MQTT_BROKER_HOST = "139.59.7.72" # MQTT gateway IP
|
MQTT_BROKER_HOST = "192.168.1.107" # MQTT gateway IP
|
||||||
|
|
||||||
|
|
||||||
MQTT_BROKER_PORT = 1883
|
MQTT_BROKER_PORT = 1883
|
||||||
|
|
@ -399,22 +399,14 @@ class TestClient:
|
||||||
def connect_mqtt(self) -> bool:
|
def connect_mqtt(self) -> bool:
|
||||||
"""Connects to the MQTT Broker."""
|
"""Connects to the MQTT Broker."""
|
||||||
# Get MQTT configuration from OTA response
|
# Get MQTT configuration from OTA response
|
||||||
mqtt_config = self.ota_config.get("mqtt", {})
|
mqtt_config = self.ota_config.get("mqtt_gateway", {})
|
||||||
|
|
||||||
# Try to get broker and port from the config
|
|
||||||
mqtt_broker = mqtt_config.get("broker", MQTT_BROKER_HOST)
|
mqtt_broker = mqtt_config.get("broker", MQTT_BROKER_HOST)
|
||||||
mqtt_port = mqtt_config.get("port", MQTT_BROKER_PORT)
|
mqtt_port = mqtt_config.get("port", MQTT_BROKER_PORT)
|
||||||
|
|
||||||
# If broker/port not directly available, try parsing from endpoint
|
logger.info(f"📍 MQTT Config from OTA: {mqtt_config}")
|
||||||
if not mqtt_broker or mqtt_broker == MQTT_BROKER_HOST:
|
logger.info(f"📍 Using MQTT Broker: {mqtt_broker}")
|
||||||
mqtt_endpoint = mqtt_config.get("endpoint", f"{MQTT_BROKER_HOST}:{MQTT_BROKER_PORT}")
|
logger.info(f"📍 Using MQTT Port: {mqtt_port}")
|
||||||
if ':' in mqtt_endpoint:
|
logger.info(f"📍 MQTT Credentials: client_id={self.mqtt_credentials.get('client_id', 'NOT SET')}")
|
||||||
mqtt_broker, port_str = mqtt_endpoint.rsplit(':', 1)
|
|
||||||
mqtt_port = int(port_str)
|
|
||||||
else:
|
|
||||||
mqtt_broker = mqtt_endpoint
|
|
||||||
mqtt_port = MQTT_BROKER_PORT
|
|
||||||
|
|
||||||
logger.info(f"▶️ STEP 2: Connecting to MQTT Gateway at {mqtt_broker}:{mqtt_port}...")
|
logger.info(f"▶️ STEP 2: Connecting to MQTT Gateway at {mqtt_broker}:{mqtt_port}...")
|
||||||
|
|
||||||
self.mqtt_client = mqtt_client.Client(
|
self.mqtt_client = mqtt_client.Client(
|
||||||
|
|
@ -429,16 +421,29 @@ class TestClient:
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
logger.info(f"🔄 Connecting to {mqtt_broker}:{mqtt_port}...")
|
logger.info(f"🔄 Attempting connection to MQTT broker...")
|
||||||
|
logger.info(f" Host: {mqtt_broker}")
|
||||||
|
logger.info(f" Port: {mqtt_port}")
|
||||||
|
logger.info(f" Client ID: {self.mqtt_credentials['client_id']}")
|
||||||
|
logger.info(f" Username: {self.mqtt_credentials['username']}")
|
||||||
|
|
||||||
self.mqtt_client.connect(mqtt_broker, mqtt_port, 60)
|
self.mqtt_client.connect(mqtt_broker, mqtt_port, 60)
|
||||||
self.mqtt_client.loop_start()
|
self.mqtt_client.loop_start()
|
||||||
|
|
||||||
# Wait a moment for connection to establish
|
# Wait a moment for connection to establish
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
|
|
||||||
|
# Check if connected
|
||||||
|
if self.mqtt_client.is_connected():
|
||||||
|
logger.info("✅ MQTT client is connected!")
|
||||||
|
else:
|
||||||
|
logger.warning("⚠️ MQTT client connection status unknown, waiting...")
|
||||||
|
|
||||||
return True
|
return True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"❌ Failed to connect to MQTT Gateway: {e}")
|
logger.error(f"❌ Failed to connect to MQTT Gateway: {e}")
|
||||||
|
logger.error(f" Error type: {type(e).__name__}")
|
||||||
|
logger.error(f" Broker: {mqtt_broker}:{mqtt_port}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def send_hello_and_get_session(self) -> bool:
|
def send_hello_and_get_session(self) -> bool:
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue