Browse Source

调整胎动计算

datasub12_fetal_heart_rate_0
H Vs 3 months ago
parent
commit
35670ab2bc
2 changed files with 117 additions and 200 deletions
  1. +5
    -4
      HealthMonitor.Service/Resolver/PregnancyHeartRateResolver.cs
  2. +112
    -196
      HealthMonitor.WebApi/Worker.cs

+ 5
- 4
HealthMonitor.Service/Resolver/PregnancyHeartRateResolver.cs View File

@@ -107,6 +107,7 @@ namespace HealthMonitor.Service.Resolver

if (isFetalHeartEnable)
{
_logger.LogInformation($"{heartRate.Serialno} 计算胎心胎动启动");
#region 定时下发触发器(定时建模)
var key = $"health_monitor/schedule_push/pregnancy_heart_rate/imei/{heartRate.Serialno}";
var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
@@ -144,7 +145,7 @@ namespace HealthMonitor.Service.Resolver
}

#endregion
_logger.LogInformation($"{heartRate.Serialno} 触发定时建模");

// 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容
var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! + 5;
@@ -429,14 +430,14 @@ namespace HealthMonitor.Service.Resolver

var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);

var normalPhrStatStartTime = nextInterval;
var normalPhrStatStartTime = nextInterval.AddMinutes(-intervalFHR) ;

var normalPhrStatEndTime = nextInterval.AddMinutes(-intervalFHR);
var normalPhrStatEndTime = nextInterval;

