LAPTOP-KB9HII50\70708 il y a 1 an
Parent
commit
0f15a81dc0

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

@ -0,0 +1,55 @@
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
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("设备数据接收接口(标准协议)")
    @RequestMapping(value = "/open/excelControl/upload", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    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{
            logger.info("typeId="+typeId+";data="+data);
            return deviceUploadService.uploadDevicesData(data,request);
        }
        catch (Exception ex)
        {
            return Result.error("Device data incoming failure!"+ex.getMessage());
        }
    }
}

+ 3 - 15
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/PatientDeviceController.java

@ -168,11 +168,11 @@ public class PatientDeviceController extends BaseController {
    }
    /**
     * 设备保存接口  ---增加血糖时间段保存 Reece v1.3.3
     * 设备保存接口  ---增加血糖时间段保存 Reece v1.3.3 06
     */
    @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\"}")
    public String saveDevice(@ApiParam(name = "json", value = "设备数据json", defaultValue = "{\"deviceId\": \"3\",\"deviceName\": \"血压计-优瑞恩\",\"deviceSn\": \"06B52305030267\",\"categoryCode\": \"1\",\"userType\": \"-1\"}")
                             @RequestParam(value = "json", required = true) String json) {
        try {
            DevicePatientDevice device = objectMapper.readValue(json, DevicePatientDevice.class);
@ -203,18 +203,6 @@ public class PatientDeviceController extends BaseController {
            //修改设备表中{"1":"0", "2":"0"}的绑定次数 和其他绑定信息
            deviceDetailService.updateAfterBinding(device,new Date(),flag);
            String flagStr ="";
            if ("1".equals(device.getCategoryCode())){
                flagStr="GLU_BIND";
            }else if ("2".equals(device.getCategoryCode())){
                flagStr="BP_BIND";
            }
            //活动的活跃度
            if (flag){
                com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
                jsonObject.put("patientId",patient.getId());
                jsonObject.put("taskCode",flagStr);
            }
            if(!"11".equals(device.getCategoryCode())){
                try {
                    String openId = patient.getOpenid();
@ -246,7 +234,7 @@ public class PatientDeviceController extends BaseController {
            return write(-1,se.getMessage());
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
            return error(-1, "设备保存失败");
        }
    }

+ 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;
    }
}

+ 34 - 11
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceDetailService.java

@ -11,14 +11,20 @@ import com.yihu.jw.entity.base.patient.BasePatientDO;
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.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@ -42,7 +48,10 @@ public class DeviceDetailService {
	private PatientDeviceDao patientDeviceDao;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private HttpClientUtil httpClientUtil;
	@Autowired
	private WlyyHospitalSysDictDao hospitalSysDictDao;
	/**
	 * 绑定时更新设备表中的信息
@ -54,8 +63,6 @@ public class DeviceDetailService {
	@Transactional
	public void updateAfterBinding(DevicePatientDevice patientDevice, Date grantTime, boolean isFirst)throws Exception{
		DeviceDetail deviceDetail = deviceDetailDao.findBySn(patientDevice.getDeviceSn());
		int bind = deviceDetail.getIsBinding();
//		SignFamily signFamily = signFamilyDao.findByIdcard(patientDevice.getUserIdcard());
		long adminTeam=0L;
		String hospital = "";
		String isFirstBind = "";
@ -66,19 +73,12 @@ public class DeviceDetailService {
		if ("2".equals(patientDevice.getUserType())){
			keyType="2";
		}
//		if (signFamily!=null){
//			adminTeam = signFamily.getAdminTeamId();
//			hospital = signFamily.getHospital();
//			hospitalName = signFamily.getHospitalName();
//			doctorCode = signFamily.getDoctor();
//			doctorName = signFamily.getDoctorName();
//		}
		//设备表没有数据则插入一条数据
		if (deviceDetail==null){
			insertDevice(patientDevice,String.valueOf(adminTeam),hospitalName,hospital,"",doctorCode,doctorName,1);
			deviceDetail = deviceDetailDao.findBySn(patientDevice.getDeviceSn());
		}
		int bind = deviceDetail.getIsBinding();
		isFirstBind = deviceDetail.getBindingCount();
		if (StringUtils.isNotBlank(isFirstBind)){
			JSONObject jsonObject = JSON.parseObject(isFirstBind);
@ -186,4 +186,27 @@ public class DeviceDetailService {
	public DeviceDetail findByDeviceSn(String deviceSn){
		return deviceDetailDao.findBySn(deviceSn);
	}
	/**
	 * 注册设备,通过iot项目进行数据推送
	 * @return
	 */
	public void registerToWlyy(DevicePatientDevice device){
		//判断设备类型
		Device deviceDO = deviceDao.findById(device.getDeviceId()).orElse(null);
		if (StringUtils.isNotBlank(deviceDO.getNeedRegister())){
			// 设备注册至iot后 通过iot将设备数据转发
//			String url = "http://www.cityihealth.com:43210/deviceManage/register";
			WlyyHospitalSysDictDO dictDO1 = hospitalSysDictDao.findOneByDictNameAndDictCode("registerToWlyy","pushAddress");
			WlyyHospitalSysDictDO dictDO2 = hospitalSysDictDao.findOneByDictNameAndDictCode("registerToWlyy","url");
			String pushAddress = dictDO1.getDictValue();
			String url = dictDO2.getDictValue();
			List<NameValuePair> params = new ArrayList<>();
			params.add(new BasicNameValuePair("deviceSN", device.getDeviceSn()));
			params.add(new BasicNameValuePair("pushAddress", pushAddress));
			String response = httpClientUtil.post(url, params,"UTF-8");
			System.out.println("注册结果:"+response);
		}
	}
}

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

@ -0,0 +1,454 @@
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.DeviceInfoDao;
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.DeviceInfo;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.module.health.controller.Result;
import com.yihu.jw.hospital.utils.CountDistance;
import com.yihu.jw.hospital.utils.DeviceDataPushLogUtil;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.GpsUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.healthIndex.HealthIndexUtil;
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.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 DeviceInfoDao deviceInfoDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private DevicePatientHealthIndexDao patientHealthIndexDao;
    @Autowired
    private SystemMessageDao systemMessageDao;
    @Autowired
    private HealthIndexUtil healthIndexUtil;
    @Autowired
    private ImUtil imUtil;
    @Autowired
    private CountDistance countDistance;
    @Autowired
    private GpsUtil gpsUtil;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DeviceDataPushLogUtil dataPushLogUtil;
    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);
            //保存消息
            BasePatientDO patientDO = patientDao.findById(result.getUser()).orElse(null);
            if (null != patientDO){
                SystemMessageDO messageDO = new SystemMessageDO();
                String typeName = null;
                switch (type){
                    case "1":
                        typeName = "您有新的血糖测量记录:血糖浓度:"+result.getValue1()+"mmol/L";
                        break;
                    case "2":
                        typeName = "您有新的血压测量记录:收缩压:"+result.getValue1()+"mmHg,舒张压:"
                                +result.getValue2()+"mmHg,脉搏:"+result.getValue3()+"次/min";
                        break;
                }
                if (StringUtils.isNotBlank(typeName)){
/*                    String adminSql = "SELECT py_code FROM wlyy_hospital_sys_dict WHERE dict_name = 'pushOnOff' AND dict_code ='"+6+"' ";
                    String onOff= jdbcTemplate.queryForObject(adminSql,String.class);
                    Boolean kg = Boolean.parseBoolean(onOff);
                    String patientOnOffSql = "select on_off from base_patient_pad_pushonoff where patient = '" + patientDO.getId() + "' and type = 3";
                    Integer integer = jdbcTemplate.queryForObject(patientOnOffSql,Integer.class);
                    if (kg&&integer==0?false:true) {
                        messageDO.setTitle(typeName);
                        messageDO.setType("42");//42体征设备测量
                        messageDO.setSender("system");
                        messageDO.setSenderName("养护助手");
                        messageDO.setRelationCode(result.getId() + "");
                        messageDO.setReceiver(patientDO.getId());
                        messageDO.setReceiverName(patientDO.getName());
//                        messageDO.setUserType(1);
                        messageDO.setOver("1");
                        messageDO.setCode(type);//与体征类型对应
                        JSONArray errorIndex = healthIndexUtil.verifyHealthIndex(Integer.parseInt(type), result.getValue1(), result.getValue2(),
                                result.getValue3(), result.getValue4(), result.getValue5(), result.getValue6(),
                                result.getValue7());
                        messageDO.setData(JSON.toJSONString(errorIndex, SerializerFeature.WriteNullStringAsEmpty));
                        messageDO.setDel("1");
                        messageDO.setCreateTime(new Date());
                        //推送socket
                        com.alibaba.fastjson.JSONObject message = new com.alibaba.fastjson.JSONObject();
                        message.put("title", typeName);
                        message.put("code", messageDO.getCode());
                        message.put("content", messageDO.getData());
                        message.put("relation_code", messageDO.getRelationCode());
                        message.put("content_type", 42);
                        message.put("content_notice", "");
//                        message.put("audioUrl", url);
                        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") + "、";
                            }
                        }
                        if (StringUtils.isNotBlank(content_notice)) {
                            content_notice = content_notice.substring(0, content_notice.length() - 1);
                            message.put("content_notice", "您的key1过高,请注意饮食,尽量食用少油少盐食物".replace("key1", content_notice));
                            messageDO.setContent("您的key1过高,请注意饮食,尽量食用少油少盐食物".replace("key1", content_notice));
                            dataPushLogUtil.updContactStatus(deviceSn, 1, true);
                        } else {
                            dataPushLogUtil.updContactStatus(deviceSn, 1, false);
                        }
                        patientHealthIndexDao.save(result);
                        systemMessageDao.save(messageDO);
                        imUtil.sendPatientSystemMessage(messageDO.getReceiver(), JSON.toJSONString(message, SerializerFeature.WriteMapNullValue));
                    }*/
                }
            }
        } 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).orElse(null);
            if(patient!=null){
                obj.setName(patient.getName());
            }
            if(deviceDetail!=null){
                obj.setHospital(deviceDetail.getGrantOrgCode());
                obj.setHospitalName(deviceDetail.getOrgName());
            }
            obj = patientHealthIndexDao.save(obj);
