Przeglądaj źródła

后台消息推送管理

wsl 2 lat temu
rodzic
commit
09eac0afc1
23 zmienionych plików z 1981 dodań i 20 usunięć
  1. 31 1
      common/common-entity/sql记录
  2. 18 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/message/SystemMessageDO.java
  3. 110 0
      common/common-entity/src/main/java/com/yihu/jw/entity/log/BasePushRecordLogEntity.java
  4. 75 0
      common/common-entity/src/main/java/com/yihu/jw/entity/log/BasePushrecordLogInfoEntity.java
  5. 9 1
      common/common-util/src/main/java/com/yihu/jw/util/date/DateUtil.java
  6. 17 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/log/BasePushRecordLogDao.java
  7. 12 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/log/BasePushrecordLogInfoDao.java
  8. 48 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/ManageMessagePush/ManageSystemPushMessageController.java
  9. 211 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/ManageMessagePush/ManageSystemPushMessageService.java
  10. 59 1
      svr/svr-base/src/main/java/com/yihu/jw/base/service/device/DeviceManageService.java
  11. 687 0
      svr/svr-base/src/main/java/com/yihu/jw/base/util/HttpClientUtilCare.java
  12. 11 0
      svr/svr-cloud-job/src/main/java/com/yihu/jw/care/dao/pushLog/BasePushRecordLogDao.java
  13. 12 0
      svr/svr-cloud-job/src/main/java/com/yihu/jw/care/dao/pushLog/BasePushrecordLogInfoDao.java
  14. 47 10
      svr/svr-cloud-job/src/main/java/com/yihu/jw/care/event/ApplicationEvent.java
  15. 1 1
      svr/svr-cloud-job/src/main/java/com/yihu/jw/care/job/device/DeviceLostAssociationJob.java
  16. 34 0
      svr/svr-cloud-job/src/main/java/com/yihu/jw/care/job/device/DeviceOffLoneJob.java
  17. 32 0
      svr/svr-cloud-job/src/main/java/com/yihu/jw/care/job/device/DeviceWatchOffWearJob.java
  18. 32 0
      svr/svr-cloud-job/src/main/java/com/yihu/jw/care/job/device/DeviceWatchRemainingPowerJob.java
  19. 81 0
      svr/svr-cloud-job/src/main/java/com/yihu/jw/care/job/pushRecord/PushRecordJob.java
  20. 132 2
      svr/svr-cloud-job/src/main/java/com/yihu/jw/care/service/device/PatientDeviceService.java
  21. 312 2
      svr/svr-cloud-job/src/main/java/com/yihu/jw/care/util/DeviceLostMessageUtil.java
  22. 9 1
      svr/svr-cloud-job/src/main/resources/system.properties
  23. 1 1
      svr/svr-iot/src/main/resources/bootstrap.yml

+ 31 - 1
common/common-entity/sql记录

