Browse Source

Merge branch 'dev' of http://192.168.1.220:10080/Amoy2/wlyy2.0 into dev

wangzhinan 3 years ago
parent
commit
59170aedbe
57 changed files with 3337 additions and 701 deletions
  1. 6 0
      business/base-service/src/main/java/com/yihu/jw/patient/dao/BasePatientDao.java
  2. 69 2
      common/common-entity/sql记录
  3. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/BasePatientOutBed.java
  4. 10 1
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/BaseSleepNightRecord.java
  5. 77 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/BaseSleepPlan.java
  6. 191 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/BaseSleepPlanDetail.java
  7. 10 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceDetail.java
  8. 65 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceHealthIndex.java
  9. 37 1
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DevicePatientDevice.java
  10. 9 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DevicePatientHealthIndex.java
  11. 37 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/HvDeviceRecord.java
  12. 130 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/HvDeviceSosLog.java
  13. 10 1
      common/common-entity/src/main/java/com/yihu/jw/entity/care/securitymonitoring/SecurityMonitoringOrderDO.java
  14. 19 0
      common/common-util/src/main/java/com/yihu/jw/util/date/DateUtil.java
  15. 9 0
      svr/svr-cloud-care/pom.xml
  16. 4 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/config/AqgConfig.java
  17. 16 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/BaseSleepPlanDao.java
  18. 2 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/DeviceDetailDao.java
  19. 4 1
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/DevicePatientHealthIndexDao.java
  20. 4 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/PatientDeviceDao.java
  21. 0 10
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/assistance/EmergencyAssistanceEndpoint.java
  22. 31 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/DoctorHealthController.java
  23. 139 9
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/PadDeviceController.java
  24. 36 3
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/PatientDeviceController.java
  25. 1 1
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/message/DoctorMessageEndpoint.java
  26. 49 4
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/statistics/DetectionPlatformEndpoint.java
  27. 14 2
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/assistance/EmergencyAssistanceService.java
  28. 2 5
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/birthday/BirthdayWishesService.java
  29. 85 2
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/PatientDeviceService.java
  30. 26 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/PatientHealthIndexService.java
  31. 2 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/lifeCare/LifeCareOrderService.java
  32. 14 6
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/message/DoctorMessageService.java
  33. 7 3
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/patient/CarePatientService.java
  34. 198 146
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/security/SecurityMonitoringOrderService.java
  35. 1 1
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/sign/ArchiveService.java
  36. 214 3
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/statistics/DetectionPlatformService.java
  37. 250 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/ArtemisPostTest.java
  38. 60 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/Tools.java
  39. 5 17
      svr/svr-cloud-device/pom.xml
  40. 19 0
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/dao/device/BaseSleepPlanDao.java
  41. 16 0
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/dao/device/BaseSleepPlanDetailDao.java
  42. 3 0
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/dao/device/DeviceDetailDao.java
  43. 16 0
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/dao/device/DeviceHealthIndexDao.java
  44. 15 0
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/dao/device/HvDeviceRecordDao.java
  45. 16 0
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/dao/device/HvDeviceSosLogDao.java
  46. 125 2
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/DeviceController.java
  47. 17 0
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/DeviceUploadController.java
  48. 153 0
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/HvDeviceController.java
  49. 84 84
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/SocketClientTest.java
  50. 103 103
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/SocketServerTest.java
  51. 151 151
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/WebSocketServer.java
  52. 199 80
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/service/DeviceService.java
  53. 17 2
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/service/DeviceUploadService.java
  54. 180 0
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/service/HvDeviceService.java
  55. 69 60
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/service/YsDeviceService.java
  56. 250 0
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/util/ArtemisPostTest.java
  57. 60 0
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/util/Tools.java

+ 6 - 0
business/base-service/src/main/java/com/yihu/jw/patient/dao/BasePatientDao.java

@ -34,6 +34,12 @@ public interface BasePatientDao extends PagingAndSortingRepository<BasePatientDO
    @Query("from BasePatientDO where mobile = ?1")
    List<BasePatientDO> findByMobile(String mobile);
    @Query("from BasePatientDO where del = 1")
    List<BasePatientDO> findAllByDel();
    @Query("from BasePatientDO where del = 1 and id = ?1")
    List<BasePatientDO> findAllByDelAndId(String user);
    @Query("from BasePatientDO p where p.mobile = ?1 and p.del=?2")
    List<BasePatientDO> findByMobileAndDel(String mobile,String del);
    

+ 69 - 2
common/common-entity/sql记录

