mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: 设备扩展属性持久化与 device_event 事件上报
- 新增 ai_device_attribute 表,用于长期存储设备语言、蓝牙信标等动态属性 - 提供 REST API:查询/更新/批量更新/删除设备属性 - /config/agent-models 返回 device_attributes,供 xiaozhi-server 读取 - xiaozhi-server 新增 device_event 消息类型,支持 language_change 与 beacon_change - 设备事件异步上报 manager-api 持久化,并实时刷新 LLM 系统提示词语言
This commit is contained in:
parent
06b0ff139b
commit
28d961cbf9
20 changed files with 629 additions and 7 deletions
|
|
@ -37,6 +37,7 @@ import xiaozhi.modules.agent.vo.AgentVoicePrintVO;
|
|||
import xiaozhi.modules.correctword.vo.CorrectWordSimpleVO;
|
||||
import xiaozhi.modules.config.service.ConfigService;
|
||||
import xiaozhi.modules.device.entity.DeviceEntity;
|
||||
import xiaozhi.modules.device.service.DeviceAttributeService;
|
||||
import xiaozhi.modules.device.service.DeviceService;
|
||||
import xiaozhi.modules.model.entity.ModelConfigEntity;
|
||||
import xiaozhi.modules.model.service.ModelConfigService;
|
||||
|
|
@ -52,6 +53,7 @@ import xiaozhi.modules.voiceclone.service.VoiceCloneService;
|
|||
public class ConfigServiceImpl implements ConfigService {
|
||||
private final SysParamsService sysParamsService;
|
||||
private final DeviceService deviceService;
|
||||
private final DeviceAttributeService deviceAttributeService;
|
||||
private final ModelConfigService modelConfigService;
|
||||
private final AgentService agentService;
|
||||
private final AgentTemplateService agentTemplateService;
|
||||
|
|
@ -244,6 +246,10 @@ public class ConfigServiceImpl implements ConfigService {
|
|||
result,
|
||||
true);
|
||||
|
||||
// 注入设备扩展属性,供 xiaozhi-server 读取并传给 LLM
|
||||
Map<String, String> deviceAttributes = deviceAttributeService.getAttributesByDeviceId(device.getMacAddress());
|
||||
result.put("device_attributes", deviceAttributes);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,98 @@
|
|||
package xiaozhi.modules.device.controller;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.shiro.authz.annotation.RequiresPermissions;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import xiaozhi.common.user.UserDetail;
|
||||
import xiaozhi.common.utils.Result;
|
||||
import xiaozhi.common.validator.ValidatorUtils;
|
||||
import xiaozhi.modules.device.dto.DeviceAttributeBatchDTO;
|
||||
import xiaozhi.modules.device.dto.DeviceAttributeDTO;
|
||||
import xiaozhi.modules.device.entity.DeviceEntity;
|
||||
import xiaozhi.modules.device.service.DeviceAttributeService;
|
||||
import xiaozhi.modules.device.service.DeviceService;
|
||||
import xiaozhi.modules.security.user.SecurityUser;
|
||||
|
||||
@Tag(name = "设备属性管理")
|
||||
@RestController
|
||||
@RequestMapping("/device/attribute")
|
||||
@AllArgsConstructor
|
||||
public class DeviceAttributeController {
|
||||
|
||||
private final DeviceAttributeService deviceAttributeService;
|
||||
private final DeviceService deviceService;
|
||||
|
||||
@GetMapping("/{deviceId}")
|
||||
@Operation(summary = "获取设备所有属性")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<Map<String, String>> list(@PathVariable String deviceId) {
|
||||
DeviceEntity device = deviceService.getDeviceByMacAddress(deviceId);
|
||||
if (device == null || !device.getUserId().equals(SecurityUser.getUser().getId())) {
|
||||
return new Result<Map<String, String>>().error("设备不存在");
|
||||
}
|
||||
return new Result<Map<String, String>>().ok(deviceAttributeService.getAttributesByDeviceId(deviceId));
|
||||
}
|
||||
|
||||
@GetMapping("/{deviceId}/{attrKey}")
|
||||
@Operation(summary = "获取单个设备属性")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<String> get(@PathVariable String deviceId, @PathVariable String attrKey) {
|
||||
DeviceEntity device = deviceService.getDeviceByMacAddress(deviceId);
|
||||
if (device == null || !device.getUserId().equals(SecurityUser.getUser().getId())) {
|
||||
return new Result<String>().error("设备不存在");
|
||||
}
|
||||
return new Result<String>().ok(deviceAttributeService.getAttributeValue(deviceId, attrKey));
|
||||
}
|
||||
|
||||
@PutMapping("/{deviceId}/{attrKey}")
|
||||
@Operation(summary = "更新设备属性")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<Void> update(@PathVariable String deviceId, @PathVariable String attrKey,
|
||||
@RequestBody(required = false) String attrValue) {
|
||||
DeviceEntity device = deviceService.getDeviceByMacAddress(deviceId);
|
||||
if (device == null || !device.getUserId().equals(SecurityUser.getUser().getId())) {
|
||||
return new Result<Void>().error("设备不存在");
|
||||
}
|
||||
deviceAttributeService.saveOrUpdateAttribute(deviceId, attrKey, attrValue);
|
||||
return new Result<Void>();
|
||||
}
|
||||
|
||||
@PostMapping("/batch")
|
||||
@Operation(summary = "批量更新设备属性")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<Void> batchUpdate(@Valid @RequestBody DeviceAttributeBatchDTO dto) {
|
||||
ValidatorUtils.validateEntity(dto);
|
||||
DeviceEntity device = deviceService.getDeviceByMacAddress(dto.getDeviceId());
|
||||
if (device == null || !device.getUserId().equals(SecurityUser.getUser().getId())) {
|
||||
return new Result<Void>().error("设备不存在");
|
||||
}
|
||||
deviceAttributeService.saveOrUpdateAttributes(dto.getDeviceId(), dto.getAttributes());
|
||||
return new Result<Void>();
|
||||
}
|
||||
|
||||
@DeleteMapping("/{deviceId}/{attrKey}")
|
||||
@Operation(summary = "删除设备属性")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<Void> delete(@PathVariable String deviceId, @PathVariable String attrKey) {
|
||||
DeviceEntity device = deviceService.getDeviceByMacAddress(deviceId);
|
||||
if (device == null || !device.getUserId().equals(SecurityUser.getUser().getId())) {
|
||||
return new Result<Void>().error("设备不存在");
|
||||
}
|
||||
deviceAttributeService.deleteAttribute(deviceId, attrKey);
|
||||
return new Result<Void>();
|
||||
}
|
||||
}
|
||||
|
|
@ -25,6 +25,7 @@ import xiaozhi.common.user.UserDetail;
|
|||
import xiaozhi.common.utils.Result;
|
||||
import xiaozhi.modules.device.dto.DeviceAddressBookAliasDTO;
|
||||
import xiaozhi.modules.device.dto.DeviceAddressBookPermissionDTO;
|
||||
import xiaozhi.modules.device.dto.DeviceEventReportDTO;
|
||||
import xiaozhi.modules.device.dto.DeviceManualAddDTO;
|
||||
import xiaozhi.modules.device.dto.DeviceRegisterDTO;
|
||||
import xiaozhi.modules.device.dto.DeviceToolsCallReqDTO;
|
||||
|
|
@ -32,6 +33,7 @@ import xiaozhi.modules.device.dto.DeviceUnBindDTO;
|
|||
import xiaozhi.modules.device.dto.DeviceUpdateDTO;
|
||||
import xiaozhi.modules.device.entity.DeviceEntity;
|
||||
import xiaozhi.modules.device.service.DeviceAddressBookService;
|
||||
import xiaozhi.modules.device.service.DeviceAttributeService;
|
||||
import xiaozhi.modules.device.service.DeviceService;
|
||||
import xiaozhi.modules.device.vo.UserShowDeviceListVO;
|
||||
import xiaozhi.modules.security.user.SecurityUser;
|
||||
|
|
@ -43,13 +45,15 @@ import xiaozhi.modules.sys.service.SysParamsService;
|
|||
public class DeviceController {
|
||||
private final DeviceService deviceService;
|
||||
private final DeviceAddressBookService deviceAddressBookService;
|
||||
private final DeviceAttributeService deviceAttributeService;
|
||||
private final RedisUtils redisUtils;
|
||||
private final SysParamsService sysParamsService;
|
||||
|
||||
public DeviceController(DeviceService deviceService, DeviceAddressBookService deviceAddressBookService,
|
||||
RedisUtils redisUtils, SysParamsService sysParamsService) {
|
||||
DeviceAttributeService deviceAttributeService, RedisUtils redisUtils, SysParamsService sysParamsService) {
|
||||
this.deviceService = deviceService;
|
||||
this.deviceAddressBookService = deviceAddressBookService;
|
||||
this.deviceAttributeService = deviceAttributeService;
|
||||
this.redisUtils = redisUtils;
|
||||
this.sysParamsService = sysParamsService;
|
||||
}
|
||||
|
|
@ -83,6 +87,36 @@ public class DeviceController {
|
|||
return new Result<String>().ok(code);
|
||||
}
|
||||
|
||||
@PostMapping("/event/report")
|
||||
@Operation(summary = "上报设备事件(xiaozhi-server间调用)")
|
||||
public Result<Void> reportDeviceEvent(@RequestBody DeviceEventReportDTO dto) {
|
||||
if (dto == null || StringUtils.isBlank(dto.getDeviceId()) || StringUtils.isBlank(dto.getEvent())) {
|
||||
return new Result<Void>().error("参数错误");
|
||||
}
|
||||
String deviceId = dto.getDeviceId();
|
||||
DeviceEntity device = deviceService.getDeviceByMacAddress(deviceId);
|
||||
if (device == null) {
|
||||
return new Result<Void>().error("设备不存在");
|
||||
}
|
||||
|
||||
// 处理语言变更事件
|
||||
if ("language_change".equals(dto.getEvent())) {
|
||||
Object language = dto.getPayload() == null ? null : dto.getPayload().get("language");
|
||||
if (language != null) {
|
||||
deviceAttributeService.saveOrUpdateAttribute(deviceId, "language", language.toString());
|
||||
}
|
||||
}
|
||||
// 处理蓝牙信标变更事件
|
||||
else if ("beacon_change".equals(dto.getEvent())) {
|
||||
Object beaconId = dto.getPayload() == null ? null : dto.getPayload().get("beacon_id");
|
||||
if (beaconId != null) {
|
||||
deviceAttributeService.saveOrUpdateAttribute(deviceId, "last_beacon_id", beaconId.toString());
|
||||
}
|
||||
}
|
||||
|
||||
return new Result<Void>();
|
||||
}
|
||||
|
||||
@GetMapping("/bind/{agentId}")
|
||||
@Operation(summary = "获取已绑定设备")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
|
|
|
|||
|
|
@ -0,0 +1,11 @@
|
|||
package xiaozhi.modules.device.dao;
|
||||
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
|
||||
import xiaozhi.modules.device.entity.DeviceAttributeEntity;
|
||||
|
||||
@Mapper
|
||||
public interface DeviceAttributeDao extends BaseMapper<DeviceAttributeEntity> {
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
package xiaozhi.modules.device.dto;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Map;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Schema(description = "设备属性批量保存DTO")
|
||||
public class DeviceAttributeBatchDTO implements Serializable {
|
||||
|
||||
@Schema(description = "设备ID")
|
||||
@NotBlank(message = "设备ID不能为空")
|
||||
private String deviceId;
|
||||
|
||||
@Schema(description = "属性映射")
|
||||
@NotNull(message = "属性不能为空")
|
||||
private Map<String, String> attributes;
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
package xiaozhi.modules.device.dto;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Map;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Schema(description = "设备属性DTO")
|
||||
public class DeviceAttributeDTO implements Serializable {
|
||||
|
||||
@Schema(description = "设备ID")
|
||||
@NotBlank(message = "设备ID不能为空")
|
||||
private String deviceId;
|
||||
|
||||
@Schema(description = "属性key")
|
||||
@NotBlank(message = "属性key不能为空")
|
||||
@Size(max = 64, message = "属性key长度不能超过64")
|
||||
private String attrKey;
|
||||
|
||||
@Schema(description = "属性值")
|
||||
@Size(max = 4096, message = "属性值长度不能超过4096")
|
||||
private String attrValue;
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
package xiaozhi.modules.device.dto;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Map;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Schema(description = "设备事件上报DTO")
|
||||
public class DeviceEventReportDTO implements Serializable {
|
||||
|
||||
@Schema(description = "设备ID(mac地址)")
|
||||
@NotBlank(message = "设备ID不能为空")
|
||||
private String deviceId;
|
||||
|
||||
@Schema(description = "事件类型")
|
||||
@NotBlank(message = "事件类型不能为空")
|
||||
private String event;
|
||||
|
||||
@Schema(description = "事件payload")
|
||||
private Map<String, Object> payload;
|
||||
|
||||
@Schema(description = "事件时间戳")
|
||||
private Long timestamp;
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
package xiaozhi.modules.device.entity;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@TableName("ai_device_attribute")
|
||||
@Schema(description = "设备扩展属性")
|
||||
public class DeviceAttributeEntity {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
@Schema(description = "ID")
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "设备ID(mac地址)")
|
||||
private String deviceId;
|
||||
|
||||
@Schema(description = "属性key")
|
||||
private String attrKey;
|
||||
|
||||
@Schema(description = "属性值")
|
||||
private String attrValue;
|
||||
|
||||
@Schema(description = "创建者")
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
private Long creator;
|
||||
|
||||
@Schema(description = "创建时间")
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
private Date createDate;
|
||||
|
||||
@Schema(description = "更新者")
|
||||
@TableField(fill = FieldFill.UPDATE)
|
||||
private Long updater;
|
||||
|
||||
@Schema(description = "更新时间")
|
||||
@TableField(fill = FieldFill.UPDATE)
|
||||
private Date updateDate;
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
package xiaozhi.modules.device.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import xiaozhi.common.service.BaseService;
|
||||
import xiaozhi.modules.device.entity.DeviceAttributeEntity;
|
||||
|
||||
public interface DeviceAttributeService extends BaseService<DeviceAttributeEntity> {
|
||||
|
||||
/**
|
||||
* 获取设备所有扩展属性
|
||||
*
|
||||
* @param deviceId 设备ID
|
||||
* @return key-value 属性映射
|
||||
*/
|
||||
Map<String, String> getAttributesByDeviceId(String deviceId);
|
||||
|
||||
/**
|
||||
* 获取单个设备属性
|
||||
*
|
||||
* @param deviceId 设备ID
|
||||
* @param attrKey 属性key
|
||||
* @return 属性值
|
||||
*/
|
||||
String getAttributeValue(String deviceId, String attrKey);
|
||||
|
||||
/**
|
||||
* 保存或更新设备属性
|
||||
*
|
||||
* @param deviceId 设备ID
|
||||
* @param attrKey 属性key
|
||||
* @param attrValue 属性值
|
||||
*/
|
||||
void saveOrUpdateAttribute(String deviceId, String attrKey, String attrValue);
|
||||
|
||||
/**
|
||||
* 批量保存或更新设备属性
|
||||
*
|
||||
* @param deviceId 设备ID
|
||||
* @param attributes 属性映射
|
||||
*/
|
||||
void saveOrUpdateAttributes(String deviceId, Map<String, String> attributes);
|
||||
|
||||
/**
|
||||
* 删除设备属性
|
||||
*
|
||||
* @param deviceId 设备ID
|
||||
* @param attrKey 属性key
|
||||
*/
|
||||
void deleteAttribute(String deviceId, String attrKey);
|
||||
|
||||
/**
|
||||
* 删除设备所有属性
|
||||
*
|
||||
* @param deviceId 设备ID
|
||||
*/
|
||||
void deleteByDeviceId(String deviceId);
|
||||
|
||||
/**
|
||||
* 批量删除设备属性
|
||||
*
|
||||
* @param deviceIds 设备ID列表
|
||||
*/
|
||||
void deleteByDeviceIds(List<String> deviceIds);
|
||||
}
|
||||
|
|
@ -0,0 +1,115 @@
|
|||
package xiaozhi.modules.device.service.impl;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import xiaozhi.common.service.impl.BaseServiceImpl;
|
||||
import xiaozhi.modules.device.dao.DeviceAttributeDao;
|
||||
import xiaozhi.modules.device.entity.DeviceAttributeEntity;
|
||||
import xiaozhi.modules.device.service.DeviceAttributeService;
|
||||
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class DeviceAttributeServiceImpl extends BaseServiceImpl<DeviceAttributeDao, DeviceAttributeEntity>
|
||||
implements DeviceAttributeService {
|
||||
|
||||
private final DeviceAttributeDao deviceAttributeDao;
|
||||
|
||||
@Override
|
||||
public Map<String, String> getAttributesByDeviceId(String deviceId) {
|
||||
if (StringUtils.isBlank(deviceId)) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
QueryWrapper<DeviceAttributeEntity> wrapper = new QueryWrapper<>();
|
||||
wrapper.eq("device_id", deviceId);
|
||||
List<DeviceAttributeEntity> list = deviceAttributeDao.selectList(wrapper);
|
||||
return list.stream()
|
||||
.collect(Collectors.toMap(DeviceAttributeEntity::getAttrKey, DeviceAttributeEntity::getAttrValue,
|
||||
(v1, v2) -> v1));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAttributeValue(String deviceId, String attrKey) {
|
||||
if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(attrKey)) {
|
||||
return null;
|
||||
}
|
||||
QueryWrapper<DeviceAttributeEntity> wrapper = new QueryWrapper<>();
|
||||
wrapper.eq("device_id", deviceId).eq("attr_key", attrKey);
|
||||
DeviceAttributeEntity entity = deviceAttributeDao.selectOne(wrapper);
|
||||
return entity == null ? null : entity.getAttrValue();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void saveOrUpdateAttribute(String deviceId, String attrKey, String attrValue) {
|
||||
if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(attrKey)) {
|
||||
return;
|
||||
}
|
||||
QueryWrapper<DeviceAttributeEntity> wrapper = new QueryWrapper<>();
|
||||
wrapper.eq("device_id", deviceId).eq("attr_key", attrKey);
|
||||
DeviceAttributeEntity entity = deviceAttributeDao.selectOne(wrapper);
|
||||
if (entity == null) {
|
||||
entity = new DeviceAttributeEntity();
|
||||
entity.setDeviceId(deviceId);
|
||||
entity.setAttrKey(attrKey);
|
||||
entity.setAttrValue(attrValue);
|
||||
deviceAttributeDao.insert(entity);
|
||||
} else {
|
||||
entity.setAttrValue(attrValue);
|
||||
deviceAttributeDao.updateById(entity);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void saveOrUpdateAttributes(String deviceId, Map<String, String> attributes) {
|
||||
if (StringUtils.isBlank(deviceId) || attributes == null || attributes.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
attributes.forEach((key, value) -> saveOrUpdateAttribute(deviceId, key, value));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void deleteAttribute(String deviceId, String attrKey) {
|
||||
if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(attrKey)) {
|
||||
return;
|
||||
}
|
||||
UpdateWrapper<DeviceAttributeEntity> wrapper = new UpdateWrapper<>();
|
||||
wrapper.eq("device_id", deviceId).eq("attr_key", attrKey);
|
||||
deviceAttributeDao.delete(wrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void deleteByDeviceId(String deviceId) {
|
||||
if (StringUtils.isBlank(deviceId)) {
|
||||
return;
|
||||
}
|
||||
UpdateWrapper<DeviceAttributeEntity> wrapper = new UpdateWrapper<>();
|
||||
wrapper.eq("device_id", deviceId);
|
||||
deviceAttributeDao.delete(wrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void deleteByDeviceIds(List<String> deviceIds) {
|
||||
if (deviceIds == null || deviceIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
UpdateWrapper<DeviceAttributeEntity> wrapper = new UpdateWrapper<>();
|
||||
wrapper.in("device_id", deviceIds);
|
||||
deviceAttributeDao.delete(wrapper);
|
||||
}
|
||||
}
|
||||
|
|
@ -88,6 +88,7 @@ public class ShiroConfig {
|
|||
// 将config路径使用server服务过滤器
|
||||
filterMap.put("/config/**", "server");
|
||||
filterMap.put("/device/address-book/call", "server");
|
||||
filterMap.put("/device/event/report", "server");
|
||||
filterMap.put("/agent/chat-history/report", "server");
|
||||
filterMap.put("/agent/chat-history/download/**", "anon");
|
||||
filterMap.put("/agent/chat-summary/**", "server");
|
||||
|
|
|
|||
|
|
@ -0,0 +1,14 @@
|
|||
-- 设备扩展属性表,用于持久化存储设备语言、蓝牙信标等动态状态
|
||||
CREATE TABLE IF NOT EXISTS `ai_device_attribute` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT 'ID',
|
||||
`device_id` VARCHAR(64) NOT NULL COMMENT '设备ID(mac地址)',
|
||||
`attr_key` VARCHAR(64) NOT NULL COMMENT '属性key',
|
||||
`attr_value` TEXT COMMENT '属性值',
|
||||
`creator` BIGINT COMMENT '创建者',
|
||||
`create_date` DATETIME COMMENT '创建时间',
|
||||
`updater` BIGINT COMMENT '更新者',
|
||||
`update_date` DATETIME COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_device_attr` (`device_id`, `attr_key`),
|
||||
KEY `idx_device_id` (`device_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='设备扩展属性';
|
||||
|
|
@ -690,3 +690,10 @@ databaseChangeLog:
|
|||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202606261131.sql
|
||||
- changeSet:
|
||||
id: 202606271800
|
||||
author: JacobNg1
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202606271800.sql
|
||||
|
|
|
|||
|
|
@ -245,6 +245,28 @@ async def report(
|
|||
return None
|
||||
|
||||
|
||||
async def report_device_event(
|
||||
device_id: str, event: str, payload: Optional[Dict] = None, timestamp: Optional[int] = None
|
||||
) -> Optional[Dict]:
|
||||
"""异步上报设备事件(语言切换、蓝牙信标变更等)"""
|
||||
if not ManageApiClient._instance:
|
||||
return None
|
||||
try:
|
||||
return await ManageApiClient._instance._execute_async_request(
|
||||
"POST",
|
||||
"/device/event/report",
|
||||
json={
|
||||
"deviceId": device_id,
|
||||
"event": event,
|
||||
"payload": payload or {},
|
||||
"timestamp": timestamp,
|
||||
},
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"设备事件上报失败: {e}")
|
||||
return None
|
||||
|
||||
|
||||
async def lookup_address_book(caller_mac: str, nickname: str) -> Optional[Dict]:
|
||||
"""根据昵称查找目标设备"""
|
||||
if not ManageApiClient._instance:
|
||||
|
|
|
|||
|
|
@ -169,6 +169,10 @@ class ConnectionHandler:
|
|||
self.iot_descriptors = {}
|
||||
self.func_handler = None
|
||||
|
||||
# 设备扩展属性(从 manager-api 持久化读取)
|
||||
self.device_attributes = {}
|
||||
self.device_language = None
|
||||
|
||||
self.cmd_exit = self.config["exit_commands"]
|
||||
|
||||
# 是否在聊天结束后关闭连接
|
||||
|
|
@ -543,6 +547,7 @@ class ConnectionHandler:
|
|||
self.device_id,
|
||||
self.client_ip,
|
||||
emoji_enabled=(self.features or {}).get("emoji", True),
|
||||
device_language=self.device_language,
|
||||
)
|
||||
if enhanced_prompt:
|
||||
self.change_system_prompt(enhanced_prompt)
|
||||
|
|
@ -779,6 +784,14 @@ class ConnectionHandler:
|
|||
if private_config.get("context_providers", None) is not None:
|
||||
self.config["context_providers"] = private_config["context_providers"]
|
||||
|
||||
# 注入设备扩展属性(语言、蓝牙信标等)
|
||||
if private_config.get("device_attributes", None) is not None:
|
||||
self.device_attributes = private_config["device_attributes"] or {}
|
||||
self.device_language = self.device_attributes.get("language")
|
||||
self.logger.bind(tag=TAG).info(
|
||||
f"加载设备扩展属性: {self.device_attributes}"
|
||||
)
|
||||
|
||||
# 注入替换词到 TTS 模块配置
|
||||
if private_config.get("correct_words", None) is not None:
|
||||
select_tts_module = self.config["selected_module"]["TTS"]
|
||||
|
|
|
|||
80
main/xiaozhi-server/core/handle/deviceEventHandle.py
Normal file
80
main/xiaozhi-server/core/handle/deviceEventHandle.py
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
import asyncio
|
||||
from typing import Dict, Any, TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from core.connection import ConnectionHandler
|
||||
from config.manage_api_client import report_device_event
|
||||
from config.logger import setup_logging
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
||||
async def handle_device_event(conn: "ConnectionHandler", msg_json: Dict[str, Any]):
|
||||
"""处理设备主动上报的事件"""
|
||||
event = msg_json.get("event")
|
||||
payload = msg_json.get("payload", {})
|
||||
timestamp = msg_json.get("timestamp")
|
||||
|
||||
if not event:
|
||||
logger.bind(tag=TAG).warning("收到空的 device_event")
|
||||
return
|
||||
|
||||
logger.bind(tag=TAG).info(f"设备事件: {event}, payload: {payload}")
|
||||
|
||||
if event == "language_change":
|
||||
language = payload.get("language")
|
||||
if language:
|
||||
await _handle_language_change(conn, language)
|
||||
elif event == "beacon_change":
|
||||
beacon_id = payload.get("beacon_id")
|
||||
if beacon_id:
|
||||
await _handle_beacon_change(conn, beacon_id, payload)
|
||||
else:
|
||||
logger.bind(tag=TAG).debug(f"未识别的设备事件: {event}")
|
||||
|
||||
# 异步上报到 manager-api 持久化
|
||||
asyncio.create_task(
|
||||
_report_event_to_manager_api(conn, event, payload, timestamp)
|
||||
)
|
||||
|
||||
|
||||
async def _handle_language_change(conn: "ConnectionHandler", language: str):
|
||||
"""处理语言变更事件"""
|
||||
conn.device_language = language
|
||||
if conn.device_attributes is None:
|
||||
conn.device_attributes = {}
|
||||
conn.device_attributes["language"] = language
|
||||
logger.bind(tag=TAG).info(f"设备语言已切换为: {language}")
|
||||
# 重新触发提示词增强,让 LLM 立即感知语言变化
|
||||
try:
|
||||
conn._init_prompt_enhancement()
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).warning(f"语言切换后刷新提示词失败: {e}")
|
||||
|
||||
|
||||
async def _handle_beacon_change(
|
||||
conn: "ConnectionHandler", beacon_id: str, payload: Dict[str, Any]
|
||||
):
|
||||
"""处理蓝牙信标变更事件"""
|
||||
if conn.device_attributes is None:
|
||||
conn.device_attributes = {}
|
||||
conn.device_attributes["last_beacon_id"] = beacon_id
|
||||
logger.bind(tag=TAG).info(f"设备蓝牙信标已更新: {beacon_id}")
|
||||
|
||||
|
||||
async def _report_event_to_manager_api(
|
||||
conn: "ConnectionHandler", event: str, payload: Dict[str, Any], timestamp: Any
|
||||
):
|
||||
"""将设备事件上报给 manager-api 持久化"""
|
||||
if not conn.read_config_from_api:
|
||||
return
|
||||
try:
|
||||
await report_device_event(
|
||||
device_id=conn.device_id,
|
||||
event=event,
|
||||
payload=payload,
|
||||
timestamp=timestamp,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"上报设备事件失败: {e}")
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
from typing import Dict, Any, TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from core.connection import ConnectionHandler
|
||||
from core.handle.textMessageHandler import TextMessageHandler
|
||||
from core.handle.textMessageType import TextMessageType
|
||||
from core.handle.deviceEventHandle import handle_device_event
|
||||
|
||||
|
||||
class DeviceEventTextMessageHandler(TextMessageHandler):
|
||||
"""设备事件消息处理器"""
|
||||
|
||||
@property
|
||||
def message_type(self) -> TextMessageType:
|
||||
return TextMessageType.DEVICE_EVENT
|
||||
|
||||
async def handle(self, conn: "ConnectionHandler", msg_json: Dict[str, Any]) -> None:
|
||||
await handle_device_event(conn, msg_json)
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
from typing import Dict, Optional
|
||||
|
||||
from core.handle.textHandler.abortMessageHandler import AbortTextMessageHandler
|
||||
from core.handle.textHandler.deviceEventMessageHandler import DeviceEventTextMessageHandler
|
||||
from core.handle.textHandler.helloMessageHandler import HelloTextMessageHandler
|
||||
from core.handle.textHandler.iotMessageHandler import IotTextMessageHandler
|
||||
from core.handle.textHandler.listenMessageHandler import ListenTextMessageHandler
|
||||
|
|
@ -29,6 +30,7 @@ class TextMessageHandlerRegistry:
|
|||
McpTextMessageHandler(),
|
||||
ServerTextMessageHandler(),
|
||||
PingMessageHandler(),
|
||||
DeviceEventTextMessageHandler(),
|
||||
]
|
||||
|
||||
for handler in handlers:
|
||||
|
|
|
|||
|
|
@ -10,3 +10,4 @@ class TextMessageType(Enum):
|
|||
MCP = "mcp"
|
||||
SERVER = "server"
|
||||
PING = "ping"
|
||||
DEVICE_EVENT = "device_event"
|
||||
|
|
|
|||
|
|
@ -252,12 +252,14 @@ class PromptManager:
|
|||
)
|
||||
|
||||
# 获取TTS选择的语言,默认值为中文
|
||||
language = (
|
||||
self.config.get("TTS", {})
|
||||
.get(self.config.get("selected_module", {}).get("TTS", ""), {})
|
||||
.get("language")
|
||||
or "中文"
|
||||
)
|
||||
language = kwargs.get("device_language")
|
||||
if not language:
|
||||
language = (
|
||||
self.config.get("TTS", {})
|
||||
.get(self.config.get("selected_module", {}).get("TTS", ""), {})
|
||||
.get("language")
|
||||
or "中文"
|
||||
)
|
||||
self.logger.bind(tag=TAG).debug(f"获取到选择的语言: {language}")
|
||||
|
||||
# 替换模板变量
|
||||
|
|
|
|||
Loading…
Reference in a new issue