DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/DetectOperations/OperationDetectionBackgroundService.cs

179 lines
6.7 KiB
C#
Raw Normal View History

2022-04-22 17:17:38 +05:00
using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
2022-04-22 17:17:38 +05:00
using System;
using System.Collections.Generic;
2022-06-15 14:57:37 +05:00
using System.Diagnostics;
2022-04-22 17:17:38 +05:00
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudInfrastructure.Services.DetectOperations.Detectors;
2022-04-22 17:17:38 +05:00
namespace AsbCloudInfrastructure.Services.DetectOperations
{
2022-07-04 17:33:32 +05:00
#nullable enable
2022-04-28 15:04:13 +05:00
public class OperationDetectionBackgroundService : BackgroundService
2022-04-22 17:17:38 +05:00
{
private readonly string connectionString;
private readonly TimeSpan period = TimeSpan.FromHours(1);
2022-04-22 17:17:38 +05:00
2022-06-30 17:37:57 +05:00
private static readonly DetectorAbstract[] detectors = new DetectorAbstract[]
{
2022-06-30 17:37:57 +05:00
new DetectorRotor(),
new DetectorSlide(),
new DetectorDevelopment(),
new DetectorTemplating(),
new DetectorSlipsTime(),
2022-07-20 09:49:36 +05:00
//new DetectorStaticSurveying(),
2022-07-19 10:29:38 +05:00
new DetectorFlashing(),
};
2022-04-28 15:04:13 +05:00
public OperationDetectionBackgroundService(IConfiguration configuration)
2022-04-22 17:17:38 +05:00
{
connectionString = configuration.GetConnectionString("DefaultConnection");
}
protected override async Task ExecuteAsync(CancellationToken token = default)
{
var timeToStartAnalysis = DateTime.Now;
var options = new DbContextOptionsBuilder<AsbCloudDbContext>()
.UseNpgsql(connectionString)
.Options;
while (!token.IsCancellationRequested)
{
if (DateTime.Now > timeToStartAnalysis)
{
timeToStartAnalysis = DateTime.Now + period;
try
{
using var context = new AsbCloudDbContext(options);
var added = await DetectedAllTelemetriesAsync(context, token);
Trace.TraceInformation($"Total detection complete. Added {added} operations.");
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
}
GC.Collect();
}
var ms = (int)(timeToStartAnalysis - DateTime.Now).TotalMilliseconds;
ms = ms > 100 ? ms : 100;
await Task.Delay(ms, token).ConfigureAwait(false);
}
}
public override async Task StopAsync(CancellationToken token)
{
await base.StopAsync(token).ConfigureAwait(false);
}
2022-07-04 17:50:16 +05:00
private static async Task<int> DetectedAllTelemetriesAsync(IAsbCloudDbContext db, CancellationToken token)
{
2022-04-28 15:04:13 +05:00
var lastDetectedDates = await db.DetectedOperations
.GroupBy(o => o.IdTelemetry)
.Select(g => new
{
IdTelemetry = g.Key,
LastDate = g.Max(o => o.DateEnd)
2022-04-28 15:04:13 +05:00
})
.ToListAsync(token);
var telemetryIds = await db.Telemetries
.Where(t => t.Info != null && t.TimeZone != null)
.Select(t => t.Id)
.ToListAsync(token);
2022-04-28 15:04:13 +05:00
var JounedlastDetectedDates = telemetryIds
.GroupJoin(lastDetectedDates,
t => t,
o => o.IdTelemetry,
2022-06-15 14:57:37 +05:00
(outer, inner) => new
{
2022-04-28 15:04:13 +05:00
IdTelemetry = outer,
2022-07-04 17:50:16 +05:00
inner.SingleOrDefault()?.LastDate,
2022-04-28 15:04:13 +05:00
});
var affected = 0;
2022-04-28 15:04:13 +05:00
foreach (var item in JounedlastDetectedDates)
{
var stopwatch = Stopwatch.StartNew();
2022-06-15 14:57:37 +05:00
var newOperations = await DetectOperationsAsync(item.IdTelemetry, item.LastDate ?? DateTimeOffset.MinValue, db, token);
stopwatch.Stop();
if (newOperations.Any())
{
db.DetectedOperations.AddRange(newOperations);
affected += await db.SaveChangesAsync(token);
2022-06-15 14:57:37 +05:00
}
}
return affected;
2022-04-22 17:17:38 +05:00
}
2022-07-04 17:50:16 +05:00
private static async Task<IEnumerable<DetectedOperation>> DetectOperationsAsync(int idTelemetry, DateTimeOffset begin, IAsbCloudDbContext db, CancellationToken token)
2022-04-22 17:17:38 +05:00
{
var query = db.TelemetryDataSaub
.AsNoTracking()
.Where(d => d.IdTelemetry == idTelemetry)
2022-06-15 14:57:37 +05:00
.Select(d => new DetectableTelemetry
{
2022-04-22 17:17:38 +05:00
DateTime = d.DateTime,
IdUser = d.IdUser,
2022-07-04 17:33:32 +05:00
WellDepth = d.WellDepth ?? float.NaN,
Pressure = d.Pressure ?? float.NaN,
HookWeight = d.HookWeight ?? float.NaN,
BlockPosition = d.BlockPosition ?? float.NaN,
BitDepth = d.BitDepth ?? float.NaN,
RotorSpeed = d.RotorSpeed ?? float.NaN,
2022-04-22 17:17:38 +05:00
})
.OrderBy(d => d.DateTime);
2022-06-27 12:43:55 +05:00
var take = 4 * 86_400; // 4 дня
2022-04-22 17:17:38 +05:00
var startDate = begin;
var detectedOperations = new List<DetectedOperation>(8);
2022-06-30 17:37:57 +05:00
DetectedOperation? lastDetectedOperation = null;
const int minOperationLength = 5;
const int maxDetectorsInterpolationFrameLength = 30;
const int gap = maxDetectorsInterpolationFrameLength + minOperationLength;
2022-04-22 17:17:38 +05:00
while (true)
{
var data = await query
.Where(d => d.DateTime > startDate)
.Take(take)
.ToArrayAsync(token);
2022-06-30 17:37:57 +05:00
if (data.Length < gap)
2022-04-22 17:17:38 +05:00
break;
var isDetected = false;
var positionBegin = 0;
2022-06-30 17:37:57 +05:00
var positionEnd = data.Length - gap;
while (positionEnd > positionBegin)
2022-04-22 17:17:38 +05:00
{
2022-06-30 17:37:57 +05:00
for (int i = 0; i < detectors.Length; i++)
2022-04-22 17:17:38 +05:00
{
2022-07-04 17:33:32 +05:00
if (detectors[i].TryDetect(idTelemetry, data, positionBegin, positionEnd, lastDetectedOperation, out OperationDetectorResult? result))
2022-04-22 17:17:38 +05:00
{
2022-07-04 17:33:32 +05:00
detectedOperations.Add(result!.Operation);
2022-06-30 17:37:57 +05:00
lastDetectedOperation = result.Operation;
isDetected = true;
2022-06-30 17:37:57 +05:00
positionBegin = result.TelemetryEnd;
break;
2022-04-22 17:17:38 +05:00
}
}
2022-06-30 17:37:57 +05:00
positionBegin++;
2022-04-22 17:17:38 +05:00
}
if (isDetected)
2022-07-04 17:33:32 +05:00
startDate = lastDetectedOperation!.DateEnd;
else
2022-06-30 17:37:57 +05:00
startDate = data[positionEnd].DateTime;
2022-04-22 17:17:38 +05:00
}
return detectedOperations;
}
}
2022-07-04 17:33:32 +05:00
#nullable disable
2022-04-22 17:17:38 +05:00
}