feat(hardware): 新增设备电量消息记录查询工具 (REQ-20260921-0007)
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
package me.iiv.agent.es;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* electricitymessage_yyyyMM(设备电量/信号/温度等消息)ES 查询网关。
|
||||
* 只走本地 ES 集群(索引只建在本地集群),索引名由调用方按月构造传入,
|
||||
* 本接口只做单次查询,便于单测 mock。
|
||||
*/
|
||||
public interface ElectricityMessageEsGateway {
|
||||
|
||||
/**
|
||||
* 分页查询单台设备的电量/信号/温度/充电循环次数/电压/电流消息记录。
|
||||
*
|
||||
* @param index 月索引名,如 electricitymessage_202609(由调用方按 startTime 月份构造)
|
||||
* @param snCode 设备 SN,match_phrase 精确短语匹配
|
||||
* @param messageType 消息类型 0-5,null=不过滤(查全部类型)
|
||||
* @param startTime createTime 下界(含),yyyy-MM-dd HH:mm:ss
|
||||
* @param endTime createTime 上界(含),yyyy-MM-dd HH:mm:ss
|
||||
* @param from from+size 分页起始偏移
|
||||
* @param size 每页条数
|
||||
* @return 命中总数(track_total_hits)与当页记录,按 createTime ASC
|
||||
*/
|
||||
Result search(String index, String snCode, Integer messageType,
|
||||
String startTime, String endTime, int from, int size);
|
||||
|
||||
/** 单次查询结果。 */
|
||||
class Result {
|
||||
private final long total;
|
||||
private final List<Record> records;
|
||||
|
||||
public Result(long total, List<Record> records) {
|
||||
this.total = total;
|
||||
this.records = records;
|
||||
}
|
||||
|
||||
public long getTotal() {
|
||||
return total;
|
||||
}
|
||||
|
||||
public List<Record> getRecords() {
|
||||
return records;
|
||||
}
|
||||
}
|
||||
|
||||
/** 单条消息记录(createTime 已统一为 yyyy-MM-dd HH:mm:ss 文本,未标注单位语义)。 */
|
||||
class Record {
|
||||
private final String createTime;
|
||||
private final Integer messageType;
|
||||
private final Integer value;
|
||||
|
||||
public Record(String createTime, Integer messageType, Integer value) {
|
||||
this.createTime = createTime;
|
||||
this.messageType = messageType;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public Integer getMessageType() {
|
||||
return messageType;
|
||||
}
|
||||
|
||||
public Integer getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package me.iiv.agent.es;
|
||||
|
||||
import co.elastic.clients.elasticsearch.ElasticsearchClient;
|
||||
import co.elastic.clients.elasticsearch._types.FieldValue;
|
||||
import co.elastic.clients.elasticsearch._types.SortOrder;
|
||||
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
|
||||
import co.elastic.clients.elasticsearch.core.SearchResponse;
|
||||
import co.elastic.clients.elasticsearch.core.search.Hit;
|
||||
import co.elastic.clients.json.JsonData;
|
||||
import jakarta.json.JsonNumber;
|
||||
import jakarta.json.JsonObject;
|
||||
import jakarta.json.JsonString;
|
||||
import jakarta.json.JsonValue;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* electricitymessage_yyyyMM ES 查询实现(elasticsearch-java 7.17 强类型 API),
|
||||
* 只注入 esLocal 客户端(索引只在本地集群,不走 esCloud)。
|
||||
* 查询口径对齐老 BatteryAnalyseController.batteryAnalyseList 但修掉其坑:
|
||||
* snCode 用 match_phrase(老代码 matchQuery 经 standard analyzer 会把 AB-123 切成 ab/123 误配)、
|
||||
* messageType 不传不加 term(老代码默认值 0 会把"不传"歧义成"电量")、createTime 闭区间 range、
|
||||
* createTime ASC 排序、from+size 分页(老代码 scroll 拉全量后内存抽样)。
|
||||
* ES 异常不静默,抛 IllegalStateException(与老系统 catch 吞异常返回空不同,见设计文档)。
|
||||
*/
|
||||
@Component
|
||||
public class ElectricityMessageEsGatewayImpl implements ElectricityMessageEsGateway {
|
||||
|
||||
private static final ZoneId BUSINESS_ZONE = ZoneId.of("Asia/Shanghai");
|
||||
private static final DateTimeFormatter TIME_FORMATTER =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(BUSINESS_ZONE);
|
||||
|
||||
private final ElasticsearchClient localClient;
|
||||
|
||||
public ElectricityMessageEsGatewayImpl(@Qualifier("esLocalClient") ElasticsearchClient localClient) {
|
||||
this.localClient = localClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Result search(String index, String snCode, Integer messageType,
|
||||
String startTime, String endTime, int from, int size) {
|
||||
List<Query> filters = new ArrayList<>();
|
||||
// 老代码 snCode 字符串走 matchQuery(BaseSearchSupportImpl2 type=0 非数值分支),
|
||||
// standard analyzer 会把 AB-123 切成 ab/123 造成误配;改用 match_phrase 精确短语
|
||||
filters.add(Query.of(q -> q.matchPhrase(m -> m.field("snCode").query(snCode))));
|
||||
if (messageType != null) {
|
||||
filters.add(Query.of(q -> q.term(t -> t.field("messageType")
|
||||
.value(FieldValue.of(messageType.longValue())))));
|
||||
}
|
||||
// 老代码 rangeQuery from(start,true).to(end,true),闭区间
|
||||
filters.add(Query.of(q -> q.range(r -> r.field("createTime")
|
||||
.gte(JsonData.of(startTime)).lte(JsonData.of(endTime)))));
|
||||
try {
|
||||
SearchResponse<JsonData> response = localClient.search(s -> s
|
||||
.index(index)
|
||||
.from(from)
|
||||
.size(size)
|
||||
.trackTotalHits(t -> t.enabled(true))
|
||||
.query(q -> q.bool(b -> b.filter(filters)))
|
||||
.sort(so -> so.field(f -> f.field("createTime").order(SortOrder.Asc))),
|
||||
JsonData.class);
|
||||
List<Record> records = new ArrayList<>();
|
||||
for (Hit<JsonData> hit : response.hits().hits()) {
|
||||
JsonData source = hit.source();
|
||||
if (source == null) {
|
||||
continue;
|
||||
}
|
||||
JsonObject obj = source.toJson().asJsonObject();
|
||||
records.add(new Record(createTimeText(obj.get("createTime")),
|
||||
integerValue(obj.get("messageType")),
|
||||
integerValue(obj.get("value"))));
|
||||
}
|
||||
return new Result(response.hits().total().value(), records);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
throw new IllegalStateException("ES 查询电量消息记录失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* createTime 在索引里可能是 yyyy-MM-dd HH:mm:ss 文本(老 range 直接传字符串可证 ES 接受该格式),
|
||||
* 也可能是 epoch 毫秒数;两种形态都归一为 yyyy-MM-dd HH:mm:ss 文本输出。
|
||||
*/
|
||||
private static String createTimeText(JsonValue value) {
|
||||
if (value == null || value.getValueType() == JsonValue.ValueType.NULL) {
|
||||
return null;
|
||||
}
|
||||
if (value instanceof JsonString) {
|
||||
return ((JsonString) value).getString();
|
||||
}
|
||||
if (value instanceof JsonNumber) {
|
||||
return TIME_FORMATTER.format(Instant.ofEpochMilli(((JsonNumber) value).longValue()));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Integer integerValue(JsonValue value) {
|
||||
return value != null && value.getValueType() == JsonValue.ValueType.NUMBER
|
||||
? ((JsonNumber) value).intValue() : null;
|
||||
}
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
package me.iiv.agent.mcp.tool;
|
||||
|
||||
import me.iiv.agent.es.ElectricityMessageEsGateway;
|
||||
import me.iiv.agent.mcp.ToolObject;
|
||||
import me.iiv.agent.mcp.XqTool;
|
||||
import org.springframework.ai.tool.annotation.Tool;
|
||||
import org.springframework.ai.tool.annotation.ToolParam;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeFormatterBuilder;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.time.format.ResolverStyle;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 设备电量/信号/温度等消息记录查询工具(ES electricitymessage_yyyyMM 月索引),
|
||||
* 对应老系统 /batteryAnalyse/batteryAnalyseList 的数据查询语义但修掉其坑。
|
||||
* 按用户拍板:不做任何权限校验(对齐老系统)、只走 esLocal 本地集群、全量分页返回(不做抽样)。
|
||||
*/
|
||||
@Component
|
||||
public class ElectricityMessageTools implements ToolObject {
|
||||
|
||||
private static final int DEFAULT_ROWS = 500;
|
||||
private static final int MAX_ROWS = 1000;
|
||||
/** ES from+size 深分页上限 max_result_window */
|
||||
private static final int MAX_RESULT_WINDOW = 10000;
|
||||
private static final String INDEX_PREFIX = "electricitymessage_";
|
||||
private static final DateTimeFormatter STRICT_TIME = new DateTimeFormatterBuilder()
|
||||
.appendPattern("uuuu-MM-dd HH:mm:ss").toFormatter().withResolverStyle(ResolverStyle.STRICT);
|
||||
private static final DateTimeFormatter INDEX_MONTH = DateTimeFormatter.ofPattern("yyyyMM");
|
||||
|
||||
final ElectricityMessageEsGateway gateway;
|
||||
|
||||
public ElectricityMessageTools(ElectricityMessageEsGateway gateway) {
|
||||
this.gateway = gateway;
|
||||
}
|
||||
|
||||
@XqTool(category = "hardware", kind = "read")
|
||||
@Tool(name = "hardware.electricity.message.list.query", description = "分页查询设备电量/信号/温度/充电循环次数/电压/电流消息记录"
|
||||
+ "(ES electricitymessage_yyyyMM 月索引,只走本地集群,无权限过滤,对齐老系统"
|
||||
+ " /batteryAnalyse/batteryAnalyseList)。snCode 必填;startTime/endTime 必填且必须为同一天"
|
||||
+ "(只支持单日查询,跨天直接拒绝);messageType 可选,0=电量、1=信号、2=温度、3=充电循环次数、"
|
||||
+ "4=电压、5=电流,不传=查全部类型;按 createTime ASC 排序,page 默认 1、rows 默认 500、上限 1000。")
|
||||
public Map<String, Object> hardwareElectricityMessageListQuery(
|
||||
@ToolParam(description = "设备 SN,必填,非空,match_phrase 精确短语匹配") String snCode,
|
||||
@ToolParam(description = "开始时间,yyyy-MM-dd HH:mm:ss,必填,与 endTime 必须为同一天") String startTime,
|
||||
@ToolParam(description = "结束时间,yyyy-MM-dd HH:mm:ss,必填,不早于 startTime") String endTime,
|
||||
@ToolParam(required = false, description = "消息类型:0=电量,1=信号,2=温度,3=充电循环次数,4=电压,5=电流;不传=查全部类型") Integer messageType,
|
||||
@ToolParam(required = false, description = "页码,从 1 开始,默认 1") Integer page,
|
||||
@ToolParam(required = false, description = "每页条数,默认 500,上限 1000,超出截断为 1000") Integer rows) {
|
||||
if (!StringUtils.hasText(snCode)) {
|
||||
throw new IllegalArgumentException("snCode 必填,非空");
|
||||
}
|
||||
LocalDateTime start = parseTime(startTime, "startTime");
|
||||
LocalDateTime end = parseTime(endTime, "endTime");
|
||||
// 老系统只按开始时间的月份选索引,跨月范围静默丢数据;这里显式拒绝跨天查询
|
||||
if (!start.toLocalDate().equals(end.toLocalDate())) {
|
||||
throw new IllegalArgumentException("只支持单日查询:startTime 与 endTime 必须为同一天(yyyy-MM-dd)");
|
||||
}
|
||||
if (start.isAfter(end)) {
|
||||
throw new IllegalArgumentException("startTime 不能晚于 endTime");
|
||||
}
|
||||
if (messageType != null && (messageType < 0 || messageType > 5)) {
|
||||
throw new IllegalArgumentException("messageType 仅支持 0-5");
|
||||
}
|
||||
|
||||
int pageNo = page == null || page < 1 ? 1 : page;
|
||||
boolean truncatedRows = rows != null && rows > MAX_ROWS;
|
||||
int pageSize = rows == null || rows < 1 ? DEFAULT_ROWS : Math.min(rows, MAX_ROWS);
|
||||
long fromLong = (long) (pageNo - 1) * pageSize;
|
||||
String windowNotice = null;
|
||||
if (fromLong >= MAX_RESULT_WINDOW) {
|
||||
// from+size 超出 ES max_result_window 会被 ES 拒绝,截断为窗口内最后可用的完整页
|
||||
fromLong = MAX_RESULT_WINDOW - pageSize;
|
||||
windowNotice = "查询起始位置超过 ES max_result_window(10000),已截断为第 "
|
||||
+ (fromLong / pageSize + 1) + " 页起的最后可用窗口";
|
||||
} else if (fromLong + pageSize > MAX_RESULT_WINDOW) {
|
||||
windowNotice = "本页超出 ES max_result_window(10000),已截断为 " + (MAX_RESULT_WINDOW - fromLong) + " 条";
|
||||
pageSize = MAX_RESULT_WINDOW - (int) fromLong;
|
||||
}
|
||||
|
||||
String index = INDEX_PREFIX + INDEX_MONTH.format(start);
|
||||
ElectricityMessageEsGateway.Result search = gateway.search(index, snCode.trim(), messageType,
|
||||
startTime.trim(), endTime.trim(), (int) fromLong, pageSize);
|
||||
|
||||
List<Map<String, Object>> records = search.getRecords().stream()
|
||||
.map(this::record)
|
||||
.collect(Collectors.toList());
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("snCode", snCode.trim());
|
||||
result.put("index", index);
|
||||
result.put("total", search.getTotal());
|
||||
result.put("page", pageNo);
|
||||
result.put("rows", pageSize);
|
||||
String notice = notice(truncatedRows, windowNotice);
|
||||
if (notice != null) {
|
||||
result.put("notice", notice);
|
||||
}
|
||||
result.put("records", records);
|
||||
return result;
|
||||
}
|
||||
|
||||
private Map<String, Object> record(ElectricityMessageEsGateway.Record message) {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("createTime", message.getCreateTime());
|
||||
row.put("messageType", message.getMessageType());
|
||||
row.put("messageTypeText", messageTypeText(message.getMessageType()));
|
||||
row.put("value", message.getValue());
|
||||
return row;
|
||||
}
|
||||
|
||||
private static String notice(boolean truncatedRows, String windowNotice) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
if (truncatedRows) {
|
||||
builder.append("rows 超过上限 1000,已截断为 1000");
|
||||
}
|
||||
if (windowNotice != null) {
|
||||
if (builder.length() > 0) {
|
||||
builder.append(";");
|
||||
}
|
||||
builder.append(windowNotice);
|
||||
}
|
||||
return builder.length() == 0 ? null : builder.toString();
|
||||
}
|
||||
|
||||
private static String messageTypeText(Integer messageType) {
|
||||
if (messageType == null || messageType < 0 || messageType > 5) {
|
||||
return null;
|
||||
}
|
||||
String[] labels = {"电量", "信号", "温度", "充电循环次数", "电压", "电流"};
|
||||
return labels[messageType];
|
||||
}
|
||||
|
||||
private static LocalDateTime parseTime(String value, String name) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
throw new IllegalArgumentException(name + " 必填,格式 yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
try {
|
||||
return LocalDateTime.parse(value.trim(), STRICT_TIME);
|
||||
} catch (DateTimeParseException ex) {
|
||||
throw new IllegalArgumentException(name + " 格式非法,要求 yyyy-MM-dd HH:mm:ss: " + value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user