作者 钟来

修改mqtt订阅bug

添加用户告警配置
添加微信小程序通知功能
正在显示 22 个修改的文件 包含 555 行增加248 行删除
... ... @@ -20,11 +20,21 @@ public class IotAlertNoticeChannel {
private String create_time; // varchar(50) NOT NULL COMMENT '创建时间',
@ApiModelProperty("修改时间")
private String update_time; // varchar(50) NOT NULL COMMENT '修改时间',
@ApiModelProperty("状态(1使用,0关闭)")
private Integer state; // varchar(50) NOT NULL COMMENT '状态(1使用,0关闭)',
public String getCreate_time() {
return create_time;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public void setCreate_time(String create_time) {
this.create_time = create_time;
}
... ...
package com.zhonglai.luhui.device.dto;
/**
* 公众号通知的配置
*/
public class WeiXinXiaoChengXuNoticeDto {
private Integer xcxConfigId;
private String xcxappid;
private String xcxsecret;
private String templateId;
private String redirectUrl;
public Integer getXcxConfigId() {
return xcxConfigId;
}
public void setXcxConfigId(Integer xcxConfigId) {
this.xcxConfigId = xcxConfigId;
}
public String getXcxappid() {
return xcxappid;
}
public void setXcxappid(String xcxappid) {
this.xcxappid = xcxappid;
}
public String getXcxsecret() {
return xcxsecret;
}
public void setXcxsecret(String xcxsecret) {
this.xcxsecret = xcxsecret;
}
public String getTemplateId() {
return templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
public String getRedirectUrl() {
return redirectUrl;
}
public void setRedirectUrl(String redirectUrl) {
this.redirectUrl = redirectUrl;
}
}
... ...
... ... @@ -18,6 +18,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<select id="selectUserTerminalGroupList" parameterType="UserTerminalGroup" resultMap="UserTerminalGroupResult">
<include refid="selectUserTerminalGroupVo"/>
<where>
<if test="user_info_id !=null">
and user_info_id = #{user_info_id}
</if>
</where>
</select>
... ...
... ... @@ -14,10 +14,10 @@ public class LhAlarmMain {
CachAlarmConfig.loadConfig();
//启动触发告警服务
// TriggerAlarmService.start();
TriggerAlarmService.start();
//启动定时任务告警
// TimerAlarmService.start();
TimerAlarmService.start();
//启动告警定时发送
SendAlarmService.start();
... ...
... ... @@ -102,13 +102,20 @@ public abstract class UpAlarmFactory<T> {
JSONObject newObject = newjson.getJSONObject(key);
String type = newObject.getString("type");
nv = GenericComparator.convertToType(newObject.getString("saveView"),type);
if(oldjson.containsKey("key"))
{
ov = GenericComparator.convertToType(oldjson.getJSONObject(key).getString("saveView"),type);
}else {
ov = null;
}
}catch (JSONException e ) //如果不是json,就按照字符串来对比
{
nv = newjson.get(key);
ov = oldjson.get(key);
}catch (NullPointerException exception)
{
logger.info("属性解析异常的参数newjson:{}",newjson);
logger.info("属性解析异常的参数oldjson:{}",oldjson);
logger.error("告警属性解析时异常",exception);
continue;
}
... ... @@ -221,4 +228,5 @@ public abstract class UpAlarmFactory<T> {
public List<IotAlertLog> getList() {
return list;
}
}
... ...
... ... @@ -423,6 +423,8 @@ public class CachAlarmConfig {
public static List<UserAlarmNoticeConfig> getUserAlarmNoticeConfig(Integer user_id,Integer getAlert_config_type,Long alert_id)
{
logger.info("获取用户告警通知配置:user_id: {},getAlert_config_type {},alert_id {}",user_id,getAlert_config_type,alert_id);
logger.info("用户告警通知配置:{}",JSONObject.toJSONString(user_alarm_config));
IotAlertUserNotice iotAlertUserNotice = user_alarm_config.get(user_id+"|"+getAlert_config_type);
if(null != iotAlertUserNotice && ("*".equals(iotAlertUserNotice.getAlert_ids()) || (","+iotAlertUserNotice.getAlert_ids()+",").indexOf(","+alert_id+",")>=0)) //*或者包含
{
... ... @@ -433,6 +435,7 @@ public class CachAlarmConfig {
private static List<UserAlarmNoticeConfig> channelIdsToUserAlarmNoticeConfig(String iot_alert_notice_channel_ids)
{
logger.info("开始渠道id转告警配置:{}",iot_alert_notice_channel_ids);
if(StringUtils.isNotEmpty(iot_alert_notice_channel_ids))
{
List<UserAlarmNoticeConfig> list = new ArrayList<>();
... ...
... ... @@ -52,9 +52,9 @@ public class DbOperateUtil {
public static List<IotAlertLog> getIotAlertLogList(Integer status,Integer limit)
{
List<IotAlertLog> list = baseDao.findBysql("select * from iot_alert_log where alert_log_id=11408",IotAlertLog.class);
// List<IotAlertLog> list = baseDao.findBysql("select * from iot_alert_log where alert_log_id=11408",IotAlertLog.class);
// List<IotAlertLog> list = baseDao.findBysql("select * from iot_alert_log where `status`=? limit ?",IotAlertLog.class,status,limit);
List<IotAlertLog> list = baseDao.findBysql("select * from iot_alert_log where `status`=? limit ?",IotAlertLog.class,status,limit);
return list;
}
... ...
... ... @@ -82,6 +82,12 @@ public class IotDevice {
case "status":
iotDevice.setStatus ( null!=column.getValue()&&!"".equals(column.getValue())?Integer.parseInt(column.getValue()):null);
break;
case "data_update_time"://一天前更新的设备不触发告警
if(new Long(System.currentTimeMillis()/1000).intValue()-Integer.parseInt(column.getValue())>=86400)
{
return null;
}
break;
}
}
if(null == iotDevice.getSummary() || null == iotDevice.getThings_model_value() || null == iotDevice.getClient_id() )
... ...
... ... @@ -125,6 +125,11 @@ public class IotTerminal {
case "online":
iotTerminal.setOnline ( null!=column.getValue()&&!"".equals(column.getValue())?Integer.parseInt(column.getValue()):null);
break;
case "data_update_time": //一天前更新的设备不触发告警
if(new Long(System.currentTimeMillis()/1000).intValue()-Integer.parseInt(column.getValue())>=86400)
{
return null;
}
}
}
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;
import com.zhonglai.luhui.alarm.dto.IotAlertLog;
import com.zhonglai.luhui.alarm.dto.UserAlarmNoticeConfig;
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.WeiXinGongZhongHaoNoticeImpl;
import com.zhonglai.luhui.alarm.notice.impl.WeiXinXiaoChengXuNoticeImpl;
import com.zhonglai.luhui.alarm.service.SendAlarmService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weixin.popular.api.MessageAPI;
import java.util.List;
... ... @@ -29,6 +36,8 @@ public interface NoticeFactory {
noticeFactory = new WeiXinGongZhongHaoNoticeImpl(iotAlertLog.getUser_id(),weiXinGongZhongHaoNoticeDto);
break;
case 2:
WeiXinXiaoChengXuNoticeDto weiXinXiaoChengXuNoticeDto = JSONObject.parseObject(userAlarmNoticeConfig.getFromConfig(),WeiXinXiaoChengXuNoticeDto.class);
noticeFactory = new WeiXinXiaoChengXuNoticeImpl(iotAlertLog.getUser_id(),weiXinXiaoChengXuNoticeDto);
break;
case 3:
break;
... ...
package com.zhonglai.luhui.alarm.notice.dto;
/**
* 公众号通知的配置
*/
public class WeiXinXiaoChengXuNoticeDto {
private Integer xcxConfigId;
private String xcxappid;
private String xcxsecret;
private String templateId;
private String redirectUrl;
public Integer getXcxConfigId() {
return xcxConfigId;
}
public void setXcxConfigId(Integer xcxConfigId) {
this.xcxConfigId = xcxConfigId;
}
public String getXcxappid() {
return xcxappid;
}
public void setXcxappid(String xcxappid) {
this.xcxappid = xcxappid;
}
public String getXcxsecret() {
return xcxsecret;
}
public void setXcxsecret(String xcxsecret) {
this.xcxsecret = xcxsecret;
}
public String getTemplateId() {
return templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
public String getRedirectUrl() {
return redirectUrl;
}
public void setRedirectUrl(String redirectUrl) {
this.redirectUrl = redirectUrl;
}
}
... ...
... ... @@ -28,75 +28,9 @@ public class WeiXinMessage {
private static Map<String,Token> tokenMap = new HashMap<>();
/**
* 发送公众号模版消息
*
* @param openid 用户标识
* @param templateId 模版id
* @param redirectUrl 模版消息重定向地址
* @param parameters 模版消息参数
*/
public static void sendTemplateMsg(String appid, String secret,String openid, String templateId, String redirectUrl, Map<String, String> parameters) {
TemplateMessage templateMessage = new TemplateMessage();
templateMessage.setTemplate_id(templateId);
templateMessage.setTouser(openid);
templateMessage.setData(parametersToData(parameters));
templateMessage.setUrl(redirectUrl);
String defaultToken = getWechatServerToken(appid,secret);
TemplateMessageResult templateMessageResult = MessageAPI.messageTemplateSend(defaultToken, templateMessage);
}
/**
* 下发小程序和公众号统一的服务消息
*
* @param openid 用户标识
* @param templateId 模版id
* @param redirectUrl 模版消息重定向地址
* @param parameters 模版消息参数
*/
public static void sendUniformMessage(String gzhappid,String xcxappid, String secret,String openid, String templateId, String redirectUrl, Map<String, String> parameters) {
WxUniformSendMessage wxUniformSendMessage = new WxUniformSendMessage();
wxUniformSendMessage.setTouser(openid);
// wxUniformSendMessage.setWeapp_template_msg(parametersToData(parameters));
MpTemplateMsg mpTemplateMsg = new MpTemplateMsg();
mpTemplateMsg.setAppid(gzhappid);
mpTemplateMsg.setData(parametersToData(parameters));
Miniprogram miniprogram = new Miniprogram();
miniprogram.setAppid(xcxappid);
miniprogram.setPagepath(redirectUrl);
mpTemplateMsg.setMiniprogram(miniprogram);
mpTemplateMsg.setTemplate_id(templateId);
// mpTemplateMsg.setUrl(redirectUrl);
wxUniformSendMessage.setMp_template_msg(mpTemplateMsg);
String defaultToken = getWechatServerToken(xcxappid,secret);
TemplateMessageResult templateMessageResult = uniform_send(defaultToken, wxUniformSendMessage);
}
private static LinkedHashMap<String, TemplateMessageItem> parametersToData(Map<String, String> parameters)
{
LinkedHashMap<String, TemplateMessageItem> msgMap = new LinkedHashMap<>();
if (parameters != null && parameters.size() > 0) {
for (String key : parameters.keySet()) {
msgMap.put(key, new TemplateMessageItem(parameters.get(key), ""));
}
}
return msgMap;
}
private static Header jsonHeader = new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
/**
* 下发小程序和公众号统一的服务消息
* @param access_token
* @return
*/
public static TemplateMessageResult uniform_send(String access_token, WxUniformSendMessage wxUniformSendMessage) {
String messageJson = JsonUtil.toJSONString(wxUniformSendMessage);
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();
return LocalHttpClient.executeJsonResult(httpUriRequest, TemplateMessageResult.class);
}
/**
* 发送模板消息
* @return
*/
... ... @@ -105,6 +39,7 @@ public class WeiXinMessage {
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();
return LocalHttpClient.executeJsonResult(httpUriRequest, TemplateMessageResult.class);
}
/**
* 获取服务号的token
*
... ... @@ -123,4 +58,5 @@ public class WeiXinMessage {
tokenMap.put(appid,token);
return token.getAccess_token();
}
}
... ...
package com.zhonglai.luhui.alarm.notice.impl;
import com.alibaba.fastjson.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.WeiXinXiaoChengXuNoticeDto;
import com.zhonglai.luhui.alarm.notice.dto.wxUniformSend.WeiXinMessage;
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 java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Set;
public class WeiXinXiaoChengXuNoticeImpl implements NoticeFactory {
private Set<String> toOpenIds;
private WeiXinXiaoChengXuNoticeDto weiXinXiaoChengXuNoticeDto;
public WeiXinXiaoChengXuNoticeImpl(Integer userId,WeiXinXiaoChengXuNoticeDto weiXinXiaoChengXuNoticeDto)
{
this.weiXinXiaoChengXuNoticeDto = weiXinXiaoChengXuNoticeDto;
toOpenIds = CachAlarmConfig.getUserXcxOpenid(userId,weiXinXiaoChengXuNoticeDto.getXcxConfigId());
}
@Override
public boolean send(IotAlertLog iotAlertLog) {
if(null != toOpenIds && toOpenIds.size() != 0)
{
return sendMessage(iotAlertLog,toOpenIds.toArray(new String[toOpenIds.size()]));
}
return false;
}
/**
* 设备告警消息
* @param os openid
*/
public boolean sendMessage(IotAlertLog iotAlertLog, String ... os)
{
WxXcxSubscribeMessage wxXcxSubscribeMessage = new WxXcxSubscribeMessage();
wxXcxSubscribeMessage.setTemplate_id(weiXinXiaoChengXuNoticeDto.getTemplateId());
wxXcxSubscribeMessage.setLang("zh_CN");
wxXcxSubscribeMessage.setPage(weiXinXiaoChengXuNoticeDto.getRedirectUrl());
wxXcxSubscribeMessage.setMiniprogram_state("formal");
LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<String, TemplateMessageItem>();
data.put("thing2",new TemplateMessageItem(iotAlertLog.getDevice_name()));
data.put("character_string1",new TemplateMessageItem(iotAlertLog.getDevice_id()));
data.put("time6",new TemplateMessageItem(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(iotAlertLog.getCreate_time()))));
data.put("thing8",new TemplateMessageItem(iotAlertLog.getAlert_name()));
wxXcxSubscribeMessage.setData(data);
for(String o:os)
{
wxXcxSubscribeMessage.setTouser(o);
MessageAPI.messageSubscribeSend(WeiXinMessage.getWechatServerToken(weiXinXiaoChengXuNoticeDto.getXcxappid(),weiXinXiaoChengXuNoticeDto.getXcxsecret()),wxXcxSubscribeMessage);
}
return true;
}
}
... ...
package com.zhonglai.luhui.alarm.service;
import com.alibaba.fastjson.JSONObject;
import com.zhonglai.luhui.alarm.config.CachAlarmConfig;
import com.zhonglai.luhui.alarm.dao.DbOperateUtil;
import com.zhonglai.luhui.alarm.dto.IotAlertLog;
... ... @@ -31,9 +32,12 @@ public class SendAlarmService {
private static void runSend()
{
logger.info("开始发送告警消息");
try {
List<IotAlertLog> list = DbOperateUtil.getIotAlertLogList(2,100); //未处理的告警
if(null != list && list.size()!=0)
{
logger.info("有告警数据:{}",list.size());
List<Long> ids = new ArrayList<>();
List<Long> notids = new ArrayList<>();
... ... @@ -44,9 +48,15 @@ public class SendAlarmService {
notids.add(iotAlertLog.getAlert_log_id());
continue;
}
if(System.currentTimeMillis()-iotAlertLog.getCreate_time()>86400000l) //24小时之前的告警不需要推送
{
notids.add(iotAlertLog.getAlert_log_id());
continue;
}
switch (iotAlertLog.getAlert_level())
{
case 1: //提醒通知
logger.info("提醒通知:{}", JSONObject.toJSONString(iotAlertLog));
if(NoticeFactory.notice(iotAlertLog))
{
ids.add(iotAlertLog.getAlert_log_id());
... ... @@ -80,6 +90,12 @@ public class SendAlarmService {
DbOperateUtil.updateIotAlertLogStatus(notids,1);
}
}
}catch (Exception e)
{
logger.error("发送任务异常",e);
}
logger.info("发送任务执行完成");
}
... ...
... ... @@ -29,7 +29,7 @@ public class TriggerAlarmService {
// 创建Canal连接器
private static CanalConnector connector = CanalConnectors.newSingleConnector(
new InetSocketAddress("8.129.82.37", 11111),
new InetSocketAddress("127.0.0.1", 11111),
"example",
"",
""
... ...
package com.zhonglai.luhui.alarm.util;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolUtil {
private static int poolSize = 100; // 线程池大小
public static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor (poolSize);
public static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor (poolSize, Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
public static void close()
{
... ...
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 日志存放路径 -->
<property name="log.path" value="logs" />
<!-- 日志输出格式 -->
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
<!-- 控制台输出 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统日志输出 -->
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-info.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logs/output.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-info.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
<fileNamePattern>logs/output.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>5</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-error.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-error.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<!-- 控制台输出 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>ERROR</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 系统模块日志级别控制 -->
<logger name="com.ruoyi" level="info" />
<!-- Spring日志级别控制 -->
<logger name="org.springframework" level="warn" />
<root level="info">
<appender-ref ref="console" />
</root>
<!--系统操作日志-->
<root level="info">
<appender-ref ref="file_info" />
<appender-ref ref="file_error" />
<appender-ref ref="FILE" />
<appender-ref ref="CONSOLE" />
</root>
</configuration>
\ No newline at end of file
... ...
package com.zhonglai.luhui.api.controller.user;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.user.UserOpenid;
import com.zhonglai.luhui.action.BaseController;
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.WeiXinGongZhongHaoNoticeDto;
import com.zhonglai.luhui.device.dto.WeiXinXiaoChengXuNoticeDto;
import com.zhonglai.luhui.security.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.SnsToken;
import java.util.List;
import java.util.Map;
@Api(tags = "用户告警管理")
@RestController
@RequestMapping("/user/alarm")
public class UserInfoAlarmController extends BaseController {
@Autowired
private PublicService publicService;
@ApiOperation("提交公众号通知服务")
@ApiImplicitParams({
@ApiImplicitParam(value = "渠道id(管理员提供)",name = "channel_id"),
@ApiImplicitParam(value = "告警类型(1系统告警,2用户告警)",name = "type"),
@ApiImplicitParam(value = "授权获取到的code",name = "code"),
})
@Log(title = "提交公众号通知服务", businessType = BusinessType.INSERT)
@Transactional
@PostMapping(value = "subGzhNoticeService/{channel_id}/{type}")
public AjaxResult subGzhNoticeService(@PathVariable Integer channel_id,@PathVariable Integer type, String code)
{
//检查渠道是否存在
IotAlertNoticeChannel iotAlertNoticeChannel = publicService.getObject(IotAlertNoticeChannel.class,"id",channel_id+"");
if(null == iotAlertNoticeChannel)
{
return AjaxResult.error("通知渠道不存在");
}
if(iotAlertNoticeChannel.getType()!=1)
{
return AjaxResult.error("该渠道不是公众号通知渠道");
}
WeiXinGongZhongHaoNoticeDto weiXinGongZhongHaoNoticeDto = JSONObject.parseObject(iotAlertNoticeChannel.getConfig(),WeiXinGongZhongHaoNoticeDto.class);
Integer user_id = SecurityUtils.getUserId().intValue();
SnsToken snsToken = SnsAPI.oauth2AccessToken(weiXinGongZhongHaoNoticeDto.getGzhappid(), weiXinGongZhongHaoNoticeDto.getGzhsecret(),code);
if(StringUtils.isEmpty(snsToken.getOpenid()))
{
return AjaxResult.error("公众号授权失败");
}
upOpenid(user_id,snsToken.getOpenid(),weiXinGongZhongHaoNoticeDto.getXcxConfigId());
return upIotAlertUserNotice(user_id,channel_id,type);
}
@ApiOperation("提交小程序通知服务")
@ApiImplicitParams({
@ApiImplicitParam(value = "渠道id(管理员提供)",name = "channel_id"),
@ApiImplicitParam(value = "告警类型(1系统告警,2用户告警)",name = "type"),
@ApiImplicitParam(value = "小程序用户openid",name = "openid"),
})
@Log(title = "提交公众号通知服务", businessType = BusinessType.INSERT)
@Transactional
@PostMapping(value = "subXcxNoticeService/{channel_id}/{type}")
public AjaxResult subXcxNoticeService(@PathVariable Integer channel_id,@PathVariable Integer type, String openid)
{
//检查渠道是否存在
IotAlertNoticeChannel iotAlertNoticeChannel = publicService.getObject(IotAlertNoticeChannel.class,"id",channel_id+"");
if(null == iotAlertNoticeChannel)
{
return AjaxResult.error("通知渠道不存在");
}
if(iotAlertNoticeChannel.getType()!=2)
{
return AjaxResult.error("该渠道不是小程序通知渠道");
}
WeiXinXiaoChengXuNoticeDto weiXinXiaoChengXuNoticeDto = JSONObject.parseObject(iotAlertNoticeChannel.getConfig(),WeiXinXiaoChengXuNoticeDto.class);
Integer user_id = SecurityUtils.getUserId().intValue();
upOpenid(user_id,openid,weiXinXiaoChengXuNoticeDto.getXcxConfigId());
return upIotAlertUserNotice(user_id,channel_id,type);
}
@ApiOperation("获取告警通知渠道配置")
@ApiImplicitParam(value = "产品id",name = "product_id")
@GetMapping(value = "getIotAlertUserNoticeList/{product_id}")
public AjaxResult getIotAlertUserNoticeList(@PathVariable Integer product_id)
{
Integer user_id = SecurityUtils.getUserId().intValue();
IotAlertUserNotice iotAlertUserNotice = new IotAlertUserNotice();
iotAlertUserNotice.setUser_id(user_id);
List<Map<String,Object>> list = publicService.getObjectList(iotAlertUserNotice,"*",null,null,0,0);
if (null != list && list.size() !=0)
{
for (Map<String,Object> map:list)
{
switch ((int)map.get("type")) //告警类型(1系统告警,2用户告警)
{
case 1:
if ((map.get("alert_ids")).equals("*"))
{
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")+")"));
}
break;
case 2:
if ((map.get("alert_ids")).equals("*"))
{
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")+")"));
}
break;
}
String channels = (String) map.get("channels");
map.put("channelList",publicService.getObjectListBySQL("select `id`,`type`,`name`,`state` from `iot_alert_notice_channel` where id in("+channels+")"));
}
}
return AjaxResult.success(list);
}
@ApiOperation("获取告警通知渠道")
@GetMapping(value = "getIotAlertNoticeChannelList")
public AjaxResult getIotAlertNoticeChannelList()
{
IotAlertNoticeChannel iotAlertNoticeChannel = new IotAlertNoticeChannel();
iotAlertNoticeChannel.setState(1);
List<Map<String,Object>> list = publicService.getObjectList(iotAlertNoticeChannel,"`id`,`name`",null,null,0,0);
return AjaxResult.success(list);
}
@ApiOperation("获取指定产品的系统告警")
@ApiImplicitParam(value = "产品id",name = "product_id")
@GetMapping(value = "getIotAlertByProduct/{product_id}")
public AjaxResult getIotAlertByProduct(@PathVariable Long product_id)
{
IotAlert iotAlert = new IotAlert();
iotAlert.setProductId(product_id);
List<Map<String,Object>> list = publicService.getObjectList(iotAlert,"*",null,null,0,0);
return AjaxResult.success(list);
}
@ApiOperation("更新告警通知渠道配置")
@ApiImplicitParams({
@ApiImplicitParam(value = "通知渠道(iot_alert_notice_channel表的id集合,多个英文逗号分割)",name = "channels"),
@ApiImplicitParam(value = "告警id集合(关联iot_alert和iot_alert_user表的id,多个英文逗号分割,*表示所有)",name = "alert_ids"),
@ApiImplicitParam(value = "主键id",name = "id"),
})
@Log(title = "更新告警通知渠道配置", businessType = BusinessType.UPDATE)
@Transactional
@PostMapping(value = "upIotAlertUserNotice/{id}")
public AjaxResult upIotAlertUserNotice(@PathVariable Integer id,String channels, String alert_ids)
{
IotAlertUserNotice iotAlertUserNotice = new IotAlertUserNotice();
iotAlertUserNotice.setId(id);
iotAlertUserNotice.setChannels(channels);
iotAlertUserNotice.setAlert_ids(alert_ids);
int i = publicService.updateObject(iotAlertUserNotice,"id");
return AjaxResult.success(i);
}
@ApiOperation("更新指定产品的告警通知渠道配置")
@ApiImplicitParams({
@ApiImplicitParam(value = "通知渠道(iot_alert_notice_channel表的id集合,多个英文逗号分割)",name = "channels"),
@ApiImplicitParam(value = "告警id集合(关联iot_alert和iot_alert_user表的id,多个英文逗号分割,*表示所有)",name = "alert_ids"),
@ApiImplicitParam(value = "主键id",name = "id"),
@ApiImplicitParam(value = "产品id",name = "product_id"),
})
@Log(title = "更新指定产品的告警通知渠道配置", businessType = BusinessType.UPDATE)
@Transactional
@PostMapping(value = "upIotAlertUserNoticeByProduct/{id}/{product_id}")
public AjaxResult upIotAlertUserNoticeByProduct(@PathVariable Integer id,@PathVariable Long product_id,String channels, String alert_ids)
{
IotAlertUserNotice iotAlertUserNotice = publicService.getObject(IotAlertUserNotice.class,"id",id+"");
IotAlertUserNotice uPiotAlertUserNotice = new IotAlertUserNotice();
uPiotAlertUserNotice.setId(id);
if(StringUtils.isNotEmpty(channels))
{
uPiotAlertUserNotice.setChannels(channels);
}
if(StringUtils.isNotEmpty(alert_ids))
{
if("*".equals(iotAlertUserNotice.getAlert_ids()))
{
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)
{
Object aids = aidsList.get(0).get("aids");
if(null != aids && !aids.equals(""))
{
uPiotAlertUserNotice.setAlert_ids(aids+","+alert_ids);
}else {
uPiotAlertUserNotice.setAlert_ids(alert_ids);
}
}
}
}
int upi = 0;
if(StringUtils.isNotEmpty(uPiotAlertUserNotice.getChannels()) || StringUtils.isNotEmpty(uPiotAlertUserNotice.getAlert_ids()))
{
upi = publicService.updateObject(uPiotAlertUserNotice,"id");
}
return AjaxResult.success(upi);
}
private void upOpenid(Integer user_id,String openid,Integer xcxConfigid)
{
//更新用户openid表
UserOpenid userOpenid = new UserOpenid();
userOpenid.setUser_id(user_id);
userOpenid.setOpenid(openid);
userOpenid.setXcx_config_id(xcxConfigid);
Long ct = publicService.getObjectListTotle(userOpenid,null);
if(0 == ct)
{
publicService.insert(userOpenid);
}
}
private AjaxResult upIotAlertUserNotice(Integer user_id,Integer channel_id,Integer type)
{
//更新用户通知
IotAlertUserNotice iotAlertUserNotice= publicService.getObject(IotAlertUserNotice.class,"user_id,type",user_id+","+type);
if(null != iotAlertUserNotice)
{
if((","+iotAlertUserNotice.getChannels()+",").indexOf(","+channel_id+",")>=0)
{
return AjaxResult.error("您已经开通过通知服务了,请到通知服务编辑页面进行编辑");
}else {
IotAlertUserNotice upIotAlertUserNotice = new IotAlertUserNotice();
upIotAlertUserNotice.setId(iotAlertUserNotice.getId());
upIotAlertUserNotice.setChannels(iotAlertUserNotice.getChannels()+","+channel_id);
upIotAlertUserNotice.setUpdate_time(DateUtils.getTime());
return AjaxResult.success(publicService.updateObject(upIotAlertUserNotice,"id"));
}
}else {
IotAlertUserNotice sysIotAlertUserNotice = new IotAlertUserNotice();
sysIotAlertUserNotice.setChannels(channel_id+"");
sysIotAlertUserNotice.setType(type);
sysIotAlertUserNotice.setUser_id(user_id);
return AjaxResult.success(publicService.insert(sysIotAlertUserNotice));
}
}
@ApiOperation("生成告警授权连接")
@RequestMapping(value = "getAlarmOauth2URL/{channel_id}", method = RequestMethod.GET)
public AjaxResult getAlarmOauth2URL(@PathVariable Integer channel_id, @RequestParam(value="redirect_uri") String redirect_uri,String state)
{
//检查渠道是否存在
IotAlertNoticeChannel iotAlertNoticeChannel = publicService.getObject(IotAlertNoticeChannel.class,"id",channel_id+"");
if(null == iotAlertNoticeChannel)
{
return AjaxResult.error("通知渠道不存在");
}
if(iotAlertNoticeChannel.getType()!=1)
{
return AjaxResult.error("该渠道不是公众号通知渠道");
}
WeiXinGongZhongHaoNoticeDto weiXinGongZhongHaoNoticeDto = JSONObject.parseObject(iotAlertNoticeChannel.getConfig(),WeiXinGongZhongHaoNoticeDto.class);
String authorizeUrl = SnsAPI.connectOauth2Authorize(weiXinGongZhongHaoNoticeDto.getGzhappid(), redirect_uri, true, state);
return AjaxResult.success("",authorizeUrl);
}
}
... ...
package com.zhonglai.luhui.api.controller.user;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.user.UserOpenid;
import com.zhonglai.luhui.action.BaseController;
import com.zhonglai.luhui.dao.service.PublicService;
import com.zhonglai.luhui.device.domain.IotAlertNoticeChannel;
import com.zhonglai.luhui.device.domain.IotAlertUserNotice;
import com.zhonglai.luhui.device.dto.WeiXinGongZhongHaoNoticeDto;
import com.zhonglai.luhui.security.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.SnsToken;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@Api(tags = "用户管理")
@RestController
@RequestMapping("/user/userInfo")
public class UserInfoController extends BaseController {
@Autowired
private PublicService publicService;
@ApiOperation("提交小程序或者微信公众号通知服务")
@ApiImplicitParams({
@ApiImplicitParam(value = "渠道id(管理员提供)",name = "channel_id"),
@ApiImplicitParam(value = "授权获取到的code",name = "code"),
})
@Log(title = "提交小程序或者微信公众号通知服务", businessType = BusinessType.INSERT)
@Transactional
@PostMapping(value = "subXcxNoticeService/{channel_id}")
public AjaxResult subXcxNoticeService(@PathVariable Integer channel_id, String code)
{
//检查渠道是否存在
IotAlertNoticeChannel iotAlertNoticeChannel = publicService.getObject(IotAlertNoticeChannel.class,"id",channel_id+"");
if(null == iotAlertNoticeChannel)
{
return AjaxResult.error("通知渠道不存在");
}
if(iotAlertNoticeChannel.getType()!=1)
{
return AjaxResult.error("该渠道不是公众号通知渠道");
}
WeiXinGongZhongHaoNoticeDto weiXinGongZhongHaoNoticeDto = JSONObject.parseObject(iotAlertNoticeChannel.getConfig(),WeiXinGongZhongHaoNoticeDto.class);
Integer user_id = SecurityUtils.getUserId().intValue();
SnsToken snsToken = SnsAPI.oauth2AccessToken(weiXinGongZhongHaoNoticeDto.getGzhappid(), weiXinGongZhongHaoNoticeDto.getGzhsecret(),code);
if(StringUtils.isEmpty(snsToken.getOpenid()))
{
return AjaxResult.error("公众号授权失败");
}
//更新用户openid表
UserOpenid userOpenid = new UserOpenid();
userOpenid.setUser_id(user_id);
userOpenid.setOpenid(snsToken.getOpenid());
userOpenid.setXcx_config_id(weiXinGongZhongHaoNoticeDto.getXcxConfigId());
Long ct = publicService.getObjectListTotle(userOpenid,null);
if(0 == ct)
{
publicService.insert(userOpenid);
}
//更新用户通知
IotAlertUserNotice iotAlertUserNotice = new IotAlertUserNotice();
iotAlertUserNotice.setUser_id(user_id);
ct = publicService.getObjectListTotle(iotAlertUserNotice,null);
if(0 < ct)
{
return AjaxResult.error("您已经开通过通知服务了,请到通知服务编辑页面进行编辑");
}
IotAlertUserNotice sysIotAlertUserNotice = new IotAlertUserNotice();
sysIotAlertUserNotice.setChannels(channel_id+"");
sysIotAlertUserNotice.setType(1);
sysIotAlertUserNotice.setUser_id(user_id);
publicService.insert(sysIotAlertUserNotice);
IotAlertUserNotice userIotAlertUserNotice = new IotAlertUserNotice();
userIotAlertUserNotice.setChannels(channel_id+"");
userIotAlertUserNotice.setType(2);
userIotAlertUserNotice.setUser_id(user_id);
publicService.insert(userIotAlertUserNotice);
return AjaxResult.success();
}
@ApiOperation("生成告警授权连接")
@RequestMapping(value = "getAlarmOauth2URL/{channel_id}", method = RequestMethod.GET)
public AjaxResult getAlarmOauth2URL(@PathVariable Integer channel_id, @RequestParam(value="redirect_uri") String redirect_uri,String state)
{
//检查渠道是否存在
IotAlertNoticeChannel iotAlertNoticeChannel = publicService.getObject(IotAlertNoticeChannel.class,"id",channel_id+"");
if(null == iotAlertNoticeChannel)
{
return AjaxResult.error("通知渠道不存在");
}
if(iotAlertNoticeChannel.getType()!=1)
{
return AjaxResult.error("该渠道不是公众号通知渠道");
}
WeiXinGongZhongHaoNoticeDto weiXinGongZhongHaoNoticeDto = JSONObject.parseObject(iotAlertNoticeChannel.getConfig(),WeiXinGongZhongHaoNoticeDto.class);
String authorizeUrl = SnsAPI.connectOauth2Authorize(weiXinGongZhongHaoNoticeDto.getGzhappid(), redirect_uri, true, state);
return AjaxResult.success("",authorizeUrl);
}
}
... ... @@ -60,6 +60,7 @@ public class MqttSubscribeService {
if (StringUtils.isEmpty(productids))
{
List<ProtocolSubTopics> list = persistenceDBService.getProtocolSubTopicsFromIp(SysParameter.service_ip);
log.info("根据ip查询的订阅消息【{}】",list);
SubTopicsAndproductDto subTopicsAndproductDto = getSubTopicsFromProtocolSubTopics(list);
return subscribeForProductids(subTopicsAndproductDto);
}
... ... @@ -182,6 +183,7 @@ public class MqttSubscribeService {
{
Set<String> tlist = new HashSet<>();
Set<Integer> plist = new HashSet<>();
Set<String> untlist = new HashSet<>();
for (ProtocolSubTopics protocolSubTopics:list)
{
if (StringUtils.isNotEmpty(protocolSubTopics.getSub_topics()))
... ... @@ -196,6 +198,8 @@ public class MqttSubscribeService {
tlist.add(topic);
topics.add(topic);
subTopicsAndproductDto.setUp(true);
}else {
untlist.add(topic);
}
}
... ... @@ -203,6 +207,7 @@ public class MqttSubscribeService {
}
subTopicsAndproductDto.setPlist(plist);
subTopicsAndproductDto.setTlist(tlist);
subTopicsAndproductDto.setUntlist(untlist);
}
return subTopicsAndproductDto;
... ... @@ -224,4 +229,9 @@ public class MqttSubscribeService {
String topic = topicStringBuffer.toString();
return topic;
}
public void connectionLost()
{
topics.clear();
}
}
... ...
... ... @@ -240,6 +240,7 @@ public class DefaultDbService {
public List<ProtocolSubTopics> getProtocolSubTopicsFromIp(String ip)
{
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` = ?");
log.info("根据ip查询订阅信息的查询语句{}",stringBuffer);
return baseDao.findBysql(stringBuffer.toString(), ProtocolSubTopics.class,ip);
}
/**
... ...
... ... @@ -39,6 +39,7 @@ public class MqttCallback extends BaseCallback implements MqttCallbackExtended {
public void connectionLost(Throwable throwable) {
//连接丢失
log.error("连接丢失",throwable);
mqttSubscribeService.connectionLost();
}
@Override
... ...