自定义指令接口

This commit is contained in:
ghlds 2025-06-19 10:29:16 +08:00
parent deadab95e3
commit 904729599e
13 changed files with 400 additions and 9 deletions

View file

@ -0,0 +1,79 @@
package xiaozhi.modules.device.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import xiaozhi.common.utils.Result;
import xiaozhi.modules.device.entity.DeviceCommandEntity;
import xiaozhi.modules.device.service.DeviceCommandService;
import java.util.List;
@Tag(name = "设备指令管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/device/command")
public class DeviceCommandController {
private final DeviceCommandService deviceCommandService;
@PostMapping("/add")
@Operation(summary = "添加设备指令")
// @RequiresPermissions("sys:role:superAdmin")
public Result<Void> addCommand(@RequestBody DeviceCommandEntity entity) {
deviceCommandService.addCommand(entity);
return new Result<>();
}
@GetMapping("/list/{deviceId}")
@Operation(summary = "查询设备指令列表")
// @RequiresPermissions("sys:role:superAdmin")
public Result<List<DeviceCommandEntity>> getCommands(@PathVariable String deviceId) {
List<DeviceCommandEntity> list = deviceCommandService.getCommandsByDeviceId(deviceId);
return new Result<List<DeviceCommandEntity>>().ok(list);
}
@PutMapping("/executed/{id}")
@Operation(summary = "设置指令为已执行")
// @RequiresPermissions("sys:role:superAdmin")
public Result<Void> setCommandExecuted(@PathVariable String id) {
deviceCommandService.setCommandExecuted(id);
return new Result<>();
}
@GetMapping("/{id}")
@Operation(summary = "根据ID查询指令详情")
// @RequiresPermissions("sys:role:superAdmin")
public Result<DeviceCommandEntity> getById(@PathVariable String id) {
DeviceCommandEntity entity = deviceCommandService.getById(id);
return new Result<DeviceCommandEntity>().ok(entity);
}
/*
* @Operation(summary = "消费一个设备指令")
*/
@PostMapping("/consume")
@Operation(summary = "消费一个设备指令")
// @RequiresPermissions("sys:role:superAdmin")
public Result<DeviceCommandEntity> consumeCommand(@RequestBody ConsumeCommandRequest request) {
DeviceCommandEntity entity = deviceCommandService.consumeCommand(request.getDeviceId());
if (entity == null) {
return new Result<DeviceCommandEntity>().error("没有可消费的指令");
}
return new Result<DeviceCommandEntity>().ok(entity);
}
// 新增请求体类
static class ConsumeCommandRequest {
private String deviceId;
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
}
}

View file

@ -0,0 +1,17 @@
package xiaozhi.modules.device.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import xiaozhi.modules.device.entity.DeviceCommandEntity;
import java.util.List;
@Mapper
public interface DeviceCommandDao extends BaseMapper<DeviceCommandEntity> {
List<DeviceCommandEntity> selectByDeviceId(@Param("deviceId") String deviceId);
int updateExecuted(@Param("id") String id, @Param("isExecuted") Integer isExecuted);
DeviceCommandEntity consumeCommand(@Param("id") String id);
}

View file

@ -0,0 +1,42 @@
package xiaozhi.modules.device.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.Date;
@Data
@TableName("zy_ai_device_command")
@Schema(description = "设备指令表")
public class DeviceCommandEntity {
@TableId(type = IdType.ASSIGN_UUID)
@Schema(description = "主键")
private String id;
@Schema(description = "设备唯一标识")
private String deviceId;
@Schema(description = "指令类型")
private String commandType;
@Schema(description = "指令内容")
private String commandContent;
@Schema(description = "是否已执行(0未执行 1已执行)")
private Integer isExecuted;
@Schema(description = "创建者")
private Long creator;
@Schema(description = "创建时间")
private Date createDate;
@Schema(description = "更新者")
private Long updater;
@Schema(description = "更新时间")
private Date updateDate;
}

View file

