Browse Source

feat:“添加设备异常微信推送功能“

soobin 1 year ago
parent
commit
b2c322a7c2

+ 17 - 3
src/main/java/com/szwl/controller/AlarmRecordIndexController.java

@@ -6,13 +6,16 @@ import com.szwl.model.dto.AlarmRecordVo;
 import com.szwl.model.entity.TAdmin;
 import com.szwl.model.entity.TAlarmRecord;
 import com.szwl.model.entity.TEquipment;
+import com.szwl.model.entity.TWechat;
 import com.szwl.model.utils.MailUtil;
 import com.szwl.model.utils.YunPianSms;
 import com.szwl.service.TAdminService;
 import com.szwl.service.TAlarmRecordService;
 import com.szwl.service.TEquipmentService;
+import com.szwl.service.TWechatService;
 import org.apache.commons.lang.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.StringRedisTemplate;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.*;
 
@@ -34,6 +37,12 @@ public class AlarmRecordIndexController {
     @Autowired
     private TAdminService adminService;
 
+    @Autowired
+    private StringRedisTemplate redisTemplate;
+
+    @Resource
+    TWechatService wechatService;
+
     private static final String appid = "07784f5fedb508046c841b391005b7de";
 
     /**
@@ -79,6 +88,14 @@ public class AlarmRecordIndexController {
         String ifForeign = admin.getIfForeign();
         String companyType = admin.getCompanyType();
         String messageReceiver = equipment.getMessageReceiver();
+        // 查询是否绑定微信
+        LambdaQueryWrapper<TWechat> wechatQuery = Wrappers.lambdaQuery();
+        wechatQuery.eq(TWechat::getAdminId, admin.getId());
+        TWechat wechat = wechatService.getOne(wechatQuery);
+        // 微信公众号推送
+        if(wechat != null) {
+            wechatService.sendAlarmMessage(wechat.getOpenId(), clientId, name, companyType, alarmContent, alarmRecordVo.getOccurrenceTime());
+        }
         if (ifForeign.equals("1")) {
             String subject = "Error message from Magic Candy Machine";
             StringBuffer contnet = new StringBuffer();
@@ -119,8 +136,6 @@ public class AlarmRecordIndexController {
                     String[] split = messageReceiver.split(",");
                     for (int i = 0; i < split.length; i++) {
                         if (StringUtils.isNotEmpty(split[i])) {
-//                            Long id = alarmRecord.getId();
-//                            String mess = ";序号:"+String.valueOf(id);
                             if (StringUtils.isNotEmpty(companyType) && companyType.equals("1")) {
                                 // 如果是七云科技的用户
                                 result = YunPianSms.sendSms(appid, getSCMessage(alarmContent, name, clientId.substring(clientId.length() - 6)), split[i]);
@@ -137,7 +152,6 @@ public class AlarmRecordIndexController {
         }
         return "报警记录添加成功";
     }
-
     private String getMessage(String content, String name, String clientId) {
         String message = "【申泽智能】您好,机器" + content + ",机器名:" + name + ",设备号:" + clientId;
         return message;

+ 24 - 1
src/main/java/com/szwl/service/TWechatService.java

@@ -3,6 +3,8 @@ package com.szwl.service;
 import com.szwl.model.entity.TWechat;
 import com.baomidou.mybatisplus.extension.service.IService;
 
+import java.util.Date;
+
 /**
  * <p>
  *  服务类
@@ -13,5 +15,26 @@ import com.baomidou.mybatisplus.extension.service.IService;
  */
 public interface TWechatService extends IService<TWechat> {
 
-    String sendNoworkMessage(String openId, String clientId, String name, String ifForeign, String companyType);
+    /**
+     * 异常离线通知
+     * @param openId
+     * @param clientId
+     * @param name
+     * @param ifForeign
+     * @param companyType
+     * @return
+     */
+    void sendNoworkMessage(String openId, String clientId, String name, String ifForeign, String companyType);
+
+    /**
+     * 异常报警通知
+     * @param openId
+     * @param clientId
+     * @param name
+     * @param companyType
+     * @param alarmContent
+     * @param occurrenceTime
+     * @return
+     */
+     void sendAlarmMessage(String openId, String clientId, String name, String companyType, String alarmContent, Date occurrenceTime);
 }

+ 133 - 35
src/main/java/com/szwl/service/impl/TWechatServiceImpl.java

@@ -1,6 +1,7 @@
 package com.szwl.service.impl;
 
 import com.alibaba.fastjson.JSONObject;
+import com.szwl.config.AccessTokenCache;
 import com.szwl.constant.ConfigConsts;
 import com.szwl.model.bean.WeChatTemplateMsg;
 import com.szwl.model.entity.TAdmin;
@@ -10,16 +11,26 @@ import com.szwl.service.TAdminService;
 import com.szwl.service.TWechatService;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.szwl.util.WechatSendUtil;
+import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.StringRedisTemplate;
 import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Service;
 import org.springframework.web.client.RestTemplate;
 
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.net.URL;
+import java.net.URLConnection;
 import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.Map;
+import java.util.concurrent.TimeUnit;
 
 /**
  * <p>
@@ -29,62 +40,149 @@ import java.util.Map;
  * @author wuhs
  * @since 2023-05-22
  */
+@Slf4j
 @Service
 public class TWechatServiceImpl extends ServiceImpl<TWechatMapper, TWechat> implements TWechatService {
 
     @Autowired
     TAdminService adminService;
 
+    @Autowired
+    AccessTokenCache accessTokenCache;
+
+    @Autowired
+    private StringRedisTemplate redisTemplate;
+
+    private static final String SZ_ACCESS_TOKEN_KEY = "sz_wechat_access_token";
+    private static final String SC_ACCESS_TOKEN_KEY = "sc_wechat_access_token";
+
+    /**
+     * 缓存1个半小时(90分钟)
+     */
+    private static final long EXPIRATION_TIME = 10 * 60;
+
+
     @Override
-    public String sendNoworkMessage(String openId, String clientId, String name, String ifForeign, String companyType) {
+    public void sendNoworkMessage(String openId, String clientId, String name, String ifForeign, String companyType) {
         // 模板参数
         Map<String, WeChatTemplateMsg> sendMag = new HashMap();
-        // 公众号的模板id(也有相应的接口可以查询到)
-        String templateId = "tNMH94OG5bRkTCK1RFi7_zdmj6Y-27iy5Fq1mBH6wTQ";
-        // 微信的基础accessToken
-        String accessToken = WechatSendUtil.getAccessToken(companyType);;
-//        TAdmin admin = adminService.getById(1L);
-//        accessToken = admin.getDepartment();
-//        if(StringUtils.isEmpty(accessToken)){
-//            accessToken = WechatSendUtil.getAccessToken();
-//        }
-        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
-
-//        StringBuffer cli = new StringBuffer();
-//        String keyword1 = cli.append(clientId.substring(clientId.length()-6)).append("-").append(name).toString();
         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         String alarmTime = format.format(new Date());
         if (StringUtils.isEmpty(ifForeign) || ifForeign.equals("0")) {
+            // 国内
             sendMag.put("thing11", new WeChatTemplateMsg(name));
             sendMag.put("character_string14", new WeChatTemplateMsg(clientId.substring(clientId.length()-6)));
             sendMag.put("thing4", new WeChatTemplateMsg("严重"));
             sendMag.put("time5", new WeChatTemplateMsg(alarmTime));
             sendMag.put("thing6", new WeChatTemplateMsg("机器可能出现断网或突然断电,请及时处理!"));
-            // 国内
-//            sendMag.put("first", new WeChatTemplateMsg("设备异常"));
-//            sendMag.put("keyword1", new WeChatTemplateMsg(keyword1));
-//            sendMag.put("keyword2", new WeChatTemplateMsg("现在"));
-//            sendMag.put("keyword3", new WeChatTemplateMsg("严重"));
-//            sendMag.put("keyword4", new WeChatTemplateMsg("信号"));
-//            sendMag.put("keyword5",
-//                    new WeChatTemplateMsg("机器可能出现断网或突然断电,请及时处理!"));
-//            sendMag.put("remark",
-//                    new WeChatTemplateMsg("Please pay attention to the time and status of the above alarms and take appropriate control measures/请注意以上告警发生的时间和状态,采取适当的控制措施."));
         } else {
+            // 国外
             sendMag.put("thing11", new WeChatTemplateMsg(name));
             sendMag.put("character_string14", new WeChatTemplateMsg(clientId.substring(clientId.length()-6)));
             sendMag.put("thing4", new WeChatTemplateMsg("Serious"));
             sendMag.put("time5", new WeChatTemplateMsg(alarmTime));
             sendMag.put("thing6", new WeChatTemplateMsg("Power/Network loss."));
-            // 国外
-//            sendMag.put("first", new WeChatTemplateMsg("Equipment abnormality"));
-//            sendMag.put("keyword1", new WeChatTemplateMsg(keyword1));
-//            sendMag.put("keyword2", new WeChatTemplateMsg("Now"));
-//            sendMag.put("keyword3", new WeChatTemplateMsg("Serious"));
-//            sendMag.put("keyword4", new WeChatTemplateMsg("Network"));
-//            sendMag.put("keyword5",
-//                    new WeChatTemplateMsg("The machine may be disconnected or suddenly power off, please deal with it in time!"));
         }
+        sendWechatMessage(openId, sendMag, companyType);
+    }
+
+    @Override
+    public void sendAlarmMessage(String openId, String clientId, String name, String companyType, String alarmContent, Date occurrenceTime) {
+        // 模板参数
+        Map<String, WeChatTemplateMsg> sendMag = new HashMap();
+        // 转换时间为String类型
+        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        String alarmTime = format.format(occurrenceTime);
+        // 模版参数
+        sendMag.put("thing11", new WeChatTemplateMsg(name));
+        sendMag.put("character_string14", new WeChatTemplateMsg(clientId.substring(clientId.length()-6)));
+        sendMag.put("thing4", new WeChatTemplateMsg("高"));
+        sendMag.put("time5", new WeChatTemplateMsg(alarmTime));
+        sendMag.put("thing6", new WeChatTemplateMsg(alarmContent));
+        sendWechatMessage(openId, sendMag, companyType);
+    }
+
+    /**
+     * 获取accessToken推送消息
+     * @param openId
+     * @param sendMag
+     * @param companyType
+     * @return
+     */
+    public void sendWechatMessage(String openId, Map<String, WeChatTemplateMsg> sendMag, String companyType) {
+        String url = "";
+        String accessToken = "";
+        try {
+            if(StringUtils.isEmpty(companyType) || companyType.equals("0")) {
+                accessToken = redisTemplate.opsForValue().get(SZ_ACCESS_TOKEN_KEY);
+            } else {
+                accessToken = redisTemplate.opsForValue().get(SC_ACCESS_TOKEN_KEY);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        if(StringUtils.isEmpty(accessToken)) {
+            if(StringUtils.isEmpty(companyType) || companyType.equals("0")) {
+                url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+                        + ConfigConsts.SZ_WX_SUB_APP_ID + "&secret=" + ConfigConsts.SZ_WX_APP_SECRET;
+            } else {
+                url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+                        + ConfigConsts.SC_WX_SUB_APP_ID + "&secret=" + ConfigConsts.SC_WX_APP_SECRET;
+            }
+            PrintWriter out = null;
+            BufferedReader in = null;
+            String line;
+            StringBuffer stringBuffer = new StringBuffer();
+            try {
+                URL realUrl = new URL(url);
+                // 打开和URL之间的连接
+                URLConnection conn = realUrl.openConnection();
+
+                // 设置通用的请求属性 设置请求格式
+                //设置返回类型
+                conn.setRequestProperty("contentType", "text/plain");
+                //设置请求类型
+                conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
+                //设置超时时间
+                conn.setConnectTimeout(1000);
+                conn.setReadTimeout(1000);
+                conn.setDoOutput(true);
+                conn.connect();
+                // 获取URLConnection对象对应的输出流
+                out = new PrintWriter(conn.getOutputStream());
+                // flush输出流的缓冲
+                out.flush();
+                // 定义BufferedReader输入流来读取URL的响应    设置接收格式
+                in = new BufferedReader(
+                        new InputStreamReader(conn.getInputStream(), "UTF-8"));
+                while ((line = in.readLine()) != null) {
+                    stringBuffer.append(line);
+                }
+                JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
+                log.info("获取token:{}",jsonObject.toString());
+                accessToken = jsonObject.getString("access_token");
+                if(StringUtils.isEmpty(companyType) || companyType.equals("0")) {
+                    redisTemplate.opsForValue().set(SZ_ACCESS_TOKEN_KEY, accessToken, EXPIRATION_TIME, TimeUnit.SECONDS);
+                } else {
+                    redisTemplate.opsForValue().set(SZ_ACCESS_TOKEN_KEY, accessToken, EXPIRATION_TIME, TimeUnit.SECONDS);
+                }
+            } catch (Exception e) {
+                e.printStackTrace();
+            } finally {
+                //使用finally块来关闭输出流、输入流
+                try {
+                    if (out != null) {
+                        out.close();
+                    }
+                    if (in != null) {
+                        in.close();
+                    }
+                } catch (IOException ex) {
+                    ex.printStackTrace();
+                }
+            }
+        }
+        // 推送消息
         RestTemplate restTemplate = new RestTemplate();
         Map<String, Object> sendBody = new HashMap<>();
         sendBody.put("touser", openId);
@@ -95,12 +193,12 @@ public class TWechatServiceImpl extends ServiceImpl<TWechatMapper, TWechat> impl
         } else {
             sendBody.put("template_id", ConfigConsts.SC_TEMPLATE_ID);
         }
-//        sendBody.put("template_id", templateId);
-        ResponseEntity<String> forEntity = restTemplate.postForEntity(url, sendBody, String.class);
+        String sendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
+        ResponseEntity<String> forEntity = restTemplate.postForEntity(sendUrl, sendBody, String.class);
         JSONObject jsonObject = JSONObject.parseObject(forEntity.getBody());
         String messageCode = jsonObject.getString("errcode");
         String msgId = jsonObject.getString("msgid");
         System.out.println("messageCode : " + messageCode + ", msgId: " +msgId);
-        return forEntity.getBody();
+        log.info("微信推送结果:{}","messageCode : " + messageCode + ", msgId: " +msgId);
     }
 }

+ 85 - 64
src/main/java/com/szwl/util/WechatSendUtil.java

@@ -5,6 +5,8 @@ import com.szwl.constant.ConfigConsts;
 import com.szwl.model.utils.MailUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.RedisTemplate;
 
 import java.io.BufferedReader;
 import java.io.IOException;
@@ -13,79 +15,98 @@ import java.io.PrintWriter;
 import java.net.URL;
 import java.net.URLConnection;
 import java.util.Date;
+import java.util.concurrent.TimeUnit;
 
 @Slf4j
 public class WechatSendUtil {
 
-    private static final String appId="wxcd5b1b2636c9f611";
-    private static final String secret="e2854aa99f8279f33b4f065b2ffb75b1";
-    private static final String orderPlacementNoticeTemplateId="tNMH94OG5bRkTCK1RFi7_zdmj6Y-27iy5Fq1mBH6wTQ";
 
     /**
      * 获取小程序token
      * @return
      */
-    public static String getAccessToken(String companyType) {
-        String url = "";
-        if(StringUtils.isEmpty(companyType) || companyType.equals("0")) {
-            url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
-                    + ConfigConsts.SZ_WX_SUB_APP_ID + "&secret=" + ConfigConsts.SZ_WX_APP_SECRET;
-        } else {
-            url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
-                    + ConfigConsts.SC_WX_SUB_APP_ID + "&secret=" + ConfigConsts.SC_WX_APP_SECRET;
-        }
-        PrintWriter out = null;
-        BufferedReader in = null;
-        String line;
-        StringBuffer stringBuffer = new StringBuffer();
-        try {
-            URL realUrl = new URL(url);
-            // 打开和URL之间的连接
-            URLConnection conn = realUrl.openConnection();
-
-            // 设置通用的请求属性 设置请求格式
-            //设置返回类型
-            conn.setRequestProperty("contentType", "text/plain");
-            //设置请求类型
-            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
-            //设置超时时间
-            conn.setConnectTimeout(1000);
-            conn.setReadTimeout(1000);
-            conn.setDoOutput(true);
-            conn.connect();
-            // 获取URLConnection对象对应的输出流
-            out = new PrintWriter(conn.getOutputStream());
-            // flush输出流的缓冲
-            out.flush();
-            // 定义BufferedReader输入流来读取URL的响应    设置接收格式
-            in = new BufferedReader(
-                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
-            while ((line = in.readLine()) != null) {
-                stringBuffer.append(line);
-            }
-            JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
-            log.info("获取token:{}",jsonObject.toString());
-            jsonObject.getString("access_token");
-            return jsonObject.getString("access_token");
-
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-        //使用finally块来关闭输出流、输入流
-        finally {
-            try {
-                if (out != null) {
-                    out.close();
-                }
-                if (in != null) {
-                    in.close();
-                }
-            } catch (IOException ex) {
-                ex.printStackTrace();
-            }
-        }
-        return null;
-    }
+//    public static String getAccessToken(String companyType) {
+//        String url = "";
+//        String accessToken = "";
+//        try {
+//            if(StringUtils.isEmpty(companyType) || companyType.equals("0")) {
+//                accessToken = redisTemplate.opsForValue().get(SZ_ACCESS_TOKEN_KEY);
+//            } else {
+////                accessToken = accessTokenCache.getAccessToken(SC_ACCESS_TOKEN_KEY);
+//                accessToken = redisTemplate.opsForValue().get(SC_ACCESS_TOKEN_KEY);
+//            }
+//        } catch (Exception e) {
+//            e.printStackTrace();
+//        }
+//        if(StringUtils.isNotEmpty(accessToken)) {
+//            return accessToken;
+//        }
+//        if(StringUtils.isEmpty(companyType) || companyType.equals("0")) {
+//            url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+//                    + ConfigConsts.SZ_WX_SUB_APP_ID + "&secret=" + ConfigConsts.SZ_WX_APP_SECRET;
+//        } else {
+//            url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+//                    + ConfigConsts.SC_WX_SUB_APP_ID + "&secret=" + ConfigConsts.SC_WX_APP_SECRET;
+//        }
+//        PrintWriter out = null;
+//        BufferedReader in = null;
+//        String line;
+//        StringBuffer stringBuffer = new StringBuffer();
+//        try {
+//            URL realUrl = new URL(url);
+//            // 打开和URL之间的连接
+//            URLConnection conn = realUrl.openConnection();
+//
+//            // 设置通用的请求属性 设置请求格式
+//            //设置返回类型
+//            conn.setRequestProperty("contentType", "text/plain");
+//            //设置请求类型
+//            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
+//            //设置超时时间
+//            conn.setConnectTimeout(1000);
+//            conn.setReadTimeout(1000);
+//            conn.setDoOutput(true);
+//            conn.connect();
+//            // 获取URLConnection对象对应的输出流
+//            out = new PrintWriter(conn.getOutputStream());
+//            // flush输出流的缓冲
+//            out.flush();
+//            // 定义BufferedReader输入流来读取URL的响应    设置接收格式
+//            in = new BufferedReader(
+//                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
+//            while ((line = in.readLine()) != null) {
+//                stringBuffer.append(line);
+//            }
+//            JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
+//            log.info("获取token:{}",jsonObject.toString());
+//            accessToken = jsonObject.getString("access_token");
+//            if(StringUtils.isEmpty(companyType) || companyType.equals("0")) {
+////                accessTokenCache.setAccessToken(SZ_ACCESS_TOKEN_KEY, accessToken);
+//                redisTemplate.opsForValue().set(SZ_ACCESS_TOKEN_KEY, accessToken, EXPIRATION_TIME, TimeUnit.SECONDS);
+//            } else {
+////                accessTokenCache.setAccessToken(SC_ACCESS_TOKEN_KEY, accessToken);
+//                redisTemplate.opsForValue().set(SZ_ACCESS_TOKEN_KEY, accessToken, EXPIRATION_TIME, TimeUnit.SECONDS);
+//            }
+//            return accessToken;
+//
+//        } catch (Exception e) {
+//            e.printStackTrace();
+//        }
+//        //使用finally块来关闭输出流、输入流
+//        finally {
+//            try {
+//                if (out != null) {
+//                    out.close();
+//                }
+//                if (in != null) {
+//                    in.close();
+//                }
+//            } catch (IOException ex) {
+//                ex.printStackTrace();
+//            }
+//        }
+//        return null;
+//    }
 
     public static void sentEmail(String email,String name) {
         String subject = "Error message from Magic Candy Machine";