作者 钟来

修改mqtt订阅bug

添加用户告警配置
添加微信小程序通知功能
正在显示 22 个修改的文件 包含 602 行增加295 行删除
@@ -20,11 +20,21 @@ public class IotAlertNoticeChannel { @@ -20,11 +20,21 @@ public class IotAlertNoticeChannel {
20 private String create_time; // varchar(50) NOT NULL COMMENT '创建时间', 20 private String create_time; // varchar(50) NOT NULL COMMENT '创建时间',
21 @ApiModelProperty("修改时间") 21 @ApiModelProperty("修改时间")
22 private String update_time; // varchar(50) NOT NULL COMMENT '修改时间', 22 private String update_time; // varchar(50) NOT NULL COMMENT '修改时间',
  23 + @ApiModelProperty("状态(1使用,0关闭)")
  24 + private Integer state; // varchar(50) NOT NULL COMMENT '状态(1使用,0关闭)',
23 25
24 public String getCreate_time() { 26 public String getCreate_time() {
25 return create_time; 27 return create_time;
26 } 28 }
27 29
  30 + public Integer getState() {
  31 + return state;
  32 + }
  33 +
  34 + public void setState(Integer state) {
  35 + this.state = state;
  36 + }
  37 +
28 public void setCreate_time(String create_time) { 38 public void setCreate_time(String create_time) {
29 this.create_time = create_time; 39 this.create_time = create_time;
30 } 40 }
  1 +package com.zhonglai.luhui.device.dto;
  2 +
  3 +/**
  4 + * 公众号通知的配置
  5 + */
  6 +public class WeiXinXiaoChengXuNoticeDto {
  7 + private Integer xcxConfigId;
  8 + private String xcxappid;
  9 + private String xcxsecret;
  10 + private String templateId;
  11 + private String redirectUrl;
  12 +
  13 +
  14 + public Integer getXcxConfigId() {
  15 + return xcxConfigId;
  16 + }
  17 +
  18 + public void setXcxConfigId(Integer xcxConfigId) {
  19 + this.xcxConfigId = xcxConfigId;
  20 + }
  21 +
  22 + public String getXcxappid() {
  23 + return xcxappid;
  24 + }
  25 +
  26 + public void setXcxappid(String xcxappid) {
  27 + this.xcxappid = xcxappid;
  28 + }
  29 +
  30 + public String getXcxsecret() {
  31 + return xcxsecret;
  32 + }
  33 +
  34 + public void setXcxsecret(String xcxsecret) {
  35 + this.xcxsecret = xcxsecret;
  36 + }
  37 +
  38 + public String getTemplateId() {
  39 + return templateId;
  40 + }
  41 +
  42 + public void setTemplateId(String templateId) {
  43 + this.templateId = templateId;
  44 + }
  45 +
  46 + public String getRedirectUrl() {
  47 + return redirectUrl;
  48 + }
  49 +
  50 + public void setRedirectUrl(String redirectUrl) {
  51 + this.redirectUrl = redirectUrl;
  52 + }
  53 +}
@@ -17,7 +17,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" @@ -17,7 +17,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
17 17
18 <select id="selectUserTerminalGroupList" parameterType="UserTerminalGroup" resultMap="UserTerminalGroupResult"> 18 <select id="selectUserTerminalGroupList" parameterType="UserTerminalGroup" resultMap="UserTerminalGroupResult">
19 <include refid="selectUserTerminalGroupVo"/> 19 <include refid="selectUserTerminalGroupVo"/>
20 - <where> 20 + <where>
  21 + <if test="user_info_id !=null">
  22 + and user_info_id = #{user_info_id}
  23 + </if>
21 </where> 24 </where>
22 </select> 25 </select>
23 26
@@ -14,10 +14,10 @@ public class LhAlarmMain { @@ -14,10 +14,10 @@ public class LhAlarmMain {
14 14
15 CachAlarmConfig.loadConfig(); 15 CachAlarmConfig.loadConfig();
16 //启动触发告警服务 16 //启动触发告警服务
17 -// TriggerAlarmService.start(); 17 + TriggerAlarmService.start();
18 18
19 //启动定时任务告警 19 //启动定时任务告警
20 -// TimerAlarmService.start(); 20 + TimerAlarmService.start();
21 21
22 //启动告警定时发送 22 //启动告警定时发送
23 SendAlarmService.start(); 23 SendAlarmService.start();
@@ -102,13 +102,20 @@ public abstract class UpAlarmFactory<T> { @@ -102,13 +102,20 @@ public abstract class UpAlarmFactory<T> {
102 JSONObject newObject = newjson.getJSONObject(key); 102 JSONObject newObject = newjson.getJSONObject(key);
103 String type = newObject.getString("type"); 103 String type = newObject.getString("type");
104 nv = GenericComparator.convertToType(newObject.getString("saveView"),type); 104 nv = GenericComparator.convertToType(newObject.getString("saveView"),type);
105 - ov = GenericComparator.convertToType(oldjson.getJSONObject(key).getString("saveView"),type); 105 + if(oldjson.containsKey("key"))
  106 + {
  107 + ov = GenericComparator.convertToType(oldjson.getJSONObject(key).getString("saveView"),type);
  108 + }else {
  109 + ov = null;
  110 + }
106 }catch (JSONException e ) //如果不是json,就按照字符串来对比 111 }catch (JSONException e ) //如果不是json,就按照字符串来对比
107 { 112 {
108 nv = newjson.get(key); 113 nv = newjson.get(key);
109 ov = oldjson.get(key); 114 ov = oldjson.get(key);
110 }catch (NullPointerException exception) 115 }catch (NullPointerException exception)
111 { 116 {
  117 + logger.info("属性解析异常的参数newjson:{}",newjson);
  118 + logger.info("属性解析异常的参数oldjson:{}",oldjson);
112 logger.error("告警属性解析时异常",exception); 119 logger.error("告警属性解析时异常",exception);
113 continue; 120 continue;
114 } 121 }
@@ -221,4 +228,5 @@ public abstract class UpAlarmFactory<T> { @@ -221,4 +228,5 @@ public abstract class UpAlarmFactory<T> {
221 public List<IotAlertLog> getList() { 228 public List<IotAlertLog> getList() {
222 return list; 229 return list;
223 } 230 }
  231 +
224 } 232 }
@@ -423,6 +423,8 @@ public class CachAlarmConfig { @@ -423,6 +423,8 @@ public class CachAlarmConfig {
423 423
424 public static List<UserAlarmNoticeConfig> getUserAlarmNoticeConfig(Integer user_id,Integer getAlert_config_type,Long alert_id) 424 public static List<UserAlarmNoticeConfig> getUserAlarmNoticeConfig(Integer user_id,Integer getAlert_config_type,Long alert_id)
425 { 425 {
  426 + logger.info("获取用户告警通知配置:user_id: {},getAlert_config_type {},alert_id {}",user_id,getAlert_config_type,alert_id);
  427 + logger.info("用户告警通知配置:{}",JSONObject.toJSONString(user_alarm_config));
426 IotAlertUserNotice iotAlertUserNotice = user_alarm_config.get(user_id+"|"+getAlert_config_type); 428 IotAlertUserNotice iotAlertUserNotice = user_alarm_config.get(user_id+"|"+getAlert_config_type);
427 if(null != iotAlertUserNotice && ("*".equals(iotAlertUserNotice.getAlert_ids()) || (","+iotAlertUserNotice.getAlert_ids()+",").indexOf(","+alert_id+",")>=0)) //*或者包含 429 if(null != iotAlertUserNotice && ("*".equals(iotAlertUserNotice.getAlert_ids()) || (","+iotAlertUserNotice.getAlert_ids()+",").indexOf(","+alert_id+",")>=0)) //*或者包含
428 { 430 {
@@ -433,6 +435,7 @@ public class CachAlarmConfig { @@ -433,6 +435,7 @@ public class CachAlarmConfig {
433 435
434 private static List<UserAlarmNoticeConfig> channelIdsToUserAlarmNoticeConfig(String iot_alert_notice_channel_ids) 436 private static List<UserAlarmNoticeConfig> channelIdsToUserAlarmNoticeConfig(String iot_alert_notice_channel_ids)
435 { 437 {
  438 + logger.info("开始渠道id转告警配置:{}",iot_alert_notice_channel_ids);
436 if(StringUtils.isNotEmpty(iot_alert_notice_channel_ids)) 439 if(StringUtils.isNotEmpty(iot_alert_notice_channel_ids))
437 { 440 {
438 List<UserAlarmNoticeConfig> list = new ArrayList<>(); 441 List<UserAlarmNoticeConfig> list = new ArrayList<>();
@@ -52,9 +52,9 @@ public class DbOperateUtil { @@ -52,9 +52,9 @@ public class DbOperateUtil {
52 52
53 public static List<IotAlertLog> getIotAlertLogList(Integer status,Integer limit) 53 public static List<IotAlertLog> getIotAlertLogList(Integer status,Integer limit)
54 { 54 {
55 - List<IotAlertLog> list = baseDao.findBysql("select * from iot_alert_log where alert_log_id=11408",IotAlertLog.class); 55 +// List<IotAlertLog> list = baseDao.findBysql("select * from iot_alert_log where alert_log_id=11408",IotAlertLog.class);
56 56
57 -// List<IotAlertLog> list = baseDao.findBysql("select * from iot_alert_log where `status`=? limit ?",IotAlertLog.class,status,limit); 57 + List<IotAlertLog> list = baseDao.findBysql("select * from iot_alert_log where `status`=? limit ?",IotAlertLog.class,status,limit);
58 return list; 58 return list;
59 } 59 }
60 60
@@ -82,6 +82,12 @@ public class IotDevice { @@ -82,6 +82,12 @@ public class IotDevice {
82 case "status": 82 case "status":
83 iotDevice.setStatus ( null!=column.getValue()&&!"".equals(column.getValue())?Integer.parseInt(column.getValue()):null); 83 iotDevice.setStatus ( null!=column.getValue()&&!"".equals(column.getValue())?Integer.parseInt(column.getValue()):null);
84 break; 84 break;
  85 + case "data_update_time"://一天前更新的设备不触发告警
  86 + if(new Long(System.currentTimeMillis()/1000).intValue()-Integer.parseInt(column.getValue())>=86400)
  87 + {
  88 + return null;
  89 + }
  90 + break;
85 } 91 }
86 } 92 }
87 if(null == iotDevice.getSummary() || null == iotDevice.getThings_model_value() || null == iotDevice.getClient_id() ) 93 if(null == iotDevice.getSummary() || null == iotDevice.getThings_model_value() || null == iotDevice.getClient_id() )
@@ -125,6 +125,11 @@ public class IotTerminal { @@ -125,6 +125,11 @@ public class IotTerminal {
125 case "online": 125 case "online":
126 iotTerminal.setOnline ( null!=column.getValue()&&!"".equals(column.getValue())?Integer.parseInt(column.getValue()):null); 126 iotTerminal.setOnline ( null!=column.getValue()&&!"".equals(column.getValue())?Integer.parseInt(column.getValue()):null);
127 break; 127 break;
  128 + case "data_update_time": //一天前更新的设备不触发告警
  129 + if(new Long(System.currentTimeMillis()/1000).intValue()-Integer.parseInt(column.getValue())>=86400)
  130 + {
  131 + return null;
  132 + }
128 } 133 }
129 } 134 }
130 if(null == iotTerminal.getThings_model_value() || null == iotTerminal.getThings_model_config() || null == iotTerminal.getId()) 135 if(null == iotTerminal.getThings_model_value() || null == iotTerminal.getThings_model_config() || null == iotTerminal.getId())
@@ -5,7 +5,14 @@ import com.zhonglai.luhui.alarm.config.CachAlarmConfig; @@ -5,7 +5,14 @@ import com.zhonglai.luhui.alarm.config.CachAlarmConfig;
5 import com.zhonglai.luhui.alarm.dto.IotAlertLog; 5 import com.zhonglai.luhui.alarm.dto.IotAlertLog;
6 import com.zhonglai.luhui.alarm.dto.UserAlarmNoticeConfig; 6 import com.zhonglai.luhui.alarm.dto.UserAlarmNoticeConfig;
7 import com.zhonglai.luhui.alarm.notice.dto.WeiXinGongZhongHaoNoticeDto; 7 import com.zhonglai.luhui.alarm.notice.dto.WeiXinGongZhongHaoNoticeDto;
  8 +import com.zhonglai.luhui.alarm.notice.dto.WeiXinXiaoChengXuNoticeDto;
  9 +import com.zhonglai.luhui.alarm.notice.dto.wxUniformSend.WeiXinMessage;
8 import com.zhonglai.luhui.alarm.notice.impl.WeiXinGongZhongHaoNoticeImpl; 10 import com.zhonglai.luhui.alarm.notice.impl.WeiXinGongZhongHaoNoticeImpl;
  11 +import com.zhonglai.luhui.alarm.notice.impl.WeiXinXiaoChengXuNoticeImpl;
  12 +import com.zhonglai.luhui.alarm.service.SendAlarmService;
  13 +import org.slf4j.Logger;
  14 +import org.slf4j.LoggerFactory;
  15 +import weixin.popular.api.MessageAPI;
9 16
10 import java.util.List; 17 import java.util.List;
11 18
@@ -29,6 +36,8 @@ public interface NoticeFactory { @@ -29,6 +36,8 @@ public interface NoticeFactory {
29 noticeFactory = new WeiXinGongZhongHaoNoticeImpl(iotAlertLog.getUser_id(),weiXinGongZhongHaoNoticeDto); 36 noticeFactory = new WeiXinGongZhongHaoNoticeImpl(iotAlertLog.getUser_id(),weiXinGongZhongHaoNoticeDto);
30 break; 37 break;
31 case 2: 38 case 2:
  39 + WeiXinXiaoChengXuNoticeDto weiXinXiaoChengXuNoticeDto = JSONObject.parseObject(userAlarmNoticeConfig.getFromConfig(),WeiXinXiaoChengXuNoticeDto.class);
  40 + noticeFactory = new WeiXinXiaoChengXuNoticeImpl(iotAlertLog.getUser_id(),weiXinXiaoChengXuNoticeDto);
32 break; 41 break;
33 case 3: 42 case 3:
34 break; 43 break;
  1 +package com.zhonglai.luhui.alarm.notice.dto;
  2 +
  3 +/**
  4 + * 公众号通知的配置
  5 + */
  6 +public class WeiXinXiaoChengXuNoticeDto {
  7 + private Integer xcxConfigId;
  8 + private String xcxappid;
  9 + private String xcxsecret;
  10 + private String templateId;
  11 + private String redirectUrl;
  12 +
  13 +
  14 + public Integer getXcxConfigId() {
  15 + return xcxConfigId;
  16 + }
  17 +
  18 + public void setXcxConfigId(Integer xcxConfigId) {
  19 + this.xcxConfigId = xcxConfigId;
  20 + }
  21 +
  22 + public String getXcxappid() {
  23 + return xcxappid;
  24 + }
  25 +
  26 + public void setXcxappid(String xcxappid) {
  27 + this.xcxappid = xcxappid;
  28 + }
  29 +
  30 + public String getXcxsecret() {
  31 + return xcxsecret;
  32 + }
  33 +
  34 + public void setXcxsecret(String xcxsecret) {
  35 + this.xcxsecret = xcxsecret;
  36 + }
  37 +
  38 + public String getTemplateId() {
  39 + return templateId;
  40 + }
  41 +
  42 + public void setTemplateId(String templateId) {
  43 + this.templateId = templateId;
  44 + }
  45 +
  46 + public String getRedirectUrl() {
  47 + return redirectUrl;
  48 + }
  49 +
  50 + public void setRedirectUrl(String redirectUrl) {
  51 + this.redirectUrl = redirectUrl;
  52 + }
  53 +}
@@ -28,75 +28,9 @@ public class WeiXinMessage { @@ -28,75 +28,9 @@ public class WeiXinMessage {
28 28
29 private static Map<String,Token> tokenMap = new HashMap<>(); 29 private static Map<String,Token> tokenMap = new HashMap<>();
30 30
31 - /**  
32 - * 发送公众号模版消息  
33 - *  
34 - * @param openid 用户标识  
35 - * @param templateId 模版id  
36 - * @param redirectUrl 模版消息重定向地址  
37 - * @param parameters 模版消息参数  
38 - */  
39 - public static void sendTemplateMsg(String appid, String secret,String openid, String templateId, String redirectUrl, Map<String, String> parameters) {  
40 - TemplateMessage templateMessage = new TemplateMessage();  
41 - templateMessage.setTemplate_id(templateId);  
42 - templateMessage.setTouser(openid);  
43 - templateMessage.setData(parametersToData(parameters));  
44 - templateMessage.setUrl(redirectUrl);  
45 - String defaultToken = getWechatServerToken(appid,secret);  
46 - TemplateMessageResult templateMessageResult = MessageAPI.messageTemplateSend(defaultToken, templateMessage);  
47 - }  
48 -  
49 - /**  
50 - * 下发小程序和公众号统一的服务消息  
51 - *  
52 - * @param openid 用户标识  
53 - * @param templateId 模版id  
54 - * @param redirectUrl 模版消息重定向地址  
55 - * @param parameters 模版消息参数  
56 - */  
57 - public static void sendUniformMessage(String gzhappid,String xcxappid, String secret,String openid, String templateId, String redirectUrl, Map<String, String> parameters) {  
58 - WxUniformSendMessage wxUniformSendMessage = new WxUniformSendMessage();  
59 - wxUniformSendMessage.setTouser(openid);  
60 -// wxUniformSendMessage.setWeapp_template_msg(parametersToData(parameters));  
61 - MpTemplateMsg mpTemplateMsg = new MpTemplateMsg();  
62 - mpTemplateMsg.setAppid(gzhappid);  
63 - mpTemplateMsg.setData(parametersToData(parameters));  
64 - Miniprogram miniprogram = new Miniprogram();  
65 - miniprogram.setAppid(xcxappid);  
66 - miniprogram.setPagepath(redirectUrl);  
67 - mpTemplateMsg.setMiniprogram(miniprogram);  
68 - mpTemplateMsg.setTemplate_id(templateId);  
69 -// mpTemplateMsg.setUrl(redirectUrl);  
70 - wxUniformSendMessage.setMp_template_msg(mpTemplateMsg);  
71 - String defaultToken = getWechatServerToken(xcxappid,secret);  
72 - TemplateMessageResult templateMessageResult = uniform_send(defaultToken, wxUniformSendMessage);  
73 - }  
74 -  
75 - private static LinkedHashMap<String, TemplateMessageItem> parametersToData(Map<String, String> parameters)  
76 - {  
77 - LinkedHashMap<String, TemplateMessageItem> msgMap = new LinkedHashMap<>();  
78 - if (parameters != null && parameters.size() > 0) {  
79 - for (String key : parameters.keySet()) {  
80 - msgMap.put(key, new TemplateMessageItem(parameters.get(key), ""));  
81 - }  
82 - }  
83 - return msgMap;  
84 - }  
85 -  
86 private static Header jsonHeader = new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString()); 31 private static Header jsonHeader = new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
87 32
88 /** 33 /**
89 - * 下发小程序和公众号统一的服务消息  
90 - * @param access_token  
91 - * @return  
92 - */  
93 - public static TemplateMessageResult uniform_send(String access_token, WxUniformSendMessage wxUniformSendMessage) {  
94 - String messageJson = JsonUtil.toJSONString(wxUniformSendMessage);  
95 - HttpUriRequest httpUriRequest = RequestBuilder.post().setHeader(jsonHeader).setUri("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send").addParameter("access_token", access_token).setEntity(new StringEntity(messageJson, Charset.forName("utf-8"))).build();  
96 - return LocalHttpClient.executeJsonResult(httpUriRequest, TemplateMessageResult.class);  
97 - }  
98 -  
99 - /**  
100 * 发送模板消息 34 * 发送模板消息
101 * @return 35 * @return
102 */ 36 */
@@ -105,6 +39,7 @@ public class WeiXinMessage { @@ -105,6 +39,7 @@ public class WeiXinMessage {
105 HttpUriRequest httpUriRequest = RequestBuilder.post().setHeader(jsonHeader).setUri("https://api.weixin.qq.com/cgi-bin/message/template/send").addParameter("access_token", getWechatServerToken(appid,secret)).setEntity(new StringEntity(messageJson, Charset.forName("utf-8"))).build(); 39 HttpUriRequest httpUriRequest = RequestBuilder.post().setHeader(jsonHeader).setUri("https://api.weixin.qq.com/cgi-bin/message/template/send").addParameter("access_token", getWechatServerToken(appid,secret)).setEntity(new StringEntity(messageJson, Charset.forName("utf-8"))).build();
106 return LocalHttpClient.executeJsonResult(httpUriRequest, TemplateMessageResult.class); 40 return LocalHttpClient.executeJsonResult(httpUriRequest, TemplateMessageResult.class);
107 } 41 }
  42 +
108 /** 43 /**
109 * 获取服务号的token 44 * 获取服务号的token
110 * 45 *
@@ -123,4 +58,5 @@ public class WeiXinMessage { @@ -123,4 +58,5 @@ public class WeiXinMessage {
123 tokenMap.put(appid,token); 58 tokenMap.put(appid,token);
124 return token.getAccess_token(); 59 return token.getAccess_token();
125 } 60 }
  61 +
126 } 62 }
  1 +package com.zhonglai.luhui.alarm.notice.impl;
  2 +
  3 +import com.alibaba.fastjson.JSONObject;
  4 +import com.zhonglai.luhui.alarm.config.CachAlarmConfig;
  5 +import com.zhonglai.luhui.alarm.dto.IotAlertLog;
  6 +import com.zhonglai.luhui.alarm.notice.NoticeFactory;
  7 +import com.zhonglai.luhui.alarm.notice.dto.WeiXinXiaoChengXuNoticeDto;
  8 +import com.zhonglai.luhui.alarm.notice.dto.wxUniformSend.WeiXinMessage;
  9 +import weixin.popular.api.MessageAPI;
  10 +import weixin.popular.bean.message.subscribe.WxXcxSubscribeMessage;
  11 +import weixin.popular.bean.message.templatemessage.Miniprogram;
  12 +import weixin.popular.bean.message.templatemessage.TemplateMessageItem;
  13 +
  14 +import java.text.SimpleDateFormat;
  15 +import java.util.Date;
  16 +import java.util.LinkedHashMap;
  17 +import java.util.Set;
  18 +
  19 +public class WeiXinXiaoChengXuNoticeImpl implements NoticeFactory {
  20 + private Set<String> toOpenIds;
  21 +
  22 + private WeiXinXiaoChengXuNoticeDto weiXinXiaoChengXuNoticeDto;
  23 +
  24 + public WeiXinXiaoChengXuNoticeImpl(Integer userId,WeiXinXiaoChengXuNoticeDto weiXinXiaoChengXuNoticeDto)
  25 + {
  26 + this.weiXinXiaoChengXuNoticeDto = weiXinXiaoChengXuNoticeDto;
  27 + toOpenIds = CachAlarmConfig.getUserXcxOpenid(userId,weiXinXiaoChengXuNoticeDto.getXcxConfigId());
  28 + }
  29 +
  30 + @Override
  31 + public boolean send(IotAlertLog iotAlertLog) {
  32 + if(null != toOpenIds && toOpenIds.size() != 0)
  33 + {
  34 + return sendMessage(iotAlertLog,toOpenIds.toArray(new String[toOpenIds.size()]));
  35 + }
  36 + return false;
  37 + }
  38 +
  39 + /**
  40 + * 设备告警消息
  41 + * @param os openid
  42 + */
  43 + public boolean sendMessage(IotAlertLog iotAlertLog, String ... os)
  44 + {
  45 + WxXcxSubscribeMessage wxXcxSubscribeMessage = new WxXcxSubscribeMessage();
  46 +
  47 + wxXcxSubscribeMessage.setTemplate_id(weiXinXiaoChengXuNoticeDto.getTemplateId());
  48 + wxXcxSubscribeMessage.setLang("zh_CN");
  49 + wxXcxSubscribeMessage.setPage(weiXinXiaoChengXuNoticeDto.getRedirectUrl());
  50 + wxXcxSubscribeMessage.setMiniprogram_state("formal");
  51 + LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<String, TemplateMessageItem>();
  52 + data.put("thing2",new TemplateMessageItem(iotAlertLog.getDevice_name()));
  53 + data.put("character_string1",new TemplateMessageItem(iotAlertLog.getDevice_id()));
  54 + data.put("time6",new TemplateMessageItem(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(iotAlertLog.getCreate_time()))));
  55 + data.put("thing8",new TemplateMessageItem(iotAlertLog.getAlert_name()));
  56 + wxXcxSubscribeMessage.setData(data);
  57 +
  58 + for(String o:os)
  59 + {
  60 + wxXcxSubscribeMessage.setTouser(o);
  61 + MessageAPI.messageSubscribeSend(WeiXinMessage.getWechatServerToken(weiXinXiaoChengXuNoticeDto.getXcxappid(),weiXinXiaoChengXuNoticeDto.getXcxsecret()),wxXcxSubscribeMessage);
  62 + }
  63 + return true;
  64 + }
  65 +}
1 package com.zhonglai.luhui.alarm.service; 1 package com.zhonglai.luhui.alarm.service;
2 2
  3 +import com.alibaba.fastjson.JSONObject;
3 import com.zhonglai.luhui.alarm.config.CachAlarmConfig; 4 import com.zhonglai.luhui.alarm.config.CachAlarmConfig;
4 import com.zhonglai.luhui.alarm.dao.DbOperateUtil; 5 import com.zhonglai.luhui.alarm.dao.DbOperateUtil;
5 import com.zhonglai.luhui.alarm.dto.IotAlertLog; 6 import com.zhonglai.luhui.alarm.dto.IotAlertLog;
@@ -31,55 +32,70 @@ public class SendAlarmService { @@ -31,55 +32,70 @@ public class SendAlarmService {
31 32
32 private static void runSend() 33 private static void runSend()
33 { 34 {
34 - List<IotAlertLog> list = DbOperateUtil.getIotAlertLogList(2,100); //未处理的告警  
35 - if(null != list && list.size()!=0)  
36 - {  
37 - List<Long> ids = new ArrayList<>();  
38 - List<Long> notids = new ArrayList<>();  
39 -  
40 - for (IotAlertLog iotAlertLog:list) 35 + logger.info("开始发送告警消息");
  36 + try {
  37 + List<IotAlertLog> list = DbOperateUtil.getIotAlertLogList(2,100); //未处理的告警
  38 + if(null != list && list.size()!=0)
41 { 39 {
42 - if(null == iotAlertLog.getUser_id())  
43 - {  
44 - notids.add(iotAlertLog.getAlert_log_id());  
45 - continue;  
46 - }  
47 - switch (iotAlertLog.getAlert_level()) 40 + logger.info("有告警数据:{}",list.size());
  41 + List<Long> ids = new ArrayList<>();
  42 + List<Long> notids = new ArrayList<>();
  43 +
  44 + for (IotAlertLog iotAlertLog:list)
48 { 45 {
49 - case 1: //提醒通知  
50 - if(NoticeFactory.notice(iotAlertLog))  
51 - {  
52 - ids.add(iotAlertLog.getAlert_log_id());  
53 - }else {  
54 - notids.add(iotAlertLog.getAlert_log_id());  
55 - }  
56 - break;  
57 - case 2: //轻微问题 46 + if(null == iotAlertLog.getUser_id())
  47 + {
  48 + notids.add(iotAlertLog.getAlert_log_id());
  49 + continue;
  50 + }
  51 + if(System.currentTimeMillis()-iotAlertLog.getCreate_time()>86400000l) //24小时之前的告警不需要推送
  52 + {
58 notids.add(iotAlertLog.getAlert_log_id()); 53 notids.add(iotAlertLog.getAlert_log_id());
59 - break;  
60 - case 3: //严重警告 54 + continue;
  55 + }
  56 + switch (iotAlertLog.getAlert_level())
  57 + {
  58 + case 1: //提醒通知
  59 + logger.info("提醒通知:{}", JSONObject.toJSONString(iotAlertLog));
  60 + if(NoticeFactory.notice(iotAlertLog))
  61 + {
  62 + ids.add(iotAlertLog.getAlert_log_id());
  63 + }else {
  64 + notids.add(iotAlertLog.getAlert_log_id());
  65 + }
  66 + break;
  67 + case 2: //轻微问题
  68 + notids.add(iotAlertLog.getAlert_log_id());
  69 + break;
  70 + case 3: //严重警告
61 71
62 - if(NoticeFactory.request(iotAlertLog))  
63 - {  
64 - ids.add(iotAlertLog.getAlert_log_id());  
65 - }else{ 72 + if(NoticeFactory.request(iotAlertLog))
  73 + {
  74 + ids.add(iotAlertLog.getAlert_log_id());
  75 + }else{
  76 + notids.add(iotAlertLog.getAlert_log_id());
  77 + }
  78 + break;
  79 + default:
66 notids.add(iotAlertLog.getAlert_log_id()); 80 notids.add(iotAlertLog.getAlert_log_id());
67 - }  
68 - break;  
69 - default:  
70 - notids.add(iotAlertLog.getAlert_log_id());  
71 - break; 81 + break;
  82 + }
  83 + }
  84 + if(ids.size()!=0)
  85 + {
  86 + DbOperateUtil.updateIotAlertLogStatus(ids,3);
  87 + }
  88 + if(notids.size()!=0)
  89 + {
  90 + DbOperateUtil.updateIotAlertLogStatus(notids,1);
72 } 91 }
73 } 92 }
74 - if(ids.size()!=0)  
75 - {  
76 - DbOperateUtil.updateIotAlertLogStatus(ids,3);  
77 - }  
78 - if(notids.size()!=0)  
79 - {  
80 - DbOperateUtil.updateIotAlertLogStatus(notids,1);  
81 - } 93 + }catch (Exception e)
  94 + {
  95 + logger.error("发送任务异常",e);
82 } 96 }
  97 +
  98 +
83 logger.info("发送任务执行完成"); 99 logger.info("发送任务执行完成");
84 } 100 }
85 101
@@ -29,7 +29,7 @@ public class TriggerAlarmService { @@ -29,7 +29,7 @@ public class TriggerAlarmService {
29 29
30 // 创建Canal连接器 30 // 创建Canal连接器
31 private static CanalConnector connector = CanalConnectors.newSingleConnector( 31 private static CanalConnector connector = CanalConnectors.newSingleConnector(
32 - new InetSocketAddress("8.129.82.37", 11111), 32 + new InetSocketAddress("127.0.0.1", 11111),
33 "example", 33 "example",
34 "", 34 "",
35 "" 35 ""
1 package com.zhonglai.luhui.alarm.util; 1 package com.zhonglai.luhui.alarm.util;
2 2
  3 +import java.util.concurrent.Executors;
3 import java.util.concurrent.ScheduledThreadPoolExecutor; 4 import java.util.concurrent.ScheduledThreadPoolExecutor;
  5 +import java.util.concurrent.ThreadPoolExecutor;
4 import java.util.concurrent.TimeUnit; 6 import java.util.concurrent.TimeUnit;
5 7
6 public class ThreadPoolUtil { 8 public class ThreadPoolUtil {
7 private static int poolSize = 100; // 线程池大小 9 private static int poolSize = 100; // 线程池大小
8 - public static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor (poolSize); 10 + public static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor (poolSize, Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
9 11
10 public static void close() 12 public static void close()
11 { 13 {
1 <?xml version="1.0" encoding="UTF-8"?> 1 <?xml version="1.0" encoding="UTF-8"?>
2 <configuration> 2 <configuration>
3 - <!-- 日志存放路径 -->  
4 - <property name="log.path" value="logs" />  
5 - <!-- 日志输出格式 -->  
6 - <property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />  
7 -  
8 - <!-- 控制台输出 -->  
9 - <appender name="console" class="ch.qos.logback.core.ConsoleAppender">  
10 - <encoder>  
11 - <pattern>${log.pattern}</pattern>  
12 - </encoder>  
13 - </appender>  
14 -  
15 - <!-- 系统日志输出 -->  
16 - <appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">  
17 - <file>${log.path}/sys-info.log</file>  
18 - <!-- 循环政策:基于时间创建日志文件 --> 3 + <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
  4 + <file>logs/output.log</file>
19 <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> 5 <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
20 - <!-- 日志文件名格式 -->  
21 - <fileNamePattern>${log.path}/sys-info.%d{yyyy-MM-dd}.log</fileNamePattern>  
22 - <!-- 日志最大的历史 60天 -->  
23 - <maxHistory>60</maxHistory> 6 + <fileNamePattern>logs/output.%d{yyyy-MM-dd}.log</fileNamePattern>
  7 + <maxHistory>5</maxHistory>
24 </rollingPolicy> 8 </rollingPolicy>
25 <encoder> 9 <encoder>
26 - <pattern>${log.pattern}</pattern> 10 + <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
27 </encoder> 11 </encoder>
28 - <filter class="ch.qos.logback.classic.filter.LevelFilter">  
29 - <!-- 过滤的级别 -->  
30 - <level>INFO</level>  
31 - <!-- 匹配时的操作:接收(记录) -->  
32 - <onMatch>ACCEPT</onMatch>  
33 - <!-- 不匹配时的操作:拒绝(不记录) -->  
34 - <onMismatch>DENY</onMismatch>  
35 - </filter>  
36 </appender> 12 </appender>
37 -  
38 - <appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">  
39 - <file>${log.path}/sys-error.log</file>  
40 - <!-- 循环政策:基于时间创建日志文件 -->  
41 - <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
42 - <!-- 日志文件名格式 -->  
43 - <fileNamePattern>${log.path}/sys-error.%d{yyyy-MM-dd}.log</fileNamePattern>  
44 - <!-- 日志最大的历史 60天 -->  
45 - <maxHistory>60</maxHistory>  
46 - </rollingPolicy>  
47 - <encoder>  
48 - <pattern>${log.pattern}</pattern>  
49 - </encoder>  
50 - <filter class="ch.qos.logback.classic.filter.LevelFilter">  
51 - <!-- 过滤的级别 -->  
52 - <level>ERROR</level>  
53 - <!-- 匹配时的操作:接收(记录) -->  
54 - <onMatch>ACCEPT</onMatch>  
55 - <!-- 不匹配时的操作:拒绝(不记录) -->  
56 - <onMismatch>DENY</onMismatch>  
57 - </filter>  
58 - </appender>  
59 -  
60 13
61 - <!-- 系统模块日志级别控制 -->  
62 - <logger name="com.ruoyi" level="info" />  
63 - <!-- Spring日志级别控制 -->  
64 - <logger name="org.springframework" level="warn" /> 14 + <!-- 控制台输出 -->
  15 + <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
  16 + <encoder>
  17 + <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
  18 + </encoder>
  19 + </appender>
65 20
  21 + <!--系统操作日志-->
66 <root level="info"> 22 <root level="info">
67 - <appender-ref ref="console" /> 23 + <appender-ref ref="FILE" />
  24 + <appender-ref ref="CONSOLE" />
68 </root> 25 </root>
69 26
70 - <!--系统操作日志-->  
71 - <root level="info">  
72 - <appender-ref ref="file_info" />  
73 - <appender-ref ref="file_error" />  
74 - </root>  
75 -  
76 </configuration> 27 </configuration>
  1 +package com.zhonglai.luhui.api.controller.user;
  2 +
  3 +import com.alibaba.fastjson.JSONObject;
  4 +import com.ruoyi.common.annotation.Log;
  5 +import com.ruoyi.common.core.domain.AjaxResult;
  6 +import com.ruoyi.common.enums.BusinessType;
  7 +import com.ruoyi.common.utils.DateUtils;
  8 +import com.ruoyi.common.utils.StringUtils;
  9 +import com.ruoyi.system.domain.user.UserOpenid;
  10 +import com.zhonglai.luhui.action.BaseController;
  11 +import com.zhonglai.luhui.dao.service.PublicService;
  12 +import com.zhonglai.luhui.device.domain.IotAlert;
  13 +import com.zhonglai.luhui.device.domain.IotAlertNoticeChannel;
  14 +import com.zhonglai.luhui.device.domain.IotAlertUserNotice;
  15 +import com.zhonglai.luhui.device.dto.WeiXinGongZhongHaoNoticeDto;
  16 +import com.zhonglai.luhui.device.dto.WeiXinXiaoChengXuNoticeDto;
  17 +import com.zhonglai.luhui.security.utils.SecurityUtils;
  18 +import io.swagger.annotations.Api;
  19 +import io.swagger.annotations.ApiImplicitParam;
  20 +import io.swagger.annotations.ApiImplicitParams;
  21 +import io.swagger.annotations.ApiOperation;
  22 +import org.springframework.beans.factory.annotation.Autowired;
  23 +import org.springframework.transaction.annotation.Transactional;
  24 +import org.springframework.web.bind.annotation.*;
  25 +import weixin.popular.api.SnsAPI;
  26 +import weixin.popular.bean.sns.SnsToken;
  27 +
  28 +import java.util.List;
  29 +import java.util.Map;
  30 +
  31 +
  32 +@Api(tags = "用户告警管理")
  33 +@RestController
  34 +@RequestMapping("/user/alarm")
  35 +public class UserInfoAlarmController extends BaseController {
  36 + @Autowired
  37 + private PublicService publicService;
  38 +
  39 + @ApiOperation("提交公众号通知服务")
  40 + @ApiImplicitParams({
  41 + @ApiImplicitParam(value = "渠道id(管理员提供)",name = "channel_id"),
  42 + @ApiImplicitParam(value = "告警类型(1系统告警,2用户告警)",name = "type"),
  43 + @ApiImplicitParam(value = "授权获取到的code",name = "code"),
  44 + })
  45 + @Log(title = "提交公众号通知服务", businessType = BusinessType.INSERT)
  46 + @Transactional
  47 + @PostMapping(value = "subGzhNoticeService/{channel_id}/{type}")
  48 + public AjaxResult subGzhNoticeService(@PathVariable Integer channel_id,@PathVariable Integer type, String code)
  49 + {
  50 + //检查渠道是否存在
  51 + IotAlertNoticeChannel iotAlertNoticeChannel = publicService.getObject(IotAlertNoticeChannel.class,"id",channel_id+"");
  52 + if(null == iotAlertNoticeChannel)
  53 + {
  54 + return AjaxResult.error("通知渠道不存在");
  55 + }
  56 + if(iotAlertNoticeChannel.getType()!=1)
  57 + {
  58 + return AjaxResult.error("该渠道不是公众号通知渠道");
  59 + }
  60 + WeiXinGongZhongHaoNoticeDto weiXinGongZhongHaoNoticeDto = JSONObject.parseObject(iotAlertNoticeChannel.getConfig(),WeiXinGongZhongHaoNoticeDto.class);
  61 +
  62 + Integer user_id = SecurityUtils.getUserId().intValue();
  63 + SnsToken snsToken = SnsAPI.oauth2AccessToken(weiXinGongZhongHaoNoticeDto.getGzhappid(), weiXinGongZhongHaoNoticeDto.getGzhsecret(),code);
  64 + if(StringUtils.isEmpty(snsToken.getOpenid()))
  65 + {
  66 + return AjaxResult.error("公众号授权失败");
  67 + }
  68 + upOpenid(user_id,snsToken.getOpenid(),weiXinGongZhongHaoNoticeDto.getXcxConfigId());
  69 +
  70 + return upIotAlertUserNotice(user_id,channel_id,type);
  71 + }
  72 +
  73 + @ApiOperation("提交小程序通知服务")
  74 + @ApiImplicitParams({
  75 + @ApiImplicitParam(value = "渠道id(管理员提供)",name = "channel_id"),
  76 + @ApiImplicitParam(value = "告警类型(1系统告警,2用户告警)",name = "type"),
  77 + @ApiImplicitParam(value = "小程序用户openid",name = "openid"),
  78 + })
  79 + @Log(title = "提交公众号通知服务", businessType = BusinessType.INSERT)
  80 + @Transactional
  81 + @PostMapping(value = "subXcxNoticeService/{channel_id}/{type}")
  82 + public AjaxResult subXcxNoticeService(@PathVariable Integer channel_id,@PathVariable Integer type, String openid)
  83 + {
  84 + //检查渠道是否存在
  85 + IotAlertNoticeChannel iotAlertNoticeChannel = publicService.getObject(IotAlertNoticeChannel.class,"id",channel_id+"");
  86 + if(null == iotAlertNoticeChannel)
  87 + {
  88 + return AjaxResult.error("通知渠道不存在");
  89 + }
  90 + if(iotAlertNoticeChannel.getType()!=2)
  91 + {
  92 + return AjaxResult.error("该渠道不是小程序通知渠道");
  93 + }
  94 + WeiXinXiaoChengXuNoticeDto weiXinXiaoChengXuNoticeDto = JSONObject.parseObject(iotAlertNoticeChannel.getConfig(),WeiXinXiaoChengXuNoticeDto.class);
  95 +
  96 + Integer user_id = SecurityUtils.getUserId().intValue();
  97 +
  98 + upOpenid(user_id,openid,weiXinXiaoChengXuNoticeDto.getXcxConfigId());
  99 +
  100 + return upIotAlertUserNotice(user_id,channel_id,type);
  101 + }
  102 +
  103 + @ApiOperation("获取告警通知渠道配置")
  104 + @ApiImplicitParam(value = "产品id",name = "product_id")
  105 + @GetMapping(value = "getIotAlertUserNoticeList/{product_id}")
  106 + public AjaxResult getIotAlertUserNoticeList(@PathVariable Integer product_id)
  107 + {
  108 + Integer user_id = SecurityUtils.getUserId().intValue();
  109 + IotAlertUserNotice iotAlertUserNotice = new IotAlertUserNotice();
  110 + iotAlertUserNotice.setUser_id(user_id);
  111 + List<Map<String,Object>> list = publicService.getObjectList(iotAlertUserNotice,"*",null,null,0,0);
  112 + if (null != list && list.size() !=0)
  113 + {
  114 + for (Map<String,Object> map:list)
  115 + {
  116 + switch ((int)map.get("type")) //告警类型(1系统告警,2用户告警)
  117 + {
  118 + case 1:
  119 + if ((map.get("alert_ids")).equals("*"))
  120 + {
  121 + map.put("iotAlertList",publicService.getObjectListBySQL("select * from `iot_alert` where product_id="+product_id));
  122 + }else {
  123 + map.put("iotAlertList",publicService.getObjectListBySQL("select * from `iot_alert` where product_id="+product_id+"alert_id in("+map.get("alert_ids")+")"));
  124 + }
  125 + break;
  126 + case 2:
  127 + if ((map.get("alert_ids")).equals("*"))
  128 + {
  129 + map.put("iotAlertList",publicService.getObjectListBySQL("select * from `iot_alert_user` where product_id="+product_id));
  130 + }else {
  131 + map.put("iotAlertList",publicService.getObjectListBySQL("select * from `iot_alert_user` where product_id="+product_id+"alert_id in("+map.get("alert_ids")+")"));
  132 + }
  133 + break;
  134 + }
  135 +
  136 + String channels = (String) map.get("channels");
  137 + map.put("channelList",publicService.getObjectListBySQL("select `id`,`type`,`name`,`state` from `iot_alert_notice_channel` where id in("+channels+")"));
  138 + }
  139 + }
  140 +
  141 + return AjaxResult.success(list);
  142 + }
  143 +
  144 + @ApiOperation("获取告警通知渠道")
  145 + @GetMapping(value = "getIotAlertNoticeChannelList")
  146 + public AjaxResult getIotAlertNoticeChannelList()
  147 + {
  148 + IotAlertNoticeChannel iotAlertNoticeChannel = new IotAlertNoticeChannel();
  149 + iotAlertNoticeChannel.setState(1);
  150 + List<Map<String,Object>> list = publicService.getObjectList(iotAlertNoticeChannel,"`id`,`name`",null,null,0,0);
  151 + return AjaxResult.success(list);
  152 + }
  153 +
  154 + @ApiOperation("获取指定产品的系统告警")
  155 + @ApiImplicitParam(value = "产品id",name = "product_id")
  156 + @GetMapping(value = "getIotAlertByProduct/{product_id}")
  157 + public AjaxResult getIotAlertByProduct(@PathVariable Long product_id)
  158 + {
  159 + IotAlert iotAlert = new IotAlert();
  160 + iotAlert.setProductId(product_id);
  161 + List<Map<String,Object>> list = publicService.getObjectList(iotAlert,"*",null,null,0,0);
  162 + return AjaxResult.success(list);
  163 + }
  164 +
  165 + @ApiOperation("更新告警通知渠道配置")
  166 + @ApiImplicitParams({
  167 + @ApiImplicitParam(value = "通知渠道(iot_alert_notice_channel表的id集合,多个英文逗号分割)",name = "channels"),
  168 + @ApiImplicitParam(value = "告警id集合(关联iot_alert和iot_alert_user表的id,多个英文逗号分割,*表示所有)",name = "alert_ids"),
  169 + @ApiImplicitParam(value = "主键id",name = "id"),
  170 + })
  171 + @Log(title = "更新告警通知渠道配置", businessType = BusinessType.UPDATE)
  172 + @Transactional
  173 + @PostMapping(value = "upIotAlertUserNotice/{id}")
  174 + public AjaxResult upIotAlertUserNotice(@PathVariable Integer id,String channels, String alert_ids)
  175 + {
  176 + IotAlertUserNotice iotAlertUserNotice = new IotAlertUserNotice();
  177 + iotAlertUserNotice.setId(id);
  178 + iotAlertUserNotice.setChannels(channels);
  179 + iotAlertUserNotice.setAlert_ids(alert_ids);
  180 + int i = publicService.updateObject(iotAlertUserNotice,"id");
  181 + return AjaxResult.success(i);
  182 + }
  183 +
  184 + @ApiOperation("更新指定产品的告警通知渠道配置")
  185 + @ApiImplicitParams({
  186 + @ApiImplicitParam(value = "通知渠道(iot_alert_notice_channel表的id集合,多个英文逗号分割)",name = "channels"),
  187 + @ApiImplicitParam(value = "告警id集合(关联iot_alert和iot_alert_user表的id,多个英文逗号分割,*表示所有)",name = "alert_ids"),
  188 + @ApiImplicitParam(value = "主键id",name = "id"),
  189 + @ApiImplicitParam(value = "产品id",name = "product_id"),
  190 + })
  191 + @Log(title = "更新指定产品的告警通知渠道配置", businessType = BusinessType.UPDATE)
  192 + @Transactional
  193 + @PostMapping(value = "upIotAlertUserNoticeByProduct/{id}/{product_id}")
  194 + public AjaxResult upIotAlertUserNoticeByProduct(@PathVariable Integer id,@PathVariable Long product_id,String channels, String alert_ids)
  195 + {
  196 + IotAlertUserNotice iotAlertUserNotice = publicService.getObject(IotAlertUserNotice.class,"id",id+"");
  197 +
  198 + IotAlertUserNotice uPiotAlertUserNotice = new IotAlertUserNotice();
  199 + uPiotAlertUserNotice.setId(id);
  200 + if(StringUtils.isNotEmpty(channels))
  201 + {
  202 + uPiotAlertUserNotice.setChannels(channels);
  203 + }
  204 +
  205 + if(StringUtils.isNotEmpty(alert_ids))
  206 + {
  207 + if("*".equals(iotAlertUserNotice.getAlert_ids()))
  208 + {
  209 + uPiotAlertUserNotice.setAlert_ids(alert_ids);
  210 + }else {
  211 + 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()+")");
  212 + if(null != aidsList && aidsList.size() != 0)
  213 + {
  214 + Object aids = aidsList.get(0).get("aids");
  215 + if(null != aids && !aids.equals(""))
  216 + {
  217 + uPiotAlertUserNotice.setAlert_ids(aids+","+alert_ids);
  218 + }else {
  219 + uPiotAlertUserNotice.setAlert_ids(alert_ids);
  220 + }
  221 +
  222 + }
  223 + }
  224 + }
  225 +
  226 + int upi = 0;
  227 + if(StringUtils.isNotEmpty(uPiotAlertUserNotice.getChannels()) || StringUtils.isNotEmpty(uPiotAlertUserNotice.getAlert_ids()))
  228 + {
  229 + upi = publicService.updateObject(uPiotAlertUserNotice,"id");
  230 + }
  231 + return AjaxResult.success(upi);
  232 + }
  233 +
  234 + private void upOpenid(Integer user_id,String openid,Integer xcxConfigid)
  235 + {
  236 + //更新用户openid表
  237 + UserOpenid userOpenid = new UserOpenid();
  238 + userOpenid.setUser_id(user_id);
  239 + userOpenid.setOpenid(openid);
  240 + userOpenid.setXcx_config_id(xcxConfigid);
  241 + Long ct = publicService.getObjectListTotle(userOpenid,null);
  242 + if(0 == ct)
  243 + {
  244 + publicService.insert(userOpenid);
  245 + }
  246 + }
  247 +
  248 + private AjaxResult upIotAlertUserNotice(Integer user_id,Integer channel_id,Integer type)
  249 + {
  250 + //更新用户通知
  251 + IotAlertUserNotice iotAlertUserNotice= publicService.getObject(IotAlertUserNotice.class,"user_id,type",user_id+","+type);
  252 + if(null != iotAlertUserNotice)
  253 + {
  254 + if((","+iotAlertUserNotice.getChannels()+",").indexOf(","+channel_id+",")>=0)
  255 + {
  256 + return AjaxResult.error("您已经开通过通知服务了,请到通知服务编辑页面进行编辑");
  257 + }else {
  258 + IotAlertUserNotice upIotAlertUserNotice = new IotAlertUserNotice();
  259 + upIotAlertUserNotice.setId(iotAlertUserNotice.getId());
  260 + upIotAlertUserNotice.setChannels(iotAlertUserNotice.getChannels()+","+channel_id);
  261 + upIotAlertUserNotice.setUpdate_time(DateUtils.getTime());
  262 + return AjaxResult.success(publicService.updateObject(upIotAlertUserNotice,"id"));
  263 + }
  264 + }else {
  265 + IotAlertUserNotice sysIotAlertUserNotice = new IotAlertUserNotice();
  266 + sysIotAlertUserNotice.setChannels(channel_id+"");
  267 + sysIotAlertUserNotice.setType(type);
  268 + sysIotAlertUserNotice.setUser_id(user_id);
  269 +
  270 + return AjaxResult.success(publicService.insert(sysIotAlertUserNotice));
  271 + }
  272 +
  273 + }
  274 + @ApiOperation("生成告警授权连接")
  275 + @RequestMapping(value = "getAlarmOauth2URL/{channel_id}", method = RequestMethod.GET)
  276 + public AjaxResult getAlarmOauth2URL(@PathVariable Integer channel_id, @RequestParam(value="redirect_uri") String redirect_uri,String state)
  277 + {
  278 + //检查渠道是否存在
  279 + IotAlertNoticeChannel iotAlertNoticeChannel = publicService.getObject(IotAlertNoticeChannel.class,"id",channel_id+"");
  280 + if(null == iotAlertNoticeChannel)
  281 + {
  282 + return AjaxResult.error("通知渠道不存在");
  283 + }
  284 + if(iotAlertNoticeChannel.getType()!=1)
  285 + {
  286 + return AjaxResult.error("该渠道不是公众号通知渠道");
  287 + }
  288 + WeiXinGongZhongHaoNoticeDto weiXinGongZhongHaoNoticeDto = JSONObject.parseObject(iotAlertNoticeChannel.getConfig(),WeiXinGongZhongHaoNoticeDto.class);
  289 + String authorizeUrl = SnsAPI.connectOauth2Authorize(weiXinGongZhongHaoNoticeDto.getGzhappid(), redirect_uri, true, state);
  290 + return AjaxResult.success("",authorizeUrl);
  291 + }
  292 +}
1 -package com.zhonglai.luhui.api.controller.user;  
2 -  
3 -import com.alibaba.fastjson.JSONObject;  
4 -import com.ruoyi.common.annotation.Log;  
5 -import com.ruoyi.common.core.domain.AjaxResult;  
6 -import com.ruoyi.common.enums.BusinessType;  
7 -import com.ruoyi.common.utils.StringUtils;  
8 -import com.ruoyi.system.domain.user.UserOpenid;  
9 -import com.zhonglai.luhui.action.BaseController;  
10 -import com.zhonglai.luhui.dao.service.PublicService;  
11 -import com.zhonglai.luhui.device.domain.IotAlertNoticeChannel;  
12 -import com.zhonglai.luhui.device.domain.IotAlertUserNotice;  
13 -import com.zhonglai.luhui.device.dto.WeiXinGongZhongHaoNoticeDto;  
14 -import com.zhonglai.luhui.security.utils.SecurityUtils;  
15 -import io.swagger.annotations.Api;  
16 -import io.swagger.annotations.ApiImplicitParam;  
17 -import io.swagger.annotations.ApiImplicitParams;  
18 -import io.swagger.annotations.ApiOperation;  
19 -import org.springframework.beans.factory.annotation.Autowired;  
20 -import org.springframework.transaction.annotation.Transactional;  
21 -import org.springframework.web.bind.annotation.*;  
22 -import weixin.popular.api.SnsAPI;  
23 -import weixin.popular.bean.sns.SnsToken;  
24 -  
25 -import javax.servlet.http.HttpServletRequest;  
26 -import java.io.UnsupportedEncodingException;  
27 -import java.net.URLEncoder;  
28 -  
29 -  
30 -@Api(tags = "用户管理")  
31 -@RestController  
32 -@RequestMapping("/user/userInfo")  
33 -public class UserInfoController extends BaseController {  
34 - @Autowired  
35 - private PublicService publicService;  
36 -  
37 - @ApiOperation("提交小程序或者微信公众号通知服务")  
38 - @ApiImplicitParams({  
39 - @ApiImplicitParam(value = "渠道id(管理员提供)",name = "channel_id"),  
40 - @ApiImplicitParam(value = "授权获取到的code",name = "code"),  
41 - })  
42 - @Log(title = "提交小程序或者微信公众号通知服务", businessType = BusinessType.INSERT)  
43 - @Transactional  
44 - @PostMapping(value = "subXcxNoticeService/{channel_id}")  
45 - public AjaxResult subXcxNoticeService(@PathVariable Integer channel_id, String code)  
46 - {  
47 - //检查渠道是否存在  
48 - IotAlertNoticeChannel iotAlertNoticeChannel = publicService.getObject(IotAlertNoticeChannel.class,"id",channel_id+"");  
49 - if(null == iotAlertNoticeChannel)  
50 - {  
51 - return AjaxResult.error("通知渠道不存在");  
52 - }  
53 - if(iotAlertNoticeChannel.getType()!=1)  
54 - {  
55 - return AjaxResult.error("该渠道不是公众号通知渠道");  
56 - }  
57 - WeiXinGongZhongHaoNoticeDto weiXinGongZhongHaoNoticeDto = JSONObject.parseObject(iotAlertNoticeChannel.getConfig(),WeiXinGongZhongHaoNoticeDto.class);  
58 -  
59 - Integer user_id = SecurityUtils.getUserId().intValue();  
60 - SnsToken snsToken = SnsAPI.oauth2AccessToken(weiXinGongZhongHaoNoticeDto.getGzhappid(), weiXinGongZhongHaoNoticeDto.getGzhsecret(),code);  
61 - if(StringUtils.isEmpty(snsToken.getOpenid()))  
62 - {  
63 - return AjaxResult.error("公众号授权失败");  
64 - }  
65 -  
66 - //更新用户openid表  
67 - UserOpenid userOpenid = new UserOpenid();  
68 - userOpenid.setUser_id(user_id);  
69 - userOpenid.setOpenid(snsToken.getOpenid());  
70 - userOpenid.setXcx_config_id(weiXinGongZhongHaoNoticeDto.getXcxConfigId());  
71 - Long ct = publicService.getObjectListTotle(userOpenid,null);  
72 - if(0 == ct)  
73 - {  
74 - publicService.insert(userOpenid);  
75 - }  
76 - //更新用户通知  
77 - IotAlertUserNotice iotAlertUserNotice = new IotAlertUserNotice();  
78 - iotAlertUserNotice.setUser_id(user_id);  
79 - ct = publicService.getObjectListTotle(iotAlertUserNotice,null);  
80 - if(0 < ct)  
81 - {  
82 - return AjaxResult.error("您已经开通过通知服务了,请到通知服务编辑页面进行编辑");  
83 - }  
84 -  
85 - IotAlertUserNotice sysIotAlertUserNotice = new IotAlertUserNotice();  
86 - sysIotAlertUserNotice.setChannels(channel_id+"");  
87 - sysIotAlertUserNotice.setType(1);  
88 - sysIotAlertUserNotice.setUser_id(user_id);  
89 - publicService.insert(sysIotAlertUserNotice);  
90 -  
91 - IotAlertUserNotice userIotAlertUserNotice = new IotAlertUserNotice();  
92 - userIotAlertUserNotice.setChannels(channel_id+"");  
93 - userIotAlertUserNotice.setType(2);  
94 - userIotAlertUserNotice.setUser_id(user_id);  
95 - publicService.insert(userIotAlertUserNotice);  
96 - return AjaxResult.success();  
97 - }  
98 -  
99 - @ApiOperation("生成告警授权连接")  
100 - @RequestMapping(value = "getAlarmOauth2URL/{channel_id}", method = RequestMethod.GET)  
101 - public AjaxResult getAlarmOauth2URL(@PathVariable Integer channel_id, @RequestParam(value="redirect_uri") String redirect_uri,String state)  
102 - {  
103 - //检查渠道是否存在  
104 - IotAlertNoticeChannel iotAlertNoticeChannel = publicService.getObject(IotAlertNoticeChannel.class,"id",channel_id+"");  
105 - if(null == iotAlertNoticeChannel)  
106 - {  
107 - return AjaxResult.error("通知渠道不存在");  
108 - }  
109 - if(iotAlertNoticeChannel.getType()!=1)  
110 - {  
111 - return AjaxResult.error("该渠道不是公众号通知渠道");  
112 - }  
113 - WeiXinGongZhongHaoNoticeDto weiXinGongZhongHaoNoticeDto = JSONObject.parseObject(iotAlertNoticeChannel.getConfig(),WeiXinGongZhongHaoNoticeDto.class);  
114 - String authorizeUrl = SnsAPI.connectOauth2Authorize(weiXinGongZhongHaoNoticeDto.getGzhappid(), redirect_uri, true, state);  
115 - return AjaxResult.success("",authorizeUrl);  
116 - }  
117 -}  
@@ -60,6 +60,7 @@ public class MqttSubscribeService { @@ -60,6 +60,7 @@ public class MqttSubscribeService {
60 if (StringUtils.isEmpty(productids)) 60 if (StringUtils.isEmpty(productids))
61 { 61 {
62 List<ProtocolSubTopics> list = persistenceDBService.getProtocolSubTopicsFromIp(SysParameter.service_ip); 62 List<ProtocolSubTopics> list = persistenceDBService.getProtocolSubTopicsFromIp(SysParameter.service_ip);
  63 + log.info("根据ip查询的订阅消息【{}】",list);
63 SubTopicsAndproductDto subTopicsAndproductDto = getSubTopicsFromProtocolSubTopics(list); 64 SubTopicsAndproductDto subTopicsAndproductDto = getSubTopicsFromProtocolSubTopics(list);
64 return subscribeForProductids(subTopicsAndproductDto); 65 return subscribeForProductids(subTopicsAndproductDto);
65 } 66 }
@@ -182,6 +183,7 @@ public class MqttSubscribeService { @@ -182,6 +183,7 @@ public class MqttSubscribeService {
182 { 183 {
183 Set<String> tlist = new HashSet<>(); 184 Set<String> tlist = new HashSet<>();
184 Set<Integer> plist = new HashSet<>(); 185 Set<Integer> plist = new HashSet<>();
  186 + Set<String> untlist = new HashSet<>();
185 for (ProtocolSubTopics protocolSubTopics:list) 187 for (ProtocolSubTopics protocolSubTopics:list)
186 { 188 {
187 if (StringUtils.isNotEmpty(protocolSubTopics.getSub_topics())) 189 if (StringUtils.isNotEmpty(protocolSubTopics.getSub_topics()))
@@ -196,6 +198,8 @@ public class MqttSubscribeService { @@ -196,6 +198,8 @@ public class MqttSubscribeService {
196 tlist.add(topic); 198 tlist.add(topic);
197 topics.add(topic); 199 topics.add(topic);
198 subTopicsAndproductDto.setUp(true); 200 subTopicsAndproductDto.setUp(true);
  201 + }else {
  202 + untlist.add(topic);
199 } 203 }
200 204
201 } 205 }
@@ -203,6 +207,7 @@ public class MqttSubscribeService { @@ -203,6 +207,7 @@ public class MqttSubscribeService {
203 } 207 }
204 subTopicsAndproductDto.setPlist(plist); 208 subTopicsAndproductDto.setPlist(plist);
205 subTopicsAndproductDto.setTlist(tlist); 209 subTopicsAndproductDto.setTlist(tlist);
  210 + subTopicsAndproductDto.setUntlist(untlist);
206 } 211 }
207 212
208 return subTopicsAndproductDto; 213 return subTopicsAndproductDto;
@@ -224,4 +229,9 @@ public class MqttSubscribeService { @@ -224,4 +229,9 @@ public class MqttSubscribeService {
224 String topic = topicStringBuffer.toString(); 229 String topic = topicStringBuffer.toString();
225 return topic; 230 return topic;
226 } 231 }
  232 +
  233 + public void connectionLost()
  234 + {
  235 + topics.clear();
  236 + }
227 } 237 }
@@ -240,6 +240,7 @@ public class DefaultDbService { @@ -240,6 +240,7 @@ public class DefaultDbService {
240 public List<ProtocolSubTopics> getProtocolSubTopicsFromIp(String ip) 240 public List<ProtocolSubTopics> getProtocolSubTopicsFromIp(String ip)
241 { 241 {
242 StringBuffer stringBuffer = new StringBuffer("SELECT b.id productid,a.`type`,a.sub_topics,b.`role_id`,b.`mqtt_username` FROM `iot_protocol_class` a LEFT JOIN `iot_product` b ON b.`analysis_clas`=a.`id` WHERE a.`type`=1 AND b.`subscribe_service_ip` = ?"); 242 StringBuffer stringBuffer = new StringBuffer("SELECT b.id productid,a.`type`,a.sub_topics,b.`role_id`,b.`mqtt_username` FROM `iot_protocol_class` a LEFT JOIN `iot_product` b ON b.`analysis_clas`=a.`id` WHERE a.`type`=1 AND b.`subscribe_service_ip` = ?");
  243 + log.info("根据ip查询订阅信息的查询语句{}",stringBuffer);
243 return baseDao.findBysql(stringBuffer.toString(), ProtocolSubTopics.class,ip); 244 return baseDao.findBysql(stringBuffer.toString(), ProtocolSubTopics.class,ip);
244 } 245 }
245 /** 246 /**
@@ -39,6 +39,7 @@ public class MqttCallback extends BaseCallback implements MqttCallbackExtended { @@ -39,6 +39,7 @@ public class MqttCallback extends BaseCallback implements MqttCallbackExtended {
39 public void connectionLost(Throwable throwable) { 39 public void connectionLost(Throwable throwable) {
40 //连接丢失 40 //连接丢失
41 log.error("连接丢失",throwable); 41 log.error("连接丢失",throwable);
  42 + mqttSubscribeService.connectionLost();
42 } 43 }
43 44
44 @Override 45 @Override