DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/TelemetryService.cs

85 lines
2.8 KiB
C#
Raw Normal View History

2021-04-07 18:01:56 +05:00
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache;
using AutoMapper;
using System.Text.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services
{
public class TelemetryService : ITelemetryService
{
private readonly IAsbCloudDbContext db;
private readonly IMapper mapper;
private readonly ICacheTable<Telemetry> cacheTelemetry;
private readonly ICacheTable<Well> cacheWell;
2021-04-07 18:01:56 +05:00
public TelemetryService(IAsbCloudDbContext db, CacheDb cacheDb, MapperConfiguration mapperConfiguration)
{
this.db = db;
mapper = mapperConfiguration.CreateMapper();
cacheTelemetry = cacheDb.GetCachedTable<Telemetry>((AsbCloudDbContext)db);
cacheWell = cacheDb.GetCachedTable<Well>((AsbCloudDbContext)db);
2021-04-07 18:01:56 +05:00
}
public int? GetWellIdByUid(string uid)
2021-04-07 18:01:56 +05:00
{
var tele = cacheTelemetry.FirstOrDefault(t => t.RemoteUid == uid, RefreshMode.IfResultEmpty);
if (tele is null)
return null;
2021-04-07 18:01:56 +05:00
return cacheWell.FirstOrDefault(w => w?.IdTelemetry == tele.Id)?.Id;
}
private Telemetry GetOrCreateTelemetry(string uid)
=> cacheTelemetry.FirstOrDefault(t => t.RemoteUid == uid, RefreshMode.IfResultEmpty)
?? cacheTelemetry.Insert(new Telemetry{ RemoteUid = uid, });
public void UpdateData(string uid, TelemetryDataDto data)
{
var telemetry = GetOrCreateTelemetry(uid);
2021-04-07 18:01:56 +05:00
if ((data.DataSaub != default) && (data.DataSaub.Count() > 0))
2021-04-07 18:01:56 +05:00
{
DataSaubBase dataSaub = default;
2021-04-07 18:01:56 +05:00
foreach (var item in data.DataSaub)
{
dataSaub = mapper.Map<DataSaubBase>(item);
2021-04-07 18:01:56 +05:00
dataSaub.IdTelemetry = telemetry.Id;
db.DataSaubBases.Add(dataSaub);
}
if(dataSaub != default)
telemetry.LastDataSaub = dataSaub;
2021-04-07 18:01:56 +05:00
db.SaveChanges();
}
2021-04-07 18:01:56 +05:00
}
public void UpdateInfo(string uid, TelemetryInfoDto info)
{
var telemetry = cacheTelemetry.FirstOrDefault(t => t.RemoteUid == uid);
var infoJson = JsonSerializer.Serialize(info);
//TODO: update telemetry timezone
2021-04-07 18:01:56 +05:00
if (telemetry is null)
{
var newTelemetry = new Telemetry
{
RemoteUid = uid,
Info = infoJson,
2021-04-07 18:01:56 +05:00
};
telemetry = cacheTelemetry.Insert(newTelemetry);
}
else
cacheTelemetry.Update(t => t.RemoteUid == uid, t => t.Info = infoJson);
2021-04-07 18:01:56 +05:00
}
}
}