Commit f96c1713 by huangjy

feat:第三方api,模型分析V1.0

parent f3e2ab89
......@@ -23,7 +23,11 @@
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.makeit</groupId>
<artifactId>server-service</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
......
package com.makeit.api.controller;
public class AlarmController {
}
package com.makeit.api.controller.external;
import com.makeit.common.dto.BaseIdDTO;
import com.makeit.common.page.PageReqDTO;
import com.makeit.common.page.PageVO;
import com.makeit.common.response.ApiResponseEntity;
import com.makeit.common.response.ApiResponseUtils;
import com.makeit.dto.platform.alarm.PlatAlarmRecordQueryDTO;
import com.makeit.dto.platform.device.PlatDeviceQueryDTO;
import com.makeit.dto.platform.elder.PlatElderQueryDTO;
import com.makeit.global.annotation.AuthIgnore;
import com.makeit.global.aspect.tenant.TenantIdIgnore;
import com.makeit.service.platform.alarm.PlatAlarmRecordService;
import com.makeit.service.platform.device.PlatDeviceService;
import com.makeit.service.platform.elder.PlatElderService;
import com.makeit.vo.platform.alarm.PlatAlarmRecordVO;
import com.makeit.vo.platform.device.PlatDeviceListVO;
import com.makeit.vo.platform.elder.PlatElderListVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.PostConstruct;
/**
* iot对外接口
*/
@RestController
@RequestMapping("/iot/external")
public class IotPlatExternalController {
@Autowired
private PlatElderService platElderService;
@Autowired
private PlatDeviceService platDeviceService;
@Autowired
private PlatAlarmRecordService platAlarmRecordService;
@ApiOperation("长者列表")
@PostMapping("elderPage")
@TenantIdIgnore
@AuthIgnore
public ApiResponseEntity<PageVO<PlatElderListVO>> elderPage(@RequestBody PageReqDTO<PlatElderQueryDTO> page) {
return ApiResponseUtils.success(platElderService.page(page));
}
@ApiOperation("设备列表")
@PostMapping("devicePage")
@TenantIdIgnore
@AuthIgnore
public ApiResponseEntity<PageVO<PlatDeviceListVO>> devicePage(@RequestBody PageReqDTO<PlatDeviceQueryDTO> pageReqDTO) {
return ApiResponseUtils.success(platDeviceService.page(pageReqDTO));
}
@ApiOperation("告警记录列表")
@PostMapping("alarmRecordPage")
@TenantIdIgnore
@AuthIgnore
public ApiResponseEntity<PageVO<PlatAlarmRecordVO>> page(@RequestBody PageReqDTO<PlatAlarmRecordQueryDTO> dto) {
return ApiResponseUtils.success(platAlarmRecordService.page(dto));
}
@ApiOperation("处理告警回调")
@PostMapping("dealAlarm")
@TenantIdIgnore
@AuthIgnore
public ApiResponseEntity<String> dealAlarm(@RequestBody BaseIdDTO dto) {
platAlarmRecordService.dealAlarm(dto);
return ApiResponseUtils.success();
}
}
package com.makeit.module.controller.elder;
import com.makeit.common.response.ApiResponseEntity;
import com.makeit.common.response.ApiResponseUtils;
import com.makeit.global.annotation.AuthIgnore;
import com.makeit.global.aspect.tenant.TenantIdIgnore;
import com.makeit.task.IotSyncTask;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 长者每天睡觉记录 前端控制器
* </p>
*
* @author eugene young
* @since 2023-09-13
*/
@Api(tags = "长者睡觉分析")
@RestController
@RequestMapping("/plat/elderSleep")
public class PlatElderSleepController {
@Autowired
private IotSyncTask iotSyncTask;
@ApiOperation("测试")
@PostMapping("test")
@AuthIgnore
@TenantIdIgnore
public ApiResponseEntity<Void> test() {
iotSyncTask.elderSleepSleepAnalysisTask();
return ApiResponseUtils.success();
}
}
package com.makeit.enums.report;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum DeviceNameEnum {
heart("呼吸心率","呼吸心率雷达"),
fall("跌倒","跌倒检测雷达"),
space("空间","空间人体雷达");
private String prefix;
private String name;
public static String getNameByPrefix(String productName) {
for (DeviceNameEnum value : DeviceNameEnum.values()) {
if ( productName.startsWith(value.prefix)) {
return value.name;
}
}
return "";
}
}
package com.makeit.service.platform.alarm;
import com.baomidou.mybatisplus.extension.service.IService;
import com.makeit.common.dto.BaseIdDTO;
import com.makeit.common.page.PageReqDTO;
import com.makeit.common.page.PageVO;
import com.makeit.dto.platform.alarm.PlatAlarmCheckDTO;
......@@ -57,4 +58,6 @@ public interface PlatAlarmRecordService extends IService<PlatAlarmRecord> {
PlatAlarmRecord convertToPlatAlarmRecord(PlatAlarmCheckDTO platAlarmCheckDTO);
void getElderListByDeviceId(PlatAlarmCheckDTO platAlarmCheckDTO);
void dealAlarm(BaseIdDTO dto);
}
......@@ -3,6 +3,7 @@ package com.makeit.service.platform.alarm.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.makeit.common.dto.BaseIdDTO;
import com.makeit.common.entity.BaseBusEntity;
import com.makeit.common.entity.BaseEntity;
import com.makeit.common.page.PageReqDTO;
......@@ -416,4 +417,14 @@ public class PlatAlarmRecordServiceImpl extends ServiceImpl<PlatAlarmRecordMappe
return sb.toString();
}
@Override
public void dealAlarm(BaseIdDTO dto) {
if (StringUtils.isEmpty(dto.getId())) {
throw new RuntimeException("id为空");
}
PlatAlarmRecord platAlarmRecord = getById(dto.getId());
platAlarmRecord.setStatus(CommonEnum.YES.getValue());
platAlarmRecord.setDealDate(LocalDateTime.now());
updateById(platAlarmRecord);
}
}
......@@ -13,4 +13,5 @@ import com.makeit.entity.platform.elder.PlatElderSleep;
*/
public interface PlatElderSleepService extends IService<PlatElderSleep> {
void elderSleepSleepAnalysisTask();
}
package com.makeit.service.platform.elder.impl;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.makeit.entity.platform.elder.PlatElderSleep;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.makeit.common.entity.BaseEntity;
import com.makeit.entity.platform.elder.*;
import com.makeit.entity.platform.space.PlatRoomBedDevice;
import com.makeit.entity.saas.analysis.*;
import com.makeit.enums.report.BreatheTypeEnum;
import com.makeit.enums.report.ElderSleepType;
import com.makeit.enums.report.HeartRateTypeEnum;
import com.makeit.enums.report.SleepTypeEnum;
import com.makeit.mapper.platform.elder.PlatElderSleepMapper;
import com.makeit.service.platform.elder.PlatElderSleepService;
import com.makeit.module.iot.service.IotProductDeviceService;
import com.makeit.module.iot.vo.DeviceOperationLogEntity;
import com.makeit.module.iot.vo.analysis.*;
import com.makeit.module.iot.vo.breathe.DeviceInfoContentBreathe;
import com.makeit.service.platform.elder.*;
import com.makeit.service.platform.space.PlatRoomBedDeviceService;
import com.makeit.service.saas.*;
import com.makeit.utils.data.convert.JsonUtil;
import com.makeit.utils.data.convert.StreamUtil;
import com.makeit.vo.platform.elder.report.day.PlatSleepRangeVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
/**
* <p>
......@@ -17,4 +51,945 @@ import org.springframework.stereotype.Service;
@Service
public class PlatElderSleepServiceImpl extends ServiceImpl<PlatElderSleepMapper, PlatElderSleep> implements PlatElderSleepService {
private static final DateTimeFormatter DEFAULT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
public static final String DATE_FORMATTER = "yyyy-MM-dd HH:mm";
@Autowired
private SaasSleepAnalysisModelService saasSleepAnalysisModelService;
@Autowired
private SaasSleepEvaluateReportService saasSleepEvaluateReportService;
@Autowired
private SaasElderReportConfigService saasElderReportConfigService;
@Autowired
private SaasSleepEvaluateStandardReportService saasSleepEvaluateStandardReportService;
@Autowired
private SaasDiseaseModelService saasDiseaseModelService;
@Autowired
private SaasDiseaseEvaluateReportService saasDiseaseEvaluateReportService;
@Autowired
private SaasDiseaseReportService saasDiseaseReportService;
@Autowired
private IotProductDeviceService productDeviceService;
@Autowired
private PlatRoomBedDeviceService roomBedDeviceService;
@Autowired
private PlatElderService platElderService;
@Autowired
private PlatElderSleepAnalysisService platElderSleepAnalysisService;
@Autowired
private PlatElderSleepService platElderSleepService;
@Autowired
private PlatElderBreatheAbnormalService platElderBreatheAbnormalService;
@Autowired
private PlatElderBreatheAnalysisService platElderBreatheAnalysisService;
@Override
@Transactional(rollbackFor = Exception.class)
public void elderSleepSleepAnalysisTask() {
List<String> dayHourRangeList = getLastDayHourRange();
String currentDate = DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN);
SaasSleepAnalysisModel analysisModel = saasSleepAnalysisModelService.getOne(new QueryWrapper<SaasSleepAnalysisModel>().lambda()
.orderByDesc(BaseEntity::getCreateBy)
.last("limit 1"));
List<PlatRoomBedDevice> platRoomBedDeviceList = roomBedDeviceService.list(new QueryWrapper<PlatRoomBedDevice>()
.lambda().isNotNull(PlatRoomBedDevice::getBedId));
SaasDiseaseModel saasDiseaseModel = saasDiseaseModelService.getOne(new QueryWrapper<SaasDiseaseModel>().lambda()
.orderByDesc(BaseEntity::getCreateBy)
.last("limit 1"));
Integer actionThreshold = Integer.valueOf(analysisModel.getActionThreshold());
int turnedThreshold = Integer.parseInt(analysisModel.getTurnedThreshold());
int sleepTimeActionThreshold = Integer.parseInt(analysisModel.getSleepTimeActionThreshold());
double sleepTimeActionDuration = Double.parseDouble(analysisModel.getSleepTimeActionDuration());
int riseActionThreshold = Integer.parseInt(analysisModel.getRiseActionThreshold());
int riseActionDuration = Integer.parseInt(analysisModel.getRiseActionDuration());
double riseLeaveThreshold = Double.parseDouble(analysisModel.getRiseLeaveThreshold());
int awakeThreshold = Integer.parseInt(analysisModel.getAwakeThreshold());
int sleepDeepActionThreshold = Integer.parseInt(analysisModel.getSleepDeepActionThreshold());
int sleepDeepActionTimeBegin = Integer.parseInt(analysisModel.getSleepDeepActionTimeBegin());
int sleepDeepBreatheMin = Integer.parseInt(analysisModel.getSleepDeepBreatheMin());
int sleepDeepBreatheMax = Integer.parseInt(analysisModel.getSleepDeepBreatheMax());
// 呼吸率
int breatheThresholdMin = Integer.parseInt(analysisModel.getBreatheThresholdMin());
int breatheThresholdMax = Integer.parseInt(analysisModel.getBreatheThresholdMax());
int breatheDuration = Integer.parseInt(analysisModel.getBreatheDuration());
// 心率
int heartThresholdMin = Integer.parseInt(analysisModel.getHeartThresholdMin());
int heartThresholdMax = Integer.parseInt(analysisModel.getHeartThresholdMax());
int heartDuration = Integer.parseInt(analysisModel.getHeartDuration());
int sleepModerateActionThreshold = Integer.parseInt(analysisModel.getSleepModerateActionThreshold());
int sleepModerateActionTimeBegin = Integer.parseInt(analysisModel.getSleepModerateActionTimeBegin());
for (PlatRoomBedDevice platRoomBedDevice : platRoomBedDeviceList) {
TreeMap<String, AnalysisVO> totalMap = new TreeMap<>();
String bedId = platRoomBedDevice.getBedId();
PlatElder elder = platElderService.getOne(new QueryWrapper<PlatElder>().lambda()
.eq(PlatElder::getBedId, bedId));
if (elder == null) {
continue;
}
String tenantId = elder.getTenantId();
for (String hourRange : dayHourRangeList) {
String[] hourRangeArray = hourRange.split("~");
List<DeviceOperationLogEntity> deviceOperationLogEntities = productDeviceService.getDeviceLogByTimeRange(platRoomBedDevice.getDeviceId(), "reportProperty", 5000, hourRangeArray[0], hourRangeArray[1]);
if (CollectionUtils.isEmpty(deviceOperationLogEntities)) {
continue;
}
List<DeviceInfoContentBreathe> deviceInfoContentBreatheList = deviceOperationLogEntities.stream()
.filter(deviceOperationLogEntity -> deviceOperationLogEntity.getType().contains("reportProperty"))
.map(deviceOperationLogEntity -> {
DeviceInfoContentBreathe deviceInfoContentBreathe = JsonUtil.toObj((String) deviceOperationLogEntity.getContent(), DeviceInfoContentBreathe.class);
deviceInfoContentBreathe.setReportTime(formatLongTime(deviceInfoContentBreathe.getTimestamp()));
return deviceInfoContentBreathe;
})
.collect(Collectors.toList());
Map<String, List<DeviceInfoContentBreathe>> minuteMap = StreamUtil.groupBy(deviceInfoContentBreatheList, DeviceInfoContentBreathe::getReportTime);
deviceOperationLogEntities.clear();
List<DeviceInfoContentBreathe> deviceInfoContentBreathes;
// 统计每小时的体动和翻身
Map<String, AnalysisVO> statisticsMap = Maps.newHashMap();
for (Map.Entry<String, List<DeviceInfoContentBreathe>> entry : minuteMap.entrySet()) {
deviceInfoContentBreathes = entry.getValue();
DeviceInfoContentBreathe.Properties breatheProperties;
Integer bodymove;
// 记录总呼吸率和总心率
int totalBr = 0;
int totalHr = 0;
// 呼吸暂停
int brStopCount = 0;
int brStopSecond = 0;
String brStopTime = "";
// 呼吸过速
int brFastCount = 0;
int brFastSecond = 0;
int brFast = 0;
String brFastTime = "";
// 呼吸过缓
int brSlowCount = 0;
int brSlowSecond = 0;
int brSlow = 0;
String brSlowTime = "";
// 心率过速
int hrFastCount = 0;
int hrFast = 0;
int hrFastSecond = 0;
String hrFastTime = "";
// 心率过缓
int hrSlowCount = 0;
int hrSlowSecond = 0;
int hrSlow = 0;
String hrSlowTime = "";
Integer bodymoveCount = 0; // 体动次数
Integer turnoverCount = 0; // 翻身次数
boolean isAction = false; // 每分钟是否动过
AnalysisVO analysisVO = new AnalysisVO();
int getUpBodymoveCount = 0;
boolean isMoveBed = true;
boolean awakeMinuteActionFlag = true; // 清醒每分钟体动是否满足要求
int sleepDeepMinuteCount = 0; // 深睡每分钟体动和翻身次数
int sleepModerateAMinuteCount = 0; // 中度睡每分钟体动和翻身次数
for (DeviceInfoContentBreathe infoContentBreathe : deviceInfoContentBreathes) {
// 体动指数
breatheProperties = infoContentBreathe.getProperties();
bodymove = breatheProperties.getBodymove();
int br = breatheProperties.getBr();
int hr = breatheProperties.getHr();
Integer hasPerson = breatheProperties.getPerson(); // 0无人,1有人
if (bodymove > actionThreshold) {
bodymoveCount++;
}
if (bodymove > turnedThreshold) {
turnoverCount++;
}
// 判断入睡时间的体动阈值
if (bodymove > sleepTimeActionThreshold) {
isAction = true;
}
// 起床每分钟体动次数
if (getUpBodymoveCount > riseActionThreshold) {
getUpBodymoveCount++;
}
// 清醒
if (bodymove < awakeThreshold || hasPerson == 1) {
awakeMinuteActionFlag = false;
}
// 判断有没有离开床
if (hasPerson == 1) {
isMoveBed = false;
}
// 判断呼吸暂停
if (br == 0) {
brStopSecond++;
brStopTime = entry.getKey();
if (brStopSecond == breatheDuration) {
brStopCount++;
brStopSecond = 0;
}
} else {
brStopSecond = 0;
}
// 判断呼吸率阈值,记录发生时间和当前呼吸率
if (breatheThresholdMax < br) {
if (StringUtils.isEmpty(brFastTime)) {
brFastTime = entry.getKey();
}
if (brFast == 0) {
brFast = br;
}
brFastSecond++;
if (brFastSecond == breatheDuration) {
brFastCount++;
brFastSecond = 0;
}
} else {
brFastSecond = 0;
}
if (br < breatheThresholdMin) {
if (StringUtils.isEmpty(brSlowTime)) {
brSlowTime = entry.getKey();
}
if (brSlow == 0) {
brSlow = br;
}
brSlowSecond++;
if (brSlowSecond == breatheDuration) {
brSlowCount++;
brSlowSecond = 0;
}
} else {
brSlowSecond = 0;
}
if (heartThresholdMax < hr) {
if (StringUtils.isEmpty(hrFastTime)) {
hrFastTime = entry.getKey();
}
if (hrFast == 0) {
hrFast = br;
}
hrFastSecond++;
if(hrFastSecond == heartDuration) {
hrFastCount++;
hrFastSecond = 0;
}
} else {
hrFastSecond = 0;
}
if (heartThresholdMin > hr) {
if (StringUtils.isEmpty(hrSlowTime)) {
hrSlowTime = entry.getKey();
}
if (hrSlow == 0) {
hrSlow = br;
}
hrSlowSecond++;
if (hrSlowSecond == heartDuration) {
hrSlowCount++;
hrSlowSecond = 0;
}
} else {
hrSlowSecond = 0;
}
totalBr += br;
totalHr += hr;
}
/* int brStopThreshold = brStopCount / breatheDuration;
int brFastThreshold = brFastCount / breatheDuration;
int brSlowThreshold = brSlowCount / breatheDuration;
int hrFastThreshold = hrFastCount / heartDuration;
int hrSlowThreshold = hrSlowCount / heartDuration;
*/
analysisVO.setBrStopThreshold(brStopCount);
analysisVO.setBrFastThreshold(brFastCount);
analysisVO.setBrSlowThreshold(brSlowCount);
analysisVO.setHrFastThreshold(hrFastCount);
analysisVO.setHrSlowThreshold(hrSlowCount);
analysisVO.setBrStopTime(brStopTime);
analysisVO.setBrFastTime(brFastTime);
analysisVO.setBrSlowTime(brSlowTime);
analysisVO.setHrFastTime(hrFastTime);
analysisVO.setHrSlowTime(hrSlowTime);
analysisVO.setBrSlow(brSlow);
analysisVO.setBrFast(brFast);
analysisVO.setHrFast(hrFast);
analysisVO.setHrSlow(hrSlow);
analysisVO.setTotalBr(totalBr);
analysisVO.setAvgBr(totalBr / 60);
analysisVO.setTotalHr(totalHr);
analysisVO.setAvgHr(totalHr / 60);
analysisVO.setActionCount(bodymoveCount);
analysisVO.setTurnedCount(turnoverCount);
analysisVO.setIsAction(isAction);
analysisVO.setIsMoveBed(isMoveBed);
analysisVO.setIsMinuteActionFlag(getUpBodymoveCount > 30);
analysisVO.setAwakeMinuteActionFlag(awakeMinuteActionFlag);
statisticsMap.put(entry.getKey(), analysisVO);
}
TreeMap<String, AnalysisVO> treeMap = new TreeMap<>(statisticsMap);
totalMap.putAll(treeMap);
statisticsMap.clear();
treeMap.clear();
}
if (totalMap.isEmpty()) {
continue;
}
// 呼吸暂停
int apneaTime = Integer.parseInt(saasDiseaseModel.getApneaTime());
int apneaThreshold = Integer.parseInt(saasDiseaseModel.getApneaThreshold());
BigDecimal apneaRate = new BigDecimal(apneaTime).divide(new BigDecimal(apneaThreshold), 2, RoundingMode.HALF_UP);
// 呼吸过速
int tachypneaTime = Integer.parseInt(saasDiseaseModel.getTachypneaTime());
int tachypneaThreshold = Integer.parseInt(saasDiseaseModel.getTachypneaThreshold());
BigDecimal tachypneaRate = new BigDecimal(tachypneaTime).divide(new BigDecimal(tachypneaThreshold), 2, RoundingMode.HALF_UP);
// 呼吸过缓
int bradypneaTime = Integer.parseInt(saasDiseaseModel.getBradypneaTime());
int bradypneaThreshold = Integer.parseInt(saasDiseaseModel.getBradypneaThreshold());
BigDecimal bradypneaRate = new BigDecimal(bradypneaTime).divide(new BigDecimal(bradypneaThreshold), 2, RoundingMode.HALF_UP);
// 心率过缓
int bradycardiaTime = Integer.parseInt(saasDiseaseModel.getBradycardiaTime());
int bradycardiaThreshold = Integer.parseInt(saasDiseaseModel.getBradycardiaThreshold());
BigDecimal bradycardiaRate = new BigDecimal(bradycardiaTime).divide(new BigDecimal(bradycardiaThreshold), 2, RoundingMode.HALF_UP);
// 心率过速
int tachycardiaTime = Integer.parseInt(saasDiseaseModel.getTachycardiaTime());
int tachycardiaComparison = Integer.parseInt(saasDiseaseModel.getTachycardiaThreshold());
BigDecimal tachycardiaRate = new BigDecimal(tachycardiaTime).divide(new BigDecimal(tachycardiaComparison), 2, RoundingMode.HALF_UP);
// 呼吸疾病报告
int brStopCount = 0;
int brFastCount = 0;
int brSlowCount = 0;
int hrFastCount = 0;
int hrSlowCount = 0;
int dayTotalHr = 0;
int dayTotalBr = 0;
// 计算异常的信息,并且统计异常的次数
List<BreatheAbnormalVO> breatheAbnormalVOList = Lists.newArrayList();
for (Map.Entry<String, AnalysisVO> entry : totalMap.entrySet()) {
BreatheAbnormalVO breatheAbnormalVO = new BreatheAbnormalVO();
AnalysisVO analysisVO = entry.getValue();
if (analysisVO.getBrStopThreshold() > 0) {
brStopCount += analysisVO.getBrStopThreshold();
breatheAbnormalVO.setType(BreatheTypeEnum.APNEA.getCode());
breatheAbnormalVO.setHappenTime(LocalDateTime.parse(analysisVO.getBrStopTime(), DEFAULT_FORMATTER));
breatheAbnormalVO.setValue("0");
breatheAbnormalVOList.add(breatheAbnormalVO);
}
if (analysisVO.getBrSlowThreshold() > 0) {
brSlowCount += analysisVO.getBrSlowThreshold();
breatheAbnormalVO.setType(BreatheTypeEnum.BRADYPNEA.getCode());
breatheAbnormalVO.setHappenTime(LocalDateTime.parse(analysisVO.getBrSlowTime(), DEFAULT_FORMATTER));
breatheAbnormalVO.setValue(String.valueOf(analysisVO.getBrSlow()));
breatheAbnormalVOList.add(breatheAbnormalVO);
}
if (analysisVO.getBrFastThreshold() > 0) {
brFastCount += analysisVO.getBrFastThreshold();
breatheAbnormalVO.setType(BreatheTypeEnum.TACHYPNEA.getCode());
breatheAbnormalVO.setHappenTime(LocalDateTime.parse(analysisVO.getBrFastTime(), DEFAULT_FORMATTER));
breatheAbnormalVO.setValue(String.valueOf(analysisVO.getBrFast()));
breatheAbnormalVOList.add(breatheAbnormalVO);
}
if (analysisVO.getHrFastThreshold() > 0) {
hrFastCount += analysisVO.getHrFastThreshold();
breatheAbnormalVO.setType(HeartRateTypeEnum.TACHYCARDIA.getCode());
breatheAbnormalVO.setHappenTime(LocalDateTime.parse(analysisVO.getHrFastTime(), DEFAULT_FORMATTER));
breatheAbnormalVO.setValue(String.valueOf(analysisVO.getHrFast()));
breatheAbnormalVOList.add(breatheAbnormalVO);
}
if (analysisVO.getHrSlowThreshold() > 0) {
hrSlowCount += analysisVO.getHrSlowThreshold();
breatheAbnormalVO.setType(HeartRateTypeEnum.BRADYCARDIA.getCode());
breatheAbnormalVO.setHappenTime(LocalDateTime.parse(analysisVO.getHrSlowTime(), DEFAULT_FORMATTER));
breatheAbnormalVO.setValue(String.valueOf(analysisVO.getHrSlow()));
breatheAbnormalVOList.add(breatheAbnormalVO);
}
dayTotalHr += analysisVO.getTotalHr();
dayTotalBr += analysisVO.getTotalBr();
}
// 判断是否满足配置的呼吸心率异常类型
BigDecimal dayBrStopRate = brStopCount == 0 ? BigDecimal.ZERO : new BigDecimal(24).divide(new BigDecimal(brStopCount), 2, RoundingMode.HALF_UP);
BigDecimal dayBrSlowRate = brSlowCount == 0 ? BigDecimal.ZERO : new BigDecimal(24).divide(new BigDecimal(brSlowCount), 2, RoundingMode.HALF_UP);
BigDecimal dayBrFastRate = brFastCount == 0 ? BigDecimal.ZERO : new BigDecimal(24).divide(new BigDecimal(brFastCount), 2, RoundingMode.HALF_UP);
BigDecimal dayHrFastRate = hrFastCount == 0 ? BigDecimal.ZERO : new BigDecimal(24).divide(new BigDecimal(hrFastCount), 2, RoundingMode.HALF_UP);
BigDecimal dayHrSlowRate = hrSlowCount == 0 ? BigDecimal.ZERO : new BigDecimal(24).divide(new BigDecimal(hrSlowCount), 2, RoundingMode.HALF_UP);
boolean brStopFlag = false;
boolean brFastFlag = false;
boolean brSlowFlag = false;
boolean hrFastFlag = false;
boolean hrSlowFlag = false;
boolean normalFlag;
if (apneaRate.compareTo(dayBrStopRate) > 0) {
brStopFlag = true;
}
if (tachypneaRate.compareTo(dayBrFastRate) > 0) {
brFastFlag = true;
}
if (bradypneaRate.compareTo(dayBrSlowRate) > 0) {
brSlowFlag = true;
}
if (tachycardiaRate.compareTo(dayHrFastRate) > 0) {
hrFastFlag = true;
}
if (bradycardiaRate.compareTo(dayHrSlowRate) > 0) {
hrSlowFlag = true;
}
normalFlag = !(hrFastFlag || brStopFlag || brFastFlag || brSlowFlag || hrSlowFlag);
SaasDiseaseEvaluateReport saasDiseaseEvaluateReport = saasDiseaseEvaluateReportService.getOne(new QueryWrapper<SaasDiseaseEvaluateReport>().lambda()
.orderByDesc(BaseEntity::getCreateBy)
.last("limit 1"));
String resultContent = saasDiseaseEvaluateReport.getResultContent();
List<DiseaseReportVO> evaluateReportList = JSON.parseArray(resultContent, DiseaseReportVO.class);
DiseaseReportVO finalReport = new DiseaseReportVO();
// 根据疾病标准配置的规则判断满足哪个区间范围
for (DiseaseReportVO diseaseReportVO : evaluateReportList) {
List<DiseaseReportVO.Condition> conditionList = diseaseReportVO.getCondition();
boolean conditionFlag = true;
for (DiseaseReportVO.Condition condition : conditionList) {
String resultRelational = condition.getResultRelational();
String resultCondition = condition.getResultCondition();
if ("or".equals(resultCondition)) {
if (conditionFlag) {
break;
}
} else {
if (resultRelational.equals("normal")) {
conditionFlag = normalFlag && conditionFlag;
}
if (resultRelational.equals(BreatheTypeEnum.APNEA.getCode())) {
conditionFlag = brStopFlag && conditionFlag;
}
if (resultRelational.equals(BreatheTypeEnum.TACHYPNEA.getCode())) {
conditionFlag = brFastFlag && conditionFlag;
}
if (resultRelational.equals(BreatheTypeEnum.BRADYPNEA.getCode())) {
conditionFlag = brSlowFlag && conditionFlag;
}
if (resultRelational.equals(HeartRateTypeEnum.TACHYCARDIA.getCode())) {
conditionFlag = hrFastFlag && conditionFlag;
}
if (resultRelational.equals(HeartRateTypeEnum.BRADYCARDIA.getCode())) {
conditionFlag = hrSlowFlag && conditionFlag;
}
}
}
if (conditionFlag) {
finalReport = diseaseReportVO;
}
}
EvaluateReportVO diseaseReport = saasDiseaseReportService.getByScore(Long.parseLong(finalReport.getScore()));
// 插入呼吸分析表
PlatElderBreatheAnalysis platElderBreatheAnalysis = new PlatElderBreatheAnalysis();
platElderBreatheAnalysis.setElderId(elder.getId());
platElderBreatheAnalysis.setAvgBreatheRate(String.valueOf(dayTotalBr / 86400));
platElderBreatheAnalysis.setAvgHeartRate(String.valueOf(dayTotalHr / 86400));
platElderBreatheAnalysis.setBreatheScore(finalReport.getScore());
platElderBreatheAnalysis.setHappenDate(currentDate);
platElderBreatheAnalysis.setTenantId(tenantId);
platElderBreatheAnalysis.setBreatheEvaluate(diseaseReport == null ? "" : diseaseReport.getEvaluate());
platElderBreatheAnalysisService.save(platElderBreatheAnalysis);
// 记录长者呼吸心率的异常事件
PlatElderBreatheAbnormal platElderBreatheAbnormal;
for (BreatheAbnormalVO breatheAbnormalVO : breatheAbnormalVOList) {
platElderBreatheAbnormal = new PlatElderBreatheAbnormal();
platElderBreatheAbnormal.setElderId(elder.getId());
platElderBreatheAbnormal.setBreatheAnalysisId(platElderBreatheAnalysis.getId());
platElderBreatheAbnormal.setType(breatheAbnormalVO.getType());
platElderBreatheAbnormal.setHappenTime(breatheAbnormalVO.getHappenTime());
platElderBreatheAbnormal.setValue(breatheAbnormalVO.getValue());
platElderBreatheAbnormal.setTenantId(tenantId);
platElderBreatheAbnormalService.save(platElderBreatheAbnormal);
}
int totalActionCount = 0;
int totalTurnedCount = 0;
// 记录长者不同类型的睡眠时间
List<SleepTimeAnalysisVO> sleepTimeAnalysisVOList = Lists.newArrayList();
SleepTimeAnalysisVO sleepTimeAnalysisVO;
// 判断睡觉时间
String startSleepTime = null; // 入睡时间开始
int sleepMinute = 0;
int currentSleepTimeDuration = 0;
for (Map.Entry<String, AnalysisVO> entry : totalMap.entrySet()) {
AnalysisVO analysisVO = entry.getValue();
if (!analysisVO.getIsAction()) {
if (StringUtils.isEmpty(startSleepTime)) {
startSleepTime = entry.getKey();
}
sleepMinute++;
continue;
}
if (StringUtils.isEmpty(startSleepTime) && sleepMinute == 0) {
continue;
}
if (sleepMinute > sleepTimeActionDuration * 60) {
sleepTimeAnalysisVO = new SleepTimeAnalysisVO();
sleepTimeAnalysisVO.setStartTime(startSleepTime);
sleepTimeAnalysisVO.setEndTime(entry.getKey());
sleepTimeAnalysisVO.setType(SleepTypeEnum.SLEEP.getCode());
sleepTimeAnalysisVOList.add(sleepTimeAnalysisVO);
}
startSleepTime = null;
sleepMinute = 0;
}
// 判断起床时间
String startGetupTime = null; // 起床时间开始
int getupMinute = 0;
for (Map.Entry<String, AnalysisVO> entry : totalMap.entrySet()) {
AnalysisVO analysisVO = entry.getValue();
if (analysisVO.getIsMoveBed()) {
if (StringUtils.isEmpty(startGetupTime)) {
startGetupTime = entry.getKey();
}
getupMinute++;
continue;
}
if (StringUtils.isEmpty(startGetupTime) && getupMinute == 0) {
continue;
}
if (getupMinute > riseLeaveThreshold * 60) {
sleepTimeAnalysisVO = new SleepTimeAnalysisVO();
sleepTimeAnalysisVO.setStartTime(startGetupTime);
sleepTimeAnalysisVO.setEndTime(entry.getKey());
sleepTimeAnalysisVO.setType(SleepTypeEnum.GETUP.getCode());
sleepTimeAnalysisVOList.add(sleepTimeAnalysisVO);
}
startGetupTime = null;
getupMinute = 0;
}
// 判断起床时间
String startGetupTime2 = null; // 起床时间开始
int getupMinute2 = 0;
for (Map.Entry<String, AnalysisVO> entry : totalMap.entrySet()) {
AnalysisVO analysisVO = entry.getValue();
if (analysisVO.getIsMinuteActionFlag()) {
if (StringUtils.isEmpty(startGetupTime2)) {
startGetupTime2 = entry.getKey();
}
getupMinute2++;
continue;
}
if (StringUtils.isEmpty(startGetupTime2) && getupMinute2 == 0) {
continue;
}
if (getupMinute2 > riseActionDuration) {
sleepTimeAnalysisVO = new SleepTimeAnalysisVO();
sleepTimeAnalysisVO.setStartTime(startGetupTime2);
sleepTimeAnalysisVO.setEndTime(entry.getKey());
sleepTimeAnalysisVO.setType(SleepTypeEnum.GETUP.getCode());
sleepTimeAnalysisVOList.add(sleepTimeAnalysisVO);
}
startGetupTime2 = null;
getupMinute2 = 0;
}
int sleepDeepMinute = 0;
String startSleepDeepTime = null; // 入睡时间开始
// 判断深度睡眠时间
for (Map.Entry<String, AnalysisVO> entry : totalMap.entrySet()) {
AnalysisVO analysisVO = entry.getValue();
totalActionCount += analysisVO.getActionCount();
totalTurnedCount += analysisVO.getTurnedCount();
if (analysisVO.getActionCount() == sleepDeepActionThreshold && analysisVO.getTurnedCount() == sleepDeepActionThreshold
&& sleepDeepBreatheMin <= analysisVO.getAvgBr() && sleepDeepBreatheMax >= analysisVO.getAvgBr()) {
if (StringUtils.isEmpty(startSleepDeepTime)) {
startSleepDeepTime = entry.getKey();
}
sleepDeepMinute++;
continue;
}
if (StringUtils.isEmpty(startSleepDeepTime) && sleepDeepMinute == 0) {
continue;
}
if (sleepDeepMinute > sleepDeepActionTimeBegin) {
sleepTimeAnalysisVO = new SleepTimeAnalysisVO();
sleepTimeAnalysisVO.setStartTime(startSleepDeepTime);
sleepTimeAnalysisVO.setEndTime(entry.getKey());
sleepTimeAnalysisVO.setType(SleepTypeEnum.SLEEP_DEEP.getCode());
sleepTimeAnalysisVOList.add(sleepTimeAnalysisVO);
}
startSleepDeepTime = null;
sleepDeepMinute = 0;
}
// 中度睡眠
int sleepMidMinute = 0;
String startSleepMidTime = null; // 入睡时间开始
for (Map.Entry<String, AnalysisVO> entry : totalMap.entrySet()) {
AnalysisVO analysisVO = entry.getValue();
if (analysisVO.getActionCount() < sleepDeepActionThreshold && analysisVO.getTurnedCount() < sleepDeepActionThreshold) {
if (StringUtils.isEmpty(startSleepMidTime)) {
startSleepMidTime = entry.getKey();
}
sleepMidMinute++;
continue;
}
if (StringUtils.isEmpty(startSleepMidTime) && sleepMidMinute == 0) {
continue;
}
if (sleepMidMinute > sleepDeepActionTimeBegin) {
sleepTimeAnalysisVO = new SleepTimeAnalysisVO();
sleepTimeAnalysisVO.setStartTime(startSleepMidTime);
sleepTimeAnalysisVO.setEndTime(entry.getKey());
sleepTimeAnalysisVO.setType(SleepTypeEnum.SLEEP_MODERATE.getCode());
sleepTimeAnalysisVOList.add(sleepTimeAnalysisVO);
}
startSleepMidTime = null;
sleepMidMinute = 0;
}
// 清醒
int awakeMinute = 0;
String startAwakeTime = null; // 入睡时间开始
for (Map.Entry<String, AnalysisVO> entry : totalMap.entrySet()) {
AnalysisVO analysisVO = entry.getValue();
if (analysisVO.getAwakeMinuteActionFlag()) {
if (StringUtils.isEmpty(startAwakeTime)) {
startAwakeTime = entry.getKey();
}
awakeMinute++;
continue;
}
if (StringUtils.isEmpty(startAwakeTime) && awakeMinute == 0) {
continue;
}
if (awakeMinute > sleepDeepActionTimeBegin) {
sleepTimeAnalysisVO = new SleepTimeAnalysisVO();
sleepTimeAnalysisVO.setStartTime(startAwakeTime);
sleepTimeAnalysisVO.setEndTime(entry.getKey());
sleepTimeAnalysisVO.setType(SleepTypeEnum.SOBER.getCode());
sleepTimeAnalysisVOList.add(sleepTimeAnalysisVO);
}
startAwakeTime = null;
awakeMinute = 0;
}
Map<String, List<SleepTimeAnalysisVO>> sleepMap = StreamUtil.groupBy(sleepTimeAnalysisVOList, SleepTimeAnalysisVO::getType);
List<SleepTimeAnalysisVO> sleepList = sleepMap.get(SleepTypeEnum.SLEEP.getCode());
if (CollectionUtils.isEmpty(sleepList)) {
continue;
}
// 遍历得出长者一天多次睡眠中包含的不同睡眠类型
List<SleepTimeAnalysisVO> finalSleepTimeAnalysisList = Lists.newArrayList(); // 记录多端睡眠记录
SleepTimeAnalysisVO sleepTimeAnalysis;
String elderSleepTime = ""; // 长者睡觉时间
String elderGetupTime = ""; // 长者起床时间
for (int i = 0; i < sleepList.size(); i++) {
sleepTimeAnalysis = new SleepTimeAnalysisVO();
List<SleepTimeAnalysisVO> deepList = Lists.newArrayList();
List<SleepTimeAnalysisVO> midList = Lists.newArrayList();
List<SleepTimeAnalysisVO> lightList = Lists.newArrayList();
List<SleepTimeAnalysisVO> soberList = Lists.newArrayList();
SleepTimeAnalysisVO timeAnalysisVO = sleepList.get(i);
if (i == 0) {
elderSleepTime = timeAnalysisVO.getStartTime();
}
if (i == sleepList.size() - 1) {
elderGetupTime = timeAnalysisVO.getEndTime();
}
BeanUtils.copyProperties(timeAnalysisVO,sleepTimeAnalysis);
String startTime = timeAnalysisVO.getStartTime();
String endTime = timeAnalysisVO.getEndTime();
Long durationRange = getDurationRange(timeAnalysisVO.getStartTime(), timeAnalysisVO.getEndTime());
timeAnalysisVO.setInterval(durationRange);
LocalDateTime startDateTime = LocalDateTime.parse(startTime, DEFAULT_FORMATTER);
LocalDateTime endDateTime = LocalDateTime.parse(endTime, DEFAULT_FORMATTER);
for (SleepTimeAnalysisVO otherSleepTime : sleepTimeAnalysisVOList) {
if (otherSleepTime.getType().equals(SleepTypeEnum.SLEEP.getCode()) || otherSleepTime.getType().equals(SleepTypeEnum.GETUP.getCode())) {
continue;
}
String deepStartTime = otherSleepTime.getStartTime();
String deepEndTime = otherSleepTime.getEndTime();
LocalDateTime startDeepDateTime = LocalDateTime.parse(deepStartTime, DEFAULT_FORMATTER);
LocalDateTime endDeepDateTime = LocalDateTime.parse(deepEndTime, DEFAULT_FORMATTER);
if ((startDateTime.isBefore(startDeepDateTime) || startDateTime.equals(startDeepDateTime)) &&
(endDateTime.isAfter(endDeepDateTime) || endDateTime.equals(endDeepDateTime))) {
if (otherSleepTime.getType().equals(SleepTypeEnum.SLEEP_DEEP.getCode())) {
deepList.add(otherSleepTime);
}
if (otherSleepTime.getType().equals(SleepTypeEnum.SLEEP_MODERATE.getCode())) {
midList.add(otherSleepTime);
}
if (timeAnalysisVO.getType().equals(SleepTypeEnum.SLEEP_LIGHTNESS.getCode())) {
lightList.add(otherSleepTime);
}
if (timeAnalysisVO.getType().equals(SleepTypeEnum.SOBER.getCode())) {
soberList.add(otherSleepTime);
}
}
}
sleepTimeAnalysis.setDeepList(deepList);
sleepTimeAnalysis.setInterval(durationRange);
sleepTimeAnalysis.setMidList(midList);
sleepTimeAnalysis.setLightList(lightList);
sleepTimeAnalysis.setSoberList(soberList);
finalSleepTimeAnalysisList.add(sleepTimeAnalysis);
}
SaasSleepEvaluateStandardReport evaluateStandardReport = saasSleepEvaluateStandardReportService.getOne(new QueryWrapper<SaasSleepEvaluateStandardReport>().lambda()
.orderByDesc(BaseEntity::getCreateBy)
.last("limit 1"));
// 算出每一段睡觉的不同睡眠类型的时间段
SaasSleepEvaluateStandardReportVO saasSleepEvaluateStandardReportVO = new SaasSleepEvaluateStandardReportVO();
List<PlatElderSleep> elderSleepList = Lists.newArrayList();
PlatSleepRangeVO sleepRangeVO;
for (SleepTimeAnalysisVO timeAnalysisVO : finalSleepTimeAnalysisList) {
List<PlatSleepRangeVO> sleepRangeVOList = Lists.newArrayList();
PlatElderSleep elderSleep = new PlatElderSleep();
for (SleepTimeAnalysisVO analysisVO : timeAnalysisVO.getDeepList()) {
sleepRangeVO = new PlatSleepRangeVO();
sleepRangeVO.setStartTime(analysisVO.getStartTime());
sleepRangeVO.setEndTime(analysisVO.getEndTime());
sleepRangeVO.setSleepType(analysisVO.getType());
sleepRangeVOList.add(sleepRangeVO);
}
for (SleepTimeAnalysisVO analysisVO : timeAnalysisVO.getMidList()) {
sleepRangeVO = new PlatSleepRangeVO();
sleepRangeVO.setStartTime(analysisVO.getStartTime());
sleepRangeVO.setEndTime(analysisVO.getEndTime());
sleepRangeVO.setSleepType(analysisVO.getType());
sleepRangeVOList.add(sleepRangeVO);
}
for (SleepTimeAnalysisVO analysisVO : timeAnalysisVO.getLightList()) {
sleepRangeVO = new PlatSleepRangeVO();
sleepRangeVO.setStartTime(analysisVO.getStartTime());
sleepRangeVO.setEndTime(analysisVO.getEndTime());
sleepRangeVO.setSleepType(analysisVO.getType());
sleepRangeVOList.add(sleepRangeVO);
}
for (SleepTimeAnalysisVO analysisVO : timeAnalysisVO.getSoberList()) {
sleepRangeVO = new PlatSleepRangeVO();
sleepRangeVO.setStartTime(analysisVO.getStartTime());
sleepRangeVO.setEndTime(analysisVO.getEndTime());
sleepRangeVO.setSleepType(analysisVO.getType());
sleepRangeVOList.add(sleepRangeVO);
}
elderSleep.setStartSleep(LocalDateTime.parse(timeAnalysisVO.getStartTime(), DEFAULT_FORMATTER));
elderSleep.setEndSleep(LocalDateTime.parse(timeAnalysisVO.getEndTime(), DEFAULT_FORMATTER));
if (timeAnalysisVO.getInterval() / 60 > 3) {
elderSleep.setElderSleepType(ElderSleepType.SLEEP.getCode());
} else {
elderSleep.setElderSleepType(ElderSleepType.REST.getCode());
}
elderSleep.setSleepRecord(sleepRangeVOList);
elderSleepList.add(elderSleep);
}
// 获取睡眠评估标准配置
String sleepDeepConfig = evaluateStandardReport.getSleepDeepConfig();
String soberConfig = evaluateStandardReport.getSoberConfig();
String sleepTimeConfig = evaluateStandardReport.getSleepTime();
String lightnessConfig = evaluateStandardReport.getSleepLightnessConfig();
List<SleepConfigVO> sleepDeepConfigList = JSON.parseArray(sleepDeepConfig, SleepConfigVO.class);
List<SleepConfigVO> soberConfigList = JSON.parseArray(soberConfig, SleepConfigVO.class);
List<SleepConfigVO> sleepTimeConfigList = JSON.parseArray(sleepTimeConfig, SleepConfigVO.class);
SleepConfigVO lightnessConfigVO = JSON.parseObject(lightnessConfig, SleepConfigVO.class);
long deepTime = 0;
long soberTime = 0;
long soberCount = 0;
long sleepTime = 0;
long lightTime = 0;
// 算出不同睡眠类型的总时长
for (SleepTimeAnalysisVO timeAnalysisVO : sleepTimeAnalysisVOList) {
Long durationRange = getDurationRange(timeAnalysisVO.getStartTime(), timeAnalysisVO.getEndTime());
timeAnalysisVO.setInterval(durationRange);
if (timeAnalysisVO.getType().equals(SleepTypeEnum.SLEEP_DEEP.getCode())) {
deepTime += durationRange;
}
if (timeAnalysisVO.getType().equals(SleepTypeEnum.SOBER.getCode())) {
soberTime += durationRange;
}
if (timeAnalysisVO.getType().equals(SleepTypeEnum.SLEEP_LIGHTNESS.getCode())) {
lightTime += durationRange;
soberCount++;
}
if (timeAnalysisVO.getType().equals(SleepTypeEnum.SLEEP.getCode())) {
sleepTime += durationRange;
}
}
// 根据睡眠报告评估标准算出不同睡眠类型的得分
sleepTime = sleepTime - soberTime;
long deepScore = 0;
for (int i = 0; i < sleepDeepConfigList.size(); i++) {
long hour = deepTime / 60;
SleepConfigVO sleepConfigVO = sleepDeepConfigList.get(i);
long configHour = Long.parseLong(sleepConfigVO.getHour());
if (i == 0 && Objects.equals(hour,configHour)) {
deepScore = Long.parseLong(sleepConfigVO.getScore());
}
if (i > 0 && hour > configHour) {
deepScore += Long.parseLong(sleepConfigVO.getScore());
}
}
saasSleepEvaluateStandardReportVO.setDeepScore(deepScore);
long soberScore = 0;
for (int i = 0; i < soberConfigList.size(); i++) {
SleepConfigVO sleepConfigVO = soberConfigList.get(i);
long configHour = Long.parseLong(sleepConfigVO.getHour());
if (i == 0 && soberCount != 0) {
soberScore = Long.parseLong(sleepConfigVO.getScore()) * soberCount;
}
if (i > 0 && soberTime > configHour) {
soberScore += Long.parseLong(sleepConfigVO.getScore());
}
}
saasSleepEvaluateStandardReportVO.setSoberScore(soberScore);
long lightScore = 0;
long lightHour = lightTime / 60;
long lightnessConfigHour = Long.parseLong(lightnessConfigVO.getHour());
if ( Objects.equals(lightHour,lightnessConfigHour)) {
lightScore = Long.parseLong(lightnessConfigVO.getScore());
}
saasSleepEvaluateStandardReportVO.setLightScore(lightScore);
long sleepScore = 0;
for (int i = 0; i < sleepTimeConfigList.size(); i++) {
long hour = sleepTime / 60;
SleepConfigVO sleepConfigVO = sleepTimeConfigList.get(i);
long configHour = Long.parseLong(sleepConfigVO.getHour());
if (i == 0 && Objects.equals(hour,configHour)) {
sleepScore = Long.parseLong(sleepConfigVO.getScore());
}
if (i > 0 && hour > configHour) {
sleepScore += Long.parseLong(sleepConfigVO.getScore());
}
}
saasSleepEvaluateStandardReportVO.setSleepScore(sleepScore);
long totalScore = sleepScore + deepScore + lightScore - soberScore;
saasSleepEvaluateStandardReportVO.setTotalScore(totalScore);
EvaluateReportVO sleepReport = saasSleepEvaluateReportService.getByScore(totalScore);
// 记录长者一天睡眠的记录
for (PlatElderSleep elderSleep : elderSleepList) {
elderSleep.setElderId(elder.getId());
elderSleep.setHappenDate(currentDate);
elderSleep.setTenantId(tenantId);
}
// TODO 起床时间和入睡时间
platElderSleepService.saveBatch(elderSleepList);
EvaluateReportVO elderReport = saasElderReportConfigService.getByScore(totalScore);
// 长者一天的睡眠分析
PlatElderSleepAnalysis elderSleepAnalysis = new PlatElderSleepAnalysis();
elderSleepAnalysis.setElderId(elder.getId());
elderSleepAnalysis.setActionCount(totalActionCount);
elderSleepAnalysis.setTurnedCount(totalTurnedCount);
elderSleepAnalysis.setHappenDate(currentDate);
elderSleepAnalysis.setSleepScore(sleepReport.getResult());
elderSleepAnalysis.setSleepTime(String.valueOf(sleepTime));
int minuteDay = 24 * 60;
// TODO 休息时间 先用一天时间 - 睡觉时间
elderSleepAnalysis.setRestTime(String.valueOf(minuteDay - sleepTime));
elderSleepAnalysis.setSleepResult(sleepReport.getResult());
elderSleepAnalysis.setTenantId(tenantId);
elderSleepAnalysis.setSleepEvaluate(elderReport == null ? "" : elderReport.getEvaluate());
platElderSleepAnalysisService.save(elderSleepAnalysis);
}
}
public Long getDurationRange(String startTime, String endTime) {
LocalDateTime target = LocalDateTime.parse(startTime,DEFAULT_FORMATTER);
// 获取当前日期,此处为了保证后续结果固定,注掉自动获取当前日期,指定固定日期
// LocalDate today = LocalDate.now();
LocalDateTime source = LocalDateTime.parse(endTime,DEFAULT_FORMATTER);
return Duration.between(target, source).toMinutes();
}
public static String formatLongTime(long time) {
return DEFAULT_FORMATTER.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()));
}
public List<String> getLastDayHourRange() {
int count = 24;
LocalDateTime now = LocalDateTime.now();
List<String> list = Lists.newArrayList();
String startTime;
String endTime;
for (int i = count; i > 0; i--) {
startTime = DateUtil.format(now.minusHours(i), DatePattern.NORM_DATETIME_PATTERN);
endTime = DateUtil.format(now.minusHours(i - 1), DatePattern.NORM_DATETIME_PATTERN);
list.add(startTime + "~" + endTime);
}
return list;
}
}
......@@ -6,6 +6,7 @@ import com.makeit.common.entity.BaseBusEntity;
import com.makeit.entity.platform.device.PlatDevice;
import com.makeit.entity.saas.PlatTenant;
import com.makeit.enums.CommonEnum;
import com.makeit.enums.report.DeviceNameEnum;
import com.makeit.global.aspect.tenant.TenantIdIgnore;
import com.makeit.module.iot.service.IotOrgService;
import com.makeit.module.iot.vo.DeviceInstanceEntity;
......@@ -13,6 +14,7 @@ import com.makeit.module.iot.vo.DeviceState;
import com.makeit.module.system.service.SysDictionaryCategoryService;
import com.makeit.module.system.vo.DictionaryVo;
import com.makeit.service.platform.device.PlatDeviceService;
import com.makeit.service.platform.elder.PlatElderSleepService;
import com.makeit.service.saas.PlatTenantService;
import com.makeit.utils.DeviceCacheUtil;
import lombok.extern.slf4j.Slf4j;
......@@ -43,6 +45,8 @@ public class IotSyncTask {
private SysDictionaryCategoryService sysDictionaryCategoryService;
@Autowired
private DeviceCacheUtil deviceCacheUtil;
@Autowired
private PlatElderSleepService platElderSleepService;
/**
* 一小时同步一次
......@@ -108,7 +112,8 @@ public class IotSyncTask {
}
platDevice.setOriDeviceId(iotDevice.getId());
platDevice.setName(iotDevice.getName());
platDevice.setProductName(iotDevice.getProductName());
String productName = iotDevice.getProductName();
platDevice.setProductName(productName);
platDevice.setProductId(iotDevice.getProductId());
if(iotDevice.getRegistryTime()!=null) {
LocalDateTime registryTime = LocalDateTime.ofEpochSecond(iotDevice.getRegistryTime() / 1000, 0, ZoneOffset.ofHours(8));
......@@ -120,7 +125,8 @@ public class IotSyncTask {
platDevice.setStatus(deviceState.getValue());
//todo 根据类型名称来匹配
platDevice.setCategory(dicNameIdMap.get(iotDevice.getProductName()));
String categoryName = DeviceNameEnum.getNameByPrefix(productName);
platDevice.setCategory(dicNameIdMap.get(categoryName));
// platDevice.setFirmwareVersion();
// platDevice.setLastOnlineData();
// platDevice.setOrgId();
......@@ -145,4 +151,15 @@ public class IotSyncTask {
*
*/
/**
* 长者睡眠分析
*/
//@Scheduled(cron = "0 6 * * *")
@TenantIdIgnore
public void elderSleepSleepAnalysisTask() {
log.info("开始定时分析长者睡眠质量");
platElderSleepService.elderSleepSleepAnalysisTask();
log.info("定时分析长者睡眠质量结束");
}
}
......@@ -21,18 +21,19 @@
<dependency>
<groupId>com.makeit</groupId>
<artifactId>server-common</artifactId>
<artifactId>saas-module</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.makeit</groupId>
<artifactId>saas-module</artifactId>
<artifactId>server-module</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.makeit</groupId>
<artifactId>server-module</artifactId>
<artifactId>server-api</artifactId>
<version>1.0.0</version>
</dependency>
......
package com.makeit.mqtt;
import com.makeit.common.response.ApiResponseEntity;
import com.makeit.common.response.ApiResponseUtils;
import com.makeit.global.annotation.AuthIgnore;
import com.makeit.global.aspect.tenant.TenantIdIgnore;
import com.makeit.module.iot.service.IotDevicePropertiesOperateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "发送mqtt消息")
@RestController
@RequestMapping("/mqtt")
public class MqttController {
@Autowired
private MqttPushClient mqttPushClient;
@Autowired
private IotDevicePropertiesOperateService devicePropertiesOperateService;
@ApiOperation("测试")
@PostMapping("testMqtt")
@AuthIgnore
@TenantIdIgnore
public ApiResponseEntity<Void> testMqtt() {
devicePropertiesOperateService.deviceWrite("1701240048151490560", 1,1,1);
return ApiResponseUtils.success();
}
}
......@@ -44,7 +44,7 @@ public class IotDeviceInfoContentFall {
@Test
void getOrgDevice() {
iotOrgService.getOrgDevice("1698939546961244160");
iotOrgService.getOrgDevice("1701223487902642176");
}
@Test
......@@ -64,7 +64,7 @@ public class IotDeviceInfoContentFall {
@Test
void getDeviceLogByTimeRange() {
iotProductDeviceService.getDeviceLogByTimeRange("1701127702523473920", "reportProperty", 100, "2023-09-12 00:00:00", "2023-09-12 23:59:00");
iotProductDeviceService.getDeviceLogByTimeRange("1702604383784333312", "reportProperty", 1000, "2023-09-19 14:23:32", "2023-09-19 15:23:32");
}
@Test
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment