Quellcode durchsuchen

设备数据接收

liubing vor 3 Jahren
Ursprung
Commit
fc3be489bd

+ 71 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceInfo.java

@ -0,0 +1,71 @@
package com.yihu.jw.entity.care.device;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.sql.Timestamp;
import java.util.Date;
/**
 * Created by lingfeng on 2016/8/19.
 */
@Entity
@Table(name = "wlyy_devices_data_record")
public class DeviceInfo extends IdEntity {
    private String deviceData;
    private String deviceType;
    private Timestamp pushDate;
    private String status;
    // Constructors
    /** default constructor */
    public DeviceInfo() {
    }
    /** full constructor */
    public DeviceInfo(String deviceData, String deviceType,
                      Timestamp pushDate, String status) {
        this.deviceData = deviceData;
        this.deviceType = deviceType;
        this.pushDate = pushDate;
        this.status = status;
    }
    @Column(name = "device_data")
    public String getDeviceData() {
        return deviceData;
    }
    public void setDeviceData(String deviceData) {
        this.deviceData = deviceData;
    }
    @Column(name = "device_type")
    public String getDeviceType() {
        return deviceType;
    }
    public void setDeviceType(String deviceType) {
        this.deviceType = deviceType;
    }
    @Column(name = "push_date")
    public Date getPushDate() {
        return pushDate;
    }
    public void setPushDate(Timestamp pushDate) {
        this.pushDate = pushDate;
    }
    @Column(name = "status")
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
}

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

@ -723,6 +723,40 @@ public class DateUtil {
        return str;
    }
    /**
     * 日期比较大小
     * @param s1
     * @param s2
     * @return
     */
    public static long compareDate(java.util.Date s1, java.util.Date s2) {
        try {
            return compareDate(YYYY_MM_DD, dateToStrShort(s1), dateToStrShort(s2));
        } catch (Exception e) {
            return -1;
        }
    }
    /**
     * 字符串日期比较大小
     * @param format
     * @param s1
     * @param s2
     * @return
     */
    public static long compareDate(String format, String s1, String s2) {
        SimpleDateFormat f = new SimpleDateFormat(format);
        try {
            return f.parse(s1).getTime() - f.parse(s2).getTime();
        } catch (Exception e) {
            return -1;
        }
    }
    /**
     * 两个时间之间的天数
     *
@ -1012,6 +1046,49 @@ public class DateUtil {
        return nousedate;
    }
    /**
     *时间字符串转为 时间戳
     * @param str
     * @param format
     * @return
     */
    public static Timestamp toTimestamp(String str, String format) {
        if (str == null) {
            return null;
        }
        try {
            return new Timestamp(stringToDate(str, format).getTime());
        } catch (Exception e) {
            return null;
        }
    }
    /**
     *时间字符串转为 时间戳
     * @param str
     * @param
     * @return
     */
    public static Timestamp toTimestamp(String str) {
        if (str == null) {
            return null;
        }
        try {
            return Timestamp.valueOf(str.trim());
        } catch (IllegalArgumentException iae) {
            return null;
        }
    }
    public static long compareDateTime(java.util.Date s1, java.util.Date s2) {
        return s1.getTime() - s2.getTime();
    }
    /**
     *  日期加减天数
     * @param date 时间
@ -1268,4 +1345,15 @@ public class DateUtil {
        return lDate;
    }
    public static String getDateFromDateTime(String dateTime) {
        if (dateTime == null || dateTime.length() < YYYY_MM_DD.length()) {
            return null;
        }
        return dateTime.substring(0, 10);
    }
}

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

@ -5,6 +5,8 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * @author yeshijie on 2018/1/10.
 */
@ -13,4 +15,9 @@ public interface DeviceDetailDao extends PagingAndSortingRepository<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);
}

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

@ -0,0 +1,9 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.DeviceInfo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface DeviceInfoDao extends CrudRepository<DeviceInfo, Long> {
}

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

@ -67,4 +67,11 @@ public interface DevicePatientHealthIndexDao
	@Query("select count(a) from DevicePatientHealthIndex a where a.recordDate >= ?1 and a.recordDate <= ?2 and a.type in (1,2) and a.status = ?3 and a.del = '1' and user = ?4")
	int getCountByTimeAndStatus(Date start, Date end, int status, String patientCode);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.deviceSn = ?2 and a.value1 = ?3 and a.type = ?4 and a.recordDate >= ?5 and a.recordDate<=?6 and a.del = '1' ")
	List<DevicePatientHealthIndex> findByTypeInHalfMinute(String patient, String deviceSn, String value1, Integer type, Date minDate,Date maxDate);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.deviceSn = ?2 and a.value1 = ?3 and a.value2=?7 and a.value3=?8 and a.type = ?4 and a.recordDate >= ?5 and a.recordDate<=?6 and a.del = '1' ")
	List<DevicePatientHealthIndex> findByTypeInHalfMinuteAllValue(String patient, String deviceSn, String value1, Integer type, Date minDate,Date maxDate,String value2,String value3);
}