//            if ("1".equals(type)||"2".equals(type)){
//                dataPushLogUtil.savePatientMonitorData(deviceSn,Integer.parseInt(type),JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue),obj.getId()+"");
//            }
            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<>();
       if (type==1){
           list =  patientHealthIndexDao.findByTypeInHalfMinute(user,deviceSn,value1,type,timeMin,timeMax);
       }else if (type==2){
           list = patientHealthIndexDao.findByTypeInHalfMinuteAllValue(user,deviceSn,value1,type,timeMin,timeMax,value2,value3);
       }
       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;
        }
    }
}

+ 10 - 6
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/PatientDeviceService.java

@ -58,6 +58,8 @@ public class PatientDeviceService  {
    private PatientDeviceLogDao patientDeviceLogDao;
    @Autowired
    private WxMessageUtil wxMessageUtil;
    @Autowired
    private DeviceDetailService deviceDetailService;
    /**
@ -109,6 +111,7 @@ public class PatientDeviceService  {
            if (device != null && !device.getId().equals(patientDevice.getId())) {
                throw new ServiceException("sn码" + sn + "已被使用!");
            }
            deviceDetailService.registerToWlyy(patientDevice);
        }
        patientDevice.setCzrq(new Date());
        patientDevice.setDel(0);
@ -116,12 +119,13 @@ public class PatientDeviceService  {
        BasePatientDO patient = patientDao.findById(patientDevice.getUser()).orElse(null);
        patientDevice.setUserIdcard(patient.getIdcard());
        if(checkDeviceSn(sn)){
            savePatientDevice(patientDevice);
        }else {
            String message = "设备不存在";
            throw new ServiceException(message);
        }
        savePatientDevice(patientDevice);
//        if(checkDeviceSn(sn)){
//            savePatientDevice(patientDevice);
//        }else {
//            String message = "设备不存在";
//            throw new ServiceException(message);
//        }
        return true;
    }

+ 85 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/CountDistance.java

@ -0,0 +1,85 @@
package com.yihu.jw.hospital.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
@Component
public class CountDistance {
    private static double EARTH_RADIUS = 6378.137;// 6378.137赤道半径6378137
    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }
    /**
     * 通过经纬度计算两点之间的距离(单位:千米)
     * @param latone
     * @param lngone
     * @param lattwo
     * @param lngtwo
     * @return
     */
    public double getDistance(double latone, double lngone, double lattwo, double lngtwo) {
        double radlatone = rad(latone);
        double radlattwo = rad(lattwo);
        double a = radlatone - radlattwo;
        double b = rad(lngone) - rad(lngtwo);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radlatone) * Math.cos(radlattwo)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000d) / 10000d;
        s = s;
        return s;
    }
    /**
     * 判断坐标是否在多边形区域内
     * @param pointLon
     * @param pointLat
     * @param rangePositions 多边形坐标 [{"lon":118.19302036660137,"lat":24.494515439791996},{"lon":118.19401849369201,"lat":24.49606682685256}]
     * @return
     */
    public boolean isInPolygon(double pointLon, double pointLat, JSONArray rangePositions) {
        // 将要判断的横纵坐标组成一个点
        double[] lon =  rangePositions.stream().mapToDouble(item->((JSONObject)item).getDouble("lon")).toArray();
        double[] lat =  rangePositions.stream().mapToDouble(item->((JSONObject)item).getDouble("lat")).toArray();;
        Point2D.Double point = new Point2D.Double(pointLon, pointLat);
        // 将区域各顶点的横纵坐标放到一个点集合里面
        List<Point2D.Double> pointList = new ArrayList<Point2D.Double>();
        double polygonPoint_x = 0.0, polygonPoint_y = 0.0;
        for (int i = 0; i < lon.length; i++) {
            polygonPoint_x = lon[i];
            polygonPoint_y = lat[i];
            Point2D.Double polygonPoint = new Point2D.Double(polygonPoint_x, polygonPoint_y);
            pointList.add(polygonPoint);
        }
        return check(point, pointList);
    }
    private static boolean check(Point2D.Double point, List<Point2D.Double> polygon) {
        java.awt.geom.GeneralPath peneralPath = new java.awt.geom.GeneralPath();
        Point2D.Double first = polygon.get(0);
        // 通过移动到指定坐标(以双精度指定),将一个点添加到路径中
        peneralPath.moveTo(first.x, first.y);
        polygon.remove(0);
        for (Point2D.Double d : polygon) {
            // 通过绘制一条从当前坐标到新指定坐标(以双精度指定)的直线,将一个点添加到路径中。
            peneralPath.lineTo(d.x, d.y);
        }
        // 将几何多边形封闭
        peneralPath.lineTo(first.x, first.y);
        peneralPath.closePath();
        // 测试指定的 Point2D 是否在 Shape 的边界内。
        return peneralPath.contains(point);
    }
}