@ -0,0 +1,17 @@
package xiaozhi.modules.device.service;
import xiaozhi.modules.device.entity.DeviceCommandEntity;
import java.util.List;
public interface DeviceCommandService {
void addCommand(DeviceCommandEntity entity);
List<DeviceCommandEntity> getCommandsByDeviceId(String deviceId);
void setCommandExecuted(String id);
DeviceCommandEntity getById(String id);
DeviceCommandEntity consumeCommand(String deviceId);
}

View file

@ -0,0 +1,51 @@
package xiaozhi.modules.device.service.impl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import xiaozhi.modules.device.dao.DeviceCommandDao;
import xiaozhi.modules.device.entity.DeviceCommandEntity;
import xiaozhi.modules.device.service.DeviceCommandService;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Service
@RequiredArgsConstructor
public class DeviceCommandServiceImpl implements DeviceCommandService {
private final DeviceCommandDao deviceCommandDao;
@Override
public void addCommand(DeviceCommandEntity entity) {
entity.setId(UUID.randomUUID().toString().replace("-", ""));
entity.setIsExecuted(0);
entity.setCreateDate(new Date());
deviceCommandDao.insert(entity);
}
@Override
public List<DeviceCommandEntity> getCommandsByDeviceId(String deviceId) {
return deviceCommandDao.selectByDeviceId(deviceId);
}
@Override
public void setCommandExecuted(String id) {
deviceCommandDao.updateExecuted(id, 1);
}
@Override
public DeviceCommandEntity getById(String id) {
return deviceCommandDao.selectById(id);
}
@Override
public DeviceCommandEntity consumeCommand(String deviceId) {
// 查询未执行的第一条命令
DeviceCommandEntity entity = deviceCommandDao.consumeCommand(deviceId);
if (entity != null) {
// 更新为已执行
deviceCommandDao.updateExecuted(entity.getId(), 1);
}
return entity;
}
}

View file

