""" 通讯API路由 """ from fastapi import APIRouter, HTTPException from pydantic import BaseModel from typing import List import uuid from datetime import datetime from ...core import EntityInfo, Message, RedisAdapter router = APIRouter() # 全局存储(生产环境应使用数据库) entities: dict[str, EntityInfo] = {} adapters: dict[str, RedisAdapter] = {} class EntityCreate(BaseModel): name: str redis_host: str = "localhost" redis_port: int = 6379 redis_db: int = 0 class MessageSend(BaseModel): sender_id: str receiver_id: str content: str class MessageResponse(BaseModel): sender_id: str receiver_id: str timestamp: str content: str @router.post("/entities", response_model=dict) async def create_entity(entity: EntityCreate): """创建新实体""" entity_id = str(uuid.uuid4()) channel = entity_id entity_info = EntityInfo( id=entity_id, name=entity.name, redis_host=entity.redis_host, redis_port=entity.redis_port, redis_db=entity.redis_db, channel=channel ) entities[entity_id] = entity_info return { "id": entity_id, "name": entity.name, "status": "created" } @router.get("/entities", response_model=List[dict]) async def list_entities(): """获取所有实体列表""" return [ { "id": entity_id, "name": entity.name, "redis_host": entity.redis_host, "redis_port": entity.redis_port, "redis_db": entity.redis_db } for entity_id, entity in entities.items() ] @router.post("/entities/{entity_id}/start") async def start_entity(entity_id: str): """启动实体通讯""" if entity_id not in entities: raise HTTPException(status_code=404, detail="Entity not found") if entity_id in adapters: raise HTTPException(status_code=400, detail="Entity already started") adapter = RedisAdapter(entities[entity_id]) if adapter.start(): adapters[entity_id] = adapter return {"status": "started"} else: raise HTTPException(status_code=500, detail="Failed to start entity") @router.post("/entities/{entity_id}/stop") async def stop_entity(entity_id: str): """停止实体通讯""" if entity_id not in adapters: raise HTTPException(status_code=404, detail="Entity not started") adapters[entity_id].stop() del adapters[entity_id] return {"status": "stopped"} @router.post("/messages/send") async def send_message(message: MessageSend): """发送消息""" if message.sender_id not in adapters: raise HTTPException(status_code=404, detail="Sender not started") if message.receiver_id not in entities: raise HTTPException(status_code=404, detail="Receiver not found") adapter = adapters[message.sender_id] success = adapter.send_message(message.receiver_id, message.content) if success: return {"status": "sent"} else: raise HTTPException(status_code=500, detail="Failed to send message") @router.get("/entities/{entity_id}/messages", response_model=List[MessageResponse]) async def get_entity_messages(entity_id: str): """获取实体的消息历史(临时存储,演示用)""" # 这里只是示例,实际应该从持久化存储获取 return []