fix: 电话报警通知逻辑修改。

This commit is contained in:
tianyongbao
2026-03-07 22:13:40 +08:00
parent 212e596237
commit 10cc7e75b3
14 changed files with 557 additions and 1294 deletions

View File

@@ -3,16 +3,22 @@ package com.intc.iot.handler;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.intc.iot.domain.AquAlarmHistory;
import com.intc.iot.domain.AquMapMessageWarnCallNotice;
import com.intc.iot.domain.AquWarnCallNotice;
import com.intc.iot.domain.VmsNoticeResponse;
import com.intc.iot.mapper.AquAlarmHistoryMapper;
import com.intc.iot.mapper.AquMapMessageWarnCallNoticeMapper;
import com.intc.iot.mapper.AquWarnCallNoticeMapper;
import com.intc.iot.mapper.IotDeviceMapper;
import com.intc.iot.service.VmsNoticeService;
import com.intc.fishery.domain.AquUser;
import com.intc.fishery.domain.Device;
import com.intc.fishery.domain.MessageWarn;
import com.intc.fishery.domain.Pond;
import com.intc.fishery.mapper.AquUserMapper;
import com.intc.fishery.mapper.DeviceMapper;
import com.intc.fishery.mapper.DeviceSwitchMapper;
import com.intc.fishery.mapper.MessageWarnMapper;
import com.intc.fishery.mapper.PondMapper;
import com.intc.tdengine.domain.DeviceSensorData;
import com.intc.tdengine.service.IDeviceSensorDataService;
import lombok.RequiredArgsConstructor;
@@ -49,10 +55,14 @@ public class DeviceDataHandler {
private final AquWarnCallNoticeMapper warnCallNoticeMapper;
/**
* 告警历史记录 Mapper
* 报警消息与通知记录关联 Mapper
*/
private final AquAlarmHistoryMapper alarmHistoryMapper;
private final AquMapMessageWarnCallNoticeMapper mapMessageWarnCallNoticeMapper;
/**
* 报警消息 Mapper
*/
private final MessageWarnMapper messageWarnMapper;
/**
* 设备 Mapper
@@ -64,6 +74,16 @@ public class DeviceDataHandler {
*/
private final DeviceSwitchMapper deviceSwitchMapper;
/**
* 用户 Mapper
*/
private final AquUserMapper aquUserMapper;
/**
* 塘口 Mapper
*/
private final PondMapper pondMapper;
/**
* VMS 语音通知服务
*/
@@ -82,15 +102,7 @@ public class DeviceDataHandler {
*/
private static final int CALL_STATUS_NO_CALL = 0;
/**
* 告警状态:未处理
*/
private static final int ALARM_STATUS_PENDING = 0;
/**
* 告警状态:已恢复
*/
private static final int ALARM_STATUS_RECOVERED = 2;
/**
* 告警间隔时间(分钟)- 同一设备同一类型告警在此时间内不重复发送
@@ -98,7 +110,14 @@ public class DeviceDataHandler {
private static final int ALARM_NOTIFICATION_INTERVAL = 30;
/**
* 告警类型常量
* 告警类型常量(对应 warn_type 字段)
*/
private static final int WARN_TYPE_DISSOLVED_OXYGEN = 2; // 溶解氧
private static final int WARN_TYPE_TEMPERATURE = 2; // 温度
private static final int WARN_TYPE_BATTERY = 2; // 电池电量
/**
* 告警类型名称
*/
private static final String ALARM_TYPE_DISSOLVED_OXYGEN = "溶解氧";
private static final String ALARM_TYPE_TEMPERATURE = "温度";
@@ -111,6 +130,11 @@ public class DeviceDataHandler {
private static final int ALARM_LEVEL_IMPORTANT = 2; // 重要
private static final int ALARM_LEVEL_URGENT = 3; // 紧急
/**
* 消息未读状态
*/
private static final int MSG_IS_READ_NO = 0;
/**
* 处理设备属性上报数据
*
@@ -190,10 +214,10 @@ public class DeviceDataHandler {
}
}
//
// // 检查是否触发报警
// if (params != null && sensorData != null) {
// checkAndTriggerAlarm(productKey, deviceName, sensorData);
// }
// 检查是否触发报警
if (params != null && sensorData != null) {
checkAndTriggerAlarm(productKey, deviceName, sensorData);
}
} catch (Exception e) {
log.error("处理设备属性数据失败", e);
@@ -313,9 +337,20 @@ public class DeviceDataHandler {
}
Long deviceId = device.getId();
Long userId = device.getUserId();
// 查询塘口名称
String pondName = null;
if (device.getPondId() != null) {
Pond pond = pondMapper.selectById(device.getPondId());
if (pond != null) {
pondName = pond.getPondName();
}
}
StringBuilder alarmMessage = new StringBuilder();
boolean hasAlarm = false;
java.util.List<AquAlarmHistory> alarmList = new java.util.ArrayList<>();
java.util.List<MessageWarn> warnList = new java.util.ArrayList<>();
// 1. 检查溶解氧(使用设备配置的阈值)
if (sensorData.getDissolvedOxygen() != null && device.getOxyWarnCallOpen() != null && device.getOxyWarnCallOpen() == 1) {
@@ -323,13 +358,12 @@ public class DeviceDataHandler {
Double oxyWarnLower = device.getOxyWarnLower();
if (oxyWarnLower != null && dissolvedOxygen < oxyWarnLower) {
String content = String.format("溶解氧过低: %.2f mg/L (最低: %.2f)",
String message = String.format("溶解氧过低: %.2f mg/L (最低: %.2f)",
dissolvedOxygen, oxyWarnLower);
alarmMessage.append(content).append("; ");
alarmMessage.append(message).append("; ");
AquAlarmHistory alarm = createAlarmHistory(deviceId, deviceName, ALARM_TYPE_DISSOLVED_OXYGEN,
ALARM_LEVEL_URGENT, content, dissolvedOxygen, oxyWarnLower);
alarmList.add(alarm);
warnList.add(createMessageWarn(deviceId, userId, pondName,
ALARM_TYPE_DISSOLVED_OXYGEN, WARN_TYPE_DISSOLVED_OXYGEN, message));
hasAlarm = true;
}
}
@@ -341,22 +375,20 @@ public class DeviceDataHandler {
Double tempWarnUpper = device.getTempWarnUpper();
if (tempWarnLower != null && temperature < tempWarnLower) {
String content = String.format("水温过低: %.2f °C (最低: %.2f)",
String message = String.format("水温过低: %.2f °C (最低: %.2f)",
temperature, tempWarnLower);
alarmMessage.append(content).append("; ");
alarmMessage.append(message).append("; ");
AquAlarmHistory alarm = createAlarmHistory(deviceId, deviceName, ALARM_TYPE_TEMPERATURE,
ALARM_LEVEL_IMPORTANT, content, temperature, tempWarnLower);
alarmList.add(alarm);
warnList.add(createMessageWarn(deviceId, userId, pondName,
ALARM_TYPE_TEMPERATURE, WARN_TYPE_TEMPERATURE, message));
hasAlarm = true;
} else if (tempWarnUpper != null && temperature > tempWarnUpper) {
String content = String.format("水温过高: %.2f °C (最高: %.2f)",
String message = String.format("水温过高: %.2f °C (最高: %.2f)",
temperature, tempWarnUpper);
alarmMessage.append(content).append("; ");
alarmMessage.append(message).append("; ");
AquAlarmHistory alarm = createAlarmHistory(deviceId, deviceName, ALARM_TYPE_TEMPERATURE,
ALARM_LEVEL_IMPORTANT, content, temperature, tempWarnUpper);
alarmList.add(alarm);
warnList.add(createMessageWarn(deviceId, userId, pondName,
ALARM_TYPE_TEMPERATURE, WARN_TYPE_TEMPERATURE, message));
hasAlarm = true;
}
}
@@ -367,36 +399,27 @@ public class DeviceDataHandler {
Double batteryWarnLower = device.getBatteryWarnLower() != null ? device.getBatteryWarnLower().doubleValue() : null;
if (batteryWarnLower != null && battery < batteryWarnLower) {
String content = String.format("电池电量低: %.2f%% (最低: %.2f%%)",
String message = String.format("电池电量低: %.2f%% (最低: %.2f%%)",
battery, batteryWarnLower);
alarmMessage.append(content).append("; ");
alarmMessage.append(message).append("; ");
AquAlarmHistory alarm = createAlarmHistory(deviceId, deviceName, ALARM_TYPE_BATTERY,
ALARM_LEVEL_NORMAL, content, battery, batteryWarnLower);
alarmList.add(alarm);
warnList.add(createMessageWarn(deviceId, userId, pondName,
ALARM_TYPE_BATTERY, WARN_TYPE_BATTERY, message));
hasAlarm = true;
}
}
// 如果有告警,保存告警历史并触发通知
// 如果有告警,保存报警消息并触发通知
if (hasAlarm) {
log.warn("[告警] {} - {}", deviceName, alarmMessage);
// 保存告警历史
for (AquAlarmHistory alarm : alarmList) {
alarmHistoryMapper.insert(alarm);
// 批量保存报警消息
for (MessageWarn warn : warnList) {
messageWarnMapper.insert(warn);
}
// 触发通知(只对紧急和重要告警发送通知)
boolean shouldNotify = alarmList.stream()
.anyMatch(alarm -> alarm.getAlarmLevel() >= ALARM_LEVEL_IMPORTANT);
if (shouldNotify) {
triggerAlarmNotification(device, alarmMessage.toString(), sensorData, alarmList);
}
} else {
// 没有告警,检查是否有未恢复的告警需要标记为已恢复
checkAndRecoverAlarms(deviceId, device, sensorData);
// 触发电话通知
triggerAlarmNotification(device, alarmMessage.toString(), sensorData, warnList);
}
} catch (Exception e) {
@@ -411,28 +434,28 @@ public class DeviceDataHandler {
* @param device 设备信息
* @param alarmMessage 告警信息
* @param sensorData 传感器数据
* @param alarmList 告警列表
* @param warnList 报警消息列表
*/
private void triggerAlarmNotification(Device device, String alarmMessage,
DeviceSensorData sensorData, java.util.List<AquAlarmHistory> alarmList) {
DeviceSensorData sensorData, java.util.List<MessageWarn> warnList) {
try {
Long deviceId = device.getId();
String deviceName = device.getDeviceName();
// 检查设备的免打扰设置
boolean shouldSkip = false;
for (AquAlarmHistory alarm : alarmList) {
if (ALARM_TYPE_DISSOLVED_OXYGEN.equals(alarm.getAlarmType()) &&
for (MessageWarn warn : warnList) {
if (WARN_TYPE_DISSOLVED_OXYGEN == warn.getWarnType() &&
device.getOxyWarnCallNoDis() != null && device.getOxyWarnCallNoDis() == 1) {
shouldSkip = true;
break;
}
if (ALARM_TYPE_TEMPERATURE.equals(alarm.getAlarmType()) &&
if (WARN_TYPE_TEMPERATURE == warn.getWarnType() &&
device.getTempWarnCallNoDis() != null && device.getTempWarnCallNoDis() == 1) {
shouldSkip = true;
break;
}
if (ALARM_TYPE_BATTERY.equals(alarm.getAlarmType()) &&
if (WARN_TYPE_BATTERY == warn.getWarnType() &&
device.getBatteryWarnCallNoDis() != null && device.getBatteryWarnCallNoDis() == 1) {
shouldSkip = true;
break;
@@ -454,23 +477,21 @@ public class DeviceDataHandler {
);
if (recentNoticeCount > 0) {
log.debug("[告警] {} - {}分钟内已通知", deviceName, ALARM_NOTIFICATION_INTERVAL);
// 更新告警历史为已通知,但不发送实际通知
for (AquAlarmHistory alarm : alarmList) {
alarm.setNotified(1);
alarm.setUpdatedTime(LocalDateTime.now());
alarmHistoryMapper.updateById(alarm);
}
log.debug("[告警] {} - {}分钟内已通知,跳过电话通知", deviceName, ALARM_NOTIFICATION_INTERVAL);
return;
}
// 从设备信息获取用户信息
Long userId = device.getUserId();
// TODO: 从用户表查询手机号
String mobilePhone = sensorData.getMobilePhone(); // 临时使用传感器数据中的手机号
// TODO: 从塘口表查询塘口名称
String pondName = deviceName; // 临时使用设备名
// 从 aqu_user 表查询手机号
String mobilePhone = null;
if (userId != null) {
AquUser aquUser = aquUserMapper.selectById(userId);
if (aquUser != null) {
mobilePhone = aquUser.getMobilePhone();
}
}
String pondName = warnList.isEmpty() ? deviceName : warnList.get(0).getPondName();
// 验证必要信息
if (userId == null || StrUtil.isBlank(mobilePhone)) {
@@ -486,22 +507,22 @@ public class DeviceDataHandler {
callNotice.setPondName(pondName);
callNotice.setCallTime(LocalDateTime.now());
callNotice.setCallStatus(CALL_STATUS_NO_CALL);
callNotice.setCreatedTime(LocalDateTime.now());
callNotice.setUpdatedTime(LocalDateTime.now());
// 保存到数据库
warnCallNoticeMapper.insert(callNotice);
// 更新告警历史中的通知ID
for (AquAlarmHistory alarm : alarmList) {
alarm.setNoticeId(callNotice.getId());
alarm.setNotified(1);
alarm.setUpdatedTime(LocalDateTime.now());
alarmHistoryMapper.updateById(alarm);
// 保存报警消息与通知记录的关联关系
for (MessageWarn warn : warnList) {
if (warn.getId() != null) {
AquMapMessageWarnCallNotice mapRecord = new AquMapMessageWarnCallNotice();
mapRecord.setMessageWarnId(warn.getId());
mapRecord.setCallNoticeId(callNotice.getId());
mapMessageWarnCallNoticeMapper.insert(mapRecord);
}
}
// 发送语音通知
sendVoiceNotification(callNotice, alarmMessage);
sendVoiceNotification(callNotice, deviceName, alarmMessage);
} catch (Exception e) {
log.error("[告警通知] 触发告警通知失败: {}", e.getMessage(), e);
@@ -509,16 +530,22 @@ public class DeviceDataHandler {
}
/**
// 发送语音通知
* @param callNotice 通知记录
* @param alarmMessage 告警信息
* 发送语音通知
*
* @param callNotice 通知记录
* @param deviceName 设备名称
* @param warnMessage 告警内容
*/
private void sendVoiceNotification(AquWarnCallNotice callNotice, String alarmMessage) {
private void sendVoiceNotification(AquWarnCallNotice callNotice, String deviceName, String warnMessage) {
try {
// 构建语音通知参数
// 构建语音通知参数(与模板变量名保持一致)
Map<String, String> ttsParams = new HashMap<>();
ttsParams.put("pond_name", callNotice.getPondName() != null ? callNotice.getPondName() : "未知塘口");
ttsParams.put("alarm_info", alarmMessage);
ttsParams.put("pondName", callNotice.getPondName() != null ? callNotice.getPondName() : "未知塘口");
ttsParams.put("deviceName", deviceName != null ? deviceName : "未知设备");
String warnMessageShort = warnMessage != null && warnMessage.contains(":")
? warnMessage.substring(0, warnMessage.indexOf(":")).trim()
: (warnMessage != null ? warnMessage : "异常");
ttsParams.put("warnMessage", warnMessageShort);
// 生成业务标识(用于回执关联)
String outId = "ALARM_" + callNotice.getId() + "_" + System.currentTimeMillis();
@@ -535,7 +562,6 @@ public class DeviceDataHandler {
callNotice.setCallStatus(1); // 呼叫成功,等待结果反馈
callNotice.setCallId(response.getCallId());
callNotice.setOutId(outId);
callNotice.setUpdatedTime(LocalDateTime.now());
warnCallNoticeMapper.updateById(callNotice);
log.info("[告警] 呼叫成功: {}", callNotice.getMobilePhone());
@@ -543,7 +569,6 @@ public class DeviceDataHandler {
// 呼叫失败
callNotice.setCallStatus(2); // 呼叫失败
callNotice.setStatusMsg(response != null ? response.getMessage() : "呼叫失败");
callNotice.setUpdatedTime(LocalDateTime.now());
warnCallNoticeMapper.updateById(callNotice);
log.error("[告警] 呼叫失败: {} - {}", callNotice.getMobilePhone(), callNotice.getStatusMsg());
@@ -556,7 +581,6 @@ public class DeviceDataHandler {
try {
callNotice.setCallStatus(2);
callNotice.setStatusMsg("发送异常: " + e.getMessage());
callNotice.setUpdatedTime(LocalDateTime.now());
warnCallNoticeMapper.updateById(callNotice);
} catch (Exception ex) {
log.error("[告警] 更新失败: {}", ex.getMessage());
@@ -588,34 +612,27 @@ public class DeviceDataHandler {
}
/**
* 创建告警历史记录
* 创建报警消息记录(写入 aqu_message_warn
*
* @param deviceId 设备ID
* @param deviceName 设备名称
* @param alarmType 告警类型
* @param alarmLevel 告警级别
* @param alarmContent 告警内容
* @param alarmValue 告警值
* @param thresholdValue 阈值
* @return 告警历史对象
* @param deviceId 设备ID
* @param userId 用户ID
* @param pondName 塘口名称
* @param title 消息标题(告警类型名称)
* @param warnType 告警类型编码
* @param message 消息内容
* @return MessageWarn 对象
*/
private AquAlarmHistory createAlarmHistory(Long deviceId, String deviceName, String alarmType,
int alarmLevel, String alarmContent,
Double alarmValue, Double thresholdValue) {
AquAlarmHistory alarm = new AquAlarmHistory();
alarm.setDeviceId(deviceId);
alarm.setDeviceName(deviceName);
alarm.setAlarmType(alarmType);
alarm.setAlarmLevel(alarmLevel);
alarm.setAlarmContent(alarmContent);
alarm.setAlarmValue(alarmValue);
alarm.setThresholdValue(thresholdValue);
alarm.setAlarmStatus(ALARM_STATUS_PENDING);
alarm.setAlarmTime(LocalDateTime.now());
alarm.setNotified(0);
alarm.setCreatedTime(LocalDateTime.now());
alarm.setUpdatedTime(LocalDateTime.now());
return alarm;
private MessageWarn createMessageWarn(Long deviceId, Long userId, String pondName,
String title, int warnType, String message) {
MessageWarn warn = new MessageWarn();
warn.setDeviceId(deviceId);
warn.setUserId(userId);
warn.setPondName(pondName);
warn.setTitle(title);
warn.setWarnType(warnType);
warn.setMessage(message);
warn.setIsRead(MSG_IS_READ_NO);
return warn;
}
/**
@@ -627,64 +644,7 @@ public class DeviceDataHandler {
* @param sensorData 传感器数据
*/
private void checkAndRecoverAlarms(Long deviceId, Device device, DeviceSensorData sensorData) {
try {
// 查询该设备所有未恢复的告警
java.util.List<AquAlarmHistory> pendingAlarms = alarmHistoryMapper.selectList(
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<AquAlarmHistory>()
.eq(AquAlarmHistory::getDeviceId, deviceId)
.ne(AquAlarmHistory::getAlarmStatus, ALARM_STATUS_RECOVERED)
);
if (pendingAlarms.isEmpty()) {
return;
}
LocalDateTime now = LocalDateTime.now();
for (AquAlarmHistory alarm : pendingAlarms) {
boolean recovered = false;
// 根据告警类型检查是否已恢复(使用设备配置的阈值)
switch (alarm.getAlarmType()) {
case ALARM_TYPE_DISSOLVED_OXYGEN:
if (sensorData.getDissolvedOxygen() != null) {
Double value = sensorData.getDissolvedOxygen();
Double oxyWarnLower = device.getOxyWarnLower();
recovered = oxyWarnLower != null && value >= oxyWarnLower;
}
break;
case ALARM_TYPE_TEMPERATURE:
if (sensorData.getTemperature() != null) {
Double value = sensorData.getTemperature();
Double tempWarnLower = device.getTempWarnLower();
Double tempWarnUpper = device.getTempWarnUpper();
recovered = (tempWarnLower == null || value >= tempWarnLower) &&
(tempWarnUpper == null || value <= tempWarnUpper);
}
break;
case ALARM_TYPE_BATTERY:
if (sensorData.getBattery() != null) {
Double batteryWarnLower = device.getBatteryWarnLower() != null ? device.getBatteryWarnLower().doubleValue() : null;
recovered = batteryWarnLower != null && sensorData.getBattery() >= batteryWarnLower;
}
break;
}
// 如果告警已恢复,更新状态
if (recovered) {
alarm.setAlarmStatus(ALARM_STATUS_RECOVERED);
alarm.setRecoveryTime(now);
alarm.setUpdatedTime(now);
alarmHistoryMapper.updateById(alarm);
log.info("[恢复] {} - {}", alarm.getDeviceName(), alarm.getAlarmType());
}
}
} catch (Exception e) {
log.error("检查告警恢复失败: {}", e.getMessage(), e);
}
// aqu_message_warn 表为消息通知,暂无需要恢复标记逻辑
}
/**