Explorar o código

在网关侧编写事件监测机制

xiaoguohua hai 6 días
pai
achega
481bcbdfde
Modificáronse 25 ficheiros con 1129 adicións e 11 borrados
  1. 172 0
      .trae/documents/alarm-event-monitoring-plan.md
  2. 2 2
      doc/数据库脚本/electricity_init_new.sql
  3. 2 2
      doc/数据库脚本/update/20261113-20261126/1.sql
  4. 16 0
      forecast-dao/src/main/java/cn/oleauto/config/mapper/ConfigDeviceMapper.java
  5. 8 0
      forecast-dao/src/main/java/cn/oleauto/config/service/IConfigChannelService.java
  6. 8 0
      forecast-dao/src/main/java/cn/oleauto/config/service/IConfigStationService.java
  7. 16 0
      forecast-dao/src/main/java/cn/oleauto/config/service/impl/ConfigChannelServiceImpl.java
  8. 16 0
      forecast-dao/src/main/java/cn/oleauto/config/service/impl/ConfigStationServiceImpl.java
  9. 19 0
      forecast-dao/src/main/java/cn/oleauto/sys/mapper/SysConfigMapper.java
  10. 15 0
      forecast-dao/src/main/java/cn/oleauto/sys/service/ISysConfigService.java
  11. 21 0
      forecast-dao/src/main/java/cn/oleauto/sys/service/impl/SysConfigServiceImpl.java
  12. 18 0
      forecast-dao/src/main/resources/mapper/config/ConfigDeviceMapper.xml
  13. 138 0
      gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/alarm/AlarmEventClient.java
  14. 120 0
      gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/alarm/AlarmEventService.java
  15. 41 0
      gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/alarm/AlarmProperties.java
  16. 73 0
      gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/alarm/AlarmStationResolver.java
  17. 137 0
      gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/alarm/DataCollectMonitor.java
  18. 144 0
      gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/alarm/DeviceCommMonitor.java
  19. 7 0
      gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/service/ChannelService.java
  20. 7 0
      gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/service/ElectricityDataSrv.java
  21. 7 0
      gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/service/WeatherDataSrv.java
  22. 19 0
      gateway/forecast-device-gateway/src/main/resources/application.yml
  23. 17 0
      gateway/forecast-protocol-common/src/main/java/cn/oleauto/protocol/common/alarm/AlarmEventPublisher.java
  24. 58 0
      gateway/forecast-protocol-common/src/main/java/cn/oleauto/protocol/common/alarm/AlarmPublishEvent.java
  25. 48 7
      gateway/forecast-south/src/main/java/cn/oleauto/south/SouthProtocolImpl.java

+ 172 - 0
.trae/documents/alarm-event-monitoring-plan.md