@ -1853,4 +1853,34 @@ CREATE TABLE `base_hz_interface_dict` (
  `request_secret` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '请求秘钥',
  `request_secret_end_time` datetime DEFAULT NULL COMMENT '请求秘钥过期时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='杭州接口';
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='杭州接口';
-- 2022-07-04 wsl
CREATE TABLE `base_pushrecord_log` (
  `id` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `content` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '发送内容',
  `pushType` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '推送类型1立即发送 2 定时发送',
  `send_time` datetime DEFAULT NULL COMMENT '发送时间',
  `num` int(10) DEFAULT NULL COMMENT '发送人数',
  `status` tinyint(2) DEFAULT NULL COMMENT '状态(1已发送,0待发送)',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
  `send_object` varchar(1000) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '发送对象',
  `send_object_type` tinyint(2) DEFAULT NULL COMMENT '发送对象类型(1签约老人,2部分签约老人)',
  `message_type` int(2) NOT NULL COMMENT '消息类型(对应字典表pushMessageType)',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='推送记录日志表';
CREATE TABLE `base_pushrecord_log_info` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `pushId` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '推送记录id',
  `patientName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '推送居民名字',
  `patient` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '推送居民id',
  `content` varchar(1000) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '发送内容',
  `status` int(2) DEFAULT NULL COMMENT '发送状态',
  `sendTime` datetime DEFAULT NULL COMMENT '发送时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='推送记录日志明细';
ALTER TABLE base_system_message ADD audio_url VARCHAR(500) COMMENT '语音地址';

+ 18 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/message/SystemMessageDO.java

@ -27,6 +27,12 @@ public class SystemMessageDO extends UuidIdentityEntity {
     * 新生儿在线咨询 850
     * 老人在线咨询 851
     * 老人健康咨询 852
     *
     * 智能手表佩戴提示 991
     * 智能手表电量提示 992
     * 报警器电量提示 993
     * 设备离线提示 994
     * 人工手动系统推送 999
     */
    private String type;
    /**
@ -83,6 +89,18 @@ public class SystemMessageDO extends UuidIdentityEntity {
    private String reason;
    private String code;
    private String senderPhoto;
    private String audioUrl; //音频地址
    @Column(name = "audio_url")
    public String getAudioUrl() {
        return audioUrl;
    }
    public void setAudioUrl(String audioUrl) {
        this.audioUrl = audioUrl;
    }
    @Column(name = "content")
    public String getContent() {
        return content;

+ 110 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/log/BasePushRecordLogEntity.java

@ -0,0 +1,110 @@
package com.yihu.jw.entity.log;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by wsl on 2022/7/4
 */
@Entity
@Table(name = "base_pushrecord_log")
public class BasePushRecordLogEntity extends UuidIdentityEntity {
    private String content;  //发送内容
    private String pushType;  //推送类型
    private Date sendTime;  //发送时间
    private Integer num;  //发送人数
    private Integer status;  //状态(1已发送,0待发送)
    private Date createTime;  //创建时间
    private String sendObject;  //发送对象
    private Integer messageType;//消息推送类型
    private  Integer sendObjectType;//发送对象类型(1签约老人,2部分签约老人)
    @Column(name = "send_object_type")
    public Integer getSendObjectType() {
        return sendObjectType;
    }
    public void setSendObjectType(Integer sendObjectType) {
        this.sendObjectType = sendObjectType;
    }
    @Column(name = "message_type")
    public Integer getMessageType() {
        return messageType;
    }
    public void setMessageType(Integer messageType) {
        this.messageType = messageType;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    @Column(name = "push_type")
    public String getPushType() {
        return pushType;
    }
    public void setPushType(String pushType) {
        this.pushType = pushType;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "send_time")
    public Date getSendTime() {
        return sendTime;
    }
    public void setSendTime(Date sendTime) {
        this.sendTime = sendTime;
    }
    public Integer getNum() {
        return num;
    }
    public void setNum(Integer num) {
        this.num = num;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "create_time")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    @Column(name = "send_object")
    public String getSendObject() {
        return sendObject;
    }
    public void setSendObject(String sendObject) {
        this.sendObject = sendObject;
    }
}

+ 75 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/log/BasePushrecordLogInfoEntity.java

@ -0,0 +1,75 @@
package com.yihu.jw.entity.log;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by wsl on 2022/7/5
 */
@Entity
@Table(name = "base_pushrecord_log_info")
public class BasePushrecordLogInfoEntity extends IdEntity {
    private String pushId; //推送记录id
    private String patientName;//推送居民名字
    private String patient; //推送居民id
    private String content; //发送内容
    private Integer status; //发送状态
    private Date sendTime; //发送时间
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
    public String getPushId() {
        return pushId;
    }
    public void setPushId(String pushId) {
        this.pushId = pushId;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getSendTime() {
        return sendTime;
    }
    public void setSendTime(Date sendTime) {
        this.sendTime = sendTime;
    }
}

+ 9 - 1
common/common-util/src/main/java/com/yihu/jw/util/date/DateUtil.java

@ -1577,5 +1577,13 @@ public class DateUtil {
        list.add(DateUtil.dateToStrLong(afterTime));
        return list;
    }
    /**
     * 计算当前时间和传入时间的相差
     * 秒数
     */
    public static Long behindSubBefore(String date){
        Date startDate = DateUtil.strToDate(date);
        Date currentDate = DateUtil.getNowDate();
        return (startDate.getTime() - currentDate.getTime()) / 1000;
    }
}

+ 17 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/log/BasePushRecordLogDao.java

@ -0,0 +1,17 @@
package com.yihu.jw.base.dao.log;
import com.yihu.jw.entity.log.BasePushRecordLogEntity;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by wsl on 2022/7/4
 */
public interface BasePushRecordLogDao extends PagingAndSortingRepository<BasePushRecordLogEntity, String>, JpaSpecificationExecutor<BasePushRecordLogEntity> {
    @Query("from BasePushRecordLogEntity")
    List<BasePushRecordLogEntity> findAll();
}

+ 12 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/log/BasePushrecordLogInfoDao.java

@ -0,0 +1,12 @@
package com.yihu.jw.base.dao.log;
import com.yihu.jw.entity.log.BasePushrecordLogInfoEntity;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by wsl on 2022/7/5
 */
public interface BasePushrecordLogInfoDao extends PagingAndSortingRepository<BasePushrecordLogInfoEntity, String>, JpaSpecificationExecutor<BasePushrecordLogInfoEntity> {
}

+ 48 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/ManageMessagePush/ManageSystemPushMessageController.java

@ -0,0 +1,48 @@
package com.yihu.jw.base.endpoint.ManageMessagePush;
import com.yihu.jw.base.service.ManageMessagePush.ManageSystemPushMessageService;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
 * Created by wsl on 2022/7/4
 */
@RestController
@RequestMapping(value = "/ManageSystemPushMessage", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(value = "消息推送管理", description = "消息推送管理接口", tags = {"wlyy消息推送 - 消息推送管理接口"})
public class ManageSystemPushMessageController extends EnvelopRestEndpoint {
    @Autowired
    ManageSystemPushMessageService mspmservice;
    @ApiOperation("获取所有签约老人")
    @GetMapping(value = "/signOlds")
    public ListEnvelop signOlds(@ApiParam(name = "name", value = "居民名字", required = false)
                                @RequestParam(value = "name", required = false) String name) {
        try {
            List<BasePatientDO> basePatientDOS = mspmservice.signOlds(name);
            return success(basePatientDOS);
        } catch (Exception e) {
            e.printStackTrace();
            return failedListEnvelopException2(e);
        }
    }
}

+ 211 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/ManageMessagePush/ManageSystemPushMessageService.java

@ -0,0 +1,211 @@
package com.yihu.jw.base.service.ManageMessagePush;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.base.dao.log.BasePushRecordLogDao;
import com.yihu.jw.base.dao.log.BasePushrecordLogInfoDao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.log.BasePushRecordLogEntity;
import com.yihu.jw.entity.log.BasePushrecordLogInfoEntity;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
 * Created by wsl on 2022/7/4
 */
@Service
public class ManageSystemPushMessageService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SystemMessageDao systemMessageDao;
    @Autowired
    private BasePushRecordLogDao basePushRecordLogDao;
    @Autowired
    private BasePushrecordLogInfoDao basePushrecordLogInfoDao;
    /*   SELECT p.id,p.name  FROM base_patient p INNER JOIN wlyy_patient_device d ON p.id = d.`user`
    WHERE p.sign_status = 0 AND p.del = 1 AND d.del = 0 AND p.id NOT IN ( SELECT dict_code FROM `base`.`wlyy_hospital_sys_dict` WHERE `dict_name` = 'jkzl_older' OR dict_name = 'jkzl_child' )*/
    /**
     * 获取签约老人
     * @param name
     */
    public List<BasePatientDO> signOlds(String name) {
        String sql = "SELECT p.id,p.`name`,p.sex FROM  base_patient p " +
                " WHERE  p.sign_status = 1 AND p.del = 1  ";
        if (StringUtils.isNotBlank(name)) {
            sql += "and p.name like '%" + name + "%'";
        }
        sql += " AND p.id NOT IN ( SELECT dict_code FROM `base`.`wlyy_hospital_sys_dict` WHERE `dict_name` = 'jkzl_older' OR dict_name = 'jkzl_child' )";
        List<BasePatientDO> basePatientDOS = jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(BasePatientDO.class));
        return basePatientDOS;
    }
    /**
     * 新增消息推送
     *
     * @param content  自定义内容
     * @param pushObjectType  推送对象类型 1签约老人 2部分签约老人
     * @param pushObjectJson 推送对象
     * @param pushDateType  推送时间 1立即推送 2定时推送
     * @param pushDate
     */
    @Transactional(rollbackFor = Exception.class)
    public void addMessage(String content, Integer pushObjectType, String pushObjectJson, Integer pushDateType, String pushDate) {
        BasePushRecordLogEntity basePushRecordLogEntity = new BasePushRecordLogEntity();
        List<BasePatientDO> basePatientDOS = null;
        List<BasePushrecordLogInfoEntity> basePushrecordLogInfoEntityList = null;
        Date date =DateUtil.strToDate(pushDate);
        //判断发送对象类型  1签约老人  2 部分签约老人
        if (1 == pushObjectType) {
            basePatientDOS = signOlds("");
            basePushRecordLogEntity.setSendObjectType(1);
            basePushRecordLogEntity.setSendObject("签约老人");
        }else {
            basePatientDOS = JSONObject.parseArray(pushObjectJson, BasePatientDO.class);
            basePushRecordLogEntity.setSendObjectType(2);
            String s = nameStringHandle(basePatientDOS);
            basePushRecordLogEntity.setSendObject(s);
        }
        //判断 1立即发送   2定时发送
        if (1==pushDateType) {
            SystemMessageDOListSave(basePatientDOS,content);
            basePushRecordLogEntity.setStatus(1);
            basePushRecordLogEntity.setSendTime(new Date());
        }else {
            //创建定时任务记录
            basePatientDOS.forEach(logInfoDO->{
                String data = content;
                if (StringUtils.containsIgnoreCase(content,"【姓名】"))data.replace("【姓名】",logInfoDO.getName());
                if (StringUtils.containsIgnoreCase(content,"【称谓】"))data.replace("【称谓】",logInfoDO.getSex()==1?"大爷":"大妈");
                BasePushrecordLogInfoEntity basePushrecordLogInfoEntity = new BasePushrecordLogInfoEntity();
                basePushrecordLogInfoEntity.setPatient(logInfoDO.getId());
                basePushrecordLogInfoEntity.setContent(data);
                basePushrecordLogInfoEntity.setStatus(0);
                basePushrecordLogInfoEntity.setSendTime(date);
                basePushrecordLogInfoEntityList.add(basePushrecordLogInfoEntity);
            });
            basePushRecordLogEntity.setSendTime(date);
            basePushRecordLogEntity.setStatus(0);
        }
        //日志保存
        //basePushRecordLogEntity.setId(UUID.randomUUID().toString().replace("-", ""));
        basePushRecordLogEntity.setContent(content);
        basePushRecordLogEntity.setPushType("人工推送");
        basePushRecordLogEntity.setNum(basePatientDOS.size());
        basePushRecordLogDao.save(basePushRecordLogEntity);
        if (basePushrecordLogInfoEntityList.size()>0) {
            basePushrecordLogInfoEntityList.forEach(basePushLogInfoEntity -> basePushLogInfoEntity.setPushId(basePushRecordLogEntity.getId()));
        }
    }
    //获取列表
    public List<BasePushRecordLogEntity> pushMessageList(Integer messageType,Integer status,String name,Integer page,Integer pageSize){
        if(page==null){
            page = 1;
        }
        if(pageSize==null){
            pageSize = 10;
        }
        String sql = "SELECT * FROM base_pushrecord_log where 1=1 ";
        if(null!=messageType){
            sql +=" and message_type ='"+messageType+"' ";
        }
        if (null!=status) {
            sql +=" and status = '"+status+"'";
        }
        if (StringUtils.isNotBlank(name)){
            sql +=" and name send_object like '%"+name+"%'";
        }
        sql += " LIMIT  " + (page - 1) * pageSize + "," + pageSize + "";
        List<BasePushRecordLogEntity> entityList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BasePushRecordLogEntity.class));
        return entityList;
    }
    //删除
    @Transactional(rollbackFor = Exception.class)
    public void delPushMessageLog(String id){
        basePushRecordLogDao.delete(id);
    }
    private void SystemMessageDOListSave(List<BasePatientDO> basePatientDOS,String content){
        List<SystemMessageDO> messageDOS = new ArrayList<>();
        for (BasePatientDO basePatientDO : basePatientDOS) {
            String data = content;
            if (StringUtils.containsIgnoreCase(content,"【姓名】"))data.replace("【姓名】",basePatientDO.getName());
            if (StringUtils.containsIgnoreCase(content,"【称谓】"))data.replace("【称谓】",basePatientDO.getSex()==1?"大爷":"大妈");
            SystemMessageDO systemMessageDO = new SystemMessageDO();
            systemMessageDO.setId(UUID.randomUUID().toString().replace("-", ""));
            systemMessageDO.setTitle("系统消息推送");
            systemMessageDO.setType("999");
            systemMessageDO.setIsRead("0");
            systemMessageDO.setSender("system");
            systemMessageDO.setSenderName("人工推送助手");
            systemMessageDO.setReceiver(basePatientDO.getId());
            systemMessageDO.setReceiverName(basePatientDO.getName());
            systemMessageDO.setData(content);
            systemMessageDO.setOver("1");
            systemMessageDO.setDel("1");
            systemMessageDO.setCreateTime(new Date());
            messageDOS.add(systemMessageDO);
        }
        systemMessageDao.save(messageDOS);
    }
    //处理名字
    private String  nameStringHandle(List<BasePatientDO> basePatientDOS){
        String names = "";
        for (int i = 0; i < basePatientDOS.size(); i++) {
            BasePatientDO basePatientDO = basePatientDOS.get(i);
            String s = i == basePatientDOS.size()-1 ? "" : ",";
            names += basePatientDO.getName()+ s;
        }
        return names;
    }
}

+ 59 - 1
svr/svr-base/src/main/java/com/yihu/jw/base/service/device/DeviceManageService.java

@ -4,21 +4,29 @@ import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.base.dao.device.DeviceDao;
import com.yihu.jw.base.dao.device.DeviceDetailDao;
import com.yihu.jw.base.util.HttpClientUtilCare;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.mysql.query.BaseJpaService;
import jxl.Workbook;
import jxl.write.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import java.io.IOException;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * Created by Bing on 2021/9/22.
@ -208,4 +216,54 @@ public class DeviceManageService extends BaseJpaService<DeviceDetail,DeviceDetai
    }
    @Autowired
    private HttpClientUtilCare httpClientUtil;
    @Autowired
    private StringRedisTemplate redisTemplate;
    public static final String baseUrl = "http://api.aiqiangua.com:8888";// 正式环境
    public static final String deviceInfo = baseUrl +"/api/device/{0}";
    private static final String username = "13559485270";
    private static final String password = "zjxl@2021";
    private static final String redisKey = "aqgCooker";
    private static final String login = baseUrl +"/api/auth/login";
    private static final Long overTime = 23L;
    public com.alibaba.fastjson.JSONObject getAqgDeviceInfo2(String imei){
        synchronized (imei.intern()){
            try {
                String url = MessageFormat.format(deviceInfo, imei);
                HttpEntity<JSONObject> response = httpClientUtil.aqgCookieHttp(url, null, HttpMethod.GET, getCookie());
                com.alibaba.fastjson.JSONObject json = response.getBody();
                if(!json.getBoolean("success")){
                    return  null;
                }
                return json.getJSONObject("obj");
            }catch (Exception e){
                e.printStackTrace();
                return null;
            }
        }
    }
    /**
     * 获取爱牵挂管理员cookie
     */
    public synchronized String getCookie(){
        if(redisTemplate.hasKey(redisKey)){
            return redisTemplate.opsForValue().get(redisKey);
        }
        MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
        param.add("username",username);
        param.add("password",password);
        HttpEntity<com.alibaba.fastjson.JSONObject> response = httpClientUtil.cookiePostHttp(login,param);
        HttpHeaders responseHeaders = response.getHeaders();
        String cookie =  responseHeaders.get("Set-Cookie").get(0);
        redisTemplate.opsForValue().set(redisKey,cookie,overTime, TimeUnit.HOURS);
        return cookie;
    }
}

+ 687 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/util/HttpClientUtilCare.java

@ -0,0 +1,687 @@
package com.yihu.jw.base.util;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@Component
public class HttpClientUtilCare {
    /**
     * 发送post请求
     *
     * @param url     请求地址
     * @param params  请求参数
     * @param chatSet 编码格式
     * @return
     */
    public  String post(String url, List<NameValuePair> params, String chatSet) {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(params, chatSet);
            httppost.setEntity(uefEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, chatSet);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * 发送get请求
     *
     * @param url     请求地址
     * @param chatSet 编码格式
     * @return
     */
    public  String get(String url, String chatSet) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, chatSet);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            System.out.println(e.getClass()+"1");
            e.printStackTrace();
        } catch (ParseException e) {
            System.out.println(e.getClass()+"2");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println(e.getClass()+"3");
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public  String get(String url,List<NameValuePair> params, String chatSet) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.
            String entityString = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
            HttpGet httpget = new HttpGet(url+"?"+entityString);
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, chatSet);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * http调用方法,(健康之路开放平台)
     *
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String httpPost(String url, Map<String, String> params) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            if (params != null && params.size() > 0) {
                List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
                    valuePairs.add(nameValuePair);
                }
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(valuePairs, "UTF-8");
                httpPost.setEntity(formEntity);
            }
            CloseableHttpResponse resp = httpclient.execute(httpPost);
            try {
                HttpEntity entity = resp.getEntity();
                String respContent = EntityUtils.toString(entity, "UTF-8").trim();
                return respContent;
            } finally {
                resp.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            httpclient.close();
        }
    }
    /**
     * 获取加密后参数集合(健康之路开放平台)
     *
     * @param params
     * @return
     */
    public  Map<String, String> getSecretParams(Map<String, String> params, String appId, String secret) {
        String timestamp = Long.toString(System.currentTimeMillis());
        params.put("timestamp", timestamp);
        StringBuilder stringBuilder = new StringBuilder();
        // 对参数名进行字典排序  
        String[] keyArray = params.keySet().toArray(new String[0]);
        Arrays.sort(keyArray);
        // 拼接有序的参数名-值串  
        stringBuilder.append(appId);
        for (String key : keyArray) {
            stringBuilder.append(key).append(params.get(key));
        }
        String codes = stringBuilder.append(secret).toString();
        String sign = org.apache.commons.codec.digest.DigestUtils.shaHex(codes).toUpperCase();
        // 添加签名,并发送请求  
        params.put("appId", appId);
        params.put("sign", sign);
        return params;
    }
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL带上参数
     * @param param
     *            POST参数。
     * @return 所代表远程资源的响应结果
     */
    public static  String sendPost(String url, String param) {
        StringBuffer buffer = new StringBuffer();
        PrintWriter out = null;
        BufferedReader in = null;
        HttpURLConnection conn = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            osw.write(param.toString());
            osw.flush();
            // 读取返回内容
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
           e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return buffer.toString();
    }
    
    public static   String postBody(String url, JSONObject params) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
        String ret = restTemplate.postForObject(url, formEntity, String.class);
        return ret;
    }
    public static String postBodyHead(String url, JSONObject params, Map<String, Object> headerMap) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        for(String str:headerMap.keySet()){
            headers.add(str,headerMap.get(str).toString());
        }
        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
        String ret = restTemplate.postForObject(url, formEntity, String.class);
        return ret;
    }
    
    public  void putBody(String url, JSONObject params) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
        restTemplate.put(url, formEntity, String.class);
    }
    /**
     * 发送post请求
     *
     * @param url     请求地址
     * @param params  请求参数
     * @param chatSet 编码格式
     * @param headerMap 请求头
     * @return
     */
    public  String headerPost(String url, List<NameValuePair> params, String chatSet, Map<String,Object> headerMap) {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(params, chatSet);
            httppost.setEntity(uefEntity);
            for(String str:headerMap.keySet()){
                httppost.addHeader(str,headerMap.get(str).toString());
            }
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, chatSet);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public  String get(String url, String chatSet,Map<String,Object> headerMap) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.
            url= url.replaceAll(" ", "%20");
            HttpGet httpget = new HttpGet(url);
            for(String str:headerMap.keySet()){
                httpget.addHeader(str,headerMap.get(str).toString());
            }
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, chatSet);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * 原生字符串发送put请求
     *
     * @param url
     * @param token
     * @param jsonStr
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String doPut(String url, String token, String jsonStr) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpPut.setConfig(requestConfig);
        httpPut.setHeader("Content-type", "application/json");
        httpPut.setHeader("DataEncoding", "UTF-8");
        httpPut.setHeader("token", token);
        CloseableHttpResponse httpResponse = null;
        try {
            httpPut.setEntity(new StringEntity(jsonStr));
            httpResponse = httpClient.execute(httpPut);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    /**
     * 发送delete请求
     *
     * @param url
     * @param token
     * @param jsonStr
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String doDelete(String url, String token, String jsonStr) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpDelete = new HttpDelete(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpDelete.setConfig(requestConfig);
        httpDelete.setHeader("Content-type", "application/json");
        httpDelete.setHeader("DataEncoding", "UTF-8");
        httpDelete.setHeader("token", token);
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpDelete);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    public String postBodyRawForm(String url, String params) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        List<NameValuePair> pairs = new ArrayList<>(0);
        pairs.add(new BasicNameValuePair("object",params));
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(formEntity);
        CloseableHttpResponse response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String ret = EntityUtils.toString(entity);
        return ret;
    }
    public String getBodyRawForm(String url, String params) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        List<NameValuePair> pairs = new ArrayList<>(0);
        pairs.add(new BasicNameValuePair("object",params));
        String entityString = EntityUtils.toString(new UrlEncodedFormEntity(pairs,Consts.UTF_8));
        HttpGet httpGet = new HttpGet(url+"?"+entityString);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String ret = EntityUtils.toString(entity);
        return ret;
    }
    /**
     * 爱牵挂请求
     * @param url
     * @param params
     * @return
     */
    public org.springframework.http.HttpEntity<JSONObject> cookiePostHttp(String url,MultiValueMap<String, String> params){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/x-www-form-urlencoded");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        org.springframework.http.HttpEntity<MultiValueMap<String, String>> request = new org.springframework.http.HttpEntity<>(params, headers);
        org.springframework.http.HttpEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.POST, request, JSONObject.class);
        return response;
    }
    public org.springframework.http.HttpEntity<JSONObject> aqgCookieHttp(String url, MultiValueMap<String, String> params,HttpMethod method,String cookie) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/x-www-form-urlencoded");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("Cookie",cookie);
        org.springframework.http.HttpEntity<MultiValueMap<String, String>> request = new org.springframework.http.HttpEntity<>(params, headers);
        org.springframework.http.HttpEntity<JSONObject> response = restTemplate.exchange(url, method, request, JSONObject.class);
        return response;
    }
    public org.springframework.http.HttpEntity<JSONObject> assesTokenPostHttp(String url, JSONObject params,HttpMethod method){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType(MediaType.APPLICATION_JSON_VALUE);
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        org.springframework.http.HttpEntity<String> request = new org.springframework.http.HttpEntity<>(params.toString(), headers);
        org.springframework.http.HttpEntity<JSONObject> response = restTemplate.exchange(url, method, request, JSONObject.class);
        return response;
    }
    public  org.springframework.http.HttpEntity<JSONObject> iotAssesTokenPostHttp(String url, MultiValueMap<String, String> params,HttpMethod method){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        org.springframework.http.HttpEntity<MultiValueMap<String, String>> request = new org.springframework.http.HttpEntity<>(params, headers);
        org.springframework.http.HttpEntity<JSONObject> response = restTemplate.exchange(url, method, request, JSONObject.class);
        return response;
    }
    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @return URL 所代表远程资源的响应结果
     */
    public String sendGet(String url,Map<String,String> headerMap) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            if(headerMap!=null){
                for (String key:headerMap.keySet()){
                    connection.setRequestProperty(key, headerMap.get(key));
                }
            }
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL带上参数
     * @param param
     *            POST参数。
     * @return 所代表远程资源的响应结果
     */
    public String sendPost(String url, String param,Map<String,String> headerMap) {
        StringBuffer buffer = new StringBuffer();
        PrintWriter out = null;
        BufferedReader in = null;
        HttpURLConnection conn = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            if(headerMap!=null){
                for (String key:headerMap.keySet()){
                    conn.setRequestProperty(key, headerMap.get(key));
                }
            }
            OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            osw.write(param.toString());
            osw.flush();
            // 读取返回内容
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return buffer.toString();
    }
    public String postBodyAuthorization(String url, String token) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic "+token);
        headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        headers.add("Accept",MediaType.ALL_VALUE);
        String str = "grant_type=client_credentials";
        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(str, headers);
        String ret = restTemplate.postForObject(url, formEntity, String.class);
        return ret;
    }
}

+ 11 - 0
svr/svr-cloud-job/src/main/java/com/yihu/jw/care/dao/pushLog/BasePushRecordLogDao.java

@ -0,0 +1,11 @@
package com.yihu.jw.care.dao.pushLog;
import com.yihu.jw.entity.log.BasePushRecordLogEntity;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by wsl on 2022/7/4
 */
public interface BasePushRecordLogDao extends PagingAndSortingRepository<BasePushRecordLogEntity, String>, JpaSpecificationExecutor<BasePushRecordLogEntity> {
}

+ 12 - 0
svr/svr-cloud-job/src/main/java/com/yihu/jw/care/dao/pushLog/BasePushrecordLogInfoDao.java

@ -0,0 +1,12 @@
package com.yihu.jw.care.dao.pushLog;
import com.yihu.jw.entity.log.BasePushrecordLogInfoEntity;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by wsl on 2022/7/5
 */
public interface BasePushrecordLogInfoDao extends PagingAndSortingRepository<BasePushrecordLogInfoEntity, String>, JpaSpecificationExecutor<BasePushrecordLogInfoEntity> {
}

+ 47 - 10
svr/svr-cloud-job/src/main/java/com/yihu/jw/care/event/ApplicationEvent.java

@ -12,6 +12,7 @@ import com.yihu.jw.care.job.order.CancelPayOrderJob;
import com.yihu.jw.care.job.order.DailyWaterJob;
import com.yihu.jw.care.job.order.EmeWarnOrderDayJob;
import com.yihu.jw.care.job.order.EmeWarnOrderJob;
import com.yihu.jw.care.job.pushRecord.PushRecordJob;
import com.yihu.jw.care.job.sim.GetSimsVoiceFlowDayJob;
import com.yihu.jw.care.job.sim.GetSimsVoiceFlowMonthJob;
import com.yihu.jw.care.job.sim.UpdateSimsJob;
@ -134,7 +135,7 @@ public class ApplicationEvent implements ApplicationListener<ContextRefreshedEve
                quartzHelper.addJob(SaveDataPushJob.class, trigger, "SAVE_DATA_PUSH_JOB", new HashMap<String, Object>());
                logger.info("SAVE_DATA_PUSH_JOB success");
            }else {
                logger.info("SAVE_DATA_PUSH_JOB success");
                logger.info("SAVE_DATA_PUSH_JOB exist");
            }
            //定时查询移动平台物联卡信息
@ -143,7 +144,7 @@ public class ApplicationEvent implements ApplicationListener<ContextRefreshedEve
                quartzHelper.addJob(UpdateSimsJob.class, trigger, "UPDATE_SIMS_JOB", new HashMap<String, Object>());
                logger.info("UPDATE_SIMS_JOB success");
            }else {
                logger.info("UPDATE_SIMS_JOB success");
                logger.info("UPDATE_SIMS_JOB exist");
            }
            //定时查询移动平台物联卡信息--日
@ -152,7 +153,7 @@ public class ApplicationEvent implements ApplicationListener<ContextRefreshedEve
                quartzHelper.addJob(GetSimsVoiceFlowDayJob.class, trigger, "GET_SIMS_VOICE_FLOW_DAY_JOB", new HashMap<String, Object>());
                logger.info("GET_SIMS_VOICE_FLOW_DAY_JOB success");
            }else {
                logger.info("GET_SIMS_VOICE_FLOW_DAY_JOB success");
                logger.info("GET_SIMS_VOICE_FLOW_DAY_JOB exist");
            }
            //定时查询移动平台物联卡信息--月
@ -161,7 +162,7 @@ public class ApplicationEvent implements ApplicationListener<ContextRefreshedEve
                quartzHelper.addJob(GetSimsVoiceFlowMonthJob.class, trigger, "GET_SIMS_VOICE_FLOW_MONTH_JOB", new HashMap<String, Object>());
                logger.info("GET_SIMS_VOICE_FLOW_MONTH_JOB success");
            }else {
                logger.info("GET_SIMS_VOICE_FLOW_MONTH_JOB success");
                logger.info("GET_SIMS_VOICE_FLOW_MONTH_JOB exist");
            }
            //#每天早上10点发送血压(1天)血糖(7天)未测量通知
@ -170,7 +171,7 @@ public class ApplicationEvent implements ApplicationListener<ContextRefreshedEve
                quartzHelper.addJob(PressureGlucoseNotJob.class, trigger, "BLOOD_PRESSURE_GLUCOSE_NOT_MEASURED", new HashMap<String, Object>());
                logger.info("BLOOD_PRESSURE_GLUCOSE_NOT_MEASURED success");
            }else {
                logger.info("BLOOD_PRESSURE_GLUCOSE_NOT_MEASURED success");
                logger.info("BLOOD_PRESSURE_GLUCOSE_NOT_MEASURED exist");
            }
            //#生日祝福未发生记录
@ -179,7 +180,7 @@ public class ApplicationEvent implements ApplicationListener<ContextRefreshedEve
                quartzHelper.addJob(BirthdayWishesNotPushJob.class, trigger, "BIRTHDAY_WISHES_NOT_PUSH_JOB", new HashMap<String, Object>());
                logger.info("BIRTHDAY_WISHES_NOT_PUSH_JOB success");
            }else {
                logger.info("BIRTHDAY_WISHES_NOT_PUSH_JOB success");
                logger.info("BIRTHDAY_WISHES_NOT_PUSH_JOB exist");
            }
            //#智慧水表工单触发
@ -188,7 +189,7 @@ public class ApplicationEvent implements ApplicationListener<ContextRefreshedEve
                quartzHelper.addJob(DailyWaterJob.class, trigger, "DAILY_WATER_JOB", new HashMap<String, Object>());
                logger.info("DAILY_WATER_JOB success");
            }else {
                logger.info("DAILY_WATER_JOB success");
                logger.info("DAILY_WATER_JOB exist");
            }
            //#人脸库每天晚上3点跑一次
@ -197,7 +198,7 @@ public class ApplicationEvent implements ApplicationListener<ContextRefreshedEve
                quartzHelper.addJob(UpdPatientFaceJob.class, trigger, "DEVICE_DATA_FACE_JOB", new HashMap<String, Object>());
                logger.info("DEVICE_DATA_FACE_JOB success");
            }else {
                logger.info("DEVICE_DATA_FACE_JOB success");
                logger.info("DEVICE_DATA_FACE_JOB exist");
            }
            //#人脸记录每30分钟跑一次
@ -206,7 +207,7 @@ public class ApplicationEvent implements ApplicationListener<ContextRefreshedEve
                quartzHelper.addJob(SynPatientFaceRecordsJob.class, trigger, "SYN_FACE_RECORD_JOB", new HashMap<String, Object>());
                logger.info("SYN_FACE_RECORD_JOB success");
            }else {
                logger.info("SYN_FACE_RECORD_JOB success");
                logger.info("SYN_FACE_RECORD_JOB exist");
            }
            //同步人脸数据,每天8点跑一次
@ -215,7 +216,43 @@ public class ApplicationEvent implements ApplicationListener<ContextRefreshedEve
                quartzHelper.addJob(SynElectricRecordsJob.class, trigger, "SYN_ELECTRIC_RECORD_JOB", new HashMap<String, Object>());
                logger.info("SYN_ELECTRIC_RECORD_JOB success");
            }else {
                logger.info("SYN_ELECTRIC_RECORD_JOB success");
                logger.info("SYN_ELECTRIC_RECORD_JOB exist");
            }
            //定时更新推送记录
            if (!quartzHelper.isExistJob("PUSHRECORD_LOG_INFO_JOB")){
                String trigger = SystemConf.getInstance().getSystemProperties().getProperty("PUSHRECORD_LOG_INFO_JOB");
                quartzHelper.addJob(PushRecordJob.class,trigger,"PUSHRECORD_LOG_INFO_JOB",new HashMap<String, Object>() );
                logger.info("PUSHRECORD_LOG_INFO_JOB success");
            }else {
                logger.info("PUSHRECORD_LOG_INFO_JOB exist");
            }
            //设备离线推送居民
            if (!quartzHelper.isExistJob("PUSH_DEVICE_OFF_LONE_JOB")){
                String trigger = SystemConf.getInstance().getSystemProperties().getProperty("PUSH_DEVICE_OFF_LONE_JOB");
                quartzHelper.addJob(DeviceOffLoneJob.class,trigger,"PUSH_DEVICE_OFF_LONE_JOB",new HashMap<String, Object>() );
                logger.info("PUSH_DEVICE_OFF_LONE_JOB success");
            }else {
                logger.info("PUSH_DEVICE_OFF_LONE_JOB exist");
            }
            //手表未佩戴
            if (!quartzHelper.isExistJob("DEVICE_WATCH_OFF_WEAR_JOB")){
                String trigger = SystemConf.getInstance().getSystemProperties().getProperty("DEVICE_WATCH_OFF_WEAR_JOB");
                quartzHelper.addJob(DeviceOffLoneJob.class,trigger,"PUSH_DEVICE_OFF_LONE_JOB",new HashMap<String, Object>() );
                logger.info("PUSH_DEVICE_OFF_LONE_JOB success");
            }else {
                logger.info("PUSH_DEVICE_OFF_LONE_JOB exist");
            }
            //手表 报警器 合并 电量低
            if (!quartzHelper.isExistJob("DEVICE_WATCH_REMAINING_POWER_JOB")){
                String trigger = SystemConf.getInstance().getSystemProperties().getProperty("DEVICE_WATCH_REMAINING_POWER_JOB");
                quartzHelper.addJob(DeviceWatchRemainingPowerJob.class,trigger,"DEVICE_WATCH_REMAINING_POWER_JOB",new HashMap<String,Object>());
                logger.info("DEVICE_WATCH_REMAINING_POWER_JOB success");
            }else {
                logger.info("DEVICE_WATCH_REMAINING_POWER_JOB exist");
            }
        } catch (Exception e) {

+ 1 - 1
svr/svr-cloud-job/src/main/java/com/yihu/jw/care/job/device/DeviceLostAssociationJob.java

@ -27,7 +27,7 @@ public class DeviceLostAssociationJob implements Job {
        logger.info("DeviceLostAssociationJob start");
        try {
            patientDeviceService.selectAndUpdate();
            patientDeviceService.selectAndUpdate(true);
            logger.info("DeviceLostAssociationJob end");
        } catch (Exception e) {
            logger.info("DeviceLostAssociationJob --ERROR MSG:"+e.getMessage());

+ 34 - 0
svr/svr-cloud-job/src/main/java/com/yihu/jw/care/job/device/DeviceOffLoneJob.java

@ -0,0 +1,34 @@
package com.yihu.jw.care.job.device;
import com.yihu.jw.care.service.device.PatientDeviceService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
 * Created by wsl on 2022/7/6
 */
public class DeviceOffLoneJob implements Job {
    private static Logger logger = LoggerFactory.getLogger(DeviceOffLoneJob.class);
    @Autowired
    private PatientDeviceService patientDeviceService;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("DeviceOffLoneJob start");
        try {
            patientDeviceService.selectAndUpdate(false);
            logger.info("DeviceOffLoneJob end");
        } catch (Exception e) {
            logger.info("DeviceOffLoneJob --ERROR MSG:"+e.getMessage());
            e.printStackTrace();
        }
    }
}

+ 32 - 0
svr/svr-cloud-job/src/main/java/com/yihu/jw/care/job/device/DeviceWatchOffWearJob.java

@ -0,0 +1,32 @@
package com.yihu.jw.care.job.device;
import com.yihu.jw.care.service.device.PatientDeviceService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
 * Created by wsl on 2022/7/8
 */
public class DeviceWatchOffWearJob implements Job {
    private static Logger logger = LoggerFactory.getLogger(DeviceWatchOffWearJob.class);
    @Autowired
    private PatientDeviceService patientDeviceService;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("DeviceWatchOffWearJob start");
        try {
            patientDeviceService.deviceWatchWearInfo();
            logger.info("DeviceWatchOffWearJob end");
        } catch (Exception e) {
            logger.info("DeviceWatchOffWearJob --ERROR MSG:"+e.getMessage());
            e.printStackTrace();
        }
    }
}

+ 32 - 0
svr/svr-cloud-job/src/main/java/com/yihu/jw/care/job/device/DeviceWatchRemainingPowerJob.java

@ -0,0 +1,32 @@
package com.yihu.jw.care.job.device;
import com.yihu.jw.care.service.device.PatientDeviceService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
 * Created by wsl on 2022/7/8
 */
public class DeviceWatchRemainingPowerJob implements Job {
    private static Logger logger = LoggerFactory.getLogger(DeviceWatchRemainingPowerJob.class);
    @Autowired
    private PatientDeviceService patientDeviceService;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("DeviceWatchRemainingPowerJob start");
        try {
            patientDeviceService.deviceWatchRemainingPower();
            logger.info("DeviceWatchRemainingPowerJob end");
        } catch (Exception e) {
            logger.info("DeviceWatchRemainingPowerJob --ERROR MSG:"+e.getMessage());
            e.printStackTrace();
        }
    }
}

+ 81 - 0
svr/svr-cloud-job/src/main/java/com/yihu/jw/care/job/pushRecord/PushRecordJob.java

@ -0,0 +1,81 @@
package com.yihu.jw.care.job.pushRecord;
import com.yihu.jw.care.dao.pushLog.BasePushRecordLogDao;
import com.yihu.jw.care.dao.pushLog.BasePushrecordLogInfoDao;
import com.yihu.jw.care.util.DateUtil;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.log.BasePushRecordLogEntity;
import com.yihu.jw.entity.log.BasePushrecordLogInfoEntity;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
 * Created by wsl on 2022/7/6
 */
@DisallowConcurrentExecution
public class PushRecordJob implements Job {
    private static Logger logger = LoggerFactory.getLogger(PushRecordJob.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BasePushRecordLogDao basePushRecordLogDao;
    @Autowired
    private BasePushrecordLogInfoDao basePushrecordLogInfoDao;
    @Autowired
    private SystemMessageDao systemMessageDao;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        String sql = "SELECT * FROM base_pushrecord_log_info WHERE `status` = 0 AND sendTime <= '"+DateUtil.getNowDate()+"'";
        List<BasePushrecordLogInfoEntity> logInfoEntityList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BasePushrecordLogInfoEntity.class));
        List<SystemMessageDO> messageDOS = new ArrayList<>();
        if (logInfoEntityList.size()>0) {
            for (BasePushrecordLogInfoEntity basePushrecordLogInfoEntity : logInfoEntityList) {
                //记录表设置已发送
                basePushrecordLogInfoEntity.setStatus(1);
                //新增推送记录
                SystemMessageDO systemMessageDO = new SystemMessageDO();
                systemMessageDO.setId(UUID.randomUUID().toString().replace("-", ""));
                systemMessageDO.setTitle("系统消息推送");
                systemMessageDO.setType("999");
                systemMessageDO.setIsRead("0");
                systemMessageDO.setSender("system");
                systemMessageDO.setSenderName("人工推送助手");
                systemMessageDO.setReceiver(basePushrecordLogInfoEntity.getPatient());
                systemMessageDO.setReceiverName(basePushrecordLogInfoEntity.getPatientName());
                systemMessageDO.setContent(basePushrecordLogInfoEntity.getContent());
                systemMessageDO.setOver("1");
                systemMessageDO.setDel("1");
                systemMessageDO.setCreateTime(new Date());
                messageDOS.add(systemMessageDO);
            }
            String basePushLogSatusSql = "select * from base_pushrecord_log where id = '"+logInfoEntityList.get(0).getPushId()+"' ";
            BasePushRecordLogEntity logEntity = jdbcTemplate.queryForObject(basePushLogSatusSql, new BeanPropertyRowMapper<>(BasePushRecordLogEntity.class));
            logEntity.setStatus(1);
            basePushRecordLogDao.save(logEntity);
            systemMessageDao.save(messageDOS);
            basePushrecordLogInfoDao.save(logInfoEntityList);
        }
    }
}

+ 132 - 2
svr/svr-cloud-job/src/main/java/com/yihu/jw/care/service/device/PatientDeviceService.java

@ -1,6 +1,7 @@
package com.yihu.jw.care.service.device;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.config.AqgConfig;
import com.yihu.jw.care.dao.device.DeviceDao;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
@ -25,6 +26,7 @@ import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import javax.annotation.PostConstruct;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
@ -234,7 +236,7 @@ public class PatientDeviceService {
    /**************************************物联网检测大屏失联率start************************************************/
    @Transactional
    public void selectAndUpdate(){
    public void selectAndUpdate(Boolean flag){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endTime = sdf.format(new Date());
        Calendar device1 = Calendar.getInstance();
@ -294,8 +296,136 @@ public class PatientDeviceService {
        }
        if (lostSN.size()>0){
            wlyyDeviceDao.updateByContactStatus(0,new Date(),lostSN);
            deviceLostMessageUtil.deviceLostMessage(lostSN);
            if (flag){
                deviceLostMessageUtil.deviceLostMessage(lostSN);
            }else {
                deviceLostMessageUtil.deviceLostMessagePatient(lostSN);
            }
        }
    }
    //爱牵挂手表离线设备获取
    public void deviceWatchWearInfo() {
        List<JSONObject> rslist = new ArrayList();
        try {
            //获取居民所有手表
            String deviceWatchSql = "SELECT p.id,p.`name`,p.sex,d.device_sn,p.photo FROM base_patient p INNER JOIN wlyy_patient_device d ON p.id = d.`user` WHERE category_code = 4 AND p.del = 1 ";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(deviceWatchSql);
            for (Map<String, Object> map : list) {
                JSONObject patients = new JSONObject();
                JSONObject response = getAqgDeviceInfo2(map.get("device_sn").toString());
                if (response.containsKey("wear_flag") && response.get("wear_flag") != null && 1 == response.getInteger("wear_flag")) {
                    //String a = 1 == response.getInteger("wear_flag") ? "未佩戴" : "已佩戴";
                    //System.out.println(a + map.get("name"));
                    patients.put("patient",map.get("id"));
                    patients.put("name",map.get("name"));
                    patients.put("sex",map.get("sex"));
                    rslist.add(patients);
                }
                Thread.sleep(1000);
            }
            if (rslist.size()>0) {
                deviceLostMessageUtil.watchOffWear(rslist);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //爱牵挂手表 报警器 电量获取判断
    public void  deviceWatchRemainingPower(){
        try {
            List<JSONObject> rslist = new ArrayList();
            String deviceWatchSql = "SELECT p.id,p.`name`,p.sex,d.device_sn,p.photo,d.category_code FROM base_patient p INNER JOIN wlyy_patient_device d ON p.id = d.`user` WHERE category_code in (4,7) AND p.del = 1 ";
            List<Map<String, Object>> patientList = jdbcTemplate.queryForList(deviceWatchSql);
            for (Map<String, Object> map : patientList) {
                JSONObject response = getAqgDeviceInfo2(map.get("device_sn").toString());
                if (response.containsKey("remaining_power") && response.get("remaining_power") != null&&response.getInteger("remaining_power")<=20){
                    JSONObject patients = new JSONObject();
                    patients.put("patient",map.get("id"));
                    patients.put("name",map.get("name"));
                    patients.put("sex",map.get("sex"));
                    patients.put("photo",map.get("photo"));
                    patients.put("category_code",map.get("category_code"));
                    rslist.add(patients);
                }
                Thread.sleep(1000);
            }
            if (rslist.size()>0) {
                deviceLostMessageUtil.watchRemainingPower(rslist);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   /* //爱牵挂报警器电量获取判断
    public void deviceSoSAlarmRemainIngPower() {
        try {
            List<JSONObject> rslist = new ArrayList();
            String deviceWatchSql = "SELECT p.id,p.`name`,p.sex,d.device_sn,p.photo FROM base_patient p INNER JOIN wlyy_patient_device d ON p.id = d.`user` WHERE category_code = 7 AND p.del = 1 ";
            List<Map<String, Object>> patientList = jdbcTemplate.queryForList(deviceWatchSql);
            for (Map<String, Object> map : patientList) {
                JSONObject response = getAqgDeviceInfo2(map.get("device_sn").toString());
                if (response.containsKey("remaining_power") && response.get("remaining_power") != null && response.getInteger("remaining_power") <= 20) {
                    JSONObject patients = new JSONObject();
                    patients.put("patient", map.get("id"));
                    patients.put("name", map.get("name"));
                    patients.put("sex", map.get("sex"));
                    rslist.add(patients);
                }
                Thread.sleep(1000);
            }
            if (rslist.size() > 0) {
                deviceLostMessageUtil.sosAlarmRemainIngPower(rslist);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
    public static final String baseUrl = "http://api.aiqiangua.com:8888";// 正式环境
    public static final String deviceInfo = baseUrl +"/api/device/{0}";
    private static final String username = "13559485270";
    private static final String password = "zjxl@2021";
    private static final String redisKey = "aqgCooker";
    private static final String login = baseUrl +"/api/auth/login";
    private static final Long overTime = 23L;
    public com.alibaba.fastjson.JSONObject getAqgDeviceInfo2(String imei){
        synchronized (imei.intern()){
            try {
                String url = MessageFormat.format(deviceInfo, imei);
                HttpEntity<JSONObject> response = httpClientUtil.aqgCookieHttp(url, null, HttpMethod.GET, getCookie());
                com.alibaba.fastjson.JSONObject json = response.getBody();
                if(!json.getBoolean("success")){
                    return  null;
                }
                return json.getJSONObject("obj");
            }catch (Exception e){
                e.printStackTrace();
                return null;
            }
        }
    }
}

+ 312 - 2
svr/svr-cloud-job/src/main/java/com/yihu/jw/care/util/DeviceLostMessageUtil.java

@ -2,15 +2,17 @@ package com.yihu.jw.care.util;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.dao.pushLog.BasePushRecordLogDao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.log.BasePushRecordLogEntity;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.rm.base.BaseRequestMapping;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@ -37,9 +39,12 @@ public class DeviceLostMessageUtil {
    private MessageUtil messageUtil;
    @Value("${wechat.id}")
    private String wxId;
    @Autowired
    BasePushRecordLogDao basePushRecordLogDao;
    /**
     * 设备离线通知
     * 设备离线通知--家属 、社工、助老元
     * @param devices
     */
    public void deviceLostMessage(List<String> devices){
@ -139,4 +144,309 @@ public class DeviceLostMessageUtil {
            systemMessageDao.save(messageDOS);
        }
    }
    /**
     * 设备离通知-用户自己
     * @param devices
     */
    public void deviceLostMessagePatient(List<String> devices){
        List<SystemMessageDO> messageDOS = new ArrayList<>();
        String content = "{name}{sex}您好,您的{device}设备已离线,请保持设备连接通畅。";
        String sql = " SELECT p.id,p.name,p.sex,GROUP_CONCAT( DISTINCT d.device_sn SEPARATOR ',' ) deviceSn,p.photo " +
                " FROM base_patient p INNER JOIN wlyy_patient_device d ON p.id = d.`user` " +
                " WHERE p.sign_status = 1  AND  p.del = 1  AND d.del = 0 " +
                " AND p.id NOT IN ( SELECT dict_code FROM `base`.`wlyy_hospital_sys_dict` WHERE `dict_name` = 'jkzl_older' OR dict_name = 'jkzl_child' ) GROUP BY p.id ";
        List<Map<String,Object>> patientList = jdbcTemplate.queryForList(sql);
        //所有居民的设备
        for (Map<String, Object> patient : patientList) {
            String deviceSns = patient.get("deviceSn").toString();
            String[] deviceSplit = deviceSns.split(",");
            String deivceName = "";
            for (String deviceSn : deviceSplit) {
                //离线的设备  offLineDevice
                for (String offLineDeviceSn : devices) {
                    if (deviceSn.equals(offLineDeviceSn)) {
                        List<SystemMessageDO> sendMessageBefore = systemMessageDao.queryByRelationCodeAndTypeIn(offLineDeviceSn,new String[]{"43"});
                        if (sendMessageBefore.size()>0){//删除之前的离线消息
                            systemMessageDao.delete(sendMessageBefore);
                        }
                        String deviceInfoSql = "SELECT device_sn,device_name,category_code FROM wlyy_patient_device WHERE device_sn = '"+offLineDeviceSn+"'";
                        DevicePatientDevice devicePatientDevice = jdbcTemplate.queryForObject(deviceInfoSql, new BeanPropertyRowMapper<>(DevicePatientDevice.class));
                        if (StringUtils.isNotBlank(deivceName)){
                            deivceName+=devicePatientDevice.getDeviceName();
                        }else {
                            deivceName+=","+devicePatientDevice.getAgentName();
                        }
                    }
                }
            }
            if (StringUtils.isNotBlank(deivceName)){
                String sContent = content;
                sContent = sContent.replace("{name}",patient.get("name").toString());
                sContent = sContent.replace("{sex}",Integer.parseInt(patient.get("sex").toString())==1?"大爷":"大妈");
                sContent = sContent.replace("{device}",deivceName);
                SystemMessageDO messageDO = new SystemMessageDO();
                messageDO.setTitle("设备离线通知");
                messageDO.setContent(sContent);
                messageDO.setType("994");
                messageDO.setIsRead("0");
                messageDO.setSender("system");
                messageDO.setSenderName("设备离线通知助手");
                messageDO.setReceiver(patient.get("id").toString());
                messageDO.setReceiverName(patient.get("name").toString());
                messageDO.setOver("1");
               // messageDO.setData(deviceName+"离线");
                messageDO.setDel("1");
                messageDO.setCreateTime(new Date());
                messageDO.setSenderPhoto(patient.get("photo").toString());
                messageDOS.add(messageDO);
            }
        }
        if (messageDOS.size()>0){
            BasePushRecordLogEntity logEntity = new BasePushRecordLogEntity();
            logEntity.setContent(content);
            logEntity.setPushType("1");
            logEntity.setSendTime(new Date());
            logEntity.setNum(messageDOS.size());
            logEntity.setStatus(1);
            logEntity.setCreateTime(new Date());
            logEntity.setSendObjectType(2);
            logEntity.setSendObject(nameStringUtil(patientList, 1));
            logEntity.setMessageType(6);
            systemMessageDao.save(messageDOS);
            basePushRecordLogDao.save(logEntity);
            systemMessageDao.save(messageDOS);
        }
    }
    /**
     * 手表未佩戴居民通知
     * @param patientList
     */
    public void watchOffWear(List<JSONObject> patientList){
        List<SystemMessageDO> messageDOS = new ArrayList<>();
        String contentOne = "{name}{sex} 监测到您没有佩戴手表,建议正确佩戴手表,方便我们对您进行照护。";
        for (JSONObject jsonObject : patientList) {
            SystemMessageDO messageDO = new SystemMessageDO();
            String contentTwo = contentOne;
            contentTwo = contentTwo.replace("{name}",jsonObject.getString("name"));
            contentTwo.replace("{sex}",1==jsonObject.getInteger("sex")?"大爷":"大妈");
            messageDO.setTitle("设备未佩戴通知");
            messageDO.setContent(contentTwo);
            messageDO.setType("991");
            messageDO.setIsRead("0");
            messageDO.setSender("system");
            messageDO.setSenderName("设备未佩戴通知助手");
            messageDO.setReceiver(jsonObject.getString("patient"));
            messageDO.setReceiverName(jsonObject.getString("name"));
            messageDO.setOver("1");
            // messageDO.setData(deviceName+"离线");
            messageDO.setDel("1");
            messageDO.setCreateTime(new Date());
            messageDO.setSenderPhoto(jsonObject.getString("photo"));
            messageDOS.add(messageDO);
        }
        if (messageDOS.size() > 0) {
            BasePushRecordLogEntity logEntity = new BasePushRecordLogEntity();
            logEntity.setContent(contentOne);
            logEntity.setPushType("1");
            logEntity.setSendTime(new Date());
            logEntity.setNum(messageDOS.size());
            logEntity.setStatus(1);
            logEntity.setCreateTime(new Date());
            logEntity.setSendObjectType(2);
            logEntity.setSendObject(nameStringUtil(patientList, 2));
            logEntity.setMessageType(3);
            systemMessageDao.save(messageDOS);
            basePushRecordLogDao.save(logEntity);
        }
    }
    /**
     * 手表 报警器 电量低通知
     * @param patientList
     */
    public void watchRemainingPower(List<JSONObject> patientList){
        List<SystemMessageDO> messageDOSWatch = new ArrayList<>();
        List<SystemMessageDO> messageDOSSOS = new ArrayList<>();
        String watchContent = "手表电量低,请充电";
        String SosContent = "报警器电量低,请充电";
        Integer watchSize = 0;
        String watchName = "";
        Integer SOSSize = 0;
        String SOSName = "";
        //推送消息保存
        for (JSONObject jsonObject : patientList) {
            switch (jsonObject.getInteger("category_code")){
                case 4:
                    SystemMessageDO messageDOWatch = new SystemMessageDO();
                    messageDOWatch.setTitle("设备电量低通知");
                    messageDOWatch.setContent(watchContent);
                    messageDOWatch.setType("992");
                    messageDOWatch.setIsRead("0");
                    messageDOWatch.setSender("system");
                    messageDOWatch.setSenderName("设备电量通知助手");
                    messageDOWatch.setReceiver(jsonObject.getString("patient"));
                    messageDOWatch.setReceiverName(jsonObject.getString("name"));
                    messageDOWatch.setOver("1");
                    // messageDO.setData(deviceName+"离线");
                    messageDOWatch.setDel("1");
                    messageDOWatch.setCreateTime(new Date());
                    messageDOWatch.setSenderPhoto(jsonObject.getString("photo"));
                    messageDOSWatch.add(messageDOWatch);
                    watchSize+=1;
                    if (StringUtils.isNotBlank(watchName)){
                        watchName+=","+jsonObject.getString("patient");
                    }else {
                        watchName+=jsonObject.getString("patient");
                    }
                    break;
                case 7:
                    SystemMessageDO messageDO = new SystemMessageDO();
                    messageDO.setTitle("设备电量低通知");
                    messageDO.setContent(SosContent);
                    messageDO.setType("993");
                    messageDO.setIsRead("0");
                    messageDO.setSender("system");
                    messageDO.setSenderName("设备电量通知助手");
                    messageDO.setReceiver(jsonObject.getString("patient"));
                    messageDO.setReceiverName(jsonObject.getString("name"));
                    messageDO.setOver("1");
                    // messageDO.setData(deviceName+"离线");
                    messageDO.setDel("1");
                    messageDO.setCreateTime(new Date());
                    messageDO.setSenderPhoto(jsonObject.getString("photo"));
                    messageDOSSOS.add(messageDO);
                    SOSSize+=1;
                    if (StringUtils.isNotBlank(SOSName)){
                        SOSName+=","+jsonObject.getString("patient");
                    }else {
                        SOSName+=jsonObject.getString("patient");
                    }
                    break;
            }
        }
        if (messageDOSWatch.size() > 0) {
            BasePushRecordLogEntity logEntity = new BasePushRecordLogEntity();
            logEntity.setContent(watchContent);
            logEntity.setPushType("1");
            logEntity.setSendTime(new Date());
            logEntity.setNum(watchSize);
            logEntity.setStatus(1);
            logEntity.setCreateTime(new Date());
            logEntity.setSendObjectType(2);
            logEntity.setSendObject(nameStringUtil(patientList, 2));
            logEntity.setMessageType(4);
            systemMessageDao.save(messageDOSWatch);
            basePushRecordLogDao.save(logEntity);
        }
        if (messageDOSSOS.size() > 0) {
            BasePushRecordLogEntity logEntity = new BasePushRecordLogEntity();
            logEntity.setContent(SosContent);
            logEntity.setPushType("1");
            logEntity.setSendTime(new Date());
            logEntity.setNum(SOSSize);
            logEntity.setStatus(1);
            logEntity.setCreateTime(new Date());
            logEntity.setSendObjectType(2);
            logEntity.setSendObject(nameStringUtil(patientList, 2));
            logEntity.setMessageType(5);
            systemMessageDao.save(messageDOSSOS);
            basePushRecordLogDao.save(logEntity);
        }
    }
    /*public void sosAlarmRemainIngPower(List<JSONObject> patientList){
        List<SystemMessageDO> messageDOS = new ArrayList<>();
        String contentOne = "报警器电量低,请充电";
        for (JSONObject jsonObject : patientList) {
            SystemMessageDO messageDO = new SystemMessageDO();
            messageDO.setTitle("设备电量低通知");
            messageDO.setContent(contentOne);
            messageDO.setType("993");
            messageDO.setIsRead("0");
            messageDO.setSender("system");
            messageDO.setSenderName("设备电量通知助手");
            messageDO.setReceiver(jsonObject.getString("patient"));
            messageDO.setReceiverName(jsonObject.getString("name"));
            messageDO.setOver("1");
            // messageDO.setData(deviceName+"离线");
            messageDO.setDel("1");
            messageDO.setCreateTime(new Date());
            messageDO.setSenderPhoto(jsonObject.getString("photo"));
            messageDOS.add(messageDO);
        }
        if (messageDOS.size() > 0) {
            BasePushRecordLogEntity logEntity = new BasePushRecordLogEntity();
            logEntity.setContent(contentOne);
            logEntity.setPushType("1");
            logEntity.setSendTime(new Date());
            logEntity.setNum(messageDOS.size());
            logEntity.setStatus(1);
            logEntity.setCreateTime(new Date());
            logEntity.setSendObjectType(2);
            logEntity.setSendObject(nameStringUtil(patientList, 2));
            logEntity.setMessageType(5);
            systemMessageDao.save(messageDOS);
            basePushRecordLogDao.save(logEntity);
        }
    }*/
    //处理名字  type = 1  List<Map<String,Object>>  type=2 List<JSONObject>
    private String nameStringUtil(List list, Integer type) {
        String names = "";
        if (type == 1) {
            List<Map<String,Object>> patients = list;
            for (int i = 0; i < patients.size(); i++) {
                String name =patients.get(i).get("name").toString();
                if (StringUtils.isNotBlank(names)) {
                    names += name;
                } else {
                    names += "," + name;
                }
            }
        } else if (type == 2) {
            List<JSONObject> patients = list;
            for (int i = 0; i < patients.size(); i++) {
                String name = patients.get(i).getString("name");
                if (StringUtils.isNotBlank(names)) {
                    names += name;
                } else {
                    names += "," + name;
                }
            }
        }
        return names;
    }
}

+ 9 - 1
svr/svr-cloud-job/src/main/resources/system.properties

@ -37,4 +37,12 @@ DEVICE_DATA_FACE_JOB= 0 0 3 * * ? *
#\u4EBA\u8138\u8BB0\u5F55\u6BCF30\u5206\u949F\u8DD1\u4E00\u6B21
SYN_FACE_RECORD_JOB= 0 0/30 * * * ? *
#\u7535\u8868\u6BCF\u5929\u65E9\u4E0A\u4E0A8\u70B9\u8DD1\u4E00\u6B21
SYN_ELECTRIC_RECORD_JOB= 0 0 3 * * ? *
SYN_ELECTRIC_RECORD_JOB= 0 0 3 * * ? *
#\u63A8\u9001\u8BB0\u5165\u624B\u52A8\u5B9A\u65F6 \u6BCF\u4E94\u5206\u949F\u8DD1\u4E00\u6B21
PUSHRECORD_LOG_INFO_JOB= 0 0/5 * * * ? *
#\u6BCF\u5929\u65E9\u4E0A\u4E5D\u70B9\u534A\u8DD1\u4E00\u6B21
PUSH_DEVICE_OFF_LONE_JOB = 0 30 9 * * ?
#\u6BCF\u5929\u65E9\u4E0A\u5341\u4E00\u70B9 \u624B\u8868\u4F69\u6234\u63D0\u9192
DEVICE_WATCH_OFF_WEAR_JOB = 0 0 11 * * ?
#\u624B\u8868\u7535\u91CF\u4F4E  \u6BCF\u4E00\u4E2A\u5C0F\u65F6\u83B7\u53D6\u4E00\u6B21 \u7535\u91CF
DEVICE_WATCH_REMAINING_POWER_JOB = 0 0 0/1 * * ? 

+ 1 - 1
svr/svr-iot/src/main/resources/bootstrap.yml

@ -1,6 +1,6 @@
spring:
  application:
    name:  svr-iot-wsl
    name:  svr-iot
  cloud:
    config:
      failFast: true