@ -90,6 +90,9 @@ public class ShiroConfig {
filterMap.put("/agent/chat-history/report", "server"); filterMap.put("/agent/chat-history/report", "server");
filterMap.put("/agent/saveMemory/**", "server"); filterMap.put("/agent/saveMemory/**", "server");
filterMap.put("/agent/play/**", "anon"); filterMap.put("/agent/play/**", "anon");
filterMap.put("/device/command/**", "anon");
filterMap.put("/admin/server/emit-command", "anon");
filterMap.put("/admin/server/device-online", "anon");
filterMap.put("/**", "oauth2"); filterMap.put("/**", "oauth2");
shiroFilter.setFilterChainDefinitionMap(filterMap); shiroFilter.setFilterChainDefinitionMap(filterMap);

View file

@ -24,6 +24,9 @@ import xiaozhi.common.annotation.LogOperation;
import xiaozhi.common.constant.Constant; import xiaozhi.common.constant.Constant;
import xiaozhi.common.exception.RenException; import xiaozhi.common.exception.RenException;
import xiaozhi.common.utils.Result; import xiaozhi.common.utils.Result;
import xiaozhi.modules.device.entity.DeviceCommandEntity;
import xiaozhi.modules.device.service.DeviceCommandService;
import xiaozhi.modules.sys.dto.EmitCommandDTO;
import xiaozhi.modules.sys.dto.EmitSeverActionDTO; import xiaozhi.modules.sys.dto.EmitSeverActionDTO;
import xiaozhi.modules.sys.dto.ServerActionPayloadDTO; import xiaozhi.modules.sys.dto.ServerActionPayloadDTO;
import xiaozhi.modules.sys.dto.ServerActionResponseDTO; import xiaozhi.modules.sys.dto.ServerActionResponseDTO;
@ -40,6 +43,7 @@ import xiaozhi.modules.sys.utils.WebSocketClientManager;
@AllArgsConstructor @AllArgsConstructor
public class ServerSideManageController { public class ServerSideManageController {
private final SysParamsService sysParamsService; private final SysParamsService sysParamsService;
private final DeviceCommandService deviceCommandService; // 新增注入
private static final ObjectMapper objectMapper; private static final ObjectMapper objectMapper;
static { static {
objectMapper = new ObjectMapper(); objectMapper = new ObjectMapper();
@ -118,4 +122,137 @@ public class ServerSideManageController {
} }
return true; return true;
} }
@Operation(summary = "通过WebSocket发送指令")
@PostMapping("/emit-command")
@LogOperation("通过WebSocket发送指令")
// @RequiresPermissions("sys:role:superAdmin")
public Result<DeviceCommandEntity> emitCommand(@RequestBody @Valid EmitCommandDTO dto) {
String wsText = sysParamsService.getValue(Constant.SERVER_WEBSOCKET, true);
if (StringUtils.isBlank(wsText)) {
throw new RenException("未配置服务端WebSocket地址");
}
String targetWs = dto.getTargetWs();
String[] wsList = wsText.split(";");
if (StringUtils.isBlank(targetWs) || !Arrays.asList(wsList).contains(targetWs)) {
throw new RenException("目标WebSocket地址不存在");
}
return new Result<DeviceCommandEntity>().ok(emitCommandByWs(targetWs, dto));
}
private DeviceCommandEntity emitCommandByWs(String targetWsUri, EmitCommandDTO dto) {
if (StringUtils.isBlank(targetWsUri) || dto == null || StringUtils.isBlank(dto.getCommand())) {
return null;
}
String serverSK = sysParamsService.getValue(Constant.SERVER_SECRET, true);
WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
headers.add("device-id", UUID.randomUUID().toString());
headers.add("client-id", UUID.randomUUID().toString());
final DeviceCommandEntity[] resultEntity = { null };
try (WebSocketClientManager client = new WebSocketClientManager.Builder()
.connectTimeout(3, TimeUnit.SECONDS)
.maxSessionDuration(120, TimeUnit.SECONDS)
.uri(targetWsUri)
.headers(headers)
.build()) {
// 发送command类型指令
Map<String, Object> payload = new HashMap<>();
payload.put("secret", serverSK);
payload.put("command", dto.getCommand());
payload.put("deviceId", dto.getDeviceId());
client.sendJson(ServerActionPayloadDTO.build(ServerActionEnum.COMMAND, payload));
// 监听返回
client.listener((jsonText) -> {
if (StringUtils.isBlank(jsonText)) {
return false;
}
try {
Map<String, Object> resp = objectMapper.readValue(jsonText, Map.class);
Object status = resp.get("status");
if ("success".equals(status) || "fail".equals(status)) {
DeviceCommandEntity entity = new DeviceCommandEntity();
entity.setDeviceId(dto.getDeviceId());
entity.setCommandContent(dto.getCommand());
entity.setCommandType("message");
entity.setIsExecuted("success".equals(status) ? 1 : 0);
deviceCommandService.addCommand(entity);
resultEntity[0] = entity;
return true;
}
} catch (Exception e) {
// ignore
}
return false;
});
} catch (Exception e) {
throw new RenException("WebSocket连接失败或连接超时");
}
return resultEntity[0];
}
@Operation(summary = "查询设备是否在线")
@PostMapping("/device-online")
@LogOperation("查询设备是否在线")
public Result<Boolean> checkDeviceOnline(@RequestBody Map<String, String> params) {
String deviceId = params.get("deviceId");
String targetWs = params.get("targetWs");
if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(targetWs)) {
throw new RenException("参数缺失");
}
String wsText = sysParamsService.getValue(Constant.SERVER_WEBSOCKET, true);
if (StringUtils.isBlank(wsText)) {
throw new RenException("未配置服务端WebSocket地址");
}
String[] wsList = wsText.split(";");
if (!Arrays.asList(wsList).contains(targetWs)) {
throw new RenException("目标WebSocket地址不存在");
}
return new Result<Boolean>().ok(checkDeviceOnlineByWs(targetWs, deviceId));
}
private Boolean checkDeviceOnlineByWs(String targetWsUri, String deviceId) {
if (StringUtils.isBlank(targetWsUri) || StringUtils.isBlank(deviceId)) {
return false;
}
String serverSK = sysParamsService.getValue(Constant.SERVER_SECRET, true);
WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
headers.add("device-id", UUID.randomUUID().toString());
headers.add("client-id", UUID.randomUUID().toString());
final boolean[] online = { false };
try (WebSocketClientManager client = new WebSocketClientManager.Builder()
.connectTimeout(3, TimeUnit.SECONDS)
.maxSessionDuration(30, TimeUnit.SECONDS)
.uri(targetWsUri)
.headers(headers)
.build()) {
// 发送CHECK_ONLINE类型指令
Map<String, Object> payload = new HashMap<>();
payload.put("secret", serverSK);
payload.put("deviceId", deviceId);
client.sendJson(ServerActionPayloadDTO.build(ServerActionEnum.CHECK_ONLINE, payload));
// 监听返回
client.listener((jsonText) -> {
if (StringUtils.isBlank(jsonText)) {
return false;
}
try {
Map<String, Object> resp = objectMapper.readValue(jsonText, Map.class);
Object status = resp.get("status");
Object onlineVal = resp.get("online");
if ("success".equals(status) && onlineVal instanceof Boolean) {
online[0] = (Boolean) onlineVal;
return true;
}
} catch (Exception e) {
// ignore
}
return false;
});
} catch (Exception e) {
throw new RenException("WebSocket连接失败或连接超时");
}
return online[0];
}
} }