@@ -0,0 +1,172 @@
+# 网关三类事件监测实现计划
+
+## Context
+
+网关 `forecast-device-gateway` 需要把以下三类运行异常统一上报到后端事件登记接口:
+
+1. 设备通信异常(采集设备/通信接口中断)
+2. 数据采集异常(实发功率、辐照度、风速等缺失、异常或长时间不更新)
+3. 调度上报异常(上报超时、文件缺失、发送失败、回执异常)
+
+后端接口已存在:`POST /alarm/eventRecord/inner`,body 为
+`{key, station_id, source, rule_code, alarm_time, map values, action: open|close}`。
+key/url 来自同库 `sys_config` 的 `alarm_event_record_key` / `alarm_event_record_url`。
+后端按 `(source, rule_code)` 幂等,因此网关侧只需维护本地开关状态,避免重复推送。
+
+已确认约束:
+
+- 规则编码:`DEVICE_DISCONNECT`、`DATA_EXCEPTION`、`TRANSMIT_EXCEPTION`(统一使用下划线,不使用空格)。
+- `alarm_event_rule.rule_code` 需与上述编码一致;若库中仍是带空格的旧值,需由配置/运维同步修正,代码侧不修改 DDL。
+- 调度上报异常只做 South 上报流程插桩,不做回执表兜底扫描。
+- 后端代码不改动。
+- 模块依赖方向:`gateway → forecast-south → forecast-protocol-common`;因此发布接口放 protocol-common,实现放 gateway。
+- Mapper 扫描路径为 `cn.oleauto.**.mapper`,新增 Mapper 必须位于 `...mapper` 包下。
+
+## 实现步骤
+
+### 1. protocol-common 新增告警发布契约
+
+目录:`gateway/forecast-protocol-common/src/main/java/cn/oleauto/protocol/common/alarm/`
+
+- `AlarmPublishEvent.java`
+  - 字段:`Long channelId`、`String ruleCode`、`boolean open`、`String sourceSuffix`、`Map<String,Object> values`。
+- `AlarmEventPublisher.java`
+  - 方法:`void publish(AlarmPublishEvent event)`。
+  - 由 gateway 提供 Spring Bean;South 通过现有 `SpringUtils.getBean(...)` 获取,获取或调用失败必须吞掉异常。
+
+### 2. gateway 新增告警组件
+
+目录:`gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/alarm/`
+
+- `AlarmProperties.java`:`@ConfigurationProperties(prefix = "app.alarm")`
+  - `enabled=true`、`url`、`key`、`commIdleMs=180000`、`commGraceMs=60000`、
+    `dataCheckMs=60000`、`dataStaleMs=600000`、`retryTimes=3`。
+- `AlarmEventClient.java`
+  - 组装 JSON body:`station_id`(Long)、`source`、`rule_code`、`alarm_time`(`yyyy-MM-dd HH:mm:ss`)、`values`、`action`。
+  - url/key:优先读取 `sys_config`,读取不到时回退 `app.alarm.url/key`。
+  - 使用 hutool `HttpUtil.post`,单线程有界队列异步发送,失败按 `retryTimes` 重试;所有异常只记录日志。
+- `AlarmEventService.java`
+  - `ConcurrentHashMap<String, Long> openedState`,key = `source + "|" + ruleCode`。
+  - `open(...)`:未处于 open 才推送 `action=open`;`close(...)`:处于 open 才推送 `action=close`。
+  - 计算 `stationId`,station 无法解析时跳过并记录 warn(避免脏数据)。
+  - 统一填充 `{occur_time}`。
+
+### 3. 场站解析
+
+- `gateway/.../gateway/mapper/SysConfigMapper.java`(必须在该包)
+  - `@Select("select config_value from sys_config where config_key = #{key} limit 1")`。
+- `gateway/.../gateway/mapper/AlarmStationMapper.java`
+  - `selectStationIdByChannelId(Long channelId)`:
+    `select config_station_id from config_device where config_channel_id = #{channelId} and config_station_id is not null and config_station_id <> '' limit 1`。
+  - `selectStationIdByDeviceId(Long deviceId)`:同上按 `id` 查询。
+- `AlarmStationResolver.java`
+  - 通道→场站、设备→场站,结果做 `ConcurrentHashMap` 缓存;
+    `config_station_id` 为数字字符串,解析失败返回 null。
+
+### 4. 通信中断监测
+
+`DeviceCommMonitor.java`
+
+- `register(Long channelId, String channelName, IChannel channel)` / `unregister(Long channelId)`,内部 `ConcurrentHashMap`。
+- 订阅 `channel.getTransmit().subscribeDisConnected(...)` 与 `subscribeConnected(...)`:
+  - 断开:记录断开时间,超过 `commGraceMs` 仍为断开则 `open`。
+  - 连接恢复:若此前已 open,则立即 `close`。
+- `@Scheduled(fixedDelayString = "${app.alarm.comm-check-ms:30000}")` 巡检:
+  - `transmit.state() != CONNECTED` 且 `now - max(lastConnected, registeredAt) > commIdleMs` → open;
+  - `state() == CONNECTED` → close(若已 open)。
+- 事件参数:
+  - `ruleCode = "DEVICE_DISCONNECT"`;
+  - `sourceSuffix = "station:{stationId}:channel:{channelId}"`;
+  - `values = {device_name: 通道名, channel_name: 通道名, occur_time: 当前时间}`。
+
+`ChannelService` 修改:
+
+- 注入 `DeviceCommMonitor`。
+- `start(ConfigChannel)` 成功后 `register`;`stop(Long)` 中先 `unregister` 再停通道。
+- 订阅异常全部捕获,不影响通道启动。
+
+### 5. 数据采集异常监测
+
+- `ElectricityDataSrv` / `WeatherDataSrv` 各新增只读方法 `getStationConfigMap()`(返回不可变视图),供巡检读取。
+- `DataCollectMonitor.java`,`@Scheduled(fixedDelayString = "${app.alarm.data-check-ms:60000}")`:
+  - 遍历两个 `stationMap` 中的测点,按 `PointIdDto` 复制为 `PointIdValueDto` 后调用
+    `RealDataCache.getInstance().getValue(dto)`。
+  - 异常判定:
+    - `tmReport == 0` → 缺失;
+    - `now - tmReport > dataStaleMs` → 长时间不更新;
+    - `pointAttr == INVALID` 或 `valueAttr == INVALID` → 采集异常;
+    - `valueAttr == LAZY` → 数据不刷新;
+    - `valueAttr ∈ {U1,U2,D1,D2}` → 越限;
+    - 遥测值为 `null`/`NaN`/`Infinite` → 数值异常。
+  - 正常则 `close`,异常则 `open`,由 `AlarmEventService` 去重。
+  - 事件参数:
+    - `ruleCode = "DATA_EXCEPTION"`;
+    - `sourceSuffix = "station:{sid}:point:{deviceId}:{pointType}:{pointCode}"`;
+    - `values = {point_name: pointCode, station_id, occur_time, reason}`。
+
+### 6. 调度上报异常插桩
+
+`gateway/forecast-south/src/main/java/cn/oleauto/south/SouthProtocolImpl.java`
+
+- 新增私有方法 `publishTransmitEvent(boolean open, String reason, String fileName)`:
+  通过 `SpringUtils.getBean(AlarmEventPublisher.class)` 发布 `TRANSMIT_EXCEPTION`,
+  `sourceSuffix = "station:resolved:channel:" + channel.getId()`,`values={channel_name, file_name, reason, occur_time}`;
+  全程 try/catch 吞异常。
+- `uploadFromFile()`:
+  - 成功:`publishTransmitEvent(false, "上报成功", ...)`;
+  - 异常分类:
+    - 消息含 `超时`/`timeout` → `reason=上报超时`;
+    - 消息含 `期望`/`响应` → `reason=回执异常`;
+    - 文档为空或数据缺失 → `reason=文件缺失`;
+    - 其他 IO → `reason=发送失败`;
+  - 异常时 `open`,且不得影响原有日志与后续定时任务。
+
+### 7. 配置
+
+`gateway/forecast-device-gateway/src/main/resources/application.yml` 增加:
+
+```yaml
+app:
+  alarm:
+    enabled: true
+    url: http://localhost:8080/alarm/eventRecord/inner
+    key:
+    comm-check-ms: 30000
+    comm-idle-ms: 180000
+    comm-grace-ms: 60000
+    data-check-ms: 60000
+    data-stale-ms: 600000
+    retry-times: 3
+```
+
+## 涉及文件
+
+新增:
+
+- `gateway/forecast-protocol-common/.../protocol/common/alarm/AlarmPublishEvent.java`
+- `gateway/forecast-protocol-common/.../protocol/common/alarm/AlarmEventPublisher.java`
+- `gateway/forecast-device-gateway/.../gateway/alarm/AlarmProperties.java`
+- `gateway/forecast-device-gateway/.../gateway/alarm/AlarmEventClient.java`
+- `gateway/forecast-device-gateway/.../gateway/alarm/AlarmEventService.java`
+- `gateway/forecast-device-gateway/.../gateway/alarm/AlarmStationResolver.java`
+- `gateway/forecast-device-gateway/.../gateway/alarm/DeviceCommMonitor.java`
+- `gateway/forecast-device-gateway/.../gateway/alarm/DataCollectMonitor.java`
+- `gateway/forecast-device-gateway/.../gateway/mapper/SysConfigMapper.java`
+- `gateway/forecast-device-gateway/.../gateway/mapper/AlarmStationMapper.java`
+
+修改:
+
+- `gateway/forecast-device-gateway/.../gateway/service/ChannelService.java`
+- `gateway/forecast-device-gateway/.../gateway/service/ElectricityDataSrv.java`
+- `gateway/forecast-device-gateway/.../gateway/service/WeatherDataSrv.java`
+- `gateway/forecast-device-gateway/src/main/resources/application.yml`
+- `gateway/forecast-south/.../south/SouthProtocolImpl.java`
+
+## 验证
+
+1. `mvn -q -DskipTests -pl gateway/forecast-protocol-common,gateway/forecast-device-gateway -am compile` 编译通过。
+2. 启动网关,确认 `ChannelRunner` 正常启动、无 Bean 循环依赖。
+3. 断开一个通道的采集连接,观察日志与后端 `alarm_event_record`:应出现一条 `DEVICE_DISCONNECT` open,恢复后 close。
+4. 停掉一个测点数据源超过 `data-stale-ms`,应产生 `DATA_EXCEPTION` open,恢复后 close。
+5. 模拟 South 上报超时/失败,应产生 `TRANSMIT_EXCEPTION` open,成功上报后 close。
+6. 后端不可达时,网关只输出告警日志,不影响采集与上报主流程。

+ 2 - 2
doc/数据库脚本/electricity_init_new.sql

@@ -3280,9 +3280,9 @@ COMMENT ON COLUMN alarm_event_rule.send_user IS '推送用户信息';
 COMMENT ON COLUMN alarm_event_rule.create_time IS '创建时间';
 COMMENT ON COLUMN alarm_event_rule.update_time IS '更新时间';
 
-INSERT INTO alarm_event_rule (id, name, alarm_template_id, rule_code, condition_json, station_id, priority, remark, need_sent, send_set, send_user, need_popup, enable_flag, del_flag, create_time, create_by, update_time, update_by) VALUES (3, '传输异常', 3, 'TRANSMIT EXCEPTION', NULL, 0, 0, NULL, false, NULL, NULL, false, true, false, '2026-11-18 16:41:41.440323', 'admin', '2026-11-18 16:41:41.440323', 'admin');
+INSERT INTO alarm_event_rule (id, name, alarm_template_id, rule_code, condition_json, station_id, priority, remark, need_sent, send_set, send_user, need_popup, enable_flag, del_flag, create_time, create_by, update_time, update_by) VALUES (3, '传输异常', 3, 'TRANSMIT_EXCEPTION', NULL, 0, 0, NULL, false, NULL, NULL, false, true, false, '2026-11-18 16:41:41.440323', 'admin', '2026-11-18 16:41:41.440323', 'admin');
 INSERT INTO alarm_event_rule (id, name, alarm_template_id, rule_code, condition_json, station_id, priority, remark, need_sent, send_set, send_user, need_popup, enable_flag, del_flag, create_time, create_by, update_time, update_by) VALUES (1, '设备通信中断', 1, 'DEVICE_DISCONNECT', NULL, 0, 0, NULL, false, NULL, NULL, false, true, false, '2026-11-18 16:41:41.440323', 'admin', '2026-11-18 16:41:41.440323', 'admin');
-INSERT INTO alarm_event_rule (id, name, alarm_template_id, rule_code, condition_json, station_id, priority, remark, need_sent, send_set, send_user, need_popup, enable_flag, del_flag, create_time, create_by, update_time, update_by) VALUES (2, '数据越限异常', 2, 'DATA EXCEPTION', NULL, 0, 0, NULL, false, NULL, NULL, false, true, false, '2026-11-18 16:41:41.440323', 'admin', '2026-11-18 16:41:41.440323', 'admin');
+INSERT INTO alarm_event_rule (id, name, alarm_template_id, rule_code, condition_json, station_id, priority, remark, need_sent, send_set, send_user, need_popup, enable_flag, del_flag, create_time, create_by, update_time, update_by) VALUES (2, '数据越限异常', 2, 'DATA_EXCEPTION', NULL, 0, 0, NULL, false, NULL, NULL, false, true, false, '2026-11-18 16:41:41.440323', 'admin', '2026-11-18 16:41:41.440323', 'admin');
 
 
 -- 事件记录表

+ 2 - 2
doc/数据库脚本/update/20261113-20261126/1.sql

@@ -114,9 +114,9 @@ COMMENT ON COLUMN alarm_event_rule.send_user IS '推送用户信息';
 COMMENT ON COLUMN alarm_event_rule.create_time IS '创建时间';
 COMMENT ON COLUMN alarm_event_rule.update_time IS '更新时间';
 
-INSERT INTO alarm_event_rule (id, name, alarm_template_id, rule_code, condition_json, station_id, priority, remark, need_sent, send_set, send_user, need_popup, enable_flag, del_flag, create_time, create_by, update_time, update_by) VALUES (3, '传输异常', 3, 'TRANSMIT EXCEPTION', NULL, 0, 0, NULL, false, NULL, NULL, false, true, false, '2026-11-18 16:41:41.440323', 'admin', '2026-11-18 16:41:41.440323', 'admin');
+INSERT INTO alarm_event_rule (id, name, alarm_template_id, rule_code, condition_json, station_id, priority, remark, need_sent, send_set, send_user, need_popup, enable_flag, del_flag, create_time, create_by, update_time, update_by) VALUES (3, '传输异常', 3, 'TRANSMIT_EXCEPTION', NULL, 0, 0, NULL, false, NULL, NULL, false, true, false, '2026-11-18 16:41:41.440323', 'admin', '2026-11-18 16:41:41.440323', 'admin');
 INSERT INTO alarm_event_rule (id, name, alarm_template_id, rule_code, condition_json, station_id, priority, remark, need_sent, send_set, send_user, need_popup, enable_flag, del_flag, create_time, create_by, update_time, update_by) VALUES (1, '设备通信中断', 1, 'DEVICE_DISCONNECT', NULL, 0, 0, NULL, false, NULL, NULL, false, true, false, '2026-11-18 16:41:41.440323', 'admin', '2026-11-18 16:41:41.440323', 'admin');
-INSERT INTO alarm_event_rule (id, name, alarm_template_id, rule_code, condition_json, station_id, priority, remark, need_sent, send_set, send_user, need_popup, enable_flag, del_flag, create_time, create_by, update_time, update_by) VALUES (2, '数据越限异常', 2, 'DATA EXCEPTION', NULL, 0, 0, NULL, false, NULL, NULL, false, true, false, '2026-11-18 16:41:41.440323', 'admin', '2026-11-18 16:41:41.440323', 'admin');
+INSERT INTO alarm_event_rule (id, name, alarm_template_id, rule_code, condition_json, station_id, priority, remark, need_sent, send_set, send_user, need_popup, enable_flag, del_flag, create_time, create_by, update_time, update_by) VALUES (2, '数据越限异常', 2, 'DATA_EXCEPTION', NULL, 0, 0, NULL, false, NULL, NULL, false, true, false, '2026-11-18 16:41:41.440323', 'admin', '2026-11-18 16:41:41.440323', 'admin');
 
 
 -- 事件记录表

+ 16 - 0
forecast-dao/src/main/java/cn/oleauto/config/mapper/ConfigDeviceMapper.java

@@ -27,6 +27,22 @@ public interface ConfigDeviceMapper
      */
     public List<ConfigDevice> selectConfigDeviceList(ConfigDevice configDevice);
 
+    /**
+     * 查询通道下任一设备所属的场站ID
+     *
+     * @param channelId 通道主键
+     * @return 场站ID
+     */
+    public String selectStationIdByChannelId(Long channelId);
+
+    /**
+     * 查询设备所属的场站ID
+     *
+     * @param deviceId 设备主键
+     * @return 场站ID
+     */
+    public String selectStationIdByDeviceId(Long deviceId);
+
     /**
      * 新增设备信息
      * 

+ 8 - 0
forecast-dao/src/main/java/cn/oleauto/config/service/IConfigChannelService.java

@@ -27,6 +27,14 @@ public interface IConfigChannelService
      */
     public List<ConfigChannel> selectConfigChannelList(ConfigChannel configChannel);
 
+    /**
+     * 查询通道下任一设备所属的场站ID
+     *
+     * @param channelId 通道主键
+     * @return 场站ID
+     */
+    public String selectStationIdByChannelId(Long channelId);
+
     /**
      * 新增通道
      * 

+ 8 - 0
forecast-dao/src/main/java/cn/oleauto/config/service/IConfigStationService.java

@@ -27,6 +27,14 @@ public interface IConfigStationService
      */
     public List<ConfigStation> selectConfigStationList(ConfigStation configStation);
 
+    /**
+     * 查询设备所属的场站ID
+     *
+     * @param deviceId 设备主键
+     * @return 场站ID
+     */
+    public String selectStationIdByDeviceId(Long deviceId);
+
     /**
      * 新增光伏场站
      * 

+ 16 - 0
forecast-dao/src/main/java/cn/oleauto/config/service/impl/ConfigChannelServiceImpl.java

@@ -5,6 +5,7 @@ import cn.oleauto.common.utils.DateUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import cn.oleauto.config.mapper.ConfigChannelMapper;
+import cn.oleauto.config.mapper.ConfigDeviceMapper;
 import cn.oleauto.config.domain.ConfigChannel;
 import cn.oleauto.config.service.IConfigChannelService;
 
@@ -20,6 +21,9 @@ public class ConfigChannelServiceImpl implements IConfigChannelService
     @Autowired
     private ConfigChannelMapper configChannelMapper;
 
+    @Autowired
+    private ConfigDeviceMapper configDeviceMapper;
+
     /**
      * 查询通道
      * 
@@ -44,6 +48,18 @@ public class ConfigChannelServiceImpl implements IConfigChannelService
         return configChannelMapper.selectConfigChannelList(configChannel);
     }
 
+    /**
+     * 查询通道下任一设备所属的场站ID
+     *
+     * @param channelId 通道主键
+     * @return 场站ID
+     */
+    @Override
+    public String selectStationIdByChannelId(Long channelId)
+    {
+        return configDeviceMapper.selectStationIdByChannelId(channelId);
+    }
+
     /**
      * 新增通道
      * 

+ 16 - 0
forecast-dao/src/main/java/cn/oleauto/config/service/impl/ConfigStationServiceImpl.java

@@ -4,6 +4,7 @@ import java.util.List;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import cn.oleauto.config.mapper.ConfigStationMapper;
+import cn.oleauto.config.mapper.ConfigDeviceMapper;
 import cn.oleauto.config.domain.ConfigStation;
 import cn.oleauto.config.service.IConfigStationService;
 
@@ -19,6 +20,9 @@ public class ConfigStationServiceImpl implements IConfigStationService
     @Autowired
     private ConfigStationMapper configStationMapper;
 
+    @Autowired
+    private ConfigDeviceMapper configDeviceMapper;
+
     /**
      * 查询光伏场站
      * 
@@ -43,6 +47,18 @@ public class ConfigStationServiceImpl implements IConfigStationService
         return configStationMapper.selectConfigStationList(configStation);
     }
 
+    /**
+     * 查询设备所属的场站ID
+     *
+     * @param deviceId 设备主键
+     * @return 场站ID
+     */
+    @Override
+    public String selectStationIdByDeviceId(Long deviceId)
+    {
+        return configDeviceMapper.selectStationIdByDeviceId(deviceId);
+    }
+
     /**
      * 新增光伏场站
      * 

+ 19 - 0
forecast-dao/src/main/java/cn/oleauto/sys/mapper/SysConfigMapper.java

@@ -0,0 +1,19 @@
+package cn.oleauto.sys.mapper;
+
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Select;
+
+/**
+ * 系统参数Mapper接口。
+ */
+public interface SysConfigMapper {
+
+    /**
+     * 按参数键查询参数值。
+     *
+     * @param key 参数键
+     * @return 参数值,不存在时返回 null
+     */
+    @Select("select config_value from sys_config where config_key = #{key} limit 1")
+    String selectConfigValue(@Param("key") String key);
+}

+ 15 - 0
forecast-dao/src/main/java/cn/oleauto/sys/service/ISysConfigService.java

@@ -0,0 +1,15 @@
+package cn.oleauto.sys.service;
+
+/**
+ * 系统参数Service接口。
+ */
+public interface ISysConfigService {
+
+    /**
+     * 按参数键查询参数值。
+     *
+     * @param key 参数键
+     * @return 参数值,不存在时返回 null
+     */
+    String selectConfigValue(String key);
+}

+ 21 - 0
forecast-dao/src/main/java/cn/oleauto/sys/service/impl/SysConfigServiceImpl.java

@@ -0,0 +1,21 @@
+package cn.oleauto.sys.service.impl;
+
+import cn.oleauto.sys.mapper.SysConfigMapper;
+import cn.oleauto.sys.service.ISysConfigService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+/**
+ * 系统参数Service业务层处理。
+ */
+@Service
+public class SysConfigServiceImpl implements ISysConfigService {
+
+    @Autowired
+    private SysConfigMapper sysConfigMapper;
+
+    @Override
+    public String selectConfigValue(String key) {
+        return sysConfigMapper.selectConfigValue(key);
+    }
+}

+ 18 - 0
forecast-dao/src/main/resources/mapper/config/ConfigDeviceMapper.xml

@@ -85,4 +85,22 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
             #{id}
         </foreach>
     </delete>
+
+    <select id="selectStationIdByChannelId" parameterType="Long" resultType="String">
+        select config_station_id
+        from config_device
+        where config_channel_id = #{channelId}
+          and config_station_id is not null
+          and config_station_id &lt;&gt; ''
+        limit 1
+    </select>
+
+    <select id="selectStationIdByDeviceId" parameterType="Long" resultType="String">
+        select config_station_id
+        from config_device
+        where id = #{deviceId}
+          and config_station_id is not null
+          and config_station_id &lt;&gt; ''
+        limit 1
+    </select>
 </mapper>

+ 138 - 0
gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/alarm/AlarmEventClient.java

@@ -0,0 +1,138 @@
+package cn.oleauto.device.gateway.alarm;
+
+import cn.hutool.http.HttpRequest;
+import cn.hutool.http.HttpResponse;
+import cn.hutool.json.JSONObject;
+import cn.oleauto.sys.service.ISysConfigService;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Component;
+
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Map;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * 事件登记接口客户端。
+ * 使用单线程有界队列异步发送,失败按配置重试;所有异常只记录日志,不影响主流程。
+ */
+@Slf4j
+@Component
+public class AlarmEventClient {
+
+    private static final String SYS_URL_KEY = "alarm_event_record_url";
+    private static final String SYS_CONFIG_KEY = "alarm_event_record_key";
+    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
+    private static final long CONFIG_CACHE_MS = 60000L;
+
+    private final AlarmProperties properties;
+    private final ISysConfigService sysConfigService;
+    private final ThreadPoolExecutor executor;
+
+    private volatile String url;
+    private volatile String key;
+    private volatile long configLoadedAt = 0L;
+
+    public AlarmEventClient(AlarmProperties properties, ISysConfigService sysConfigService) {
+        this.properties = properties;
+        this.sysConfigService = sysConfigService;
+        AtomicInteger index = new AtomicInteger();
+        this.executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
+                new ArrayBlockingQueue<>(1000),
+                r -> {
+                    Thread t = new Thread(r, "alarm-event-sender-" + index.incrementAndGet());
+                    t.setDaemon(true);
+                    return t;
+                });
+    }
+
+    /**
+     * 异步发送事件。
+     */
+    public void send(Long stationId, String source, String ruleCode, boolean open, Map<String, Object> values) {
+        if (!properties.isEnabled()) {
+            return;
+        }
+        String body = buildBody(stationId, source, ruleCode, open, values);
+        try {
+            executor.execute(() -> doSend(body));
+        } catch (RejectedExecutionException ex) {
+            log.warn("alarm event queue is full, drop event, source={}, rule={}", source, ruleCode);
+        }
+    }
+
+    private String buildBody(Long stationId, String source, String ruleCode, boolean open, Map<String, Object> values) {
+        JSONObject json = new JSONObject();
+        json.set("key", getConfig(SYS_CONFIG_KEY, properties.getKey()));
+        json.set("station_id", stationId);
+        json.set("source", source);
+        json.set("rule_code", ruleCode);
+        json.set("alarm_time", LocalDateTime.now().format(TIME_FORMATTER));
+        json.set("values", values == null ? new JSONObject() : values);
+        json.set("action", open ? "open" : "close");
+        return json.toString();
+    }
+
+    private void doSend(String body) {
+        String target = getConfig(SYS_URL_KEY, properties.getUrl());
+        if (StringUtils.isBlank(target)) {
+            log.warn("alarm event url is not configured, skip send");
+            return;
+        }
+        int times = Math.max(1, properties.getRetryTimes());
+        for (int i = 1; i <= times; i++) {
+            try (HttpResponse response = HttpRequest.post(target)
+                    .contentType("application/json")
+                    .body(body)
+                    .timeout(5000)
+                    .execute()) {
+                if (response.isOk()) {
+                    return;
+                }
+                log.warn("alarm event send failed, status={}, body={}, attempt={}",
+                        response.getStatus(), response.body(), i);
+            } catch (Exception ex) {
+                log.warn("alarm event send error, attempt={}, ex={}", i, ex.getMessage());
+            }
+            if (i < times) {
+                try {
+                    Thread.sleep(1000L);
+                } catch (InterruptedException ex) {
+                    Thread.currentThread().interrupt();
+                    return;
+                }
+            }
+        }
+    }
+
+    /**
+     * 优先使用 sys_config 中的配置,未配置时回退到 application.yml。
+     * 配置结果缓存一分钟,避免每条事件都查库。
+     */
+    private String getConfig(String configKey, String fallback) {
+        long now = System.currentTimeMillis();
+        if (now - configLoadedAt > CONFIG_CACHE_MS) {
+            synchronized (this) {
+                if (now - configLoadedAt > CONFIG_CACHE_MS) {
+                    String dbUrl = null;
+                    String dbKey = null;
+                    try {
+                        dbUrl = sysConfigService.selectConfigValue(SYS_URL_KEY);
+                        dbKey = sysConfigService.selectConfigValue(SYS_CONFIG_KEY);
+                    } catch (Exception ex) {
+                        log.warn("load alarm event config from sys_config failed, ex={}", ex.getMessage());
+                    }
+                    url = StringUtils.isNotBlank(dbUrl) ? dbUrl : properties.getUrl();
+                    key = StringUtils.isNotBlank(dbKey) ? dbKey : properties.getKey();
+                    configLoadedAt = now;
+                }
+            }
+        }
+        return SYS_URL_KEY.equals(configKey) ? url : key;
+    }
+}