+ 110 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/DeviceDataPushLogUtil.java

@ -0,0 +1,110 @@
package com.yihu.jw.hospital.utils;
import com.yihu.jw.device.dao.DeviceDataPushLogDao;
import com.yihu.jw.device.dao.DeviceDetailDao;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DeviceDataPushLog;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * Created by Bing on 2021/9/2.
 * 设备数据推送日志保存
 */
@Component
public class DeviceDataPushLogUtil {
    @Autowired
    private DeviceDataPushLogDao deviceDataPushLogDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private DeviceLostMessageUtil deviceLostMessageUtil;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @Autowired
    private SystemMessageDao systemMessageDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public void savePushLog(String sn,String data,String apiName){
        try {
            DeviceDataPushLog pushLog = new DeviceDataPushLog();
            pushLog.setDeviceSn(sn);
            pushLog.setData(data);
            pushLog.setApiName(apiName);
            pushLog.setCreateTime(new Date());
            List<DevicePatientDevice> devices= patientDeviceDao.findByDeviceSn(sn);
            if (devices.size()>0){
                DevicePatientDevice tmp = devices.get(0);
                BasePatientDO patientDO = patientDao.findById(tmp.getUser()).orElse(null);
                if (null!=patientDO){
                    pushLog.setPatient(tmp.getUser());
                    pushLog.setPatientName(patientDO.getName());
                }
                pushLog.setDeviceName(tmp.getDeviceName());
                pushLog.setDeviceCategory(tmp.getCategoryCode());
            }
            deviceDataPushLogDao.save(pushLog);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 更新在线状态 及次数
     * @param sn
     * @param status
     * @param flag 状态 true 异常 false 正常 null其他
     */
    @Transactional
    public void updContactStatus(String sn,Integer status,Boolean flag){
        DeviceDetail deviceDetail = deviceDetailDao.findBySn(sn);
        if(deviceDetail!=null){
            deviceDetail.setContactStatus(status);
            if(0==status){
                List<String> sns =  new ArrayList<String>();
                sns.add(sn);
                deviceLostMessageUtil.deviceLostMessage(sns);
            }
            else if(1==status){
                //设备在线清除原有的离线消息
                List<String> sns = new ArrayList<String>();
                sns.add(sn);
                systemMessageDao.delMessageByRelationCode(sns);
            }
            deviceDetail.setContactStatusTime(new Date());
            if(deviceDetail.getCollectNum()==null){
                deviceDetail.setCollectNum(0L);
            }
            if(deviceDetail.getAbnormalNum()==null){
                deviceDetail.setAbnormalNum(0L);
            }
            if(flag!=null){
                deviceDetail.setCollectNum(deviceDetail.getCollectNum()+1L);
                if(flag){
                    deviceDetail.setAbnormalNum(deviceDetail.getAbnormalNum()+1L);
                }
            }
            deviceDetailDao.save(deviceDetail);
        }
    }
}

+ 116 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/DeviceLostMessageUtil.java

@ -0,0 +1,116 @@
package com.yihu.jw.hospital.utils;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * Created by Bing on 2021/9/13.
 */
@Component
public class DeviceLostMessageUtil {
    @Autowired
    private SystemMessageDao systemMessageDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BasePatientDao patientDao;
    /**
     * 设备离线通知
     * @param devices
     */
    public void deviceLostMessage(List<String> devices){
        List<SystemMessageDO> messageDOS = new ArrayList<>();
        for (String id:devices){
            List<SystemMessageDO> sendMessageBefore = systemMessageDao.queryByRelationCodeAndTypeIn(id,new String[]{"43"});
            if (sendMessageBefore.size()>0){//删除之前的离线消息
                systemMessageDao.deleteAll(sendMessageBefore);
            }
            List<DevicePatientDevice> pds =  patientDeviceDao.findByDeviceSn(id);
            if (pds.size()>0){
                DevicePatientDevice deviceDO = pds.get(0);
                String sql = "SELECT DISTINCT d.id,d.name from base_service_package_sign_record sr,base_service_package_record r,base_team_member m,base_doctor d  " +
                        "               WHERE sr.status=1 and m.team_code = r.team_code and sr.id=r.sign_id and m.doctor_code = d.id " +
                        "               and m.del = '1' and sr.patient = '"+deviceDO.getUser()+"' " ;
                List<Map<String,Object>> doctors = jdbcTemplate.queryForList(sql);
                // 家属
                sql = " select  t2.id,t2.name from  base_patient_family_member t1,  base_patient t2 where  " +
                        "t2.id in (select family_member from base_patient_family_member where patient = '"+deviceDO.getUser()+"' )  " +
                        " and t1.patient = '"+deviceDO.getUser()+"'  and t1.family_member = t2.id  " +
                        " and t2.archive_type=3 GROUP BY t2.id " ;
                List<Map<String,Object>> relatives = jdbcTemplate.queryForList(sql);
                doctors.addAll(relatives);
                String deviceName="";
                for (Map<String,Object> docTmp:doctors){
                    switch (deviceDO.getCategoryCode()){
                        case "1":
                            deviceName="血糖仪离线";
                            break;
                        case "2":
                            deviceName="血压计离线";
                            break;
                        case "4":
                            deviceName="智能手表离线";
                            break;
                        case "7":
                            deviceName="居家安全报警器离线";
                            break;
                        case "12":
                            deviceName="监控器离线";
                            break;
                        case "13":
                            deviceName="睡眠带离线";
                            break;
                        case "14":
                            deviceName="气感报警器离线";
                            break;
                        case "15":
                            deviceName="烟感报警器离线";
                            break;
                        case "16":
                            deviceName="智能拐杖离线";
                            break;
                        case "17":
                            deviceName="随身WiFi离线";
                            break;
                    }
                    BasePatientDO patientDO = patientDao.findById(deviceDO.getUser()).orElse(null);
                    SystemMessageDO messageDO = new SystemMessageDO();
                    messageDO.setTitle("设备离线通知");
                    messageDO.setType("43");
                    messageDO.setIsRead("0");
                    messageDO.setSender(deviceDO.getUser());
                    messageDO.setSenderName(patientDO.getName());
                    messageDO.setRelationCode(id);
                    messageDO.setReceiver(docTmp.get("id").toString());
                    messageDO.setReceiverName(docTmp.get("name").toString());
                    messageDO.setOver("1");
                    messageDO.setData(deviceName);
                    messageDO.setDel("1");
                    messageDO.setCreateTime(new Date());
                    messageDO.setSenderPhoto(patientDO.getPhoto());
                    messageDOS.add(messageDO);
                }
            }
        }
        if (messageDOS.size()>0){
            systemMessageDao.saveAll(messageDOS);
        }
    }
}