瀏覽代碼

代码修改

LAPTOP-KB9HII50\70708 1 年之前
父節點
當前提交
ad946524ee
共有 20 個文件被更改,包括 1294 次插入145 次删除
  1. 32 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/DeviceDetailDao.java
  2. 10 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/DevicePatientHealthIndexDao.java
  3. 36 13
      business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/entrance/HcyyEntranceService.java
  4. 27 5
      svr/svr-visit-behind/pom.xml
  5. 105 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/config/SystemConfig.java
  6. 66 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DeviceUploadController.java
  7. 60 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/Result.java
  8. 376 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceUploadService.java
  9. 70 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/iot/controller/IotDeviceController.java
  10. 58 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/iot/service/CallApiGatewaySample.java
  11. 190 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/iot/service/IotDeviceService.java
  12. 95 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/iot/service/LogService.java
  13. 130 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/iot/service/SDKRunnerService.java
  14. 1 0
      svr/svr-visit-behind/src/main/resources/jwkey/350211A1049_PrivateKey.SM2.key
  15. 5 0
      svr/svr-visit-behind/src/main/resources/jwkey/350211A1049_PrivateKey.SM2_V2.key
  16. 1 0
      svr/svr-visit-behind/src/main/resources/jwkey/350211A1049_PublicKey.SM2.key
  17. 4 0
      svr/svr-visit-behind/src/main/resources/jwkey/350211A1049_PublicKey.SM2_V2.key
  18. 1 0
      svr/svr-visit-behind/src/main/resources/jwkey/ZOE.PLATFORM_PublicKey.SM2.key
  19. 4 0
      svr/svr-visit-behind/src/main/resources/jwkey/ZOE.PLATFORM_PublicKey.SM2_V2.key
  20. 23 127
      svr/svr-visit-behind/src/main/resources/system.properties

+ 32 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/DeviceDetailDao.java

@ -0,0 +1,32 @@
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.care.device.DeviceDetail;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
/**
 * @author yeshijie on 2018/1/10.
 */
public interface DeviceDetailDao extends JpaRepository<DeviceDetail, Long>, JpaSpecificationExecutor<DeviceDetail> {
    @Query(value = "select a.* from wlyy_devices a where a.device_code=?1 limit 0,1",nativeQuery = true)
    DeviceDetail findBySn(String sn);
    List<DeviceDetail> findByDeviceCode(String deviceCode);
    @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 = ?1")
    List<DeviceDetail> findBySim(String sim);
    @Query("select a from DeviceDetail a where a.iccid = ?1")
    List<DeviceDetail> findByIccid(String iccid);
    @Query("select a from DeviceDetail a where a.imsi = ?1")
    List<DeviceDetail> findByImsi(String sim);
}

+ 10 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/DevicePatientHealthIndexDao.java

@ -0,0 +1,10 @@
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface DevicePatientHealthIndexDao
		extends PagingAndSortingRepository<DevicePatientHealthIndex, Long>, JpaSpecificationExecutor<DevicePatientHealthIndex> {
}

+ 36 - 13
business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/entrance/HcyyEntranceService.java

