mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
修改python服务端内容-自定义指令接受发送
This commit is contained in:
parent
904729599e
commit
e37b3607db
5 changed files with 147 additions and 2 deletions
|
|
@ -68,6 +68,14 @@ def get_config_from_api(config):
|
||||||
"vision_explain": config["server"].get("vision_explain", ""),
|
"vision_explain": config["server"].get("vision_explain", ""),
|
||||||
"auth_key": config["server"].get("auth_key", ""),
|
"auth_key": config["server"].get("auth_key", ""),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# 获取ssl配置
|
||||||
|
if config.get("ssl"):
|
||||||
|
config_data["ssl"] = {
|
||||||
|
"enabled": config["ssl"].get("enabled", False),
|
||||||
|
"certfile": config["ssl"].get("certfile", ""),
|
||||||
|
"keyfile": config["ssl"].get("keyfile", ""),
|
||||||
|
}
|
||||||
return config_data
|
return config_data
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -191,3 +191,17 @@ def init_service(config):
|
||||||
|
|
||||||
def manage_api_http_safe_close():
|
def manage_api_http_safe_close():
|
||||||
ManageApiClient.safe_close()
|
ManageApiClient.safe_close()
|
||||||
|
|
||||||
|
# 自定义获取指令集合
|
||||||
|
def get_device_commands(mac_address: str) -> Optional[Dict]:
|
||||||
|
"""获取设备命令"""
|
||||||
|
try:
|
||||||
|
return ManageApiClient._instance._execute_request(
|
||||||
|
"POST", f"/device/command/consume",
|
||||||
|
json={
|
||||||
|
"deviceId": mac_address
|
||||||
|
},
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"获取设备命令失败: {e}")
|
||||||
|
return None
|
||||||
|
|
|
||||||
|
|
@ -38,6 +38,7 @@ from config.config_loader import get_private_config_from_api
|
||||||
from core.providers.tts.dto.dto import ContentType, TTSMessageDTO, SentenceType
|
from core.providers.tts.dto.dto import ContentType, TTSMessageDTO, SentenceType
|
||||||
from config.logger import setup_logging, build_module_string, update_module_string
|
from config.logger import setup_logging, build_module_string, update_module_string
|
||||||
from config.manage_api_client import DeviceNotFoundException, DeviceBindException
|
from config.manage_api_client import DeviceNotFoundException, DeviceBindException
|
||||||
|
from config.manage_api_client import DeviceNotFoundException, DeviceBindException, get_device_commands
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
@ -49,6 +50,9 @@ class TTSException(RuntimeError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# 全局字典,最高效的 device_id -> websocket 映射
|
||||||
|
DEVICE_WS_MAP = {}
|
||||||
|
|
||||||
class ConnectionHandler:
|
class ConnectionHandler:
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
|
|
@ -188,6 +192,12 @@ class ConnectionHandler:
|
||||||
self.websocket = ws
|
self.websocket = ws
|
||||||
self.device_id = self.headers.get("device-id", None)
|
self.device_id = self.headers.get("device-id", None)
|
||||||
|
|
||||||
|
# 最高效:建立 device_id 到 websocket 的映射
|
||||||
|
if self.device_id:
|
||||||
|
DEVICE_WS_MAP[self.device_id] = self
|
||||||
|
print(f"设备 {self.device_id} 已连接,映射到 websocket")
|
||||||
|
print(f"当前连接的设备数量: {DEVICE_WS_MAP}")
|
||||||
|
|
||||||
# 启动超时检查任务
|
# 启动超时检查任务
|
||||||
self.timeout_task = asyncio.create_task(self._check_timeout())
|
self.timeout_task = asyncio.create_task(self._check_timeout())
|
||||||
|
|
||||||
|
|
@ -200,6 +210,12 @@ class ConnectionHandler:
|
||||||
# 异步初始化
|
# 异步初始化
|
||||||
self.executor.submit(self._initialize_components)
|
self.executor.submit(self._initialize_components)
|
||||||
|
|
||||||
|
# 等待初始化完成(可选:如果你有初始化完成的信号,可以await)
|
||||||
|
# await asyncio.sleep(1) # 这里可以用更优雅的方式判断初始化完成
|
||||||
|
|
||||||
|
# 初始化完成后再调用
|
||||||
|
await self.run_device_commands()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
async for message in self.websocket:
|
async for message in self.websocket:
|
||||||
await self._route_message(message)
|
await self._route_message(message)
|
||||||
|
|
@ -961,6 +977,10 @@ class ConnectionHandler:
|
||||||
elif self.websocket:
|
elif self.websocket:
|
||||||
await self.websocket.close()
|
await self.websocket.close()
|
||||||
|
|
||||||
|
# 最高效:移除 device_id 到 websocket 的映射
|
||||||
|
if self.device_id and self.device_id in DEVICE_WS_MAP:
|
||||||
|
DEVICE_WS_MAP.pop(self.device_id, None)
|
||||||
|
|
||||||
# 最后关闭线程池(避免阻塞)
|
# 最后关闭线程池(避免阻塞)
|
||||||
if self.executor:
|
if self.executor:
|
||||||
self.executor.shutdown(wait=False)
|
self.executor.shutdown(wait=False)
|
||||||
|
|
@ -1024,3 +1044,40 @@ class ConnectionHandler:
|
||||||
break
|
break
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"超时检查任务出错: {e}")
|
self.logger.bind(tag=TAG).error(f"超时检查任务出错: {e}")
|
||||||
|
|
||||||
|
# 自定义指令------------------------------------------------------------------------
|
||||||
|
async def run_device_commands(self):
|
||||||
|
# 如果设备ID带有-,说明并不是真的设备ID,而是一个虚拟设备ID
|
||||||
|
if "-" in self.device_id:
|
||||||
|
print(f"并不是真正的设备,停止指令发送: {self.device_id}")
|
||||||
|
return
|
||||||
|
command = get_device_commands(self.device_id)
|
||||||
|
print(f"获取设备指令1: {self.device_id}")
|
||||||
|
print(f"获取设备指令2++++++++++++++++++++++++++++++++: {command}")
|
||||||
|
if command is None:
|
||||||
|
self.logger.bind(tag=TAG).error("获取设备指令失败,无法发送命令")
|
||||||
|
return
|
||||||
|
# 根据不同类型的命令进行处理
|
||||||
|
# 如果commandType是 "message" 则直接发送消息
|
||||||
|
# [{'id': '32a862b5a118446ea84044e5796830d1', 'deviceId': '10:20:ba:00:00:68', 'commandType': 'message', 'commandContent': '孩子,你需要上学了,听话', 'isExecuted': 0, 'creator': None, 'createDate': '2025-06-10 16:53:56', 'updater': None, 'updateDate': None}, {'id': '80586238070144d2ac9ab687cfb53ae7', 'deviceId': '10:20:ba:00:00:68', 'commandType': 'message', 'commandContent': '孩子,你需要上学了,听话', 'isExecuted': 0, 'creator': None, 'createDate': '2025-06-10 16:33:17', 'updater': None, 'updateDate': None}]
|
||||||
|
# 获取队列里的第一条指令,并进行处理
|
||||||
|
# 如果有第一条指令,则发送
|
||||||
|
commandContentand = command.get("commandContent", command)
|
||||||
|
if not commandContentand:
|
||||||
|
self.logger.bind(tag=TAG).error("设备指令内容为空,无法发送")
|
||||||
|
return
|
||||||
|
# 通过websocket发送指令
|
||||||
|
# await asyncio.sleep(10) # 这里可以用更优雅的方式判断初始化完成
|
||||||
|
fake_message = json.dumps({
|
||||||
|
"type": "listen",
|
||||||
|
"mode": "manual",
|
||||||
|
"state": "detect",
|
||||||
|
"text": f"{commandContentand}"
|
||||||
|
})
|
||||||
|
await handleTextMessage(self, fake_message)
|
||||||
|
print(f"发送设备指令: {commandContentand}")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_ws_by_device_id(device_id):
|
||||||
|
"""根据 device_id 获取 websocket 连接实例"""
|
||||||
|
return DEVICE_WS_MAP.get(device_id)
|
||||||
|
|
|
||||||
|
|
@ -161,6 +161,62 @@ async def handleTextMessage(conn, message):
|
||||||
# 重启服务器
|
# 重启服务器
|
||||||
elif msg_json["action"] == "restart":
|
elif msg_json["action"] == "restart":
|
||||||
await conn.handle_restart(msg_json)
|
await conn.handle_restart(msg_json)
|
||||||
|
# 检查设备在线状态
|
||||||
|
elif msg_json["action"] == "check_online":
|
||||||
|
print(f"收到检查设备在线状态的请求:{msg_json}")
|
||||||
|
content = msg_json.get("content", {})
|
||||||
|
device_id = content.get("deviceId", "")
|
||||||
|
device_websocket = conn.get_ws_by_device_id(device_id)
|
||||||
|
await conn.websocket.send(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"type": "server",
|
||||||
|
"status": "success",
|
||||||
|
"message": "设备在线" if device_websocket is not None else "设备不在线",
|
||||||
|
"online": device_websocket is not None,
|
||||||
|
"content": {"action": "check_online"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
# 收到模拟说话的请求
|
||||||
|
elif msg_json["action"] == "command":
|
||||||
|
content = msg_json.get("content", {})
|
||||||
|
device_websocket = conn.get_ws_by_device_id(
|
||||||
|
content["deviceId"])
|
||||||
|
original_text = content.get("command", "")
|
||||||
|
print(f"收到模拟说话的请求:{original_text}")
|
||||||
|
print(f"收到模拟说话的请求:{device_websocket}")
|
||||||
|
# 设备在线,立即发送数据包
|
||||||
|
if device_websocket is not None and original_text != "":
|
||||||
|
print(f"设备在线,直接发送:{msg_json}")
|
||||||
|
await conn.websocket.send(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"type": "server",
|
||||||
|
"status": "success",
|
||||||
|
"message": "模拟说话请求已发送到设备",
|
||||||
|
"content": {"action": "command"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
await handleAbortMessage(device_websocket)
|
||||||
|
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
|
||||||
|
enqueue_asr_report(device_websocket, original_text, [])
|
||||||
|
# 否则需要LLM对文字内容进行答复
|
||||||
|
await startToChat(device_websocket, original_text)
|
||||||
|
else:
|
||||||
|
print("设备不在线,发送失败")
|
||||||
|
await conn.websocket.send(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"type": "server",
|
||||||
|
"status": "fail",
|
||||||
|
"message": "设备不在线或命令为空",
|
||||||
|
"content": {"action": "command"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
conn.logger.bind(tag=TAG).error(f"收到未知类型消息:{message}")
|
conn.logger.bind(tag=TAG).error(f"收到未知类型消息:{message}")
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ from core.connection import ConnectionHandler
|
||||||
from config.config_loader import get_config_from_api
|
from config.config_loader import get_config_from_api
|
||||||
from core.utils.modules_initialize import initialize_modules
|
from core.utils.modules_initialize import initialize_modules
|
||||||
from core.utils.util import check_vad_update, check_asr_update
|
from core.utils.util import check_vad_update, check_asr_update
|
||||||
|
import ssl
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -37,8 +37,18 @@ class WebSocketServer:
|
||||||
host = server_config.get("ip", "0.0.0.0")
|
host = server_config.get("ip", "0.0.0.0")
|
||||||
port = int(server_config.get("port", 8000))
|
port = int(server_config.get("port", 8000))
|
||||||
|
|
||||||
|
# 如果配置了SSL证书,则使用SSL
|
||||||
|
ssl_context = None
|
||||||
|
ssl_config = self.config["ssl"]
|
||||||
|
if ssl_config.get("enabled", False):
|
||||||
|
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||||
|
ssl_context.load_cert_chain(
|
||||||
|
ssl_config["certfile"],
|
||||||
|
keyfile=ssl_config["keyfile"]
|
||||||
|
)
|
||||||
|
print(f"run with SSL")
|
||||||
async with websockets.serve(
|
async with websockets.serve(
|
||||||
self._handle_connection, host, port, process_request=self._http_response
|
self._handle_connection, host, port, process_request=self._http_response, ssl=ssl_context
|
||||||
):
|
):
|
||||||
await asyncio.Future()
|
await asyncio.Future()
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue