作者 钟来

添加告警短信和语音通知

正在显示 25 个修改的文件 包含 944 行增加36 行删除
package com.zhonglai.luhui.device.dto;
public class AliyunSmsNoticeDto {
private String accessKeyId;
private String accessKeySecret;
private String region;
private String signName;
private String templateCode;
private Integer intervalTime;
private String subjectName;
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public Integer getIntervalTime() {
return intervalTime;
}
public void setIntervalTime(Integer intervalTime) {
this.intervalTime = intervalTime;
}
public String getSignName() {
return signName;
}
public void setSignName(String signName) {
this.signName = signName;
}
public String getTemplateCode() {
return templateCode;
}
public void setTemplateCode(String templateCode) {
this.templateCode = templateCode;
}
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
}
... ...
package com.zhonglai.luhui.device.dto;
public class AliyunTTSNoticeDto {
private String accessKeyId;
private String accessKeySecret;
private String region;
private String ttsCode;
private Integer intervalTime;
private String subjectName;
private String calledNumber;
private Integer volume; //音量
private Integer playTimes; //播放次数
private Integer speed; //语速
public Integer getVolume() {
return volume;
}
public void setVolume(Integer volume) {
this.volume = volume;
}
public Integer getPlayTimes() {
return playTimes;
}
public void setPlayTimes(Integer playTimes) {
this.playTimes = playTimes;
}
public Integer getSpeed() {
return speed;
}
public void setSpeed(Integer speed) {
this.speed = speed;
}
public String getCalledNumber() {
return calledNumber;
}
public void setCalledNumber(String calledNumber) {
this.calledNumber = calledNumber;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public Integer getIntervalTime() {
return intervalTime;
}
public void setIntervalTime(Integer intervalTime) {
this.intervalTime = intervalTime;
}
public String getTtsCode() {
return ttsCode;
}
public void setTtsCode(String ttsCode) {
this.ttsCode = ttsCode;
}
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
}
... ...
package com.zhonglai.luhui.device.dto;
public class UserAlertPhone {
private Integer id; // int NOT NULL AUTO_INCREMENT COMMENT '主键',
private Integer user_id; // int NOT NULL COMMENT '用户id',
private String phone; // varchar(50) NOT NULL COMMENT '手机号',
private String create_time; // datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCreate_time() {
return create_time;
}
public void setCreate_time(String create_time) {
this.create_time = create_time;
}
}
... ...
... ... @@ -11,6 +11,16 @@ public class WeiXinGongZhongHaoNoticeDto {
private String gzhsecret;
private String templateId;
private String redirectUrl;
private Integer intervalTime;
public Integer getIntervalTime() {
return intervalTime;
}
public void setIntervalTime(Integer intervalTime) {
this.intervalTime = intervalTime;
}
public String getGzhsecret() {
return gzhsecret;
... ...
... ... @@ -9,7 +9,15 @@ public class WeiXinXiaoChengXuNoticeDto {
private String xcxsecret;
private String templateId;
private String redirectUrl;
private Integer intervalTime;
public Integer getIntervalTime() {
return intervalTime;
}
public void setIntervalTime(Integer intervalTime) {
this.intervalTime = intervalTime;
}
public Integer getXcxConfigId() {
return xcxConfigId;
... ...
... ... @@ -13,7 +13,10 @@ import com.zhonglai.luhui.dao.service.PublicService;
import com.zhonglai.luhui.device.domain.IotAlertLog;
import com.zhonglai.luhui.device.domain.IotAlertNoticeChannel;
import com.zhonglai.luhui.device.domain.IotPermission;
import com.zhonglai.luhui.device.dto.AliyunSmsNoticeDto;
import com.zhonglai.luhui.device.dto.AliyunTTSNoticeDto;
import com.zhonglai.luhui.device.dto.WeiXinGongZhongHaoNoticeDto;
import com.zhonglai.luhui.device.dto.WeiXinXiaoChengXuNoticeDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
... ... @@ -65,6 +68,27 @@ public class IotAlertNoticeChannelController extends BaseController {
return AjaxResult.error("渠道配置填写错误");
}
break;
case 2:
WeiXinXiaoChengXuNoticeDto weiXinXiaoChengXuNoticeDto = JSONObject.parseObject(iotAlertNoticeChannel.getConfig(), WeiXinXiaoChengXuNoticeDto.class);
if(BeanUtil.isNotEmpty(weiXinXiaoChengXuNoticeDto))
{
return AjaxResult.error("渠道配置填写错误");
}
break;
case 4:
AliyunSmsNoticeDto aliyunSmsNoticeDto = JSONObject.parseObject(iotAlertNoticeChannel.getConfig(), AliyunSmsNoticeDto.class);
if(BeanUtil.isNotEmpty(aliyunSmsNoticeDto))
{
return AjaxResult.error("渠道配置填写错误");
}
break;
case 5:
AliyunTTSNoticeDto aliyunTTSNoticeDto = JSONObject.parseObject(iotAlertNoticeChannel.getConfig(), AliyunTTSNoticeDto.class);
if(BeanUtil.isNotEmpty(aliyunTTSNoticeDto))
{
return AjaxResult.error("渠道配置填写错误");
}
break;
}
return toAjax(publicService.insert(iotAlertNoticeChannel));
}
... ...
... ... @@ -41,6 +41,19 @@
<groupId>com.zhonglai</groupId>
<artifactId>weixin-api</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>alibabacloud-dysmsapi20170525</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>alibabacloud-dyvmsapi20170525</artifactId>
</dependency>
</dependencies>
<build>
... ...
... ... @@ -46,13 +46,14 @@ public abstract class UpAlarmFactory<T> {
return new IotTerminalAlarm(IotTerminal.instantiate(beforecolumns),IotTerminal.instantiate(aftercolumns));
case "mqtt_broker.iot_alert":
return new IotAlertAlarm(IotAlert.instantiate(beforecolumns),IotAlert.instantiate(aftercolumns));
case "mqtt_broker.iot_alert_notice_channel":
return new IotAlertNoticeChannelUpCach(IotAlertNoticeChannel.instantiate(beforecolumns),IotAlertNoticeChannel.instantiate(aftercolumns));
case "mqtt_broker.iot_alert_user_notice":
return new IotAlertUserNoticeUpCack(IotAlertUserNotice.instantiate(beforecolumns),IotAlertUserNotice.instantiate(aftercolumns));
case "mqtt_broker.user_openid":
return new UserOpenidUpCach(UserOpenid.instantiate(beforecolumns),UserOpenid.instantiate(aftercolumns));
case "mqtt_broker.user_alert_phone":
return new UserAlertPhoneUpCach(UserAlertPhone.instantiate(beforecolumns),UserAlertPhone.instantiate(aftercolumns));
}
return null;
}
... ...
package com.zhonglai.luhui.alarm.clas;
import com.zhonglai.luhui.alarm.config.CachAlarmConfig;
import com.zhonglai.luhui.alarm.dto.UserAlertPhone;
import com.zhonglai.luhui.alarm.dto.UserOpenid;
import java.io.Serializable;
import java.util.Set;
/**
* 用户告警手机号
*/
public class UserAlertPhoneUpCach extends UpAlarmFactory<UserAlertPhone> implements Serializable {
public UserAlertPhoneUpCach(UserAlertPhone beforeupAlarmDb, UserAlertPhone afterupAlarmDb) {
super(beforeupAlarmDb, afterupAlarmDb);
}
@Override
void deleteGenerateAlarm() {
Set<String> set = CachAlarmConfig.user_phone.get(beforeupAlarmDb.getUser_id());
if(null != set)
{
set.remove(beforeupAlarmDb.getPhone());
if(set.size()==0)
{
CachAlarmConfig.user_phone.remove(beforeupAlarmDb.getUser_id());
}
}
}
@Override
void insertGenerateAlarm() {
CachAlarmConfig.addUserPhone(afterupAlarmDb);
}
@Override
void updateGenerateAlarm() {
deleteGenerateAlarm();
insertGenerateAlarm();
}
@Override
Object getNowValue(Object model_name, Integer type) {
return null;
}
}
... ...
... ... @@ -44,6 +44,10 @@ public class CachAlarmConfig {
/** 用户设备关系 */
public static Map<String, Integer> dervice_user = new HashMap<>();
/** 用户手机号关系 */
public static Map<Integer, Set<String>> user_phone = new HashMap<>();
public static void loadConfig()
{
//加载属性告警配置
... ... @@ -69,6 +73,9 @@ public class CachAlarmConfig {
//加载设备用户
loadDeviceUser();
//加载用户手机号
loadUserPhone();
}
/**
... ... @@ -225,6 +232,29 @@ public class CachAlarmConfig {
}
}
private static void loadUserPhone()
{
List<UserAlertPhone> list = DbOperateUtil.getUserPhoneList();
if(null != list && list.size() != 0)
{
for (UserAlertPhone userAlertPhone:list)
{
addUserPhone(userAlertPhone);
}
}
}
public static void addUserPhone(UserAlertPhone userAlertPhone)
{
Set<String> phoneset = user_phone.get(userAlertPhone.getUser_id());
if(null == phoneset)
{
phoneset = new HashSet<>();
user_phone.put(userAlertPhone.getUser_id(),phoneset);
}
phoneset.add(userAlertPhone.getPhone());
}
public static void addDeviceUser(String derviceInfoid,Integer userInfoId)
{
dervice_user.put(derviceInfoid,userInfoId);
... ... @@ -466,4 +496,14 @@ public class CachAlarmConfig {
}
return null;
}
public static Set<String> getUserPhone(Integer user_id)
{
if(user_phone.containsKey(user_id) && null != user_phone.get(user_id))
{
return user_phone.get(user_id);
}
return null;
}
}
... ...
... ... @@ -82,4 +82,9 @@ public class DbOperateUtil {
{
return baseDao.findBysql("SELECT user_info_id,id FROM `iot_terminal` WHERE user_info_id IS NOT NULL",IotTerminal.class);
}
public static List<UserAlertPhone> getUserPhoneList()
{
return baseDao.findBysql("SELECT user_id,phone FROM `user_alert_phone` WHERE user_info_id IS NOT NULL",UserAlertPhone.class);
}
}
... ...
package com.zhonglai.luhui.alarm.dto;
import com.alibaba.otter.canal.protocol.CanalEntry;
import java.util.List;
/**
* 用户告警手机号
*/
public class UserAlertPhone {
private Integer id; // int NOT NULL AUTO_INCREMENT COMMENT '主键',
private Integer user_id; // int NOT NULL COMMENT '用户id',
private String phone; // varchar(50) NOT NULL COMMENT '手机号',
private String create_time; // datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
public static UserAlertPhone instantiate(List<CanalEntry.Column> columns) {
if (null == columns || columns.size() ==0)
{
return null;
}
UserAlertPhone userAlertPhone = new UserAlertPhone();
for (CanalEntry.Column column : columns)
{
switch (column.getName())
{
case "user_id":
userAlertPhone.setUser_id(Integer.parseInt(column.getValue()));
break;
case "phone":
userAlertPhone.setPhone(column.getValue());
break;
}
}
if(null == userAlertPhone.getPhone() || null == userAlertPhone.getUser_id())
{
return null;
}
return userAlertPhone;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCreate_time() {
return create_time;
}
public void setCreate_time(String create_time) {
this.create_time = create_time;
}
}
... ...
... ... @@ -4,9 +4,13 @@ import com.alibaba.fastjson.JSONObject;
import com.zhonglai.luhui.alarm.config.CachAlarmConfig;
import com.zhonglai.luhui.alarm.dto.IotAlertLog;
import com.zhonglai.luhui.alarm.dto.UserAlarmNoticeConfig;
import com.zhonglai.luhui.alarm.notice.dto.AliyunSmsNoticeDto;
import com.zhonglai.luhui.alarm.notice.dto.AliyunTTSNoticeDto;
import com.zhonglai.luhui.alarm.notice.dto.WeiXinGongZhongHaoNoticeDto;
import com.zhonglai.luhui.alarm.notice.dto.WeiXinXiaoChengXuNoticeDto;
import com.zhonglai.luhui.alarm.notice.dto.wxUniformSend.WeiXinMessage;
import com.zhonglai.luhui.alarm.notice.impl.AliyunSmsNoticeImpl;
import com.zhonglai.luhui.alarm.notice.impl.AliyunTTSNoticeImpl;
import com.zhonglai.luhui.alarm.notice.impl.WeiXinGongZhongHaoNoticeImpl;
import com.zhonglai.luhui.alarm.notice.impl.WeiXinXiaoChengXuNoticeImpl;
import com.zhonglai.luhui.alarm.service.SendAlarmService;
... ... @@ -17,6 +21,7 @@ import weixin.popular.api.MessageAPI;
import java.util.List;
public interface NoticeFactory {
static final Logger logger = LoggerFactory.getLogger(NoticeFactory.class);
boolean send(IotAlertLog iotAlertLog);
static boolean notice(IotAlertLog iotAlertLog)
{
... ... @@ -40,10 +45,15 @@ public interface NoticeFactory {
noticeFactory = new WeiXinXiaoChengXuNoticeImpl(iotAlertLog.getUser_id(),weiXinXiaoChengXuNoticeDto);
break;
case 3:
break;
case 4:
AliyunSmsNoticeDto aliyunSmsNoticeDto = JSONObject.parseObject(userAlarmNoticeConfig.getFromConfig(),AliyunSmsNoticeDto.class);
noticeFactory = new AliyunSmsNoticeImpl(iotAlertLog.getUser_id(),aliyunSmsNoticeDto);
break;
case 5:
AliyunTTSNoticeDto aliyunTTSNoticeDto = JSONObject.parseObject(userAlarmNoticeConfig.getFromConfig(), AliyunTTSNoticeDto.class);
noticeFactory = new AliyunTTSNoticeImpl(iotAlertLog.getUser_id(),aliyunTTSNoticeDto);
break;
}
if(null != noticeFactory)
... ...
package com.zhonglai.luhui.alarm.notice.dto;
public class AliyunSmsNoticeDto {
private String accessKeyId;
private String accessKeySecret;
private String region; //服务器地区
private String signName; //签名名称
private String templateCode; //模板
private Integer intervalTime; //间隔时间
private String subjectName; //主题名称
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public Integer getIntervalTime() {
return intervalTime;
}
public void setIntervalTime(Integer intervalTime) {
this.intervalTime = intervalTime;
}
public String getSignName() {
return signName;
}
public void setSignName(String signName) {
this.signName = signName;
}
public String getTemplateCode() {
return templateCode;
}
public void setTemplateCode(String templateCode) {
this.templateCode = templateCode;
}
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
}
... ...
package com.zhonglai.luhui.alarm.notice.dto;
public class AliyunTTSNoticeDto {
private String accessKeyId;
private String accessKeySecret;
private String region;
private String ttsCode;
private Integer intervalTime;
private String subjectName;
private String calledNumber; //来电显示手机号
private Integer volume; //音量
private Integer playTimes; //播放次数
private Integer speed; //语速
public Integer getVolume() {
return volume;
}
public void setVolume(Integer volume) {
this.volume = volume;
}
public Integer getPlayTimes() {
return playTimes;
}
public void setPlayTimes(Integer playTimes) {
this.playTimes = playTimes;
}
public Integer getSpeed() {
return speed;
}
public void setSpeed(Integer speed) {
this.speed = speed;
}
public String getCalledNumber() {
return calledNumber;
}
public void setCalledNumber(String calledNumber) {
this.calledNumber = calledNumber;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public Integer getIntervalTime() {
return intervalTime;
}
public void setIntervalTime(Integer intervalTime) {
this.intervalTime = intervalTime;
}
public String getTtsCode() {
return ttsCode;
}
public void setTtsCode(String ttsCode) {
this.ttsCode = ttsCode;
}
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
}
... ...
... ... @@ -11,7 +11,15 @@ public class WeiXinGongZhongHaoNoticeDto {
private String gzhsecret;
private String templateId;
private String redirectUrl;
private Integer intervalTime;
public Integer getIntervalTime() {
return intervalTime;
}
public void setIntervalTime(Integer intervalTime) {
this.intervalTime = intervalTime;
}
public String getGzhsecret() {
return gzhsecret;
}
... ...
... ... @@ -10,7 +10,15 @@ public class WeiXinXiaoChengXuNoticeDto {
private String templateId;
private String redirectUrl;
private Integer intervalTime;
public Integer getIntervalTime() {
return intervalTime;
}
public void setIntervalTime(Integer intervalTime) {
this.intervalTime = intervalTime;
}
public Integer getXcxConfigId() {
return xcxConfigId;
}
... ...
package com.zhonglai.luhui.alarm.notice.impl;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.zhonglai.luhui.alarm.config.CachAlarmConfig;
import com.zhonglai.luhui.alarm.dto.IotAlertLog;
import com.zhonglai.luhui.alarm.notice.NoticeFactory;
import com.zhonglai.luhui.alarm.notice.dto.AliyunSmsNoticeDto;
import darabonba.core.client.ClientOverrideConfiguration;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
/**
* 阿里云短信通知告警
*/
public class AliyunSmsNoticeImpl implements NoticeFactory {
private static Map<String,Integer> phoneLastNoticeTimeMap = new HashMap<>();
private Set<String> phones;
private AliyunSmsNoticeDto aliyunSmsNoticeDto;
public AliyunSmsNoticeImpl(Integer userId, AliyunSmsNoticeDto aliyunSmsNoticeDto)
{
this.aliyunSmsNoticeDto = aliyunSmsNoticeDto;
phones = CachAlarmConfig.getUserPhone(userId);
}
@Override
public boolean send(IotAlertLog iotAlertLog) {
if(null != phones && phones.size() != 0 )
{
int nowtime = new Long(System.currentTimeMillis()/1000).intValue();
List<String> dphones = new ArrayList<>();
for (String phone:phones)
{
if(phoneLastNoticeTimeMap.containsKey(phone) && nowtime - phoneLastNoticeTimeMap.get(phone) < aliyunSmsNoticeDto.getIntervalTime())
{
dphones.add(phone);
}else {
phoneLastNoticeTimeMap.put(phone,nowtime);
}
}
for (String phone:dphones)
{
phones.remove(phone);
}
AsyncClient client = createSendClient(aliyunSmsNoticeDto.getAccessKeyId(),aliyunSmsNoticeDto.getAccessKeySecret(),aliyunSmsNoticeDto.getRegion());
try {
send(client,iotAlertLog);
} catch (Exception e) {
logger.info("发送短信告警异常",e);
}finally {
client.close();
}
}
return false;
}
private AsyncClient createSendClient(String accessKeyId,String accessKeySecret,String region)
{
StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
.accessKeyId(accessKeyId)
.accessKeySecret(accessKeySecret)
.build());
// Configure the Client
AsyncClient client = AsyncClient.builder()
.region(region) // Region ID
.credentialsProvider(provider)
.overrideConfiguration(
ClientOverrideConfiguration.create()
.setEndpointOverride("dysmsapi.aliyuncs.com")
)
.build();
return client;
}
private SendSmsResponse send(AsyncClient client,IotAlertLog iotAlertLog) throws ExecutionException, InterruptedException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("userName",aliyunSmsNoticeDto.getSubjectName()+"用户");
jsonObject.put("deviceName",iotAlertLog.getDevice_name());
jsonObject.put("alarmTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(iotAlertLog.getCreate_time())));
jsonObject.put("alarmName",iotAlertLog.getAlert_name());
SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
.phoneNumbers(String.join(",", phones))
.signName(aliyunSmsNoticeDto.getSignName())
.templateCode(aliyunSmsNoticeDto.getTemplateCode())
.templateParam(jsonObject.toJSONString())
.build();
CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
SendSmsResponse resp = response.get();
return resp;
}
}
... ...
package com.zhonglai.luhui.alarm.notice.impl;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dyvmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dyvmsapi20170525.models.SingleCallByTtsRequest;
import com.aliyun.sdk.service.dyvmsapi20170525.models.SingleCallByTtsResponse;
import com.zhonglai.luhui.alarm.config.CachAlarmConfig;
import com.zhonglai.luhui.alarm.dto.IotAlertLog;
import com.zhonglai.luhui.alarm.notice.NoticeFactory;
import com.zhonglai.luhui.alarm.notice.dto.AliyunSmsNoticeDto;
import com.zhonglai.luhui.alarm.notice.dto.AliyunTTSNoticeDto;
import darabonba.core.client.ClientOverrideConfiguration;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
/**
* 阿里云语音通知
*/
public class AliyunTTSNoticeImpl implements NoticeFactory {
private static Map<String,Integer> phoneLastNoticeTimeMap = new HashMap<>();
private Set<String> phones;
private AliyunTTSNoticeDto aliyunTTSNoticeDto;
public AliyunTTSNoticeImpl(Integer userId, AliyunTTSNoticeDto aliyunTTSNoticeDto)
{
this.aliyunTTSNoticeDto = aliyunTTSNoticeDto;
phones = CachAlarmConfig.getUserPhone(userId);
}
@Override
public boolean send(IotAlertLog iotAlertLog) {
if(null != phones && phones.size() != 0 )
{
int nowtime = new Long(System.currentTimeMillis()/1000).intValue();
List<String> dphones = new ArrayList<>();
for (String phone:phones)
{
if(phoneLastNoticeTimeMap.containsKey(phone) && nowtime - phoneLastNoticeTimeMap.get(phone) < aliyunTTSNoticeDto.getIntervalTime())
{
dphones.add(phone);
}else {
phoneLastNoticeTimeMap.put(phone,nowtime);
}
}
for (String phone:dphones)
{
phones.remove(phone);
}
AsyncClient client = createSendClient();
try {
send(client,iotAlertLog);
} catch (Exception e) {
logger.info("发送短信告警异常",e);
}finally {
client.close();
}
}
return false;
}
private AsyncClient createSendClient()
{
StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
.accessKeyId(aliyunTTSNoticeDto.getAccessKeyId())
.accessKeySecret(aliyunTTSNoticeDto.getAccessKeySecret())
.build());
AsyncClient client = AsyncClient.builder()
.region(aliyunTTSNoticeDto.getRegion()) // Region ID
.credentialsProvider(provider)
.overrideConfiguration(
ClientOverrideConfiguration.create()
.setEndpointOverride("dyvmsapi.aliyuncs.com")
)
.build();
return client;
}
private void send(AsyncClient client,IotAlertLog iotAlertLog) throws ExecutionException, InterruptedException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("userName",aliyunTTSNoticeDto.getSubjectName()+"用户");
jsonObject.put("deviceName",iotAlertLog.getDevice_name());
jsonObject.put("alarmTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(iotAlertLog.getCreate_time())));
jsonObject.put("alarmName",iotAlertLog.getAlert_name());
for (String phone:phones)
{
SingleCallByTtsRequest singleCallByTtsRequest = SingleCallByTtsRequest.builder()
.ttsCode(aliyunTTSNoticeDto.getTtsCode())
.ttsParam(jsonObject.toJSONString())
.playTimes(aliyunTTSNoticeDto.getPlayTimes())
.volume(aliyunTTSNoticeDto.getVolume())
.speed(aliyunTTSNoticeDto.getSpeed())
.calledNumber(phone)
.calledShowNumber(aliyunTTSNoticeDto.getCalledNumber())
.build();
CompletableFuture<SingleCallByTtsResponse> response = client.singleCallByTts(singleCallByTtsRequest);
SingleCallByTtsResponse resp = response.get();
System.out.println(JSONObject.toJSONString(resp));
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
AliyunTTSNoticeDto aliyunTTSNoticeDto = new AliyunTTSNoticeDto();
aliyunTTSNoticeDto.setAccessKeyId("LTAI4GCBdtG2yynzneLiGFdH");
aliyunTTSNoticeDto.setAccessKeySecret("UQSSRgQYBSQPDFFETq4inFWsF8LO5Z");
aliyunTTSNoticeDto.setCalledNumber("02566825265");
aliyunTTSNoticeDto.setRegion("cn-shanghai");
aliyunTTSNoticeDto.setIntervalTime(60);
aliyunTTSNoticeDto.setTtsCode("TTS_93335008");
aliyunTTSNoticeDto.setSubjectName("鱼儿乐");
AliyunTTSNoticeImpl aliyunTTSNoticeImpl = new AliyunTTSNoticeImpl(1,aliyunTTSNoticeDto);
AsyncClient client = aliyunTTSNoticeImpl.createSendClient();
aliyunTTSNoticeImpl.send(client,null);
}
}
... ...
... ... @@ -11,6 +11,7 @@ import weixin.popular.api.MessageAPI;
import weixin.popular.bean.message.templatemessage.Miniprogram;
import weixin.popular.bean.message.templatemessage.TemplateMessage;
import weixin.popular.bean.message.templatemessage.TemplateMessageItem;
import weixin.popular.bean.message.templatemessage.TemplateMessageResult;
import java.text.SimpleDateFormat;
import java.util.*;
... ... @@ -19,6 +20,7 @@ import java.util.*;
* 微信公众号
*/
public class WeiXinGongZhongHaoNoticeImpl implements NoticeFactory {
private static Map<String,Integer> wxsendtimeMap = new HashMap<>();
private Set<String> toOpenIds;
... ... @@ -54,15 +56,24 @@ public class WeiXinGongZhongHaoNoticeImpl implements NoticeFactory {
miniprogram.setAppid(weiXinGongZhongHaoNoticeDto.getXcxappid());
miniprogram.setPagepath(weiXinGongZhongHaoNoticeDto.getRedirectUrl());
int nowtime = new Long(System.currentTimeMillis()/1000).intValue();
for(String o:os)
{
if(wxsendtimeMap.containsKey(o) && nowtime - wxsendtimeMap.get(o) < weiXinGongZhongHaoNoticeDto.getIntervalTime())
{
continue;
}
JSONObject templateMessage = new JSONObject();
templateMessage.put("touser",o);
templateMessage.put("template_id",weiXinGongZhongHaoNoticeDto.getTemplateId());
templateMessage.put("data",data);
templateMessage.put("miniprogram",miniprogram);
WeiXinMessage.messageTemplateSend(weiXinGongZhongHaoNoticeDto.getGzhappid(),weiXinGongZhongHaoNoticeDto.getGzhsecret(),templateMessage);
TemplateMessageResult templateMessageResult = WeiXinMessage.messageTemplateSend(weiXinGongZhongHaoNoticeDto.getGzhappid(),weiXinGongZhongHaoNoticeDto.getGzhsecret(),templateMessage);
if("0".equals(templateMessageResult.getErrcode()))
{
wxsendtimeMap.put(o,nowtime);
}
}
return true;
}
... ...
... ... @@ -10,13 +10,13 @@ import weixin.popular.api.MessageAPI;
import weixin.popular.bean.message.subscribe.WxXcxSubscribeMessage;
import weixin.popular.bean.message.templatemessage.Miniprogram;
import weixin.popular.bean.message.templatemessage.TemplateMessageItem;
import weixin.popular.bean.message.templatemessage.TemplateMessageResult;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.*;
public class WeiXinXiaoChengXuNoticeImpl implements NoticeFactory {
private static Map<String,Integer> wxsendtimeMap = new HashMap<>();
private Set<String> toOpenIds;
private WeiXinXiaoChengXuNoticeDto weiXinXiaoChengXuNoticeDto;
... ... @@ -55,10 +55,19 @@ public class WeiXinXiaoChengXuNoticeImpl implements NoticeFactory {
data.put("thing8",new TemplateMessageItem(iotAlertLog.getAlert_name()));
wxXcxSubscribeMessage.setData(data);
int nowtime = new Long(System.currentTimeMillis()/1000).intValue();
for(String o:os)
{
if(wxsendtimeMap.containsKey(o) && nowtime - wxsendtimeMap.get(o) < weiXinXiaoChengXuNoticeDto.getIntervalTime())
{
continue;
}
wxXcxSubscribeMessage.setTouser(o);
MessageAPI.messageSubscribeSend(WeiXinMessage.getWechatServerToken(weiXinXiaoChengXuNoticeDto.getXcxappid(),weiXinXiaoChengXuNoticeDto.getXcxsecret()),wxXcxSubscribeMessage);
TemplateMessageResult templateMessageResult = MessageAPI.messageSubscribeSend(WeiXinMessage.getWechatServerToken(weiXinXiaoChengXuNoticeDto.getXcxappid(),weiXinXiaoChengXuNoticeDto.getXcxsecret()),wxXcxSubscribeMessage);
if("0".equals(templateMessageResult.getErrcode()))
{
wxsendtimeMap.put(o,nowtime);
}
}
return true;
}
... ...
... ... @@ -63,7 +63,7 @@ public class TriggerAlarmService {
// 连接到Canal服务器
connector.connect();
// 订阅指定的表(这里以database.table为例)
connector.subscribe("mqtt_broker\\.(iot_device|iot_terminal|iot_alert|iot_alert_notice_channel|iot_alert_user_notice|user_openid)");
connector.subscribe("mqtt_broker\\.(iot_device|iot_terminal|iot_alert|iot_alert_notice_channel|iot_alert_user_notice|user_openid|user_alert_phone)");
}
private static void handle() throws InterruptedException {
... ... @@ -82,7 +82,7 @@ public class TriggerAlarmService {
processEntries(message.getEntries());
}catch (Exception e)
{
logger.info("数据处理异常"+message.toString(),e);
logger.info("数据处理异常",e);
}
},0, TimeUnit.SECONDS);
}
... ...
... ... @@ -12,6 +12,7 @@ import com.zhonglai.luhui.dao.service.PublicService;
import com.zhonglai.luhui.device.domain.IotAlert;
import com.zhonglai.luhui.device.domain.IotAlertNoticeChannel;
import com.zhonglai.luhui.device.domain.IotAlertUserNotice;
import com.zhonglai.luhui.device.dto.UserAlertPhone;
import com.zhonglai.luhui.device.dto.WeiXinGongZhongHaoNoticeDto;
import com.zhonglai.luhui.device.dto.WeiXinXiaoChengXuNoticeDto;
import com.zhonglai.luhui.security.utils.SecurityUtils;
... ... @@ -120,7 +121,7 @@ public class UserInfoAlarmController extends BaseController {
{
map.put("iotAlertList",publicService.getObjectListBySQL("select * from `iot_alert` where product_id="+product_id));
}else {
map.put("iotAlertList",publicService.getObjectListBySQL("select * from `iot_alert` where product_id="+product_id+"alert_id in("+map.get("alert_ids")+")"));
map.put("iotAlertList",publicService.getObjectListBySQL("select * from `iot_alert` where product_id="+product_id+" and alert_id in("+map.get("alert_ids")+")"));
}
break;
case 2:
... ... @@ -128,7 +129,7 @@ public class UserInfoAlarmController extends BaseController {
{
map.put("iotAlertList",publicService.getObjectListBySQL("select * from `iot_alert_user` where product_id="+product_id));
}else {
map.put("iotAlertList",publicService.getObjectListBySQL("select * from `iot_alert_user` where product_id="+product_id+"alert_id in("+map.get("alert_ids")+")"));
map.put("iotAlertList",publicService.getObjectListBySQL("select * from `iot_alert_user` where product_id="+product_id+" and alert_id in("+map.get("alert_ids")+")"));
}
break;
}
... ... @@ -209,17 +210,12 @@ public class UserInfoAlarmController extends BaseController {
uPiotAlertUserNotice.setAlert_ids(alert_ids);
}else {
List<Map<String,Object>> aidsList = publicService.getObjectListBySQL("SELECT GROUP_CONCAT(alert_id) aids FROM `iot_alert` WHERE product_id<>"+product_id+" AND alert_id IN("+iotAlertUserNotice.getAlert_ids()+")");
if(null != aidsList && aidsList.size() != 0)
if(null != aidsList && aidsList.size() != 0 && null != aidsList.get(0) && null != aidsList.get(0).get("aids"))
{
Object aids = aidsList.get(0).get("aids");
if(null != aids && !aids.equals(""))
{
uPiotAlertUserNotice.setAlert_ids(aids+","+alert_ids);
uPiotAlertUserNotice.setAlert_ids(aidsList.get(0).get("aids")+","+alert_ids);
}else {
uPiotAlertUserNotice.setAlert_ids(alert_ids);
}
}
}
}
... ... @@ -231,6 +227,66 @@ public class UserInfoAlarmController extends BaseController {
return AjaxResult.success(upi);
}
@ApiOperation("获取告警通知的手机号")
@GetMapping(value = "getUserAlertPhoneList")
public AjaxResult getUserAlertPhoneList()
{
Integer user_id = SecurityUtils.getUserId().intValue();
List<Map<String,Object>> list = publicService.getObjectListBySQL("select * from user_alert_phone where user_id="+user_id);
return AjaxResult.success(list);
}
@ApiOperation("删除告警通知的手机号")
@ApiImplicitParam(value = "被删除的手机号",name = "phone")
@PostMapping(value = "delUserAlertPhone")
public AjaxResult delUserAlertPhone(String phone)
{
Integer user_id = SecurityUtils.getUserId().intValue();
return AjaxResult.success(publicService.updateBySql("DELETE FROM `user_alert_phone` WHERE phone='"+phone+"' AND user_id="+user_id));
}
@ApiOperation("添加告警通知手机号")
@ApiImplicitParam(value = "手机号",name = "phone")
@PostMapping(value = "addUserAlertPhone")
public AjaxResult addUserAlertPhone(String phone)
{
Integer user_id = SecurityUtils.getUserId().intValue();
UserAlertPhone userAlertPhone = new UserAlertPhone();
userAlertPhone.setPhone(phone);
userAlertPhone.setUser_id(user_id);
Long lg = publicService.getObjectListTotle(userAlertPhone,null);
if (lg>0)
{
return AjaxResult.error("该手机号已经添加过了");
}
return AjaxResult.success( publicService.insert(userAlertPhone));
}
@ApiOperation("开通指定通知服务")
@ApiImplicitParams({
@ApiImplicitParam(value = "渠道id(管理员提供)",name = "channel_id"),
@ApiImplicitParam(value = "告警类型(1系统告警,2用户告警)",name = "type"),
})
@Log(title = "开通指定通知服务", businessType = BusinessType.INSERT)
@Transactional
@PostMapping(value = "openNoticeService/{channel_id}/{type}")
public AjaxResult openNoticeService(@PathVariable Integer channel_id,@PathVariable Integer type)
{
//检查渠道是否存在
IotAlertNoticeChannel iotAlertNoticeChannel = publicService.getObject(IotAlertNoticeChannel.class,"id",channel_id+"");
if(null == iotAlertNoticeChannel)
{
return AjaxResult.error("通知渠道不存在");
}
if(iotAlertNoticeChannel.getType()!=1)
{
return AjaxResult.error("该渠道不是公众号通知渠道");
}
Integer user_id = SecurityUtils.getUserId().intValue();
return upIotAlertUserNotice(user_id,channel_id,type);
}
private void upOpenid(Integer user_id,String openid,Integer xcxConfigid)
{
//更新用户openid表
... ...
... ... @@ -32,6 +32,7 @@
<mybatis-spring-boot.version>2.2.2</mybatis-spring-boot.version>
<pagehelper.boot.version>1.4.3</pagehelper.boot.version>
<fastjson.version>1.2.80</fastjson.version>
<fastjson2.version>2.0.25</fastjson2.version>
<oshi.version>6.2.1</oshi.version>
<commons.io.version>2.11.0</commons.io.version>
<commons.fileupload.version>1.4</commons.fileupload.version>
... ... @@ -148,7 +149,7 @@
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>${fastjson.version}</version>
<version>${fastjson2.version}</version>
</dependency>
<!-- Token生成与解析-->
... ... @@ -191,7 +192,7 @@
<!-- 代码生成-->
<dependency>
<groupId>com.ruoyi</groupId>
<groupId>com.zhonglai.luhui</groupId>
<artifactId>ruoyi-generator</artifactId>
<version>${ruoyi.version}</version>
</dependency>
... ... @@ -217,13 +218,6 @@
<version>${ruoyi.version}</version>
</dependency>
<!-- 系统模块-->
<dependency>
<groupId>com.zhonglai.luhui</groupId>
<artifactId>jhlt-domin</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!-- 代码生成模块-->
<dependency>
<groupId>com.zhonglai.luhui</groupId>
... ... @@ -245,13 +239,6 @@
<version>${ruoyi.version}</version>
</dependency>
<!-- poi -->
<dependency>
<groupId>com.zhonglai.luhui</groupId>
<artifactId>lh-common-poi</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!-- 公用dao趁层 -->
<dependency>
<groupId>com.zhonglai.luhui</groupId>
... ... @@ -580,7 +567,11 @@
<artifactId>alibabacloud-dysmsapi20170525</artifactId>
<version>2.0.24</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>alibabacloud-dyvmsapi20170525</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>com.alibaba.otter</groupId>
<artifactId>canal.client</artifactId>
... ... @@ -595,7 +586,13 @@
<dependency>
<groupId>com.zhonglai</groupId>
<artifactId>weixin-api</artifactId>
<version>1.3.2</version>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.1.3</version>
</dependency>
</dependencies>
... ...
... ... @@ -83,7 +83,6 @@
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.1.3</version>
</dependency>
</dependencies>
... ...