_logger.LogInformation($"{heartRate.Serialno} 计算胎心数据, 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} ");
var filteredPhr = daysPhr
// 使用 last_update 下一刻
.Where(i => i.LastUpdate <= normalPhrStatStartTime && i.LastUpdate >= normalPhrStatEndTime)
.Where(i => i.LastUpdate <= normalPhrStatEndTime && i.LastUpdate >= normalPhrStatStartTime)
.ToList();
if (filteredPhr.Count == 0)
{


+ 112
- 196
HealthMonitor.WebApi/Worker.cs View File

@@ -342,103 +342,6 @@ namespace HealthMonitor.WebApi
//health_monitor/schedule_push/cal_fetal_movement/imei/
else if (key.Contains("health_monitor/schedule_push/cal_fetal_movement/imei/"))
{
//// 计算胎动数据
//var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
//var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
//if (isFetalHeartEnable)
//{
// // 检查胎心建模
// var fchr = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
// if (fchr != null)
// {
// // 获取孕妇心率数据接近最近2小时的数据
// var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
// var now = DateTime.Now;
// var ago2hrs = now.AddHours(-2);
// var phrRange = phr.Where(i => i.LastUpdate >= ago2hrs)
// .OrderByDescending(i => i.LastUpdate)
// .Select(i => i.LastUpdate)
// .ToList();

// if (phrRange.Count >= 2)
// {
// var duringMins = (phrRange.First() - phrRange.Last()).TotalMinutes;
// //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
// bool isInTimeRanges = IsNowInTimeRanges();

// //long.TryParse(watchConfig!["EDOC"]!.ToString(), out long edoc);
// var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());

// int pregnancyWeeks = (DateTime.Now -edoc.AddDays(-280)).Days / 7;
// if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
// {
// var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();

// var fetalMovementMapValue = isInTimeRanges? fetalMovementMap
// .Where(i =>
// i.PregnancyPeriod![0] <= pregnancyWeeks &&
// i.PregnancyPeriod[1] >= pregnancyWeeks)
// .Select(i=>i.MedianMovement)
// .FirstOrDefault()
// :
// fetalMovementMap
// .Where(i =>
// i.PregnancyPeriod![0] <= pregnancyWeeks &&
// i.PregnancyPeriod[1] >= pregnancyWeeks)
// .Select(i => i.InitialMovement)
// .FirstOrDefault()
// ;

// var fetalMovementValue = fetalMovementMapValue * duringMins * 2 / 120;
// // 四舍五入
// var fetalMovement= (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);

// var sampleTime = DateTimeUtil.ConvertToTimeStamp(DateTime.Now).ToString();
// // 告警上限阀值
// var upperAlarmThreshold = (int)watchConfig["upperAlarmThreshold"]!;
// // 告警下限阀值
// var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;

// GeneralParam param = new()
// {
// Filters = new List<QueryFilterCondition>
// {
// new ()
// {
// Key=nameof(HisGpsFetalimeiDel),
// Value=imeiDel,
// ValueType=QueryValueTypeEnum.String,
// Operator=QueryOperatorEnum.Equal
// }
// },
// OrderBys = new List<OrderByCondition>
// {
// new() {
// IsDesc=true,
// Key=nameof(HisGpsFetalHeartRate.CreateTime)
// }
// }
// };
// var frh = await _hisFetalHeartApiClient.GetFirstAsync(param, imeiDel.Substring(imeiDel.Length - 2), null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") }).ConfigureAwait(false);
// if (frh != null)
// {
// var fetalHeartRate = frh.HeartRate;
// var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
// // 推送到api/v1/open/OpenIot/SetFetalMovementConfig
// await _serviceIotApi.SetFetalMovementConfig(imeiDel, fetalMovement, sampleTime, isAbnormal);
// // 保存到MySQL数据库
// }
// }

// }

// }

// #region 定时计算胎动数据触发器 2小时后
// await SetIntervalTriggerAsync(key, imeiDel, 60 * 60 * 2);
// #endregion
//}

#region 胎动延时计算
var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
_logger.LogInformation($"触发胎动计算,设备配置{JsonConvert.SerializeObject(watchConfig)}");
@@ -477,41 +380,10 @@ namespace HealthMonitor.WebApi
// 判断是否有持续佩戴
if (phrRange.Count >= 2)
{
var duringMins = Math.Abs((phrRange.First() - statStartTime).TotalMinutes);
//在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
bool isInTimeRanges = IsLastUpdateInTimeRanges(phrRange.First());

int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
// 读取胎心数据
GeneralParam param = new()
{
var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();

var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
.Where(i =>
i.PregnancyPeriod![0] <= pregnancyWeeks &&
i.PregnancyPeriod[1] >= pregnancyWeeks)
.Select(i => i.MedianMovement)
.FirstOrDefault()
:
fetalMovementMap
.Where(i =>
i.PregnancyPeriod![0] <= pregnancyWeeks &&
i.PregnancyPeriod[1] >= pregnancyWeeks)
.Select(i => i.InitialMovement)
.FirstOrDefault()
;

var fetalMovementValue = (fetalMovementMapValue * duringMins * 2) / 120;
// 四舍五入
var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
// _logger.LogInformation($"{imeiDel} segmentCountFMIndex: {i} -- fetalMovementSampleTime:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")} -- statStartTime: {statStartTime} -- statEndTime: {statEndTime}-- isFetalMovementExisted: {isFetalMovementExisted} ");

_logger.LogInformation($"{imeiDel} 孕周:{pregnancyWeeks},胎动数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 原始胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{statStartTime}-{phrRange.First()}, 胎动计算值:{fetalMovementValue}, 胎动最终值:{fetalMovement} 已完成.");

// 读取胎心数据
GeneralParam param = new()
{
Filters = new List<QueryFilterCondition>
Filters = new List<QueryFilterCondition>
{
new ()
{
@@ -528,88 +400,132 @@ namespace HealthMonitor.WebApi
// Operator=QueryOperatorEnum.GreaterEqual
//},
},
OrderBys=new List<OrderByCondition>
{
new (){
OrderBys = new List<OrderByCondition>
{
new (){
IsDesc=true,
Key=nameof(HisGpsFetalHeartRate.SampleTime)
}
}
};
var fetalHeartRateIsAbnormal = 0;
var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
// 获取胎心数据状态与胎动数据状态一致
var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
//var feltalMovementIsAbnormal = 0;
// 推送到api/v1/open/OpenIot/SetFetalMovementConfig

await _serviceIotApi.SetFetalMovementConfig(imeiDel, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);

// 保存到MySQL数据库
HisGpsFetalMovement fm = new()
{
FetalMovementId = Guid.NewGuid().ToString("D"),
PersonId = commonPHR!.PersonId,
Serialno = imeiDel,
CreateTime = DateTime.Now,
IsAbnormal = feltalMovementIsAbnormal,
FetalMovementValue = fetalMovement,
SampleTime = fetalMovementSampleTime,
Method = 1,
IsDisplay = 1,
DeviceKey = commonPHR!.DeviceKey
};
await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);

var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(imeiDel).ConfigureAwait(false);
var fmMsgId = $"{imeiDel}-{fetalMovementSampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
var fmMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
// 胎动数据推送到第三方
var topic = "topic.push.third";
var fmThridMsg = new
{
messageId = fmMsgId,
topic = topic,
time = fmMsgTime,
data = new
{
imei = imeiDel,
value = fetalMovement,
isAbnormal= feltalMovementIsAbnormal,
type = "fetalMovement"
}
};
await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, 31, fmThridMsg).ConfigureAwait(false);
};
var fetalHeartRateIsAbnormal = 0;
var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });

// 胎心数据时间与胎动时间一致
var time = long.Parse(fhr.SampleTime.Length < 13 ? fhr.SampleTime.PadRight(13, '0') : fhr.SampleTime);
var fhrSampleTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(time);

// 胎心数据时间与胎动时间一致,最后一条胎心数据与胎动数据的小时差不大于2
if ((DateTime.Now.Hour - fhrSampleTime.Hour) <= 2)
{
var duringMins = Math.Abs((phrRange.First() - phrRange.Last()).TotalMinutes);
//在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
bool isInTimeRanges = IsLastUpdateInTimeRanges(phrRange.First());

// 胎动数据推送到微信
if (feltalMovementIsAbnormal != 0)
int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
{
topic = "topic.push.wx";
var fmMsg = new
var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();

var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
.Where(i =>
i.PregnancyPeriod![0] <= pregnancyWeeks &&
i.PregnancyPeriod[1] >= pregnancyWeeks)
.Select(i => i.MedianMovement)
.FirstOrDefault()
:
fetalMovementMap
.Where(i =>
i.PregnancyPeriod![0] <= pregnancyWeeks &&
i.PregnancyPeriod[1] >= pregnancyWeeks)
.Select(i => i.InitialMovement)
.FirstOrDefault()
;

var fetalMovementValue = (fetalMovementMapValue * duringMins * 2) / 120;
// 四舍五入
var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
// _logger.LogInformation($"{imeiDel} segmentCountFMIndex: {i} -- fetalMovementSampleTime:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")} -- statStartTime: {statStartTime} -- statEndTime: {statEndTime}-- isFetalMovementExisted: {isFetalMovementExisted} ");

_logger.LogInformation($"{imeiDel} 孕周:{pregnancyWeeks},胎动数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 原始胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{statStartTime}-{phrRange.First()}, 胎动计算值:{fetalMovementValue}, 胎动最终值:{fetalMovement} 已完成.");

// 获取胎心数据状态与胎动数据状态一致
//etalHeartRateIsAbnormal= fhr.IsAbnormal;
var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;

await _serviceIotApi.SetFetalMovementConfig(imeiDel, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);

// 保存到MySQL数据库
HisGpsFetalMovement fm = new()
{
FetalMovementId = Guid.NewGuid().ToString("D"),
PersonId = commonPHR!.PersonId,
Serialno = imeiDel,
CreateTime = DateTime.Now,
IsAbnormal = feltalMovementIsAbnormal,
FetalMovementValue = fetalMovement,
SampleTime = fetalMovementSampleTime,
Method = 1,
IsDisplay = 1,
DeviceKey = commonPHR!.DeviceKey
};
await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);

var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(imeiDel).ConfigureAwait(false);
var fmMsgId = $"{imeiDel}-{fetalMovementSampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
var fmMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
// 胎动数据推送到第三方
var topic = "topic.push.third";
var fmThridMsg = new
{
messageId = Guid.NewGuid().ToString("D"),
messageId = fmMsgId,
topic = topic,
time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss"),
time = fmMsgTime,
data = new
{
deviceId = device?.DeviceId,
imei = imeiDel,
alarmTypeId = 12,
alarmDeviceName = imeiDel,
alarmRemarks = JsonConvert.SerializeObject(new { fetalMovementValue = fetalMovement, isAbnormal = feltalMovementIsAbnormal }),
address = string.Empty,
deviceKey = device?.DeviceId
value = fetalMovement,
isAbnormal = feltalMovementIsAbnormal,
type = "fetalMovement"
}
};
await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, fmMsg).ConfigureAwait(false);
}
// 设置入库缓存记录
await _deviceCacheMgr.SetFetalMovementAsync(imeiDel, fetalMovementSampleTime, fm);
await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, 31, fmThridMsg).ConfigureAwait(false);

// 胎动数据推送到微信
if (feltalMovementIsAbnormal != 0)
{
topic = "topic.push.wx";
var fmMsg = new
{
messageId = Guid.NewGuid().ToString("D"),
topic = topic,
time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss"),
data = new
{
deviceId = device?.DeviceId,
imei = imeiDel,
alarmTypeId = 12,
alarmDeviceName = imeiDel,
alarmRemarks = JsonConvert.SerializeObject(new { fetalMovementValue = fetalMovement, isAbnormal = feltalMovementIsAbnormal }),
address = string.Empty,
deviceKey = device?.DeviceId
}
};
await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, fmMsg).ConfigureAwait(false);
}
// 设置入库缓存记录
await _deviceCacheMgr.SetFetalMovementAsync(imeiDel, fetalMovementSampleTime, fm);


}
else
{
_logger.LogWarning($"{imeiDel} 孕周 {pregnancyWeeks},超出胎动计算范围");
}
}
else
{
_logger.LogWarning($"{imeiDel} 孕周 {pregnancyWeeks},超出胎动计算范围");
_logger.LogWarning($"{imeiDel} 最后一条胎心数据与胎动数据的小时差大于2,不计算胎动数据");
}
}
else


Loading…
Cancel
Save