You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 4 месеца
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 4 месеца
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 4 месеца
преди 1 година
преди 4 месеца
преди 1 година
преди 1 година
преди 1 година
преди 4 месеца
преди 4 месеца
преди 4 месеца
преди 4 месеца
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 5 месеца
преди 1 година
преди 4 месеца
преди 4 месеца
преди 4 месеца
преди 4 месеца
преди 3 месеца
преди 4 месеца
преди 1 година
преди 1 година
преди 3 месеца
преди 4 месеца
преди 4 месеца
преди 3 месеца
преди 4 месеца
преди 4 месеца
преди 1 година
преди 1 година
преди 5 месеца
преди 1 година
преди 1 година
преди 1 година
преди 4 месеца
преди 4 месеца
преди 3 месеца
преди 4 месеца
преди 4 месеца
преди 3 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 5 месеца
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 1 година
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 5 месеца
преди 5 месеца
преди 5 месеца
преди 5 месеца
преди 5 месеца
преди 3 месеца
преди 5 месеца
преди 3 месеца
преди 5 месеца
преди 3 месеца
преди 4 месеца
преди 3 месеца
преди 4 месеца
преди 4 месеца
преди 3 месеца
преди 4 месеца
преди 3 месеца
преди 5 месеца
преди 5 месеца
преди 5 месеца
преди 3 месеца
преди 5 месеца
преди 3 месеца
преди 5 месеца
преди 3 месеца
преди 5 месеца
преди 3 месеца
преди 5 месеца
преди 3 месеца
преди 5 месеца
преди 3 месеца
преди 5 месеца
преди 5 месеца
преди 5 месеца
преди 5 месеца
преди 4 месеца
преди 4 месеца
преди 5 месеца
преди 3 месеца
преди 4 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 2 месеца
преди 2 месеца
преди 3 месеца
преди 4 месеца
преди 3 месеца
преди 4 месеца
преди 4 месеца
преди 3 месеца
преди 4 месеца
преди 4 месеца
преди 3 месеца
преди 4 месеца
преди 4 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 4 месеца
преди 3 месеца
преди 4 месеца
преди 4 месеца
преди 3 месеца
преди 4 месеца
преди 3 месеца
преди 3 месеца
преди 4 месеца
преди 4 месеца
преди 3 месеца
преди 4 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 4 месеца
преди 4 месеца
преди 4 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 4 месеца
преди 3 месеца
преди 4 месеца
преди 4 месеца
преди 4 месеца
преди 3 месеца
преди 4 месеца
преди 4 месеца
преди 3 месеца
преди 4 месеца
преди 2 месеца
преди 2 месеца
преди 2 месеца
преди 2 месеца
преди 2 месеца
преди 2 месеца
преди 2 месеца
преди 2 месеца
преди 2 месеца
преди 3 месеца
преди 4 месеца
преди 5 месеца
преди 5 месеца
преди 5 месеца
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 1 година
преди 5 месеца
преди 1 година
преди 3 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 5 месеца
преди 1 година
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 1 година
преди 5 месеца
преди 3 месеца
преди 5 месеца
преди 4 месеца
преди 4 месеца
преди 4 месеца
преди 2 месеца
преди 4 месеца
преди 4 месеца
преди 4 месеца
преди 2 месеца
преди 4 месеца
преди 4 месеца
преди 4 месеца
преди 4 месеца
преди 4 месеца
преди 4 месеца
преди 2 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 2 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 2 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 2 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 2 месеца
преди 3 месеца
преди 2 месеца
преди 2 месеца
преди 2 месеца
преди 2 месеца
преди 2 месеца
преди 2 месеца
преди 1 месец
преди 1 месец
преди 2 месеца
преди 2 месеца
преди 2 месеца
преди 2 месеца
преди 1 месец
преди 2 месеца
преди 1 месец
преди 2 месеца
преди 1 месец
преди 2 месеца
преди 1 месец
преди 2 месеца
преди 1 месец
преди 2 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 3 месеца
преди 1 година
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266
  1. using dotnet_etcd;
  2. using Etcdserverpb;
  3. using Google.Protobuf.WellKnownTypes;
  4. using HealthMonitor.Common;
  5. using HealthMonitor.Common.helper;
  6. using HealthMonitor.Core.Common.Extensions;
  7. using HealthMonitor.Core.Pipeline;
  8. using HealthMonitor.Model.Config;
  9. using HealthMonitor.Model.Service;
  10. using HealthMonitor.Model.Service.Mapper;
  11. using HealthMonitor.Service.Biz;
  12. using HealthMonitor.Service.Biz.db;
  13. using HealthMonitor.Service.Cache;
  14. using HealthMonitor.Service.Etcd;
  15. using HealthMonitor.Service.MessageQueue;
  16. using HealthMonitor.Service.Sub;
  17. using Microsoft.AspNetCore.Mvc.RazorPages;
  18. using Microsoft.EntityFrameworkCore.Metadata;
  19. using Microsoft.EntityFrameworkCore.Metadata.Internal;
  20. using Microsoft.Extensions.Options;
  21. using NetTaste;
  22. using Newtonsoft.Json;
  23. using Newtonsoft.Json.Linq;
  24. using System;
  25. using System.Reflection;
  26. using System.Text.RegularExpressions;
  27. using System.Threading.Channels;
  28. using TDengineDriver;
  29. using TDengineTMQ;
  30. using TelpoDataService.Util.Clients;
  31. using TelpoDataService.Util.Entities.GpsCard;
  32. using TelpoDataService.Util.Entities.GpsLocationHistory;
  33. using TelpoDataService.Util.Models;
  34. using TelpoDataService.Util.QueryObjects;
  35. namespace HealthMonitor.WebApi
  36. {
  37. public class Worker : BackgroundService
  38. {
  39. private readonly ILogger<Worker> _logger;
  40. private readonly IServiceProvider _services;
  41. private readonly TDengineDataSubcribe _tdEngineDataSubcribe;
  42. private readonly PackageProcess _processor;
  43. private readonly TDengineService _serviceTDengine;
  44. private readonly EtcdService _serviceEtcd;
  45. private readonly HttpHelper _httpHelper = default!;
  46. private readonly IotApiService _serviceIotApi;
  47. private readonly BoodPressResolverConfig _configBoodPressResolver;
  48. private readonly BloodPressReferenceValueCacheManager _bpRefValCacheManager;
  49. private readonly PersonCacheManager _personCacheMgr;
  50. private readonly DeviceCacheManager _deviceCacheMgr;
  51. private readonly FetalMovementNormalValueRangeCacheManager _mgrFetalMovementNormalValueRangeCache;
  52. private readonly GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> _hisFetalHeartApiClient;
  53. private readonly GpsLocationHistoryAccessorClient<HisGpsFetalMovement> _hisFetalMovementApiClient;
  54. private readonly GpsLocationHistoryAccessorClient<HisGpsPsychResult> _hisPsychResultApiClient;
  55. private readonly MqProcessLogic _serviceMqProcess;
  56. private CancellationTokenSource _tokenSource = default!;
  57. private static int INTERVAL_FHR = 15;
  58. public Worker(ILogger<Worker> logger, IServiceProvider services, PersonCacheManager personCacheMgr,
  59. BloodPressReferenceValueCacheManager bpRefValCacheManager, IotApiService IotApiService,
  60. IOptions<BoodPressResolverConfig> optionBoodPressResolver, PackageProcess processor,
  61. TDengineDataSubcribe tdEngineDataSubcribe, TDengineService serviceDengine,
  62. GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> hisFetalHeartApiClient,
  63. GpsLocationHistoryAccessorClient<HisGpsFetalMovement> hisFetalMovementApiClient,
  64. GpsLocationHistoryAccessorClient<HisGpsPsychResult> hisGpsPsychResultApiClient,
  65. FetalMovementNormalValueRangeCacheManager fetalMovementNormalValueRangeCacheMgr, MqProcessLogic serviceMqProcess,
  66. HttpHelper httpHelper, EtcdService serviceEtcd, DeviceCacheManager deviceCacheMgr)
  67. {
  68. _logger = logger;
  69. _tdEngineDataSubcribe = tdEngineDataSubcribe;
  70. _services = services;
  71. _serviceIotApi = IotApiService;
  72. _processor = processor;
  73. _serviceEtcd = serviceEtcd;
  74. _serviceTDengine = serviceDengine;
  75. _httpHelper = httpHelper;
  76. _configBoodPressResolver = optionBoodPressResolver.Value;
  77. _bpRefValCacheManager = bpRefValCacheManager;
  78. _personCacheMgr = personCacheMgr;
  79. _deviceCacheMgr = deviceCacheMgr;
  80. _hisFetalHeartApiClient = hisFetalHeartApiClient;
  81. _hisFetalMovementApiClient = hisFetalMovementApiClient;
  82. _hisPsychResultApiClient = hisGpsPsychResultApiClient;
  83. _serviceMqProcess = serviceMqProcess;
  84. _mgrFetalMovementNormalValueRangeCache = fetalMovementNormalValueRangeCacheMgr;
  85. }
  86. public override Task StartAsync(CancellationToken cancellationToken)
  87. {
  88. //_logger.LogInformation("------StartAsync");
  89. _tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  90. return base.StartAsync(cancellationToken);
  91. }
  92. public override Task StopAsync(CancellationToken cancellationToken)
  93. {
  94. //_logger.LogInformation("------StopAsync");
  95. _tokenSource.Cancel(); //停止工作线程
  96. return base.StopAsync(cancellationToken);
  97. }
  98. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  99. {
  100. var tasks = new[]
  101. {
  102. Task.Run(async () =>
  103. {
  104. _logger.LogInformation("解析器启动");
  105. while (!stoppingToken.IsCancellationRequested)
  106. {
  107. await _processor.ResolveAsync().ConfigureAwait(false);
  108. }
  109. }, stoppingToken),
  110. Task.Run(() =>
  111. {
  112. _logger.LogInformation("TDengine 订阅启动");
  113. while (!stoppingToken.IsCancellationRequested)
  114. {
  115. _tdEngineDataSubcribe.BeginListen(stoppingToken);
  116. }
  117. }, stoppingToken),
  118. Task.Run(() =>
  119. _serviceEtcd.WacthKeysWithPrefixResponseAsync("health_monitor/schedule_push", WatchEvents),
  120. stoppingToken)
  121. };
  122. await Task.WhenAll(tasks);
  123. }
  124. private void WatchEvents(WatchResponse response)
  125. {
  126. response.Events.ToList<Mvccpb.Event>().ForEach(async e =>
  127. {
  128. try
  129. {
  130. switch (e.Type.ToString())
  131. {
  132. case "Put":
  133. // 获取时间点计算TTL
  134. Console.BackgroundColor = ConsoleColor.Blue;
  135. Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  136. Console.BackgroundColor = ConsoleColor.Black;
  137. break;
  138. case "Delete":
  139. // TTL到了重新计算TTL,下发
  140. //Console.BackgroundColor = ConsoleColor.Green;
  141. //Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  142. // var key = $"health_monitor/schedule_push/imei/{bp.Serialno}";
  143. var key = e.Kv.Key.ToStringUtf8();
  144. //var imeiDel = key.Split('/')[^1];
  145. var imeiDel = ExtractImei(key);
  146. if (string.IsNullOrEmpty(imeiDel))
  147. {
  148. _logger.LogWarning("定时器不能抽取imei");
  149. return;
  150. }
  151. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  152. if (string.IsNullOrWhiteSpace(schedule_push))
  153. {
  154. // 胎心数据建模
  155. if (key.Contains("pregnancy_heart_rate"))
  156. {
  157. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = $"MODE-{imeiDel}-{DateTime.Now.ToString("yyyyMMddHHmmss")}" }))
  158. {
  159. #region 胎心数据建模
  160. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  161. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  162. if (isFetalHeartEnable)
  163. {
  164. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容
  165. //var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! + 5;
  166. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容(最小highFreqSampleInterval=60)
  167. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! + 5 : 60;
  168. // 处理孕妇业务,计算一般心率并下发
  169. var commonPHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(imeiDel, highFreqSampleInterval: highFreqSampleInterval);
  170. if (commonPHR == null)
  171. {
  172. // 建模中
  173. var flag = await _serviceIotApi.SetFetalConfig(imeiDel);
  174. _logger.LogInformation($"{imeiDel} 建模建模中");
  175. }
  176. else
  177. {
  178. // 建模完成
  179. var flag = await _serviceIotApi.SetFetalConfig(imeiDel, 1, commonPHR.MaxValue, commonPHR.MinValue);
  180. _logger.LogInformation($"{imeiDel} 建模完成");
  181. // 保存到TDengine数据库
  182. await _serviceTDengine.InsertAsync<PregnancyCommonHeartRateModel>("hm_pchr", commonPHR);
  183. _logger.LogInformation($"保存TDengine完成");
  184. //
  185. }
  186. }
  187. #endregion
  188. #region 注册定时下发
  189. var startTime = DateTime.Now;
  190. // 注册下次下推
  191. var endTime = DateTime.Now;
  192. #if DEBUG
  193. //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  194. //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  195. var interval = 0;
  196. // 获取当前时间
  197. DateTime now = DateTime.Now;
  198. // 计算距离下一个$interval天后的8点的时间间隔
  199. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  200. TimeSpan timeUntilNextRun = nextRunTime - now;
  201. // 如果当前时间已经超过了8点,将等待到明天后的8点
  202. if (timeUntilNextRun < TimeSpan.Zero)
  203. {
  204. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  205. nextRunTime += timeUntilNextRun;
  206. }
  207. //long ttl = timeUntilNextRun.Milliseconds/1000;
  208. long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  209. var data = new
  210. {
  211. imei = imeiDel,
  212. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  213. ttl,
  214. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  215. };
  216. var result = JsonConvert.SerializeObject(data);
  217. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  218. #else
  219. // 每$interval天,晚上8点
  220. var interval = 1;
  221. // 获取当前时间
  222. DateTime now = DateTime.Now;
  223. var rand = new Random();
  224. var pushSec = rand.Next(59);
  225. int pushMin = int.TryParse(imeiDel.AsSpan(imeiDel.Length - 1), out pushMin) ? pushMin : 10;
  226. // 计算距离下一个$interval天后的0点的时间间隔
  227. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 6, pushMin, pushSec).AddDays(interval);
  228. TimeSpan timeUntilNextRun = nextRunTime - now;
  229. // 如果当前时间已经超过了8点,将等待到明天后的8点
  230. if (timeUntilNextRun < TimeSpan.Zero)
  231. {
  232. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  233. nextRunTime += timeUntilNextRun;
  234. }
  235. // var ttl = timeUntilNextRun.TotalMilliseconds;
  236. long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  237. var data = new
  238. {
  239. imei = imeiDel,
  240. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  241. ttl,
  242. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  243. };
  244. var result = JsonConvert.SerializeObject(data);
  245. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  246. #endif
  247. #endregion
  248. }
  249. }
  250. // health_monitor/schedule_push/cal_fetal_heart_rate/imei/
  251. // 高频结束后计算胎心数据,防止结束后与常规心理的胎心处理过长
  252. if (key.Contains("health_monitor/schedule_push/cal_freqhr_fetal_heart_rate/imei/"))
  253. {
  254. /// 延时计算高频状态的胎心数据,防止高频结束后与触发数据时间相隔过长。
  255. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(imeiDel);
  256. // 高频不停,15分钟内只下发一条
  257. var push = await _deviceCacheMgr.GetBizIntervalAsync(imeiDel, "SaveAndPushFetalHeartRate");
  258. var triggerValue = (JObject)JsonConvert.DeserializeObject(e.PrevKv.Value.ToStringUtf8())!;
  259. var trigger = triggerValue["trigger"]?.ToString();
  260. // 验证高频首条是否还存在
  261. if (phrFreqstatus != null && string.IsNullOrEmpty(push))
  262. {
  263. if (!string.IsNullOrEmpty(trigger))
  264. {
  265. var triggerHeartRate = JsonConvert.DeserializeObject<HisGpsHeartRate>(trigger);
  266. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = triggerHeartRate?.MessageId! }))
  267. {
  268. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  269. _logger.LogInformation($"{imeiDel}高频结束后,延迟计算高频数据产生的胎心数据");
  270. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  271. if (isFetalHeartEnable)
  272. {
  273. // 防止超过12条连续正常,高频不停止
  274. if (phrFreqstatus.MessageId == triggerHeartRate?.MessageId)
  275. {
  276. // 告警上限阀值
  277. var upperAlarmThreshold = (int)watchConfig!["upperAlarmThreshold"]!;
  278. // 告警下限阀值
  279. var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  280. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容(最小highFreqSampleInterval=60)
  281. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! + 5 : 60;
  282. //停止高频心率采样心率连续正常次数
  283. var stopHighFreqSampleCount = (int)watchConfig["stopHighFreqSampleCount"]!;
  284. // 高频心率采集时长 0 为持续采集,非零为高频心率的采集时长
  285. //var highFreqSampleTimes = (int)watchConfig["highFreqSampleTimes"]!;
  286. var highFreqSampleTimes = 540;
  287. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  288. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  289. var phrFromFreqstatus = phr.Where(i => i.LastUpdate >= phrFreqstatus.LastUpdate).ToList();
  290. // 高频数据
  291. var phrInFreqstatus = GetFreqPregnancyHeartRate(phrFromFreqstatus, highFreqSampleInterval)
  292. .OrderByDescending(i => i.LastUpdate).ToList();
  293. if (phrInFreqstatus.Count > stopHighFreqSampleCount)
  294. {
  295. // 取最后 stopHighFreqSampleCount 条高频数据
  296. phrInFreqstatus = phrInFreqstatus
  297. .OrderByDescending(i => i.LastUpdate)
  298. .Take(stopHighFreqSampleCount).ToList(); // 计算最后12条
  299. var avgPhr = phrInFreqstatus
  300. .Select(i => i.PregnancyHeartRate).Average();
  301. var FreqStatsEnd = phrInFreqstatus.First().LastUpdate;
  302. _logger.LogInformation($"延时计算,{imeiDel} 高频状态持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,统计周期:{phrFreqstatus!.LastUpdate.ToString("yyyy-MM-dd HH:mm:ss")}----{FreqStatsEnd.ToString("yyyy-MM-dd HH:mm:ss")},高频心率平均值:{(int)avgPhr},将下发指令");
  303. //await SaveAndPushFetalHeartRateAsync(triggerHeartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  304. triggerHeartRate.HeartRate = (int)avgPhr;
  305. //await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(triggerHeartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  306. // 判断是否够highFreqSampleTimes,540s
  307. var lastPhr = phrInFreqstatus;
  308. // 最后一条高频心率
  309. var lastFreqHr = phrInFreqstatus.First();
  310. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)lastFreqHr.LastUpdate!, phrFreqstatus!.LastUpdate);
  311. if (ts < highFreqSampleTimes)
  312. {
  313. /// 不够10分钟最近12个数据的最小值生成胎心值
  314. _logger.LogInformation($"{triggerHeartRate.Serialno} 不够10分钟最近12个数据的最小值生成胎心值");
  315. triggerHeartRate.HeartRate = lastPhr.Select(i => i.PregnancyHeartRate).Min();
  316. triggerHeartRate.LastUpdate = lastFreqHr.LastUpdate;
  317. }
  318. _logger.LogInformation($"{triggerHeartRate.Serialno} 高频结束后计算胎心数据,防止结束后与常规心理的胎心处理过长,定时器时长highFreqSampleInterval触发的高频心率处理");
  319. await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(triggerHeartRate, commonPHR, highFreqSampleTimes, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  320. }
  321. else
  322. {
  323. _logger.LogWarning($"{imeiDel} 高频心率的数据不大于{stopHighFreqSampleCount}条,不进行高频数据的胎心计算");
  324. }
  325. // 删除高频状态的首条记录
  326. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(imeiDel);
  327. }
  328. else
  329. {
  330. _logger.LogWarning($"{imeiDel} 超过12条连续正常,高频不停止,暂不处理");
  331. }
  332. }
  333. else
  334. {
  335. _logger.LogWarning($"{imeiDel} 胎心监测功能没有启动");
  336. }
  337. }
  338. }
  339. }
  340. }
  341. // 延时计算常规胎心数据
  342. else if (key.Contains("health_monitor/schedule_push/cal_normalphr_fetal_heart_rate/imei/"))
  343. {
  344. var triggerValue = (JObject)JsonConvert.DeserializeObject(e.PrevKv.Value.ToStringUtf8())!;
  345. var trigger = triggerValue["trigger"]?.ToString();
  346. if (!string.IsNullOrEmpty(trigger))
  347. {
  348. var triggerHeartRate = JsonConvert.DeserializeObject<HisGpsHeartRate>(trigger);
  349. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = triggerHeartRate?.MessageId! }))
  350. {
  351. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  352. _logger.LogInformation($"{imeiDel}延迟常规胎心数据产生的胎心数据");
  353. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  354. if (isFetalHeartEnable)
  355. {
  356. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  357. if (commonPHR!=null)
  358. {
  359. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! : 60;
  360. await CalculateNormalFetalHeartRateIntervalAsync(triggerHeartRate!, commonPHR, highFreqSampleInterval);
  361. }
  362. else
  363. {
  364. _logger.LogWarning($"{imeiDel} 胎心数据建模中...");
  365. }
  366. }
  367. else
  368. {
  369. _logger.LogWarning($"{imeiDel} 胎心监测功能没有启动");
  370. }
  371. }
  372. }
  373. }
  374. else if (key.Contains("health_monitor/schedule_push/cal_fetal_heart_rate/imei/"))
  375. {
  376. /**
  377. var triggerValue= (JObject)JsonConvert.DeserializeObject(e.PrevKv.Value.ToStringUtf8())!;
  378. var trigger = triggerValue["trigger"]?.ToString();
  379. if (!string.IsNullOrEmpty(trigger))
  380. {
  381. var triggerHeartRate= JsonConvert.DeserializeObject<HisGpsHeartRate>(trigger);
  382. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = triggerHeartRate?.MessageId! }))
  383. {
  384. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  385. _logger.LogInformation($"触发常规心率计算胎心");
  386. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  387. if (isFetalHeartEnable)
  388. {
  389. // 告警上限阀值
  390. var upperAlarmThreshold = (int)watchConfig!["upperAlarmThreshold"]!;
  391. // 告警下限阀值
  392. var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  393. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容(最小highFreqSampleInterval=60)
  394. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! + 5 : 60;
  395. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  396. // 最后一条孕妇心率
  397. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(imeiDel);
  398. var isNormalHeartRate = triggerHeartRate?.MessageId == lastPhr.MessageId;
  399. // 判断最后一条孕妇心率与解析器的触发心率是否一致
  400. if (isNormalHeartRate)
  401. {
  402. //最后一条孕妇心率与解析器的触发心率一致
  403. HisGpsHeartRate heartRate = new()
  404. {
  405. CreateTime = lastPhr.CreateTime,
  406. DeviceKey = lastPhr.DeviceKey,
  407. HeartRate = lastPhr.PregnancyHeartRate,
  408. HeartRateId = lastPhr.PregnancyHeartRateId,
  409. IsDisplay = lastPhr.IsDisplay ? 1 : 0,
  410. MessageId = lastPhr.MessageId,
  411. LastUpdate = lastPhr.LastUpdate,
  412. Method = lastPhr.Method,
  413. PersonId = lastPhr.PersonId,
  414. Serialno = lastPhr.SerialNumber
  415. };
  416. var intervalFHR = 15;
  417. await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  418. }
  419. // 最后一条孕妇心率与解析器的触发心率不一致,触发心率是高频心率的首条
  420. else
  421. {
  422. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  423. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(imeiDel);
  424. if (phrFreqstatus != null)
  425. {
  426. #region 高频缓存
  427. // 高频首条是触发心率,30秒后,高频第二条已经写入首条高频缓存
  428. var diffCount = phr.Where(i => i.CreateTime >= phrFreqstatus.CreateTime && i.CreateTime <= lastPhr.CreateTime)
  429. .OrderByDescending(i => i.CreateTime);
  430. _logger.LogInformation($"{imeiDel} 存在高频缓存,高频心率首条记录${phrFreqstatus.MessageId},高频首条到当前的MSG ID{string.Join(",",diffCount.Select(i=>i.MessageId))}");
  431. #endregion
  432. }
  433. // 不在高频状态状态,但触发孕妇心率与最后一条孕妇心率不一致,
  434. // 常规心率数据是批量上报,需要计算每条心率对应的胎心数据
  435. else
  436. {
  437. _logger.LogInformation($"{imeiDel} 常规心率数据是批量上报,需要计算每条心率对应的胎心数据");
  438. #region 计算每条心率对应的胎心数据
  439. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  440. // 获取高频数据
  441. var freqCollection = new List<PregnancyHeartRateModel>();
  442. PregnancyHeartRateModel? previousItem = null;
  443. foreach (var item in phr)
  444. {
  445. if (previousItem != null)
  446. {
  447. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  448. if (timeNextDiff <= highFreqSampleInterval)
  449. {
  450. freqCollection.Add(item);
  451. }
  452. }
  453. previousItem = item;
  454. }
  455. //去除高频
  456. foreach (var item in freqCollection)
  457. {
  458. phr.Remove(item);
  459. }
  460. // 排序并过滤高频数据
  461. //var previousItem = phr.OrderByDescending(i => i.LastUpdate).ToList().First();
  462. //phr = phr.Skip(1)
  463. // .Where(item =>
  464. // {
  465. // var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  466. // previousItem = item;
  467. // return timeNextDiff > highFreqSampleInterval;
  468. // })
  469. // .Prepend(previousItem)
  470. // .OrderByDescending(i => i.LastUpdate)
  471. // .ToList();
  472. var calFhrTasks = phr.Where(p => p.LastUpdate >= triggerHeartRate!.LastUpdate)
  473. .Select( async p =>
  474. {
  475. HisGpsHeartRate heartRate = new()
  476. {
  477. CreateTime = p.CreateTime,
  478. DeviceKey = p.DeviceKey,
  479. HeartRate = p.PregnancyHeartRate,
  480. HeartRateId = p.PregnancyHeartRateId,
  481. IsDisplay = p.IsDisplay ? 1 : 0,
  482. MessageId = p.MessageId,
  483. LastUpdate = p.LastUpdate,
  484. Method = p.Method,
  485. PersonId = p.PersonId,
  486. Serialno = p.SerialNumber
  487. };
  488. var intervalFHR = 15;
  489. await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  490. });
  491. await Task.WhenAll(calFhrTasks);
  492. #endregion
  493. }
  494. }
  495. }
  496. else
  497. {
  498. _logger.LogWarning($"{imeiDel} 胎心监测功能没有开启");
  499. }
  500. }
  501. }
  502. else
  503. {
  504. _logger.LogWarning($"{imeiDel} trigger is not set");
  505. }
  506. */
  507. }
  508. // 胎动计算
  509. //health_monitor/schedule_push/cal_fetal_movement/imei/
  510. else if (key.Contains("health_monitor/schedule_push/cal_fetal_movement/imei/"))
  511. {
  512. #region 相隔2小时胎动延时计算(实时now是3小时,计算 lastupdate 0~2范围的数据,)
  513. /**
  514. ///实时now的hour是3小时,计算 lastupdate 0~2范围的数据,
  515. ///只在 HOUR = new int[] { 1, 3, 5, 7, 9, 11,13, 15, 17, 19, 21, 23 };是奇数
  516. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = $"FM-{imeiDel}-{DateTime.Now.ToString("yyyyMMddHHmmss")}" }))
  517. {
  518. try
  519. {
  520. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  521. _logger.LogInformation($"触发胎动计算,设备配置{JsonConvert.SerializeObject(watchConfig)}");
  522. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  523. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! : 60;
  524. if (isFetalHeartEnable)
  525. {
  526. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  527. // 已经建模
  528. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  529. if (commonPHR != null)
  530. {
  531. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  532. _logger.LogInformation($"{imeiDel} 计算胎动数据 ");
  533. DateTime fmNow = DateTime.Now;
  534. int fmNowHour = fmNow.Hour;
  535. DateTime statStartTime;
  536. DateTime statEndTime;
  537. if (fmNowHour == 1)
  538. {
  539. // last_update 22~0
  540. statStartTime = fmNow.Date.AddDays(-1).AddHours(22);
  541. statEndTime = fmNow.Date;
  542. }
  543. else
  544. {
  545. statStartTime = fmNow.Date.AddHours(fmNowHour - 3);
  546. statEndTime = fmNow.Date.AddHours(fmNowHour - 1);
  547. }
  548. _logger.LogInformation($"{imeiDel} 胎动统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  549. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(statEndTime).ToString()[..10];
  550. var isFetalMovementExisted = await _deviceCacheMgr.FetalMovementIsExistedAsync(imeiDel, fetalMovementSampleTime);
  551. if (!isFetalMovementExisted)
  552. {
  553. /// 开始计算
  554. var phrRange = phr.Where(i => i.LastUpdate >= statStartTime && i.LastUpdate <= statEndTime)
  555. .OrderByDescending(i => i.LastUpdate)
  556. .Select(i => i.LastUpdate)
  557. .ToList();
  558. // 判断是否有持续佩戴
  559. if (phrRange.Count >= 2)
  560. {
  561. // 读取胎心数据
  562. GeneralParam param = new()
  563. {
  564. Filters = new List<QueryFilterCondition>
  565. {
  566. new ()
  567. {
  568. Key=nameof(HisGpsFetalHeartRate.Serialno),
  569. Value=imeiDel,
  570. ValueType=QueryValueTypeEnum.String,
  571. Operator=QueryOperatorEnum.Equal
  572. },
  573. //new ()
  574. //{
  575. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  576. // Value=sampleTime,
  577. // ValueType=QueryValueTypeEnum.String,
  578. // Operator=QueryOperatorEnum.GreaterEqual
  579. //},
  580. },
  581. OrderBys = new List<OrderByCondition>
  582. {
  583. new (){
  584. IsDesc=true,
  585. Key=nameof(HisGpsFetalHeartRate.SampleTime)
  586. }
  587. }
  588. };
  589. var fetalHeartRateIsAbnormal = 0;
  590. var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  591. // 胎心数据时间与胎动时间一致
  592. var time = long.Parse(fhr.SampleTime.Length < 13 ? fhr.SampleTime.PadRight(13, '0') : fhr.SampleTime);
  593. var fhrSampleTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(time);
  594. // 胎心数据时间与胎动时间一致,最后一条胎心数据与胎动数据的小时差不大于3
  595. if ((DateTime.Now.Hour - fhrSampleTime.Hour) <= 3)
  596. {
  597. var duringMins = Math.Abs((phrRange.First() - phrRange.Last()).TotalMinutes);
  598. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  599. bool isInTimeRanges = IsLastUpdateInTimeRanges(phrRange.First());
  600. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  601. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  602. {
  603. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  604. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  605. .Where(i =>
  606. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  607. i.PregnancyPeriod[1] >= pregnancyWeeks)
  608. .Select(i => i.MedianMovement)
  609. .FirstOrDefault()
  610. :
  611. fetalMovementMap
  612. .Where(i =>
  613. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  614. i.PregnancyPeriod[1] >= pregnancyWeeks)
  615. .Select(i => i.InitialMovement)
  616. .FirstOrDefault()
  617. ;
  618. var fetalMovementTimeVar = (fetalMovementMapValue * duringMins * 2) / 120;
  619. //// 四舍五入
  620. //var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  621. // _logger.LogInformation($"{imeiDel} segmentCountFMIndex: {i} -- fetalMovementSampleTime:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")} -- statStartTime: {statStartTime} -- statEndTime: {statEndTime}-- isFetalMovementExisted: {isFetalMovementExisted} ");
  622. #region 生理健康与胎动的关系
  623. /// (步数)运动步数超过1500步则加1;
  624. /// (体温)低烧则胎动减1,高烧胎动减2;低烧是37.3~38.5,38.6以上是高烧。
  625. /// (血压)血压收缩压大于160则加1。
  626. /// (心理)心理压力高加2,压力中加1;
  627. var fetalMovementStepVar = 0;
  628. var fetalMovementTempVar = 0;
  629. var fetalMovementBpVar = 0;
  630. var fetalMovementPpVar = 0;
  631. var fetalMovementFhrVar = 0;
  632. // 步数
  633. if (false)
  634. {
  635. var step = await _personCacheMgr.GetStepPeriodicityAsync(imeiDel);
  636. if (step != null)
  637. {
  638. if (DateTime.Now.Hour - ((DateTime)step?.LastUpdate!).Hour <= 2)
  639. {
  640. if (step.Steps > 1500) fetalMovementStepVar = 1;
  641. }
  642. else
  643. {
  644. _logger.LogWarning($"{imeiDel} 周期步数 时间无效");
  645. }
  646. }
  647. else
  648. {
  649. _logger.LogWarning($"{imeiDel} 周期步数无数据");
  650. }
  651. }
  652. // 体温
  653. if (true)
  654. {
  655. var temp = await _personCacheMgr.GetTemperaturePeriodicityAsync(imeiDel);
  656. if (temp != null)
  657. {
  658. if (DateTime.Now.Hour - ((DateTime)temp?.LastUpdate!).Hour <= 2)
  659. {
  660. // 中烧
  661. if (temp.Temperature >= 37.3M && temp.Temperature <= 38.5M)
  662. {
  663. fetalMovementTempVar = -1;
  664. }
  665. // 高烧
  666. if (temp.Temperature >= 38.6M)
  667. {
  668. fetalMovementTempVar = -2;
  669. }
  670. }
  671. else
  672. {
  673. _logger.LogWarning($"{imeiDel} 周期体温 时间无效");
  674. }
  675. }
  676. else
  677. {
  678. _logger.LogWarning($"{imeiDel} 周期体温无数据");
  679. }
  680. }
  681. // 血压
  682. if (true)
  683. {
  684. var bp = await _personCacheMgr.GetBloodPressPeriodicityAsync(imeiDel);
  685. if (bp != null)
  686. {
  687. if (DateTime.Now.Hour - ((DateTime)bp?.LastUpdate!).Hour <= 2)
  688. {
  689. if (bp.SystolicValue > 160)
  690. {
  691. fetalMovementBpVar = 1;
  692. }
  693. }
  694. else
  695. {
  696. _logger.LogWarning($"{imeiDel} 周期血压 时间无效");
  697. }
  698. }
  699. else
  700. {
  701. _logger.LogWarning($"{imeiDel} 周期血压无数据");
  702. }
  703. }
  704. // 心理
  705. if (false)
  706. {
  707. //-1 不处理,
  708. //0 正常,
  709. //1 轻度,
  710. //2 中度;
  711. //3 重度;
  712. GeneralParam psychResultParam = new()
  713. {
  714. Filters = new List<QueryFilterCondition>
  715. {
  716. new ()
  717. {
  718. Key=nameof(HisGpsPsychResult.Serialno),
  719. Value=imeiDel,
  720. ValueType=QueryValueTypeEnum.String,
  721. Operator=QueryOperatorEnum.Equal
  722. },
  723. //new ()
  724. //{
  725. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  726. // Value=sampleTime,
  727. // ValueType=QueryValueTypeEnum.String,
  728. // Operator=QueryOperatorEnum.GreaterEqual
  729. //},
  730. },
  731. OrderBys = new List<OrderByCondition>
  732. {
  733. new (){
  734. IsDesc=true,
  735. Key=nameof(HisGpsPsychResult.Serialno)
  736. }
  737. }
  738. };
  739. var psych = await _hisPsychResultApiClient.GetFirstAsync(psychResultParam, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  740. if (psych != null)
  741. {
  742. if (psych?.StressScore == 2)
  743. {
  744. fetalMovementPpVar = 1;
  745. }
  746. if (psych?.StressScore == 3)
  747. {
  748. fetalMovementPpVar = 2;
  749. }
  750. }
  751. else
  752. {
  753. _logger.LogWarning($"{imeiDel} 周期心理压力无数据");
  754. }
  755. }
  756. #endregion
  757. #region 胎心与胎动的关系
  758. /// 胎心值过缓时,则胎动数量减1;胎心值过速时,则胎动也加1。
  759. /// 此值允许在上限值上继续增加,在下限值上继续减少,最小值为0。
  760. /// 告警上限阀值
  761. //1表示偏高;2表示偏低
  762. if (true)
  763. {
  764. if (fhr.IsAbnormal == 2)
  765. {
  766. fetalMovementPpVar = -1;
  767. }
  768. if (fhr.IsAbnormal == 1)
  769. {
  770. fetalMovementPpVar = 1;
  771. }
  772. }
  773. #endregion
  774. //var fetalMovementTimeVar = fetalMovementValue;
  775. _logger.LogInformation($"{imeiDel} 时间比例胎动值:{fetalMovementTimeVar}, 步数参数变动值:{fetalMovementStepVar},体温参数变动值:{fetalMovementTempVar},血压参数变动值:{fetalMovementBpVar},心理压力参数变动值:{fetalMovementPpVar},胎心参数变动值:{fetalMovementFhrVar}");
  776. var fetalMovementValue = fetalMovementTimeVar + fetalMovementStepVar + fetalMovementTempVar + fetalMovementBpVar + fetalMovementPpVar + fetalMovementFhrVar;
  777. // 四舍五入
  778. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  779. _logger.LogInformation($"{imeiDel} 孕周:{pregnancyWeeks},胎动数据采样时间:{fetalMovementSampleTime}|{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 时间比例胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{phrRange.Last()}-{phrRange.First()}, 胎动计算值:{fetalMovementTimeVar}, 胎动四舍五入最终值:{fetalMovement} 已完成.");
  780. // 获取胎心数据状态与胎动数据状态一致
  781. //etalHeartRateIsAbnormal= fhr.IsAbnormal;
  782. var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  783. await _serviceIotApi.SetFetalMovementConfig(imeiDel, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  784. // 保存到MySQL数据库
  785. HisGpsFetalMovement fm = new()
  786. {
  787. FetalMovementId = Guid.NewGuid().ToString("D"),
  788. PersonId = commonPHR!.PersonId,
  789. Serialno = imeiDel,
  790. CreateTime = DateTime.Now,
  791. IsAbnormal = feltalMovementIsAbnormal,
  792. FetalMovementValue = fetalMovement,
  793. SampleTime = fetalMovementSampleTime,
  794. Method = 1,
  795. IsDisplay = 1,
  796. DeviceKey = commonPHR!.DeviceKey
  797. };
  798. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  799. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(imeiDel).ConfigureAwait(false);
  800. var fmMsgId = $"{imeiDel}-{fetalMovementSampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  801. var fmMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  802. // 胎动数据推送到第三方
  803. var topic = "topic.push.third";
  804. var fmThridMsg = new
  805. {
  806. messageId = fmMsgId,
  807. topic = topic,
  808. time = fmMsgTime,
  809. data = new
  810. {
  811. imei = imeiDel,
  812. value = fetalMovement,
  813. isAbnormal = feltalMovementIsAbnormal,
  814. type = "fetalMovement"
  815. }
  816. };
  817. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, 31, fmThridMsg).ConfigureAwait(false);
  818. // 胎动数据推送到微信
  819. if (feltalMovementIsAbnormal != 0)
  820. {
  821. topic = "topic.push.wx";
  822. var fmMsg = new
  823. {
  824. messageId = Guid.NewGuid().ToString("D"),
  825. topic = topic,
  826. time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss"),
  827. data = new
  828. {
  829. deviceId = device?.DeviceId,
  830. imei = imeiDel,
  831. alarmTypeId = 12,
  832. alarmDeviceName = imeiDel,
  833. alarmRemarks = JsonConvert.SerializeObject(new { fetalMovementValue = fetalMovement, isAbnormal = feltalMovementIsAbnormal }),
  834. address = string.Empty,
  835. deviceKey = device?.DeviceId
  836. }
  837. };
  838. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, fmMsg).ConfigureAwait(false);
  839. }
  840. // 设置入库缓存记录
  841. await _deviceCacheMgr.SetFetalMovementAsync(imeiDel, fetalMovementSampleTime, fm);
  842. }
  843. else
  844. {
  845. _logger.LogWarning($"{imeiDel} 孕周 {pregnancyWeeks},超出胎动计算范围");
  846. }
  847. }
  848. else
  849. {
  850. _logger.LogWarning($"{imeiDel} 最后一条胎心数据与胎动数据的小时差大于2,不计算胎动数据");
  851. }
  852. }
  853. else
  854. {
  855. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 不足两条,不能判断是否持续佩戴");
  856. }
  857. }
  858. else
  859. {
  860. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 已处理");
  861. }
  862. }
  863. else
  864. {
  865. _logger.LogWarning($"{imeiDel} 没有胎心建模数据");
  866. }
  867. }
  868. else
  869. {
  870. _logger.LogWarning($"{imeiDel} 胎心监测功能没有开启");
  871. }
  872. }
  873. catch (Exception ex )
  874. {
  875. _logger.LogError($"{imeiDel} 计算胎动数据异常 {ex.Message}\n {ex.StackTrace}");
  876. }
  877. }
  878. */
  879. #endregion
  880. #region 相隔1小时胎动延时计算(实时now是2小时,计算 lastupdate 0~1范围的数据,)
  881. /**
  882. 0~1->2
  883. 1~2->3
  884. 2~3->4
  885. 3~4->5
  886. 4~5->6
  887. 5~6->7
  888. 7~8->9
  889. 8~9->10
  890. 9~10->11
  891. 10~11->12
  892. 11~12->13
  893. 12~13->14
  894. 14~15->16
  895. 14~15->16
  896. 15~16->17
  897. 16~17->18
  898. 17~18->19
  899. 18~19->20
  900. 19~20->21
  901. 20~21->22
  902. 21~22->23
  903. 22~23->0
  904. 23~0->1
  905. */
  906. /*
  907. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = $"FM-{imeiDel}-{DateTime.Now.ToString("yyyyMMddHHmmss")}" }))
  908. {
  909. try
  910. {
  911. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  912. _logger.LogInformation($"触发胎动计算,设备配置{JsonConvert.SerializeObject(watchConfig)}");
  913. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  914. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! : 60;
  915. if (isFetalHeartEnable)
  916. {
  917. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  918. // 已经建模
  919. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  920. if (commonPHR != null)
  921. {
  922. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  923. _logger.LogInformation($"{imeiDel} 计算胎动数据 ");
  924. DateTime fmNow = DateTime.Now;
  925. int fmNowHour = fmNow.Hour;
  926. DateTime statStartTime;
  927. DateTime statEndTime;
  928. if (fmNowHour == 1)
  929. {
  930. // last_update 23~0
  931. statStartTime = fmNow.Date.AddDays(-1).AddHours(23);
  932. statEndTime = fmNow.Date;
  933. }
  934. else
  935. {
  936. // last_update 0~1->2,1~2->3,2~3->4...21~22->23
  937. statStartTime = fmNow.Date.AddHours(fmNowHour - 2);
  938. statEndTime = fmNow.Date.AddHours(fmNowHour - 1);
  939. }
  940. _logger.LogInformation($"{imeiDel} 胎动统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  941. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(statStartTime).ToString()[..10];
  942. var isFetalMovementExisted = await _deviceCacheMgr.FetalMovementIsExistedAsync(imeiDel, fetalMovementSampleTime);
  943. if (!isFetalMovementExisted)
  944. {
  945. /// 开始计算
  946. var phrRange = phr.Where(i => i.LastUpdate >= statStartTime && i.LastUpdate <= statEndTime)
  947. .OrderByDescending(i => i.LastUpdate)
  948. .Select(i => i.LastUpdate)
  949. .ToList();
  950. // 判断是否有持续佩戴
  951. if (phrRange.Count >= 2)
  952. {
  953. // 读取胎心数据
  954. GeneralParam param = new()
  955. {
  956. Filters = new List<QueryFilterCondition>
  957. {
  958. new ()
  959. {
  960. Key=nameof(HisGpsFetalHeartRate.Serialno),
  961. Value=imeiDel,
  962. ValueType=QueryValueTypeEnum.String,
  963. Operator=QueryOperatorEnum.Equal
  964. },
  965. //new ()
  966. //{
  967. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  968. // Value=sampleTime,
  969. // ValueType=QueryValueTypeEnum.String,
  970. // Operator=QueryOperatorEnum.GreaterEqual
  971. //},
  972. },
  973. OrderBys = new List<OrderByCondition>
  974. {
  975. new (){
  976. IsDesc=true,
  977. Key=nameof(HisGpsFetalHeartRate.SampleTime)
  978. }
  979. }
  980. };
  981. var fetalHeartRateIsAbnormal = 0;
  982. var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  983. // 胎心数据时间与胎动时间一致
  984. var time = long.Parse(fhr.SampleTime.Length < 13 ? fhr.SampleTime.PadRight(13, '0') : fhr.SampleTime);
  985. var fhrSampleTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(time);
  986. //// 胎心数据时间与胎动时间一致,最后一条胎心数据与胎动数据的小时差不大于3
  987. //if ((DateTime.Now.Hour - fhrSampleTime.Hour) <= 3)
  988. // 胎心数据时间与胎动时间一致,最后一条胎心数据与胎动数据的小时差不大于2
  989. if ((DateTime.Now.Hour - fhrSampleTime.Hour) <= 2)
  990. {
  991. var duringMins = Math.Abs((phrRange.First() - phrRange.Last()).TotalMinutes);
  992. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  993. bool isInTimeRanges = IsLastUpdateInTimeRanges(phrRange.First());
  994. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  995. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  996. {
  997. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  998. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  999. .Where(i =>
  1000. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  1001. i.PregnancyPeriod[1] >= pregnancyWeeks)
  1002. .Select(i => i.MedianMovement)
  1003. .FirstOrDefault()
  1004. :
  1005. fetalMovementMap
  1006. .Where(i =>
  1007. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  1008. i.PregnancyPeriod[1] >= pregnancyWeeks)
  1009. .Select(i => i.InitialMovement)
  1010. .FirstOrDefault()
  1011. ;
  1012. // var fetalMovementTimeVar = (fetalMovementMapValue * duringMins * 2) / 120;
  1013. var fetalMovementTimeVar = (fetalMovementMapValue * duringMins ) / 60;
  1014. if (duringMins < 59)
  1015. {
  1016. // 取12小时胎动总数最小值
  1017. fetalMovementMapValue = fetalMovementMap
  1018. .Where(i =>i.PregnancyPeriod![0] <= pregnancyWeeks &&i.PregnancyPeriod[1] >= pregnancyWeeks)
  1019. .First()
  1020. .TwelveHourMovementRange[0];
  1021. //取12小时胎动总数最小值的平均值
  1022. fetalMovementTimeVar = fetalMovementMapValue / 12;
  1023. _logger.LogWarning($"{imeiDel} 佩戴不足1小时,12小时胎动总数最小值{fetalMovementMapValue},平均值{fetalMovementTimeVar}");
  1024. }
  1025. #region 生理健康与胎动的关系
  1026. /// (步数)运动步数超过1500步则加1;
  1027. /// (体温)低烧则胎动减1,高烧胎动减2;低烧是37.3~38.5,38.6以上是高烧。
  1028. /// (血压)血压收缩压大于160则加1。
  1029. /// (心理)心理压力高加2,压力中加1;
  1030. var fetalMovementStepVar = 0;
  1031. var fetalMovementTempVar = 0;
  1032. var fetalMovementBpVar = 0;
  1033. var fetalMovementPpVar = 0;
  1034. var fetalMovementFhrVar = 0;
  1035. // 步数
  1036. if (false)
  1037. {
  1038. var step = await _personCacheMgr.GetStepPeriodicityAsync(imeiDel);
  1039. if (step != null)
  1040. {
  1041. if (DateTime.Now.Hour - ((DateTime)step?.LastUpdate!).Hour <= 2)
  1042. {
  1043. if (step.Steps > 1500) fetalMovementStepVar = 1;
  1044. }
  1045. else
  1046. {
  1047. _logger.LogWarning($"{imeiDel} 周期步数 时间无效");
  1048. }
  1049. }
  1050. else
  1051. {
  1052. _logger.LogWarning($"{imeiDel} 周期步数无数据");
  1053. }
  1054. }
  1055. // 体温
  1056. if (true)
  1057. {
  1058. var temp = await _personCacheMgr.GetTemperaturePeriodicityAsync(imeiDel);
  1059. if (temp != null)
  1060. {
  1061. if (DateTime.Now.Hour - ((DateTime)temp?.LastUpdate!).Hour <= 2)
  1062. {
  1063. // 中烧
  1064. if (temp.Temperature >= 37.3M && temp.Temperature <= 38.5M)
  1065. {
  1066. fetalMovementTempVar = -1;
  1067. }
  1068. // 高烧
  1069. if (temp.Temperature >= 38.6M)
  1070. {
  1071. fetalMovementTempVar = -2;
  1072. }
  1073. }
  1074. else
  1075. {
  1076. _logger.LogWarning($"{imeiDel} 周期体温 时间无效");
  1077. }
  1078. }
  1079. else
  1080. {
  1081. _logger.LogWarning($"{imeiDel} 周期体温无数据");
  1082. }
  1083. }
  1084. // 血压
  1085. if (true)
  1086. {
  1087. var bp = await _personCacheMgr.GetBloodPressPeriodicityAsync(imeiDel);
  1088. if (bp != null)
  1089. {
  1090. if (DateTime.Now.Hour - ((DateTime)bp?.LastUpdate!).Hour <= 2)
  1091. {
  1092. if (bp.SystolicValue > 160)
  1093. {
  1094. fetalMovementBpVar = 1;
  1095. }
  1096. }
  1097. else
  1098. {
  1099. _logger.LogWarning($"{imeiDel} 周期血压 时间无效");
  1100. }
  1101. }
  1102. else
  1103. {
  1104. _logger.LogWarning($"{imeiDel} 周期血压无数据");
  1105. }
  1106. }
  1107. // 心理
  1108. if (false)
  1109. {
  1110. //-1 不处理,
  1111. //0 正常,
  1112. //1 轻度,
  1113. //2 中度;
  1114. //3 重度;
  1115. GeneralParam psychResultParam = new()
  1116. {
  1117. Filters = new List<QueryFilterCondition>
  1118. {
  1119. new ()
  1120. {
  1121. Key=nameof(HisGpsPsychResult.Serialno),
  1122. Value=imeiDel,
  1123. ValueType=QueryValueTypeEnum.String,
  1124. Operator=QueryOperatorEnum.Equal
  1125. },
  1126. //new ()
  1127. //{
  1128. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  1129. // Value=sampleTime,
  1130. // ValueType=QueryValueTypeEnum.String,
  1131. // Operator=QueryOperatorEnum.GreaterEqual
  1132. //},
  1133. },
  1134. OrderBys = new List<OrderByCondition>
  1135. {
  1136. new (){
  1137. IsDesc=true,
  1138. Key=nameof(HisGpsPsychResult.Serialno)
  1139. }
  1140. }
  1141. };
  1142. var psych = await _hisPsychResultApiClient.GetFirstAsync(psychResultParam, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  1143. if (psych != null)
  1144. {
  1145. if (psych?.StressScore == 2)
  1146. {
  1147. fetalMovementPpVar = 1;
  1148. }
  1149. if (psych?.StressScore == 3)
  1150. {
  1151. fetalMovementPpVar = 2;
  1152. }
  1153. }
  1154. else
  1155. {
  1156. _logger.LogWarning($"{imeiDel} 周期心理压力无数据");
  1157. }
  1158. }
  1159. #endregion
  1160. #region 胎心与胎动的关系
  1161. /// 胎心值过缓时,则胎动数量减1;胎心值过速时,则胎动也加1。
  1162. /// 此值允许在上限值上继续增加,在下限值上继续减少,最小值为0。
  1163. /// 告警上限阀值
  1164. //1表示偏高;2表示偏低
  1165. if (true)
  1166. {
  1167. if (fhr.IsAbnormal == 2)
  1168. {
  1169. fetalMovementPpVar = -1;
  1170. }
  1171. if (fhr.IsAbnormal == 1)
  1172. {
  1173. fetalMovementPpVar = 1;
  1174. }
  1175. }
  1176. #endregion
  1177. _logger.LogInformation($"{imeiDel} 时间比例胎动值:{fetalMovementTimeVar}, 步数参数变动值:{fetalMovementStepVar},体温参数变动值:{fetalMovementTempVar},血压参数变动值:{fetalMovementBpVar},心理压力参数变动值:{fetalMovementPpVar},胎心参数变动值:{fetalMovementFhrVar}");
  1178. var fetalMovementValue = fetalMovementTimeVar + fetalMovementStepVar + fetalMovementTempVar + fetalMovementBpVar + fetalMovementPpVar + fetalMovementFhrVar;
  1179. // 四舍五入
  1180. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  1181. _logger.LogInformation($"{imeiDel} 孕周:{pregnancyWeeks},胎动数据采样时间:{fetalMovementSampleTime}|{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 时间比例胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{phrRange.Last()}-{phrRange.First()}, 胎动计算值:{fetalMovementTimeVar}, 胎动四舍五入最终值:{fetalMovement} 已完成.");
  1182. // 获取胎心数据状态与胎动数据状态一致
  1183. //etalHeartRateIsAbnormal= fhr.IsAbnormal;
  1184. var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  1185. await _serviceIotApi.SetFetalMovementConfig(imeiDel, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  1186. // 保存到MySQL数据库
  1187. HisGpsFetalMovement fm = new()
  1188. {
  1189. FetalMovementId = Guid.NewGuid().ToString("D"),
  1190. PersonId = commonPHR!.PersonId,
  1191. Serialno = imeiDel,
  1192. CreateTime = DateTime.Now,
  1193. IsAbnormal = feltalMovementIsAbnormal,
  1194. FetalMovementValue = fetalMovement,
  1195. SampleTime = fetalMovementSampleTime,
  1196. Method = 1,
  1197. IsDisplay = 1,
  1198. DeviceKey = commonPHR!.DeviceKey
  1199. };
  1200. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  1201. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(imeiDel).ConfigureAwait(false);
  1202. var fmMsgId = $"{imeiDel}-{fetalMovementSampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  1203. var fmMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  1204. // 胎动数据推送到第三方
  1205. var topic = "topic.push.third";
  1206. var fmThridMsg = new
  1207. {
  1208. messageId = fmMsgId,
  1209. topic = topic,
  1210. time = fmMsgTime,
  1211. data = new
  1212. {
  1213. imei = imeiDel,
  1214. value = fetalMovement,
  1215. isAbnormal = feltalMovementIsAbnormal,
  1216. type = "fetalMovement"
  1217. }
  1218. };
  1219. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, 31, fmThridMsg).ConfigureAwait(false);
  1220. // 胎动数据推送到微信
  1221. if (feltalMovementIsAbnormal != 0)
  1222. {
  1223. topic = "topic.push.wx";
  1224. var fmMsg = new
  1225. {
  1226. messageId = Guid.NewGuid().ToString("D"),
  1227. topic = topic,
  1228. time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss"),
  1229. data = new
  1230. {
  1231. deviceId = device?.DeviceId,
  1232. imei = imeiDel,
  1233. alarmTypeId = 12,
  1234. alarmDeviceName = imeiDel,
  1235. alarmRemarks = JsonConvert.SerializeObject(new { fetalMovementValue = fetalMovement, isAbnormal = feltalMovementIsAbnormal }),
  1236. address = string.Empty,
  1237. deviceKey = device?.DeviceId
  1238. }
  1239. };
  1240. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, fmMsg).ConfigureAwait(false);
  1241. }
  1242. // 设置入库缓存记录
  1243. await _deviceCacheMgr.SetFetalMovementAsync(imeiDel, fetalMovementSampleTime, fm);
  1244. }
  1245. else
  1246. {
  1247. _logger.LogWarning($"{imeiDel} 孕周 {pregnancyWeeks},超出胎动计算范围");
  1248. }
  1249. }
  1250. else
  1251. {
  1252. _logger.LogWarning($"{imeiDel} 最后一条胎心数据与胎动数据的小时差大于2,不计算胎动数据");
  1253. }
  1254. }
  1255. else
  1256. {
  1257. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 不足两条,不能判断是否持续佩戴");
  1258. }
  1259. }
  1260. else
  1261. {
  1262. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 已处理");
  1263. }
  1264. }
  1265. else
  1266. {
  1267. _logger.LogWarning($"{imeiDel} 没有胎心建模数据");
  1268. }
  1269. }
  1270. else
  1271. {
  1272. _logger.LogWarning($"{imeiDel} 胎心监测功能没有开启");
  1273. }
  1274. }
  1275. catch (Exception ex)
  1276. {
  1277. _logger.LogError($"{imeiDel} 计算胎动数据异常 {ex.Message}\n {ex.StackTrace}");
  1278. }
  1279. }
  1280. */
  1281. #endregion
  1282. #region 相隔1小时胎动延时计算(实时now是2小时,计算 lastupdate 0~1范围的数据,)
  1283. /**
  1284. 0~1->2,0~1 的lastupdate数据,sample_time 是1点,计算时间2点
  1285. 1~2->3
  1286. 2~3->4
  1287. 3~4->5
  1288. 4~5->6
  1289. 5~6->7
  1290. 7~8->9
  1291. 8~9->10
  1292. 9~10->11
  1293. 10~11->12
  1294. 11~12->13
  1295. 12~13->14
  1296. 14~15->16
  1297. 15~16->17
  1298. 16~17->18
  1299. 17~18->19
  1300. 18~19->20
  1301. 19~20->21
  1302. 20~21->22
  1303. 21~22->23
  1304. 22~23->0
  1305. 23~0->1
  1306. */
  1307. var triggerValue = (JObject)JsonConvert.DeserializeObject(e.PrevKv.Value.ToStringUtf8())!;
  1308. var trigger = triggerValue["trigger"]?.ToString();
  1309. if (!string.IsNullOrEmpty(trigger))
  1310. {
  1311. var triggerHeartRate = JsonConvert.DeserializeObject<HisGpsHeartRate>(trigger);
  1312. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = $"FM-{imeiDel}-{triggerHeartRate?.MessageId}" }))
  1313. {
  1314. try
  1315. {
  1316. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  1317. _logger.LogInformation($"触发胎动计算,设备配置{JsonConvert.SerializeObject(watchConfig)}");
  1318. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  1319. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! : 60;
  1320. if (isFetalHeartEnable)
  1321. {
  1322. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  1323. // 已经建模
  1324. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  1325. if (commonPHR != null)
  1326. {
  1327. await CalculateFetalMovementIntervalAsync(triggerHeartRate!, commonPHR, edoc);
  1328. }
  1329. else
  1330. {
  1331. _logger.LogWarning($"{imeiDel} 没有胎心建模数据");
  1332. }
  1333. }
  1334. else
  1335. {
  1336. _logger.LogWarning($"{imeiDel} 胎心监测功能没有开启");
  1337. }
  1338. }
  1339. catch (Exception ex)
  1340. {
  1341. _logger.LogError($"{imeiDel} 计算胎动数据异常 {ex.Message}\n {ex.StackTrace}");
  1342. }
  1343. }
  1344. }
  1345. #endregion
  1346. }
  1347. else
  1348. {
  1349. // 处理血压业务
  1350. int systolicInc;
  1351. int diastolicInc;
  1352. int systolicRefValue;
  1353. int diastolicRefValue;
  1354. decimal systolicAvg;
  1355. decimal diastolicAvg;
  1356. int systolicMax = 0;
  1357. int diastolicMax = 0;
  1358. // 统计时间
  1359. //DateTime endTime = DateTime.Now; //测试
  1360. DateTime statStartTime = DateTime.Now;
  1361. // 最小值
  1362. int systolicMin = 0;
  1363. int diastolicMin = 0;
  1364. // 偏移参数
  1365. var avgOffset = 0.25M;
  1366. var systolicAvgOffset = avgOffset;
  1367. var diastolicAvgOffset = avgOffset;
  1368. // 最后一次下发值
  1369. int lastPushSystolicInc = 0;
  1370. int lastPushDiastolicInc = 0;
  1371. var startTime = DateTime.Now;
  1372. // 下发增量值
  1373. #region 统计定时下发增量值
  1374. //var last = await _serviceTDengine.GetLastAsync("stb_hm_bloodpress_stats_inc", $"serialno='{imeiDel}' order by last_update desc");
  1375. //var ts = last?[0];
  1376. // 最后一条血压数据
  1377. var condition = $"serialno='{imeiDel}' order by last_update desc";
  1378. var field = "last_row(*)";
  1379. var lastHmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition, field);
  1380. var lastHmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(lastHmBpResponse!);
  1381. var lastHmBp = lastHmBpParser?.Select().FirstOrDefault();
  1382. //if (lastHmBpParser?.Select()?.ToList().Count < 2)
  1383. //{
  1384. // _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 血压数据条目不足");
  1385. // break;
  1386. //}
  1387. // 7 天有效数据
  1388. if (lastHmBp?.Timestamp.AddDays(7) > DateTime.Now)
  1389. {
  1390. // 计算增量值
  1391. condition = $"serialno='{imeiDel}' order by ts desc";
  1392. var lastPushResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bp_push_ref_inc_value", condition, field);
  1393. if (lastPushResponse == null)
  1394. {
  1395. _logger.LogInformation($"{imeiDel}--没有下发记录");
  1396. break;
  1397. }
  1398. var lastPushParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressurePushRefIncModel>>(lastPushResponse);
  1399. var lastPush = lastPushParser!.Select().FirstOrDefault();
  1400. // 有下推记录
  1401. if (lastPush != null)
  1402. {
  1403. systolicRefValue = lastPush!.SystolicRefValue;
  1404. diastolicRefValue = lastPush!.DiastolicRefValue;
  1405. lastPushSystolicInc = lastPush!.SystolicIncValue;
  1406. lastPushDiastolicInc = lastPush!.DiastolicIncValue;
  1407. condition = $"ts between '{lastPush?.Timestamp:yyyy-MM-dd HH:mm:ss.fff}' and '{startTime:yyyy-MM-dd HH:mm:ss.fff}' " +
  1408. $"and serialno='{imeiDel}' " +
  1409. $"and is_display = true";
  1410. // 使用最近一次的下推时间作为统计的开始时间
  1411. statStartTime = lastPush!.Timestamp;
  1412. }
  1413. // 没有下推记录(历史遗留数据),没有初始的测量值产生的平均值(测量值=平均值)
  1414. else
  1415. {
  1416. #region 获取个人信息
  1417. var person = await _personCacheMgr.GetDeviceGpsPersonCacheBySerialNoAsync(Guid.NewGuid().ToString(), imeiDel).ConfigureAwait(false);
  1418. //验证这个信息是否存在
  1419. if (person == null || person?.Person.BornDate == null)
  1420. {
  1421. _logger.LogWarning($"{nameof(Worker)}--{imeiDel} 验证个人信息,找不到个人信息,跳过此消息");
  1422. break;
  1423. }
  1424. // 验证年龄是否在范围 (2 - 120)
  1425. var age = SafeType.SafeInt(DateTime.Today.Year - person?.Person.BornDate!.Value.Year!);
  1426. if (age < 2 || age > 120)
  1427. {
  1428. _logger.LogWarning($"{nameof(Worker)}--{imeiDel} 验证年龄,不在范围 (2 - 120)岁,跳过此消息");
  1429. break;
  1430. }
  1431. var gender = person?.Person.Gender == true ? 1 : 2;
  1432. var isHypertension = SafeType.SafeBool(person?.Person.Ishypertension!);
  1433. var height = SafeType.SafeDouble(person?.Person.Height!);
  1434. var weight = SafeType.SafeDouble(person?.Person.Weight!);
  1435. #endregion
  1436. #region 初始化常规血压标定值标定值
  1437. var bpRef = await _bpRefValCacheManager.GetBloodPressReferenceValueAsync(age, gender, isHypertension);
  1438. //systolicRefValue = bpRef!.Systolic;//?
  1439. //diastolicRefValue = bpRef!.Diastolic;//?
  1440. #endregion
  1441. systolicRefValue = bpRef!.Systolic;
  1442. diastolicRefValue = bpRef!.Diastolic;
  1443. lastPushSystolicInc = 0;
  1444. lastPushDiastolicInc = 0;
  1445. condition = $"ts <= '{startTime:yyyy-MM-dd HH:mm:ss.fff}' " +
  1446. $"and serialno='{imeiDel}' " +
  1447. $"and is_display = true";
  1448. }
  1449. var hmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition);
  1450. var hmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(hmBpResponse!);
  1451. var hmBp = hmBpParser?.Select();
  1452. //if (hmBp?.ToList().Count < 2)
  1453. // 1. 判断数据样本数量
  1454. if (hmBpParser!.Rows < 5)
  1455. {
  1456. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 统计定时下发,计算增量值的数据条目不足:{hmBpParser!.Rows} < 5");
  1457. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} 没有足够的数据样本,不会定时下发");
  1458. break;
  1459. }
  1460. // 没有下推记录重新计算统计时间
  1461. if (lastPush == null)
  1462. {
  1463. var firstHmBp = hmBpParser?.Select(i => i).OrderBy(i => i.Timestamp).FirstOrDefault();
  1464. statStartTime = firstHmBp!.Timestamp;
  1465. }
  1466. // GetSampleTime(systolicRefValue, hmBpParser);
  1467. // 最大值
  1468. //systolicMax = (int)hmBpParser?.Select(i => i.SystolicValue).Max()!;
  1469. //diastolicMax = (int)hmBpParser?.Select(i => i.DiastolicValue).Max()!;
  1470. //// 最小值
  1471. //systolicMin = (int)hmBpParser?.Select(i => i.SystolicValue).Min()!;
  1472. //diastolicMin = (int)hmBpParser?.Select(i => i.DiastolicValue).Min()!;
  1473. //systolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.SystolicValue, SafeType.SafeInt(systolicRefValue!)))!;
  1474. //diastolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.DiastolicValue, SafeType.SafeInt(diastolicRefValue!)))!;
  1475. var avgs = _serviceTDengine.AverageAfterRemovingOneMinMaxRef(hmBpParser!);
  1476. systolicAvg = avgs[0];
  1477. diastolicAvg = avgs[1];
  1478. // 2. 判断能否计算增量值
  1479. if (systolicAvg.Equals(0))
  1480. {
  1481. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}--计算平均值" +
  1482. $"\n currentSystolicAvg:{systolicAvg} -- lastPushSystolicInc:{lastPushSystolicInc}" +
  1483. $"\n currentDiastolicInc:{diastolicAvg} -- lastPushDiastolicInc:{lastPushDiastolicInc}");
  1484. _logger.LogInformation($"{imeiDel}--{nameof(Worker)} 没有足够的数据样本计算平均值,不会定时下发");
  1485. break;
  1486. }
  1487. // 除最大值和最小值后的平均值与标定值差值少于4后(当天计算出该结果则也不产生增量调整),就不再进行增量值调整了。
  1488. if (systolicRefValue - systolicAvg < 4)
  1489. {
  1490. _logger.LogInformation($"diastolic 舒张压 {imeiDel}除最大值和最小值后的平均值:{diastolicAvg}与标定值:{diastolicRefValue}\n systolic 收缩压 {imeiDel}除最大值和最小值后的平均值:{systolicAvg}与标定值:{systolicRefValue}的差值(标定值-平均值)少于4后,systolic 收缩压 不再进行增量值调整");
  1491. break;
  1492. }
  1493. if (diastolicRefValue - diastolicAvg < 4)
  1494. {
  1495. _logger.LogInformation($"systolic 收缩压 {imeiDel}除最大值和最小值后的平均值:{systolicAvg}与标定值:{systolicRefValue}\n diastolic 舒张压 {imeiDel}除最大值和最小值后的平均值:{diastolicAvg}与标定值:{diastolicRefValue}的差值(标定值-平均值)少于4后,diastolic 舒张压 不再进行增量值调整");
  1496. break;
  1497. }
  1498. // 增量值=(标定值-平均值)* 0.25
  1499. var currentSystolicInc = (int)((systolicRefValue - systolicAvg) * systolicAvgOffset)!;
  1500. var currentDiastolicInc = (int)((diastolicRefValue - diastolicAvg) * diastolicAvgOffset)!;
  1501. // 累计增量
  1502. systolicInc = currentSystolicInc + lastPushSystolicInc;
  1503. diastolicInc = currentDiastolicInc + lastPushDiastolicInc;
  1504. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}--计算增量值" +
  1505. $"\n {imeiDel} -- systolicAvg:{systolicAvg}-- systolicInc:{systolicInc}-- currentSystolicInc:{currentSystolicInc} -- lastPushSystolicInc:{lastPushSystolicInc}" +
  1506. $"\n {imeiDel} -- diastolicAvg:{diastolicAvg}-- diastolicInc:{diastolicInc} --currentDiastolicInc:{currentDiastolicInc} -- lastPushDiastolicInc:{lastPushDiastolicInc}");
  1507. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}-- 定时校准,发给设备的绝对增量值=(上次绝对增量值+新数据的增量值)");
  1508. _logger.LogInformation($"{nameof(Worker)} 开启血压标定值下发: {_configBoodPressResolver.EnableBPRefPush}");
  1509. if (_configBoodPressResolver.EnableBPRefPush)
  1510. // if (false) // 临时关闭
  1511. {
  1512. BloodPressCalibrationConfigModel bpIncData = new()
  1513. {
  1514. Imei = imeiDel,
  1515. SystolicRefValue = SafeType.SafeInt(((int)systolicRefValue!)), //收缩压标定值,值为0 表示不生效
  1516. DiastolicRefValue = SafeType.SafeInt(((int)diastolicRefValue!)), //舒张压标定值,值为0表示不生效
  1517. SystolicIncValue = SafeType.SafeInt(((int)systolicInc!)), //收缩压显示增量,值为0 表示不生效
  1518. DiastolicIncValue = SafeType.SafeInt(((int)diastolicInc!)) //舒张压显示增量,值为0 表示不生效
  1519. };
  1520. //var pushedBP = await _serviceIotApi.SetBloodPressCalibrationConfigAsync(bpIncData).ConfigureAwait(false);
  1521. var response = await _serviceIotApi.SetBloodPressCalibrationConfig2Async(bpIncData).ConfigureAwait(false);
  1522. var pushedBP = response.Flag;
  1523. if (pushedBP)
  1524. {
  1525. #region 保存下推记录 stb_hm_bp_push_ref_inc_value
  1526. var sql = $"INSERT INTO health_monitor.hm_bp_push_ref_inc_value_{imeiDel.Substring(imeiDel.Length - 2)} " +
  1527. $"USING health_monitor.stb_hm_bp_push_ref_inc_value " +
  1528. $"TAGS ('{imeiDel.Substring(imeiDel.Length - 2)}') " +
  1529. $"VALUES(" +
  1530. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  1531. $"'{imeiDel}'," +
  1532. $"{bpIncData.SystolicRefValue}," +
  1533. $"{bpIncData.DiastolicRefValue}," +
  1534. $"{bpIncData.SystolicIncValue}," +
  1535. $"{bpIncData.DiastolicIncValue}," +
  1536. $"{false}," +
  1537. $"{systolicAvg}," +
  1538. $"{diastolicAvg}," +
  1539. $"{systolicAvgOffset}," +
  1540. $"{diastolicAvgOffset}," +
  1541. $"'{statStartTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  1542. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'" +
  1543. $")";
  1544. _serviceTDengine.ExecuteInsertSQL(sql);
  1545. #endregion
  1546. #region 注册定时下发
  1547. // 注册下次下推
  1548. var endTime = DateTime.Now;
  1549. #if DEBUG
  1550. //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  1551. //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  1552. var interval = 0;
  1553. // 获取当前时间
  1554. DateTime now = DateTime.Now;
  1555. // 计算距离下一个$interval天后的8点的时间间隔
  1556. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  1557. TimeSpan timeUntilNextRun = nextRunTime - now;
  1558. // 如果当前时间已经超过了8点,将等待到明天后的8点
  1559. if (timeUntilNextRun < TimeSpan.Zero)
  1560. {
  1561. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  1562. nextRunTime += timeUntilNextRun;
  1563. }
  1564. // var ttl = timeUntilNextRun.TotalMilliseconds;
  1565. long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  1566. var data = new
  1567. {
  1568. imei = imeiDel,
  1569. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  1570. ttl,
  1571. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  1572. };
  1573. var result = JsonConvert.SerializeObject(data);
  1574. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  1575. #else
  1576. // 每$interval天,晚上8点
  1577. var interval = 1;
  1578. // 获取当前时间
  1579. DateTime now = DateTime.Now;
  1580. // 计算距离下一个$interval天后的8点的时间间隔
  1581. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 20, 0, 0).AddDays(interval);
  1582. TimeSpan timeUntilNextRun = nextRunTime - now;
  1583. // 如果当前时间已经超过了8点,将等待到明天后的8点
  1584. if (timeUntilNextRun < TimeSpan.Zero)
  1585. {
  1586. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  1587. nextRunTime += timeUntilNextRun;
  1588. }
  1589. // var ttl = timeUntilNextRun.TotalMilliseconds;
  1590. long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  1591. var data = new
  1592. {
  1593. imei = imeiDel,
  1594. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  1595. ttl,
  1596. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  1597. };
  1598. var result = JsonConvert.SerializeObject(data);
  1599. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  1600. #endif
  1601. #endregion
  1602. }
  1603. else
  1604. {
  1605. _logger.LogInformation($"错误响应,没有下推数据:{response.Message}");
  1606. }
  1607. }
  1608. }
  1609. else
  1610. {
  1611. _logger.LogInformation($"向{imeiDel}统计数据已经失效");
  1612. }
  1613. #endregion
  1614. }
  1615. }
  1616. break;
  1617. }
  1618. }
  1619. catch (Exception ex)
  1620. {
  1621. _logger.LogError($"{nameof(WatchEvents)},出错: |{ex.Message}|{ex.StackTrace}");
  1622. }
  1623. });
  1624. }
  1625. private async Task SetIntervalTriggerAsync(string key, string imei, long interval)
  1626. {
  1627. // var key = $"health_monitor/schedule_push/{type}/imei/{imei}";
  1628. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  1629. if (string.IsNullOrWhiteSpace(schedulePush))
  1630. {
  1631. var now = DateTime.Now;
  1632. var timeNextRun = now.Add(TimeSpan.FromSeconds(interval));
  1633. var data = new
  1634. {
  1635. imei,
  1636. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  1637. ttl = interval,
  1638. next_run_time = timeNextRun.ToString("yyyy-MM-dd HH:mm:ss")
  1639. };
  1640. var result = JsonConvert.SerializeObject(data);
  1641. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  1642. }
  1643. }
  1644. public static bool IsNowInTimeRanges()
  1645. {
  1646. var now = DateTime.Now.TimeOfDay;
  1647. var timeRanges = new List<(TimeSpan Start, TimeSpan End)>
  1648. {
  1649. // 8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00
  1650. (new TimeSpan(8, 0, 0), new TimeSpan(10, 0, 0)),
  1651. (new TimeSpan(12, 0, 0), new TimeSpan(14, 0, 0)),
  1652. (new TimeSpan(18, 0, 0), new TimeSpan(20, 0, 0)),
  1653. (new TimeSpan(22, 0, 0), new TimeSpan(24, 0, 0))
  1654. };
  1655. return timeRanges.Any(range => now >= range.Start && now <= range.End);
  1656. }
  1657. public static bool IsLastUpdateInTimeRanges(DateTime lastUpdate)
  1658. {
  1659. var now = lastUpdate.TimeOfDay;
  1660. var timeRanges = new List<(TimeSpan Start, TimeSpan End)>
  1661. {
  1662. // 8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00
  1663. (new TimeSpan(8, 0, 0), new TimeSpan(10, 0, 0)),
  1664. (new TimeSpan(12, 0, 0), new TimeSpan(14, 0, 0)),
  1665. (new TimeSpan(18, 0, 0), new TimeSpan(20, 0, 0)),
  1666. (new TimeSpan(22, 0, 0), new TimeSpan(24, 0, 0))
  1667. };
  1668. return timeRanges.Any(range => now >= range.Start && now <= range.End);
  1669. }
  1670. private async Task SaveAndPushFetalHeartRateEndFreqHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int upperAlarmThreshold, int lowerAlarmThreshold, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  1671. {
  1672. // 计算胎心=孕妇心率*系数
  1673. /**
  1674. var fetalHeartRate = SafeType.SafeInt(phrValue * commonPHR?.StatModeAvgFprCoefficient!);
  1675. fetalHeartRate = fetalHeartRate > 220 ? 220 : fetalHeartRate; // 胎心的最大值调整为220,超过都按该值220输出
  1676. if (fetalHeartRate >= 220)
  1677. {
  1678. // 先使用最小系数计算
  1679. var statMaxValueFprCoefficient = commonPHR?.StatMaxValueFprCoefficient!;
  1680. var statMinValueFprCoefficient = commonPHR?.StatMinValueFprCoefficient!;
  1681. var coefficient = statMaxValueFprCoefficient < statMinValueFprCoefficient ? statMaxValueFprCoefficient : statMinValueFprCoefficient;
  1682. fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  1683. if (fetalHeartRate < 220)
  1684. {
  1685. _logger.LogWarning($"{heartRate.Serialno} 使用极值系数 {coefficient} ,建模数据可能出现异常,请检查");
  1686. }
  1687. else
  1688. {
  1689. fetalHeartRate = 220;
  1690. _logger.LogWarning($"{heartRate.Serialno} 使用所有系数都不能放映实际,建模数据可能出现异常,请检查");
  1691. }
  1692. }
  1693. */
  1694. #region 胎心系数使用基于心率与中位数对比
  1695. var coefficient = 0f;
  1696. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  1697. if (heartRate.HeartRate < commonPHR!.Mode)
  1698. {
  1699. coefficient = commonPHR.StatMinValueFprCoefficient!;
  1700. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  1701. }
  1702. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  1703. else if (heartRate.HeartRate > commonPHR.Mode)
  1704. {
  1705. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  1706. {
  1707. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  1708. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  1709. }
  1710. else
  1711. {
  1712. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  1713. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  1714. }
  1715. }
  1716. else
  1717. {
  1718. coefficient = commonPHR.StatModeAvgFprCoefficient;
  1719. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  1720. }
  1721. #endregion
  1722. var fetalHeartRate = SafeType.SafeInt(heartRate.HeartRate! * coefficient);
  1723. // 胎心的最大值调整为220,超过都按该值220输出
  1724. fetalHeartRate = fetalHeartRate >= 220 ? 220 : fetalHeartRate;
  1725. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  1726. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  1727. if (phrFreqstatus == null) isAbnormal = 0;
  1728. var statsusDesc = (phrFreqstatus == null) ? "常规" : "高频";
  1729. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1730. //if (!isFreq)
  1731. //{
  1732. // statStartTime = heartRate.LastUpdate;
  1733. //
  1734. //}
  1735. // 保存到 数据服务 MySQL 数据库
  1736. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  1737. {
  1738. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  1739. PersonId = commonPHR!.PersonId,
  1740. Serialno = heartRate.Serialno,
  1741. HeartRate = fetalHeartRate,
  1742. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  1743. IsAbnormal = isAbnormal,
  1744. StatStartTime = statStartTime,
  1745. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  1746. CreateTime = DateTime.Now,
  1747. Method = 1,
  1748. IsDisplay = 1,
  1749. DeviceKey = commonPHR!.DeviceKey
  1750. };
  1751. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  1752. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  1753. // 推送最后一条常规心率计算的胎心数据到iot设备
  1754. #region 推送最后一条常规心率计算的胎心数据到iot设备
  1755. // 高频(<=12)-常规
  1756. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  1757. if (lastPhr.MessageId == heartRate.MessageId && phrFreqstatus == null)
  1758. {
  1759. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1760. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(<=12)-常规");
  1761. }
  1762. // 高频(13)-常规-高频(13)
  1763. if (phrFreqstatus != null)
  1764. {
  1765. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 1);
  1766. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1767. // 获取高频数据
  1768. var freqCollection = new List<PregnancyHeartRateModel>();
  1769. PregnancyHeartRateModel? previousItem = null;
  1770. foreach (var item in phr)
  1771. {
  1772. if (previousItem != null)
  1773. {
  1774. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1775. if (timeNextDiff <= 60)
  1776. {
  1777. freqCollection.Add(item);
  1778. }
  1779. }
  1780. // 高频最后一条
  1781. if (lastPhr.MessageId == item.MessageId)
  1782. {
  1783. freqCollection.Add(item);
  1784. }
  1785. previousItem = item;
  1786. }
  1787. //去除高频
  1788. foreach (var item in freqCollection)
  1789. {
  1790. phr.Remove(item);
  1791. }
  1792. lastPhr = phr.FirstOrDefault();
  1793. if (lastPhr?.MessageId == heartRate.MessageId)
  1794. {
  1795. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1796. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(13)-常规-高频(13)");
  1797. }
  1798. }
  1799. #endregion
  1800. #region 高频心率计算胎心数据到iot设备
  1801. // 高频(17) ,连续12个高频正常,也不停止且数据偏高和偏低也推送到iot
  1802. if (phrFreqstatus != null && isAbnormal != 0)
  1803. {
  1804. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1805. }
  1806. #endregion
  1807. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  1808. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  1809. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  1810. // 胎心数据推送到第三方
  1811. var topic = "topic.push.third";
  1812. var fhrThridMsg = new
  1813. {
  1814. messageId = fhrMsgId,
  1815. topic = topic,
  1816. time = fhrMsgTime,
  1817. data = new
  1818. {
  1819. imei = heartRate.Serialno,
  1820. value = fetalHeartRate,
  1821. isAbnormal,
  1822. type = "fetalHeart"
  1823. }
  1824. };
  1825. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  1826. // 胎心数据推送到微信
  1827. if (isAbnormal != 0)
  1828. {
  1829. topic = "topic.push.wx";
  1830. var fhrMsg = new
  1831. {
  1832. messageId = fhrMsgId,
  1833. topic = topic,
  1834. time = fhrMsgTime,
  1835. data = new
  1836. {
  1837. deviceId = device?.DeviceId,
  1838. imei = heartRate.Serialno,
  1839. alarmTypeId = 12,
  1840. alarmDeviceName = heartRate.Serialno,
  1841. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  1842. address = string.Empty,
  1843. deviceKey = device?.DeviceId
  1844. }
  1845. };
  1846. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  1847. }
  1848. }
  1849. /// <summary>
  1850. /// 高频胎心处理
  1851. /// 1. 高频数据触发连续12个值都是正常的的高频心率处理
  1852. /// 2. 高频结束后的highFreqSampleTimes=0的高频心率处理
  1853. /// 3. 高频结束后的在highFreqSampleTimes>0 正常心率触发的高频心率处理(常态)
  1854. /// 4. 高频结束后的时间倒序的正常心率触发的高频心率处理
  1855. /// 5. 高频结束后计算胎心数据,防止结束后与常规心理的胎心处理过长,定时器时长highFreqSampleInterval触发的高频心率处理
  1856. /// 高频结束后超过9分钟且不在阈值内才告警
  1857. /// </summary>
  1858. /// <param name="heartRate"></param>
  1859. /// <param name="commonPHR"></param>
  1860. /// <param name="highFreqSampleTimes"></param>
  1861. /// <param name="upperAlarmThreshold"></param>
  1862. /// <param name="lowerAlarmThreshold"></param>
  1863. /// <param name="sampleTime"></param>
  1864. /// <param name="statStartTime"></param>
  1865. /// <param name="statEndTime"></param>
  1866. /// <returns></returns>
  1867. private async Task SaveAndPushFetalHeartRateEndFreqHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int highFreqSampleTimes, int upperAlarmThreshold, int lowerAlarmThreshold, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  1868. {
  1869. // 计算胎心=孕妇心率*系数
  1870. #region 胎心系数使用基于心率与中位数对比
  1871. var coefficient = 0f;
  1872. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  1873. if (heartRate.HeartRate < commonPHR!.Mode)
  1874. {
  1875. coefficient = commonPHR.StatMinValueFprCoefficient!;
  1876. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  1877. }
  1878. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  1879. else if (heartRate.HeartRate > commonPHR.Mode)
  1880. {
  1881. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  1882. {
  1883. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  1884. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  1885. }
  1886. else
  1887. {
  1888. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  1889. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  1890. }
  1891. }
  1892. else
  1893. {
  1894. coefficient = commonPHR.StatModeAvgFprCoefficient;
  1895. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  1896. }
  1897. #endregion
  1898. var fetalHeartRate = SafeType.SafeInt(heartRate.HeartRate! * coefficient);
  1899. // 胎心的最大值调整为220,超过都按该值220输出
  1900. // fetalHeartRate = fetalHeartRate>= 220 ? 220 : fetalHeartRate;
  1901. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  1902. var isAbnormal = 0;
  1903. #region 判断是否够highFreqSampleTimes,540s
  1904. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)heartRate.LastUpdate!, phrFreqstatus!.LastUpdate);
  1905. // 判断是否够highFreqSampleTimes,540s
  1906. ///高频时长不足10分钟停止高频的胎心值生成说明:最近12个数据的最小值生成胎心值,
  1907. ///对于小于高频下限阀值取高频下限阀值进行转换;
  1908. ///对于高于高频上限阀值取高频上限阀值进行转换。并输出相关日志后续进行数据分析。
  1909. if (ts < highFreqSampleTimes)
  1910. {
  1911. if (fetalHeartRate > upperAlarmThreshold)
  1912. {
  1913. _logger.LogWarning($"{heartRate.Serialno} 高频持续不足10分钟,计算胎心值 {fetalHeartRate} 高于高频警告上限阀值{upperAlarmThreshold},最后胎心值{upperAlarmThreshold},并且不告警");
  1914. fetalHeartRate = upperAlarmThreshold;
  1915. }
  1916. else if (fetalHeartRate < lowerAlarmThreshold)
  1917. {
  1918. _logger.LogWarning($"{heartRate.Serialno} 高频持续不足10分钟,计算胎心值 {fetalHeartRate} 低于高频警告下限阀值 {lowerAlarmThreshold},最后胎心值{lowerAlarmThreshold},并且不告警");
  1919. fetalHeartRate = lowerAlarmThreshold;
  1920. }
  1921. else
  1922. {
  1923. _logger.LogWarning($"{heartRate.Serialno} 高频持续不足10分钟,在高频警告下限阀值 {lowerAlarmThreshold} 和 高频警告上限阀值:{upperAlarmThreshold}之间,最后胎心值{fetalHeartRate},并且不告警");
  1924. }
  1925. }
  1926. // 超过highFreqSampleTimes,540s
  1927. else
  1928. {
  1929. if (fetalHeartRate > 220)
  1930. {
  1931. fetalHeartRate = 220;
  1932. _logger.LogWarning($"{heartRate.Serialno} 大于220,按220输出,计算因子:孕妇心率 {heartRate.HeartRate},系数 {coefficient},周期 周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1933. }
  1934. // 胎心的最小值调整为90,超过都按该值90
  1935. if (fetalHeartRate < 90)
  1936. {
  1937. fetalHeartRate = 90;
  1938. _logger.LogWarning($"{heartRate.Serialno} 小于90,按90输出,计算因子:孕妇心率 {heartRate.HeartRate},系数 {coefficient},周期 周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1939. }
  1940. isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  1941. }
  1942. #endregion
  1943. //if (phrFreqstatus == null) isAbnormal = 0;
  1944. //var statsusDesc = (phrFreqstatus == null) ? "常规" : "高频";
  1945. var statsusDesc = "高频";
  1946. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1947. // 保存到 数据服务 MySQL 数据库
  1948. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  1949. {
  1950. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  1951. PersonId = commonPHR!.PersonId,
  1952. Serialno = heartRate.Serialno,
  1953. HeartRate = fetalHeartRate,
  1954. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  1955. IsAbnormal = isAbnormal,
  1956. StatStartTime = statStartTime,
  1957. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  1958. CreateTime = DateTime.Now,
  1959. Method = 1,
  1960. IsDisplay = 1,
  1961. DeviceKey = commonPHR!.DeviceKey
  1962. };
  1963. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  1964. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  1965. // 推送最后一条常规心率计算的胎心数据到iot设备
  1966. #region 推送最后一条常规心率计算的胎心数据到iot设备
  1967. // 高频(<=12)-常规
  1968. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  1969. if (lastPhr.MessageId == heartRate.MessageId && phrFreqstatus == null)
  1970. {
  1971. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1972. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(<=12)-常规");
  1973. }
  1974. // 高频(13)-常规-高频(13)
  1975. if (phrFreqstatus != null)
  1976. {
  1977. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 1);
  1978. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1979. // 获取高频数据
  1980. var freqCollection = new List<PregnancyHeartRateModel>();
  1981. PregnancyHeartRateModel? previousItem = null;
  1982. foreach (var item in phr)
  1983. {
  1984. if (previousItem != null)
  1985. {
  1986. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1987. if (timeNextDiff <= 60)
  1988. {
  1989. freqCollection.Add(item);
  1990. }
  1991. }
  1992. // 高频最后一条
  1993. if (lastPhr.MessageId == item.MessageId)
  1994. {
  1995. freqCollection.Add(item);
  1996. }
  1997. previousItem = item;
  1998. }
  1999. //去除高频
  2000. foreach (var item in freqCollection)
  2001. {
  2002. phr.Remove(item);
  2003. }
  2004. lastPhr = phr.FirstOrDefault();
  2005. if (lastPhr?.MessageId == heartRate.MessageId)
  2006. {
  2007. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  2008. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(13)-常规-高频(13)");
  2009. }
  2010. }
  2011. #endregion
  2012. #region 高频心率计算胎心数据到iot设备
  2013. // 高频(17) ,连续12个高频正常,也不停止且数据偏高和偏低也推送到iot
  2014. if (phrFreqstatus != null && isAbnormal != 0)
  2015. {
  2016. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  2017. }
  2018. #endregion
  2019. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  2020. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  2021. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  2022. // 胎心数据推送到第三方
  2023. var topic = "topic.push.third";
  2024. var fhrThridMsg = new
  2025. {
  2026. messageId = fhrMsgId,
  2027. topic = topic,
  2028. time = fhrMsgTime,
  2029. data = new
  2030. {
  2031. imei = heartRate.Serialno,
  2032. value = fetalHeartRate,
  2033. isAbnormal,
  2034. type = "fetalHeart"
  2035. }
  2036. };
  2037. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  2038. // 胎心数据推送到微信
  2039. if (isAbnormal != 0)
  2040. {
  2041. topic = "topic.push.wx";
  2042. var fhrMsg = new
  2043. {
  2044. messageId = fhrMsgId,
  2045. topic = topic,
  2046. time = fhrMsgTime,
  2047. data = new
  2048. {
  2049. deviceId = device?.DeviceId,
  2050. imei = heartRate.Serialno,
  2051. alarmTypeId = 12,
  2052. alarmDeviceName = heartRate.Serialno,
  2053. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  2054. address = string.Empty,
  2055. deviceKey = device?.DeviceId
  2056. }
  2057. };
  2058. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  2059. }
  2060. }
  2061. /// <summary>
  2062. /// 去除高频数据
  2063. /// </summary>
  2064. /// <param name="phr"></param>
  2065. /// <param name="highFreqSampleInterva"></param>
  2066. /// <returns></returns>
  2067. private static List<PregnancyHeartRateModel> GetNonFreqPregnancyHeartRate(List<PregnancyHeartRateModel> phr, int highFreqSampleInterval)
  2068. {
  2069. //phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  2070. //var result = new List<PregnancyHeartRateModel>();
  2071. //PregnancyHeartRateModel? previousItem = null;
  2072. //foreach (var item in phr)
  2073. //{
  2074. // if (previousItem != null)
  2075. // {
  2076. // var timeNextDiff =(previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  2077. // if (timeNextDiff > highFreqSampleInterval)
  2078. // {
  2079. // result.Add(previousItem);
  2080. // }
  2081. // }
  2082. // previousItem = item;
  2083. //}
  2084. //// 添加上一个
  2085. //if (previousItem != null)
  2086. //{
  2087. // result.Add(previousItem);
  2088. //}
  2089. //return result;
  2090. #region 反向
  2091. var phr1 = phr.OrderByDescending(i => i.LastUpdate).ToList();
  2092. var result = new List<PregnancyHeartRateModel>();
  2093. PregnancyHeartRateModel? previousItem1 = null;
  2094. foreach (var item in phr1)
  2095. {
  2096. if (previousItem1 != null)
  2097. {
  2098. var timeNextDiff = (previousItem1!.LastUpdate - item.LastUpdate).TotalSeconds;
  2099. if (timeNextDiff > highFreqSampleInterval)
  2100. {
  2101. result.Add(previousItem1);
  2102. }
  2103. }
  2104. previousItem1 = item;
  2105. }
  2106. // 添加上一个
  2107. if (previousItem1 != null)
  2108. {
  2109. result.Add(previousItem1);
  2110. }
  2111. #endregion
  2112. #region 正向
  2113. var phr2 = phr.OrderByDescending(i => i.LastUpdate).ToList(); ;
  2114. var freqCollection = new List<PregnancyHeartRateModel>();
  2115. PregnancyHeartRateModel? previousItem = null;
  2116. foreach (var item in phr2)
  2117. {
  2118. if (previousItem != null)
  2119. {
  2120. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  2121. if (timeNextDiff <= highFreqSampleInterval)
  2122. {
  2123. freqCollection.Add(item);
  2124. }
  2125. }
  2126. previousItem = item;
  2127. }
  2128. //去除高频
  2129. foreach (var item in freqCollection)
  2130. {
  2131. phr2.Remove(item);
  2132. }
  2133. #endregion
  2134. // 交集
  2135. var commonElements = phr2.Intersect(result).ToList();
  2136. return commonElements;
  2137. }
  2138. /// <summary>
  2139. /// 获取高频数据
  2140. /// </summary>
  2141. /// <param name="phr"></param>
  2142. /// <param name="highFreqSampleInterval"></param>
  2143. /// <returns></returns>
  2144. private static List<PregnancyHeartRateModel> GetFreqPregnancyHeartRate(List<PregnancyHeartRateModel> phr, int highFreqSampleInterval)
  2145. {
  2146. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  2147. var freqCollection = new List<PregnancyHeartRateModel>();
  2148. PregnancyHeartRateModel? previousItem = null;
  2149. foreach (var item in phr)
  2150. {
  2151. if (previousItem != null)
  2152. {
  2153. var timeNextDiff = (previousItem.LastUpdate - item.LastUpdate).TotalSeconds;
  2154. if (timeNextDiff <= highFreqSampleInterval)
  2155. {
  2156. freqCollection.Add(previousItem);
  2157. }
  2158. }
  2159. previousItem = item;
  2160. }
  2161. // 检查最后一条是否高频
  2162. if (previousItem != null && (phr.Last().LastUpdate - previousItem.LastUpdate).TotalSeconds <= highFreqSampleInterval)
  2163. {
  2164. freqCollection.Add(previousItem);
  2165. }
  2166. return freqCollection;
  2167. }
  2168. public async Task CalculateNormalFetalHeartRateIntervalAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR,int highFreqSampleInterval)
  2169. {
  2170. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  2171. var now = DateTime.Now;
  2172. var filteredPhr = daysPhr.Where(i => i.LastUpdate >= heartRate.LastUpdate && i.LastUpdate <= now).ToList();
  2173. // 去除高频
  2174. var normalPhr = GetNonFreqPregnancyHeartRate(filteredPhr, highFreqSampleInterval).OrderBy(i => i.LastUpdate);
  2175. if (normalPhr.ToList().Count==0)
  2176. {
  2177. _logger.LogWarning($"{heartRate.Serialno} 时间段{heartRate.LastUpdate}-{now},去除高频心率数据后,没有常规数据,不计算常规胎心数据");
  2178. return;
  2179. }
  2180. var startPhr = normalPhr.First();
  2181. var endPhr = normalPhr.Last();
  2182. //var sampleTime = GetSampleTimeFromLastUpdate((DateTime)heartRate.LastUpdate!, INTERVAL_FHR);
  2183. // 数据统计边界
  2184. var boundaryStatStartTime = GetSampleTimeFromLastUpdate((DateTime)startPhr.LastUpdate!, INTERVAL_FHR);
  2185. var boundaryStatEndTime = GetSampleTimeFromLastUpdate((DateTime)endPhr.LastUpdate!, INTERVAL_FHR).AddMinutes(INTERVAL_FHR);
  2186. _logger.LogInformation($"{heartRate.Serialno} 常规胎心统计边界{boundaryStatStartTime}-{boundaryStatEndTime}");
  2187. try
  2188. {
  2189. //var CalNow = DateTime.Now;
  2190. //var during = TimeSpan.FromSeconds(300); //5分钟
  2191. var c = 0;
  2192. while (true)
  2193. {
  2194. //if (DateTime.Now - CalNow > during)
  2195. //{
  2196. // _logger.LogInformation($"{heartRate.Serialno} 超过1分钟,迭代完成跳出循环 ");
  2197. // break;
  2198. //}
  2199. await Task.Delay(TimeSpan.FromSeconds(1));
  2200. var segmentStatStartTime = boundaryStatStartTime.AddMinutes(c * INTERVAL_FHR);
  2201. var segmentStatEndTime = segmentStatStartTime.AddMinutes(INTERVAL_FHR);
  2202. c++;
  2203. var statStartTime = segmentStatStartTime;
  2204. var statEndTime = segmentStatEndTime;
  2205. _logger.LogInformation($"{heartRate.Serialno} 当前统计周期{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  2206. if (statEndTime > boundaryStatEndTime)
  2207. {
  2208. _logger.LogInformation($"{heartRate.Serialno} 常规胎心统计超过时间边界,迭代完成跳出循环 ");
  2209. break;
  2210. }
  2211. var segmentPhr = normalPhr
  2212. .Where(i => i.LastUpdate <= statEndTime && i.LastUpdate >= statStartTime)
  2213. .ToList();
  2214. if (segmentPhr.Count == 0)
  2215. {
  2216. // 跳出当次迭代,进入下次迭代
  2217. _logger.LogWarning($"{heartRate.Serialno} 统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")} 孕妇心率数据不足,{segmentPhr.Count}条记录,不处理");
  2218. continue;
  2219. }
  2220. _logger.LogInformation($"{heartRate.Serialno} 当前统计周期{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")},对应的常规心率ID{string.Join(",", segmentPhr.Select(i=>i.MessageId))}");
  2221. var sampleTime = DateTimeUtil.ConvertToTimeStamp(segmentStatStartTime).ToString();
  2222. sampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime;
  2223. //检测 是否存在,不存在则处理
  2224. GeneralParam param = new()
  2225. {
  2226. Filters = new List<QueryFilterCondition>
  2227. {
  2228. new ()
  2229. {
  2230. Key=nameof(HisGpsFetalHeartRate.Serialno),
  2231. Value=heartRate.Serialno,
  2232. ValueType=QueryValueTypeEnum.String,
  2233. Operator=QueryOperatorEnum.Equal
  2234. },
  2235. new ()
  2236. {
  2237. Key=nameof(HisGpsFetalHeartRate.SampleTime),
  2238. Value=sampleTime,
  2239. ValueType=QueryValueTypeEnum.String,
  2240. Operator=QueryOperatorEnum.Equal
  2241. },
  2242. },
  2243. OrderBys = new List<OrderByCondition>
  2244. {
  2245. new (){
  2246. IsDesc=true,
  2247. Key=nameof(HisGpsFetalHeartRate.SampleTime)
  2248. }
  2249. }
  2250. };
  2251. var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, heartRate.Serialno[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  2252. if (fhr == null)
  2253. {
  2254. var avgPhr = segmentPhr.Count == 1
  2255. ? segmentPhr.First().PregnancyHeartRate
  2256. : segmentPhr.Average(i => i.PregnancyHeartRate);
  2257. heartRate.HeartRate = (int)avgPhr;
  2258. #region 胎心系数使用基于心率与中位数对比
  2259. var coefficient = 0f;
  2260. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  2261. if (heartRate.HeartRate < commonPHR!.Mode)
  2262. {
  2263. coefficient = commonPHR.StatMinValueFprCoefficient!;
  2264. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  2265. }
  2266. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  2267. else if (heartRate.HeartRate > commonPHR.Mode)
  2268. {
  2269. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  2270. {
  2271. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  2272. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  2273. }
  2274. else
  2275. {
  2276. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  2277. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  2278. }
  2279. }
  2280. else
  2281. {
  2282. coefficient = commonPHR.StatModeAvgFprCoefficient;
  2283. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  2284. }
  2285. #endregion
  2286. #region 胎心阈值判断
  2287. //var fetalHeartRate = SafeType.SafeInt(heartRate.HeartRate * coefficient);
  2288. //// 胎心的最大值调整为220,超过都按该值220输出
  2289. //// fetalHeartRate = fetalHeartRate>= 220 ? 220 : fetalHeartRate;
  2290. //if (fetalHeartRate > 220)
  2291. //{
  2292. // fetalHeartRate = 220;
  2293. // _logger.LogWarning($"{heartRate.Serialno} 大于220,按220输出,计算因子:孕妇心率 {heartRate.HeartRate},系数 {coefficient},周期 周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  2294. //}
  2295. //// 胎心的最小值调整为90,超过都按该值90
  2296. //if (fetalHeartRate < 90)
  2297. //{
  2298. // fetalHeartRate = 90;
  2299. // _logger.LogWarning($"{heartRate.Serialno} 小于90,按90输出,计算因子:孕妇心率 {heartRate.HeartRate},系数 {coefficient},周期 周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  2300. //}
  2301. // 计算胎心率并进行边界检查
  2302. var fetalHeartRate = Math.Clamp((int)(heartRate.HeartRate * coefficient), 90, 220);
  2303. if (fetalHeartRate != (int)(heartRate.HeartRate * coefficient))
  2304. {
  2305. _logger.LogWarning($"{heartRate.Serialno} 胎心率超出范围, 按修正值 {fetalHeartRate} 输出, 计算因子:孕妇心率 {heartRate.HeartRate}, 系数 {coefficient}, 周期 {statStartTime} - {statEndTime}");
  2306. }
  2307. #endregion
  2308. _logger.LogInformation($"{heartRate.Serialno} 在 常规 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  2309. var isAbnormal = 0;
  2310. #region 保存到Mysql数据库
  2311. // 保存到 数据服务 MySQL 数据库
  2312. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  2313. {
  2314. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  2315. PersonId = commonPHR!.PersonId,
  2316. Serialno = heartRate.Serialno,
  2317. HeartRate = fetalHeartRate,
  2318. SampleTime = sampleTime,
  2319. IsAbnormal = isAbnormal,
  2320. StatStartTime = statStartTime,
  2321. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  2322. CreateTime = DateTime.Now,
  2323. Method = 1,
  2324. IsDisplay = 1,
  2325. DeviceKey = commonPHR!.DeviceKey
  2326. };
  2327. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  2328. #endregion
  2329. #region 推送最后一条常规心率计算的胎心数据到iot设备
  2330. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  2331. if (segmentStatEndTime == boundaryStatEndTime)
  2332. {
  2333. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  2334. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备");
  2335. }
  2336. #endregion
  2337. #region 推送到第三方
  2338. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  2339. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  2340. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  2341. var topic = "topic.push.third";
  2342. var fhrThridMsg = new
  2343. {
  2344. messageId = fhrMsgId,
  2345. topic = topic,
  2346. time = fhrMsgTime,
  2347. data = new
  2348. {
  2349. imei = heartRate.Serialno,
  2350. value = fetalHeartRate,
  2351. isAbnormal,
  2352. type = "fetalHeart"
  2353. }
  2354. };
  2355. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  2356. #endregion
  2357. #region 推送到微信
  2358. if (isAbnormal != 0)
  2359. {
  2360. topic = "topic.push.wx";
  2361. var fhrMsg = new
  2362. {
  2363. messageId = fhrMsgId,
  2364. topic = topic,
  2365. time = fhrMsgTime,
  2366. data = new
  2367. {
  2368. deviceId = device?.DeviceId,
  2369. imei = heartRate.Serialno,
  2370. alarmTypeId = 12,
  2371. alarmDeviceName = heartRate.Serialno,
  2372. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  2373. address = string.Empty,
  2374. deviceKey = device?.DeviceId
  2375. }
  2376. };
  2377. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  2378. }
  2379. #endregion
  2380. }
  2381. else
  2382. {
  2383. _logger.LogInformation($"{heartRate.Serialno},统计常规胎心周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")} ,常规胎心已处理");
  2384. }
  2385. //await Task.Delay(TimeSpan.FromSeconds(1));
  2386. // 跳出循环
  2387. if (statEndTime.ToString("yyyyMMddHHmm") == boundaryStatEndTime.ToString("yyyyMMddHHmm"))
  2388. {
  2389. _logger.LogInformation($"{heartRate.Serialno} 迭代完成跳出循环 ");
  2390. break;
  2391. }
  2392. //if (statEndTime>= boundaryStatEndTime)
  2393. //{
  2394. // _logger.LogInformation($"{heartRate.Serialno} 时间边界,迭代完成跳出循环 ");
  2395. // break;
  2396. //}
  2397. }
  2398. }
  2399. catch (Exception ex)
  2400. {
  2401. _logger.LogError($"处理常规胎心数据时发生错误: {ex.Message}");
  2402. }
  2403. //for (var segmentStatStartTime = boundaryStatStartTime;
  2404. // segmentStatStartTime < boundaryStatEndTime;
  2405. // segmentStatStartTime = segmentStatStartTime.AddMinutes(INTERVAL_FHR))
  2406. //{
  2407. // var segmentStatEndTime = segmentStatStartTime.AddMinutes(INTERVAL_FHR);
  2408. // var segmentPhr = daysPhr
  2409. // .Where(i => i.LastUpdate <= segmentStatEndTime && i.LastUpdate >= segmentStatStartTime)
  2410. // .ToList();
  2411. // if (segmentStatEndTime == boundaryStatEndTime)
  2412. // {
  2413. // break;
  2414. // }
  2415. //}
  2416. }
  2417. public async Task CalculateFetalMovementIntervalAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR,DateTime edoc)
  2418. {
  2419. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  2420. DateTime fmNow = DateTime.Now;
  2421. int fmNowHour = fmNow.Hour;
  2422. DateTime startHour;
  2423. DateTime endHour;
  2424. if (fmNow.Subtract((DateTime)heartRate.LastUpdate!).Hours>2)
  2425. {
  2426. _logger.LogWarning($"{heartRate.Serialno} 当前计算时间与lastUpdate 时差超过2小时,将从当前触发心率到当天的所有心率计算对应的胎动");
  2427. startHour = ((DateTime)heartRate.LastUpdate!).Date.AddHours(((DateTime)heartRate.LastUpdate!).Hour);
  2428. endHour = ((DateTime)heartRate.LastUpdate!).Date.AddDays(1);
  2429. }
  2430. else
  2431. {
  2432. // 跨天
  2433. if (fmNowHour == 1)
  2434. {
  2435. // last_update 23~0
  2436. startHour = fmNow.Date.AddDays(-1).AddHours(((DateTime)heartRate.LastUpdate!).Hour);
  2437. endHour = fmNow.Date;
  2438. }
  2439. else
  2440. {
  2441. // last_update 0~1->2,1~2->3,2~3->4...21~22->23
  2442. startHour = fmNow.Date.AddHours(((DateTime)heartRate.LastUpdate!).Hour);
  2443. endHour = fmNow.Date.AddHours(fmNowHour - 1);
  2444. }
  2445. }
  2446. try
  2447. {
  2448. var filterPhr = daysPhr
  2449. .Where(i => i.LastUpdate >= startHour && i.LastUpdate <= endHour)
  2450. .OrderBy(i => i.LastUpdate).ToList();
  2451. //if (filterPhr.Count < 2)
  2452. //{
  2453. // _logger.LogWarning($"{heartRate.Serialno} 胎动统计数据少于2条,不统计,{string.Join('-', filterPhr.Select(i=>i.LastUpdate))}");
  2454. // return;
  2455. //}
  2456. if (filterPhr.Count < 1)
  2457. {
  2458. _logger.LogWarning($"{heartRate.Serialno} 胎动统计数据少于1条,不统计,{string.Join('-', filterPhr.Select(i => i.LastUpdate))}");
  2459. return;
  2460. }
  2461. var startPhr = filterPhr.First();
  2462. var endPhr = filterPhr.Last();
  2463. // 数据统计边界
  2464. var boundaryStatStartTime = startPhr.LastUpdate.Date.AddHours(startPhr.LastUpdate.Hour);
  2465. var boundaryStatEndTime = endPhr.LastUpdate.Date.AddHours(endPhr.LastUpdate.Hour + 1);
  2466. _logger.LogInformation($"{heartRate.Serialno} 胎动统计边界{boundaryStatStartTime}-{boundaryStatEndTime}");
  2467. var c = 0;
  2468. while (true)
  2469. {
  2470. await Task.Delay(TimeSpan.FromSeconds(1));
  2471. var segmentStatStartTime = boundaryStatStartTime.AddHours(c * 1);
  2472. var segmentStatEndTime = segmentStatStartTime.AddHours(1);
  2473. c++;
  2474. var statStartTime = segmentStatStartTime;
  2475. var statEndTime = segmentStatEndTime;
  2476. _logger.LogInformation($"{heartRate.Serialno} 当前胎动统计周期{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  2477. if (statEndTime > boundaryStatEndTime)
  2478. {
  2479. _logger.LogInformation($"{heartRate.Serialno} 常规胎心统计超过时间边界,迭代完成跳出循环 ");
  2480. break;
  2481. }
  2482. var segmentPhr = filterPhr
  2483. .Where(i => i.LastUpdate <= statEndTime && i.LastUpdate >= statStartTime)
  2484. .ToList();
  2485. if (segmentPhr.Count == 0)
  2486. {
  2487. // 跳出当次迭代,进入下次迭代
  2488. _logger.LogWarning($"{heartRate.Serialno} 胎动统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")} 孕妇心率数据不足,{segmentPhr.Count}条记录,不处理");
  2489. continue;
  2490. }
  2491. _logger.LogInformation($"{heartRate.Serialno} 当前胎动统计周期{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")},对应的常规心率ID{string.Join(",", segmentPhr.Select(i => i.MessageId))}");
  2492. // 0~1 点的lastUpdate数据sample_time是1点,计算是2点
  2493. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(statEndTime).ToString()[..10];
  2494. var isFetalMovementExisted = await _deviceCacheMgr.FetalMovementIsExistedAsync(heartRate.Serialno, fetalMovementSampleTime);
  2495. if (!isFetalMovementExisted)
  2496. {
  2497. /// 开始计算
  2498. var phrRange = segmentPhr.OrderByDescending(i => i.LastUpdate)
  2499. .Select(i => i.LastUpdate)
  2500. .ToList();
  2501. if (phrRange.Count >= 1)
  2502. {
  2503. // 读取胎心数据
  2504. GeneralParam param = new()
  2505. {
  2506. Filters = new List<QueryFilterCondition>
  2507. {
  2508. new ()
  2509. {
  2510. Key=nameof(HisGpsFetalHeartRate.Serialno),
  2511. Value=heartRate.Serialno,
  2512. ValueType=QueryValueTypeEnum.String,
  2513. Operator=QueryOperatorEnum.Equal
  2514. },
  2515. //new ()
  2516. //{
  2517. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  2518. // Value=sampleTime,
  2519. // ValueType=QueryValueTypeEnum.String,
  2520. // Operator=QueryOperatorEnum.GreaterEqual
  2521. //},
  2522. },
  2523. OrderBys = new List<OrderByCondition>
  2524. {
  2525. new (){
  2526. IsDesc=true,
  2527. Key=nameof(HisGpsFetalHeartRate.SampleTime)
  2528. }
  2529. }
  2530. };
  2531. var fetalHeartRateIsAbnormal = 0;
  2532. var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, heartRate.Serialno[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  2533. // 胎心数据时间与胎动时间一致
  2534. var time = long.Parse(fhr.SampleTime.Length < 13 ? fhr.SampleTime.PadRight(13, '0') : fhr.SampleTime);
  2535. var fhrSampleTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(time);
  2536. // 胎心数据时间与胎动时间一致,最后一条胎心数据与胎动数据的小时差不大于2
  2537. //if ((DateTime.Now.Hour - fhrSampleTime.Hour) <= 2)
  2538. if(true)
  2539. {
  2540. var duringMins = Math.Abs((phrRange.First() - phrRange.Last()).TotalMinutes);
  2541. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  2542. bool isInTimeRanges = IsLastUpdateInTimeRanges(phrRange.First());
  2543. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  2544. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  2545. {
  2546. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  2547. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  2548. .Where(i =>
  2549. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  2550. i.PregnancyPeriod[1] >= pregnancyWeeks)
  2551. .Select(i => i.MedianMovement)
  2552. .FirstOrDefault()
  2553. :
  2554. fetalMovementMap
  2555. .Where(i =>
  2556. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  2557. i.PregnancyPeriod[1] >= pregnancyWeeks)
  2558. .Select(i => i.InitialMovement)
  2559. .FirstOrDefault()
  2560. ;
  2561. // var fetalMovementTimeVar = (fetalMovementMapValue * duringMins * 2) / 120;
  2562. #region 取消使用时间长度比例
  2563. //var fetalMovementTimeVar = (fetalMovementMapValue * duringMins) / 60;
  2564. //if (duringMins < 59)
  2565. //{
  2566. // // 取12小时胎动总数最小值
  2567. // fetalMovementMapValue = fetalMovementMap
  2568. // .Where(i => i.PregnancyPeriod![0] <= pregnancyWeeks && i.PregnancyPeriod[1] >= pregnancyWeeks)
  2569. // .First()
  2570. // .TwelveHourMovementRange[0];
  2571. // //取12小时胎动总数最小值的平均值
  2572. // fetalMovementTimeVar = fetalMovementMapValue / 12;
  2573. // _logger.LogWarning($"{heartRate.Serialno} 佩戴不足1小时,12小时胎动总数最小值{fetalMovementMapValue},平均值{fetalMovementTimeVar}");
  2574. //}
  2575. #endregion
  2576. var fetalMovementTimeVar = (double)fetalMovementMapValue;
  2577. #region 生理健康与胎动的关系
  2578. /// (步数)运动步数超过1500步则加1;
  2579. /// (体温)低烧则胎动减1,高烧胎动减2;低烧是37.3~38.5,38.6以上是高烧。
  2580. /// (血压)血压收缩压大于160则加1。
  2581. /// (心理)心理压力高加2,压力中加1;
  2582. var fetalMovementStepVar = 0;
  2583. var fetalMovementTempVar = 0;
  2584. var fetalMovementBpVar = 0;
  2585. var fetalMovementPpVar = 0;
  2586. var fetalMovementFhrVar = 0;
  2587. // 步数
  2588. if (false)
  2589. {
  2590. var step = await _personCacheMgr.GetStepPeriodicityAsync(heartRate.Serialno);
  2591. if (step != null)
  2592. {
  2593. if (DateTime.Now.Hour - ((DateTime)step?.LastUpdate!).Hour <= 2)
  2594. {
  2595. if (step.Steps > 1500) fetalMovementStepVar = 1;
  2596. }
  2597. else
  2598. {
  2599. _logger.LogWarning($"{heartRate.Serialno} 周期步数 时间无效");
  2600. }
  2601. }
  2602. else
  2603. {
  2604. _logger.LogWarning($"{heartRate.Serialno} 周期步数无数据");
  2605. }
  2606. }
  2607. // 体温
  2608. if (true)
  2609. {
  2610. var temp = await _personCacheMgr.GetTemperaturePeriodicityAsync(heartRate.Serialno);
  2611. if (temp != null)
  2612. {
  2613. if (DateTime.Now.Hour - ((DateTime)temp?.LastUpdate!).Hour <= 2)
  2614. {
  2615. // 中烧
  2616. if (temp.Temperature >= 37.3M && temp.Temperature <= 38.5M)
  2617. {
  2618. fetalMovementTempVar = -1;
  2619. }
  2620. // 高烧
  2621. if (temp.Temperature >= 38.6M)
  2622. {
  2623. fetalMovementTempVar = -2;
  2624. }
  2625. }
  2626. else
  2627. {
  2628. _logger.LogWarning($"{heartRate.Serialno} 周期体温 时间无效");
  2629. }
  2630. }
  2631. else
  2632. {
  2633. _logger.LogWarning($"{heartRate.Serialno} 周期体温无数据");
  2634. }
  2635. }
  2636. // 血压
  2637. if (true)
  2638. {
  2639. var bp = await _personCacheMgr.GetBloodPressPeriodicityAsync(heartRate.Serialno);
  2640. if (bp != null)
  2641. {
  2642. if (DateTime.Now.Hour - ((DateTime)bp?.LastUpdate!).Hour <= 2)
  2643. {
  2644. if (bp.SystolicValue > 160)
  2645. {
  2646. fetalMovementBpVar = 1;
  2647. }
  2648. }
  2649. else
  2650. {
  2651. _logger.LogWarning($"{heartRate.Serialno} 周期血压 时间无效");
  2652. }
  2653. }
  2654. else
  2655. {
  2656. _logger.LogWarning($"{heartRate.Serialno} 周期血压无数据");
  2657. }
  2658. }
  2659. // 心理
  2660. if (false)
  2661. {
  2662. //-1 不处理,
  2663. //0 正常,
  2664. //1 轻度,
  2665. //2 中度;
  2666. //3 重度;
  2667. GeneralParam psychResultParam = new()
  2668. {
  2669. Filters = new List<QueryFilterCondition>
  2670. {
  2671. new ()
  2672. {
  2673. Key=nameof(HisGpsPsychResult.Serialno),
  2674. Value=heartRate.Serialno,
  2675. ValueType=QueryValueTypeEnum.String,
  2676. Operator=QueryOperatorEnum.Equal
  2677. },
  2678. //new ()
  2679. //{
  2680. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  2681. // Value=sampleTime,
  2682. // ValueType=QueryValueTypeEnum.String,
  2683. // Operator=QueryOperatorEnum.GreaterEqual
  2684. //},
  2685. },
  2686. OrderBys = new List<OrderByCondition>
  2687. {
  2688. new (){
  2689. IsDesc=true,
  2690. Key=nameof(HisGpsPsychResult.Serialno)
  2691. }
  2692. }
  2693. };
  2694. var psych = await _hisPsychResultApiClient.GetFirstAsync(psychResultParam, heartRate.Serialno[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  2695. if (psych != null)
  2696. {
  2697. if (psych?.StressScore == 2)
  2698. {
  2699. fetalMovementPpVar = 1;
  2700. }
  2701. if (psych?.StressScore == 3)
  2702. {
  2703. fetalMovementPpVar = 2;
  2704. }
  2705. }
  2706. else
  2707. {
  2708. _logger.LogWarning($"{heartRate.Serialno} 周期心理压力无数据");
  2709. }
  2710. }
  2711. #endregion
  2712. #region 胎心与胎动的关系
  2713. /// 胎心值过缓时,则胎动数量减1;胎心值过速时,则胎动也加1。
  2714. /// 此值允许在上限值上继续增加,在下限值上继续减少,最小值为0。
  2715. /// 告警上限阀值
  2716. //1表示偏高;2表示偏低
  2717. if (true)
  2718. {
  2719. if (fhr.IsAbnormal == 2)
  2720. {
  2721. fetalMovementPpVar = -1;
  2722. }
  2723. if (fhr.IsAbnormal == 1)
  2724. {
  2725. fetalMovementPpVar = 1;
  2726. }
  2727. }
  2728. #endregion
  2729. _logger.LogInformation($"{heartRate.Serialno} 时间比例胎动值:{fetalMovementTimeVar}, 步数参数变动值:{fetalMovementStepVar},体温参数变动值:{fetalMovementTempVar},血压参数变动值:{fetalMovementBpVar},心理压力参数变动值:{fetalMovementPpVar},胎心参数变动值:{fetalMovementFhrVar}");
  2730. var fetalMovementValue = fetalMovementTimeVar + fetalMovementStepVar + fetalMovementTempVar + fetalMovementBpVar + fetalMovementPpVar + fetalMovementFhrVar;
  2731. // 四舍五入
  2732. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  2733. _logger.LogInformation($"{heartRate.Serialno} 孕周:{pregnancyWeeks},胎动数据采样时间:{fetalMovementSampleTime}|{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 时间比例胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{phrRange.Last()}-{phrRange.First()}, 胎动计算值:{fetalMovementTimeVar}, 胎动四舍五入最终值:{fetalMovement} 已完成.");
  2734. // 获取胎心数据状态与胎动数据状态一致
  2735. //etalHeartRateIsAbnormal= fhr.IsAbnormal;
  2736. var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  2737. await _serviceIotApi.SetFetalMovementConfig(heartRate.Serialno, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  2738. // 保存到MySQL数据库
  2739. HisGpsFetalMovement fm = new()
  2740. {
  2741. FetalMovementId = Guid.NewGuid().ToString("D"),
  2742. PersonId = commonPHR!.PersonId,
  2743. Serialno = heartRate.Serialno,
  2744. CreateTime = DateTime.Now,
  2745. IsAbnormal = feltalMovementIsAbnormal,
  2746. FetalMovementValue = fetalMovement,
  2747. SampleTime = fetalMovementSampleTime,
  2748. Method = 1,
  2749. IsDisplay = 1,
  2750. DeviceKey = commonPHR!.DeviceKey
  2751. };
  2752. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  2753. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  2754. var fmMsgId = $"{heartRate.Serialno}-{fetalMovementSampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  2755. var fmMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  2756. // 胎动数据推送到第三方
  2757. var topic = "topic.push.third";
  2758. var fmThridMsg = new
  2759. {
  2760. messageId = fmMsgId,
  2761. topic = topic,
  2762. time = fmMsgTime,
  2763. data = new
  2764. {
  2765. imei = heartRate.Serialno,
  2766. value = fetalMovement,
  2767. isAbnormal = feltalMovementIsAbnormal,
  2768. type = "fetalMovement"
  2769. }
  2770. };
  2771. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, 31, fmThridMsg).ConfigureAwait(false);
  2772. // 胎动数据推送到微信
  2773. if (feltalMovementIsAbnormal != 0)
  2774. {
  2775. topic = "topic.push.wx";
  2776. var fmMsg = new
  2777. {
  2778. messageId = Guid.NewGuid().ToString("D"),
  2779. topic = topic,
  2780. time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss"),
  2781. data = new
  2782. {
  2783. deviceId = device?.DeviceId,
  2784. imei = heartRate.Serialno,
  2785. alarmTypeId = 12,
  2786. alarmDeviceName = heartRate.Serialno,
  2787. alarmRemarks = JsonConvert.SerializeObject(new { fetalMovementValue = fetalMovement, isAbnormal = feltalMovementIsAbnormal }),
  2788. address = string.Empty,
  2789. deviceKey = device?.DeviceId
  2790. }
  2791. };
  2792. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, fmMsg).ConfigureAwait(false);
  2793. }
  2794. // 设置入库缓存记录
  2795. await _deviceCacheMgr.SetFetalMovementAsync(heartRate.Serialno, fetalMovementSampleTime, fm);
  2796. }
  2797. else
  2798. {
  2799. _logger.LogWarning($"{heartRate.Serialno} 孕周 {pregnancyWeeks},超出胎动计算范围");
  2800. }
  2801. }
  2802. else
  2803. {
  2804. _logger.LogWarning($"{heartRate.Serialno} 最后一条胎心数据与胎动数据的小时差大于2,不计算胎动数据");
  2805. }
  2806. }
  2807. else
  2808. {
  2809. _logger.LogInformation($"{heartRate.Serialno} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 不足1条,不能判断是否持续佩戴");
  2810. }
  2811. }
  2812. else
  2813. {
  2814. _logger.LogInformation($"{heartRate.Serialno} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 已处理");
  2815. }
  2816. // 跳出循环
  2817. if (statEndTime.ToString("yyyyMMddHHmm") == boundaryStatEndTime.ToString("yyyyMMddHHmm"))
  2818. {
  2819. _logger.LogInformation($"{heartRate.Serialno} 胎动记录迭代完成跳出循环 ");
  2820. break;
  2821. }
  2822. else
  2823. {
  2824. _logger.LogInformation($"{heartRate.Serialno} 胎动周期{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}计算完成, ");
  2825. }
  2826. }
  2827. }
  2828. catch (Exception ex)
  2829. {
  2830. _logger.LogError($"处理胎动数据时发生错误: {ex.Message}");
  2831. }
  2832. }
  2833. //private DateTime GetSampleTimeFromLastUpdate(DateTime lastUpdate,int interval)
  2834. //{
  2835. // DateTime nowInterval = lastUpdate;
  2836. // //if (nowInterval.Second > 0)
  2837. // //{
  2838. // // nowInterval = nowInterval.AddMinutes(1);
  2839. // //}
  2840. // // 计算last_update到上一间隔的分钟数
  2841. // int minutesToSubtract = nowInterval.Minute % interval;
  2842. // // 计算上一间隔的时间
  2843. // DateTime previousInterval = nowInterval.AddMinutes(-minutesToSubtract).AddSeconds(-nowInterval.Second).AddMilliseconds(-nowInterval.Millisecond);
  2844. // return previousInterval;
  2845. //}
  2846. public static DateTime GetSampleTimeFromLastUpdate(DateTime lastUpdate, int interval)
  2847. {
  2848. // 获取当前的分钟
  2849. int minute = lastUpdate.Minute;
  2850. // 按 15 分钟为单位划分时间段
  2851. int intervalStartMinute = (minute / interval) * interval;
  2852. // 返回当前时间刻度下的 DateTime,保留小时和新计算的分钟,秒和毫秒设为0
  2853. return new DateTime(lastUpdate.Year, lastUpdate.Month, lastUpdate.Day, lastUpdate.Hour, intervalStartMinute, 0, 0);
  2854. }
  2855. public static string ExtractImei(string input)
  2856. {
  2857. // 提取 'imei/' 后的数字
  2858. string pattern = @"imei/(\d+)";
  2859. Match match = Regex.Match(input, pattern);
  2860. if (match.Success)
  2861. {
  2862. return match.Groups[1].Value;
  2863. }
  2864. else
  2865. {
  2866. return string.Empty;
  2867. }
  2868. }
  2869. }
  2870. }