+ 60 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/Result.java

@ -0,0 +1,60 @@
package com.yihu.jw.care.endpoint;
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;
    }
}

+ 2 - 2
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doorCoach/DoctorDoorCoachOrderService.java

@ -299,8 +299,8 @@ public class DoctorDoorCoachOrderService {
            String statusName = "";
            switch (statustemp){
                case -1:statusName="已取消";break;
                case 1:statusName="待服务";break;
                case 2:statusName="待服务";break;
                case 1:statusName="待接单";break;
                case 2:statusName="待接单";break;
                case 3:statusName="待服务";break;
                case 4:statusName="待服务";break;
                case 5:statusName="待服务";break;

+ 1 - 1
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doorCoach/PatientDoorCoachOrderService.java

@ -1379,7 +1379,7 @@ public class PatientDoorCoachOrderService extends BaseJpaService<BaseDoorCoachOr
                case 2:statusName="待接单";break;
                case 3:statusName="待服务";break;
                case 4:statusName="待服务";break;
                case 5:statusName="已完成";break;
                case 5:statusName="待服务";break;
                case 6:statusName="已完成";break;
            }

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

@ -5,6 +5,8 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * @author yeshijie on 2018/1/10.
 */
@ -13,4 +15,9 @@ public interface DeviceDetailDao extends PagingAndSortingRepository<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);
}

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

@ -0,0 +1,9 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.DeviceInfo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface DeviceInfoDao extends CrudRepository<DeviceInfo, Long> {
}

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

@ -67,4 +67,11 @@ public interface DevicePatientHealthIndexDao
	@Query("select count(a) from DevicePatientHealthIndex a where a.recordDate >= ?1 and a.recordDate <= ?2 and a.type in (1,2) and a.status = ?3 and a.del = '1' and user = ?4")
	int getCountByTimeAndStatus(Date start, Date end, int status, String patientCode);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.deviceSn = ?2 and a.value1 = ?3 and a.type = ?4 and a.recordDate >= ?5 and a.recordDate<=?6 and a.del = '1' ")
	List<DevicePatientHealthIndex> findByTypeInHalfMinute(String patient, String deviceSn, String value1, Integer type, Date minDate,Date maxDate);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.deviceSn = ?2 and a.value1 = ?3 and a.value2=?7 and a.value3=?8 and a.type = ?4 and a.recordDate >= ?5 and a.recordDate<=?6 and a.del = '1' ")
	List<DevicePatientHealthIndex> findByTypeInHalfMinuteAllValue(String patient, String deviceSn, String value1, Integer type, Date minDate,Date maxDate,String value2,String value3);
}

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

@ -24,7 +24,7 @@ import java.util.Map;
 */
@RestController
@RequestMapping("/device")
@Api(value = "设备相关服务", description = "设备相关服务")
@Api(value = "爱牵挂设备相关服务", description = "设备相关服务")
public class DeviceController {
    private static Logger logger = LoggerFactory.getLogger(DeviceController.class);

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

@ -0,0 +1,52 @@
package com.yihu.jw.care.endpoint;
import com.yihu.jw.care.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;
/**
 * 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 = "/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)
    {
        try{
            logger.info("typeId="+typeId+";data="+data);
            return deviceUploadService.uploadDevicesData(data);
        }
        catch (Exception ex)
        {
            return Result.error("Device data incoming failure!"+ex.getMessage());
        }
    }
}

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

@ -0,0 +1,60 @@
package com.yihu.jw.care.endpoint;
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;
    }
}

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

@ -0,0 +1,348 @@
package com.yihu.jw.care.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.dao.device.DeviceDetailDao;
import com.yihu.jw.care.dao.device.DeviceInfoDao;
import com.yihu.jw.care.dao.device.DevicePatientHealthIndexDao;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.endpoint.Result;
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.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.stereotype.Service;
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;
    public Result uploadDevicesData(String dataJson) {
        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血压
            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!");
            }
        } 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);
            }
        }
        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);
            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<>();
       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;
        }
    }
}