|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286 |
- using HealthMonitor.Common;
- using HealthMonitor.Common.helper;
- using HealthMonitor.Model.Config;
- using HealthMonitor.Model.Service.Mapper;
- using HealthMonitor.Service.Biz.db.Dto;
- using HealthMonitor.Util.Models;
- using Microsoft.EntityFrameworkCore.Metadata.Internal;
- using Microsoft.Extensions.Logging;
- using Microsoft.Extensions.Options;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using SqlSugar;
- using SqlSugar.DbConvert;
- using SqlSugar.TDengine;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- using System.Xml.Linq;
- using TDengineDriver;
- using TDengineDriver.Impl;
- using TDengineTMQ;
- using HealthMonitor.Service.Cache;
- using System.Text.RegularExpressions;
- using Etcdserverpb;
- using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
-
- namespace HealthMonitor.Service.Biz.db
- {
- public class TDengineService
- {
-
- private readonly ILogger<TDengineService> _logger;
- private readonly HttpHelper _httpHelper=default!;
- private readonly TDengineServiceConfig _configTDengineService;
- private readonly SqlSugarClient _clientSqlSugar;
- private readonly FhrPhrMapCacheManager _mgrFhrPhrMapCache;
- private readonly DeviceCacheManager _deviceCacheMgr;
-
- public TDengineService(ILogger<TDengineService> logger,
- IOptions<TDengineServiceConfig> configTDengineService,
- HttpHelper httpHelper,
- FhrPhrMapCacheManager fhrPhrMapCacheManager, DeviceCacheManager deviceCacheMgr
- )
- {
- _logger = logger;
- _configTDengineService = configTDengineService.Value;
- _httpHelper = httpHelper;
- _mgrFhrPhrMapCache = fhrPhrMapCacheManager;
- _deviceCacheMgr = deviceCacheMgr;
- _clientSqlSugar = new SqlSugarClient(new ConnectionConfig()
- {
- DbType = SqlSugar.DbType.TDengine,
- ConnectionString = $"Host={_configTDengineService.Host};Port={_configTDengineService.Port};Username={_configTDengineService.UserName};Password={_configTDengineService.Password};Database={_configTDengineService.DB};TsType=config_ns",
- IsAutoCloseConnection = true,
- AopEvents = new AopEvents
- {
- OnLogExecuting = (sql, p) =>
- {
- Console.WriteLine(SqlSugar.UtilMethods.GetNativeSql(sql, p));
- }
- },
- ConfigureExternalServices = new ConfigureExternalServices()
- {
- EntityService = (property, column) =>
- {
- if (column.SqlParameterDbType == null)
- {
- column.SqlParameterDbType = typeof(CommonPropertyConvert);
- }
- }
- },
- MoreSettings=new ConnMoreSettings()
- {
- PgSqlIsAutoToLower = false,
- PgSqlIsAutoToLowerCodeFirst = false,
- }
-
- });
-
- }
- public IntPtr Connection()
- {
-
- string host = _configTDengineService.Host;
- string user = _configTDengineService.UserName;
- string db = _configTDengineService.DB;
- short port = _configTDengineService.Port;
- string password = _configTDengineService.Password;
-
-
-
-
-
- IntPtr conn = TDengine.Connect(host, user, password, db, port);
-
-
- if (conn == IntPtr.Zero)
- {
- _logger.LogError($"连接 TDengine 失败....");
- }
- else
- {
- _logger.LogInformation($"连接 TDengine 成功....");
- }
- return conn;
- }
- public void ExecuteSQL(IntPtr conn, string sql)
- {
- IntPtr res = TDengine.Query(conn, sql);
-
- if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0))
- {
- Console.Write(sql + " failure, ");
-
- if (res != IntPtr.Zero)
- {
- Console.Write("reason:" + TDengine.Error(res));
- }
- }
- else
- {
- Console.Write(sql + " success, {0} rows affected", TDengine.AffectRows(res));
-
-
-
- TDengine.FreeResult(res);
- }
- }
-
- public void ExecuteQuerySQL(IntPtr conn, string sql)
- {
- IntPtr res = TDengine.Query(conn, sql);
-
- if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0))
- {
- Console.Write(sql + " failure, ");
-
- if (res != IntPtr.Zero)
- {
- Console.Write("reason:" + TDengine.Error(res));
- }
- }
- else
- {
- Console.Write(sql + " success, {0} rows affected", TDengine.AffectRows(res));
-
-
- List<TDengineDriver.TDengineMeta> resMeta = LibTaos.GetMeta(res);
- List<object> resData = LibTaos.GetData(res);
-
- foreach (var meta in resMeta)
- {
- _logger.LogInformation("\t|{meta.name} {meta.TypeName()} ({meta.size})\t|", meta.name, meta.TypeName(), meta.size);
- }
-
- for (int i = 0; i < resData.Count; i++)
- {
- _logger.LogInformation($"|{resData[i].ToString()} \t");
- if (((i + 1) % resMeta.Count == 0))
- {
- _logger.LogInformation("");
- }
- }
-
-
- TDengine.FreeResult(res);
- }
- }
-
- public void CheckRes(IntPtr conn, IntPtr res, String errorMsg)
- {
- if (TDengine.ErrorNo(res) != 0)
- {
- throw new Exception($"{errorMsg} since: {TDengine.Error(res)}");
- }
- }
-
- public void ExecuteInsertSQL(string sql)
- {
- var conn = Connection();
- try
- {
-
-
-
-
-
-
-
-
-
- _logger.LogInformation($"Insert SQL: {sql}");
- IntPtr res = TDengine.Query(conn, sql);
- CheckRes(conn, res, "failed to insert data");
- int affectedRows = TDengine.AffectRows(res);
- _logger.LogInformation("affectedRows {affectedRows}" , affectedRows);
- TDengine.FreeResult(res);
- }
- finally
- {
- TDengine.Close(conn);
- }
- }
-
- #region TDengine.Connector async query
- public void QueryCallback(IntPtr param, IntPtr taosRes, int code)
- {
- if (code == 0 && taosRes != IntPtr.Zero)
- {
- FetchRawBlockAsyncCallback fetchRowAsyncCallback = new FetchRawBlockAsyncCallback(FetchRawBlockCallback);
- TDengine.FetchRawBlockAsync(taosRes, fetchRowAsyncCallback, param);
- }
- else
- {
- _logger.LogInformation("async query data failed, failed code {code}",code);
- }
- }
-
- public void FetchRawBlockCallback(IntPtr param, IntPtr taosRes, int numOfRows)
- {
- if (numOfRows > 0)
- {
- _logger.LogInformation("{numOfRows} rows async retrieved", numOfRows);
- IntPtr pdata = TDengine.GetRawBlock(taosRes);
- List<TDengineMeta> metaList = TDengine.FetchFields(taosRes);
- List<object> dataList = LibTaos.ReadRawBlock(pdata, metaList, numOfRows);
-
- for (int i = 0; i < metaList.Count; i++)
- {
- _logger.LogInformation("{0} {1}({2}) \t|", metaList[i].name, metaList[i].type, metaList[i].size);
- }
- _logger.LogInformation("");
- for (int i = 0; i < dataList.Count; i++)
- {
- if (i != 0 && i % metaList.Count == 0)
- {
- _logger.LogInformation("{dataList[i]}\t|", dataList[i]);
- }
- _logger.LogInformation("{dataList[i]}\t|", dataList[i]);
- }
- TDengine.FetchRawBlockAsync(taosRes, FetchRawBlockCallback, param);
- }
- else
- {
- if (numOfRows == 0)
- {
- _logger.LogInformation("async retrieve complete.");
- }
- else
- {
- _logger.LogInformation("FetchRawBlockCallback callback error, error code {numOfRows}", numOfRows);
- }
- TDengine.FreeResult(taosRes);
- }
- }
-
- public void ExecuteQueryAsync(string sql)
- {
- var conn = Connection();
- QueryAsyncCallback queryAsyncCallback = new QueryAsyncCallback(QueryCallback);
- TDengine.QueryAsync(conn, sql, queryAsyncCallback, IntPtr.Zero);
- }
-
-
-
-
-
-
-
-
-
-
- public Aggregate GetAggregateValue(string field, string tbName, string? condition)
- {
- List<int> data = new();
-
- var sql = $"SELECT MAX({field}), MIN({field}) FROM {_configTDengineService.DB}.{tbName} WHERE {condition}";
-
- var conn = Connection();
- try
- {
- IntPtr res = TDengine.Query(conn, sql);
-
- if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0))
- {
- Console.Write(sql + " failure, ");
-
- if (res != IntPtr.Zero)
- {
- Console.Write("reason:" + TDengine.Error(res));
- }
- }
- else
- {
- Console.Write(sql + " success, {0} rows affected", TDengine.AffectRows(res));
-
-
- List<TDengineMeta> resMeta = LibTaos.GetMeta(res);
- List<object> resData = LibTaos.GetData(res);
-
- foreach (var meta in resMeta)
- {
- Console.Write($"\t|{meta.name} {meta.TypeName()} ({meta.size})\t|");
- }
- resData.ForEach(x => data.Add(SafeType.SafeInt(x)));
-
-
- TDengine.FreeResult(res);
- }
- }
- finally
- {
- TDengine.Close(conn);
- }
-
-
- return new Aggregate
- {
- Max = data.Count.Equals(0) ? 0 : data[0],
- Min = data.Count.Equals(0) ? 0 : data[1],
- };
- }
-
- public int GetAvgExceptMaxMinValue(string field, string tbName, string? condition)
- {
- List<int> data = new();
- var sql = $"SELECT MAX({field}), MIN({field}) FROM {_configTDengineService.DB}.{tbName} WHERE {condition}";
-
- var aggregate= GetAggregateValue(field, tbName, condition);
-
- var sqlAvg = $"SELECT AVG({field}) FROM {_configTDengineService.DB}.{tbName} WHERE {condition} AND {field} < {aggregate.Max} and {field} > {aggregate.Min}";
-
- var conn = Connection();
-
- try
- {
- IntPtr res = TDengine.Query(conn, sqlAvg);
-
- if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0))
- {
- Console.Write(sqlAvg + " failure, ");
-
- if (res != IntPtr.Zero)
- {
- Console.Write("reason:" + TDengine.Error(res));
- }
- }
- else
- {
- Console.Write(sqlAvg + " success, {0} rows affected", TDengine.AffectRows(res));
-
-
- List<TDengineMeta> resMeta = LibTaos.GetMeta(res);
- List<object> resData = LibTaos.GetData(res);
-
- foreach (var meta in resMeta)
- {
- Console.Write($"\t|{meta.name} {meta.TypeName()} ({meta.size})\t|");
- }
- resData.ForEach(x => data.Add(SafeType.SafeInt(x)));
-
-
- TDengine.FreeResult(res);
- }
- }
- finally
- {
- TDengine.Close(conn);
- }
-
-
- return data.Count.Equals(0) ? 0 : data[0];
- }
- #endregion
-
- #region RestAPI
-
- public async Task<string?> ExecuteQuerySQLRestResponse(string sql)
- {
- var url = $"http://{_configTDengineService.Host}:{_configTDengineService.RestPort}/rest/sql/{_configTDengineService.DB}";
- List<KeyValuePair<string, string>> headers = new()
- {
- new KeyValuePair<string, string>("Authorization", "Basic " + _configTDengineService.Token)
- };
- var result = await _httpHelper.HttpToPostAsync(url, sql, headers).ConfigureAwait(false);
- return result;
- }
-
- public async Task<string?> ExecuteSelectRestResponseAsync( string tbName, string condition="1", string field = "*")
- {
- var url = $"http://{_configTDengineService.Host}:{_configTDengineService.RestPort}/rest/sql/{_configTDengineService.DB}";
- var sql = $"SELECT {field} FROM {_configTDengineService.DB}.{tbName} WHERE {condition}";
-
- List<KeyValuePair<string, string>> headers = new()
- {
- new KeyValuePair<string, string>("Authorization", "Basic " + _configTDengineService.Token)
- };
- _logger.LogInformation($"{nameof(ExecuteSelectRestResponseAsync)} --- SQL 语句执行 {sql}");
- var result = await _httpHelper.HttpToPostAsync(url, sql, headers).ConfigureAwait(false);
- return result;
- }
- public async Task<bool> GernalRestSql(string sql)
- {
-
-
- var url = $"http://{_configTDengineService.Host}:{_configTDengineService.RestPort}/rest/sql/{_configTDengineService.DB}";
- List<KeyValuePair<string, string>> headers = new()
- {
- new KeyValuePair<string, string>("Authorization", "Basic " + _configTDengineService.Token)
- };
- var result = await _httpHelper.HttpToPostAsync(url, sql, headers).ConfigureAwait(false);
- var res = JsonConvert.DeserializeObject<TDengineRestResBase>(result!);
- if (result != null)
- {
- if (res?.Code == 0)
- {
- _logger.LogInformation($"{nameof(GernalRestSql)},SQL 语句执行成功|{sql}");
- return true;
- }
- else
- {
- _logger.LogWarning($"{nameof(GernalRestSql)},SQL 语句执行失败||{sql}");
- return false;
- }
- }
- else
- {
- _logger.LogError($"{nameof(GernalRestSql)},TDengine 服务器IP:{_configTDengineService.Host} 错误,请联系运维人员");
- return false;
- }
-
- }
-
- public async Task<string?> GernalRestSqlResTextAsync(string sql)
- {
- _logger.LogInformation($"执行 SQL: {nameof(GernalRestSqlResTextAsync)}--{sql}");
- var url = $"http://{_configTDengineService.Host}:{_configTDengineService.RestPort}/rest/sql/{_configTDengineService.DB}";
- List<KeyValuePair<string, string>> headers = new()
- {
- new KeyValuePair<string, string>("Authorization", "Basic " + _configTDengineService.Token)
- };
- var result = await _httpHelper.HttpToPostAsync(url, sql, headers).ConfigureAwait(false);
- return result;
- }
-
-
-
- #endregion
-
-
-
-
-
-
-
-
-
- public static decimal AverageAfterRemovingOneMinMaxRef(List<int> collection, int max, int min,int refValue)
- {
- collection.Remove(max);
- collection.Remove(min);
- collection.RemoveAll(_ => _ > refValue);
- if (collection.Count < 2)
- {
- throw new ArgumentException($"数据集{collection.ToArray()},去掉一个最大值 {max}和一个最小值{min},异常值(大于标定值{refValue}),后数据值不足");
- }
-
- return (decimal)collection.Average(x => x);
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
-
-
-
-
-
-
-
- public decimal[] AverageAfterRemovingOneMinMaxRef(int systolicRefValue, ParseTDengineRestResponse<BloodPressureModel>? hmBpParser)
- {
- var sortedList = hmBpParser?.Select(i => i)
- .Where(i => i.IsDisplay.Equals(true))
- .OrderByDescending(i => i.SystolicValue)
- .ThenByDescending(i => i.DiastolicValue)
- .ToList();
- _logger.LogInformation($"计算时间段排列数据集:{JsonConvert.SerializeObject(sortedList)}");
-
- var trimmedList = sortedList?
- .Skip(1)
- .Take(sortedList.Count - 2)
- .ToList();
-
- _logger.LogInformation($"计算去除最大值和最小值各一个数据集:{JsonConvert.SerializeObject(trimmedList)}");
-
- var filteredList = trimmedList?.Where(bp => bp.SystolicValue < SafeType.SafeInt(systolicRefValue!)).ToList();
-
- _logger.LogInformation($"计算除异常值个数据集:{JsonConvert.SerializeObject(filteredList)}");
-
- if (filteredList?.Count < 2)
- {
-
-
- return new decimal[] { 0M, 0M };
- }
- var systolicAvg = filteredList?.Select(bp => bp.SystolicValue).Average();
- var diastolicAvg = filteredList?.Select(bp => bp.DiastolicValue).Average();
-
- return new decimal[] { (decimal)systolicAvg!, (decimal)diastolicAvg! };
- }
-
-
-
-
-
-
-
- public decimal[] AverageAfterRemovingOneMinMaxRef(ParseTDengineRestResponse<BloodPressureModel>? hmBpParser)
- {
- var sortedList = hmBpParser?.Select(i => i)
- .Where(i => i.IsDisplay.Equals(true))
- .OrderByDescending(i => i.SystolicValue)
- .ThenByDescending(i => i.DiastolicValue)
- .ToList();
- _logger.LogInformation($"计算时间段排列数据集:{JsonConvert.SerializeObject(sortedList)}");
-
- var trimmedList = sortedList?
- .Skip(1)
- .Take(sortedList.Count - 2)
- .ToList();
-
- _logger.LogInformation($"计算去除最大值和最小值各一个数据集:{JsonConvert.SerializeObject(trimmedList)}");
-
- var filteredList = trimmedList?.ToList();
-
- _logger.LogInformation($"计算除异常值个数据集:{JsonConvert.SerializeObject(filteredList)}");
-
- if (filteredList?.Count < 2)
- {
-
-
- return new decimal[] { 0M, 0M };
- }
- var systolicAvg = filteredList?.Select(bp => bp.SystolicValue).Average();
- var diastolicAvg = filteredList?.Select(bp => bp.DiastolicValue).Average();
-
- return new decimal[] { (decimal)systolicAvg!, (decimal)diastolicAvg! };
- }
-
- #region SqlSugarClient
-
-
-
-
-
-
-
-
-
-
-
- public async Task InsertAsync<T>(string tbName, T model)
- {
- var stbName = typeof(T)
- .GetCustomAttribute<STableAttribute>()?
- .STableName;
-
- if (stbName == null)
- {
- throw new InvalidOperationException($"STableAttribute not found on {nameof(T)} class.");
- }
- var tailNo = typeof(T).GetProperty("SerialTailNumber")?.GetValue(model)?.ToString();
-
- if (string.IsNullOrEmpty(tailNo))
- {
- throw new InvalidOperationException($"SerialNumberAttribute not found on {nameof(T)} class.");
- }
- var tbFullName = $"{tbName}_{tailNo}";
- await _clientSqlSugar.Ado.ExecuteCommandAsync($"create table IF NOT EXISTS {tbFullName} using {stbName} tags('{tailNo}')");
-
-
- _clientSqlSugar.InsertableByObject(model).AS(tbFullName).ExecuteCommand();
- }
-
- public Task<T> GetLastAsync<T>() where T : class
- {
- var tableName = typeof(T)
- .GetCustomAttribute<STableAttribute>()?
- .STableName;
-
- var parameter = Expression.Parameter(typeof(T), "x");
- var property = Expression.Property(parameter, "Timestamp");
- var lambda = Expression.Lambda<Func<T, object>>(Expression.Convert(property, typeof(object)), parameter);
-
-
- var first = _clientSqlSugar
- .Queryable<T>()
- .AS(tableName)
- .OrderByDescending(lambda).FirstAsync();
- return first;
- }
-
- public Task<T> GetLastAsync<T>(string serialNo) where T : class
- {
- var tableName = typeof(T)
- .GetCustomAttribute<STableAttribute>()?
- .STableName;
-
- var parameter = Expression.Parameter(typeof(T), "x");
- var timestampProperty = Expression.Property(parameter, "Timestamp");
- var timestampLambda = Expression.Lambda<Func<T, object>>(Expression.Convert(timestampProperty, typeof(object)), parameter);
-
-
- var serialNoProperty = Expression.Property(parameter, "SerialNumber");
- var serialNoConstant = Expression.Constant(serialNo);
- var equalExpression = Expression.Equal(serialNoProperty, serialNoConstant);
- var serialNoLambda = Expression.Lambda<Func<T, bool>>(equalExpression, parameter);
-
- var first = _clientSqlSugar
- .Queryable<T>()
- .AS(tableName)
- .Where(serialNoLambda)
- .OrderByDescending(timestampLambda).FirstAsync();
- return first;
- }
-
- public async Task<List<T>> GetBySerialNoAsync<T>(string serialNo) where T : class
- {
- var tableName = typeof(T)
- .GetCustomAttribute<STableAttribute>()?
- .STableName;
-
- var parameter = Expression.Parameter(typeof(T), "x");
- var timestampProperty = Expression.Property(parameter, "Timestamp");
- var timestampLambda = Expression.Lambda<Func<T, object>>(Expression.Convert(timestampProperty, typeof(object)), parameter);
-
-
- var serialNoProperty = Expression.Property(parameter, "SerialNumber");
- var serialNoConstant = Expression.Constant(serialNo);
- var equalExpression = Expression.Equal(serialNoProperty, serialNoConstant);
- var serialNoLambda = Expression.Lambda<Func<T, bool>>(equalExpression, parameter);
-
- var res = await _clientSqlSugar
- .Queryable<T>()
- .AS(tableName)
- .Where(serialNoLambda)
- .OrderByDescending(timestampLambda).ToListAsync();
- return res;
- }
-
- public async Task<List<T>> GetBySerialNoAsync<T>(string serialNo, int days) where T : class
- {
- var tableName = typeof(T)
- .GetCustomAttribute<STableAttribute>()?
- .STableName;
-
-
- var parameter = Expression.Parameter(typeof(T), "x");
- var timestampProperty = Expression.Property(parameter, "Timestamp");
- var timestampLambda = Expression.Lambda<Func<T, object>>(Expression.Convert(timestampProperty, typeof(object)), parameter);
-
-
- var serialNoProperty = Expression.Property(parameter, "SerialNumber");
- var serialNoConstant = Expression.Constant(serialNo);
- var equalExpression = Expression.Equal(serialNoProperty, serialNoConstant);
-
-
- var daysAgo = DateTime.Now.AddDays(-days);
- var daysAgoConstant = Expression.Constant(daysAgo, typeof(DateTime));
- var greaterThanExpression = Expression.GreaterThan(timestampProperty, daysAgoConstant);
-
-
- var combinedExpression = Expression.AndAlso(equalExpression, greaterThanExpression);
- var combinedLambda = Expression.Lambda<Func<T, bool>>(combinedExpression, parameter);
-
- var res = await _clientSqlSugar
- .Queryable<T>()
- .AS(tableName)
- .Where(combinedLambda)
- .OrderByDescending(timestampLambda).ToListAsync();
-
- return res;
- }
-
-
- public async Task DeleteAllBySerialNoCMDAsync<T>(string serialNo) where T : class
- {
- var records = await GetBySerialNoAsync<T>(serialNo, 365);
-
- var stbName = typeof(T)
- .GetCustomAttribute<STableAttribute>()?
- .STableName;
-
- var tasks = records.Select(async r =>
- {
- Type modelType = typeof(T);
- PropertyInfo timestampProperty = typeof(T).GetProperty("Timestamp")!;
- object timestampValue = timestampProperty.GetValue(r)!;
- var ts = ((DateTime)timestampValue);
- var startTimestamp = ts.ToString("yyyy-MM-dd HH:mm:ss.fff");
- var endTimestamp = ts.AddMilliseconds(1).ToString("yyyy-MM-dd HH:mm:ss.fff");
- var sql = $"DELETE FROM {stbName} WHERE ts >= '{startTimestamp}' AND ts < '{endTimestamp}'";
- var res= await _clientSqlSugar.Ado.ExecuteCommandAsync(sql);
- Console.WriteLine(res);
- });
- await Task.WhenAll(tasks);
- }
-
-
- #endregion
-
- #region 胎心算法
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public async Task<PregnancyCommonHeartRateModel?> InitPregnancyCommonHeartRateModeAsync(string serialNo, int days = 7, int percentage = 90, int highFreqSampleInterval=0)
- {
- var tableName = typeof(PregnancyHeartRateModel)
- .GetCustomAttribute<STableAttribute>()?
- .STableName;
-
- var daysAgo = DateTime.Now.AddDays(-days);
- var collection = await _clientSqlSugar
- .Queryable<PregnancyHeartRateModel>()
- .AS(tableName)
- .Where(i => i.SerialNumber.Equals(serialNo))
- .Where(i => i.LastUpdate > daysAgo)
- .OrderByDescending(i => i.LastUpdate)
- .ToArrayAsync();
-
-
- var filteredCollection = new List<PregnancyHeartRateModel>();
- PregnancyHeartRateModel? previousItem = null;
-
-
-
-
-
-
-
-
-
-
-
- foreach (var item in collection)
- {
- if (previousItem!=null)
- {
- var timeDiff = (previousItem.LastUpdate - item.LastUpdate).TotalSeconds;
- Console.WriteLine($"previousItem:{previousItem.PregnancyHeartRate} -- item:{previousItem.PregnancyHeartRate} timeDiff:{timeDiff}--highFreqSampleInterval:{highFreqSampleInterval}");
- if (timeDiff >= highFreqSampleInterval)
- {
- filteredCollection.Add(item);
- }
- }
- previousItem = item;
- }
-
-
- if (filteredCollection.Count < 30)
- {
- _logger.LogInformation($"{serialNo} 心率数据不足,无法计算其众数");
- return null;
- }
-
-
- var res = filteredCollection
- .Select(i => i.PregnancyHeartRate).ToList();
-
-
-
-
-
-
- var listRes = filteredCollection.Select(i => new { last_update=i.LastUpdate.ToString("yyyy-MM-dd HH:mm:ss"),heart_rate=i.PregnancyHeartRate }).ToList();
-
-
- _logger.LogInformation($"{serialNo} 去除高频数据后的数据集: " + string.Join(", ", res));
-
- #region 计算众数
- var mode = res.GroupBy(n => n)
- .OrderByDescending(g => g.Count())
- .First()
- .Key;
-
- Console.WriteLine("众数是: " + mode);
-
-
- var maxCount = res.GroupBy(n => n)
- .Max(g => g.Count());
-
- var modes = res.GroupBy(n => n)
- .Where(g => g.Count() == maxCount)
- .Select(g => g.Key)
- .ToList();
-
- if (modes.Count > 1)
- {
-
- double average = res.Average();
- Console.WriteLine("平均值是: " + average);
-
-
- double median;
- int count = res.Count;
- var sortedRes = res.OrderBy(n => n).ToList();
- if (count % 2 == 0)
- {
-
- median = (sortedRes[count / 2 - 1] + sortedRes[count / 2]) / 2.0;
- }
- else
- {
-
- median = sortedRes[count / 2];
- }
-
- _logger.LogInformation($"{serialNo} 中位数是: " + median);
-
-
-
-
-
- var closestToMedian = modes.OrderBy(m => Math.Abs(m - median)).First();
- _logger.LogInformation($"{serialNo} 最接近中位数的众数是: " + closestToMedian);
- mode = closestToMedian;
- }
- #endregion
-
-
- int requiredCount = (int)(res.Count * 0.9);
-
-
- var closestToModeData = res.OrderBy(n => Math.Abs(n - mode))
- .Take(requiredCount)
- .ToList();
-
-
- _logger.LogInformation($"{serialNo} 新数据集: " + string.Join(", ", closestToModeData));
- _logger.LogInformation($"{serialNo} 新数据集的数量: {closestToModeData.Count},最大值: {closestToModeData.Max()},最小值 {closestToModeData.Min()},原始最大值: {res.Max()},原始最小值 {res.Min()}" );
-
- var fhrMap = _mgrFhrPhrMapCache.GetHeartRatesMap();
- var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(serialNo, "0067");
- if (watchConfig == null)
- {
- return null;
- }
-
-
-
- var edoc = DateTimeUtil.ToDateTime(watchConfig["EDOC"]!.ToString());
- int pregnancyWeek = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
-
- _logger.LogInformation($"IMEI {serialNo},EDOC:{edoc},NOW:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},SinceNOW:{edoc.AddDays(-280).ToString("yyyy-MM-dd HH:mm:ss")},怀孕周数 {pregnancyWeek}");
-
- float statMaxValueFprCoefficient = 0f;
- float statMinValueFprCoefficient = 0f;
- float StatModeAvgFprCoefficient = 0f;
-
- if (pregnancyWeek >= 12 && pregnancyWeek <= 45)
- {
- var map = fhrMap
- .Where(i =>
- i.PregnancyPeriod![0] <= pregnancyWeek &&
- i.PregnancyPeriod[1] >= pregnancyWeek &&
- i.PregnancyHeartRateRange![0] <= mode &&
- i.PregnancyHeartRateRange[1] >= mode)
- .FirstOrDefault();
-
- if (map != null)
- {
- statMaxValueFprCoefficient = (float)Math.Round((decimal)map.FetalHeartRateRange![1] / res.Max(), 3);
- statMinValueFprCoefficient = (float)Math.Round((decimal)map.FetalHeartRateRange[0] / res.Min(), 3);
- StatModeAvgFprCoefficient = (float)Math.Round((decimal)map.FetalHeartRateAverage / mode, 3);
- }
- }
-
- var maxValue = closestToModeData.Max();
- var minValue = closestToModeData.Min();
-
- if ((maxValue >= 60 && maxValue <= 100) && (minValue >= 60 && minValue <= 100))
- {
- minValue = 60;
- maxValue = 100;
- }
-
- return new PregnancyCommonHeartRateModel()
- {
- Timestamp = DateTime.Now,
- PersonId = collection.First().DeviceKey,
- DeviceKey = collection.First().DeviceKey,
- SerialNumber = collection.First().SerialNumber,
- Mode = mode,
- Percentage = percentage,
- MaxValue = maxValue,
- MinValue = minValue,
- OriginalMaxValue = res.Max(),
- OriginalMinValue = res.Min(),
- CreateTime = DateTime.Now,
- StatStartTime = collection.OrderBy(i => i.Timestamp).Select(i => i.Timestamp).First(),
- StatEndTime = collection.OrderBy(i => i.Timestamp).Select(i => i.Timestamp).Last(),
- StatMaxValueFprCoefficient = statMaxValueFprCoefficient,
- StatMinValueFprCoefficient = statMinValueFprCoefficient,
- StatModeAvgFprCoefficient = StatModeAvgFprCoefficient,
- Remark = string.Empty,
- SerialTailNumber = serialNo.Substring(serialNo.Length - 2)
- };
-
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #endregion
- }
- }
|