View file

@ -0,0 +1,14 @@
package xiaozhi.modules.sys.dto;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
public class EmitCommandDTO {
@NotBlank
private String targetWs;
@NotBlank
private String command;
@NotBlank
private String deviceId;
}

View file

@ -2,29 +2,38 @@ package xiaozhi.modules.sys.enums;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.annotation.JsonValue;
import xiaozhi.common.exception.RenException;
/** /**
* 服务端动作枚举 * 服务端动作枚举
*/ */
public enum ServerActionEnum { public enum ServerActionEnum
{
RESTART("restart"), RESTART("restart"),
UPDATE_CONFIG("update_config"); UPDATE_CONFIG("update_config"),
COMMAND("command"), // 新增
CHECK_ONLINE("check_online");
private final String value; private final String value;
ServerActionEnum(String value) { ServerActionEnum(String value)
{
this.value = value; this.value = value;
} }
@JsonValue @JsonValue
public String getValue() { public String getValue()
{
return value; return value;
} }
@JsonCreator @JsonCreator
public static ServerActionEnum fromValue(String value) { public static ServerActionEnum fromValue(String value)
for (ServerActionEnum action : ServerActionEnum.values()) { {
if (action.value.equalsIgnoreCase(value)) { for (ServerActionEnum action : ServerActionEnum.values())
{
if (action.value.equalsIgnoreCase(value))
{
return action; return action;
} }
} }

View file

@ -12,9 +12,9 @@ spring:
druid: druid:
#MySQL #MySQL
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true url: jdbc:mysql://106.75.77.213:3306/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
username: root username: root
password: 123456 password: zy123456
initial-size: 10 initial-size: 10
max-active: 100 max-active: 100
min-idle: 10 min-idle: 10

View file

@ -5,6 +5,7 @@ server:
threads: threads:
max: 1000 max: 1000
min-spare: 30 min-spare: 30
address: 0.0.0.0
port: 8002 port: 8002
servlet: servlet:
context-path: /xiaozhi context-path: /xiaozhi

View file

@ -205,6 +205,13 @@ databaseChangeLog:
- sqlFile: - sqlFile:
encoding: utf8 encoding: utf8
path: classpath:db/changelog/202506080955.sql path: classpath:db/changelog/202506080955.sql
- changeSet:
id: 202506101359
author: lds
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202506101359.sql
- changeSet: - changeSet:
id: 202506161101 id: 202506161101
author: hrz author: hrz

View file

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xiaozhi.modules.device.dao.DeviceCommandDao">
<select id="selectByDeviceId" resultType="xiaozhi.modules.device.entity.DeviceCommandEntity">
SELECT * FROM zy_ai_device_command WHERE device_id = #{deviceId} AND is_executed = 0 ORDER BY create_date DESC
</select>
<select id="consumeCommand" resultType="xiaozhi.modules.device.entity.DeviceCommandEntity">
SELECT * FROM zy_ai_device_command WHERE is_executed = 0 ORDER BY create_date ASC LIMIT 1 FOR UPDATE
</select>
<update id="updateExecuted">
UPDATE zy_ai_device_command SET is_executed = #{isExecuted}, update_date = NOW() WHERE id = #{id}
</update>
</mapper>