diff --git a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java index 8ee25a365..e11d5874d 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java +++ b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java @@ -84,6 +84,11 @@ public interface Constant { */ String SERVER_SECRET = "server.secret"; + /** + * websocket地址 + */ + String SERVER_WEBSOCKET = "server.websocket"; + /** * 是否允许用户注册 */ diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java index e18439a12..eb108eae7 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java @@ -23,11 +23,13 @@ import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; +import xiaozhi.common.constant.Constant; import xiaozhi.modules.device.dto.DeviceReportReqDTO; import xiaozhi.modules.device.dto.DeviceReportRespDTO; import xiaozhi.modules.device.entity.DeviceEntity; import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.device.utils.NetworkUtil; +import xiaozhi.modules.sys.service.SysParamsService; @Tag(name = "设备管理", description = "OTA 相关接口") @Slf4j @@ -36,6 +38,7 @@ import xiaozhi.modules.device.utils.NetworkUtil; @RequestMapping("/ota/") public class OTAController { private final DeviceService deviceService; + private final SysParamsService sysParamsService; @Operation(summary = "OTA版本和设备激活状态检查") @PostMapping @@ -76,7 +79,11 @@ public class OTAController { @GetMapping @Hidden public ResponseEntity getOTA() { - return ResponseEntity.ok("OTA接口运行正常"); + String wsUrl = sysParamsService.getValue(Constant.SERVER_WEBSOCKET, true); + if (StringUtils.isBlank(wsUrl) || wsUrl.equals("null")) { + return ResponseEntity.ok("OTA接口不正常,缺少websocket地址"); + } + return ResponseEntity.ok("OTA接口运行正常,websocket集群数量:" + wsUrl.split(";").length); } @SneakyThrows diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java index 8f6da594f..2006791bc 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java @@ -18,6 +18,7 @@ import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import cn.hutool.core.util.RandomUtil; +import lombok.extern.slf4j.Slf4j; import xiaozhi.common.constant.Constant; import xiaozhi.common.exception.RenException; import xiaozhi.common.page.PageData; @@ -36,6 +37,7 @@ import xiaozhi.modules.security.user.SecurityUser; import xiaozhi.modules.sys.service.SysParamsService; import xiaozhi.modules.sys.service.SysUserUtilService; +@Slf4j @Service public class DeviceServiceImpl extends BaseServiceImpl implements DeviceService { @@ -43,8 +45,6 @@ public class DeviceServiceImpl extends BaseServiceImpl private final SysUserUtilService sysUserUtilService; - private final String frontedUrl; - private final RedisTemplate redisTemplate; private final SysParamsService sysParamsService; @@ -55,7 +55,6 @@ public class DeviceServiceImpl extends BaseServiceImpl RedisTemplate redisTemplate) { this.deviceDao = deviceDao; this.sysUserUtilService = sysUserUtilService; - this.frontedUrl = sysParamsService.getValue(Constant.SERVER_FRONTED_URL, true); this.redisTemplate = redisTemplate; this.sysParamsService = sysParamsService; } @@ -134,15 +133,26 @@ public class DeviceServiceImpl extends BaseServiceImpl firmware.setVersion(deviceReport.getApplication().getVersion()); firmware.setUrl("http://localhost:8002/xiaozhi/ota/download"); response.setFirmware(firmware); - + // 添加WebSocket配置 DeviceReportRespDTO.Websocket websocket = new DeviceReportRespDTO.Websocket(); // 从系统参数获取WebSocket URL,如果未配置则使用默认值 - String wsUrl = sysParamsService.getValue("websocket_url", true); - if (StringUtils.isBlank(wsUrl)) { - wsUrl = "ws://localhost:8000/xiaozhi/v1/"; + String wsUrl = sysParamsService.getValue(Constant.SERVER_WEBSOCKET, true); + if (StringUtils.isBlank(wsUrl) || wsUrl.equals("null")) { + log.error("WebSocket URL is not configured"); + wsUrl = "ws://xiaozhi.server.com:8000/xiaozhi/v1/"; + websocket.setUrl(wsUrl); + } else { + String[] wsUrls = wsUrl.split("\\;"); + if (wsUrls.length > 0) { + // 随机选择一个WebSocket URL + websocket.setUrl(wsUrls[RandomUtil.randomInt(0, wsUrls.length)]); + } else { + log.error("WebSocket URL list is empty"); + websocket.setUrl("ws://xiaozhi.server.com:8000/xiaozhi/v1/"); + } } - websocket.setUrl(wsUrl); + response.setWebsocket(websocket); DeviceEntity deviceById = getDeviceById(macAddress); @@ -263,11 +273,13 @@ public class DeviceServiceImpl extends BaseServiceImpl if (StringUtils.isNotBlank(cachedCode)) { code.setCode(cachedCode); + String frontedUrl = sysParamsService.getValue(Constant.SERVER_FRONTED_URL, true); code.setMessage(frontedUrl + "\n" + cachedCode); code.setChallenge(deviceId); } else { String newCode = RandomUtil.randomNumbers(6); code.setCode(newCode); + String frontedUrl = sysParamsService.getValue(Constant.SERVER_FRONTED_URL, true); code.setMessage(frontedUrl + "\n" + newCode); code.setChallenge(deviceId); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysParamsController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysParamsController.java index 1951333fd..157eb94eb 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysParamsController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysParamsController.java @@ -2,6 +2,7 @@ package xiaozhi.modules.sys.controller; import java.util.Map; +import org.apache.commons.lang3.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -20,6 +21,7 @@ import io.swagger.v3.oas.annotations.tags.Tag; import lombok.AllArgsConstructor; import xiaozhi.common.annotation.LogOperation; import xiaozhi.common.constant.Constant; +import xiaozhi.common.exception.RenException; import xiaozhi.common.page.PageData; import xiaozhi.common.utils.Result; import xiaozhi.common.validator.AssertUtils; @@ -30,6 +32,7 @@ import xiaozhi.common.validator.group.UpdateGroup; import xiaozhi.modules.config.service.ConfigService; import xiaozhi.modules.sys.dto.SysParamsDTO; import xiaozhi.modules.sys.service.SysParamsService; +import xiaozhi.modules.sys.utils.WebSocketValidator; /** * 参数管理 @@ -91,11 +94,43 @@ public class SysParamsController { // 效验数据 ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class); + // 验证WebSocket地址列表 + validateWebSocketUrls(dto.getParamCode(), dto.getParamValue()); + sysParamsService.update(dto); configService.getConfig(false); return new Result(); } + /** + * 验证WebSocket地址列表 + * + * @param urls WebSocket地址列表,以分号分隔 + * @return 验证结果 + */ + private void validateWebSocketUrls(String paramCode, String urls) { + if (!paramCode.equals(Constant.SERVER_WEBSOCKET)) { + return; + } + String[] wsUrls = urls.split("\\;"); + if (wsUrls.length == 0) { + throw new RenException("WebSocket地址列表不能为空"); + } + for (String url : wsUrls) { + if (StringUtils.isNotBlank(url)) { + // 验证WebSocket地址格式 + if (!WebSocketValidator.validateUrlFormat(url)) { + throw new RenException("WebSocket地址格式不正确: " + url); + } + + // 测试WebSocket连接 + if (!WebSocketValidator.testConnection(url)) { + throw new RenException("WebSocket连接测试失败: " + url); + } + } + } + } + @PostMapping("/delete") @Operation(summary = "删除") @LogOperation("删除") diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/utils/WebSocketTestHandler.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/utils/WebSocketTestHandler.java new file mode 100644 index 000000000..d9563c297 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/utils/WebSocketTestHandler.java @@ -0,0 +1,46 @@ +package xiaozhi.modules.sys.utils; + +import java.util.concurrent.CompletableFuture; + +import org.springframework.web.socket.CloseStatus; +import org.springframework.web.socket.WebSocketHandler; +import org.springframework.web.socket.WebSocketMessage; +import org.springframework.web.socket.WebSocketSession; + +public class WebSocketTestHandler implements WebSocketHandler { + private final CompletableFuture future; + + public WebSocketTestHandler(CompletableFuture future) { + this.future = future; + } + + @Override + public void afterConnectionEstablished(WebSocketSession session) { + future.complete(true); + try { + session.close(); + } catch (Exception e) { + // 忽略关闭异常 + } + } + + @Override + public void handleMessage(WebSocketSession session, WebSocketMessage message) { + // 不需要处理消息 + } + + @Override + public void handleTransportError(WebSocketSession session, Throwable exception) { + future.complete(false); + } + + @Override + public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) { + // 连接关闭时不做任何处理 + } + + @Override + public boolean supportsPartialMessages() { + return false; + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/utils/WebSocketValidator.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/utils/WebSocketValidator.java new file mode 100644 index 000000000..d9ff280b4 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/utils/WebSocketValidator.java @@ -0,0 +1,58 @@ +package xiaozhi.modules.sys.utils; + +import java.net.URI; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.socket.client.WebSocketClient; +import org.springframework.web.socket.client.standard.StandardWebSocketClient; + +public class WebSocketValidator { + private static final Logger logger = LoggerFactory.getLogger(WebSocketValidator.class); + + // WebSocket URL正则表达式 + private static final Pattern WS_URL_PATTERN = Pattern + .compile("^wss?://[\\w.-]+(?:\\.[\\w.-]+)*(?::\\d+)?(?:/[\\w.-]*)*$"); + + /** + * 验证WebSocket地址格式 + * + * @param url WebSocket地址 + * @return 是否有效 + */ + public static boolean validateUrlFormat(String url) { + if (StringUtils.isBlank(url)) { + return false; + } + return WS_URL_PATTERN.matcher(url.trim()).matches(); + } + + /** + * 测试WebSocket连接 + * + * @param url WebSocket地址 + * @return 是否可连接 + */ + public static boolean testConnection(String url) { + if (!validateUrlFormat(url)) { + return false; + } + + try { + WebSocketClient client = new StandardWebSocketClient(); + CompletableFuture future = new CompletableFuture<>(); + + client.doHandshake(new WebSocketTestHandler(future), null, URI.create(url)); + + // 等待最多5秒获取连接结果 + return future.get(5, TimeUnit.SECONDS); + } catch (Exception e) { + logger.error("WebSocket连接测试失败: {}", url, e); + return false; + } + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202504221644.sql b/main/manager-api/src/main/resources/db/changelog/202504221644.sql new file mode 100644 index 000000000..8237b247d --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202504221644.sql @@ -0,0 +1,7 @@ +-- 删除server.ip和server.port,改成在xiaozhi-server中配置,方便运行多个websocket +delete from `sys_params` where id = 100; +delete from `sys_params` where id = 101; + +delete from `sys_params` where id = 103; +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (103, 'server.websocket', 'null', 'string', 1, 'websocket地址,多个用;分隔'); + diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index db23d5e17..fd570ff39 100755 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -71,4 +71,11 @@ databaseChangeLog: changes: - sqlFile: encoding: utf8 - path: classpath:db/changelog/202504221135.sql \ No newline at end of file + path: classpath:db/changelog/202504221135.sql + - changeSet: + id: 202504221644 + author: John + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202504221644.sql \ No newline at end of file diff --git a/main/xiaozhi-server/config/config_loader.py b/main/xiaozhi-server/config/config_loader.py index 49a66558a..849a2a8a3 100644 --- a/main/xiaozhi-server/config/config_loader.py +++ b/main/xiaozhi-server/config/config_loader.py @@ -69,6 +69,11 @@ def get_config_from_api(config): "url": config["manager-api"].get("url", ""), "secret": config["manager-api"].get("secret", ""), } + if config.get("server"): + config_data["server"] = { + "ip": config["server"].get("ip", ""), + "port": config["server"].get("port", ""), + } return config_data diff --git a/main/xiaozhi-server/config_from_api.yaml b/main/xiaozhi-server/config_from_api.yaml index d5fd69bc3..15962bb65 100644 --- a/main/xiaozhi-server/config_from_api.yaml +++ b/main/xiaozhi-server/config_from_api.yaml @@ -5,6 +5,9 @@ # 先启动manager-api和manager-web,注册一个账号,第一个注册的账号为管理员 # 使用管理员,进入【参数管理】页面,找到【server.secret】,复制它到参数值,注意每次从零部署,server.secret都会变化 # 打开本data目录下的.config.yaml文件,修改manager-api.secret为刚才复制出来的server.secret +server: + ip: 0.0.0.0 + port: 8000 manager-api: # 你的manager-api的地址,最好使用局域网ip url: http://127.0.0.1:8002/xiaozhi diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index cb4dee08a..d5fb69db6 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -24,7 +24,7 @@ class WebSocketServer: async def start(self): server_config = self.config["server"] - host = server_config["ip"] + host = server_config.get("ip", "0.0.0.0") port = int(server_config.get("port", 8000)) self.logger.bind(tag=TAG).info( diff --git a/main/xiaozhi-server/docker-compose_all.yml b/main/xiaozhi-server/docker-compose_all.yml index 74acdd562..919101204 100644 --- a/main/xiaozhi-server/docker-compose_all.yml +++ b/main/xiaozhi-server/docker-compose_all.yml @@ -47,9 +47,9 @@ services: - SPRING_DATASOURCE_DRUID_PASSWORD=123456 - SPRING_DATA_REDIS_HOST=xiaozhi-esp32-server-redis - SPRING_DATA_REDIS_PORT=6379 - # volumes: - # # 配置文件目录 - # - ./uploadfile:/app/uploadfile + volumes: + # 配置文件目录 + - ./uploadfile:/app/uploadfile xiaozhi-esp32-server-db: image: mysql:latest