+ 120 - 0
gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/alarm/AlarmEventService.java

@@ -0,0 +1,120 @@
+package cn.oleauto.device.gateway.alarm;
+
+import cn.oleauto.protocol.common.alarm.AlarmEventPublisher;
+import cn.oleauto.protocol.common.alarm.AlarmPublishEvent;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
+
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * 告警事件服务。
+ * 维护事件源开关状态,只在状态变化时上报,避免重复推送。
+ */
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class AlarmEventService implements AlarmEventPublisher {
+
+    /** 设备通信中断 */
+    public static final String RULE_DEVICE_DISCONNECT = "DEVICE_DISCONNECT";
+    /** 数据采集异常 */
+    public static final String RULE_DATA_EXCEPTION = "DATA_EXCEPTION";
+    /** 调度上报异常 */
+    public static final String RULE_TRANSMIT_EXCEPTION = "TRANSMIT_EXCEPTION";
+
+    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
+
+    private final AlarmProperties properties;
+    private final AlarmEventClient alarmEventClient;
+    private final AlarmStationResolver alarmStationResolver;
+
+    /** key = source + "|" + ruleCode,value = 最近一次打开时间 */
+    private final ConcurrentHashMap<String, Long> openedState = new ConcurrentHashMap<>();
+
+    @Override
+    public void publish(AlarmPublishEvent event) {
+        if (event == null) {
+            return;
+        }
+        if (event.isOpen()) {
+            openByChannel(event.getChannelId(), event.getRuleCode(), event.getSourceSuffix(), event.getValues());
+        } else {
+            closeByChannel(event.getChannelId(), event.getRuleCode(), event.getSourceSuffix(), event.getValues());
+        }
+    }
+
+    /**
+     * 按通道上报事件打开状态。
+     */
+    public void openByChannel(Long channelId, String ruleCode, String sourceSuffix, Map<String, Object> values) {
+        Long stationId = alarmStationResolver.getStationIdByChannelId(channelId);
+        if (stationId == null) {
+            log.warn("alarm event station not resolved, channelId={}, rule={}", channelId, ruleCode);
+            return;
+        }
+        open(stationId, ruleCode, sourceSuffix, values);
+    }
+
+    /**
+     * 按通道上报事件恢复状态。
+     */
+    public void closeByChannel(Long channelId, String ruleCode, String sourceSuffix, Map<String, Object> values) {
+        Long stationId = alarmStationResolver.getStationIdByChannelId(channelId);
+        if (stationId == null) {
+            return;
+        }
+        close(stationId, ruleCode, sourceSuffix, values);
+    }
+
+    /**
+     * 上报事件发生。已处于打开状态时不重复上报。
+     */
+    public void open(Long stationId, String ruleCode, String sourceSuffix, Map<String, Object> values) {
+        if (!properties.isEnabled() || stationId == null) {
+            return;
+        }
+        String source = buildSource(stationId, sourceSuffix);
+        String key = source + "|" + ruleCode;
+        if (openedState.putIfAbsent(key, System.currentTimeMillis()) != null) {
+            return;
+        }
+        log.info("alarm event open, source={}, rule={}", source, ruleCode);
+        alarmEventClient.send(stationId, source, ruleCode, true, withOccurTime(values));
+    }
+
+    /**
+     * 上报事件恢复。未处于打开状态时不重复上报。
+     */
+    public void close(Long stationId, String ruleCode, String sourceSuffix, Map<String, Object> values) {
+        if (!properties.isEnabled() || stationId == null) {
+            return;
+        }
+        String source = buildSource(stationId, sourceSuffix);
+        String key = source + "|" + ruleCode;
+        if (openedState.remove(key) == null) {
+            return;
+        }
+        log.info("alarm event close, source={}, rule={}", source, ruleCode);
+        alarmEventClient.send(stationId, source, ruleCode, false, withOccurTime(values));
+    }
+
+    private String buildSource(Long stationId, String sourceSuffix) {
+        if (StringUtils.isBlank(sourceSuffix)) {
+            return "station:" + stationId;
+        }
+        return sourceSuffix.replace("{stationId}", String.valueOf(stationId));
+    }
+
+    private Map<String, Object> withOccurTime(Map<String, Object> values) {
+        Map<String, Object> result = values == null ? new LinkedHashMap<>() : new LinkedHashMap<>(values);
+        result.putIfAbsent("occur_time", LocalDateTime.now().format(TIME_FORMATTER));
+        return result;
+    }
+}

+ 41 - 0
gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/alarm/AlarmProperties.java

@@ -0,0 +1,41 @@
+package cn.oleauto.device.gateway.alarm;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+/**
+ * 事件监测配置。
+ */
+@Data
+@Component
+@ConfigurationProperties(prefix = "app.alarm")
+public class AlarmProperties {
+
+    /** 是否启用事件监测 */
+    private boolean enabled = true;
+
+    /** 事件登记接口地址,sys_config 未配置时使用 */
+    private String url;
+
+    /** 事件登记校验密钥,sys_config 未配置时使用 */
+    private String key;
+
+    /** 通信状态巡检周期(ms) */
+    private long commCheckMs = 30000;
+
+    /** 通信中断判定时长(ms):超过该时长未连接则判定为中断 */
+    private long commIdleMs = 180000;
+
+    /** 断开事件宽限期(ms):断开后超过该时长仍未恢复才上报 */
+    private long commGraceMs = 60000;
+
+    /** 数据采集巡检周期(ms) */
+    private long dataCheckMs = 60000;
+
+    /** 数据超时判定时长(ms):超过该时长未更新则判定为长时间不更新 */
+    private long dataStaleMs = 600000;
+
+    /** 事件上报重试次数 */
+    private int retryTimes = 3;
+}

+ 73 - 0
gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/alarm/AlarmStationResolver.java

