|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600 |
- 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 System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Xml.Linq;
- using TDengineDriver;
- using TDengineDriver.Impl;
-
- namespace HealthMonitor.Service.Biz.db
- {
- public class TDengineService
- {
-
- private readonly ILogger<TDengineService> _logger;
- private readonly HttpHelper _httpHelper=default!;
- private readonly TDengineServiceConfig _configTDengineService;
- public TDengineService(ILogger<TDengineService> logger,
- IOptions<TDengineServiceConfig> configTDengineService,
- HttpHelper httpHelper
- )
- {
- _logger = logger;
- _configTDengineService = configTDengineService.Value;
- _httpHelper = httpHelper;
- }
- 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! };
- }
- }
- }
|