@ -1287,7 +1287,7 @@ CREATE TABLE `base_sleep_night_record` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='睡眠带起夜记录数据';
-- 20210818 lb
CREATE TABLE base_patient_out_bed (
CREATE TABLE base_sleep_patient_out_bed (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `patient` varchar(50) DEFAULT NULL COMMENT '居民id',
  `device_sn` varchar(50) DEFAULT NULL COMMENT '睡眠带sn',
@ -1308,4 +1308,71 @@ CREATE TABLE `base_patient_add` (
  `team_code` varchar(255) DEFAULT NULL COMMENT '签约团队code',
  `del` int(1) DEFAULT '1' COMMENT '1有效  0失效',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 2021-08-23 气感烟感设备
CREATE TABLE `base_device_health_index` (
  `id` varchar(50) NOT NULL,
  `device_sn` varchar(50) DEFAULT NULL COMMENT '设备sn',
  `device_type` varchar(4) DEFAULT NULL COMMENT '设备类型 1气感 2烟感',
  `value` varchar(20) DEFAULT NULL COMMENT '测量值',
  `unit` varchar(20) DEFAULT NULL COMMENT '单位',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `record_time` varchar(50) DEFAULT NULL COMMENT '记录时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='烟感气感实时数据';
CREATE TABLE `base_hvdevice_record` (
  `id` varchar(50) NOT NULL,
  `device_id` varchar(50) DEFAULT NULL COMMENT '海康平台设备id',
  `device_sn` varchar(50) DEFAULT NULL COMMENT '设备sn',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='海康烟感气感设备记录表';
CREATE TABLE `base_hvdevice_sos_log` (
  `id` varchar(50) NOT NULL,
  `resource_id` varchar(50) DEFAULT NULL,
  `resource_serial` varchar(50) DEFAULT NULL,
  `resource_name` varchar(50) DEFAULT NULL,
  `alarm_num` int(10) DEFAULT NULL,
  `alarm_time` varchar(50) DEFAULT NULL,
  `monitor_value` varchar(50) DEFAULT NULL,
  `alarm_type` varchar(20) DEFAULT NULL,
  `system_type` varchar(20) DEFAULT NULL,
  `alarm_id` varchar(50) DEFAULT NULL,
  `resource_type` varchar(50) DEFAULT NULL,
  `location` varchar(500) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='烟感气感设备报警日志记录表';
-- 2021-08-23 已执行
ALTER table `base`.`wlyy_devices` add column `device_type` tinyint(2) DEFAULT NULL COMMENT '设备种类 0健康设备 1安防设备'
-- 20210819
alter table wlyy_devices add COLUMN device_type TINYINT(2) default null COMMENT '设备种类 0健康设备 1安防设备';
alter table wlyy_patient_device add COLUMN device_type TINYINT(2) default null COMMENT '设备种类 0健康设备 1安防设备';
-- 20210823
alter table base_sleep_night_record add COLUMN day varchar(50) DEFAULT NULL COMMENT '睡眠监控日期';
CREATE TABLE `base_sleep_plan_detail` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `patient` varchar(50) DEFAULT NULL COMMENT '居民id',
  `device_sn` varchar(50) DEFAULT NULL COMMENT '睡眠带sn',
  `day` varchar(50) DEFAULT NULL COMMENT '睡眠监控日期',
  `up_status` tinyint(2) DEFAULT NULL COMMENT '起床状态 0未起床 1起床',
  `up_time` timestamp NULL DEFAULT NULL COMMENT '起床时间',
  `siesta_status` tinyint(2) DEFAULT NULL COMMENT '午睡状态 0未入床 1已入床 2无午睡计划',
  `siesta_time_begin` timestamp NULL DEFAULT NULL COMMENT '午睡开始时间',
  `siesta_time_end` timestamp NULL DEFAULT NULL COMMENT '午睡结束时间',
  `siesta_long` varchar(10) DEFAULT NULL COMMENT '午睡时长 单位秒',
  `in_status` varchar(10) DEFAULT NULL COMMENT '睡觉状态 0未入床 1已入床',
  `in_time_begin` timestamp null DEFAULT NULL COMMENT '夜眠开始时间',
  `in_time_end` timestamp null DEFAULT NULL COMMENT '夜眠结束时间 ',
  `create_time` timestamp NULL DEFAULT NULL COMMENT '创建日期',
  `update_time` timestamp NULL DEFAULT NULL COMMENT '更新日期',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='睡眠带监测计划详情';
-- 20210824
alter table base_security_monitoring_order add COLUMN warn_info varchar(3000) DEFAULT NULL COMMENT '触发工单时信息如 烟雾心率等';

+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/BasePatientOutBed.java

@ -11,7 +11,7 @@ import java.util.Date;
 * Created by Bing on 2021/8/18.
 */
@Entity
@Table(name="base_patient_out_bed")
@Table(name="base_sleep_patient_out_bed")
public class BasePatientOutBed extends IdEntity {
    private String patient ;
    private String deviceSn;

+ 10 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/BaseSleepNightRecord.java

@ -15,8 +15,9 @@ import java.util.Date;
public class BaseSleepNightRecord extends IdEntity {
    private String patient ;
    private String deviceSn;
    private String outTime;//离床时长
    private String outTime;//离床时长 秒
    private Integer status;//是否回床 0否,1是
    private String day;//监控日期
    private Date createTime;// 创建日期 即起床时间
    private Date updateTime;// 更新日期
@ -52,6 +53,14 @@ public class BaseSleepNightRecord extends IdEntity {
        this.status = status;
    }
    public String getDay() {
        return day;
    }
    public void setDay(String day) {
        this.day = day;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;

+ 77 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/BaseSleepPlan.java

@ -0,0 +1,77 @@
package com.yihu.jw.entity.care.device;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
import java.util.List;
/***
 * @ClassName: BaseSleepPlan
 * @Description:    睡眠带监测计划
 * @Auther: shi kejing
 * @Date: 2021/8/23 17:17
 */
@Entity
@Table(name="base_sleep_plan")
public class BaseSleepPlan extends IdEntity {
    private String patient;
    private String deviceSn;
    private String getUpTime;
    private String napTime;
    private String nightRestTime;
    private Date createTime;
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getDeviceSn() {
        return deviceSn;
    }
    public void setDeviceSn(String deviceSn) {
        this.deviceSn = deviceSn;
    }
    public String getGetUpTime() {
        return getUpTime;
    }
    public void setGetUpTime(String getUpTime) {
        this.getUpTime = getUpTime;
    }
    public String getNapTime() {
        return napTime;
    }
    public void setNapTime(String napTime) {
        this.napTime = napTime;
    }
    public String getNightRestTime() {
        return nightRestTime;
    }
    public void setNightRestTime(String nightRestTime) {
        this.nightRestTime = nightRestTime;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

+ 191 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/BaseSleepPlanDetail.java

@ -0,0 +1,191 @@
package com.yihu.jw.entity.care.device;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
import java.util.List;
/**
 * Created by Bing on 2021/8/23.
 */
@Entity
@Table(name="base_sleep_plan_detail")
public class BaseSleepPlanDetail extends IdEntity {
    private String  patient;
    private String  deviceSn;
    private String  day; //睡眠监控日期
    private Integer  upStatus; //起床状态 0未起床 1起床
    private Date  upTime; //起床时间
    private Integer  siestaStatus; //午睡状态 0未入床 1已入床
    private Date  siestaTimeBegin; //午睡开始时间
    private Date  siestaTimeEnd;  //午睡结束时间
    private String  siestaLong; //午睡时长 单位秒
    private Integer  inStatus; //睡觉状态 0未入床 1已入床,2无午睡计划
    private Date  inTimeBegin; //夜眠开始时间
    private Date  inTimeEnd; //夜眠结束时间
    private Date createTime;
    private Date  updateTime;
    private List<BaseSleepNightRecord> sleepNightRecordList;
    private String heartRate;
    private String breath;
    private Integer bedStatus;
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getDeviceSn() {
        return deviceSn;
    }
    public void setDeviceSn(String deviceSn) {
        this.deviceSn = deviceSn;
    }
    public String getDay() {
        return day;
    }
    public void setDay(String day) {
        this.day = day;
    }
    public Integer getUpStatus() {
        return upStatus;
    }
    public void setUpStatus(Integer upStatus) {
        this.upStatus = upStatus;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getUpTime() {
        return upTime;
    }
    public void setUpTime(Date upTime) {
        this.upTime = upTime;
    }
    public Integer getSiestaStatus() {
        return siestaStatus;
    }
    public void setSiestaStatus(Integer siestaStatus) {
        this.siestaStatus = siestaStatus;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getSiestaTimeBegin() {
        return siestaTimeBegin;
    }
    public void setSiestaTimeBegin(Date siestaTimeBegin) {
        this.siestaTimeBegin = siestaTimeBegin;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getSiestaTimeEnd() {
        return siestaTimeEnd;
    }
    public void setSiestaTimeEnd(Date siestaTimeEnd) {
        this.siestaTimeEnd = siestaTimeEnd;
    }
    public String getSiestaLong() {
        return siestaLong;
    }
    public void setSiestaLong(String siestaLong) {
        this.siestaLong = siestaLong;
    }
    public Integer getInStatus() {
        return inStatus;
    }
    public void setInStatus(Integer inStatus) {
        this.inStatus = inStatus;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getInTimeBegin() {
        return inTimeBegin;
    }
    public void setInTimeBegin(Date inTimeBegin) {
        this.inTimeBegin = inTimeBegin;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getInTimeEnd() {
        return inTimeEnd;
    }
    public void setInTimeEnd(Date inTimeEnd) {
        this.inTimeEnd = inTimeEnd;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    @Transient
    public List<BaseSleepNightRecord> getSleepNightRecordList() {
        return sleepNightRecordList;
    }
    public void setSleepNightRecordList(List<BaseSleepNightRecord> sleepNightRecordList) {
        this.sleepNightRecordList = sleepNightRecordList;
    }
    @Transient
    public String getHeartRate() {
        return heartRate;
    }
    public void setHeartRate(String heartRate) {
        this.heartRate = heartRate;
    }
    @Transient
    public String getBreath() {
        return breath;
    }
    public void setBreath(String breath) {
        this.breath = breath;
    }
    @Transient
    public Integer getBedStatus() {
        return bedStatus;
    }
    public void setBedStatus(Integer bedStatus) {
        this.bedStatus = bedStatus;
    }
}

+ 10 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceDetail.java

@ -43,6 +43,7 @@ public class DeviceDetail extends IdEntity {
    private Integer isBinding;//是否绑定(0否 1 绑定单端口 2 绑定双端口)
    private String bindingCount;//绑定次数({"1":"0", "2":"0"})
    private Date grantTime;//发放时间
    private Integer deviceType;
    //1.5.0版本新增字段
    private String grantDoctor;//发放医生code
@ -314,4 +315,13 @@ public class DeviceDetail extends IdEntity {
    public void setGrantDoctorName(String grantDoctorName) {
        this.grantDoctorName = grantDoctorName;
    }
    @Column(name = "device_type")
    public Integer getDeviceType() {
        return deviceType;
    }
    public void setDeviceType(Integer deviceType) {
        this.deviceType = deviceType;
    }
}

+ 65 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceHealthIndex.java

@ -0,0 +1,65 @@
package com.yihu.jw.entity.care.device;
import com.yihu.jw.entity.UuidIdentityEntityWithCreateTime;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created with IntelliJ IDEA.
 * base_device_health_index
 * 烟感气感实时数据
 * @Author: yeshijie
 * @Date: 2021/8/23
 * @Description:
 */
@Entity
@Table(name = "base_device_health_index")
public class DeviceHealthIndex extends UuidIdentityEntityWithCreateTime{
    private String deviceSn;//设备sn
    private String deviceType;//设备类型 1气感 2烟感
    private String value;//测量值
    private String unit;//单位
    private String recordTime;//记录时间
    public String getDeviceSn() {
        return deviceSn;
    }
    public void setDeviceSn(String deviceSn) {
        this.deviceSn = deviceSn;
    }
    public String getDeviceType() {
        return deviceType;
    }
    public void setDeviceType(String deviceType) {
        this.deviceType = deviceType;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    public String getUnit() {
        return unit;
    }
    public void setUnit(String unit) {
        this.unit = unit;
    }
    public String getRecordTime() {
        return recordTime;
    }
    public void setRecordTime(String recordTime) {
        this.recordTime = recordTime;
    }
}

+ 37 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DevicePatientDevice.java

@ -21,7 +21,7 @@ public class DevicePatientDevice extends IdEntity {
    private String deviceName;
    // 用户code
    private String user;
    // 设备类型标识 1血糖仪,2.血压计,3药盒,4智能手表,7 = 居家报警器,12 监控器 13 睡眠带 14火灾报警器
    // 设备类型标识 1血糖仪,2.血压计,3药盒,4智能手表,7 = 居家报警器,12 监控器 13 睡眠带 14气感报警器 15烟感报警器
    private String categoryCode;
    // 用户类型标准 -1代表单用户
    private String userType;
@ -78,6 +78,18 @@ public class DevicePatientDevice extends IdEntity {
     */
    private String deviceImgUrl;
    private Integer deviceType;//设备种类 0健康设备 1安防设备
    /**
     * wifi对应的设备
     */
    private String iotDeviceSn;
    /**
     * 智能拐杖对应的围栏
     */
    private String safeAreaGz;
    @Column(name = "device_id")
    public Long getDeviceId() {
        return deviceId;
@ -328,4 +340,28 @@ public class DevicePatientDevice extends IdEntity {
    public void setOnlineStatus(Integer onlineStatus) {
        this.onlineStatus = onlineStatus;
    }
    public Integer getDeviceType() {
        return deviceType;
    }
    public void setDeviceType(Integer deviceType) {
        this.deviceType = deviceType;
    }
    public String getIotDeviceSn() {
        return iotDeviceSn;
    }
    public void setIotDeviceSn(String iotDeviceSn) {
        this.iotDeviceSn = iotDeviceSn;
    }
    public String getSafeAreaGz() {
        return safeAreaGz;
    }
    public void setSafeAreaGz(String safeAreaGz) {
        this.safeAreaGz = safeAreaGz;
    }
}

+ 9 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DevicePatientHealthIndex.java

@ -51,6 +51,7 @@ public class DevicePatientHealthIndex extends IdEntity {
	//设备编号
	private String deviceSn;
	private Integer manageResult;//0未干预 1异常有效干预 2异常无效干预
	private Integer status;//状态:0为标准,1为异常
	private String name;//居民姓名
	private String hospital;//医院
@ -195,6 +196,14 @@ public class DevicePatientHealthIndex extends IdEntity {
		this.deviceSn = deviceSn;
	}
	public Integer getManageResult() {
		return manageResult;
	}
	public void setManageResult(Integer manageResult) {
		this.manageResult = manageResult;
	}
	public Integer getStatus() {
		return status;
	}

+ 37 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/HvDeviceRecord.java

@ -0,0 +1,37 @@
package com.yihu.jw.entity.care.device;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created with IntelliJ IDEA.
 * '海康烟感气感设备记录表'
 * @Author: yeshijie
 * @Date: 2021/8/23
 * @Description:
 */
@Entity
@Table(name = "base_hvdevice_record")
public class HvDeviceRecord extends UuidIdentityEntity {
    private String deviceId;//海康平台设备id
    private String deviceSn;//设备sn
    public String getDeviceId() {
        return deviceId;
    }
    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }
    public String getDeviceSn() {
        return deviceSn;
    }
    public void setDeviceSn(String deviceSn) {
        this.deviceSn = deviceSn;
    }
}

+ 130 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/HvDeviceSosLog.java

@ -0,0 +1,130 @@
package com.yihu.jw.entity.care.device;
import com.yihu.jw.entity.UuidIdentityEntityWithCreateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created with IntelliJ IDEA.
 * 烟感气感设备报警日志记录表
 * @Author: yeshijie
 * @Date: 2021/8/23
 * @Description:
 */
@Entity
@Table(name = "base_hvdevice_sos_log")
public class HvDeviceSosLog extends UuidIdentityEntityWithCreateTime{
    private String resourceID;
    private String resourceSerial;
    private String resourceName;
    private Integer alarmNum;
    private String alarmTime;
    private String monitorValue;
    private String alarmType;
    private String systemType;
    private String alarmID;
    private String resourceType;
    private String location;
    @Column(name = "resource_id")
    public String getResourceID() {
        return resourceID;
    }
    public void setResourceID(String resourceID) {
        this.resourceID = resourceID;
    }
    @Column(name = "resource_serial")
    public String getResourceSerial() {
        return resourceSerial;
    }
    public void setResourceSerial(String resourceSerial) {
        this.resourceSerial = resourceSerial;
    }
    @Column(name = "resource_name")
    public String getResourceName() {
        return resourceName;
    }
    public void setResourceName(String resourceName) {
        this.resourceName = resourceName;
    }
    @Column(name = "alarm_num")
    public Integer getAlarmNum() {
        return alarmNum;
    }
    public void setAlarmNum(Integer alarmNum) {
        this.alarmNum = alarmNum;
    }
    @Column(name = "alarm_time")
    public String getAlarmTime() {
        return alarmTime;
    }
    public void setAlarmTime(String alarmTime) {
        this.alarmTime = alarmTime;
    }
    @Column(name = "monitor_value")
    public String getMonitorValue() {
        return monitorValue;
    }
    public void setMonitorValue(String monitorValue) {
        this.monitorValue = monitorValue;
    }
    @Column(name = "alarm_type")
    public String getAlarmType() {
        return alarmType;
    }
    public void setAlarmType(String alarmType) {
        this.alarmType = alarmType;
    }
    @Column(name = "system_type")
    public String getSystemType() {
        return systemType;
    }
    public void setSystemType(String systemType) {
        this.systemType = systemType;
    }
    @Column(name = "alarm_id")
    public String getAlarmID() {
        return alarmID;
    }
    public void setAlarmID(String alarmID) {
        this.alarmID = alarmID;
    }
    @Column(name = "resource_type")
    public String getResourceType() {
        return resourceType;
    }
    public void setResourceType(String resourceType) {
        this.resourceType = resourceType;
    }
    @Column(name = "location")
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
}

+ 10 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/care/securitymonitoring/SecurityMonitoringOrderDO.java

@ -318,11 +318,12 @@ public class SecurityMonitoringOrderDO extends UuidIdentityEntityWithOperator {
    private String serviceStatus;//服务类型 1-预约项目 2-即时项目
    private String orderInfo;//工单详情 0-未推送 1-未确认 2-已确认
    private String doctorConfirmFinishImg;
    private Integer orderSource;//工单发起来源状态 1APP 2手环 3居家报警 4监控器发起 5睡眠带
    private Integer orderSource;//工单发起来源状态 1APP 2手环 3居家报警 4监控器发起 5睡眠带 6气感报警器 7 烟感报警器
    private Integer emergencyCancel;// 紧急预警工单误报警原因 字典emergency_cancel
    private String topicItem;//安防工单所属专题 base_system_dict_entry表service_item
    private String sceneImg;//现场照片
    private String deviceSn;//设备sn  设备触发是才有该字段值
    private String warnInfo;//触发工单时信息如 烟雾心率等
    /**
     * 医生确认医生结束服务时间
@ -736,4 +737,12 @@ public class SecurityMonitoringOrderDO extends UuidIdentityEntityWithOperator {
    public void setDeviceSn(String deviceSn) {
        this.deviceSn = deviceSn;
    }
    public String getWarnInfo() {
        return warnInfo;
    }
    public void setWarnInfo(String warnInfo) {
        this.warnInfo = warnInfo;
    }
}

+ 19 - 0
common/common-util/src/main/java/com/yihu/jw/util/date/DateUtil.java

@ -1355,6 +1355,23 @@ public class DateUtil {
        return dateTime.substring(0, 10);
    }
    /**
     * 判断时间是否在某个区间内
     * @param time
     * @param begin
     * @param end
     * @return
     */
    public static boolean isInArea(Date time,Date begin,Date end) {
        Long beginTime = DateUtil.compareDateTime(time,begin);
        Long endTime = DateUtil.compareDateTime(time, end);
        if (beginTime > 0 && endTime < 0) {
            return true;
        } else {
            return false;
        }
    }
    /**
     *  返回 xx天XX小时XX分钟XX秒前
     * @param date1 当前时间
@ -1405,4 +1422,6 @@ public class DateUtil {
        return result.toString();
    }
}

+ 9 - 0
svr/svr-cloud-care/pom.xml

@ -219,6 +219,10 @@
                    <groupId>xalan</groupId>
                    <artifactId>xalan</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.his.hesb</groupId>
                    <artifactId>mqSdk</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
@ -256,6 +260,11 @@
            <artifactId>es-service</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.hikvision.ga</groupId>
            <artifactId>artemis-http-client</artifactId>
            <version>1.1.3</version>
        </dependency>
    </dependencies>
    <build>

+ 4 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/config/AqgConfig.java

@ -48,6 +48,10 @@ public class AqgConfig {
     */
    public static final String  sleepDevice_info=baseUrl+"/api/sleepdevice/";
    /**
     * X1定位数据  即轨迹
     */
    public static final String X1_locations = baseUrl+"/api/locationdata/";
    public static final String username = "13559485270";
    public static final String password = "zjxl@2021";

+ 16 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/BaseSleepPlanDao.java

@ -0,0 +1,16 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.BaseSleepDeviceReport;
import com.yihu.jw.entity.care.device.BaseSleepPlan;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/***
 * @ClassName: BaseSleepPlanDao
 * @Description:
 * @Auther: shi kejing
 * @Date: 2021/8/23 17:20
 */
public interface BaseSleepPlanDao extends PagingAndSortingRepository<BaseSleepPlan,Long>,
        JpaSpecificationExecutor<BaseSleepPlan> {
}

+ 2 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/DeviceDetailDao.java

@ -17,6 +17,8 @@ public interface DeviceDetailDao extends PagingAndSortingRepository<DeviceDetail
    List<DeviceDetail> findByDeviceCode(String deviceCode);
    List<DeviceDetail> findBySim(String sim);
    @Query("select a from DeviceDetail a where a.deviceCode = ?1 and a.manufacturerCode = ?2")
    DeviceDetail findByDeviceCodeAndManufacturerCode(String deviceCode,String manufacturerCode);

+ 4 - 1
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/DevicePatientHealthIndexDao.java

@ -3,6 +3,7 @@ package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
@ -73,5 +74,7 @@ public interface DevicePatientHealthIndexDao
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.deviceSn = ?2 and a.value1 = ?3 and a.value2=?7 and a.value3=?8 and a.type = ?4 and a.recordDate >= ?5 and a.recordDate<=?6 and a.del = '1' ")
	List<DevicePatientHealthIndex> findByTypeInHalfMinuteAllValue(String patient, String deviceSn, String value1, Integer type, Date minDate,Date maxDate,String value2,String value3);
	@Modifying
	@Query("update DevicePatientHealthIndex a set a.manageResult=1 where a.id in (?1) ")
	void handleHealthIndex(Long[] id);
}

+ 4 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/PatientDeviceDao.java

@ -1,5 +1,6 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
@ -54,6 +55,9 @@ public interface PatientDeviceDao extends PagingAndSortingRepository<DevicePatie
    @Query("select a from DevicePatientDevice a")
    List<DevicePatientDevice> findAll();
    @Query("select a from DevicePatientDevice a where a.categoryCode = ?1")
    List<DevicePatientDevice> findAllByCategoryCode(String categoryCode);
    @Modifying
    @Query("delete DevicePatientDevice a where a.deviceSn = ?1")
    int deleteByDeviceSn(String deviceSN);

+ 0 - 10
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/assistance/EmergencyAssistanceEndpoint.java

@ -318,16 +318,6 @@ public class EmergencyAssistanceEndpoint extends EnvelopRestEndpoint {
        }
    }
    @GetMapping(value = "getMonitorUrl")
    @ApiOperation(value = "获取监控录像地址")
    public ObjEnvelop getMonitorUrl(@ApiParam(name="patient")@RequestParam(value = "patient")String patient){
        try {
            return null;
        }catch (Exception e){
            return failedObjEnvelopException2(e);
        }
    }
    @PostMapping("doctorSendMessageLog")
    @ApiOperation(value = "助老员紧急预警im发送消息日志")
    public ObjEnvelop doctorSendMessageLog(

+ 31 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/DoctorHealthController.java

@ -314,4 +314,35 @@ public class DoctorHealthController extends BaseController {
			return errorResult(e);
		}
	}
	@RequestMapping(value = "getErrorHealthIndexPatients",method = RequestMethod.GET)
	@ApiOperation("获取签约医生底下未干预异常体征患者")
	public String getErrorHealthIndexPatients(@ApiParam(name="doctor")@RequestParam(value = "doctor")String doctor) {
		try {
			return write(200, "查询成功", "data", healthIndexService.getErrorHealthIndexPatients(doctor));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	@RequestMapping(value = "getErrorHealthIndexByPatients",method = RequestMethod.GET)
	@ApiOperation("获取患者未干预异常体征列表")
	public String getErrorHealthIndexByPatients(@ApiParam(name="patient")@RequestParam(value = "patient")String patient) {
		try {
			return write(200, "查询成功", "data", healthIndexService.getErrorHealthIndexByPatients(patient));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	@RequestMapping(value = "handleHealthIndex",method = RequestMethod.POST)
	@ApiOperation("医生体征干预")
	public String handleHealthIndex(@ApiParam(name="user")@RequestParam(value = "user")String ids) {
		try {
			healthIndexService.handleHealthIndex(ids);
			return write(200, "处理成功");
		} catch (Exception e) {
			return errorResult(e);
		}
	}
}

+ 139 - 9
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/PadDeviceController.java

@ -2,7 +2,9 @@ package com.yihu.jw.care.endpoint.device;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.dao.device.DeviceDetailDao;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.endpoint.BaseController;
import com.yihu.jw.care.service.contacts.ContactsService;
@ -13,24 +15,31 @@ import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.sync.BaseSyncDataDO;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.BaseSleepPlan;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
/***
 * @ClassName: PadDeviceController
@ -54,6 +63,9 @@ public class PadDeviceController extends BaseController {
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private ContactsService contactsService;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    /**
     * 设备列表获取
     *
@ -104,10 +116,19 @@ public class PadDeviceController extends BaseController {
    public String saveDevice(@ApiParam(name = "json", value = "设备数据json", defaultValue = "{     \"deviceId\":\"3\",     \"deviceName\":\"血压计-优瑞恩\",     \"deviceSn\":\"7052169111\",     \"categoryCode\":\"7\",     \"userType\":\"-1\", \"sosAddress\":\"福建省厦门市思明区望海路55号之1\" }")
                             @RequestParam(value = "json", required = true) String json,
                             @ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = false) String patientCode,
                             @ApiParam(name = "doctorCode", value = "管理员code") @RequestParam(value = "doctorCode", required = false) String doctorCode
                             @ApiParam(name = "doctorCode", value = "管理员code") @RequestParam(value = "doctorCode", required = false) String doctorCode,
                             @ApiParam(name = "sleepPlanJson", value = "睡眠计划json") @RequestParam(value = "sleepPlanJson", required = false) String sleepPlanJson,
                             @ApiParam(name = "iotDeviceSn", value = "iotDeviceSn") @RequestParam(value = "iotDeviceSn", required = false) String iotDeviceSn,
                             @ApiParam(name = "safeAreaGz", value = "safeAreaGz") @RequestParam(value = "safeAreaGz", required = false) String safeAreaGz
                             //{"deviceSn": "7052169111","getUpTime": "07:00","napTime": "13:00","nightRestTime": "21:30"}
                             ) {
        try {
            DevicePatientDevice device = objectMapper.readValue(json, DevicePatientDevice.class);
            BaseSleepPlan sleepPlan = new BaseSleepPlan();
            if (StringUtils.isNotBlank(sleepPlanJson)){
                sleepPlan = objectMapper.readValue(sleepPlanJson,BaseSleepPlan.class);
                sleepPlan.setPatient(patientCode);
            }
            // 设置患者标识
            device.setUser(patientCode);
            //患者和设备是否首绑
@ -123,7 +144,7 @@ public class PadDeviceController extends BaseController {
            device.setAgentName(doctor.getName());
            String sn = device.getDeviceSn();
            synchronized (sn.intern()){
                Boolean flagDevice = patientDeviceService.saveDevice(device);
                Boolean flagDevice = patientDeviceService.saveDevice(device,sleepPlan,iotDeviceSn,safeAreaGz);
                if (flagDevice == false){
                    return write(-1,"请填写投放地址");
                }
@ -167,5 +188,114 @@ public class PadDeviceController extends BaseController {
        }
    }
    @RequestMapping(value = "/importDeviceFromExcel", produces = "application/json;charset=UTF-8",method = RequestMethod.POST)
    @ResponseBody
    public String importFromExcel(HttpServletRequest request,@ApiParam(value = "文件", required = true)
    @RequestParam(value = "file", required = true) MultipartFile file) {
        List errorLs = new ArrayList<>();
        List correctLs = new ArrayList<>();
        Map<String, String> errorMsgMap = new HashMap<>();
        List<String> deviceCodes = new ArrayList<>();
        try {
            request.setCharacterEncoding("UTF-8");
            InputStream inputStream = file.getInputStream();
            Workbook rwb = Workbook.getWorkbook(inputStream);
            Sheet[] sheets = rwb.getSheets();
            int rows;
            int row;
            String manufacturer=null;//厂商名称
            String deviceName; //设备名称
            String deviceModel; //设备型号
            String deviceCode;  //设备SN
            String sim;  //sim卡号
            String bindingCount; //单人{"1":"0"}  多人{"1":"0", "2":"0"}
            String deviceType; //设备种类  0健康设备 1安防设备
            Sheet sheet = sheets[0];    //第一张表
            rows = sheet.getRows();
            for (int j = 1; j < rows; j++) {
                if (sheet.getRow(j).length == 0) {
                    continue;
                }
                DeviceDetail deviceDetail = new DeviceDetail();
                row = j;
                manufacturer = sheet.getCell(0, row).getContents().trim();    //0 厂商名称
                deviceName = sheet.getCell(1, row).getContents().trim();  //1 设备名称
                deviceModel = sheet.getCell(2, row).getContents().trim();   //2 设备型号
                deviceCode = sheet.getCell(3, row).getContents().trim(); //3 设备SN
                sim = sheet.getCell(4, row).getContents().trim();  //4 sim卡号
                bindingCount = sheet.getCell(5, row).getContents().trim(); //5
                deviceType = sheet.getCell(6, row).getContents().trim(); //6 设备种类
                if (StringUtils.isBlank(deviceCode)){
                    continue;
                }
                if (deviceCodes.contains(deviceCode)){
                    errorMsgMap.put(deviceCode,"设备SN码重复");
                    continue;
                }
                deviceCodes.add(deviceCode);
                if (StringUtils.isBlank(manufacturer)){
                    errorMsgMap.put(deviceCode,"厂商名称不能为空");
                    continue;
                }
                if (StringUtils.isBlank(deviceName)){
                    errorMsgMap.put(deviceCode,"设备名称不能为空");
                    continue;
                }
                if (StringUtils.isBlank(deviceModel)){
                    errorMsgMap.put(deviceCode,"设备型号不能为空");
                    continue;
                }
                if (StringUtils.isBlank(bindingCount)){
                    errorMsgMap.put(deviceCode,"设备类型不能为空");
                    continue;
                }
                if (StringUtils.isBlank(deviceType)){
                    errorMsgMap.put(deviceCode,"设备种类不能为空");
                    continue;
                }else {
                    if ("健康设备".equals(deviceType)){
                        deviceType = "1";
                    }
                    else if ("安防设备".equals(deviceType)){
                        deviceType= "0";
                    }
                    else {
                        errorMsgMap.put(deviceCode,"不支持该设备种类");
                        continue;
                    }
                }
                if (deviceDetailDao.findByDeviceCode(deviceCode).size()>0){
                    errorMsgMap.put(deviceCode,"该设备SN码已存在");
                    continue;
                }
                if (deviceDetailDao.findBySim(sim).size()>0){
                    errorMsgMap.put(deviceCode,"该sim卡号已存在");
                    continue;
                }
                deviceDetail.setManufacturer(manufacturer);
                deviceDetail.setDeviceName(deviceName);
                deviceDetail.setDeviceModel(deviceModel);
                deviceDetail.setDeviceCode(deviceCode);
                deviceDetail.setSim(sim);
                deviceDetail.setBindingCount(bindingCount);
                deviceDetail.setDeviceType(Integer.parseInt(deviceType));
                correctLs.add(deviceDetail);
            }
            deviceDetailDao.save(correctLs);
            //包装导入结果(导入成功数量、错误对象集合)
            Map<String, Object> map = new HashMap<>();
            map.put("successNum", correctLs.size());
            map.put("failedNum", rows-1 - correctLs.size() );
            map.put("errorData", JSON.toJSONString(errorMsgMap, SerializerFeature.WriteMapNullValue));
            return write(200, "操作成功", "data", map);
        } catch (Exception e) {
            error(e);
            return error(-1, "操作失败!");
        }
    }
}

+ 36 - 3
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/PatientDeviceController.java

@ -7,10 +7,10 @@ import com.yihu.jw.care.service.device.DeviceDetailService;
import com.yihu.jw.care.service.device.PatientDeviceService;
import com.yihu.jw.care.service.device.PatientHealthIndexService;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.BaseSleepPlan;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.ListEnvelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@ -68,6 +68,30 @@ public class PatientDeviceController extends BaseController {
        }
    }
    @ApiOperation("燃气浓度")
    @RequestMapping(value = "gasConcentration", method = RequestMethod.GET)
    public String gasConcentration(@ApiParam(name = "patientId", value = "居民id", defaultValue = "808080eb7917a3be017918a979380055")
                             @RequestParam(value = "patientId", required = true) String patientId,
                                   @ApiParam(name = "date", value = "日期", defaultValue = "2021-08-24")
                                   @RequestParam(value = "date", required = true) String date){
        try {
            return write(200,"获取成功","data",patientDeviceService.gasConcentration(patientId,date));
        } catch (Exception ex) {
            return errorResult(ex);
        }
    }
    @ApiOperation("环境信息")
    @RequestMapping(value = "envMessage", method = RequestMethod.GET)
    public String envMessage(@ApiParam(name = "patientId", value = "居民id", defaultValue = "1")
                                    @RequestParam(value = "patientId", required = true) String patientId){
        try {
            JSONObject json = patientDeviceService.envMessage(patientId);
            return write(200,"获取成功","data",json);
        } catch (Exception ex) {
            return errorResult(ex);
        }
    }
    /**
     * 设备保存接口  ---增加血糖时间段保存 Reece v1.3.3
@ -75,9 +99,18 @@ public class PatientDeviceController extends BaseController {
    @ApiOperation("设备保存接口")
    @RequestMapping(value = "SavePatientDevice", method = RequestMethod.POST)
    public String saveDevice(@ApiParam(name = "json", value = "设备数据json", defaultValue = "{\"deviceId\": \"3\",\"deviceName\": \"血压计-优瑞恩\",\"deviceSn\": \"7052169111\",\"categoryCode\": \"1\",\"userType\": \"-1\"}")
                             @RequestParam(value = "json", required = true) String json) {
                             @RequestParam(value = "json", required = true) String json,
                             @ApiParam(name = "sleepPlanJson", value = "睡眠计划json") @RequestParam(value = "sleepPlanJson", required = false) String sleepPlanJson,
                             @ApiParam(name = "iotDeviceSn", value = "iotDeviceSn") @RequestParam(value = "iotDeviceSn", required = false) String iotDeviceSn,
                             @ApiParam(name = "safeAreaGz", value = "safeAreaGz") @RequestParam(value = "safeAreaGz", required = false) String safeAreaGz){
        //{"deviceSn": "7052169111","getUpTime": "07:00","napTime": "13:00","nightRestTime": "21:30"})
        try {
            DevicePatientDevice device = objectMapper.readValue(json, DevicePatientDevice.class);
            BaseSleepPlan sleepPlan = new BaseSleepPlan();
            if (StringUtils.isNotBlank(sleepPlanJson)){
                sleepPlan = objectMapper.readValue(sleepPlanJson,BaseSleepPlan.class);
                sleepPlan.setPatient(getRepUID());
            }
            // 设置患者标识
            device.setUser(getRepUID());
            //患者和设备是否首绑
@ -96,7 +129,7 @@ public class PatientDeviceController extends BaseController {
            String sn = device.getDeviceSn();
            synchronized (sn.intern()){
//                patientDeviceService.saveDevice(device);
                Boolean flagDevice = patientDeviceService.saveDevice(device);
                Boolean flagDevice = patientDeviceService.saveDevice(device,sleepPlan,iotDeviceSn,safeAreaGz);
                if (flagDevice == false){
                    return write(-1,"请填写投放地址");
                }

+ 1 - 1
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/message/DoctorMessageEndpoint.java

@ -24,7 +24,7 @@ public class DoctorMessageEndpoint extends EnvelopRestEndpoint {
    @GetMapping(value = "messages")
    @ApiOperation("应用消息")
    public ObjEnvelop messages(@ApiParam(name = "type", value = "消息类型 10床位申请,11安全监护,12紧急救助")
    public ObjEnvelop messages(@ApiParam(name = "type", value = "消息类型 10床位申请,11安全监护,12紧急救助,13体征异常消息")
                               @RequestParam(value = "type", required = false) String type,
                               @ApiParam(name = "doctor", value = "doctor")
                               @RequestParam(value = "doctor", required = false) String doctor){

+ 49 - 4
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/statistics/DetectionPlatformEndpoint.java

@ -1,7 +1,9 @@
package com.yihu.jw.care.endpoint.statistics;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.service.statistics.DetectionPlatformService;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
@ -16,7 +18,7 @@ import org.springframework.web.bind.annotation.RestController;
/***
 * @ClassName: DetectionPlatformEndpoint
 * @Description: 社区云照护平台--物联网健康监测展示平台
 * @Description: 社区云照护平台--物联网健康监测展示平台 v1.0.0
 * @Auther: shi kejing
 * @Date: 2021/8/20 9:28
 */
@ -29,9 +31,9 @@ public class DetectionPlatformEndpoint extends EnvelopRestEndpoint {
    @Autowired
    private DetectionPlatformService platformService;
    @GetMapping(value = "statisticsTotalAmount")
    @ApiOperation(value = "统计总数")
    public PageEnvelop statisticsTotalAmount(
    @GetMapping(value = "getHealthMonitoringListNew")
    @ApiOperation(value = "体征监测/安防监护")
    public PageEnvelop getHealthMonitoringListNew(
            @ApiParam(name="page",value = "page") @RequestParam(required = true) int page,
            @ApiParam(name="size",value = "size") @RequestParam(required = true) int size,
            @ApiParam(name="type",value = "type=1(健康监测)   type=2(安防检测)") @RequestParam(required = true) int type) {
@ -42,6 +44,49 @@ public class DetectionPlatformEndpoint extends EnvelopRestEndpoint {
        }
    }
    @GetMapping(value = "getDeviceCompany")
    @ApiOperation(value = "设备入驻")
    public ObjEnvelop getDeviceCompany(){
        try {
            JSONObject o = platformService.getDeviceComapny();
            return success(o);
        }catch (Exception e){
            return failedObjEnvelopException(e);
        }
    }
    @GetMapping(value = "getDeviceType")
    @ApiOperation(value = "设备类型")
    public ListEnvelop getDeviceType(){
        try {
            return success("查询成功",200,platformService.getDeviceType());
        }catch (Exception e){
            return failedListEnvelopException(e);
        }
    }
    @GetMapping(value = "getDeviceByCondition")
    @ApiOperation(value = "地图展示,根据不同的条件展示不同的数据")
    public ListEnvelop<Object> getDeviceByCondition(            @ApiParam(name="categoryCode",value = "categoryCode") @RequestParam(required = false) String categoryCode,
                                                                @ApiParam(name="patient",value = "patient") @RequestParam(required = false) String patient){
        try {
            JSONArray object = platformService.getDeviceByCondition(categoryCode,patient);
            return success("查询成功",200,object);
        }catch (Exception e){
            return failedListEnvelopException(e);
        }
    }
    @GetMapping(value = "getDeviceInfo")
    @ApiOperation(value = "地图展示,根据设备sn码查询详情")
    public ObjEnvelop getDeviceInfo(            @ApiParam(name="deviceSn",value = "deviceSn") @RequestParam(required = true) String deviceSn){
        try {
            JSONObject object = platformService.getDeviceInfo(deviceSn);
            return success("查询成功",200,object);
        }catch (Exception e){
            return failedObjEnvelopException(e);
        }
    }
}

+ 14 - 2
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/assistance/EmergencyAssistanceService.java

@ -9,7 +9,6 @@ import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.dao.security.BaseEmergencyWarnLogDao;
import com.yihu.jw.care.dao.security.EmergencyWarnConclusionDao;
import com.yihu.jw.care.dao.security.EmergencyWarnDoctorResponseDao;
import com.yihu.jw.care.dao.security.SecurityMonitoringOrderDao;
import com.yihu.jw.care.dao.sign.ServicePackageSignRecordDao;
import com.yihu.jw.care.dao.team.BaseTeamMemberDao;
import com.yihu.jw.care.service.common.DictService;
@ -30,7 +29,6 @@ import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.care.securitymonitoring.BaseEmergencyWarnLogDO;
import com.yihu.jw.entity.care.securitymonitoring.EmergencyWarnConclusionDO;
import com.yihu.jw.entity.care.securitymonitoring.EmergencyWarnDoctorResponseDO;
import com.yihu.jw.entity.care.securitymonitoring.SecurityMonitoringOrderDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.im.dao.ConsultDao;
@ -108,6 +106,20 @@ public class EmergencyAssistanceService extends BaseJpaService<EmergencyAssistan
    @Autowired
    private ContactsService contactsService;
    /**
     * 获取百度天气
     */
    public JSONObject getBaiduWeather(){
        String url = "https://api.map.baidu.com/weather/v1/?district_id=330100&data_type=now&ak=0vjnCSReegE7A47a941ohjv9a07ONiMC";
        String response = httpClientUtil.get(url,"UTF-8");
        JSONObject responseObj = JSONObject.parseObject(response);
        if (responseObj.getInteger("status")==0){
            JSONObject now = responseObj.getJSONObject("result").getJSONObject("now");
            return now;
        }
        return new JSONObject();
    }
    /**
     * 新建居民紧急救助
     * @param patient

+ 2 - 5
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/birthday/BirthdayWishesService.java

@ -403,7 +403,7 @@ public class BirthdayWishesService {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String createTime = f.format(new Date())+" 00:00:00";
        //医生今日推送的居民
        List<BirthDayWishesToPatient> sendPatientList = findSendPatientByCreateTime(p.toString(),createTime);
        List<BirthDayWishesToPatient> sendPatientList = findSendPatientByCreateTime(createTime);
        Set<String> sendPatient = sendPatientList.stream().map(BirthDayWishesToPatient::getPatientCode).collect(Collectors.toSet());
        Set<String> openidSet = new HashSet<>();
@ -501,13 +501,10 @@ public class BirthdayWishesService {
     * @param
     * @return
     */
    public List<BirthDayWishesToPatient> findSendPatientByCreateTime(String patient,String createTime) {
    public List<BirthDayWishesToPatient> findSendPatientByCreateTime(String createTime) {
        StringBuffer sql = new StringBuffer("select patient_code patientCode from  birthday_wishes_to_patient  "+
                " where user_type=1 and create_time>'" + createTime + "' ");
        if (StringUtils.isNotBlank(patient)){
            sql.append(" and patient_code in ( "+patient+" ) ") ;
        }
        sql.append(" limit 0,500000 ");
        List<BirthDayWishesToPatient> patientList = jdbcTemplate.query(sql.toString(),new BeanPropertyRowMapper<>(BirthDayWishesToPatient.class));
        return patientList;

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

@ -4,9 +4,11 @@ package com.yihu.jw.care.service.device;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yihu.jw.care.config.AqgConfig;
import com.yihu.jw.care.dao.device.BaseSleepPlanDao;
import com.yihu.jw.care.dao.device.DeviceDao;
import com.yihu.jw.care.dao.device.DeviceDetailDao;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.service.assistance.EmergencyAssistanceService;
import com.yihu.jw.care.service.contacts.ContactsService;
import com.yihu.jw.care.service.wechat.WeiXinAccessTokenUtils;
import com.yihu.jw.care.util.ConcealUtil;
@ -14,12 +16,12 @@ import com.yihu.jw.care.util.MyJdbcTemplate;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.BaseSleepPlan;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.util.common.GpsUtil;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
@ -87,6 +89,8 @@ public class PatientDeviceService extends BaseJpaService<DevicePatientDevice, Pa
    private HttpClientUtil httpClientUtil;
    @Autowired
    private YsDeviceService ysDeviceService;
    @Autowired
    private BaseSleepPlanDao sleepPlanDao;
    @Autowired
    WeiXinAccessTokenUtils tokenUtils;
@ -103,6 +107,8 @@ public class PatientDeviceService extends BaseJpaService<DevicePatientDevice, Pa
    private ContactsService contactsService;
    @Autowired
    private HealthIndexUtil healthIndexUtil;
    @Autowired
    private EmergencyAssistanceService emergencyAssistanceService;
    @PostConstruct
    public void init() {
@ -117,6 +123,60 @@ public class PatientDeviceService extends BaseJpaService<DevicePatientDevice, Pa
        relations.put(8, "免疫关联");
    }
    /**
     * 获取烟雾 燃气浓度
     * @param patient
     */
    public JSONObject concentrationMessage(String patient){
        JSONObject result = new JSONObject();
        String sql = "SELECT r.value from wlyy_patient_device pd,base_device_health_index r " +
                "WHERE pd.device_sn = r.device_sn and pd.`user` = '"+patient+"' ";
        String sql1 = sql + " and pd.category_code='14' ORDER BY r.create_time desc LIMIT 1";
        String sql2 = sql + " and pd.category_code='15' ORDER BY r.create_time desc LIMIT 1";
        List<Map<String,Object>> list1 = jdbcTemplate.queryForList(sql1);
        if(list1.size()==0){
            result.put("methane","-1");
        }else{
            result.put("methane",list1.get(0).get("value"));
        }
        List<Map<String,Object>> list2 = jdbcTemplate.queryForList(sql2);
        if(list2.size()==0){
            result.put("smoke","-1");
        }else{
            result.put("smoke",list2.get(0).get("value"));
        }
        return result;
    }
    /**
     * 环境信息
     * @return
     */
    public JSONObject envMessage(String patient){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("concentration",concentrationMessage(patient));
        jsonObject.put("weather",emergencyAssistanceService.getBaiduWeather());
        return jsonObject;
    }
    /**
     * 燃气浓度
     * @param patient
     */
    public List<Map<String,Object>> gasConcentration(String patient,String date){
        String sql = "SELECT r.value,r.create_time from wlyy_patient_device pd,base_device_health_index r " +
                "WHERE pd.device_sn = r.device_sn and pd.`user` = '"+patient+"' ";
        sql += " and pd.category_code='14' and r.create_time>'"+date+" 00:00:00' and r.create_time<'"+date+" 23:59:59'  ORDER BY r.create_time desc ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }
    /**
     * 验证sn码 先调总部接口 未注册才查询本地数据库,如果也没有才不能绑定
     * 屏蔽总部调总部接口,直接本地数据库验证,modify by Hmf on 2020.1.15
@ -136,13 +196,14 @@ public class PatientDeviceService extends BaseJpaService<DevicePatientDevice, Pa
    /**
     * 保存患者设备
     */
    public boolean saveDevice(DevicePatientDevice devicePatientDevice) throws Exception {
    public boolean saveDevice(DevicePatientDevice devicePatientDevice, BaseSleepPlan sleepPlan, String iotDeviceSn, String safeAreaGz) throws Exception {
        //判断sn码是否被使用
        String sn = devicePatientDevice.getDeviceSn();
        String type = devicePatientDevice.getCategoryCode();
        Long deviceId = devicePatientDevice.getDeviceId();
        String userType = devicePatientDevice.getUserType();
        String sosAddress = null;
        String url ="";
        if (userType == null) {
            userType = "-1";
            devicePatientDevice.setUserType("-1");
@ -177,6 +238,12 @@ public class PatientDeviceService extends BaseJpaService<DevicePatientDevice, Pa
        if (needVerify) {
            DevicePatientDevice device = patientDeviceDao.findByDeviceSnAndUserType(sn, userType);
            if (device != null && !device.getId().equals(devicePatientDevice.getId()) && device.getDel() == 0) {
                //V1.0.0    监控器、报警器、燃气传感器 烟雾传感器支持一个设备绑定多个居民
                //监控器 12   报警器 7  14  15
                if ("12".equals(type) || "14".equals(type) || "15".equals(type) || "7".equals(type) ) {
                    System.out.println("此类设备支持多绑定");
                }
                throw new Exception("sn码" + sn + "已被使用!");
            }
        }
@ -186,7 +253,23 @@ public class PatientDeviceService extends BaseJpaService<DevicePatientDevice, Pa
        BasePatientDO patient = patientDao.findById(devicePatientDevice.getUser());
        devicePatientDevice.setUserIdcard(patient.getIdcard());
        MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
        if(checkDeviceSn(sn)){
            if ("13".equals(type)){ //睡眠带
                if (StringUtils.isBlank(sleepPlan.getGetUpTime()) || StringUtils.isBlank(sleepPlan.getNightRestTime())) {
                    String message = "请完善睡眠时间规划";
                    throw new Exception(message);
                }
                sleepPlanDao.save(sleepPlan);
            }
            if ("17".equals(type)) {    //判断设备是不是随身wifi,如果是,则添加对应的设备sn
                devicePatientDevice.setIotDeviceSn(iotDeviceSn);
            }
            if ("16".equals(type)) {   //判断设备是不是拐杖,如果是拐杖,需要保存围栏地址
                devicePatientDevice.setSafeAreaGz(safeAreaGz);
            }
            patientDeviceDao.save(devicePatientDevice);
        }else {
            String message = "设备不存在";

+ 26 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/PatientHealthIndexService.java

@ -10,6 +10,7 @@ import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.patient.Patient;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
@ -1604,4 +1605,29 @@ public class PatientHealthIndexService extends BaseJpaService<DevicePatientHealt
    public DevicePatientHealthIndex getHealthIndexById(Long id) {
        return patientHealthIndexDao.findOne(id);
    }
    public List<Map<String,Object>> getErrorHealthIndexPatients(String doctor){
        String sql = " select count(id),patient,name,photo,mobile,record_date from (\n" +
                "select idx.id,p.id patient,p.name,p.photo,DATE_FORMAT(idx.record_date,'%Y-%m-%d %H:%i:%S')record_date ,p.mobile from wlyy_patient_health_index idx,base_patient p " +
                "where  idx.user = p.id and  status=1 and (manage_result=0 or manage_result is null)  and EXISTS ( " +
                " SELECT 1 from base_service_package_sign_record sr,base_service_package_record r ,base_team_member m where " +
                "idx.user = CONVERT(sr.patient USING utf8) and  sr.id = r.sign_id and sr.status=1 and   m.team_code = r.team_code  " +
                " and sr.`status`=1  and m.doctor_code = '"+doctor+"' and m.del = '1') order by idx.record_date " +
                " desc)A GROUP BY A.patient order by record_date desc ";
        List<Map<String,Object>> result = jdbcTemplate.queryForList(sql);
        return result;
    }
    public List<Map<String,Object>> getErrorHealthIndexByPatients(String patient){
        String sql = " select *,cast(DATE_FORMAT(max(idx.record_date),'%Y-%m-%d %H:%i:%S') as char)record_date  from  wlyy_patient_health_index idx where user='"+patient+"' and  " +
                "status=1 and (manage_result=0 or manage_result is null) ";
        List<Map<String,Object>> result = jdbcTemplate.queryForList(sql);
        return result;
    }
    @Transactional
    public void handleHealthIndex(String id){
        String sql = " update wlyy_patient_health_index a set a.manageResult=1 where a.user='"+id+"' and  status=1 and (manage_result=0 or manage_result is null)  ";
        jdbcTemplate.execute(sql);
    }
}

+ 2 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/lifeCare/LifeCareOrderService.java

@ -790,6 +790,8 @@ public class LifeCareOrderService extends BaseJpaService<LifeCareOrderDO, LifeCa
        //3 已签到
        lifeCareOrderDO.setStatus(3);
        BaseDoctorDO doctorDO = doctorDao.findById(doctorId);
        lifeCareOrderDO.setDoctor(doctorId);
        lifeCareOrderDO.setDoctorName(doctorDO.getName());
        lifeCareOrderDO.setSignDoctor(doctorId);
        lifeCareOrderDO.setSignDoctorName(doctorDO.getName());
        lifeCareOrderDO.setUpdateTime(new Date());

+ 14 - 6
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/message/DoctorMessageService.java

@ -21,10 +21,8 @@ import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.*;
/**
 * Created by Bing on 2021/4/10.
@ -49,7 +47,7 @@ public class DoctorMessageService {
    /**
     *
     * @param doctor
     * @param type  11床位申请,11安全监护 ,12紧急救助
     * @param type  11床位申请,11安全监护 ,12紧急救助,13体征异常消息
     * @return
     */
    public JSONObject findDoctorAllMessage(String doctor,String type){
@ -92,7 +90,7 @@ public class DoctorMessageService {
            List<Map<String,Object>> listTmp = new ArrayList<>();
            String sql ="select count(*) count,patient_name,DATE_FORMAT(create_time,'%Y-%m-%d %H:%i:%S') create_time,serve_desc from base_security_monitoring_order ord where 1=1 " +
                    "and status <>-1 and status<> 0  ";
            sql+= "and  EXISTS ( SELECT 1 from base_service_package_sign_record sr,base_service_package_record r" +
            sql+= "and  EXISTS ( SELECT 1 from base_service_package_sign_record sr,base_service_package_record r," +
                    "base_team_member m " +
                    "where ord.patient = CONVERT(sr.patient USING utf8) and  sr.id = r.sign_id and sr.status=1 and " +
                    "  m.team_code = r.team_code   and sr.`status`=1  and m.doctor_code = '"+doctor+"' and m.del = '1') ";
@ -134,6 +132,16 @@ public class DoctorMessageService {
            }
            result.put("assistance",tmpJson);
        }
        if (typeNull||type.equals("13")){//居民体征异常消息
            JSONObject tmpJson = new JSONObject();
            Map<String,Object> tmpObj = new HashMap<>();
            String sql = " select count(idx.id) count,DATE_FORMAT( max(idx.record_date),'%Y-%m-%d %H:%i:%S') record_date from wlyy_patient_health_index idx where status=1 and (manage_result=0 or manage_result is null) " +
                    "and  EXISTS ( SELECT 1 from base_service_package_sign_record sr,base_service_package_record r ,base_team_member m " +
                    " where idx.user = CONVERT(sr.patient USING utf8) and  sr.id = r.sign_id and sr.status=1 and m.team_code = r.team_code " +
                    "  and sr.`status`=1  and m.doctor_code = '"+doctor+"' and m.del = '1')  order by idx.record_date desc   ";
            tmpObj = jdbcTemplate.queryForMap(sql);
            result.put("errorHealthIndex",tmpObj);
        }
        return result;
    }

+ 7 - 3
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/patient/CarePatientService.java

@ -249,17 +249,21 @@ public class CarePatientService extends BaseJpaService<BasePatientDO, BasePatien
     */
    @Transactional(rollbackFor = Exception.class)
    public void updPatientLabel(String jsonData,String patientId) throws Exception{
        patientLabelDao.deleteByPatientAndLabelType(patientId,"2");
        JSONArray jsonArray = JSON.parseArray(jsonData);
        List<WlyyPatientLabelDO> labelDOList = new ArrayList<>();
        for (int i=0;i<jsonArray.size();i++){
            WlyyPatientLabelDO labelDO = JSONObject.parseObject(jsonArray.getJSONObject(i).toJSONString(), WlyyPatientLabelDO.class);
            labelDO.setPatient(patientId);
            labelDO.setCzrq(new Date());
            labelDO.setLabelType("2");
            if(StringUtils.isNotBlank(labelDO.getLabelType())){
                patientLabelDao.deleteByPatientAndLabelType(patientId,labelDO.getLabelType());
            }else {
                patientLabelDao.deleteByPatientAndLabelType(patientId,"2");
                labelDO.setLabelType("2");
            }
            labelDOList.add(labelDO);
        }
        patientLabelDao.save(labelDOList);
            patientLabelDao.save(labelDOList);
    }
    public Boolean updatePatientPw(String id,String pw,String orgPw){

+ 198 - 146
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/security/SecurityMonitoringOrderService.java

@ -18,32 +18,31 @@ import com.yihu.jw.care.service.family.PatientFamilyMemberService;
import com.yihu.jw.care.service.sign.ServicePackageService;
import com.yihu.jw.care.util.ConstantUtil;
import com.yihu.jw.care.util.CountDistance;
import com.yihu.jw.care.util.MessageUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.contacts.PatientSosContactsDO;
import com.yihu.jw.entity.care.device.BasePatientOutBed;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.care.securitymonitoring.*;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.dao.ConsultTeamDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.emergency.EmergencyOrderVO;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.util.common.GpsUtil;
import com.yihu.jw.care.util.MessageUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.care.securitymonitoring.*;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.mysql.query.BaseJpaService;
import jdk.management.resource.internal.inst.FileOutputStreamRMHooks;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -351,19 +350,31 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        }
        if (5==orderDO.getOrderSource()){//睡眠带工单
            try {
                JSONObject monitorInfo = patientSignTopicInfo(null,orderDO.getPatient(),"preventOutOfBed");
                Map<String,Object> tmp = JSONObject.parseObject(objectMapper.writeValueAsString(monitorInfo));
                if ("true".equals( tmp.get("sleepStatus").toString())){
                    Map<String,Object> sleepInfo = (Map<String, Object>) tmp.get("sleepInfo");
                    sleepInfo.put("outBedTime","30分钟");
                }
                emergencyOrderVO.setInformation(tmp);
                JSONObject monitorInfo = JSONObject.parseObject(orderDO.getWarnInfo());
                monitorInfo = patientSignTopicInfo(monitorInfo,orderDO.getPatient(),"preventFall");
                emergencyOrderVO.setInformation(monitorInfo);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if (6==orderDO.getOrderSource()){//气感工单
            try {
                JSONObject monitorInfo = JSONObject.parseObject(orderDO.getWarnInfo());
                monitorInfo = patientSignTopicInfo(monitorInfo,orderDO.getPatient(),"preventFall");
                emergencyOrderVO.setInformation(monitorInfo);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if (7==orderDO.getOrderSource()){//烟感工单
            try {
                JSONObject monitorInfo = JSONObject.parseObject(orderDO.getWarnInfo());
                monitorInfo = patientSignTopicInfo(monitorInfo,orderDO.getPatient(),"preventFall");
                emergencyOrderVO.setInformation(monitorInfo);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //TODO 火灾、燃气、离床专题返回值
        // http://192.168.1.103:85/%E5%8C%BB%E5%85%BB%E7%BB%93%E5%90%88/V0.7.0/#g=1&p=%E6%96%B0%E5%AE%89%E9%98%B2%E5%8C%85
        //通知对象
        List<Map<String,Object>> noticePersons = new ArrayList<>();
@ -1217,145 +1228,186 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        return result;
    }
    public JSONObject patientSignTopicInfo(JSONObject result,String patient,String topicItem){
        if (null==result){
            result = new JSONObject();
    public void preventLost(JSONObject result,String patient){
        List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByUserAndCategoryCode(patient,"4");
        if (devicePatientDeviceDos.size()==0){
            return;
        }
        if ("preventLost".equals(topicItem)||StringUtils.isBlank(topicItem)){
            List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByUserAndCategoryCode(patient,"4");
            if (devicePatientDeviceDos.size()==0){}
            else {
                DevicePatientDevice device = devicePatientDeviceDos.get(0);
                result.put("deviceSn",device.getDeviceSn());
                try {
                    JSONObject response= patientDeviceService.getAqgDeviceInfo(device.getDeviceSn());
                    if (response!=null){
                        //定位信息
                        if (response.containsKey("last_location")&&response.get("last_location")!=null){
                            JSONObject locationTmp = response.getJSONObject("last_location");
                            Double lon = locationTmp.getJSONArray("coordinates").getDouble(0);
                            Double lat = locationTmp.getJSONArray("coordinates").getDouble(1);
                            JSONObject tmp = gpsUtil.gcj02_To_Bd09(lat,lon);
                            tmp.put("city",response.getString("last_city"));
                            tmp.put("province",response.getString("last_province"));
                            tmp.put("address",response.getString("last_address"));
                            result.put("location",tmp);
                        }
                        //围栏信息
                        if (response.containsKey("fences")&&response.get("fences")!=null){
                            JSONArray fencesArr = response.getJSONArray("fences");
                            JSONArray fencesEnables = new JSONArray();
                            for (int i=0;i<fencesArr.size();i++){
                                JSONObject tmp = fencesArr.getJSONObject(i);
                                if (tmp.getBooleanValue("enable")){//围栏生效
                                    JSONObject fenceTmp = new JSONObject();
                                    fenceTmp.put("fenceNO",tmp.getInteger("seqid").toString());
                                    fenceTmp.put("name",tmp.getString("name"));
                                    JSONArray fenceLocationTmp = tmp.getJSONObject("safe_area").getJSONArray("coordinates").getJSONArray(0);
                                    JSONArray fenceLocation = new JSONArray();
                                    for (int j=0;j<fenceLocationTmp.size();j++){
                                        Double lon = fenceLocationTmp.getJSONArray(j).getDouble(0);
                                        Double lat = fenceLocationTmp.getJSONArray(j).getDouble(1);
                                        JSONObject positionTmp = gpsUtil.gcj02_To_Bd09(lat,lon);
                                        fenceLocation.add(positionTmp);
                                    }
                                    fenceTmp.put("location",fenceLocation);
                                    fenceTmp.put("inFenceStatus",countDistance.isInPolygon(result.getJSONObject("location").getDouble("lon"),result.getJSONObject("location").getDouble("lat"),fenceLocation));
                                    fencesEnables.add(fenceTmp);
                                }
                            }
                            if (fencesEnables.size()>0){
                                result.put("fences",fencesEnables);
        DevicePatientDevice device = devicePatientDeviceDos.get(0);
        result.put("deviceSn",device.getDeviceSn());
        try {
            JSONObject response= patientDeviceService.getAqgDeviceInfo(device.getDeviceSn());
            if (response!=null){
                //定位信息
                if (response.containsKey("last_location")&&response.get("last_location")!=null){
                    JSONObject locationTmp = response.getJSONObject("last_location");
                    Double lon = locationTmp.getJSONArray("coordinates").getDouble(0);
                    Double lat = locationTmp.getJSONArray("coordinates").getDouble(1);
                    JSONObject tmp = gpsUtil.gcj02_To_Bd09(lat,lon);
                    tmp.put("city",response.getString("last_city"));
                    tmp.put("province",response.getString("last_province"));
                    tmp.put("address",response.getString("last_address"));
                    result.put("location",tmp);
                }
                //围栏信息
                if (response.containsKey("fences")&&response.get("fences")!=null){
                    JSONArray fencesArr = response.getJSONArray("fences");
                    JSONArray fencesEnables = new JSONArray();
                    for (int i=0;i<fencesArr.size();i++){
                        JSONObject tmp = fencesArr.getJSONObject(i);
                        if (tmp.getBooleanValue("enable")){//围栏生效
                            JSONObject fenceTmp = new JSONObject();
                            fenceTmp.put("fenceNO",tmp.getInteger("seqid").toString());
                            fenceTmp.put("name",tmp.getString("name"));
                            JSONArray fenceLocationTmp = tmp.getJSONObject("safe_area").getJSONArray("coordinates").getJSONArray(0);
                            JSONArray fenceLocation = new JSONArray();
                            for (int j=0;j<fenceLocationTmp.size();j++){
                                Double lon = fenceLocationTmp.getJSONArray(j).getDouble(0);
                                Double lat = fenceLocationTmp.getJSONArray(j).getDouble(1);
                                JSONObject positionTmp = gpsUtil.gcj02_To_Bd09(lat,lon);
                                fenceLocation.add(positionTmp);
                            }
                            fenceTmp.put("location",fenceLocation);
                            fenceTmp.put("inFenceStatus",countDistance.isInPolygon(result.getJSONObject("location").getDouble("lon"),result.getJSONObject("location").getDouble("lat"),fenceLocation));
                            fencesEnables.add(fenceTmp);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    result.put("location",null);
                }
            }
        }
        if ("preventFall".equals(topicItem)||StringUtils.isBlank(topicItem)){
            List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByUserAndCategoryCode(patient,"12");
            if (devicePatientDeviceDos.size()==0){}
            else{
                try {
                    DevicePatientDevice deviceDo = devicePatientDeviceDos.get(0);
                    JSONObject monitorUrl = ysDeviceServicel.getDeviceLiveAddress(patient,deviceDo.getDeviceSn(),1,null);
                    result.put("monitorInfoStatus",monitorUrl.getIntValue(ResponseContant.resultFlag));
                    result.put("patientAddress",deviceDo.getSosAddress());
                    if (monitorUrl.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail){
                        result.put("monitorInfo",monitorUrl.getString(ResponseContant.resultMsg));
                    }
                    else {
                        result.put("monitorInfo",monitorUrl.getJSONObject(ResponseContant.resultMsg));
                    if (fencesEnables.size()>0){
                        result.put("fences",fencesEnables);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            result.put("location",null);
        }
        if ("preventOutOfBed".equals(topicItem)||StringUtils.isBlank(topicItem)){
            List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByUserAndCategoryCode(patient,"13");
            if (devicePatientDeviceDos.size()==0){}
            else {
                DevicePatientDevice deviceDo = devicePatientDeviceDos.get(0);
                JSONObject deviceInfo =  patientDeviceService.getSleepDeviceInfo(deviceDo.getDeviceSn());
                if(deviceInfo.getBooleanValue("success")){
                    result.put("patientAddress",deviceDo.getSosAddress());
                    JSONArray objInfo = deviceInfo.getJSONArray("objs");
                    if (objInfo.size()>0){
                        result.put("sleepStatus",true);
                        JSONObject tmp = objInfo.getJSONObject(0);
                        JSONObject sleepInfo = new JSONObject();
                        sleepInfo.put("online",tmp.getBooleanValue("online"));
                        sleepInfo.put("onbed",tmp.getBooleanValue("onbed"));
                        sleepInfo.put("heartrate",tmp.getString("heartrate"));
                        sleepInfo.put("breathrate",tmp.getString("breathrate"));
                        BasePatientOutBed outBed = outBedDao.findByPatientAndDeviceSnAndStatus(patient,deviceDo.getDeviceSn(),0);
                        if (null!=outBed){
                            String outBedTime = "";
                            Date date = new Date();
                            long millisecondsDiff = date.getTime() - outBed.getCreateTime().getTime();
                            long minutesDiff = millisecondsDiff / TimeUnit.MINUTES.toMillis(1L);
                            long hoursDiff = millisecondsDiff / TimeUnit.HOURS.toMillis(1L);
                            long minuteFieldDiff = minutesDiff - TimeUnit.HOURS.toMinutes(hoursDiff);
                            if (hoursDiff > 0L) {
                                outBedTime += String.format("%d小时", hoursDiff);
                            }
                            if (minuteFieldDiff>0){
                                outBedTime +=String.format("%d分钟", minuteFieldDiff);
                            }
                            sleepInfo.put("outBedTime",outBedTime);
                        }else {
                            sleepInfo.put("outBedTime","无");
    }
    public void preventOutOfBed(JSONObject result,String patient){
        List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByUserAndCategoryCode(patient,"13");
        if (devicePatientDeviceDos.size()==0){}
        else {
            DevicePatientDevice deviceDo = devicePatientDeviceDos.get(0);
            JSONObject deviceInfo =  patientDeviceService.getSleepDeviceInfo(deviceDo.getDeviceSn());
            if(deviceInfo.getBooleanValue("success")){
                result.put("patientAddress",deviceDo.getSosAddress());
                JSONArray objInfo = deviceInfo.getJSONArray("objs");
                if (objInfo.size()>0){
                    result.put("sleepStatus",true);
                    JSONObject tmp = objInfo.getJSONObject(0);
                    JSONObject sleepInfo = new JSONObject();
                    sleepInfo.put("online",tmp.getBooleanValue("online"));
                    sleepInfo.put("onbed",tmp.getBooleanValue("onbed"));
                    sleepInfo.put("heartrate",tmp.getString("heartrate"));
                    sleepInfo.put("breathrate",tmp.getString("breathrate"));
                    BasePatientOutBed outBed = outBedDao.findByPatientAndDeviceSnAndStatus(patient,deviceDo.getDeviceSn(),0);
                    if (null!=outBed){
                        String outBedTime = "";
                        Date date = new Date();
                        long millisecondsDiff = date.getTime() - outBed.getCreateTime().getTime();
                        long minutesDiff = millisecondsDiff / TimeUnit.MINUTES.toMillis(1L);
                        long hoursDiff = millisecondsDiff / TimeUnit.HOURS.toMillis(1L);
                        long minuteFieldDiff = minutesDiff - TimeUnit.HOURS.toMinutes(hoursDiff);
                        if (hoursDiff > 0L) {
                            outBedTime += String.format("%d小时", hoursDiff);
                        }
                        if (minuteFieldDiff>0){
                            outBedTime +=String.format("%d分钟", minuteFieldDiff);
                        }
                        result.put("sleepInfo",sleepInfo);
                        sleepInfo.put("outBedTime",outBedTime);
                    }else {
                        sleepInfo.put("outBedTime","无");
                    }
                }else {
                    result.put("sleepStatus",false);
                    result.put("sleepInfo","获取睡眠带数据失败");
                    result.put("sleepInfo",sleepInfo);
                }
            }else {
                result.put("sleepStatus",false);
                result.put("sleepInfo","获取睡眠带数据失败");
            }
            //监控
            devicePatientDeviceDos = patientDeviceDao.findByUserAndCategoryCode(patient,"12");
            if (devicePatientDeviceDos.size()==0){}
            else{
                try {
                    DevicePatientDevice deviceDo = devicePatientDeviceDos.get(0);
                    JSONObject monitorUrl = ysDeviceServicel.getDeviceLiveAddress(patient,deviceDo.getDeviceSn(),1,null);
                    result.put("monitorInfoStatus",monitorUrl.getIntValue(ResponseContant.resultFlag));
                    result.put("patientAddress",deviceDo.getSosAddress());
                    if (monitorUrl.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail){
                        result.put("monitorInfo",monitorUrl.getString(ResponseContant.resultMsg));
                    }
                    else {
                        result.put("monitorInfo",monitorUrl.getJSONObject(ResponseContant.resultMsg));
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
        }
        monitorInfo(result, patient);
    }
    public void preventFire(JSONObject result,String patient){
        String sql = "SELECT r.value from wlyy_patient_device pd,base_device_health_index r " +
                "WHERE pd.device_sn = r.device_sn and pd.`user` = '"+patient+"' ";
        sql += " and pd.category_code='15' ORDER BY r.create_time desc LIMIT 1";
        List<Map<String,Object>> list1 = jdbcTemplate.queryForList(sql);
        if(list1.size()==0){
            result.put("smoke","-1");
        }else{
            result.put("smoke",list1.get(0).get("value"));
        }
        result.put("smokeOrderNum",getOrder(patient,"preventFire"));
        monitorInfo(result, patient);
    }
    public Integer getOrder(String patient,String topicItem){
        String sql = "select count(1) from base_security_monitoring_order " +
                "WHERE patient = '"+patient+"' and `status` = 1 and topic_item = '"+topicItem+"'";
        Integer num = jdbcTemplate.queryForObject(sql,Integer.class);
        return num;
    }
    public void preventGasLeakage(JSONObject result,String patient){
        String sql = "SELECT r.value from wlyy_patient_device pd,base_device_health_index r " +
                "WHERE pd.device_sn = r.device_sn and pd.`user` = '"+patient+"' ";
        sql += " and pd.category_code='14' ORDER BY r.create_time desc LIMIT 1";
        List<Map<String,Object>> list1 = jdbcTemplate.queryForList(sql);
        if(list1.size()==0){
            result.put("methane","-1");
        }else{
            result.put("methane",list1.get(0).get("value"));
        }
        result.put("methaneOrderNum",getOrder(patient,"preventGasLeakage"));
        monitorInfo(result, patient);
    }
    public void monitorInfo(JSONObject result,String patient){
        //监控
        List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByUserAndCategoryCode(patient,"12");
        if (devicePatientDeviceDos.size()==0){
            return;
        }
        try {
            DevicePatientDevice deviceDo = devicePatientDeviceDos.get(0);
            JSONObject monitorUrl = ysDeviceServicel.getDeviceLiveAddress(patient,deviceDo.getDeviceSn(),1,null);
            result.put("monitorInfoStatus",monitorUrl.getIntValue(ResponseContant.resultFlag));
            result.put("patientAddress",deviceDo.getSosAddress());
            if (monitorUrl.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail){
                result.put("monitorInfo",monitorUrl.getString(ResponseContant.resultMsg));
            }
            else {
                result.put("monitorInfo",monitorUrl.getJSONObject(ResponseContant.resultMsg));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public JSONObject patientSignTopicInfo(JSONObject result,String patient,String topicItem){
        if (null==result){
            result = new JSONObject();
        }
        if ("preventLost".equals(topicItem)||StringUtils.isBlank(topicItem)){
            preventLost(result, patient);
        }
        if ("preventFall".equals(topicItem)||StringUtils.isBlank(topicItem)){
            monitorInfo(result, patient);
        }
        if ("preventOutOfBed".equals(topicItem)||StringUtils.isBlank(topicItem)){
            preventOutOfBed(result, patient);
        }
        if ("preventFire".equals(topicItem)||StringUtils.isBlank(topicItem)){
            preventFire(result, patient);
        }
        if ("preventGasLeakage".equals(topicItem)||StringUtils.isBlank(topicItem)){
            preventGasLeakage(result, patient);
        }
        return result;
    }

+ 1 - 1
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/sign/ArchiveService.java

@ -81,7 +81,7 @@ public class ArchiveService extends BaseJpaService<ArchiveDO, ArchiveDao> {
    }
    public PageEnvelop<List<Map<String,Object>>> archiveList(String doctorId, int page, int size,Integer signStatus,String name){
        String sql = " select * from ( SELECT a.create_time,p.openid,p.idcard,p.mobile,p.name,p.sex,p.id,p.photo,CAST(a.sign_status AS char) sign_status ";
        String sql = " select * from ( SELECT a.create_time,p.openid,p.pad_imei padImei,p.idcard,p.mobile,p.name,p.sex,p.id,p.photo,CAST(a.sign_status AS char) sign_status ";
        String countSql = "SELECT count(*) from ( ";
        String filters = "from wlyy_archive a,base_patient p " +

+ 214 - 3
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/statistics/DetectionPlatformService.java

@ -1,14 +1,28 @@
package com.yihu.jw.care.service.statistics;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xerces.internal.xs.datatypes.ByteList;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.service.device.PatientDeviceService;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.utils.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/***
 * @ClassName: DetectionPlatformService
@ -23,14 +37,23 @@ public class DetectionPlatformService  {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private BasePatientDao patientDao;
    /**
     * 体征监测 安防监护
     * @param page
     * @param pageSize
     * @param type
     * @return
     */
    public PageEnvelop getHealthMonitoringListNew(Integer page, Integer pageSize, Integer type){
        page = page>0?page-1:0;
        if (type == 1) {
            String sql = " SELECT id,user,`name`,'健康监测' as serve_desc,czrq,value1,value2,value3,value4,value5,value6,value7,type \n" +
                    "FROM wlyy_patient_health_index WHERE del = 1 AND type < 3 ORDER BY czrq ";
                    "FROM wlyy_patient_health_index WHERE del = 1 AND type < 3 ORDER BY czrq desc ";
            String countSql = "select count(id) from ("+sql+")A ";
            long count = jdbcTemplate.queryForObject(countSql,long.class);
            sql +=" limit "+page*pageSize+","+pageSize;
@ -45,8 +68,196 @@ public class DetectionPlatformService  {
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
            return PageEnvelop.getSuccessListWithPage("查询成功",list,page,pageSize,count);
        }
    }
    public JSONObject getDeviceComapny(){
        JSONObject object = new JSONObject();
        String deviceTypeSum = "SELECT * FROM wlyy_devices WHERE device_name IS NOT NULL AND device_name != '' GROUP BY device_name";
        List<Map<String , Object>> deviceList = jdbcTemplate.queryForList(deviceTypeSum);
        if (deviceList.size() > 0) {
            object.put("deviceTypeCount",deviceList.size()); //设备品牌数量
        } else {
            object.put("deviceTypeCount",0);
        }
        String manufacturerSql = "SELECT * FROM wlyy_devices WHERE manufacturer IS NOT NULL AND manufacturer != '' GROUP BY manufacturer ;";
        List<Map<String , Object>> manufacturerList = jdbcTemplate.queryForList(manufacturerSql);
        if (manufacturerList.size() > 0) {
            object.put("manufacturerCount",manufacturerList.size()); //入驻厂商数量
        } else {
            object.put("manufacturerCount",0);
        }
        String securitySql = "SELECT allCount,isUse,(allCount - isUse) inventory FROM \n" +
                "(SELECT COUNT(1) allCount FROM wlyy_devices WHERE device_type = 1) allCount,\n" +
                "(SELECT COUNT(pd.id) isUse FROM wlyy_devices d,wlyy_patient_device pd WHERE d.device_type = 1 AND d.device_code = pd.device_sn AND pd.del = 0) isUse";
        List<Map<String , Object>> securityList = jdbcTemplate.queryForList(securitySql);
        if (securityList.size() > 0) {
            object.put("securityAllCount",securityList.get(0).get("allCount")); //安防设备总量
            object.put("securityIsUseCount",securityList.get(0).get("isUse"));//安防设备使用中数量
            object.put("securityInventoryCount",securityList.get(0).get("inventory"));//安防设备库存量
        } else {
            object.put("securityAllCount",0); //安防设备总量
            object.put("securityIsUseCount",0);//安防设备使用中数量
            object.put("securityInventoryCount",0);//安防设备库存量
        }
        String healthSql = "SELECT allCount,isUse,(allCount - isUse) inventory FROM \n" +
                "(SELECT COUNT(1) allCount FROM wlyy_devices WHERE device_type = 0) allCount,\n" +
                "(SELECT COUNT(pd.id) isUse FROM wlyy_devices d,wlyy_patient_device pd WHERE d.device_type = 0 AND d.device_code = pd.device_sn AND pd.del = 0) isUse";
        List<Map<String , Object>> healthList = jdbcTemplate.queryForList(healthSql);
        if (healthList.size() > 0) {
            object.put("healthAllCount",securityList.get(0).get("allCount"));//健康设备总量
            object.put("healthIsUseCount",securityList.get(0).get("isUse"));//健康设备使用中数量
            object.put("healthInventoryCount",securityList.get(0).get("inventory"));//健康设备库存量
        } else {
            object.put("healthAllCount",0);//健康设备总量
            object.put("healthIsUseCount",0);//健康设备使用中数量
            object.put("healthInventoryCount",0);//健康设备库存量
        }
        Long securityIsUser = (Long) securityList.get(0).get("isUse");
        Long healthIsUser = (Long) healthList.get(0).get("isUse");
        Long securityAllCount = (Long) securityList.get(0).get("allCount");
        Long healthAllCount = (Long) healthList.get(0).get("allCount");
        object.put("lawOfIOT",getRange( (securityIsUser.intValue() + healthIsUser.intValue() ),( securityAllCount.intValue() + healthAllCount.intValue()  ) ));//物联率
        object.put("isUseAllIot",(securityIsUser.intValue() + healthIsUser.intValue()));//已发放设备
        object.put("allIot",securityAllCount.intValue() + healthAllCount.intValue());//总设备
//        String unUseSql = "";//连续一周为上传数据
//        List<Map<String , Object>> unUseList = jdbcTemplate.queryForList(unUseSql);
//        Long unUseCount = (Long) securityList.get(0).get("allCount");
////        if (unUseList.size() > 0){
////            unUseCount = (Long) securityList.get(0).get("allCount");
////        }
//        object.put("lostLaw",getRange(unUseCount.intValue(),securityIsUser.intValue() + healthIsUser.intValue()));//设备失联率
        object.put("lostLaw","0%");//设备失联率
        return object;
    }
    public String getRange(int first, int second) {
        if (second == 0 && first > 0) {
            //如果分母为0 分子不为0 返回100%
            return "100%";
        } else if (second == 0 && first == 0) {
            //如果分母为0 分子为0 返回0%
            return "0%";
        }
        float size = (float) (first * 100) / second;
        DecimalFormat df = new DecimalFormat("0.00");//格式化小数,不足的补0
        String filesize = df.format(size);
        return filesize + "%";
    }
    public List<Map<String , Object>> getDeviceType(){
        String sql = "SELECT category_code,device_name FROM wlyy_patient_device GROUP BY category_code";
        return jdbcTemplate.queryForList(sql);
    }
    public JSONArray getDeviceByCondition(String categoryCode , String user){
        JSONArray jsonArray = new JSONArray();
        List<DevicePatientDevice> patientDevices = patientDeviceDao.findAll();
        if (StringUtils.isNotBlank(categoryCode)) {  //categoryCode != null   根据设备类型查询
            patientDevices = patientDeviceDao.findAllByCategoryCode(categoryCode);
        }
        Map<String, List<DevicePatientDevice>> byUser = patientDevices.stream().collect(Collectors.groupingBy(DevicePatientDevice::getUser));
        List<BasePatientDO> patientDOS = patientDao.findAllByDel();
        if (StringUtils.isNotBlank(user)) {
            patientDOS = patientDao.findAllByDelAndId(user);  //user != null   根据居民查询
        }
        Map<String, List<BasePatientDO>> byId = patientDOS.stream().collect(Collectors.groupingBy(BasePatientDO::getId));
        //首页默认根据居民展示  绑定设备的居民
        String userSql = "SELECT `user` FROM wlyy_patient_device WHERE del = 0 GROUP BY `user`";
        List<Map<String , Object>> userList = jdbcTemplate.queryForList(userSql);
        if (userList.size() > 0) {
            JSONObject userObj = new JSONObject();
            for (int i=0;i<userList.size();i++) {
                JSONArray arrayAll = new JSONArray();
                JSONArray array = new JSONArray();
                userObj.put("patient",userList.get(i).get("user"));
                userObj.put("patientName",byId.get(userList.get(i).get("user")).get(0).getName());
                userObj.put("patientType",byId.get(userList.get(i).get("user")).get(0).getArchiveType());
                userObj.put("latLon",byId.get(userList.get(i).get("user")).get(0).getLatLon());
                List<DevicePatientDevice> deviceList = byUser.get(userList.get(i).get("user"));
                if (deviceList.size() > 1) {    //居民绑定多台设备
                    for (int j=0;j<deviceList.size();j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("deviceSn",deviceList.get(j).getDeviceSn());
                        obj.put("deviceName",deviceList.get(j).getDeviceName());
                        obj.put("categoryCode",deviceList.get(j).getCategoryCode());
                        array.add(obj);
                    }
                    userObj.put("deviceCount",deviceList.size());
                    userObj.put("deviceInfo",array);
                    arrayAll.add(userObj);
                } else {    //居民只绑定一台设备
                    for (int j=0;j<deviceList.size();j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("deviceSn",deviceList.get(j).getDeviceSn());
                        obj.put("deviceName",deviceList.get(j).getDeviceName());
                        obj.put("categoryCode",deviceList.get(j).getCategoryCode());
                        array.add(obj);
                    }
                    userObj.put("deviceCount",deviceList.size());
                    userObj.put("deviceInfo",array);
                    arrayAll.add(userObj);
                }
                jsonArray.add(arrayAll);
            }
        } else {
            return jsonArray;
        }
        return jsonArray;
    }
    public JSONObject getDeviceInfo(String deviceSn) throws Exception{
        String categoryCode = "";
        JSONObject object = new JSONObject();
        String deviceInfoSql = "SELECT device_name deviceName,device_type deviceType,device_code deviceSn,manufacturer FROM wlyy_devices WHERE  device_code = '"+deviceSn+"' ";
        List<Map<String , Object>> deviceInfoList = jdbcTemplate.queryForList(deviceInfoSql);
        if (deviceInfoList.size() > 0){
            object.put("deviceName",deviceInfoList.get(0).get("deviceName"));
            object.put("deviceType",deviceInfoList.get(0).get("deviceType"));
            object.put("deviceSn",deviceInfoList.get(0).get("deviceSn"));
            object.put("manufacturer",deviceInfoList.get(0).get("manufacturer"));
            String patientInfoSql = "SELECT p.`name` patientName,p.id patient,p.mobile,p.idcard,p.address,pd.category_code categoryCode " +
                    "FROM wlyy_patient_device pd,base_patient p WHERE p.id = pd.`user` AND p.del = 1 AND pd.del = 0 AND pd.device_sn = '"+deviceSn+"'";
            List<Map<String , Object>> patientInfoList = jdbcTemplate.queryForList(patientInfoSql);
            if (patientInfoList.size() > 0) {
                categoryCode = patientInfoList.get(0).get("categoryCode").toString();
                object.put("patientName",patientInfoList.get(0).get("patientName"));
                object.put("patient",patientInfoList.get(0).get("patient"));
                object.put("mobile",patientInfoList.get(0).get("mobile"));
                object.put("idcard",patientInfoList.get(0).get("idcard"));
                object.put("address",patientInfoList.get(0).get("address"));
                String dataSql= "";
                List<Map<String , Object>> dataList = new ArrayList<>();
                switch (categoryCode) {
                    // 1=血糖仪  2=血压计  4=智能手表  13=智能床带/睡眠带  14=燃气报警器  15=烟雾报警器
                    case "1" :
                        dataSql = "SELECT record_date recordDate,value1,value2,value3,value4,value5,value6,value7,type FROM wlyy_patient_health_index WHERE device_sn = '"+deviceSn+"' AND del = 1 ORDER BY sort_date DESC LIMIT 10";
                        dataList = jdbcTemplate.queryForList(dataSql);
                        object.put("data",dataList);
                        break;
                    case "2" :
                        dataSql = "SELECT record_date recordDate,value1,value2,value3,value4,value5,value6,value7,type FROM wlyy_patient_health_index WHERE device_sn = '"+deviceSn+"' AND del = 1 ORDER BY sort_date DESC LIMIT 10";
                        dataList = jdbcTemplate.queryForList(dataSql);
                        object.put("data",dataList);
                        break;
                    case "14" :
                        dataSql = "SELECT record_time recordDate,`value`,unit,device_type FROM base_device_health_index WHERE device_sn = '"+deviceSn+"' ORDER BY record_time DESC LIMIT 10 ";
                        dataList = jdbcTemplate.queryForList(dataSql);
                        object.put("data",dataList);
                        break;
                    case "15" :
                        dataSql = "SELECT record_time recordDate,`value`,unit,device_type FROM base_device_health_index WHERE device_sn = '"+deviceSn+"' ORDER BY record_time DESC LIMIT 10 ";
                        dataList = jdbcTemplate.queryForList(dataSql);
                        object.put("data",dataList);
                        break;
                }
            } else {
                throw new Exception("无法找到该设备对应使用人");
            }
        }else {
            throw new Exception("设备SN码对应的设备不存在!");
        }
        return object;
    }
}

+ 250 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/ArtemisPostTest.java

@ -0,0 +1,250 @@
package com.yihu.jw.care.util;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class ArtemisPostTest {
	/**
	 * 请根据自己的appKey和appSecret更换static静态块中的三个参数. [1 host]
	 * 如果你选择的是和现场环境对接,host要修改为现场环境的ip,https端口默认为443,http端口默认为80.例如10.33.25.22:443 或者10.33.25.22:80
	 * appKey和appSecret请按照或得到的appKey和appSecret更改.
	 * TODO 调用前先要清楚接口传入的是什么,是传入json就用doPostStringArtemis方法,下载图片doPostStringImgArtemis方法
	 */
	static {
		ArtemisConfig.host = "open.hikfirecloud.com";// 代理API网关nginx服务器ip端口
		ArtemisConfig.appKey = "23553385";// 秘钥appkey
		ArtemisConfig.appSecret = "HfjuKlQnzTbn0mfxm5Vk";// 秘钥appSecret
	}
	/**
	 * 能力开放平台的网站路径
	 * TODO 路径不用修改,就是/artemis
	 */
	private static final String ARTEMIS_PATH = "/artemis";
	/**
	 * 调用POST请求类型(application/json)接口,这里以入侵报警事件日志为例
	 * https://open.hikvision.com/docs/918519baf9904844a2b608e558b21bb6#e6798840
	 *
	 * @return
	 */
	public static String callPostStringApi(String url,String body){
		/**
		 * http://10.33.47.50/artemis/api/scpms/v1/eventLogs/searches
		 * 根据API文档可以看出来,这是一个POST请求的Rest接口,而且传入的参数值为一个json
		 * ArtemisHttpUtil工具类提供了doPostStringArtemis这个函数,一共六个参数在文档里写明其中的意思,因为接口是https,
		 * 所以第一个参数path是一个hashmap类型,请put一个key-value,query为传入的参数,body为传入的json数据
		 * 传入的contentType为application/json,accept不指定为null
		 * header没有额外参数可不传,指定为null
		 *
		 */
		final String getCamsApi = ARTEMIS_PATH + url;
		Map<String, String> path = new HashMap<String, String>(2) {
			{
				put("https://", getCamsApi);//根据现场环境部署确认是http还是https
			}
		};
		String result = ArtemisHttpUtil.doPostStringArtemis(path,body,null,null,"application/json",null);// post请求application/json类型参数
		return result;
	}
	/**
	 * 调用POST请求下载图片类型接口,这里以获取访客记录中的图片接口为例
	 * https://open.hikvision.com/docs/a0a1a0a24701a00aa904f7b151f97410#f11f3208
	 *
	 * @return
	 */
	public static void callPostImgStringApi(){
		/**
		 * http://10.33.47.50/api/visitor/v1/record/pictures
		 * 根据API文档可以看出来,这是一个POST请求的Rest接口,而且传入的参数值为一个json
		 * ArtemisHttpUtil工具类提供了doPostStringImgArtemis这个函数,一共六个参数在文档里写明其中的意思,因为接口是https,
		 * 所以第一个参数path是一个hashmap类型,请put一个key-value,query为传入的参数,body为传入的json数据
		 * 传入的contentType为application/json,accept不指定为null
		 * header没有额外参数可不传,指定为null
		 *
		 */
		final String VechicleDataApi = ARTEMIS_PATH +"/api/visitor/v1/record/pictures";
		Map<String,String> path = new HashMap<String,String>(2){
			{
				put("http://",VechicleDataApi);
			}
		};
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("svrIndexCode", "8907fd9d-d090-43d3-bb3a-3a4b10dd7219");
		jsonBody.put("picUri", "/pic?0dd453i3c-e*046456451175m6ep=t=i2p*i=d1s*i3d0d*=*1b8i81f4747059503--bdf90a-855s5721z3b9i=1=");
		String body = jsonBody.toJSONString();
		System.out.println("body: "+body);
		HttpResponse result = ArtemisHttpUtil.doPostStringImgArtemis(path,body,null,null,"application/json",null);
		try {
			HttpResponse resp = result;
			if (200==resp.getStatusLine().getStatusCode()) {
				HttpEntity entity = resp.getEntity();
				InputStream in = entity.getContent();
				Tools.savePicToDisk(in, "d:/", "test4.jpg");
				System.out.println("下载成功");
			}else{
				System.out.println("下载出错");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 消息订阅
	 *
	 * 980001	资源信息变更通知	1
		 980002	报警实时信息	2
		 980003	报警处理信息	3
		 980004	故障实时信息	4
		 980005	故障处理信息	5
		 980006	设备在离线消息	6
		 980007	监控点在离线消息	7
		 980008	监测实时信息	8
     */
	public static void subscription_info(String msgType){
		String url = "/api/firepro/v1/subscription/info";
		//消息类型	msgType	String	是
		//回调URL	postUrl	String	是
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("msgType", msgType);
		jsonBody.put("postUrl", "http://ehr.yihu.com/wlyy/aqg/hvdevice/messageNotification");
		//http://ehr.yihu.com/wlyy/aqg/device/byOnlineStatus
		//http://ehr.yihu.com/wlyy/aqg
		String body = jsonBody.toJSONString();
		String StringeResult = callPostStringApi(url,body);
		System.out.println("StringeResult结果示例: "+StringeResult);
	}
	/**
	 * 修改订阅
	 */
	public void subscription_update(){
		String url = "/api/firepro/v1/subscription/update";
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("pageNo", 1);
		jsonBody.put("pageSize", 3);
		String body = jsonBody.toJSONString();
		String StringeResult = callPostStringApi(url,body);
		System.out.println("StringeResult结果示例: "+StringeResult);
	}
	/**
	 * 删除订阅
	 */
	public void subscription_deletion(){
		String url = "/api/firepro/v1/subscription/deletion";
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("pageNo", 1);
		jsonBody.put("pageSize", 3);
		String body = jsonBody.toJSONString();
		String StringeResult = callPostStringApi(url,body);
		System.out.println("StringeResult结果示例: "+StringeResult);
	}
	/**
	 * 设备监测信息查询
	 */
	public static String getMonitor(String deviceID){
		String url = "/api/firepro/v1/getMonitor";
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("deviceID", deviceID);
		jsonBody.put("pageNo", 1);
		jsonBody.put("pageSize", 1);
		jsonBody.put("flagId", "");
		jsonBody.put("offset", 0);
		String body = jsonBody.toJSONString();
		String StringeResult = callPostStringApi(url,body);
		return StringeResult;
	}
	/**
	 * 获取消防设备信息
	 */
	public static String getDevice(){
		String url = "/api/firepro/v1/getDevice";
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("pageNo", 1);
		jsonBody.put("pageSize", 500);
		jsonBody.put("flagId", "");
		jsonBody.put("offset", 0);
		String body = jsonBody.toJSONString();
		String StringeResult = callPostStringApi(url,body);
		return StringeResult;
	}
	/**
	 * 消防设备添加
	 *
	 * 设备名称	deviceName	String	true	设备名称
	 设备序列号	deviceSerial	String	true	设备序列号
	 设备型号	deviceModel	String	true	设备型号,详见字典表
	 800022	NP-FY200-N 烟
	 800056 JT-HK400-N 气
	 设备类型	deviceType	Number	true	设备类型,详见字典表
	 600002	独立式光电感烟探测器(NB)
	 600006	独立式可燃气体探测器(NB)
	 通讯类型	communicationType	Number	true	通讯类型,详见字典表
	 900004	NB移动
	 */
	public static void addDevice(String deviceName,String deviceSerial,String deviceModel,String deviceType){
		String url = "/api/bws/device/v1/add";
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("deviceName", deviceName);
		jsonBody.put("deviceSerial", deviceSerial);
		jsonBody.put("deviceModel", deviceModel);
		jsonBody.put("deviceType", deviceType);
		jsonBody.put("communicationType", "900004");
		String body = jsonBody.toJSONString();
		String StringeResult = callPostStringApi(url,body);
		System.out.println("StringeResult结果示例: "+StringeResult);
	}
	/**
	 * 查询订阅
	 */
	public void subscription_list(){
		String url = "/api/firepro/v1/subscription/list";
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("pageNo", 1);
		jsonBody.put("pageSize", 3);
		String body = jsonBody.toJSONString();
		String StringeResult = callPostStringApi(url,body);
		System.out.println("StringeResult结果示例: "+StringeResult);
	}
	public static void main(String[] args) {
//		String url = "/api/firepro/v1/getCompany";
//		JSONObject jsonBody = new JSONObject();
//		jsonBody.put("pageNo", 1);
//		jsonBody.put("pageSize", 3);
//		String body = jsonBody.toJSONString();
//		String StringeResult = callPostStringApi(url,body);
//		System.out.println("StringeResult结果示例: "+StringeResult);
//		callPostImgStringApi();
//		getDevice();
		System.out.println(getMonitor("635486270136270848"));
//		subscription_info("980001");
//		subscription_info("980002");
//		subscription_info("980003");
//		subscription_info("980004");
//		subscription_info("980005");
//		subscription_info("980006");
//		subscription_info("980007");
//		subscription_info("980008");
	}
}

+ 60 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/Tools.java

@ -0,0 +1,60 @@
package com.yihu.jw.care.util;/**
 * Created by lifutao on 2019/1/11.
 */
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
 * 工具类
 *
 * @author
 * @create 2019-01-11 17:06
 **/
public class Tools {
    /**
     * 将图片写到 硬盘指定目录下
     *
     * @param in
     * @param dirPath
     * @param filePath
     */
    public static void savePicToDisk(InputStream in, String dirPath,
                                      String filePath) {
        try {
            File dir = new File(dirPath);
            if (dir == null || !dir.exists()) {
                dir.mkdirs();
            }
            //文件真实路径
            String realPath = dirPath.concat(filePath);
            File file = new File(realPath);
            if (file == null || !file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = in.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

+ 5 - 17
svr/svr-cloud-device/pom.xml

@ -25,23 +25,7 @@
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!-- 支持Tomcat启动 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
@ -103,7 +87,11 @@
            <artifactId>HikariCP</artifactId>
            <!-- <scope>runtime</scope> -->
        </dependency>
        <dependency>
            <groupId>com.hikvision.ga</groupId>
            <artifactId>artemis-http-client</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>io.github.swagger2markup</groupId>
            <artifactId>swagger2markup</artifactId>

+ 19 - 0
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/dao/device/BaseSleepPlanDao.java

@ -0,0 +1,19 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.BaseSleepPlan;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/***
 * @ClassName: BaseSleepPlanDao
 * @Description:
 * @Auther: shi kejing
 * @Date: 2021/8/23 17:20
 */
public interface BaseSleepPlanDao extends PagingAndSortingRepository<BaseSleepPlan,Long>,
        JpaSpecificationExecutor<BaseSleepPlan> {
    List<BaseSleepPlan> findByPatientAndDeviceSn(String patient,String deviceSn);
}

+ 16 - 0
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/dao/device/BaseSleepPlanDetailDao.java

@ -0,0 +1,16 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.BaseSleepPlanDetail;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Bing on 2021/8/23.
 */
public interface BaseSleepPlanDetailDao extends PagingAndSortingRepository<BaseSleepPlanDetail,Long>,
        JpaSpecificationExecutor<BaseSleepPlanDetail> {
    List<BaseSleepPlanDetail> findByDay(String day);
}

+ 3 - 0
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/dao/device/DeviceDetailDao.java

@ -20,4 +20,7 @@ public interface DeviceDetailDao extends PagingAndSortingRepository<DeviceDetail
    @Query("select a from DeviceDetail a where a.deviceCode = ?1 and a.manufacturerCode = ?2")
    DeviceDetail findByDeviceCodeAndManufacturerCode(String deviceCode,String manufacturerCode);
    @Query("select a from DeviceDetail a where a.sim = ?2")
    List<DeviceDetail> findBySim(String sim);
}

+ 16 - 0
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/dao/device/DeviceHealthIndexDao.java

@ -0,0 +1,16 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.DeviceHealthIndex;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yeshijie
 * @Date: 2021/8/23
 * @Description:
 */
public interface DeviceHealthIndexDao extends PagingAndSortingRepository<DeviceHealthIndex, String>, JpaSpecificationExecutor<DeviceHealthIndex> {
}

+ 15 - 0
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/dao/device/HvDeviceRecordDao.java

@ -0,0 +1,15 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.HvDeviceRecord;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yeshijie
 * @Date: 2021/8/23
 * @Description:
 */
public interface HvDeviceRecordDao extends PagingAndSortingRepository<HvDeviceRecord, String>, JpaSpecificationExecutor<HvDeviceRecord> {
}

+ 16 - 0
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/dao/device/HvDeviceSosLogDao.java

@ -0,0 +1,16 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.HvDeviceSosLog;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yeshijie
 * @Date: 2021/8/23
 * @Description:
 */
public interface HvDeviceSosLogDao extends PagingAndSortingRepository<HvDeviceSosLog, String>, JpaSpecificationExecutor<HvDeviceSosLog> {
}

+ 125 - 2
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/DeviceController.java

@ -1,19 +1,27 @@
package com.yihu.jw.care.endpoint;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.dao.device.DeviceDetailDao;
import com.yihu.jw.care.service.DeviceService;
import com.yihu.jw.entity.care.device.DeviceDetail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created with IntelliJ IDEA.
@ -31,6 +39,121 @@ public class DeviceController {
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @RequestMapping(value = "/importDeviceFromExcel", produces = "application/json;charset=UTF-8",method = RequestMethod.POST)
    @ResponseBody
    public String importFromExcel(HttpServletRequest request,@ApiParam(value = "文件", required = true)
    @RequestParam(value = "file", required = true) MultipartFile file) {
        List errorLs = new ArrayList<>();
        List correctLs = new ArrayList<>();
        Map<String, String> errorMsgMap = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<String> deviceCodes = new ArrayList<>();
        try {
            request.setCharacterEncoding("UTF-8");
            InputStream inputStream = file.getInputStream();
            Workbook rwb = Workbook.getWorkbook(inputStream);
            Sheet[] sheets = rwb.getSheets();
            int rows;
            int row;
            String manufacturer=null;//厂商名称
            String deviceName; //设备名称
            String deviceModel; //设备型号
            String deviceCode;  //设备SN
            String sim;  //sim卡号
            String bindingCount; //单人{"1":"0"}  多人{"1":"0", "2":"0"}
            String deviceType; //设备种类  0健康设备 1安防设备
            Sheet sheet = sheets[0];    //第一张表
            rows = sheet.getRows();
            for (int j = 1; j < rows; j++) {
                if (sheet.getRow(j).length == 0) {
                    continue;
                }
                DeviceDetail deviceDetail = new DeviceDetail();
                row = j;
                manufacturer = sheet.getCell(0, row).getContents().trim();    //0 厂商名称
                deviceName = sheet.getCell(1, row).getContents().trim();  //1 设备名称
                deviceModel = sheet.getCell(2, row).getContents().trim();   //2 设备型号
                deviceCode = sheet.getCell(3, row).getContents().trim(); //3 设备SN
                sim = sheet.getCell(4, row).getContents().trim();  //4 sim卡号
                bindingCount = sheet.getCell(5, row).getContents().trim(); //5
                deviceType = sheet.getCell(6, row).getContents().trim(); //6 设备种类
                if (StringUtils.isBlank(deviceCode)){
                    continue;
                }
                if (deviceCodes.contains(deviceCode)){
                    errorMsgMap.put(deviceCode,"设备SN码重复");
                    continue;
                }
                deviceCodes.add(deviceCode);
                if (StringUtils.isBlank(manufacturer)){
                    errorMsgMap.put(deviceCode,"厂商名称不能为空");
                    continue;
                }
                if (StringUtils.isBlank(deviceName)){
                    errorMsgMap.put(deviceCode,"设备名称不能为空");
                    continue;
                }
                if (StringUtils.isBlank(deviceModel)){
                    errorMsgMap.put(deviceCode,"设备型号不能为空");
                    continue;
                }
                if (StringUtils.isBlank(bindingCount)){
                    errorMsgMap.put(deviceCode,"设备类型不能为空");
                    continue;
                }
                if (StringUtils.isBlank(deviceType)){
                    errorMsgMap.put(deviceCode,"设备种类不能为空");
                    continue;
                }else {
                    if ("健康设备".equals(deviceType)){
                        deviceType = "1";
                    }
                    else if ("安防设备".equals(deviceType)){
                        deviceType= "0";
                    }
                    else {
                        errorMsgMap.put(deviceCode,"不支持该设备种类");
                        continue;
                    }
                }
                if (deviceDetailDao.findByDeviceCode(deviceCode).size()>0){
                    errorMsgMap.put(deviceCode,"该设备SN码已存在");
                    continue;
                }
                if (StringUtils.isNotBlank(sim) && deviceDetailDao.findBySim(sim).size()>0){
                    errorMsgMap.put(deviceCode,"该sim卡号已存在");
                    continue;
                }
                deviceDetail.setApplyDate(sdf.format(new Date()));
                deviceDetail.setManufacturer(manufacturer);
                deviceDetail.setDeviceName(deviceName);
                deviceDetail.setDeviceModel(deviceModel);
                deviceDetail.setDeviceCode(deviceCode);
                deviceDetail.setSim(sim);
                deviceDetail.setBindingCount("");
                deviceDetail.setDeviceType(Integer.parseInt(deviceType));
                correctLs.add(deviceDetail);
            }
            deviceDetailDao.save(correctLs);
            //包装导入结果(导入成功数量、错误对象集合)
            Map<String, Object> map = new HashMap<>();
            map.put("successNum", correctLs.size());
            map.put("failedNum", rows-1 - correctLs.size() );
            map.put("errorData", JSON.toJSONString(errorMsgMap, SerializerFeature.WriteMapNullValue));
            System.out.println(map);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "操作失败!");
        }
    }
    @GetMapping("test")
    public String test(){

+ 17 - 0
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/DeviceUploadController.java

@ -49,4 +49,21 @@ public class DeviceUploadController {
            return Result.error("Device data incoming failure!"+ex.getMessage());
        }
    }
    @ApiOperation("拐杖数据接收")
    @RequestMapping(value = "/cane_upload", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public Result uploadDevicesData(
            @ApiParam(value="message",name="message")
            @RequestParam(value = "message", required = true)String message)
    {
        try{
            logger.info("message="+message);
            return deviceUploadService.caneUpload(message);
        }
        catch (Exception ex)
        {
            return Result.error("Device data incoming failure!"+ex.getMessage());
        }
    }
}

+ 153 - 0
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/HvDeviceController.java

@ -0,0 +1,153 @@
package com.yihu.jw.care.endpoint;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.service.HvDeviceService;
import com.yihu.jw.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
 * Created with IntelliJ IDEA.
 * 海威烟感 气感
 * @Author: yeshijie
 * @Date: 2021/8/20
 * @Description:
 */
@RestController
@RequestMapping("/hvdevice")
@Api(value = "海威设备相关服务", description = "海威设备相关服务")
public class HvDeviceController {
    private static Logger logger = LoggerFactory.getLogger(HvDeviceController.class);
    @Autowired
    private HvDeviceService hvDeviceService;
    /**
     * 消息订阅
     *
     * 980001	资源信息变更通知	1
     980002	报警实时信息	2
     980003	报警处理信息	3
     980004	故障实时信息	4
     980005	故障处理信息	5
     980006	设备在离线消息	6
     980007	监控点在离线消息	7
     980008	监测实时信息	8
     */
    @ApiOperation("消息通知接收")
    @RequestMapping(value = "messageNotification",method = {RequestMethod.POST,RequestMethod.GET})
    public String messageNotification(
            HttpServletRequest request) {
        try {
            String str = getRequestBodyData(request);
            if(!StringUtil.isBlank(str)){
                JSONObject json = JSON.parseObject(str);
                JSONObject fps = json.getJSONObject("fps");
                JSONArray msgList = fps.getJSONArray("msgList");
                for(int i=0;i<msgList.size();i++){
                    JSONObject jsonObject = msgList.getJSONObject(i);
                    hvDeviceService.messageNotification(jsonObject);
                }
            }
            logger.info("======================:"+str);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"Device data incoming failure");
        }
    }
    @ApiOperation("同步设备")
    @RequestMapping(value = "synDevice",method = {RequestMethod.POST})
    public String synDevice() {
        try {
            hvDeviceService.synDevice();
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"Device data incoming failure");
        }
    }
    /**
     * 获取request中body数据
     */
    public static String getRequestBodyData(HttpServletRequest request) throws IOException {
        BufferedReader bufferReader = new BufferedReader(request.getReader());
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = bufferReader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String error(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put("success", false);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 接口处理成功
     * @return
     */
    public String success() {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", 200);
            map.put("success", true);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public String write(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put("success", true);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

+ 84 - 84
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/SocketClientTest.java

@ -1,84 +1,84 @@
package com.yihu.jw.care.endpoint;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
/***
 * @ClassName: SocketTest
 * @Description: scoket客户端
 * @Auther: shi kejing
 * @Date: 2021/8/20 11:00
 */
public class SocketClientTest {
    public static void main(String[] args) {
        SocketClientTest client=new SocketClientTest();
        client.startAction();
    }
    void readSocketInfo(BufferedReader reader){
        new Thread(new MyRuns(reader)).start();
    }
    class MyRuns implements Runnable{
        BufferedReader reader;
        public MyRuns(BufferedReader reader) {
            super();
            this.reader = reader;
        }
        public void run() {
            try {
                String lineString="";
                while( (lineString = reader.readLine())!=null ){
                    System.out.println(lineString);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public void startAction(){
        Socket socket=null;
        BufferedReader reader=null;
        BufferedWriter writer=null;
        BufferedReader reader2=null;
        try {
            socket=new Socket("172.26.0.107", 9112);
            reader = new BufferedReader(new InputStreamReader(System.in));
            reader2=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            readSocketInfo(reader2);
            String lineString="";
            while(!(lineString=reader.readLine()).equals("exit")){
                writer.write(lineString+"\n");
                writer.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader!=null) {
                    reader.close();
                }
                if (writer!=null) {
                    writer.close();
                }
                if (socket!=null) {
                    socket.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
}
//package com.yihu.jw.care.endpoint;
//
//import java.io.BufferedReader;
//import java.io.BufferedWriter;
//import java.io.InputStreamReader;
//import java.io.OutputStreamWriter;
//import java.net.Socket;
//
///***
// * @ClassName: SocketTest
// * @Description: scoket客户端
// * @Auther: shi kejing
// * @Date: 2021/8/20 11:00
// */
//public class SocketClientTest {
//
//    public static void main(String[] args) {
//        SocketClientTest client=new SocketClientTest();
//        client.startAction();
//    }
//
//    void readSocketInfo(BufferedReader reader){
//        new Thread(new MyRuns(reader)).start();
//    }
//
//    class MyRuns implements Runnable{
//
//        BufferedReader reader;
//
//        public MyRuns(BufferedReader reader) {
//            super();
//            this.reader = reader;
//        }
//
//        public void run() {
//            try {
//                String lineString="";
//                while( (lineString = reader.readLine())!=null ){
//                    System.out.println(lineString);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//
//    }
//
//    public void startAction(){
//        Socket socket=null;
//        BufferedReader reader=null;
//        BufferedWriter writer=null;
//        BufferedReader reader2=null;
//        try {
//            socket=new Socket("172.26.0.107", 9112);
//            reader = new BufferedReader(new InputStreamReader(System.in));
//            reader2=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//            readSocketInfo(reader2);
//            String lineString="";
//            while(!(lineString=reader.readLine()).equals("exit")){
//                writer.write(lineString+"\n");
//                writer.flush();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (reader!=null) {
//                    reader.close();
//                }
//                if (writer!=null) {
//                    writer.close();
//                }
//                if (socket!=null) {
//                    socket.close();
//                }
//            } catch (Exception e2) {
//                e2.printStackTrace();
//            }
//        }
//    }
//
//
//}

+ 103 - 103
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/SocketServerTest.java

@ -1,103 +1,103 @@
package com.yihu.jw.care.endpoint;
import com.tencentcloudapi.oceanus.v20190422.models.SystemResourceItem;
import com.yihu.jw.entity.util.SystemConfEntity;
import jdk.internal.cmm.SystemResourcePressureImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.Property;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
/***
 * @ClassName: SocketServerTest
 * @Description: socket服务器端
 * @Auther: shi kejing
 * @Date: 2021/8/20 11:04
 */
@Component
public class SocketServerTest {
    private final static Logger logger = LoggerFactory.getLogger(SocketServerTest.class);
    public static void main(String[] args) {
        SocketServerTest st = new SocketServerTest();
        st.startAction();
    }
//    @PostConstruct
    public void startAction(){
        logger.info("服务端服务启动监听:");
        ServerSocket serverSocket=null;
        try {
            serverSocket=new ServerSocket(9112);  //端口号
            logger.info("服务端服务启动监听:");
            //通过死循环开启长连接,开启线程去处理消息
            while(true){
                Socket socket=serverSocket.accept();
                new Thread(new SocketServerTest.MyRuns(socket)).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (serverSocket!=null) {
                    serverSocket.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
    class MyRuns implements Runnable{
        Socket socket;
        BufferedReader reader;
        BufferedWriter writer;
        public MyRuns(Socket socket) {
            super();
            this.socket = socket;
        }
        public void run() {
            try {
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));//读取客户端消息
                writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));//向客户端写消息
                String lineString=""; //服务器接受到的消息
                while(!(lineString=reader.readLine()).equals("bye")){
                    logger.info("收到来自客户端的发送的消息是:" + lineString);
                    writer.write("服务器返回:"+lineString+"\n");
                    writer.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (reader!=null) {
                        reader.close();
                    }
                    if (writer!=null) {
                        writer.close();
                    }
                    if (socket!=null) {
                        socket.close();
                    }
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
    }
}
//package com.yihu.jw.care.endpoint;
//
//import com.tencentcloudapi.oceanus.v20190422.models.SystemResourceItem;
//import com.yihu.jw.entity.util.SystemConfEntity;
//import jdk.internal.cmm.SystemResourcePressureImpl;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.core.convert.Property;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import java.io.BufferedReader;
//import java.io.BufferedWriter;
//import java.io.InputStreamReader;
//import java.io.OutputStreamWriter;
//import java.net.ServerSocket;
//import java.net.Socket;
//
///***
// * @ClassName: SocketServerTest
// * @Description: socket服务器端
// * @Auther: shi kejing
// * @Date: 2021/8/20 11:04
// */
//@Component
//public class SocketServerTest {
//    private final static Logger logger = LoggerFactory.getLogger(SocketServerTest.class);
//
//    public static void main(String[] args) {
//        SocketServerTest st = new SocketServerTest();
//        st.startAction();
//    }
//
////    @PostConstruct
//    public void startAction(){
//        logger.info("服务端服务启动监听:");
//        ServerSocket serverSocket=null;
//        try {
//            serverSocket=new ServerSocket(9112);  //端口号
//            logger.info("服务端服务启动监听:");
//            //通过死循环开启长连接,开启线程去处理消息
//            while(true){
//                Socket socket=serverSocket.accept();
//                new Thread(new SocketServerTest.MyRuns(socket)).start();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (serverSocket!=null) {
//                    serverSocket.close();
//                }
//            } catch (Exception e2) {
//                e2.printStackTrace();
//            }
//        }
//    }
//
//    class MyRuns implements Runnable{
//
//        Socket socket;
//        BufferedReader reader;
//        BufferedWriter writer;
//
//        public MyRuns(Socket socket) {
//            super();
//            this.socket = socket;
//        }
//
//        public void run() {
//            try {
//                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));//读取客户端消息
//                writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));//向客户端写消息
//                String lineString=""; //服务器接受到的消息
//
//                while(!(lineString=reader.readLine()).equals("bye")){
//                    logger.info("收到来自客户端的发送的消息是:" + lineString);
//                    writer.write("服务器返回:"+lineString+"\n");
//                    writer.flush();
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            } finally {
//                try {
//                    if (reader!=null) {
//                        reader.close();
//                    }
//                    if (writer!=null) {
//                        writer.close();
//                    }
//                    if (socket!=null) {
//                        socket.close();
//                    }
//                } catch (Exception e2) {
//                    e2.printStackTrace();
//                }
//            }
//        }
//
//    }
//
//
//}

+ 151 - 151
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/WebSocketServer.java

@ -1,151 +1,151 @@
package com.yihu.jw.care.endpoint;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import com.alibaba.fastjson.JSON;
/***
 * @ClassName: WebSocketServer
 * @Description:
 * @Auther: shi kejing
 * @Date: 2021/8/20 14:20
 */
@ServerEndpoint("/")
@Component
public class WebSocketServer {
    private final static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId="ijk";
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) {
        userId="ijk";
        log.info("userId = "+userId);
        this.session = session;
        this.userId=userId;
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
            //加入set中
        }else{
            webSocketMap.put(userId,this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }
        log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("用户:"+userId+",网络异常!!!!!!");
        }
    }
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
    }
    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:"+userId+",报文:"+message);
        //可以群发消息
        //消息保存到数据库、redis
        if(StringUtils.isNotBlank(message)){
            try {
                //解析发送的报文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加发送人(防止串改)
                jsonObject.put("fromUserId",this.userId);
                String toUserId=jsonObject.getString("toUserId");
                //传送给对应toUserId用户的websocket
                if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){
                    webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
                }else{
                    log.error("请求的userId:"+toUserId+"不在该服务器上");
                    //否则不在这个服务器上,发送到mysql或者redis
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
    /**
     * 发送自定义消息
     * */
    public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {
        log.info("发送消息到:"+userId+",报文:"+message);
        if(StringUtils.isNotBlank(userId)&&webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendMessage(message);
        }else{
            log.error("用户"+userId+",不在线!");
        }
    }
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
//package com.yihu.jw.care.endpoint;
//
//import com.alibaba.fastjson.JSONObject;
//import org.apache.commons.lang.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.stereotype.Component;
//
//
//import javax.websocket.*;
//import javax.websocket.server.PathParam;
//import javax.websocket.server.ServerEndpoint;
//import java.io.IOException;
//import java.util.concurrent.ConcurrentHashMap;
//import com.alibaba.fastjson.JSON;
//
///***
// * @ClassName: WebSocketServer
// * @Description:
// * @Auther: shi kejing
// * @Date: 2021/8/20 14:20
// */
//@ServerEndpoint("/")
//@Component
//public class WebSocketServer {
//
//
//    private final static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
//    /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
//    private static int onlineCount = 0;
//    /**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
//    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
//    /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
//    private Session session;
//    /**接收userId*/
//    private String userId="ijk";
//
//    /**
//     * 连接建立成功调用的方法*/
//    @OnOpen
//    public void onOpen(Session session,@PathParam("userId") String userId) {
//        userId="ijk";
//        log.info("userId = "+userId);
//        this.session = session;
//        this.userId=userId;
//        if(webSocketMap.containsKey(userId)){
//            webSocketMap.remove(userId);
//            webSocketMap.put(userId,this);
//            //加入set中
//        }else{
//            webSocketMap.put(userId,this);
//            //加入set中
//            addOnlineCount();
//            //在线数加1
//        }
//
//        log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());
//
//        try {
//            sendMessage("连接成功");
//        } catch (IOException e) {
//            log.error("用户:"+userId+",网络异常!!!!!!");
//        }
//    }
//
//    /**
//     * 连接关闭调用的方法
//     */
//    @OnClose
//    public void onClose() {
//        if(webSocketMap.containsKey(userId)){
//            webSocketMap.remove(userId);
//            //从set中删除
//            subOnlineCount();
//        }
//        log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
//    }
//
//    /**
//     * 收到客户端消息后调用的方法
//     *
//     * @param message 客户端发送过来的消息*/
//    @OnMessage
//    public void onMessage(String message, Session session) {
//        log.info("用户消息:"+userId+",报文:"+message);
//        //可以群发消息
//        //消息保存到数据库、redis
//        if(StringUtils.isNotBlank(message)){
//            try {
//                //解析发送的报文
//                JSONObject jsonObject = JSON.parseObject(message);
//                //追加发送人(防止串改)
//                jsonObject.put("fromUserId",this.userId);
//                String toUserId=jsonObject.getString("toUserId");
//                //传送给对应toUserId用户的websocket
//                if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){
//                    webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
//                }else{
//                    log.error("请求的userId:"+toUserId+"不在该服务器上");
//                    //否则不在这个服务器上,发送到mysql或者redis
//                }
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//        }
//    }
//
//    /**
//     *
//     * @param session
//     * @param error
//     */
//    @OnError
//    public void onError(Session session, Throwable error) {
//        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
//        error.printStackTrace();
//    }
//    /**
//     * 实现服务器主动推送
//     */
//    public void sendMessage(String message) throws IOException {
//        this.session.getBasicRemote().sendText(message);
//    }
//
//
//    /**
//     * 发送自定义消息
//     * */
//    public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {
//        log.info("发送消息到:"+userId+",报文:"+message);
//        if(StringUtils.isNotBlank(userId)&&webSocketMap.containsKey(userId)){
//            webSocketMap.get(userId).sendMessage(message);
//        }else{
//            log.error("用户"+userId+",不在线!");
//        }
//    }
//
//    public static synchronized int getOnlineCount() {
//        return onlineCount;
//    }
//
//    public static synchronized void addOnlineCount() {
//        WebSocketServer.onlineCount++;
//    }
//
//    public static synchronized void subOnlineCount() {
//        WebSocketServer.onlineCount--;
//    }
//
//
//}

+ 199 - 80
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/service/DeviceService.java

@ -78,6 +78,10 @@ public class DeviceService {
    private BaseSleepNightRecordDao nightRecord;
    @Autowired
    private BasePatientOutBedDao outBedDao;
    @Autowired
    private BaseSleepPlanDetailDao sleepPlanDetailDao;
    @Autowired
    private BaseSleepPlanDao sleepPlanDao;
    /**
     * 获取爱牵挂管理员cookie
@ -361,13 +365,9 @@ public class DeviceService {
                    patientHealthIndex.setRecordDate(recordDate);
                    patientHealthIndex.setSortDate(recordDate);
                    patientHealthIndex.setCzrq(new Date());
                    if (heartrate >= theshold_heartrate_h || heartrate <= theshold_heartrate_l) {
                        patientHealthIndex.setStatus(1);
                    } else {
                        patientHealthIndex.setStatus(0);
                    }
                    patientHealthIndex.setStatus(0);
                    patientHealthIndex.setDel("1");
                    healthIndexDao.save(patientHealthIndex);
                    SystemMessageDO messageDO = new SystemMessageDO();
                    String typeName = "您有新的心率测量记录。心率:" + patientHealthIndex.getValue1() + "次/min";
@ -397,6 +397,9 @@ public class DeviceService {
                    String content_notice = null;
                    for (int i=0;i<errorIndex.size();i++){
                        com.alibaba.fastjson.JSONObject tmp = errorIndex.getJSONObject(i);
                        if (0!=tmp.getInteger("error")){
                            patientHealthIndex.setStatus(1);
                        }
                        if (1 == tmp.getInteger("error")){
                            content_notice += tmp.getString("indexName")+"、";
                        }
@ -406,6 +409,7 @@ public class DeviceService {
                        message.put("content_notice","您的key1过高,请注意饮食,尽量食用少油少盐食物".replace("key1",content_notice));
                        messageDO.setContent("您的key1过高,请注意饮食,尽量食用少油少盐食物".replace("key1",content_notice));
                    }
                    healthIndexDao.save(patientHealthIndex);
                    systemMessageDao.save(messageDO);
                    imUtil.sendPatientSystemMessage(messageDO.getReceiver(),JSON.toJSONString(message,SerializerFeature.WriteMapNullValue));
@ -445,14 +449,8 @@ public class DeviceService {
                    patientHealthIndex.setRecordDate(recordDate);
                    patientHealthIndex.setSortDate(recordDate);
                    patientHealthIndex.setCzrq(new Date());
                    if (sbp>=sbp_h||dbp<=dbp_l){
                        patientHealthIndex.setStatus(1);
                    }
                    else {
                        patientHealthIndex.setStatus(0);
                    }
                    patientHealthIndex.setStatus(0);
                    patientHealthIndex.setDel("1");
                    healthIndexDao.save(patientHealthIndex);
                    SystemMessageDO messageDO = new SystemMessageDO();
                    String typeName = "您有新的血压测量记录:收缩压:"+patientHealthIndex.getValue1()+"mmHg,收缩压:"
@ -481,6 +479,9 @@ public class DeviceService {
                    String content_notice = "";
                    for (int i=0;i<errorIndex.size();i++){
                        com.alibaba.fastjson.JSONObject tmp = errorIndex.getJSONObject(i);
                        if (0!=tmp.getInteger("error")){
                            patientHealthIndex.setStatus(1);
                        }
                        if (1 == tmp.getInteger("error")){
                            content_notice += tmp.getString("indexName")+"、";
                        }
@ -490,6 +491,8 @@ public class DeviceService {
                        message.put("content_notice","您的key1过高,请注意饮食,尽量食用少油少盐食物".replace("key1",content_notice));
                        messageDO.setContent("您的key1过高,请注意饮食,尽量食用少油少盐食物".replace("key1",content_notice));
                    }
                    healthIndexDao.save(patientHealthIndex);
                    systemMessageDao.save(messageDO);
                    imUtil.sendPatientSystemMessage(messageDO.getReceiver(),JSON.toJSONString(message,SerializerFeature.WriteMapNullValue));
                }
@ -553,86 +556,201 @@ public class DeviceService {
    public String bySleep(String device,String time_begin,String heartrate,String breath,String bed_status,String turn_over,String is_warn) {
        try {
            if(StringUtils.isNotBlank(device)){
                boolean orderCreate=false;
                Integer upLongWarn=3; //起床预警时长
                Integer siestaLongWarn=5;//午睡预警时长
                Integer nightLongWarn=2;//起夜预警时长
                List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByDeviceSn(device);
                if (devicePatientDeviceDos.size()>0){
                    String patient = devicePatientDeviceDos.get(0).getUser();
                    //更新患者在床状态
                    updatePatientSleepStatus(device,patient,time_begin,bed_status);
                    //12点以后
                    Date bedIn = DateUtil.getDateStart();//入睡时间
                    Calendar today = Calendar.getInstance();
                    today.set(Calendar.HOUR_OF_DAY, 5);
                    today.set(Calendar.MINUTE, 59);
                    today.set(Calendar.SECOND, 59);
                    today.set(Calendar.MILLISECOND, 999);
                    Date bedUp = today.getTime();//起床时间
                    Date timeDate = DateUtil.strToDate(time_begin);
                    Long timeDiffer = timeDate.getTime() - bedIn.getTime();
                    if (timeDiffer>0&&timeDate.before(bedUp)){ //起夜记录
                        BaseSleepNightRecord record = new BaseSleepNightRecord();
                        if ("0".equals(bed_status)){//离床
                            List<BaseSleepNightRecord> records = nightRecord.findBySnStaPaTime(device,patient,0,bedIn);
                            if (records.size()==0){
                                record.setPatient(devicePatientDeviceDos.get(0).getUser());
                                record.setDeviceSn(device);
                                record.setStatus(0);
                                record.setCreateTime(timeDate);
                                nightRecord.save(record);
                            }else {//是否触发工单
                                record = records.get(0);
                                timeDiffer = timeDate.getTime()-record.getCreateTime().getTime();
                                if (timeDiffer>1800*1000){//超过半小时 触发工单
                                    outBedOrder(records.get(0),devicePatientDeviceDos.get(0),patient,device,"起夜超时未回床");
                                    return null;
                    List<BaseSleepPlan> sleepPlans = sleepPlanDao.findByPatientAndDeviceSn(patient,device);
                    BaseSleepPlanDetail planDetail = new BaseSleepPlanDetail();
                    BaseSleepPlan sleepPlan= null;
                    if (sleepPlans.size()>0){
                        sleepPlan = sleepPlans.get(0);
                    }
                    if (null!=sleepPlan){
                        Date timeDate = DateUtil.strToDate(time_begin);//当前时间
                        Date bedUp = DateUtil.strToDate(DateUtil.getStringDateShort()+" "+sleepPlan.getGetUpTime()+":00");// 起床时间 起床前一小时内算为起床
                        if (timeDate.before(bedUp)){
                            bedUp = DateUtil.getNextDay1(bedUp,-1);
                        }
                        Date bedUpBegin = DateUtil.getNextMin(bedUp,-60);//起床时间 起床前一小时内算为起床
                        Date bedUpEnd = DateUtil.getNextMin(bedUp,60*3);//起床时间 起床后一小时内算为起床
                        boolean needSiesta=false;// 是否有午睡习惯
                        Date SiestaTime = null;// 午睡时间
                        Date SiestaBegin = null;// 午睡开始时间
                        if (StringUtils.isNotBlank(sleepPlan.getNapTime())){
                            needSiesta=true;
                            SiestaTime = DateUtil.strToDate(DateUtil.getStringDateShort()+" "+sleepPlan.getNapTime()+":00");
                            SiestaBegin = DateUtil.getNextMin(SiestaTime,-60);// 午睡开始时间
                        }
                        String inTime = sleepPlan.getNightRestTime();
                        Date bedIn = null;// 入睡时间
                        Date bedBegin = null;// 入睡开始时间
                        String dayTime = DateUtil.dateToStr(bedUp,DateUtil.YYYY_MM_DD);//监测日期
                        if (inTime.charAt(0)=='0') {
                            bedIn = DateUtil.strToDate(dayTime+" "+sleepPlan.getNightRestTime()+":00");
                            bedIn = DateUtil.getNextDay1(bedIn,1);
                        }else {
                            bedIn = DateUtil.strToDate(dayTime+" "+sleepPlan.getNightRestTime()+":00");
                        }
                        bedBegin = DateUtil.getNextMin(bedIn,-60*2);
                        List<BaseSleepPlanDetail> planDetails = sleepPlanDetailDao.findByDay(dayTime);
                        if (planDetails.size()>0){
                            planDetail = planDetails.get(0);
                        }
                        planDetail.setDay(dayTime);
                        planDetail.setPatient(patient);
                        planDetail.setDeviceSn(device);
                        /***起床***/
                        Long timeDiffer = timeDate.getTime() - bedUp.getTime();
                        if(DateUtil.isInArea(timeDate,bedUpBegin,bedUpEnd)){//起床时间内
                            if ("0".equals(bed_status)){//起床
                                if (null==planDetail.getUpStatus()){
                                    planDetail.setUpStatus(1);
                                    planDetail.setUpTime(timeDate);
                                }
                            }
                        }
                        if ("1".equals(bed_status)){//在床记录起夜时长
                            timeDiffer = bedUp.getTime()-timeDate.getTime();
                            if (timeDiffer>0){//6点之前入睡时间
                             List<BaseSleepNightRecord> records = nightRecord.findBySnStaPaTime(device,patient,0,bedIn);
                                if (records.size()>0){//
                                    record = records.get(0);
                                    record.setStatus(1);
                                    record.setUpdateTime(timeDate);
                                    Date outDate = record.getCreateTime();
                                    timeDiffer = (timeDate.getTime() - outDate.getTime())/1000;
                                    record.setOutTime(timeDiffer+"");
                                    nightRecord.save(record);
                        else if (3600*upLongWarn*1000<timeDiffer&&timeDiffer<(3600*upLongWarn+600)*1000){//距离起床超过三个小时还在床
                            if ("1".equals(bed_status)){//还在床
                                if (1==planDetail.getUpStatus()){}//起床后再次入睡超时未起床不触发
                                else {
                                    if (null==planDetail.getUpStatus()){
                                        planDetail.setUpStatus(0);
                                        planDetail.setBedStatus(0);
                                        planDetail.setBreath(breath);
                                        planDetail.setHeartRate(heartrate);
                                        outBedOrder(null,devicePatientDeviceDos.get(0),patient,device,"超时未起床",JSON.toJSONStringWithDateFormat(planDetail,"yyyy-MM-dd HH:mm:ss",SerializerFeature.WriteMapNullValue));
                                        orderCreate=true;
                                    }
                                }
                            }
                        }
                    }
                    else {
                        if ("1".equals(bed_status)){
                            timeDiffer = timeDate.getTime() - bedUp.getTime();
                            if (1800*1000<timeDiffer&&timeDiffer<3600*1000){//超过半小时未起床
                                outBedOrder(null,devicePatientDeviceDos.get(0),patient,device,"超时未起床");
                                return null;
                        /***午睡***/
                        if(needSiesta&&DateUtil.isInArea(timeDate,SiestaBegin,bedIn)){//午睡时段
                            if ("0".equals(bed_status)){
                                if (null==planDetail.getSiestaStatus()){//超时未午睡午睡
                                    timeDiffer = timeDate.getTime() - SiestaTime.getTime();
                                    if (timeDiffer>3600*siestaLongWarn*1000){
                                        planDetail.setSiestaStatus(0);
                                        planDetail.setBedStatus(0);
                                        outBedOrder(null,devicePatientDeviceDos.get(0),patient,device,"超时未午睡",JSON.toJSONStringWithDateFormat(planDetail,"yyyy-MM-dd HH:mm:ss",SerializerFeature.WriteMapNullValue));
                                        orderCreate=true;
                                    }
                                }
                                else if(1 == planDetail.getSiestaStatus()&&null==planDetail.getSiestaTimeEnd()){//午睡起床
                                    planDetail.setSiestaTimeEnd(timeDate);
                                    timeDiffer = (planDetail.getSiestaTimeEnd().getTime()-planDetail.getSiestaTimeBegin().getTime())/1000;
                                    planDetail.setSiestaLong(timeDiffer+"");
                                }
                            }
                            if ("1".equals(bed_status)){
                                if (null==planDetail.getSiestaStatus()){
                                    planDetail.setSiestaStatus(1);
                                    planDetail.setSiestaTimeBegin(timeDate);
                                }
                                else if(1==planDetail.getSiestaStatus()&&null==planDetail.getSiestaTimeEnd()){
                                    timeDiffer = timeDate.getTime() - planDetail.getSiestaTimeBegin().getTime();
                                    if(3600*siestaLongWarn*1000<timeDiffer&&timeDiffer<(3600*siestaLongWarn+600)*1000){//午睡超时未起床
                                        planDetail.setBedStatus(0);
                                        planDetail.setBreath(breath);
                                        planDetail.setHeartRate(heartrate);
                                        outBedOrder(null,devicePatientDeviceDos.get(0),patient,device,"午睡超时未起床",JSON.toJSONStringWithDateFormat(planDetail,"yyyy-MM-dd HH:mm:ss",SerializerFeature.WriteMapNullValue));
                                        orderCreate=true;
                                    }
                                }
                            }
                        }
                    }
                    if ("1".equals(bed_status)){//呼吸 心率检测
                        Integer theshold_breath_h = 25;
                        Integer theshold_breath_l = 8;
                        Integer theshold_heartrate_h = 100;
                        Integer theshold_heartrate_l = 50;
                        if (StringUtils.isNotBlank(breath)){
                          Integer breath1 = Integer.parseInt(breath);
                          if (breath1>theshold_breath_h||breath1<theshold_breath_l){
                              outBedOrder(null,devicePatientDeviceDos.get(0),patient,device,"心率和呼吸频率异常");
                              return null;
                          }
                        }
                        if (StringUtils.isNotBlank(heartrate)){
                            Integer heartrate1 = Integer.parseInt(heartrate);
                            if (heartrate1>theshold_heartrate_h||theshold_heartrate_h<theshold_heartrate_l){
                                outBedOrder(null,devicePatientDeviceDos.get(0),patient,device,"心率和呼吸频率异常");
                                return null;
                        /**晚休***/
                        timeDiffer = timeDate.getTime() - bedBegin.getTime();
                        if (timeDiffer>0&&timeDate.after(bedBegin)){ //起夜记录
                            BaseSleepNightRecord record = new BaseSleepNightRecord();
                            if ("1".equals(bed_status)){
                                if (null==planDetail.getInStatus()){
                                    planDetail.setInStatus(1);
                                    planDetail.setInTimeBegin(timeDate);
                                }
                                else if (1==planDetail.getInStatus()){//在床记录起夜时长
                                    List<BaseSleepNightRecord> records = nightRecord.findBySnStaPaTime(device,patient,0,bedIn);
                                    if (records.size()>0){//
                                        record = records.get(0);
                                        record.setStatus(1);
                                        record.setUpdateTime(timeDate);
                                        Date outDate = record.getCreateTime();
                                        timeDiffer = (timeDate.getTime() - outDate.getTime())/1000;
                                        record.setOutTime(timeDiffer+"");
                                        nightRecord.save(record);
                                    }
                                }
                            }
                            if ("0".equals(bed_status)){//离床
                                List<BaseSleepNightRecord> records = nightRecord.findBySnStaPaTime(device,patient,0,bedIn);
                                if(null==planDetail.getInStatus()){
                                    timeDiffer = timeDate.getTime() - bedIn.getTime();
                                    if (timeDiffer>3600*nightLongWarn*1000){
                                        planDetail.setInStatus(0);
                                        planDetail.setBedStatus(1);
                                        planDetail.setSleepNightRecordList(records);
                                        outBedOrder(null,devicePatientDeviceDos.get(0),patient,device,"超时未上床晚休",JSON.toJSONStringWithDateFormat(planDetail,"yyyy-MM-dd HH:mm:ss",SerializerFeature.WriteMapNullValue));
                                        orderCreate=true;
                                    }
                                }
                                else if (1==planDetail.getInStatus()){
                                    if (records.size()==0){
                                        record.setPatient(devicePatientDeviceDos.get(0).getUser());
                                        record.setDeviceSn(device);
                                        record.setStatus(0);
                                        record.setDay(DateUtil.dateToStr(bedUp,DateUtil.YYYY_MM_DD));
                                        record.setCreateTime(timeDate);
                                        nightRecord.save(record);
                                    }else {//是否触发工单
                                        record = records.get(0);
                                        timeDiffer = timeDate.getTime()-record.getCreateTime().getTime();
                                        if (timeDiffer>3600*nightLongWarn*1000){//超过2未回床小时 触发工单
                                            planDetail.setSleepNightRecordList(records);
                                            planDetail.setBedStatus(0);
                                            outBedOrder(records.get(0),devicePatientDeviceDos.get(0),patient,device,"起夜超时未回床",JSON.toJSONStringWithDateFormat(planDetail,"yyyy-MM-dd HH:mm:ss",SerializerFeature.WriteMapNullValue));
                                            orderCreate=true;
                                        }
                                    }
                                }
                            }
                        }
                        sleepPlanDetailDao.save(planDetail);
                    }
                    //更新患者在床状态
                    updatePatientSleepStatus(device,patient,time_begin,bed_status);
                    if (!orderCreate){
                        if ("1".equals(bed_status)){//呼吸 心率检测
                            Integer theshold_breath_h = 25;
                            Integer theshold_breath_l = 8;
                            Integer theshold_heartrate_h = 100;
                            Integer theshold_heartrate_l = 50;
                            if (StringUtils.isNotBlank(breath)){
                                Integer breath1 = Integer.parseInt(breath);
                                if (breath1>theshold_breath_h||breath1<theshold_breath_l){
                                    planDetail.setBreath(breath);
                                    planDetail.setHeartRate(heartrate);
                                    planDetail.setBedStatus(1);
                                    outBedOrder(null,devicePatientDeviceDos.get(0),patient,device,"心率和呼吸频率异常",JSON.toJSONStringWithDateFormat(planDetail,"yyyy-MM-dd HH:mm:ss",SerializerFeature.WriteMapNullValue));
                                    return null;
                                }
                            }
                            if (StringUtils.isNotBlank(heartrate)){
                                Integer heartrate1 = Integer.parseInt(heartrate);
                                if (heartrate1>theshold_heartrate_h||theshold_heartrate_h<theshold_heartrate_l){
                                    planDetail.setBreath(breath);
                                    planDetail.setHeartRate(heartrate);
                                    planDetail.setBedStatus(1);
                                    outBedOrder(null,devicePatientDeviceDos.get(0),patient,device,"心率和呼吸频率异常",JSON.toJSONStringWithDateFormat(planDetail,"yyyy-MM-dd HH:mm:ss",SerializerFeature.WriteMapNullValue));
                                    return null;
                                }
                            }
                        }
                    }
                }
@ -643,7 +761,7 @@ public class DeviceService {
        return null;
    }
    public void outBedOrder(BaseSleepNightRecord record,DevicePatientDevice patientDevice,String patient ,String device,String serverName)throws Exception{
    public void outBedOrder(BaseSleepNightRecord record,DevicePatientDevice patientDevice,String patient ,String device,String serverName,String warnInfo)throws Exception{
        // //夜间十二点 起床半小时后未回床 触发安防工单
            BasePatientDO patientDO = patientDao.findById(patient);
            if(null!=patientDO){
@ -677,6 +795,7 @@ public class DeviceService {
                    jsonObject.put("serveLon",lng);
                    jsonObject.put("topicItem","preventOutOfBed");
                    jsonObject.put("deviceSn",device);
                    jsonObject.put("warnInfo",warnInfo);
                    JSONObject jsonObjectParam = new JSONObject();
                    jsonObjectParam.put("order", jsonObject);
                    map.put("jsonData", jsonObjectParam.toJSONString());

+ 17 - 2
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/service/DeviceUploadService.java

@ -160,6 +160,9 @@ public class DeviceUploadService {
                    String content_notice = "";
                    for (int i=0;i<errorIndex.size();i++){
                        com.alibaba.fastjson.JSONObject tmp = errorIndex.getJSONObject(i);
                        if (0!=tmp.getInteger("error")){
                            result.setStatus(1);
                        }
                        if (1 == tmp.getInteger("error")){
                            content_notice += tmp.getString("indexName")+"、";
                        }
@ -169,6 +172,7 @@ public class DeviceUploadService {
                        message.put("content_notice","您的key1过高,请注意饮食,尽量食用少油少盐食物".replace("key1",content_notice));
                        messageDO.setContent("您的key1过高,请注意饮食,尽量食用少油少盐食物".replace("key1",content_notice));
                    }
                    patientHealthIndexDao.save(result);
                    systemMessageDao.save(messageDO);
                    imUtil.sendPatientSystemMessage(messageDO.getReceiver(),JSON.toJSONString(message,SerializerFeature.WriteMapNullValue));
                }
@ -206,7 +210,7 @@ public class DeviceUploadService {
        List<DeviceDetail> deviceDetails = deviceDetailDao.findByDeviceCode(deviceSn);
        if (deviceDetails != null || deviceDetails.size()!=0){
            deviceDetail = deviceDetails.get(0);
            if (deviceDetail.getGrantOrgCode() != null&& deviceDetail.getGrantOrgCode().equals("3502050300")){
            if (deviceDetail.getGrantOrgCode() != null&& deviceDetail.getGrantOrgCode().equals("3502050300")){//
                List<DevicePatientDevice> patientDeviceList =  patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
                if (patientDeviceList != null&&patientDeviceList.size()==1) {
                    device = patientDeviceList.get(0);
@ -329,7 +333,6 @@ public class DeviceUploadService {
                obj.setHospitalName(deviceDetail.getOrgName());
            }
//            obj = patientHealthIndexDao.save(obj);
            obj = patientHealthIndexDao.save(obj);
            return obj;
        }
@ -415,5 +418,17 @@ public class DeviceUploadService {
            return false;
        }
    }
    //[XT*334588000000156*00CD*UD,180916,025723,A,22.570733,N,113.8626083,E,0.00,249.5,0.0,6,100,
    //60,0,0,00000010,7,255,460,1,9529,21809,158,9529,63555,133,9529,63554,129,9529,21405,126,95
    //29,21242,124,9529,21151,120,9529,63556,119,0]
    public Result caneUpload(String message)throws Exception {
        if (StringUtils.isBlank(message)){
            return Result.error("message is null");
        }else {
            String[] messages = message.split(",");
        }
        return Result.success("success");
    }
}

+ 180 - 0
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/service/HvDeviceService.java

@ -0,0 +1,180 @@
package com.yihu.jw.care.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yihu.jw.care.dao.device.DeviceHealthIndexDao;
import com.yihu.jw.care.dao.device.HvDeviceRecordDao;
import com.yihu.jw.care.dao.device.HvDeviceSosLogDao;
import com.yihu.jw.care.util.ArtemisPostTest;
import com.yihu.jw.entity.care.device.DeviceHealthIndex;
import com.yihu.jw.entity.care.device.HvDeviceRecord;
import com.yihu.jw.entity.care.device.HvDeviceSosLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yeshijie
 * @Date: 2021/8/23
 * @Description:
 */
@Service
public class HvDeviceService {
    private static Logger logger = LoggerFactory.getLogger(HvDeviceService.class);
    @Autowired
    private DeviceHealthIndexDao deviceHealthIndexDao;
    @Autowired
    private YsDeviceService ysDeviceService;
    @Autowired
    private HvDeviceSosLogDao hvdeviceSosLogDao;
    @Autowired
    private HvDeviceRecordDao hvdeviceRecordDao;
    /**
     * 消息通知接收
     * @param json
     */
    public void messageNotification(JSONObject json){
        String msgType = json.getString("msgType");
        JSONObject body = json.getJSONObject("body");
        if("980008".equals(msgType)){
            message980008(body);
            return;
        }
        if ("980002".equals(msgType)){
            message980002(body);
            return;
        }
    }
    /**
     * 报警实时信息
     * @param json
     */
    public void message980002(JSONObject json){
        JSONArray data = json.getJSONArray("data");
        List<HvDeviceSosLog> list = new ArrayList<>();
        for (int i=0;i<data.size();i++){
            JSONObject jsonObject = data.getJSONObject(i);
            String resourceSerial = jsonObject.getString("resourceSerial");
            String deviceType = jsonObject.getString("deviceType");
            Integer alarmNum = jsonObject.getInteger("alarmNum");
            String resourceID = jsonObject.getString("resourceID");
            String location = jsonObject.getString("location");
            String resourceType = jsonObject.getString("resourceType");
            String alarmID = jsonObject.getString("alarmID");
            String systemType = jsonObject.getString("systemType");
            String alarmType = jsonObject.getString("alarmType");
            String monitorValue = jsonObject.getString("monitorValue");
            String resourceName = jsonObject.getString("resourceName");
            String alarmTime = jsonObject.getString("alarmTime");
            HvDeviceSosLog log = new HvDeviceSosLog();
            log.setAlarmID(alarmID);
            log.setAlarmNum(alarmNum);
            log.setAlarmTime(alarmTime);
            log.setAlarmType(alarmType);
            log.setLocation(location);
            log.setMonitorValue(monitorValue);
            log.setResourceID(resourceID);
            log.setResourceName(resourceName);
            log.setResourceSerial(resourceSerial);
            log.setResourceType(resourceType);
            log.setSystemType(systemType);
            list.add(log);
            if(alarmNum>1){
                continue;
            }
            if("600006".equals(deviceType)){
                //独立式可燃气体探测器(NB)
                JSONObject tmp = new JSONObject();
                tmp.put("gas",monitorValue);
                ysDeviceService.createOrder(resourceSerial,null,new JSONObject(),6,"11","preventGasLeakage",JSON.toJSONString(tmp, SerializerFeature.WriteMapNullValue));
            }
            if("600002".equals(deviceType)){
                //独立式光电感烟探测器(NB)
                JSONObject tmp = new JSONObject();
                tmp.put("smoke",monitorValue);
                ysDeviceService.createOrder(resourceSerial,null,new JSONObject(),7,"10","preventFire",JSON.toJSONString(tmp, SerializerFeature.WriteMapNullValue));
            }
        }
        if(list.size()>0){
            hvdeviceSosLogDao.save(list);
        }
    }
    /**
     * 监测实时信息
     */
    public void message980008(JSONObject json){
        JSONArray data = json.getJSONArray("data");
        List<DeviceHealthIndex> list = new ArrayList<>();
        for (int i=0;i<data.size();i++){
            JSONObject jsonObject = data.getJSONObject(i);
            String resourceSerial = jsonObject.getString("resourceSerial");
            String monitorType = jsonObject.getString("monitorType");
            String resourceType = jsonObject.getString("resourceType");
            String monitorUnit = jsonObject.getString("monitorUnit");
            String monitorValue = jsonObject.getString("monitorValue");
            String happenTime = jsonObject.getString("happenTime");
            DeviceHealthIndex index = new DeviceHealthIndex();
            index.setDeviceSn(resourceSerial);
            index.setUnit(monitorUnit);
            index.setValue(monitorValue);
            index.setRecordTime(happenTime);
            if("600006".equals(resourceType)&&"400003".equals(monitorType)){
                //独立式可燃气体探测器(NB)
                index.setDeviceType("1");
                list.add(index);
            }
            if("600002".equals(resourceType)&&"400013".equals(monitorType)){
                //独立式光电感烟探测器(NB)
                index.setDeviceType("2");
                list.add(index);
            }
        }
        if(list.size()>0){
            deviceHealthIndexDao.save(list);
        }
    }
    /**
     * 同步设备
     */
    public void synDevice(){
        String res = ArtemisPostTest.getDevice();
        JSONObject jsonObject = JSON.parseObject(res);
        if("0".equals(jsonObject.getString("code"))){
            List<HvDeviceRecord> deviceRecordList = new ArrayList<>();
            JSONArray list = jsonObject.getJSONObject("data").getJSONArray("list");
            for (int i=0;i<list.size();i++){
                JSONObject json = list.getJSONObject(i);
                String deviceID = json.getString("deviceID");
                String deviceSerial = json.getString("deviceSerial");
                HvDeviceRecord record = new HvDeviceRecord();
                record.setDeviceSn(deviceSerial);
                record.setDeviceId(deviceID);
                deviceRecordList.add(record);
            }
            if(deviceRecordList.size()>0){
                hvdeviceRecordDao.deleteAll();;
                hvdeviceRecordDao.save(deviceRecordList);
            }
        }
    }
}

+ 69 - 60
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/service/YsDeviceService.java

@ -1,9 +1,7 @@
package com.yihu.jw.care.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.care.config.YsConfig;
@ -17,16 +15,8 @@ import com.yihu.jw.restmodel.iot.common.UploadVO;
import com.yihu.jw.util.common.LatitudeUtils;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.utils.encode.Base64;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.csource.common.MyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -44,7 +34,6 @@ import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.HashMap;
@ -148,66 +137,86 @@ public class YsDeviceService {
                }
            }
            if (fallFlag){//发起安防工单
                String lat = "";
                String lon = "";
                List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByDeviceSn(deviceSN);
                if (devicePatientDeviceDos.size()>0){
                    DevicePatientDevice deviceDO = devicePatientDeviceDos.get(0);
                    Map<String, String> json = null;
                    if (org.apache.commons.lang.StringUtils.isNotBlank(deviceDO.getSosAddress())) {
                        json = LatitudeUtils.getGeocoderLatitude(deviceDO.getSosAddress().replace("G.", "").replace("(糖友网)", "").replace("(高友网)", ""));
                    }
                    if (json != null) {
                        lat = json.get("lat").toString();
                        lon = json.get("lng").toString();
                    }
                result = createOrder(deviceSN,sceneUrl,result,4,"2","preventFall",null);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
        //https://www.yuque.com/u1400669/kb/mlqrm2
        //https://www.yuque.com/u1400669/kb/div5py
    }
                    BasePatientDO patientDO = patientDao.findById(deviceDO.getUser());
                    String  url = cloudCareUrl+"/cloudCare/noLogin/security/createOrder";
                    Map map = new HashMap<String, String>();
                    map = new HashMap();
                    String sql ="select DISTINCT item.org_code,item.org_name\n" +
                            " from base_service_package_sign_record sr,base_service_package_record pr,base_service_package_item item ,base_service_package pack\n" +
                            "where pr.patient = '"+patientDO.getId()+"' and sr.id = pr.sign_id and pr.service_package_id = item.service_package_id \tand  item.`code`='preventFall'  and item.service_package_id = pack.id \n" +
                            "  and pack.del=1";
                    List<Map<String,Object>> sqlResult = jdbcTemplate.queryForList(sql);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("patient",patientDO.getId());
                    jsonObject.put("patientName",patientDO.getName());
                    jsonObject.put("patientPhone",patientDO.getMobile());
                    jsonObject.put("serveDesc","疑似跌倒");
                    jsonObject.put("hospital",sqlResult.get(0).get("org_code"));
                    jsonObject.put("serveAddress",deviceDO.getSosAddress());
                    jsonObject.put("serveLat",lat);
                    jsonObject.put("serveLon",lon);
                    jsonObject.put("topicItem","preventFall");
                    jsonObject.put("deviceSn",deviceSN);
                    if (StringUtils.isNotBlank(sceneUrl)){
                        jsonObject.put("sceneImg",sceneUrl);
                    }
                    JSONObject jsonObjectParam = new JSONObject();
                    jsonObjectParam.put("order", jsonObject);
                    map.put("jsonData", jsonObjectParam.toJSONString());
                    map.put("orderSource", 4);
                    map.put("warnStr", "疑似跌倒");
    public JSONObject createOrder(String deviceSN,String sceneUrl,JSONObject result,Integer orderSource,String dictCode,String topicItem,String warnInfo){
        try {
            String lat = "";
            String lon = "";
            List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByDeviceSn(deviceSN);
            if (devicePatientDeviceDos.size()>0){
                DevicePatientDevice deviceDO = devicePatientDeviceDos.get(0);
                Map<String, String> json = null;
                if (org.apache.commons.lang.StringUtils.isNotBlank(deviceDO.getSosAddress())) {
                    json = LatitudeUtils.getGeocoderLatitude(deviceDO.getSosAddress().replace("G.", "").replace("(糖友网)", "").replace("(高友网)", ""));
                }
                if (json != null) {
                    lat = json.get("lat").toString();
                    lon = json.get("lng").toString();
                }
                BasePatientDO patientDO = patientDao.findById(deviceDO.getUser());
                String  url = cloudCareUrl+"/cloudCare/noLogin/security/createOrder";
                Map map = new HashMap<String, String>();
                map = new HashMap();
                String sql ="select DISTINCT item.org_code,item.org_name\n" +
                        " from base_service_package_sign_record sr,base_service_package_record pr,base_service_package_item item ,base_service_package pack\n" +
                        "where pr.patient = '"+patientDO.getId()+"' and sr.id = pr.sign_id and pr.service_package_id = item.service_package_id \tand  item.`code`='preventFall'  and item.service_package_id = pack.id \n" +
                        "  and pack.del=1";
                List<Map<String,Object>> sqlResult = jdbcTemplate.queryForList(sql);
                String serveDesc = "";
                String sqlDesc = "SELECT dict_value from wlyy_hospital_sys_dict WHERE dict_code = '"+dictCode+"' and dict_name = 'security_server_dict'";
                List<Map<String,Object>> listTmp = jdbcTemplate.queryForList(sqlDesc);
                if (listTmp!=null&&listTmp.size()>0){
                    serveDesc = listTmp.get(0).get("dict_value")+"";
                }
                    String content = com.alibaba.fastjson.JSONObject.toJSONString(map);
                    String postParams = AesEncryptUtils.agEncrypt(content);
                    String response = httpClientUtil.postBodyRawForm(url,postParams);
                    result = com.alibaba.fastjson.JSONObject.parseObject(response);
                    JSONObject jsonObjectData =JSONObject.parseObject(AesEncryptUtils.agDecrypt(result.getString("data")));
                    System.out.println(jsonObjectData.toJSONString());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("patient",patientDO.getId());
                jsonObject.put("patientName",patientDO.getName());
                jsonObject.put("patientPhone",patientDO.getMobile());
                jsonObject.put("serveDesc",serveDesc);
                jsonObject.put("hospital",sqlResult.get(0).get("org_code"));
                jsonObject.put("serveAddress",deviceDO.getSosAddress());
                jsonObject.put("serveLat",lat);
                jsonObject.put("serveLon",lon);
                jsonObject.put("topicItem",topicItem);
                jsonObject.put("deviceSn",deviceSN);
                jsonObject.put("warnInfo",warnInfo);
                if (StringUtils.isNotBlank(sceneUrl)){
                    jsonObject.put("sceneImg",sceneUrl);
                }
                JSONObject jsonObjectParam = new JSONObject();
                jsonObjectParam.put("order", jsonObject);
                map.put("jsonData", jsonObjectParam.toJSONString());
                map.put("orderSource", orderSource);
                map.put("warnStr", serveDesc);
                String content = com.alibaba.fastjson.JSONObject.toJSONString(map);
                String postParams = AesEncryptUtils.agEncrypt(content);
                String response = httpClientUtil.postBodyRawForm(url,postParams);
                result = com.alibaba.fastjson.JSONObject.parseObject(response);
                JSONObject jsonObjectData =JSONObject.parseObject(AesEncryptUtils.agDecrypt(result.getString("data")));
                System.out.println(jsonObjectData.toJSONString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
        //https://www.yuque.com/u1400669/kb/mlqrm2
        //https://www.yuque.com/u1400669/kb/div5py
    }
    /**
     * 消息解密
     * @param sSrc

+ 250 - 0
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/util/ArtemisPostTest.java

@ -0,0 +1,250 @@
package com.yihu.jw.care.util;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class ArtemisPostTest {
	/**
	 * 请根据自己的appKey和appSecret更换static静态块中的三个参数. [1 host]
	 * 如果你选择的是和现场环境对接,host要修改为现场环境的ip,https端口默认为443,http端口默认为80.例如10.33.25.22:443 或者10.33.25.22:80
	 * appKey和appSecret请按照或得到的appKey和appSecret更改.
	 * TODO 调用前先要清楚接口传入的是什么,是传入json就用doPostStringArtemis方法,下载图片doPostStringImgArtemis方法
	 */
	static {
		ArtemisConfig.host = "open.hikfirecloud.com";// 代理API网关nginx服务器ip端口
		ArtemisConfig.appKey = "23553385";// 秘钥appkey
		ArtemisConfig.appSecret = "HfjuKlQnzTbn0mfxm5Vk";// 秘钥appSecret
	}
	/**
	 * 能力开放平台的网站路径
	 * TODO 路径不用修改,就是/artemis
	 */
	private static final String ARTEMIS_PATH = "/artemis";
	/**
	 * 调用POST请求类型(application/json)接口,这里以入侵报警事件日志为例
	 * https://open.hikvision.com/docs/918519baf9904844a2b608e558b21bb6#e6798840
	 *
	 * @return
	 */
	public static String callPostStringApi(String url,String body){
		/**
		 * http://10.33.47.50/artemis/api/scpms/v1/eventLogs/searches
		 * 根据API文档可以看出来,这是一个POST请求的Rest接口,而且传入的参数值为一个json
		 * ArtemisHttpUtil工具类提供了doPostStringArtemis这个函数,一共六个参数在文档里写明其中的意思,因为接口是https,
		 * 所以第一个参数path是一个hashmap类型,请put一个key-value,query为传入的参数,body为传入的json数据
		 * 传入的contentType为application/json,accept不指定为null
		 * header没有额外参数可不传,指定为null
		 *
		 */
//		final String getCamsApi = ARTEMIS_PATH +"/api/scpms/v1/eventLogs/searches";
//		final String getCamsApi = ARTEMIS_PATH +"/api/firepro/v1/getCompany";
		final String getCamsApi = ARTEMIS_PATH + url;
		Map<String, String> path = new HashMap<String, String>(2) {
			{
				put("https://", getCamsApi);//根据现场环境部署确认是http还是https
			}
		};
		String result = ArtemisHttpUtil.doPostStringArtemis(path,body,null,null,"application/json",null);// post请求application/json类型参数
		return result;
	}
	/**
	 * 调用POST请求下载图片类型接口,这里以获取访客记录中的图片接口为例
	 * https://open.hikvision.com/docs/a0a1a0a24701a00aa904f7b151f97410#f11f3208
	 *
	 * @return
	 */
	public static void callPostImgStringApi(){
		/**
		 * http://10.33.47.50/api/visitor/v1/record/pictures
		 * 根据API文档可以看出来,这是一个POST请求的Rest接口,而且传入的参数值为一个json
		 * ArtemisHttpUtil工具类提供了doPostStringImgArtemis这个函数,一共六个参数在文档里写明其中的意思,因为接口是https,
		 * 所以第一个参数path是一个hashmap类型,请put一个key-value,query为传入的参数,body为传入的json数据
		 * 传入的contentType为application/json,accept不指定为null
		 * header没有额外参数可不传,指定为null
		 *
		 */
		final String VechicleDataApi = ARTEMIS_PATH +"/api/visitor/v1/record/pictures";
		Map<String,String> path = new HashMap<String,String>(2){
			{
				put("http://",VechicleDataApi);
			}
		};
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("svrIndexCode", "8907fd9d-d090-43d3-bb3a-3a4b10dd7219");
		jsonBody.put("picUri", "/pic?0dd453i3c-e*046456451175m6ep=t=i2p*i=d1s*i3d0d*=*1b8i81f4747059503--bdf90a-855s5721z3b9i=1=");
		String body = jsonBody.toJSONString();
		System.out.println("body: "+body);
		HttpResponse result = ArtemisHttpUtil.doPostStringImgArtemis(path,body,null,null,"application/json",null);
		try {
			HttpResponse resp = result;
			if (200==resp.getStatusLine().getStatusCode()) {
				HttpEntity entity = resp.getEntity();
				InputStream in = entity.getContent();
				Tools.savePicToDisk(in, "d:/", "test4.jpg");
				System.out.println("下载成功");
			}else{
				System.out.println("下载出错");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 消息订阅
	 *
	 * 980001	资源信息变更通知	1
		 980002	报警实时信息	2
		 980003	报警处理信息	3
		 980004	故障实时信息	4
		 980005	故障处理信息	5
		 980006	设备在离线消息	6
		 980007	监控点在离线消息	7
		 980008	监测实时信息	8
     */
	public static void subscription_info(String msgType){
		String url = "/api/firepro/v1/subscription/info";
		//消息类型	msgType	String	是
		//回调URL	postUrl	String	是
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("msgType", msgType);
		jsonBody.put("postUrl", "http://ehr.yihu.com/wlyy/aqg/hvdevice/messageNotification");
		//http://ehr.yihu.com/wlyy/aqg/device/byOnlineStatus
		//http://ehr.yihu.com/wlyy/aqg
		String body = jsonBody.toJSONString();
		String StringeResult = callPostStringApi(url,body);
		System.out.println("StringeResult结果示例: "+StringeResult);
	}
	/**
	 * 修改订阅
	 */
	public void subscription_update(){
		String url = "/api/firepro/v1/subscription/update";
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("pageNo", 1);
		jsonBody.put("pageSize", 3);
		String body = jsonBody.toJSONString();
		String StringeResult = callPostStringApi(url,body);
		System.out.println("StringeResult结果示例: "+StringeResult);
	}
	/**
	 * 删除订阅
	 */
	public void subscription_deletion(){
		String url = "/api/firepro/v1/subscription/deletion";
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("pageNo", 1);
		jsonBody.put("pageSize", 3);
		String body = jsonBody.toJSONString();
		String StringeResult = callPostStringApi(url,body);
		System.out.println("StringeResult结果示例: "+StringeResult);
	}
	/**
	 * 设备监测信息查询
	 */
	public static void getMonitor(){
		String url = "/api/firepro/v1/getMonitor";
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("pageNo", 1);
		jsonBody.put("pageSize", 10);
		jsonBody.put("flagId", "");
		jsonBody.put("offset", 0);
		String body = jsonBody.toJSONString();
		String StringeResult = callPostStringApi(url,body);
		System.out.println("StringeResult结果示例: "+StringeResult);
	}
	/**
	 * 获取消防设备信息
	 */
	public static String getDevice(){
		String url = "/api/firepro/v1/getDevice";
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("pageNo", 1);
		jsonBody.put("pageSize", 500);
		jsonBody.put("flagId", "");
		jsonBody.put("offset", 0);
		String body = jsonBody.toJSONString();
		String StringeResult = callPostStringApi(url,body);
		return StringeResult;
	}
	/**
	 * 消防设备添加
	 *
	 * 设备名称	deviceName	String	true	设备名称
	 设备序列号	deviceSerial	String	true	设备序列号
	 设备型号	deviceModel	String	true	设备型号,详见字典表
	 800022	NP-FY200-N 烟
	 800056 JT-HK400-N 气
	 设备类型	deviceType	Number	true	设备类型,详见字典表
	 600002	独立式光电感烟探测器(NB)
	 600006	独立式可燃气体探测器(NB)
	 通讯类型	communicationType	Number	true	通讯类型,详见字典表
	 900004	NB移动
	 */
	public static void addDevice(String deviceName,String deviceSerial,String deviceModel,String deviceType){
		String url = "/api/bws/device/v1/add";
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("deviceName", deviceName);
		jsonBody.put("deviceSerial", deviceSerial);
		jsonBody.put("deviceModel", deviceModel);
		jsonBody.put("deviceType", deviceType);
		jsonBody.put("communicationType", "900004");
		String body = jsonBody.toJSONString();
		String StringeResult = callPostStringApi(url,body);
		System.out.println("StringeResult结果示例: "+StringeResult);
	}
	/**
	 * 查询订阅
	 */
	public void subscription_list(){
		String url = "/api/firepro/v1/subscription/list";
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("pageNo", 1);
		jsonBody.put("pageSize", 3);
		String body = jsonBody.toJSONString();
		String StringeResult = callPostStringApi(url,body);
		System.out.println("StringeResult结果示例: "+StringeResult);
	}
	public static void main(String[] args) {
//		String url = "/api/firepro/v1/getCompany";
//		JSONObject jsonBody = new JSONObject();
//		jsonBody.put("pageNo", 1);
//		jsonBody.put("pageSize", 3);
//		String body = jsonBody.toJSONString();
//		String StringeResult = callPostStringApi(url,body);
//		System.out.println("StringeResult结果示例: "+StringeResult);
//		callPostImgStringApi();
//		getDevice();
		getMonitor();
//		subscription_info("980001");
//		subscription_info("980002");
//		subscription_info("980003");
//		subscription_info("980004");
//		subscription_info("980005");
//		subscription_info("980006");
//		subscription_info("980007");
//		subscription_info("980008");
	}
}

+ 60 - 0
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/util/Tools.java

@ -0,0 +1,60 @@
package com.yihu.jw.care.util;/**
 * Created by lifutao on 2019/1/11.
 */
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
 * 工具类
 *
 * @author
 * @create 2019-01-11 17:06
 **/
public class Tools {
    /**
     * 将图片写到 硬盘指定目录下
     *
     * @param in
     * @param dirPath
     * @param filePath
     */
    public static void savePicToDisk(InputStream in, String dirPath,
                                      String filePath) {
        try {
            File dir = new File(dirPath);
            if (dir == null || !dir.exists()) {
                dir.mkdirs();
            }
            //文件真实路径
            String realPath = dirPath.concat(filePath);
            File file = new File(realPath);
            if (file == null || !file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = in.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}