@@ -0,0 +1,73 @@
+package cn.oleauto.device.gateway.alarm;
+
+import cn.oleauto.config.service.IConfigChannelService;
+import cn.oleauto.config.service.IConfigStationService;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Component;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * 通道/设备到场站的解析。
+ * 解析结果缓存,未解析到的使用哨兵值做负缓存,避免巡检时反复查库。
+ */
+@Slf4j
+@Component
+@RequiredArgsConstructor
+public class AlarmStationResolver {
+
+    private static final Long NONE = -1L;
+
+    private final IConfigChannelService configChannelService;
+    private final IConfigStationService configStationService;
+
+    private final Map<Long, Long> channelStationCache = new ConcurrentHashMap<>();
+    private final Map<Long, Long> deviceStationCache = new ConcurrentHashMap<>();
+
+    /**
+     * 按通道解析场站ID。
+     */
+    public Long getStationIdByChannelId(Long channelId) {
+        if (channelId == null) {
+            return null;
+        }
+        Long cached = channelStationCache.get(channelId);
+        if (cached != null) {
+            return NONE.equals(cached) ? null : cached;
+        }
+        Long stationId = parse(configChannelService.selectStationIdByChannelId(channelId));
+        channelStationCache.put(channelId, stationId == null ? NONE : stationId);
+        return stationId;
+    }
+
+    /**
+     * 按设备解析场站ID。
+     */
+    public Long getStationIdByDeviceId(Long deviceId) {
+        if (deviceId == null || deviceId < 0) {
+            return null;
+        }
+        Long cached = deviceStationCache.get(deviceId);
+        if (cached != null) {
+            return NONE.equals(cached) ? null : cached;
+        }
+        Long stationId = parse(configStationService.selectStationIdByDeviceId(deviceId));
+        deviceStationCache.put(deviceId, stationId == null ? NONE : stationId);
+        return stationId;
+    }
+
+    private Long parse(String value) {
+        if (StringUtils.isBlank(value)) {
+            return null;
+        }
+        try {
+            return Long.parseLong(value.trim());
+        } catch (NumberFormatException ex) {
+            log.warn("invalid config_station_id={}", value);
+            return null;
+        }
+    }
+}

+ 137 - 0
gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/alarm/DataCollectMonitor.java

@@ -0,0 +1,137 @@
+package cn.oleauto.device.gateway.alarm;
+
+import cn.oleauto.common.core.dto.PointIdDto;
+import cn.oleauto.common.core.dto.PointIdValueDto;
+import cn.oleauto.common.enums.PointAttributeType;
+import cn.oleauto.common.enums.PointType;
+import cn.oleauto.common.enums.ValueAttributeType;
+import cn.oleauto.device.gateway.service.ElectricityDataSrv;
+import cn.oleauto.device.gateway.service.WeatherDataSrv;
+import cn.oleauto.protocol.common.cache.RealDataCache;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.BeanUtils;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import java.lang.reflect.Field;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * 数据采集异常监测。
+ * 定时巡检电力/气象测点,判断数据缺失、长时间不更新、状态异常、不刷新与越限。
+ */
+@Slf4j
+@Component
+@RequiredArgsConstructor
+public class DataCollectMonitor {
+
+    private final AlarmProperties properties;
+    private final AlarmEventService alarmEventService;
+    private final ElectricityDataSrv electricityDataSrv;
+    private final WeatherDataSrv weatherDataSrv;
+
+    /** 启动宽限期结束时间,避免启动初期缓存为空时集中误报 */
+    private volatile long graceUntil = 0L;
+
+    @Scheduled(fixedDelayString = "${app.alarm.data-check-ms:60000}")
+    public void check() {
+        if (!properties.isEnabled()) {
+            return;
+        }
+        long now = System.currentTimeMillis();
+        if (graceUntil == 0L) {
+            graceUntil = now + properties.getDataStaleMs();
+        }
+        if (now < graceUntil) {
+            return;
+        }
+        electricityDataSrv.getStationConfigMap()
+                .forEach((stationId, config) -> checkStation(stationId, config));
+        weatherDataSrv.getStationConfigMap()
+                .forEach((stationId, config) -> checkStation(stationId, config));
+    }
+
+    private void checkStation(Long stationId, Object config) {
+        for (Field field : config.getClass().getDeclaredFields()) {
+            if (!PointIdDto.class.isAssignableFrom(field.getType())) {
+                continue;
+            }
+            field.setAccessible(true);
+            PointIdDto point;
+            try {
+                point = (PointIdDto) field.get(config);
+            } catch (IllegalAccessException ex) {
+                continue;
+            }
+            if (point == null) {
+                continue;
+            }
+            try {
+                checkPoint(stationId, point);
+            } catch (Exception ex) {
+                log.warn("check point failed, station={}, point={}, ex={}",
+                        stationId, point.getPointCode(), ex.getMessage());
+            }
+        }
+    }
+
+    private void checkPoint(Long stationId, PointIdDto point) {
+        PointIdValueDto valueDto = new PointIdValueDto();
+        BeanUtils.copyProperties(point, valueDto);
+        RealDataCache.getInstance().getValue(valueDto);
+
+        String reason = evaluate(valueDto);
+        String sourceSuffix = "station:" + stationId + ":point:" + point.getDeviceId()
+                + ":" + pointType(point) + ":" + point.getPointCode();
+        Map<String, Object> values = new LinkedHashMap<>();
+        values.put("point_name", point.getPointCode());
+        values.put("station_id", stationId);
+        values.put("reason", reason == null ? "" : reason);
+
+        if (reason == null) {
+            alarmEventService.close(stationId, AlarmEventService.RULE_DATA_EXCEPTION, sourceSuffix, values);
+        } else {
+            alarmEventService.open(stationId, AlarmEventService.RULE_DATA_EXCEPTION, sourceSuffix, values);
+        }
+    }
+
+    /**
+     * 判断测点数据是否异常,正常返回 null。
+     */
+    private String evaluate(PointIdValueDto valueDto) {
+        long now = System.currentTimeMillis();
+        if (valueDto.getTmReport() <= 0) {
+            return "数据缺失";
+        }
+        if (now - valueDto.getTmReport() > properties.getDataStaleMs()) {
+            return "数据长时间未更新";
+        }
+        if (valueDto.getPointAttr() == PointAttributeType.INVALID) {
+            return "测点状态无效";
+        }
+        ValueAttributeType valueAttr = valueDto.getValueAttr();
+        if (valueAttr == ValueAttributeType.INVALID) {
+            return "采集数据异常";
+        }
+        if (valueAttr == ValueAttributeType.LAZY) {
+            return "数据长时间未刷新";
+        }
+        if (valueAttr == ValueAttributeType.U1 || valueAttr == ValueAttributeType.U2
+                || valueAttr == ValueAttributeType.D1 || valueAttr == ValueAttributeType.D2) {
+            return "数据越限";
+        }
+        if (valueDto.getPointType() == PointType.YC) {
+            Double value = valueDto.getDValue();
+            if (value == null || value.isNaN() || value.isInfinite()) {
+                return "遥测值为空或非法";
+            }
+        }
+        return null;
+    }
+
+    private String pointType(PointIdDto point) {
+        return point.getPointType() == null ? PointType.UNKNOWN.getType() : point.getPointType().getType();
+    }
+}

+ 144 - 0
gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/alarm/DeviceCommMonitor.java