@ -3,13 +3,11 @@ package com.yihu.jw.hospital.prescription.service.entrance;
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.dict.dao.DictDoctorDutyDao;
import com.yihu.jw.dict.dao.DictHospitalDeptDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
import com.yihu.jw.entity.auth.OauthRsaKeyDO;
import com.yihu.jw.entity.base.dict.DictDoctorDutyDO;
import com.yihu.jw.entity.base.dict.DictHospitalDeptDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
@ -17,31 +15,28 @@ import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.BasePatientWechatDo;
import com.yihu.jw.entity.ca.OauthCaConfigDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.dict.WlyyChargeDictDO;
import com.yihu.jw.entity.hospital.httplog.WlyyHttpLogDO;
import com.yihu.jw.entity.hospital.mapping.DoctorMappingDO;
import com.yihu.jw.entity.hospital.mapping.PatientMappingDO;
import com.yihu.jw.entity.hospital.prescription.*;
import com.yihu.jw.file_upload.FileUploadService;
import com.yihu.jw.hospital.dict.WlyyChargeDictDao;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.httplog.dao.WlyyHttpLogDao;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
import com.yihu.jw.hospital.mapping.dao.PatientMappingDao;
import com.yihu.jw.hospital.prescription.dao.*;
import com.yihu.jw.hospital.prescription.service.entrance.util.AES;
import com.yihu.jw.oauth.OauthRsaKeyDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.hospital.doctor.CheckInfoVO;
import com.yihu.jw.restmodel.hospital.doctor.PersonInfoVO;
import com.yihu.jw.restmodel.hospital.prescription.*;
import com.yihu.jw.restmodel.hospital.prescription.WlyyInspectionVO;
import com.yihu.jw.restmodel.hospital.prescription.WlyyPrescriptionDiagnosisVO;
import com.yihu.jw.restmodel.hospital.prescription.WlyyPrescriptionInfoVO;
import com.yihu.jw.restmodel.hospital.prescription.WlyyPrescriptionVO;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
import com.yihu.jw.utils.StringUtil;
import com.yihu.jw.utils.WebserviceUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.jw.wechat.dao.BasePatientWechatDao;
@ -49,7 +44,6 @@ import com.yihu.utils.network.HttpResponse;
import com.yihu.utils.network.HttpUtils;
import com.yihu.utils.security.MD5;
import net.sf.json.xml.XMLSerializer;
import nu.xom.*;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
@ -61,9 +55,6 @@ import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.io.StringReader;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
@ -148,6 +139,8 @@ public class HcyyEntranceService {
    public static String entranceUrl = "http://172.16.100.240:10023/xzzx/";
    public static String entranceUrlLocal = "http://127.0.0.1:10023/hcyy/";
    //请求内网服务
    public static String entranceIotUrl = "http://127.0.0.1:10023/iotDevice/";
    private final static String url="http://127.0.0.1:10023/hcyy/createSQLQuery";
@ -155,6 +148,36 @@ public class HcyyEntranceService {
    public static String hospitalUrl = "http://192.168.118.240:10022/";//172.16.100.63
    //推送物联网体征数据
    public void pushIotDeviceDataInfo(Long id){
        try {
            String url = entranceIotUrl +"uploadDeviceData";
            Map<String,Object> params = new HashedMap();
            params.put("id",id);
            HttpResponse response = HttpUtils.doPost(url,params);
            String content = response.getContent();
            logger.info("response:"+content);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void pushIotDeviceRegistration(String deviceSn,String deviceModel,String deviceName,String categoryCode,String categoryName){
        try {
            String url = entranceIotUrl +"deviceRegistration";
            Map<String,Object> params = new HashedMap();
            params.put("deviceSn",deviceSn);
            params.put("deviceModel",deviceModel);
            params.put("deviceName",deviceName);
            params.put("categoryCode",categoryCode);
            params.put("categoryName",categoryName);
            HttpResponse response = HttpUtils.doPost(url,params);
            String content = response.getContent();
            logger.info("response:"+content);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public String getSelectUrl(){
        List<WlyyHospitalSysDictDO> list =  wlyyHospitalSysDictDao.findByDictName("hcyyWebSelectService");

+ 27 - 5
svr/svr-visit-behind/pom.xml

@ -243,11 +243,6 @@
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>push-service</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>im-service</artifactId>
@ -291,6 +286,33 @@
            <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
            <version>1.2.5</version>
        </dependency>
        <!-- 基卫统一平台接口 -->
        <dependency>
            <groupId>sehrCrypto</groupId>
            <artifactId>sehrCrypto</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.zoesoft</groupId>
            <artifactId>phip-ssp-sdk</artifactId>
            <version>1.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.zoesoft</groupId>
            <artifactId>zoe-crypto</artifactId>
            <version>1.4.0</version>
        </dependency>
        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna</artifactId>
            <version>4.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.zoesoft</groupId>
            <artifactId>zoe-encrypt-sm</artifactId>
            <version>1.0</version>
        </dependency>
    </dependencies>
    <build>

+ 105 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/config/SystemConfig.java

@ -0,0 +1,105 @@
package com.yihu.jw.hospital.config;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
 * @created hzp 2016/9/13.
 */
@Configuration
public class SystemConfig {
    private static Object lock = new Object();
    // 全局系统配置信息
    private static SystemConfig systemConf;
    // 系统配置文件
    private Properties systemProperties;
    //从system_properties表中取到的系统参数集,key参数key,value参数值
    public static Map<String,String> sysPropertiesSets = new HashMap<>();
    public static SystemConfig getInstance() {
        if (systemConf == null) {
            synchronized (lock) {
                systemConf = new SystemConfig();
            }
        }
        return systemConf;
    }
    /**
     * 加载系统配置文件
     * @return
     */
    public Properties getSystemProperties() {
        if (systemProperties == null) {
            InputStream is = null;
            try {
                is = this.getClass().getResourceAsStream("/system.properties");
                systemProperties = new Properties();
                systemProperties.load(is);
            } catch (IOException e1) {
                e1.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return systemProperties;
    }
    /************************* 基卫服务配置 ********************************************/
    public String getGatewayUrl()
    {
         return  getSystemProperties().getProperty("gateway_url");
    }
    public String getGatewayLicence()
    {
        return  getSystemProperties().getProperty("gateway_licence");
    }
    public String getPublicKey() { return  getSystemProperties().getProperty("gateway_public_key"); }
    public String getJwHospital()
    {
        return  getSystemProperties().getProperty("jw_hospital");
    }
    public String getJwLicence()
    {
        return  getSystemProperties().getProperty("jw_licence");
    }
    public String getPlatformPublicKey()
    {
        return  getSystemProperties().getProperty("platform.public.key");
    }
    public String getCompanyPublicKey()
    {
        return  getSystemProperties().getProperty("company.public.key");
    }
    public String getCompanyPrivateKey()
    {
        return  getSystemProperties().getProperty("company.private.key");
    }
    public String getAuthorizationCode()
    {
        return  getSystemProperties().getProperty("authorization.code");
    }
    public String getKeyReadType()
    {
        return  getSystemProperties().getProperty("key.read.type");
    }
}

+ 66 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DeviceUploadController.java

@ -0,0 +1,66 @@
package com.yihu.jw.hospital.module.health.controller;
import com.yihu.jw.hospital.module.health.service.DeviceUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/**
 * Created by Bing on 2021/7/7.
 */
@RestController
@Api(description = "第三放设备数据推送接口")
@RequestMapping(value = "/deviceData")
public class DeviceUploadController {
    //设备需要注册后才能推送至注册时地址,否则统一推送至默认地址
    //注册地址(post): http://www.cityihealth.com:43210/deviceManage/register?deviceSN=设备SN码&pushAddress=设备推送地址完整地址
    //
    private static Logger logger = LoggerFactory.getLogger(DeviceUploadController.class);
    @Autowired
    private DeviceUploadService deviceUploadService;
    @ApiOperation("设备注册接口(标准协议)")
    @PostMapping(value = "/open/excelControl/deviceRegistration")
    public Result deviceRegistration(String deviceSn, String deviceModel, String deviceName, String categoryCode, String categoryName) {
        try{
             deviceUploadService.deviceRegistration(deviceSn,deviceModel,deviceName,categoryCode,categoryName);
            return Result.success("deviceRegistration success");
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("deviceRegistration failure!");
        }
    }
    @ApiOperation("设备数据接收接口(标准协议)")
    @PostMapping(value = "/open/excelControl/upload")
    public Result uploadDevicesData(
            @ApiParam(value="推送类型(44代表体征推送)",defaultValue = "44")
            @RequestParam(value = "typeId", required = false)  Integer typeId ,
            @ApiParam(value="体征数据",defaultValue =
                    "{\"button\":\"1\",\"data\":\"1.81\",\"deviceSn\":\"16C000337\",\"deviceType\":2,\"id\":2377," +
                            "\"manufacturerCode\":\"threeNod\",\"manufacturerName\":\"三诺\",\"sendTime\":\"2017-03-13 13:47:42\"," +
                            "\"state\":0,\"unit\":\"mmol/L\",\"uploadTime\":\"2017-03-13 13:46:59\"}")
            @RequestParam(value = "data", required = true)  String data, HttpServletRequest request)
    {
        try{
            //{"button":"1","data":"93,57,81","deviceSn":"06B52305030267","deviceType":1,"id":2377,"manufacturerCode":"zte","manufacturerName":"中兴","sendTime":"2024-02-02 13:47:42","state":0,"unit":"mmol/L","uploadTime":"2024-02-02 13:46:59"}
            logger.info("typeId="+typeId+";data="+data);
            return deviceUploadService.uploadDevicesData(data,request);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return Result.error("Device data incoming failure!");
        }
    }
}

+ 60 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/Result.java

@ -0,0 +1,60 @@
package com.yihu.jw.hospital.module.health.controller;
import java.util.Map;
public class Result {
    protected boolean successFlg = true;
    protected String message;
    protected Map<String, Object> objectMap;
    public boolean isSuccessFlg() {
        return successFlg;
    }
    public void setSuccessFlg(boolean successFlg) {
        this.successFlg = successFlg;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public Map<String, Object> getObjectMap() {
        return objectMap;
    }
    public void setObjectMap(Map<String, Object> objectMap) {
        this.objectMap = objectMap;
    }
    /**
     * 错误消息
     */
    public static Result error(String message) {
        Result re= new Result();
        re.successFlg = false;
        re.message = message;
        return re;
    }
    /**
     * 成功消息
     */
    public static Result success(String message) {
        Result re= new Result();
        re.successFlg = true;
        re.message = message;
        return re;
    }
    public static Result authError(String message) {
        Result re= new Result();
        re.successFlg = false;
        re.message = message;
        return re;
    }
}

+ 376 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceUploadService.java

@ -0,0 +1,376 @@
package com.yihu.jw.hospital.module.health.service;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.device.dao.DeviceDetailDao;
import com.yihu.jw.device.dao.DevicePatientHealthIndexDao;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.hospital.module.health.controller.Result;
import com.yihu.jw.hospital.module.iot.service.IotDeviceService;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.StringUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * Created by Bing on 2021/7/7.
 */
@Service
public class DeviceUploadService {
    private static Logger logger = LoggerFactory.getLogger(DeviceUploadService.class);
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private DevicePatientHealthIndexDao patientHealthIndexDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private IotDeviceService iotDeviceService;
    public void deviceRegistration(String deviceSn, String deviceModel, String deviceName, String categoryCode, String categoryName) {
        try {
            iotDeviceService.deviceRegistration(deviceSn,deviceModel,deviceName,categoryCode,categoryName);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public Result uploadDevicesData(String dataJson, HttpServletRequest request)throws Exception {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = objectMapper.readValue(dataJson, Map.class);
            String deviceSn = map.get("deviceSn").toString();//设备唯一码
            Integer deviceType = Integer.parseInt(map.get("deviceType").toString());//设备类型1:血压 2:血糖
            String data = map.get("data").toString();//体征值(血糖:data=血糖值   血压:data=收缩压,舒张压,脉搏)
            String uploadTime = map.get("uploadTime").toString();//体征上传时间yyyy-MM-dd HH:mm:ss
            String manufacturerCode = map.get("manufacturerCode").toString();//厂商代码
            String manufacturerName = map.get("manufacturerName").toString();//厂商名称
            String unit = map.get("unit").toString();//单位mmol/L,mmHg
            String sendTime = map.get("sendTime").toString();//发送时间yyyy-MM-dd HH:mm:ss
            String userType = map.get("button").toString();//按键号 即 userType
            String measurementType=null==map.get("measurementType")?"":map.get("measurementType").toString(); //单个设备的测量类型,deviceType=4智能手表:1心率,2血压
            String paraString = JSON.toJSONString(request.getParameterMap());
            JSONObject json = new JSONObject();
            json.put("deviceSn", deviceSn);
            json.put("deviceType", deviceType);
            json.put("data", data);
            json.put("uploadTime", uploadTime);//三诺的上传时间
            json.put("manufacturerCode", manufacturerCode);
            json.put("manufacturerName", manufacturerName);
            json.put("unit", unit);
            json.put("sendTime", sendTime);//三诺的测量时间
            json.put("userType", userType);
            json.put("measurementType", measurementType);
            String type = deviceType + "";
            if (1 == deviceType) {
                type = "2";
            } else if (2 == deviceType) {
                type = "1";
                userType = "-1";
            }
//            DeviceInfo deviceInfo = new DeviceInfo();
//            deviceInfo.setDeviceData(dataJson);
//            deviceInfo.setDeviceType(type);
//            deviceInfo.setPushDate(DateUtil.getNowTimestamp());
//            deviceInfo.setStatus("1");
//            deviceInfoDao.save(deviceInfo);
            DevicePatientHealthIndex result = null;
            if(type.equalsIgnoreCase("1")){
                if (Double.parseDouble(data)>=1){
                    result = savePatientDeviceData(deviceSn, type, data, uploadTime, userType, json,measurementType);
                }else {
                    logger.info("This blood device data below 1.0:====="+dataJson);
                    throw new Exception("This blood device data below 1.0 ");
                }
            }else {
                result = savePatientDeviceData(deviceSn, type, data, uploadTime, userType, json,measurementType);
            }
            if (result == null) {
                logger.info("This device is not relate patient!:====="+dataJson);
                throw new Exception("This device is not relate patient!");
            }
//            dataPushLogUtil.savePushLog(deviceSn,paraString,"体征数据接收");
//            dataPushLogUtil.updContactStatus(deviceSn,1,false);
            iotDeviceService.uploadDeviceData(result.getId());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return Result.success("Device data incoming success");
    }
    /**
     * 保存设备数据
     * @param type 设备类型 4 智能手表
     * @param userType 用户身份:-1 单用户
     * @param measurementType 单设备多功能类型 type=4时,measurementType=1心率,measurementType=2血压
     */
    public DevicePatientHealthIndex savePatientDeviceData(String deviceSn, String type, String data, String uploadTime, String userType, JSONObject json, String measurementType) throws Exception {
        Date currentTime = DateUtil.getNowTimestamp();
        Date time = currentTime;
        if (!StringUtil.isEmpty(uploadTime)) {
            //设备重新开机启动会有默认时间,相隔很远.
            time = DateUtil.toTimestamp(uploadTime, DateUtil.YYYY_MM_DD_HH_MM_SS);
            Date monthTime = DateUtil.getNextMonthReturnDate( currentTime,-12);
            if (DateUtil.compareDate(time, monthTime) < 0) {
                time = currentTime;
            }
        }
        if (StringUtil.isStrEmpty(userType)) {
            userType = "-1";
        }
        DevicePatientDevice device = null;
        DeviceDetail deviceDetail = null;
        List<DeviceDetail> deviceDetails = deviceDetailDao.findByDeviceCode(deviceSn);
        if (deviceDetails != null || deviceDetails.size()!=0){
            deviceDetail = deviceDetails.get(0);
            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);
                }else if(patientDeviceList != null&&patientDeviceList.size()==2){
                    for (int i=0;i<patientDeviceList.size();i++){
                        if(userType.equals(patientDeviceList.get(i).getUserType())){
                            device = patientDeviceList.get(i);
                            break;
                        }
                    }
                }
            }else {
//                device = patientDeviceDao.findByDeviceSnAndCategoryCodeAndUserType(deviceSn, type, userType);
                List<DevicePatientDevice> devices = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
                if (devices.size()>0){
                    device = devices.get(0);
                }else {
                    device=null;
                }
            }
        }
        if (device != null) {
        /*//根据设备获取患者(设备只绑定一个人的时候,不判断按键)
        if (device!=null) {*/
            /************设备数据重复推送处理 start**********************/
            String value1 = data;
            String value2="";
            String value3="";
            if("2".equals(type)){
                String[] value = data.split(",");
                if (value.length > 0) {
                    value1 = value[0];     //收缩压
                    value2 = value[1];
                    value3 = value[2];
                }
            }else if("4".equals(type)){
                if(StringUtils.isNotBlank(measurementType)&&"2".equals(measurementType)){
                    type="2";
                    String[] value = data.split(",");
                    if (value.length > 0) {
                        value1 = value[0];     //收缩压
                        value2 = value[1];
                        /* value3 = value[2];*/
                    }
                }else {
                    //心率
                    type="5";
                }
            }
            if (value1.equals(value2) && value2.equals(value3)){
                return null;
            }
//            List<PatientHealthIndex> list = patientHealthIndexDao.findByType(device.getUser(),deviceSn,value1,Integer.parseInt(type),time);
            /*long maxtime = time.getTime()+30*1000;
            long mintime = time.getTime()-30*1000;*/
            Date minDate = DateUtil.getPreDays(time,-3);
            Date maxDate = DateUtil.getPreDays(time,3);
            List<DevicePatientHealthIndex> list = ioTfindByType(device.getUser(),deviceSn,value1,value2,value3,Integer.parseInt(type),time,minDate,maxDate);
            if(list!=null&&list.size()>0){
                return null;
            }
            /************设备数据重复推送处理 end**********************/
            DevicePatientHealthIndex obj = new DevicePatientHealthIndex();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            obj.setCzrq(sdf.parse(json.getString("sendTime")));//创建时间取三诺的测量时间记录
            obj.setDeviceSn(deviceSn);
            obj.setDel("1");
            obj.setRecordDate(sdf.parse(json.getString("uploadTime")));    //记录时间取上传时间
            obj.setSortDate(time);      //排序时间
//            obj.setManageResult(0);//默认数据是医生未干预状态
            String user = device.getUser();
            obj.setUser(user);
//            obj.setButton(userType);
            obj.setIdcard(device.getUserIdcard());
            obj.setStatus(0);
            //  1血糖 2血压 3体重 4腰围,5心率
            switch (type) {
                case "1":
                    obj.setType(1);
                    obj.setValue1(data);     //血糖值
                    obj.setValue2(formatBloodSuger(user,deviceSn,DateUtil.dateToStr(time, DateUtil.YYYY_MM_DD_HH_MM_SS)));
                    break;
                case "2":
                    obj.setType(2);
                    String[] value = data.split(",");
                    if (value.length > 0) {
                        obj.setValue1(value[0]);     //收缩压
                    }
                    if (value.length > 1) {
                        obj.setValue2(value[1]);     //舒张压
                    }
                    if (value.length > 2) {
                        obj.setValue3(value[2]);     //脉搏
                    }
                    if (value.length > 3) {
                        obj.setValue4(value[3]);     //有无心率不齐
                    }
                    break;
                case "3":
                    obj.setType(3);
                    obj.setValue1(data); //体重
                    break;
                case "4":
                    obj.setType(4);
                    obj.setValue1(data);  //腰围
                    break;
                case "5":
                    obj.setType(5);
                    obj.setValue1(data);  //心率
                    break;
                default:
                    throw new Exception("Can not support the metric!");
            }
            //新增字段处理
            BasePatientDO patient = patientDao.findById(user);
            if(patient!=null){
                obj.setName(patient.getName());
            }
            if(deviceDetail!=null){
                obj.setHospital(deviceDetail.getGrantOrgCode());
                obj.setHospitalName(deviceDetail.getOrgName());
            }
            obj = patientHealthIndexDao.save(obj);
            return obj;
        }
        return null;
    }
    /**
     * 查找重复数据
     * @param user
     * @param deviceSn
     * @param value1
     * @param type
     * @param time
     * @return
     */
    public List<DevicePatientHealthIndex> ioTfindByType(String user,String deviceSn,String value1,String value2,String value3,Integer type,Date time,Date timeMin,Date timeMax){
        List<DevicePatientHealthIndex> list = new ArrayList<>();
        String sql = "";
        String startTime = DateUtil.dateToStrLong(timeMin);
        String endTime = DateUtil.dateToStrLong(timeMax);
        if (type==1){
            sql = "select a.* from wlyy_patient_health_index a where a.user = '"+user+"' and a.device_sn = '"+deviceSn+"' " +
                   "and a.value1 = '"+value1+"' and a.type = "+type+" and a.record_date >= '"+startTime+"' and a.record_date<='"+endTime+"' and a.del = '1' ";
        }else if (type==2){
           sql = "select a.* from wlyy_patient_health_index a where a.user = '"+user+"' and a.device_sn = '"+deviceSn+"' " +
                   "and a.value1 = '"+value1+"' and a.value2='"+value2+"'  and a.value3='"+value3+"' and a.type = "+type+" " +
                   "and a.record_date >= '"+startTime+"' and a.record_date<='"+endTime+"' and a.del = '1' ";
        }
        list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(DevicePatientHealthIndex.class));
        return list;
    }
    /**
     * 血糖测量时间段
     * @param user
     * @param deviceSN
     * @param dateTime
     * @return
     */
    private String formatBloodSuger(String user,String deviceSN,String dateTime) {
        String fastingStart = "00:00:00";
        String fastingEnd = "07:59:59";
        String afterBreakFastStart = "08:00:00";
        String afterBreakFastEnd = "09:59:59";
        String beforeLunchStart = "10:00:00";
        String beforeLunchEnd = "11:59:59";
        String afterLunchStart = "12:00:00";
        String afterLunchEnd = "13:59:59";
        String beforeDinnerStart = "14:00:00";
        String beforeDinnerEnd = "17:59:59";
        String afterDinnerStart = "18:00:00";
        String afterDinnerEnd = "19:59:59";
        String beforeSleepStart = "20:00:00";
        String beforeSleepEnd = "23:59:59";
        if (isInArea(dateTime, fastingStart,fastingEnd)) {
            return "1";//"空腹血糖"
        }
        if (isInArea(dateTime, afterBreakFastStart,afterBreakFastEnd)) {
            return "2";//"早餐后血糖"
        }
        if (isInArea(dateTime, beforeLunchStart,beforeLunchEnd)) {
            return "3";//"午餐前血糖"
        }
        if (isInArea(dateTime, afterLunchStart,afterLunchEnd)) {
            return "4";//"午餐后血糖"
        }
        if (isInArea(dateTime, beforeDinnerStart,beforeDinnerEnd)) {
            return "5";//"晚餐前血糖"
        }
        if (isInArea(dateTime, afterDinnerStart,afterDinnerEnd)) {
            return "6";//"晚餐后血糖"
        }
        if (isInArea(dateTime, beforeSleepStart,beforeSleepEnd)) {
            return "7";//"睡前血糖"
        }
        return "1";//"空腹血糖"
    }
    // 判断时间是否在对应时间段
    private Boolean isInArea(String time,String begin,String end) {
        String date = DateUtil.getDateFromDateTime(time);
        Long beginTime = DateUtil.compareDateTime(DateUtil.toTimestamp(time), DateUtil.toTimestamp(date + " " + begin ));
        Long endTime = DateUtil.compareDateTime(DateUtil.toTimestamp(time), DateUtil.toTimestamp(date + " " + end ));
        if (beginTime > 0 && endTime < 0) {
            return true;
        } else {
            return false;
        }
    }
}

+ 70 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/iot/controller/IotDeviceController.java

@ -0,0 +1,70 @@
package com.yihu.jw.hospital.module.iot.controller;
import com.yihu.jw.hospital.module.iot.service.IotDeviceService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by yeshijie on 2023/12/6.
 */
@RestController
@RequestMapping(value ="/iotDevice")
@Api(value = "物联网设备", description = "物联网设备", tags = {"物联网设备"})
public class IotDeviceController extends EnvelopRestEndpoint {
    @Autowired
    private IotDeviceService iotDeviceService;
    @PostMapping(value = "/uploadDeviceInfo")
    @ApiOperation(value = "设备状态信息上传")
    public Envelop uploadDeviceInfo() {
        try {
            return success(iotDeviceService.uploadDeviceInfo());
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("查询失败");
        }
    }
    @PostMapping(value = "/uploadDeviceData")
    @ApiOperation(value = "设备业务数据信息上传")
    public Envelop uploadDeviceData(Long id) {
        try {
            return success(iotDeviceService.uploadDeviceData(id));
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("查询失败");
        }
    }
    @PostMapping(value = "/deviceRegistration")
    @ApiOperation(value = "设备相关基础信息注册")
    public Envelop deviceRegistration(String deviceSn,String deviceModel,String deviceName,String categoryCode,String categoryName) {
        try {
            return success(iotDeviceService.deviceRegistration(deviceSn,deviceModel,deviceName,categoryCode,categoryName));
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("查询失败");
        }
    }
    @GetMapping(value = "/accesstoken")
    @ApiOperation(value = "获取accesstoken")
    public Envelop getAccessToken() {
        try {
            return success(iotDeviceService.getAccessToken());
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("查询失败");
        }
    }
}

+ 58 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/iot/service/CallApiGatewaySample.java

@ -0,0 +1,58 @@
package com.yihu.jw.hospital.module.iot.service;
import cn.com.zoe.crypto.jna.CryptoType;
import com.zoe.phip.ssp.sdk.*;
import java.io.IOException;
import java.util.List;
public class CallApiGatewaySample extends AbstractApiExecuter2 {
    private String apiUrl;
    private List<RequestValue> parameters;
    private RequestMethod method;
    private HeaderValue[] headers;
    public CallApiGatewaySample(byte[] platformPublicKey, byte[] parameterPublicKey, byte[] resultPrivateKey) {
        super(platformPublicKey, parameterPublicKey, resultPrivateKey);
    }
    public CallApiGatewaySample(String publicKeyBase64String, String parameterPublicKey, String resultPrivateKey) {
        super(publicKeyBase64String, parameterPublicKey, resultPrivateKey);
    }
    public CallApiGatewaySample setApiUrl(String apiUrl) {
        this.apiUrl = apiUrl;
        return this;
    }
    public CallApiGatewaySample setParameters(List<RequestValue> parameters) {
        this.parameters = parameters;
        return this;
    }
    public CallApiGatewaySample setMethod(RequestMethod method) {
        this.method = method;
        return this;
    }
    public CallApiGatewaySample setHeaders(HeaderValue[] headers) {
        this.headers = headers;
        return this;
    }
    @Override
    public String run(String authorizationCode, boolean openCrypto, CryptoType type) throws ApiException, IOException {
        if (!CryptoType.NO_CRYPTO.equals(type) && (authorizationCode == null || "".equals(authorizationCode))) {
            throw new ApiException("用户token不能为空", null);
        }
        if (apiUrl == null || "".equals(apiUrl)) {
            throw new ApiException("未填写接口地址", null);
        }
        if (method == null) {
            method = RequestMethod.POST;
        }
        return doHttp(apiUrl, method, authorizationCode, openCrypto, parameters, type, headers);
    }
}

+ 190 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/iot/service/IotDeviceService.java

@ -0,0 +1,190 @@
package com.yihu.jw.hospital.module.iot.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.device.dao.DevicePatientHealthIndexDao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.iot.gateway.GcToken;
import com.yihu.jw.gateway.dao.GcTokenDao;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
 * 三院物联网对接
 * Created by yeshijie on 2023/12/6.
 */
@Service
public class IotDeviceService {
    @Autowired
    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
    @Autowired
    private SDKRunnerService sdkRunnerService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private GcTokenDao gcTokenDao;
    @Autowired
    private DevicePatientHealthIndexDao patientHealthIndexDao;
    @Autowired
    private BasePatientDao patientDao;
    private static String iotHospital = "350211A1049";
    private static String iotHospitalName = "厦门医学院附属海沧医院";
    //设备状态信息上传
    @Transactional
    public String uploadDeviceInfo(){
        Map<String,String> header = new HashMap<>();
        String jsonData = "{\"deviceSn\":\"xty_hcyy\",\"deviceModel\":\"测试\",\"name\":\"血糖仪TEST\",\"hospital\":\""+iotHospital+"\"," +
                "\"hospitalName\":\""+iotHospitalName+"\",\"categoryCode\":\"2\",\"categoryName\":\" 血糖仪\",\"commonName\":\" 血糖仪\"," +
                "\"combinationMethod\":\"1\",\"networkTransmission\":\" 11\",\"deviceUse\":\"2\",\"dropLocation\":\"2\",\"dataAcquisition\":" +
                "\"IoT_equipment_blood_glucose_mete\",\"companyName\":\"血糖仪厂商名称\",\"companyType\":\"3\"}";
        Map<String,String> params = new HashMap<>();
        params.put("jsonData",jsonData);
        header.put("accesstoken",getAccessToken());
        String response = sdkRunnerService.post("wlw/uploadDeviceInfo","设备状态信息上传",params,header,true,true);
        return response;
    }
    //设备业务数据信息上传
    @Transactional
    public String uploadDeviceData(Long id){
        if(id == null){
            return " id is null";
        }
        DevicePatientHealthIndex healthIndex = patientHealthIndexDao.findOne(id);
        if(healthIndex==null){
            return " data is null";
        }
        JSONObject jsonData = new JSONObject();
        jsonData.put("deviceSn",healthIndex.getDeviceSn());
        jsonData.put("hospital",iotHospital);
        BasePatientDO patientDO = patientDao.findById(healthIndex.getUser());
        if(patientDO!=null){
            jsonData.put("name",patientDO.getName());
            jsonData.put("idcard",patientDO.getIdcard());
        }
        JSONArray data = new JSONArray();
        if(healthIndex.getType()==1){
            jsonData.put("categoryCode","2");
            JSONObject blood = new JSONObject();
            blood.put("blood_sugar",healthIndex.getValue1());
            blood.put("measure_time",DateUtil.dateToStrLong(healthIndex.getRecordDate()));
            data.add(blood);
        }else if(healthIndex.getType()==2){
            jsonData.put("categoryCode","1");
            // 血压:data={ "systolic ": "110", "diastolic ": "78", "pulse ": "66", "heart_rate ": "66", "measure_time ": "2023-02-02 14:07:25"
            JSONObject blood = new JSONObject();
            blood.put("systolic",healthIndex.getValue1());
            blood.put("diastolic",healthIndex.getValue2());
            blood.put("heart_rate",healthIndex.getValue3());
            blood.put("measure_time",DateUtil.dateToStrLong(healthIndex.getRecordDate()));
            data.add(blood);
        }else {
            return " only type 1 or 2";
        }
        jsonData.put("data",data);
        Map<String,String> header = new HashMap<>();
        Map<String,String> params = new HashMap<>();
        params.put("jsonData",jsonData.toJSONString());
        header.put("accesstoken",getAccessToken());
        String response = sdkRunnerService.post("wlw/uploadDeviceData","设备业务数据信息上传",params,header,true,true);
        return response;
    }
    //设备相关基础信息注册
    @Transactional
    public String deviceRegistration(String deviceSn,String deviceModel,String deviceName,String categoryCode,String categoryName){
        Map<String,String> header = new HashMap<>();
        JSONObject json = new JSONObject();
        json.put("deviceSn",deviceSn);
        json.put("deviceModel",deviceModel);
        json.put("name",deviceName);
        json.put("hospital",iotHospital);
        json.put("hospitalName",iotHospitalName);
        json.put("categoryCode",categoryCode);
        json.put("categoryName",categoryName);
        json.put("commonName",categoryName);
        json.put("combinationMethod","1");
        json.put("networkTransmission","11");
        json.put("deviceUse","1");
        json.put("dropLocation","2");
        json.put("dataAcquisition","IoT_equipment_blood_glucose_mete");
        json.put("companyName","厂商名称");
        json.put("companyType","3");
        Map<String,String> params = new HashMap<>();
        params.put("jsonData",json.toJSONString());
        header.put("accesstoken",getAccessToken());
        String response = sdkRunnerService.post("wlw/deviceRegistration","设备相关基础信息注册",params,header,true,true);
        return response;
    }
    /**
     * 获取accesstoken
     * @return
     */
    @Transactional
    public synchronized String getAccessToken(){
        //新增accesstoken 缓存
        Map<String,String> header = new HashMap<>();
        List<WlyyHospitalSysDictDO> dictDOList =  wlyyHospitalSysDictDao.findByDictName("zy_iot");
        Map<String,String> dictMap = dictDOList.stream().collect(Collectors.toMap(WlyyHospitalSysDictDO::getDictCode,WlyyHospitalSysDictDO::getDictValue));
        String appid = dictMap.get("appid");
        String appSecret = dictMap.get("appSecret");
        Map<String,String> params = new HashMap<>();
        params.put("appid",appid);
        params.put("appSecret",appSecret);
        String sql = "SELECT * from gc_token WHERE appid='"+appid+"' and del='1' and out_time>='"+DateUtil.getStringDate()+"' ORDER BY id desc LIMIT 1";
        List<GcToken> gcTokenList = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(GcToken.class));
        if(gcTokenList.size()>0){
            //缓存未失效前直接读缓存
            return gcTokenList.get(0).getAccesstoken();
        }
        String response = sdkRunnerService.post("wlw/accesstoken","获取accesstoken",params,header,true,true);
        System.out.println("response===="+response);
        JSONObject json = JSON.parseObject(response);
        if(json.getInteger("status")==10000){
            JSONObject result = json.getJSONObject("result");
            String accesstoken = result.getString("accesstoken");
            //两个小时超时
            long createTime = result.getLong("createTime");
            long outTime = result.getLong("outTime");
            outTime = outTime - Math.abs(System.currentTimeMillis()-createTime)-1000;
            //把该用户之前有效的token设置为无效
            gcTokenDao.updateDel(appid);
            GcToken gc = new GcToken();
            gc.setAppid(appid);
            gc.setCreateTime(new Date());
            gc.setOutTime(longToDate(outTime));
            gc.setAccesstoken(accesstoken);
            gc.setDel(1);
            gcTokenDao.save(gc);
            return accesstoken;
        }
        return null;
    }
    public static Date longToDate(long timestamp){
        Instant instant = Instant.ofEpochMilli(timestamp);
        return Date.from(instant);
    }
}

+ 95 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/iot/service/LogService.java

@ -0,0 +1,95 @@
package com.yihu.jw.hospital.module.iot.service;
import com.yihu.jw.entity.hospital.httplog.WlyyHttpLogDO;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.httplog.dao.WlyyHttpLogDao;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.UUID;
/**
 * Created by hzp on 2016/9/24.
 * 日志服务
 */
@Service
public class LogService {
    private org.slf4j.Logger logger= LoggerFactory.getLogger(LogService.class);
    @Autowired
    private WlyyHttpLogDao httpLogDao;
    @Autowired
    private WlyyHospitalSysDictDao hospitalSysDictDao;
    public String archiveType = "2";
    public String onePayType = "3";
    public String caType = "4";
    public String getCode() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    /**
     * 新增开放api调用日志
     **/
    public void saveOpenApiLog(Boolean isSuccess,String url,String content,String method,String params,String response,String error)
    {
        try {
            WlyyHttpLogDO log = new WlyyHttpLogDO();
            log.setCode(url+method);
            log.setName(content);
            log.setRequest(params);
            log.setCreateTime(new Date());
            if(response.length()>10652261){
                log.setResponse(response.substring(0,10652260));
            }else {
                log.setResponse(response);
            }
            log.setStatus(isSuccess?"1":"0");
            httpLogDao.save(log);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
    /**
     * 保存http调用日志【基卫接口】
     **/
    public void saveHttpLog(Boolean isSuccess,String url,String content,String method,String params,String response,String error)
    {
        saveHttpLog( isSuccess, url, content, method,  params, response, error,"1");
    }
    /**
     * 保存http调用日志    0开放api  1基卫接口  2市民健康网接口   3易联众接口  4长处方接口
     **/
    public void saveHttpLog(Boolean isSuccess,String url,String content,String method,String params,String response,String error,String type)
    {
        try {
            WlyyHttpLogDO log = new WlyyHttpLogDO();
            log.setCode(url+method);
            log.setName(content);
            log.setRequest(params);
            log.setCreateTime(new Date());
            if(response.length()>10652261){
                log.setResponse(response.substring(0,10652260));
            }else {
                log.setResponse(response);
            }
            log.setStatus(isSuccess?"1":"0");
            httpLogDao.save(log);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

+ 130 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/iot/service/SDKRunnerService.java

@ -0,0 +1,130 @@
package com.yihu.jw.hospital.module.iot.service;
import cn.com.zoe.crypto.Base64;
import cn.com.zoe.crypto.jna.CryptoType;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yihu.jw.hospital.config.SystemConfig;
import com.zoe.phip.ssp.sdk.ApiException;
import com.zoe.phip.ssp.sdk.HeaderValue;
import com.zoe.phip.ssp.sdk.RequestMethod;
import com.zoe.phip.ssp.sdk.RequestValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * SDK调用代码参考
 */
@Service
public class SDKRunnerService {
    private static String platformPublicKey;
    private static String companyPrivateKeyBase64String;
    private static String companyPublicKeyBase64String;
    private static String authorizationCode;
    private static String gateway_url;
    @Autowired
    private LogService logService;
    static {
        platformPublicKey = getEncryptData(SystemConfig.getInstance().getPlatformPublicKey());
        companyPrivateKeyBase64String = getEncryptData(SystemConfig.getInstance().getCompanyPrivateKey());
        companyPublicKeyBase64String = getEncryptData(SystemConfig.getInstance().getCompanyPublicKey());
//        platformPublicKey = SystemConfig.getInstance().getPlatformPublicKey();
//        companyPrivateKeyBase64String = SystemConfig.getInstance().getCompanyPrivateKey();
//        companyPublicKeyBase64String = SystemConfig.getInstance().getCompanyPublicKey();
        // 平台分配的授权码
        authorizationCode = SystemConfig.getInstance().getAuthorizationCode();
        gateway_url = SystemConfig.getInstance().getGatewayUrl();
    }
    /**
     *
     * @param api
     * @param params
     * @param header
     * @param openCrypto 是否启用平台加密
     * @param urlEncode url编码
     * @return
     */
    public String post(String api,String content, Map<String,String> params,Map<String,String> header,boolean openCrypto,boolean urlEncode){
        String result = null;
        String msgBody = JSONObject.toJSONString(params, SerializerFeature.WriteMapNullValue);
        String msgHeader = JSONObject.toJSONString(header, SerializerFeature.WriteMapNullValue);
        try {
            // 密钥类型(RSA、SM2、SM2V2)
            CryptoType type = CryptoType.SM2_V2;
            // 接口地址
            String apiUrl = gateway_url+api;
            // 参数
            List<RequestValue> parameters = new ArrayList<>();
            if(params!=null)
            {
                // 普通参数请求示例
//                    new RequestValue("msgHeader", "<?xml version=\"1.0\" encoding=\"utf-8\"?><ROOT></ROOT>", true, openCrypto),
//                    new RequestValue("msgBody", "<?xml version=\"1.0\" encoding=\"utf-8\"?><ROOT></ROOT>", true, openCrypto)
                // new RequestValue("idCard", "123", true, openCrypto)
                //实体参数请求示例
                for(String key :params.keySet())
                {
                    RequestValue obj = new RequestValue(key,params.get(key),urlEncode,openCrypto);
                    parameters.add(obj);
                }
            }
            HeaderValue[] headers = new HeaderValue[header.size()];
//            headers[0] = new HeaderValue("Content-Type","application/json",true);
            int i = 0;
            for(String key :header.keySet())
            {
                headers[i] = new HeaderValue(key,header.get(key),urlEncode);
                i++;
            }
            // 请求方式
            RequestMethod method = RequestMethod.POST;
            //实例化需要使用的接口对象
            CallApiGatewaySample runnable =
                    new CallApiGatewaySample(platformPublicKey, companyPublicKeyBase64String, companyPrivateKeyBase64String)
                            .setApiUrl(apiUrl)
                            .setParameters(parameters)
                            .setHeaders(headers)
                            .setMethod(method);
            // 运行Api进行数据请求
            result = runnable.run(authorizationCode, openCrypto, type);
            //保存http日志
            logService.saveHttpLog(true,api,content,method.name(),msgHeader,msgBody,result,null);
        } catch (ApiException e) {
            //保存http日志
            logService.saveHttpLog(false,api,content,null,msgHeader,msgBody,result,null);
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }
    private static String getEncryptData(String value) {
        InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(value);
        try {
            if (stream != null && stream.available() > 0) {
                byte[] bytes = new byte[stream.available()];
                stream.read(bytes);
                return Base64.getEncoder().encodeToString(bytes);
            } else {
                System.out.println("未找到密钥文件:"+value);
            }
        } catch (Exception e) {
            System.out.println("读取密钥文件出错:"+value);
            e.printStackTrace();
        }
        return null;
    }
}

+ 1 - 0
svr/svr-visit-behind/src/main/resources/jwkey/350211A1049_PrivateKey.SM2.key

@ -0,0 +1 @@
00B0BFBEF40DD9C2AA8F5DEF215B84DA3A168D0B91DA93E48249D77DBB131365A7

+ 5 - 0
svr/svr-visit-behind/src/main/resources/jwkey/350211A1049_PrivateKey.SM2_V2.key

@ -0,0 +1,5 @@
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBG0wawIBAQQgStMGk4ZO9NjKSTON
+wrft9hnd/gnxlnrbekHF5ROe7mhRANCAATfE8FZj2JfNDYUUrdKO6SENplXzsHA
fDMwDTG6W4lzWmsU7eNslOjSXzfnXL767QWkdW+x8ZR7JAQYb9mtZ1Xi
-----END PRIVATE KEY-----

+ 1 - 0
svr/svr-visit-behind/src/main/resources/jwkey/350211A1049_PublicKey.SM2.key

@ -0,0 +1 @@
04127F810FDB668318B6D5B4175BF3601FFAC09422E8236C903EA70AE0F2387A5DDBDE2B28A61630CF38051C958B63E1117BFE31CE205F112EE312C34D031EF97F

+ 4 - 0
svr/svr-visit-behind/src/main/resources/jwkey/350211A1049_PublicKey.SM2_V2.key

@ -0,0 +1,4 @@
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE3xPBWY9iXzQ2FFK3SjukhDaZV87B
wHwzMA0xuluJc1prFO3jbJTo0l8351y++u0FpHVvsfGUeyQEGG/ZrWdV4g==
-----END PUBLIC KEY-----

+ 1 - 0
svr/svr-visit-behind/src/main/resources/jwkey/ZOE.PLATFORM_PublicKey.SM2.key

@ -0,0 +1 @@
048C90BC86F59449E5C8784F043EEB0BB778212043029FB7F96FCD65E788B8F752DAA6787B385CFEFCC182DAB9827A7004E6F78DC3F1B75A1B642F66CC67C4EBF8

+ 4 - 0
svr/svr-visit-behind/src/main/resources/jwkey/ZOE.PLATFORM_PublicKey.SM2_V2.key

@ -0,0 +1,4 @@
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAErmfpquDHQpe51A8K8DwiaFrUex6g
wsmi1k8JbkUAbFXJ6LJn9x7Fm3QlxExCKfnYV7mkCoK1u8i7sHsD9GbaOg==
-----END PUBLIC KEY-----

+ 23 - 127
svr/svr-visit-behind/src/main/resources/system.properties

@ -1,130 +1,26 @@
#-------------------------共同配置-----------------------------#
# 预约配置参数
guahao_url = http://www.xmsmjk.com/UrpNetService/ReservationNet.asmx
guahao_namespace = http://www.zysoft.com.cn/
#?????? 0?? 1???
key.read.type=0
##test
#gateway_url = http://117.25.173.18:18280/
#gateway_licence = 1GPM6UKII0NF33155F0A0000348D061E
#gateway_public_key = PublicKeyTest.key
#jw_hospital = 350211A1004
#jw_licence = 1GPM6UKII0NF33155F0A0000348D061E
#platform.public.key=jwkey/ZOE.PLATFORM_PublicKey.SM2_V2.key
#company.public.key=jwkey/sqsyy_PublicKey.SM2_V2.key
#company.private.key=jwkey/sqsyy_PrivateKey.SM2_V2.key
#authorization.code=1ERSRATH80010100007F0000E43BC68D
###prod
gateway_url = http://192.168.120.103:6021/
gateway_licence = 1E72F34S509433155F0A0000C0FAAB96
gateway_public_key = PublicGov.key
jw_hospital = 350211A1049
jw_licence = 1E72F34S509433155F0A0000C0FAAB96
platform.public.key=jwkey/ZOE.PLATFORM_PublicKey.SM2_V2.key
company.public.key=jwkey/350211A1049_PublicKey.SM2_V2.key
company.private.key=jwkey/350211A1049_PrivateKey.SM2_V2.key
authorization.code=1E72F34S509433155F0A0000C0FAAB96
# 基卫对接服务地址
jw_url = http://59.61.92.90:8072/wlyy_service
# EHR档案服务地址
ehr_used = true
ehr_services = http://localhost:9009/api/v1.0/
ehr_services_base = http://localhost:10220/api/v1.0/
# 微信图文消息URL
doctor_qrcode_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2fssgg%2fhtml%2fdoctor-homepage-new.html&amp;response_type=code&amp;scope=snsapi_base&amp;state={doctorCode}#wechat_redirect
doctor_hos_qrcode_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2fqygl%2fhtml%2fsearch-doctor.html&amp;response_type=code&amp;scope=snsapi_base&amp;state={hospital}#wechat_redirect
doctor_subscribe_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2fqygl%2fhtml%2fsigning-welcome.html&amp;response_type=code&amp;scope=snsapi_base&amp;state=code#wechat_redirect
doctor_town_qrcode_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2fqygl%2fhtml%2fsearch-community.html&amp;response_type=code&amp;scope=snsapi_base&amp;state={town}#wechat_redirect
doctor_qrcode_pic_url={server}/images/familycontract.png
doctor_invitel_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&redirect_uri={server}%2fwx%2fhtml%2fssgg%2fhtml%2fdoctor-homepage-new.html&response_type=code&scope=snsapi_base&state={doctorCode}__{invilogcode}__{currentPatient}__{currentZH}__{currentName}#wechat_redirect
#就诊记录
patient_visit_url = https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2fjkda%2fhtml%2fjiuzhenjilu.html&amp;response_type=code&amp;scope=snsapi_base&amp;state=STATE#wechat_redirect
#检查检验
patient_inspect_url =https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2fjkda%2fhtml%2fjianchajianyan.html&amp;response_type=code&amp;scope=snsapi_base&amp;state=STATE#wechat_redirect
#社区体检
patient_examination_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2fjkda%2fhtml%2fjiankangtijian.html&amp;response_type=code&amp;scope=snsapi_base&amp;state=STATE#wechat_redirect
#处方记录
patient_prescription_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2fprescription%2fhtml%2fprescription_records.html&amp;response_type=code&amp;scope=snsapi_base&amp;state=STATE#wechat_redirect
#居民取药码
patient_QRCode_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2fprescription%2fhtml%2fmy-medicine-code.html&amp;response_type=code&amp;scope=snsapi_base&amp;state=STATE#wechat_redirect
#居民产检计划
patient_prenata_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2ffybj%2fhtml%2fyunjianjihua.html&amp;response_type=code&amp;scope=snsapi_base&amp;state=STATE#wechat_redirect
#居民免疫计划
patient_immune_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2ffybj%2fhtml%2fmianyijihua.html&amp;response_type=code&amp;scope=snsapi_base&amp;state=STATE#wechat_redirect
#互联网医院医生二维码图片
hlwyy_doctor_qrcode_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2fhome%2fhtml%2fims-forward.html&amp;response_type=code&amp;scope=snsapi_base&amp;state={doctorCode}#wechat_redirect
#互联网医院图文图片
hlwyy_doctor_pic_url={server}/images/hlwyyDoctor.png
#居民wifi图片地址
patient_wifi_pic_url = {server}/images/wifi.png
#居民抽奖图片地址
patient_draw_pic_url = {server}/images/banner02.png
#专科医生签约图片地址
specialist_sign_url = {server}/images/SpBanner.png
#专科医生签约图片地址
doctor_activity_url = {server}/images/activity.png
#通用活动图片地址
currency_url = {server}/images/currency.png
#居民wifi链接
patient_wifi_url =http://freewifi.mobcb.com/Portal/Wx/login
#就诊记录
patient_visit_pic ={server}/images/visit.png
#检查检验
patient_inspect_pic ={server}/images/inspect.png
#社区体检
patient_examination_pic={server}/images/examination.png
#处方记录
patient_prescription_pic={server}/images/prescriptionRecords.png
#居民取药码
patient_QRCode_pic={server}/images/patientQRCode.png
#居民产检计划
patient_prenata_pic={server}/images/patientPrenata.png
#居民免疫计划
patient_immune_pic={server}/images/patientImmune.png
patient_operatinginstrutions_pic_url={server}/images/operatinginstructions.png
patient_booking_pic_url={server}/images/booking.png
patient_device_pic_url={server}/images/device.png
patient_family_pic_url={server}/images/myfamily.png
patient_sign_again_pic_url={server}/images/renew.png
patient_consult_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2fintroduction%2fhtml%2fyszx.html&amp;response_type=code&amp;scope=snsapi_base&amp;state=code#wechat_redirect
patient_booking_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2fintroduction%2fhtml%2fyygh.html&amp;response_type=code&amp;scope=snsapi_base&amp;state=code#wechat_redirect
patient_device_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2fintroduction%2fhtml%2ftzsb.html&amp;response_type=code&amp;scope=snsapi_base&amp;state=code#wechat_redirect
patient_family_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2fintroduction%2fhtml%2ffamily.html&amp;response_type=code&amp;scope=snsapi_base&amp;state=code#wechat_redirect
patient_sign_again_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2fxuqian%2fhtml%2finformation.html&amp;response_type=code&amp;scope=snsapi_base&amp;state=code#wechat_redirect
patient_sign_url=https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&amp;redirect_uri={server}%2fwx%2fhtml%2fintroduction%2fhtml%2fjyqy.html&amp;response_type=code&amp;scope=snsapi_base&amp;state=code#wechat_redirect
# SMS短信配置
yihu_sms_url=https://smsapi.ums86.com:9600/sms/Api/Send.do
yihu_sms_code=229336
yihu_sms_name=jkzldxjr
yihu_sms_password=jkzldxjrpwd123
yihu_guahao_url=http://ssotest.yihu.cn/OpenPlatform/cgiBin/1.0/
yihu_guahao_appid=sanshi
yihu_guahao_secret=sanshi
# 上传文件配置
upload_temp_path=/var/local/temp
image_path=/var/local/upload/images
voice_path=/var/local/upload/voice
chat_file_path=/var/local/upload/chat
#系统管理员token
admin_uid=admin
admin_token=0a5c5258-8863-4b07-a3f9-88c768528ab4
# 签约到期JOB触发时间,每年7月1日零点
sign_end_job_trigger= 0 0 0 1 7 ?
# 续签提醒JOB触发时间 (每7天一次)
sign_again_job_trigger=59 59 23 7/7 * ?
# 续签提醒JOB停止时间
sign_again_job_end=2017-10-1 00:00:00
# 产检提醒JOB触发时间 (每天6点一次)
prenatal_inspector_job_trigger=0 0 6 * * ?
evaluate_score_job = 0 0 */2 * * ?
#续方支付到期,每天0点触发
prescription_pay_overdue_job = 0 0 0 * * ?
#统一支付平台支付成功后页面跳转地址
return_url={server}/wx/html/qygl/html/pay_result.html
#统一支付平台支付接口地址
bindCardType=onepay.sicard.bind.info
chargeType=onepay.trade.medical.charge
chargeQueryType=onepay.trade.medical.charge.query
createSicardType=onepay.sicard.createurl
receiveNotify=wlyy.onepay.receiveNotify
returnUrl=wlyy.onepay.returnUrl
#长处方
#redist订阅消息主题
redisMessage=redisMessage
#是否需要药师审方
pharmacistExaminationType=false
#集美宣教-健康专栏-刊物详情
wlyy_publication_url={server}/wx/html/propaganda_jm/html/weekly-detail-list.html?publicationId=