using AsbCloudDb.Model; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services.DetectOperations { public class DetectorService { readonly IEnumerable detectors = new List { new Detectors.DetectorSlipsTime(), // new Detectors.DetectorDrillingRotor(), // new Detectors.DetectorDrillingSlide(), }; private readonly int minStepLength; private readonly int minFragmentLength; public DetectorService() { minStepLength = detectors.Min(d => d.StepLength); minStepLength = minStepLength > 0 ? minStepLength : 3; minFragmentLength = detectors.Min(d => d.FragmentLength); minFragmentLength = minFragmentLength > 0 ? minFragmentLength : 6; } public async Task> DetectOperationsAsync(int idTelemetry, DateTimeOffset begin, IAsbCloudDbContext db, CancellationToken token) { var query = db.TelemetryDataSaub .AsNoTracking() .Where(d => d.IdTelemetry == idTelemetry) .Select(d => new DetectableTelemetry{ DateTime = d.DateTime, IdUser = d.IdUser, WellDepth = d.WellDepth, Pressure = d.Pressure, HookWeight = d.HookWeight, BlockPosition = d.BlockPosition, BitDepth = d.BitDepth, RotorSpeed = d.RotorSpeed, }) .OrderBy(d => d.DateTime); var take = 4 * 86_400; var startDate = begin; var detectedOperations = new List(8); var dbRequests_ = 0; var dbTime_ = 0d; var sw_ = new System.Diagnostics.Stopwatch(); var otherTime_ = 0d; while (true) { sw_.Restart(); var data = await query .Where(d => d.DateTime > startDate) .Take(take) .ToArrayAsync(token); sw_.Stop(); dbTime_ += sw_.ElapsedMilliseconds; dbRequests_++; sw_.Restart(); if (data.Length < minFragmentLength) break; var skip = 0; var isDetected = false; while (data.Length > skip + minFragmentLength) { var isDetected1 = false; foreach (var detector in detectors) { if(data.Length < skip + detector.StepLength + detector.FragmentLength) continue; var detectedOperation = detector.DetectOrDefault(data, ref skip); if (detectedOperation is not null) { isDetected1 = true; isDetected = true; detectedOperations.Add(detectedOperation); startDate = detectedOperation.End; break; } } if (!isDetected1) skip += minStepLength; } sw_.Stop(); otherTime_ += sw_.ElapsedMilliseconds; if (!isDetected) { if (data.Length < take) break; var lastPartDate = data.Last().DateTime; startDate = startDate + (0.75 * (lastPartDate - startDate)); } } return detectedOperations; } } }