@@ -0,0 +1,144 @@
+package cn.oleauto.device.gateway.alarm;
+
+import cn.oleauto.protocol.common.IChannel;
+import cn.oleauto.protocol.common.ITransmit;
+import cn.oleauto.protocol.common.transmit.TransmitState;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * 设备通信异常监测。
+ * 通道启动时注册,订阅连接/断开事件,并定时巡检连接状态。
+ */
+@Slf4j
+@Component
+@RequiredArgsConstructor
+public class DeviceCommMonitor {
+
+    private final AlarmProperties properties;
+    private final AlarmEventService alarmEventService;
+
+    private final Map<Long, ChannelMonitor> monitors = new ConcurrentHashMap<>();
+
+    /**
+     * 注册通道监测。
+     */
+    public void register(Long channelId, String channelName, IChannel channel) {
+        if (channelId == null || channel == null) {
+            return;
+        }
+        unregister(channelId);
+        ChannelMonitor monitor = new ChannelMonitor(channelId, channelName, channel);
+        long now = System.currentTimeMillis();
+        monitor.registeredAt = now;
+        monitor.lastConnectedAt = now;
+        monitors.put(channelId, monitor);
+
+        ITransmit transmit = channel.getTransmit();
+        if (transmit == null) {
+            return;
+        }
+        try {
+            transmit.subscribeConnected(args -> onConnected(monitor));
+            transmit.subscribeDisConnected(args -> onDisconnected(monitor));
+        } catch (Exception ex) {
+            log.warn("subscribe transmit event failed, channelId={}, ex={}", channelId, ex.getMessage());
+        }
+    }
+
+    /**
+     * 注销通道监测。
+     */
+    public void unregister(Long channelId) {
+        if (channelId != null) {
+            monitors.remove(channelId);
+        }
+    }
+
+    /**
+     * 定时巡检通信状态。
+     */
+    @Scheduled(fixedDelayString = "${app.alarm.comm-check-ms:30000}")
+    public void check() {
+        if (!properties.isEnabled()) {
+            return;
+        }
+        monitors.values().forEach(this::checkChannel);
+    }
+
+    private void checkChannel(ChannelMonitor monitor) {
+        // 通道已被重新注册时,旧回调不再处理
+        if (monitors.get(monitor.channelId) != monitor) {
+            return;
+        }
+        ITransmit transmit = monitor.channel.getTransmit();
+        if (transmit == null) {
+            return;
+        }
+        long now = System.currentTimeMillis();
+        if (transmit.state() == TransmitState.CONNECTED) {
+            monitor.lastConnectedAt = now;
+            monitor.disconnected = false;
+            alarmEventService.closeByChannel(monitor.channelId,
+                    AlarmEventService.RULE_DEVICE_DISCONNECT, sourceSuffix(monitor.channelId), values(monitor));
+            return;
+        }
+        long since = monitor.disconnected ? monitor.disconnectedAt : monitor.lastConnectedAt;
+        long threshold = monitor.disconnected ? properties.getCommGraceMs() : properties.getCommIdleMs();
+        if (now - since > threshold) {
+            alarmEventService.openByChannel(monitor.channelId,
+                    AlarmEventService.RULE_DEVICE_DISCONNECT, sourceSuffix(monitor.channelId), values(monitor));
+        }
+    }
+
+    private void onConnected(ChannelMonitor monitor) {
+        if (monitors.get(monitor.channelId) != monitor) {
+            return;
+        }
+        monitor.lastConnectedAt = System.currentTimeMillis();
+        monitor.disconnected = false;
+        alarmEventService.closeByChannel(monitor.channelId,
+                AlarmEventService.RULE_DEVICE_DISCONNECT, sourceSuffix(monitor.channelId), values(monitor));
+    }
+
+    private void onDisconnected(ChannelMonitor monitor) {
+        if (monitors.get(monitor.channelId) != monitor) {
+            return;
+        }
+        monitor.disconnectedAt = System.currentTimeMillis();
+        monitor.disconnected = true;
+    }
+
+    private String sourceSuffix(Long channelId) {
+        return "station:{stationId}:channel:" + channelId;
+    }
+
+    private Map<String, Object> values(ChannelMonitor monitor) {
+        Map<String, Object> values = new LinkedHashMap<>();
+        values.put("device_name", monitor.channelName);
+        values.put("channel_name", monitor.channelName);
+        return values;
+    }
+
+    private static class ChannelMonitor {
+        private final Long channelId;
+        private final String channelName;
+        private final IChannel channel;
+        private volatile long registeredAt;
+        private volatile long lastConnectedAt;
+        private volatile long disconnectedAt;
+        private volatile boolean disconnected;
+
+        private ChannelMonitor(Long channelId, String channelName, IChannel channel) {
+            this.channelId = channelId;
+            this.channelName = channelName;
+            this.channel = channel;
+        }
+    }
+}

+ 7 - 0
gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/service/ChannelService.java

@@ -6,6 +6,7 @@ import cn.oleauto.common.enums.IsTrueFalseType;
 import cn.oleauto.common.exception.ServiceException;
 import cn.oleauto.config.domain.ConfigChannel;
 import cn.oleauto.config.service.IConfigChannelService;
+import cn.oleauto.device.gateway.alarm.DeviceCommMonitor;
 import cn.oleauto.protocol.common.IChannel;
 import cn.oleauto.protocol.common.cache.RealDataCache;
 import cn.oleauto.protocol.common.channel.DefaultChannel;
@@ -24,6 +25,9 @@ public class ChannelService {
     @Autowired
     private IConfigChannelService configChannelService;
 
+    @Autowired
+    private DeviceCommMonitor deviceCommMonitor;
+
     private ConcurrentHashMap<Long, IChannel> channelMap = new ConcurrentHashMap<>();
     public void start(){
         List<ConfigChannel> channelList = configChannelService.selectConfigChannelList(new ConfigChannel());
@@ -34,6 +38,7 @@ public class ChannelService {
 
     public void stop(){
         for(IChannel channel : channelMap.values()){
+            deviceCommMonitor.unregister(channel.getId());
             channel.stop();
         }
     }
@@ -65,9 +70,11 @@ public class ChannelService {
             return;
         }
         channelMap.put(configChannel.getId(), newChannel);
+        deviceCommMonitor.register(configChannel.getId(), configChannel.getName(), newChannel);
     }
 
     private void stop(Long id){
+        deviceCommMonitor.unregister(id);
         // 先停之前的服务
         IChannel oldChannel = channelMap.get(id);
         if(oldChannel != null){

+ 7 - 0
gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/service/ElectricityDataSrv.java

@@ -58,6 +58,13 @@ public class ElectricityDataSrv {
         stationMap = tempMap;
     }
 
+    /**
+     * 获取场站测点配置(只读),供数据采集异常巡检使用。
+     */
+    public Map<Long, DataElectricityPoint> getStationConfigMap() {
+        return Collections.unmodifiableMap(stationMap);
+    }
+
     private static void refreshStationConfig(ConfigStation r, ConfigElectricityLocal s, HashMap<Long, DataElectricityPoint> tempMap) {
         DataElectricityPoint dataElectricityPoint = new DataElectricityPoint();
         dataElectricityPoint.setConfigStationId(r.getId());

+ 7 - 0
gateway/forecast-device-gateway/src/main/java/cn/oleauto/device/gateway/service/WeatherDataSrv.java

@@ -57,6 +57,13 @@ public class WeatherDataSrv {
         stationMap = tempMap;
     }
 
+    /**
+     * 获取场站测点配置(只读),供数据采集异常巡检使用。
+     */
+    public Map<Long, DataWeatherPoint> getStationConfigMap() {
+        return Collections.unmodifiableMap(stationMap);
+    }
+
     private static void refreshStationConfig(ConfigStation r, ConfigWeatherLocal s, HashMap<Long, DataWeatherPoint> tempMap) {
         DataWeatherPoint dataWeatherPoint = new DataWeatherPoint();
         dataWeatherPoint.setConfigStationId(r.getId());

+ 19 - 0
gateway/forecast-device-gateway/src/main/resources/application.yml

@@ -72,3 +72,22 @@ app:
     interval-ms: 300000
   electricity:
     interval-ms: 300000
+  alarm:
+    # 是否启用事件监测
+    enabled: true
+    # 事件登记接口,优先使用 sys_config 中的 alarm_event_record_url
+    url: http://localhost:8080/alarm/eventRecord/inner
+    # 校验密钥,优先使用 sys_config 中的 alarm_event_record_key
+    key:
+    # 通信状态巡检周期(ms)
+    comm-check-ms: 30000
+    # 通信中断判定时长(ms)
+    comm-idle-ms: 180000
+    # 断开事件宽限期(ms)
+    comm-grace-ms: 60000
+    # 数据采集巡检周期(ms)
+    data-check-ms: 60000
+    # 数据超时判定时长(ms)
+    data-stale-ms: 600000
+    # 事件上报重试次数
+    retry-times: 3

+ 17 - 0
gateway/forecast-protocol-common/src/main/java/cn/oleauto/protocol/common/alarm/AlarmEventPublisher.java

@@ -0,0 +1,17 @@
+package cn.oleauto.protocol.common.alarm;
+
+/**
+ * 告警事件发布接口。
+ * <p>
+ * 接口定义在 protocol-common,实现由 gateway 提供;下层模块通过 SpringUtils 获取,
+ * 获取或调用失败时必须自行吞掉异常,不能影响采集与上报主流程。
+ */
+public interface AlarmEventPublisher {
+
+    /**
+     * 发布告警事件。
+     *
+     * @param event 告警事件
+     */
+    void publish(AlarmPublishEvent event);
+}

+ 58 - 0
gateway/forecast-protocol-common/src/main/java/cn/oleauto/protocol/common/alarm/AlarmPublishEvent.java

@@ -0,0 +1,58 @@
+package cn.oleauto.protocol.common.alarm;
+
+import java.util.Map;
+
+/**
+ * 告警事件发布对象。
+ * <p>
+ * South 等下层模块只负责构造事件,具体的场站解析、去重与上报由 gateway 侧实现。
+ */
+public class AlarmPublishEvent {
+
+    /** 通道ID,可为空;为空时由实现侧根据事件源解析 */
+    private final Long channelId;
+
+    /** 规则编码:DEVICE_DISCONNECT / DATA_EXCEPTION / TRANSMIT_EXCEPTION */
+    private final String ruleCode;
+
+    /** true=事件发生,false=事件恢复 */
+    private final boolean open;
+
+    /**
+     * 事件源后缀,与 ruleCode 一起唯一标识一个事件。
+     * 支持 {stationId} 占位符,由实现侧替换为解析出的场站ID。
+     */
+    private final String sourceSuffix;
+
+    /** 模板格式化参数 */
+    private final Map<String, Object> values;
+
+    public AlarmPublishEvent(Long channelId, String ruleCode, boolean open,
+                             String sourceSuffix, Map<String, Object> values) {
+        this.channelId = channelId;
+        this.ruleCode = ruleCode;
+        this.open = open;
+        this.sourceSuffix = sourceSuffix;
+        this.values = values;
+    }
+
+    public Long getChannelId() {
+        return channelId;
+    }
+
+    public String getRuleCode() {
+        return ruleCode;
+    }
+
+    public boolean isOpen() {
+        return open;
+    }
+
+    public String getSourceSuffix() {
+        return sourceSuffix;
+    }
+
+    public Map<String, Object> getValues() {
+        return values;
+    }
+}

+ 48 - 7
gateway/forecast-south/src/main/java/cn/oleauto/south/SouthProtocolImpl.java

@@ -8,6 +8,8 @@ import cn.oleauto.data.domain.DataSuperShortTermForecastReport;
 import cn.oleauto.data.service.IDataReportLogService;
 import cn.oleauto.data.service.IDataSuperShortTermForecastReportService;
 import cn.oleauto.protocol.common.IChannel;
+import cn.oleauto.protocol.common.alarm.AlarmEventPublisher;
+import cn.oleauto.protocol.common.alarm.AlarmPublishEvent;
 import cn.oleauto.protocol.common.protocol.AbstractProtocol;
 import cn.oleauto.protocol.common.transmit.TransmitState;
 import cn.oleauto.south.efile.EBlock;
@@ -203,11 +205,8 @@ public class SouthProtocolImpl extends AbstractProtocol {
      * 从配置的文件路径读取 E 语言文件并上传。
      */
     private void uploadFromFile() {
-        // File file = new File(uploadFile);
-//        if (!file.isFile()) {
-//            log.warn("upload file not found: {}", uploadFile);
-//            return;
-//        }
+        String fileName = (uploadFile == null || uploadFile.isBlank())
+                ? String.valueOf(nameOfFile) : uploadFile;
         try {
 //            log.info("channel={} start upload file={}", channel.getName(), uploadFile);
 //            EDocument doc = new EParser().parse(file);
@@ -217,9 +216,47 @@ public class SouthProtocolImpl extends AbstractProtocol {
 //            southTransmit.getFileTransfer().sendFile(nameOfFile, doc, charset)
             log.info("channel={} upload file done", channel.getName());
             insertReportLog();
-
+            publishTransmitEvent(false, "上报成功", fileName);
         } catch (Exception e) {
-            log.warn("channel={} upload file failed, ex={}", channel.getName(), e.getMessage());
+            String reason = classifyUploadFailure(e);
+            log.warn("channel={} upload file failed, reason={}, ex={}",
+                    channel.getName(), reason, e.getMessage());
+            publishTransmitEvent(true, reason, fileName);
+        }
+    }
+
+    /**
+     * 调度上报异常分类。
+     */
+    private static String classifyUploadFailure(Exception e) {
+        String message = e.getMessage() == null ? "" : e.getMessage();
+        String lower = message.toLowerCase();
+        if (message.contains("超时") || lower.contains("timeout") || lower.contains("timed out")) {
+            return "上报超时";
+        }
+        if (message.contains("无可用上报数据")) {
+            return "文件缺失";
+        }
+        if (message.contains("期望") || message.contains("响应") || lower.contains("ack")) {
+            return "回执异常";
+        }
+        return "发送失败";
+    }
+
+    /**
+     * 上报调度上报异常事件。告警失败不得影响上报主流程。
+     */
+    private void publishTransmitEvent(boolean open, String reason, String fileName) {
+        try {
+            AlarmEventPublisher publisher = SpringUtils.getBean(AlarmEventPublisher.class);
+            Map<String, Object> values = new LinkedHashMap<>();
+            values.put("channel_name", channel.getName());
+            values.put("file_name", fileName);
+            values.put("reason", reason);
+            publisher.publish(new AlarmPublishEvent(channel.getId(), "TRANSMIT_EXCEPTION", open,
+                    "station:{stationId}:channel:" + channel.getId(), values));
+        } catch (Exception ex) {
+            log.warn("channel={} publish transmit event failed, ex={}", channel.getName(), ex.getMessage());
         }
     }
 
@@ -284,6 +321,10 @@ public class SouthProtocolImpl extends AbstractProtocol {
         IDataSuperShortTermForecastReportService service =
                 SpringUtils.getBean(IDataSuperShortTermForecastReportService.class);
         List<DataSuperShortTermForecastReport> records = service.selectLatestOrderById(16);
+        if (records == null || records.isEmpty()) {
+            // 无数据视为上报文件缺失
+            throw new IllegalStateException("无可用上报数据");
+        }
 
         EDocument doc = new EDocument();
         EBlock block = new EBlock("DataSuperShortTermForecastReport");