Merge branch 'TelemetryTimeZone' into dev

This commit is contained in:
Фролов 2021-11-22 11:31:10 +05:00
commit 14bc1e12b4
30 changed files with 3259 additions and 100 deletions

View File

@ -0,0 +1,24 @@
namespace AsbCloudApp.Data
{
public class TelemetryTimeZoneDto
{
public double Hours { get; set; }
public string TimeZoneId { get; set; }
public bool IsOverride { get; set; }
public override bool Equals(object obj)
{
if(obj is TelemetryTimeZoneDto tTimeZone
&& tTimeZone.Hours == Hours
&& tTimeZone.TimeZoneId == TimeZoneId
&& tTimeZone.IsOverride == IsOverride)
return true;
return false;
}
public override int GetHashCode()
=> Hours.GetHashCode()
| TimeZoneId.GetHashCode()
| IsOverride.GetHashCode();
}
}

View File

@ -0,0 +1,4 @@
namespace AsbCloudApp.Data
{
}

View File

@ -9,10 +9,11 @@ namespace AsbCloudApp.Services
public interface IMessageService
{
Task<PaginationContainer<MessageDto>> GetMessagesAsync(int idWell,
IEnumerable<int> categoryids = null, DateTime begin = default,
IEnumerable<int> categoryids = default, DateTime begin = default,
DateTime end = default, string searchString = default,
int skip = 0, int take = 32, CancellationToken token = default);
Task<DatesRangeDto> GetMessagesDatesRangeAsync(int idWell,
int skip = 0, int take = 32, bool isUtc = true,
CancellationToken token = default);
Task<DatesRangeDto> GetMessagesDatesRangeAsync(int idWell, bool isUtc,
CancellationToken token = default);
Task InsertAsync(string uid, IEnumerable<TelemetryMessageDto> dtos,
CancellationToken token);

View File

@ -14,12 +14,11 @@ namespace AsbCloudApp.Services
Action<object, int> handleReportProgress);
int GetReportPagesCount(int idWell, DateTime begin, DateTime end,
int stepSeconds, int format);
Task<List<ReportPropertiesDto>> GetSuitableReportsAsync(int idWell,
DateTime begin, DateTime end, int stepSeconds, int format,
CancellationToken token);
Task<DatesRangeDto> GetReportsDatesRangeAsync(int idWell,
CancellationToken token);
Task<DatesRangeDto> GetReportsDatesRangeAsync(int idWell, bool isUtc,
CancellationToken token = default);
Task<List<ReportPropertiesDto>> GetAllReportsByWellAsync(int idWell, CancellationToken token);
}
}

View File

@ -24,7 +24,7 @@ namespace AsbCloudApp.Services
int intervalHoursTimestamp, int workBeginTimestamp,
CancellationToken token = default);
Task AnalyzeAndSaveTelemetriesAsync(CancellationToken token = default);
Task<DatesRangeDto> GetOperationsDateRangeAsync(int idWell,
Task<DatesRangeDto> GetOperationsDateRangeAsync(int idWell, bool isUtc,
CancellationToken token = default);
}
}

View File

@ -8,8 +8,11 @@ namespace AsbCloudApp.Services
{
public interface ITelemetryDataService<TDto> where TDto : ITelemetryData
{
Task<IEnumerable<TDto>> GetAsync(int idWell, DateTime dateBegin = default, double intervalSec = 600, int approxPointsCount = 1024, CancellationToken token = default);
Task<DatesRangeDto> GetDataDatesRangeAsync(int idWell, CancellationToken token = default);
Task<IEnumerable<TDto>> GetAsync(int idWell,
DateTime dateBegin = default, double intervalSec = 600d,
int approxPointsCount = 1024, bool isUtc = false, CancellationToken token = default);
Task<DatesRangeDto> GetDataDatesRangeAsync(int idWell, bool isUtc = false,
CancellationToken token = default);
Task<int> UpdateDataAsync(string uid, IEnumerable<TDto> dtos, CancellationToken token = default);
}
}

View File

@ -8,10 +8,16 @@ namespace AsbCloudApp.Services
{
public interface ITelemetryService
{
ITimeZoneService TimeZoneService { get; }
int? GetidWellByTelemetryUid(string uid);
int GetOrCreateTemetryIdByUid(string uid);
double GetTimezoneOffsetByTelemetryId(int idTelemetry);
void UpdateInfo(string uid, TelemetryInfoDto info);
Task UpdateInfoAsync(string uid, TelemetryInfoDto info, CancellationToken token);
Task<double?> GetTelemetryTimeZoneOffsetAsync(int idTelemetry, CancellationToken token);
Task<DatesRangeDto> FixDatesRangeByTimeZoneAsync(int telemetryId, DatesRangeDto result,
CancellationToken token);
Task UpdateTimeZoneAsync(string uid, TelemetryTimeZoneDto telemetryTimeZoneInfo, CancellationToken token);
int? GetIdTelemetryByIdWell(int idWell);
int Merge(IEnumerable<int> telemetryIds);
IEnumerable<(string Key, int[] Ids)> GetRedundentRemoteUids();

View File

@ -0,0 +1,13 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services
{
public interface ITimeZoneService
{
DateTime DateToUtc(DateTime date, double remoteOTimezoneffsetHours);
DateTime DateToTimeZone(DateTime date, double remoteOTimezoneffsetHours);
Task<Data.TelemetryTimeZoneDto> GetByCoordinatesAsync(double latitude, double longitude, CancellationToken token);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,25 @@
using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore.Migrations;
namespace AsbCloudDb.Migrations
{
public partial class Add_Telemetry_TimeZone : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<TelemetryTimeZone>(
name: "timezone",
table: "t_telemetry",
type: "jsonb",
nullable: true,
comment: "Смещение часового пояса от UTC");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "timezone",
table: "t_telemetry");
}
}
}

View File

@ -768,6 +768,11 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone")
.HasColumnType("jsonb")
.HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC");
b.HasKey("Id");
b.HasIndex(new[] { "RemoteUid" }, "t_telemetry_remote_uid_index");

View File

@ -1,5 +1,4 @@
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
@ -27,6 +26,9 @@ namespace AsbCloudDb.Model
[Column("info", TypeName = "jsonb"), Comment("Информация с панели о скважине")]
public TelemetryInfo Info { get; set; }
[Column("timezone", TypeName = "jsonb"), Comment("Смещение часового пояса от UTC")]
public TelemetryTimeZone TelemetryTimeZone { get; set; }
[InverseProperty(nameof(Model.Well.Telemetry))]
public virtual Well Well { get; set; }

View File

@ -0,0 +1,9 @@
namespace AsbCloudDb.Model
{
public class TelemetryTimeZone
{
public double Hours { get; set; }
public string TimeZoneId { get; set; }
public bool IsOverride { get; set; }
}
}

View File

@ -47,6 +47,7 @@ namespace AsbCloudInfrastructure
services.AddTransient<IDrillingProgramService, DrillingProgramService>();
services.AddTransient<IDrillParamsService, DrillParamsService>();
services.AddTransient<IDrillFlowChartService, DrillFlowChartService>();
services.AddTransient<ITimeZoneService, TimeZoneService>();
// admin crud services:
services.AddTransient<ICrudService<DepositDto>, CrudServiceBase<DepositDto, Deposit>>();

View File

@ -40,7 +40,8 @@ namespace AsbCloudInfrastructure.Services.Analysis
try
{
using var context = new AsbCloudDbContext(options);
var telemetryService = new TelemetryService(context, telemetryTracker, cacheDb);
var timeZoneService = new TimeZoneService();
var telemetryService = new TelemetryService(context, telemetryTracker, timeZoneService, cacheDb);
var analyticsService = new TelemetryAnalyticsService(context,
telemetryService, cacheDb);

View File

@ -294,7 +294,7 @@ namespace AsbCloudInfrastructure.Services.Analysis
}
}
public async Task<DatesRangeDto> GetOperationsDateRangeAsync(int idWell,
public async Task<DatesRangeDto> GetOperationsDateRangeAsync(int idWell, bool isUtc,
CancellationToken token = default)
{
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
@ -315,13 +315,21 @@ namespace AsbCloudInfrastructure.Services.Analysis
.FirstOrDefaultAsync(token)
.ConfigureAwait(false);
return new DatesRangeDto
var result = new DatesRangeDto
{
From = DateTimeOffset.FromUnixTimeSeconds(datesRange.From).DateTime,
To = datesRange.To == default
? DateTime.MaxValue
: DateTimeOffset.FromUnixTimeSeconds(datesRange.To).DateTime
};
if (isUtc)
return result;
result = await telemetryService.FixDatesRangeByTimeZoneAsync((int)telemetryId, result, token)
.ConfigureAwait(false);
return result;
}
private async Task<DateTime> GetLastAnalysisDateAsync(int idTelemetry, CancellationToken token = default)

View File

@ -16,6 +16,7 @@ namespace AsbCloudInfrastructure.Services
{
private readonly IAsbCloudDbContext db;
private readonly ITelemetryService telemetryService;
private readonly CacheTable<Telemetry> cacheTelemetry;
private readonly CacheTable<TelemetryEvent> cacheEvents;
private readonly CacheTable<TelemetryUser> cacheTUsers;
@ -23,6 +24,7 @@ namespace AsbCloudInfrastructure.Services
{
this.db = db;
this.telemetryService = telemetryService;
cacheTelemetry = cacheDb.GetCachedTable<Telemetry>((AsbCloudDbContext)db);
cacheEvents = cacheDb.GetCachedTable<TelemetryEvent>((AsbCloudDbContext)db);
cacheTUsers = cacheDb.GetCachedTable<TelemetryUser>((AsbCloudDbContext)db);
}
@ -35,18 +37,19 @@ namespace AsbCloudInfrastructure.Services
string searchString = default,
int skip = 0,
int take = 32,
bool isUtc = true,
CancellationToken token = default)
{
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
if (telemetryId is null)
var idTelemetry = telemetryService.GetIdTelemetryByIdWell(idWell);
if (idTelemetry is null)
return null;
var events = cacheEvents.Where(e => e.IdTelemetry == telemetryId);
var events = cacheEvents.Where(e => e.IdTelemetry == idTelemetry);
if (!events.Any())
return null;
var query = db.TelemetryMessages.Where(m => m.IdTelemetry == telemetryId)
var query = db.TelemetryMessages.Where(m => m.IdTelemetry == idTelemetry)
.OrderBy(m => m.Date).AsNoTracking();
if ((categoryids?.Any() == true) || !string.IsNullOrEmpty(searchString))
@ -67,6 +70,16 @@ namespace AsbCloudInfrastructure.Services
query = query.OrderByDescending(m => m.Date);
var timeOffset = await telemetryService.GetTelemetryTimeZoneOffsetAsync(idTelemetry??default, token)
.ConfigureAwait(false);
if (timeOffset is not null)
{
begin = telemetryService.TimeZoneService.DateToUtc(begin, timeOffset ?? default);
end = telemetryService.TimeZoneService.DateToUtc(end, timeOffset ?? default);
}
if (begin != default)
query = query.Where(m => m.Date >= begin);
@ -89,7 +102,7 @@ namespace AsbCloudInfrastructure.Services
if (messagesList.Count == 0)
return result;
var users = cacheTUsers.Where(u => u.IdTelemetry == telemetryId);
var users = cacheTUsers.Where(u => u.IdTelemetry == idTelemetry);
foreach (var message in messagesList)
{
@ -121,10 +134,19 @@ namespace AsbCloudInfrastructure.Services
result.Items.Add(messageDto);
}
if (isUtc && timeOffset is not null)
return result;
result.Items = result.Items.Select(m =>
{
m.Date = telemetryService.TimeZoneService.DateToTimeZone( m.Date, timeOffset ?? default);
return m;
}).ToList();
return result;
}
public async Task<DatesRangeDto> GetMessagesDatesRangeAsync(int idWell,
public async Task<DatesRangeDto> GetMessagesDatesRangeAsync(int idWell, bool isUtc,
CancellationToken token = default)
{
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
@ -134,7 +156,15 @@ namespace AsbCloudInfrastructure.Services
var (From, To) = await db.GetDatesRangeAsync<TelemetryMessage>((int)telemetryId, token)
.ConfigureAwait(false);
return new DatesRangeDto { From = From, To = To };
var result = new DatesRangeDto { From = From, To = To };
if (isUtc)
return result;
result = await telemetryService.FixDatesRangeByTimeZoneAsync((int)telemetryId, result, token)
.ConfigureAwait(false);
return result;
}
public Task InsertAsync(string uid, IEnumerable<TelemetryMessageDto> dtos,

View File

@ -97,7 +97,7 @@ namespace AsbCloudInfrastructure.Services
return generator.GetPagesCount();
}
public async Task<DatesRangeDto> GetReportsDatesRangeAsync(int idWell,
public async Task<DatesRangeDto> GetReportsDatesRangeAsync(int idWell, bool isUtc,
CancellationToken token = default)
{
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
@ -121,11 +121,19 @@ namespace AsbCloudInfrastructure.Services
.FirstOrDefaultAsync(token)
.ConfigureAwait(false);
return new DatesRangeDto
var result = new DatesRangeDto
{
From = datesRange.From,
To = datesRange.To.Year == 1 ? DateTime.MaxValue : datesRange.To
};
if (isUtc)
return result;
result = await telemetryService.FixDatesRangeByTimeZoneAsync((int)telemetryId, result, token)
.ConfigureAwait(false);
return result;
}
public Task<List<ReportPropertiesDto>> GetSuitableReportsAsync(int idWell, DateTime begin, DateTime end, int stepSeconds, int format, CancellationToken token) =>

View File

@ -4,7 +4,6 @@ using AsbCloudDb.Model;
using AsbCloudDb;
using AsbCloudInfrastructure.Services.Cache;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@ -20,7 +19,6 @@ namespace AsbCloudInfrastructure.Services
{
private readonly IAsbCloudDbContext db;
private readonly ITelemetryService telemetryService;
protected readonly CacheTable<Telemetry> cacheTelemetry;
protected readonly CacheTable<TelemetryUser> cacheTelemetryUsers;
protected readonly CacheTable<Well> cacheWells;
@ -32,7 +30,6 @@ namespace AsbCloudInfrastructure.Services
{
this.db = db;
this.telemetryService = telemetryService;
cacheTelemetry = cacheDb.GetCachedTable<Telemetry>((AsbCloudDbContext)db);
cacheTelemetryUsers = cacheDb.GetCachedTable<TelemetryUser>((AsbCloudDbContext)db);
cacheWells = cacheDb.GetCachedTable<Well>((AsbCloudDbContext)db);
@ -59,36 +56,42 @@ namespace AsbCloudInfrastructure.Services
foreach (var duplicate in duplicates)
dtosList.Remove(duplicate);
}
var offsetHours = await telemetryService.GetTelemetryTimeZoneOffsetAsync(idTelemetry, token);
var enitties = dtosList.Select(d => {
var e = Convert(d);
e.IdTelemetry = idTelemetry;
return e;
var entities = dtosList.Select(d => {
var e = Convert(d);
e.IdTelemetry = idTelemetry;
if(offsetHours is not null)
e.Date = telemetryService.TimeZoneService.DateToUtc(d.Date, (double)offsetHours);
return e;
});
var dbset = db.Set<TModel>();
try
{
return await db.Database.ExecInsertOrUpdateAsync(dbset, enitties, token).ConfigureAwait(false);
return await db.Database.ExecInsertOrUpdateAsync(dbset, entities, token).ConfigureAwait(false);
}
catch(Exception ex)
{
Trace.WriteLine($"Fail to save data telemerty uid: {uid}, idTelemetry {idTelemetry} count: {enitties.Count()} dataDate: {enitties.FirstOrDefault()?.Date}. Message: {ex.Message}");
Trace.WriteLine($"Fail to save data telemerty uid: {uid}, idTelemetry {idTelemetry} count: {entities.Count()} dataDate: {entities.FirstOrDefault()?.Date}. Message: {ex.Message}");
return 0;
}
}
public virtual async Task<IEnumerable<TDto>> GetAsync(int idWell,
DateTime dateBegin = default, double intervalSec = 600d,
int approxPointsCount = 1024, CancellationToken token = default)
int approxPointsCount = 1024, bool isUtc = false, CancellationToken token = default)
{
var well = cacheWells.FirstOrDefault(w => w.Id == idWell);
if (well?.IdTelemetry is null)
return default;
var idTelemetry = well?.IdTelemetry ?? default;
if (dateBegin == default)
{
dateBegin = telemetryService.GetLastTelemetryDate(well.IdTelemetry ?? 0);
dateBegin = telemetryService.GetLastTelemetryDate(idTelemetry);
if (dateBegin != default)
dateBegin = dateBegin.AddSeconds(-intervalSec);
}
@ -99,13 +102,19 @@ namespace AsbCloudInfrastructure.Services
if (dateBegin.Kind == DateTimeKind.Unspecified)
dateBegin = DateTime.SpecifyKind(dateBegin, DateTimeKind.Utc);
var datEnd = dateBegin.AddSeconds(intervalSec);
var timeOffset = await telemetryService.GetTelemetryTimeZoneOffsetAsync(idTelemetry, token)
.ConfigureAwait(false);
if(timeOffset is not null)
dateBegin = telemetryService.TimeZoneService.DateToUtc(dateBegin, timeOffset?? default);
var dateEnd = dateBegin.AddSeconds(intervalSec);
var dbSet = db.Set<TModel>();
var query = from data in dbSet
where data.IdTelemetry == well.IdTelemetry
&& data.Date >= dateBegin && data.Date < datEnd
select data;
var query = dbSet
.Where(d => d.IdTelemetry == idTelemetry
&& d.Date >= dateBegin
&& d.Date < dateEnd);
var fullDataCount = await query.CountAsync(token)
.ConfigureAwait(false);
@ -128,10 +137,22 @@ namespace AsbCloudInfrastructure.Services
var dtos = entities.Select(e => Convert(e));
if (isUtc)
return dtos;
if (timeOffset is null)
return dtos;
dtos = dtos.Select(d =>
{
d.Date = telemetryService.TimeZoneService.DateToTimeZone(d.Date, timeOffset ?? default);
return d;
});
return dtos;
}
public virtual async Task<DatesRangeDto> GetDataDatesRangeAsync(int idWell,
public virtual async Task<DatesRangeDto> GetDataDatesRangeAsync(int idWell, bool isUtc,
CancellationToken token = default)
{
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
@ -141,7 +162,16 @@ namespace AsbCloudInfrastructure.Services
var (From, To) = await db.GetDatesRangeAsync<TModel>((int)telemetryId, token)
.ConfigureAwait(false);
return new DatesRangeDto { From = From, To = To };
var result = new DatesRangeDto {From = From, To = To};
if (isUtc)
return result;
result = await telemetryService.FixDatesRangeByTimeZoneAsync((int)telemetryId, result, token)
.ConfigureAwait(false);
return result;
}
public abstract TDto Convert(TModel src);

View File

@ -6,7 +6,7 @@ using Mapster;
namespace AsbCloudInfrastructure.Services
{
public class TelemetryDataSaubService: TelemetryDataBaseService<AsbCloudApp.Data.TelemetryDataSaubDto, AsbCloudDb.Model.TelemetryDataSaub>
public class TelemetryDataSaubService: TelemetryDataBaseService<TelemetryDataSaubDto, TelemetryDataSaub>
{
public TelemetryDataSaubService(
IAsbCloudDbContext db,

View File

@ -6,7 +6,7 @@ using Mapster;
namespace AsbCloudInfrastructure.Services
{
public class TelemetryDataSpinService : TelemetryDataBaseService<AsbCloudApp.Data.TelemetryDataSpinDto, AsbCloudDb.Model.TelemetryDataSpin>
public class TelemetryDataSpinService : TelemetryDataBaseService<TelemetryDataSpinDto, TelemetryDataSpin>
{
public TelemetryDataSpinService(
IAsbCloudDbContext db,

View File

@ -5,7 +5,9 @@ using AsbCloudInfrastructure.Services.Cache;
using Mapster;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System;
using System.Threading;
using Microsoft.EntityFrameworkCore;
namespace AsbCloudInfrastructure.Services
@ -14,16 +16,27 @@ namespace AsbCloudInfrastructure.Services
{
private readonly CacheTable<Telemetry> cacheTelemetry;
private readonly CacheTable<Well> cacheWells;
private readonly CacheTable<Cluster> cacheClusters;
private readonly CacheTable<Deposit> cacheDeposits;
private readonly IAsbCloudDbContext db;
private readonly ITelemetryTracker telemetryTracker;
private readonly ITimeZoneService timeZoneService;
public TelemetryService(IAsbCloudDbContext db, ITelemetryTracker telemetryTracker,
public ITimeZoneService TimeZoneService => timeZoneService;
public TelemetryService(
IAsbCloudDbContext db,
ITelemetryTracker telemetryTracker,
ITimeZoneService timeZoneService,
CacheDb cacheDb)
{
cacheTelemetry = cacheDb.GetCachedTable<Telemetry>((AsbCloudDbContext)db);
cacheWells = cacheDb.GetCachedTable<Well>((AsbCloudDbContext)db);
cacheClusters = cacheDb.GetCachedTable<Cluster>((AsbCloudDbContext)db);
cacheDeposits = cacheDb.GetCachedTable<Deposit>((AsbCloudDbContext)db);
this.db = db;
this.telemetryTracker = telemetryTracker;
this.timeZoneService = timeZoneService;
}
public IEnumerable<TelemetryDto> GetTransmittingTelemetriesAsync(int idCompany)
@ -69,11 +82,92 @@ namespace AsbCloudInfrastructure.Services
public double GetTimezoneOffsetByTelemetryId(int idTelemetry) =>
cacheTelemetry.FirstOrDefault(t => t.Id == idTelemetry).Info?.TimeZoneOffsetTotalHours ?? 0d;
public void UpdateInfo(string uid, TelemetryInfoDto info)
public async Task UpdateInfoAsync(string uid, TelemetryInfoDto info,
CancellationToken token)
{
var telemetry = GetOrCreateTelemetryByUid(uid);
telemetry.Info = info.Adapt<TelemetryInfo>();
cacheTelemetry.Upsert(telemetry);
if (!string.IsNullOrEmpty(info.TimeZoneId) &&
telemetry.TelemetryTimeZone?.IsOverride != true)
telemetry.TelemetryTimeZone = new TelemetryTimeZone()
{
Hours = info.TimeZoneOffsetTotalHours,
TimeZoneId = info.TimeZoneId
};
await cacheTelemetry.UpsertAsync(telemetry, token)
.ConfigureAwait(false);
}
public async Task<double?> GetTelemetryTimeZoneOffsetAsync(int idTelemetry, CancellationToken token)
{
var telemetry =
await cacheTelemetry.FirstOrDefaultAsync(t => t.Id == idTelemetry, token);
if (!string.IsNullOrEmpty(telemetry.TelemetryTimeZone?.TimeZoneId))
return telemetry.TelemetryTimeZone.Hours;
if (!string.IsNullOrEmpty(telemetry.Info?.TimeZoneId))
{
telemetry.TelemetryTimeZone = new TelemetryTimeZone
{
Hours = telemetry.Info.TimeZoneOffsetTotalHours,
IsOverride = false,
TimeZoneId = telemetry.Info.TimeZoneId,
};
}
else
{
var well = await cacheWells.FirstOrDefaultAsync(t => t.IdTelemetry == telemetry.Id, token)
.ConfigureAwait(false);
if (well is null)
return null;
var coordinates = await GetWellCoordinatesAsync(well.Id, token);
if (coordinates is null)
return null;
var requestedTimeZone = await timeZoneService.GetByCoordinatesAsync(coordinates.Value.latitude, coordinates.Value.longitude, token)
.ConfigureAwait(false);
if (requestedTimeZone is null)
return null;
telemetry.TelemetryTimeZone = requestedTimeZone.Adapt<TelemetryTimeZone>();
}
await cacheTelemetry.UpsertAsync(telemetry, token).ConfigureAwait(false);
return telemetry.TelemetryTimeZone.Hours;
}
public async Task<DatesRangeDto> FixDatesRangeByTimeZoneAsync(int idTelemetry, DatesRangeDto range,
CancellationToken token)
{
var offset = await GetTelemetryTimeZoneOffsetAsync(idTelemetry, token);
if (offset is null)
return range;
return new DatesRangeDto()
{
From = timeZoneService.DateToTimeZone(range.From, offset ?? default),
To = timeZoneService.DateToTimeZone(range.To, offset ?? default),
};
}
public async Task UpdateTimeZoneAsync(string uid, TelemetryTimeZoneDto timeZoneInfo,
CancellationToken token)
{
var telemetry = GetOrCreateTelemetryByUid(uid);
var newTelemetryTimeZone = timeZoneInfo.Adapt<TelemetryTimeZone>();
if (newTelemetryTimeZone?.Equals(telemetry.TelemetryTimeZone) == true)
return;
await cacheTelemetry.UpsertAsync(telemetry, token)
.ConfigureAwait(false);
}
public int? GetIdTelemetryByIdWell(int idWell)
@ -85,6 +179,33 @@ namespace AsbCloudInfrastructure.Services
return well.IdTelemetry;
}
private async Task<(double latitude, double longitude)?> GetWellCoordinatesAsync(int idWell,
CancellationToken token)
{
var well = await cacheWells.FirstOrDefaultAsync(w => w.Id == idWell, token)
.ConfigureAwait(false);
if (well is null)
return null;
if (well.Latitude is not null && well.Longitude is not null)
return (well.Latitude ?? default, well.Longitude??default);
var cluster = await cacheClusters.FirstOrDefaultAsync(c => c.Id == well.IdCluster, token)
.ConfigureAwait(false);
if (cluster.Latitude is not null && cluster.Longitude is not null)
return (cluster.Latitude ?? default, cluster.Longitude ?? default);
var deposit = await cacheDeposits.FirstOrDefaultAsync(d => d.Id == cluster.IdDeposit, token)
.ConfigureAwait(false);
if (deposit.Latitude is not null && deposit.Longitude is not null)
return (deposit.Latitude ?? default, deposit.Longitude ?? default);
return null;
}
private Well GetWellByTelemetryUid(string uid)
{
var tele = cacheTelemetry.FirstOrDefault(t => t.RemoteUid == uid);
@ -247,5 +368,7 @@ namespace AsbCloudInfrastructure.Services
return rows;
}
}
}

View File

@ -43,10 +43,11 @@ namespace AsbCloudInfrastructure.Services
var keyValuePairs = new Dictionary<string, TrackerStat>(cacheTelemetry.Count());
foreach (var telemetry in cacheTelemetry)
{
var date = telemetry.Info?.DrillingStartDate
var date = telemetry.Info?.DrillingStartDate
?? GetDateByUidOrDefault(telemetry.RemoteUid, DateTime.MinValue);
keyValuePairs[telemetry.RemoteUid] = new TrackerStat {
keyValuePairs[telemetry.RemoteUid] = new TrackerStat
{
RemoteUid = telemetry.RemoteUid,
LastTimeRemote = date,
LastTimeServer = date,
@ -54,14 +55,16 @@ namespace AsbCloudInfrastructure.Services
}
requests = new ConcurrentDictionary<string, TrackerStat>(keyValuePairs);
Task.Run(async() => {
Task.Run(async () =>
{
db.Database.SetCommandTimeout(2 * 60);
var dates = await db.TelemetryDataSaub
.GroupBy(d => d.IdTelemetry)
.Select(g => new
{
IdTelemetry = g.Key,
Date = g.Max(d=>d.Date)
DateMax = g.Max(d => d.Date),
DateMin = g.Min(d => d.Date),
})
.AsNoTracking()
.ToListAsync()
@ -71,18 +74,18 @@ namespace AsbCloudInfrastructure.Services
var oldReqs = dates.Select(t => new
{
Uid = cacheTelemetry.FirstOrDefault(c => c.Id == t.IdTelemetry).RemoteUid,
t.Date,
t.DateMax,
});
foreach (var oldReq in oldReqs)
{
var request = requests.GetValueOrDefault(oldReq.Uid);
if(request is not null)
if (request is not null)
{
if (request.LastTimeRemote < oldReq.Date)
request.LastTimeRemote = oldReq.Date;
if (request.LastTimeServer < oldReq.Date)
request.LastTimeServer = oldReq.Date;
if (request.LastTimeRemote < oldReq.DateMax)
request.LastTimeRemote = oldReq.DateMax;
if (request.LastTimeServer < oldReq.DateMax)
request.LastTimeServer = oldReq.DateMax;
}
}
});

View File

@ -0,0 +1,86 @@
using AsbCloudApp.Services;
using System.Net.Http;
using AsbCloudApp.Data;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System;
namespace AsbCloudInfrastructure.Services
{
public class TimeZoneService : ITimeZoneService
{
class TimeZoneInfo
{
public string Sunrise { get; set; }
public double Lng { get; set; }
public double Lat { get; set; }
public string CountryCode { get; set; }
public double GmtOffset { get; set; }
public double RawOffset { get; set; }
public string Sunset { get; set; }
public string TimezoneId { get; set; }
public double DstOffset { get; set; }
public string CountryName { get; set; }
public string Time { get; set; }
}
private readonly string timeZoneApiUrl = "http://api.geonames.org/timezoneJSON";
private readonly string timezoneApiUserName = "asbautodrilling";
public async Task<TelemetryTimeZoneDto> GetByCoordinatesAsync(double latitude, double longitude, CancellationToken token)
{
var lat = latitude.ToString(System.Globalization.CultureInfo.InvariantCulture);
var lng = longitude.ToString(System.Globalization.CultureInfo.InvariantCulture);
var url =
$"{timeZoneApiUrl}?lat={lat}&lng={lng}&username={timezoneApiUserName}";
using var client = new HttpClient();
var response = await client.GetAsync(url, token)
.ConfigureAwait(false);
var responseJson = await response.Content.ReadAsStringAsync(token)
.ConfigureAwait(false);
if (!(responseJson.Contains("timezoneId") && responseJson.Contains("dstOffset")))
return null;
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
var timeZoneInfo = JsonSerializer.Deserialize<TimeZoneInfo>(responseJson, options);
return new TelemetryTimeZoneDto
{
Hours = timeZoneInfo.DstOffset,
IsOverride = false,
TimeZoneId = timeZoneInfo.TimezoneId,
};
}
public DateTime DateToUtc(DateTime date, double remoteTimezoneOffsetHours)
{
var newDate = date.Kind switch
{
DateTimeKind.Local => date.ToUniversalTime(),
DateTimeKind.Unspecified => date.AddHours(-remoteTimezoneOffsetHours),
_ => date,
};
return DateTime.SpecifyKind(newDate, DateTimeKind.Utc);
}
public DateTime DateToTimeZone(DateTime date, double remoteTimezoneOffsetHours)
{
var newDate = date.Kind switch
{
DateTimeKind.Local => date.ToUniversalTime().AddHours(remoteTimezoneOffsetHours),
DateTimeKind.Utc => date.AddHours(remoteTimezoneOffsetHours),
_ => date,
};
return DateTime.SpecifyKind(newDate, DateTimeKind.Unspecified);
}
}
}

View File

@ -31,6 +31,7 @@ namespace AsbCloudWebApi.Controllers
/// <param name="skip">для пагинации кол-во записей пропустить</param>
/// <param name="take">для пагинации кол-во записей </param>
/// <param name="searchString"> Строка поиска </param>
/// <param name="isUtc">Даты в формате UTC или часового пояса скважины</param>
/// <param name="token">Токен для отмены задачи</param>
/// <returns>список сообщений по скважине</returns>
[HttpGet]
@ -39,6 +40,7 @@ namespace AsbCloudWebApi.Controllers
[FromQuery] IEnumerable<int> categoryids = default,
DateTime begin = default, DateTime end = default,
string searchString = default,
bool isUtc = true,
CancellationToken token = default)
{
if (take > 1024)
@ -49,7 +51,7 @@ namespace AsbCloudWebApi.Controllers
var result = await messageService.GetMessagesAsync(idWell,
categoryids, begin, end, searchString,
skip, take, token).ConfigureAwait(false);
skip, take, isUtc, token).ConfigureAwait(false);
if (result is null || result.Count == 0)
return NoContent();
@ -62,11 +64,12 @@ namespace AsbCloudWebApi.Controllers
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="token">Токен для отмены задачи</param>
/// <param name="isUtc">Смена дат с UTC формата на часовой пояс скважины</param>
/// <returns>список сообщений по скважине</returns>
[HttpGet]
[Route("datesRange")]
[ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetMessagesDateRangeAsync(int idWell,
public async Task<IActionResult> GetMessagesDateRangeAsync(int idWell, bool isUtc = true,
CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
@ -80,8 +83,8 @@ namespace AsbCloudWebApi.Controllers
if (!isCompanyOwnsWell)
return Forbid();
DatesRangeDto wellMessagesDatesRange = await messageService.GetMessagesDatesRangeAsync(idWell,
token);
var wellMessagesDatesRange = await messageService.GetMessagesDatesRangeAsync(idWell,
isUtc, token);
return Ok(wellMessagesDatesRange);
}

View File

@ -167,11 +167,12 @@ namespace AsbCloudWebApi.Controllers
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="token">Токен для отмены задачи</param>
/// <param name="isUtc">Смена дат с UTC формата на часовой пояс скважины</param>
/// <returns>Даты самого старого и самого свежего отчетов в БД</returns>
[HttpGet]
[Route("datesRange")]
[ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetReportsDateRangeAsync(int idWell,
public async Task<IActionResult> GetReportsDateRangeAsync(int idWell, bool isUtc = true,
CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
@ -183,7 +184,7 @@ namespace AsbCloudWebApi.Controllers
idWell, token).ConfigureAwait(false))
return Forbid();
DatesRangeDto wellReportsDatesRange = await reportService.GetReportsDatesRangeAsync(idWell,
var wellReportsDatesRange = await reportService.GetReportsDatesRangeAsync(idWell, isUtc,
token).ConfigureAwait(false);
return Ok(wellReportsDatesRange);

View File

@ -176,11 +176,12 @@ namespace AsbCloudWebApi.Controllers
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="token">Токен для отмены задачи</param>
/// <param name="isUtc">Смена дат с UTC формата на часовой пояс скважины</param>
/// <returns>Даты самой первой и самой последней операций на скважине</returns>
[HttpGet]
[Route("datesRange")]
[ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetOperationsDateRangeAsync(int idWell,
public async Task<IActionResult> GetOperationsDateRangeAsync(int idWell, bool isUtc = true,
CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
@ -192,8 +193,8 @@ namespace AsbCloudWebApi.Controllers
idWell, token).ConfigureAwait(false))
return Forbid();
DatesRangeDto wellOperationsDatesRange = await analyticsService.GetOperationsDateRangeAsync(idWell,
token).ConfigureAwait(false);
var wellOperationsDatesRange = await analyticsService.GetOperationsDateRangeAsync(idWell,
isUtc, token).ConfigureAwait(false);
return Ok(wellOperationsDatesRange);
}

View File

@ -42,13 +42,32 @@ namespace AsbCloudWebApi.Controllers
/// Принимает общую информацию по скважине
/// </summary>
/// <param name="uid">Уникальный идентификатор отправителя</param>
/// <param name="info">нформация об отправителе</param>
/// <param name="info">Информация об отправителе</param>
/// <param name="token">Токен отмены задачи</param>
/// <returns></returns>
[HttpPost]
[Route("{uid}/info")]
public IActionResult PostInfo(string uid, [FromBody] TelemetryInfoDto info)
public async Task<IActionResult> PostInfoAsync(string uid, [FromBody] TelemetryInfoDto info,
CancellationToken token = default)
{
telemetryService.UpdateInfo(uid, info);
await telemetryService.UpdateInfoAsync(uid, info, token).ConfigureAwait(false);
return Ok();
}
/// <summary>
/// Обновляет часовой пояс скважины
/// </summary>
/// <param name="uid">Уникальный идентификатор отправителя</param>
/// <param name="timeZoneInfo">Информация о часовом поясе</param>
/// <param name="token">Токен отмены задачи</param>
/// <returns></returns>
[HttpPost]
[Route("{uid}/timeZone")]
public async Task<IActionResult> UpdateTimeZoneAsync(string uid, TelemetryTimeZoneDto timeZoneInfo,
CancellationToken token = default)
{
await telemetryService.UpdateTimeZoneAsync(uid, timeZoneInfo, token)
.ConfigureAwait(false);
return Ok();
}
@ -104,33 +123,5 @@ namespace AsbCloudWebApi.Controllers
telemetryUserService.Upsert(uid, users);
return Ok();
}
///// <summary>
///// Загрузка архива (sqlite3).
///// <example>
///// var fileName = @"C:\temp\default.sqlite3";
///// var fileStream = System.IO.File.OpenRead(fileName);
///// var file = new FileParameter(fileStream, System.IO.Path.GetFileName(fileName));
///// cli.ApiTelemetryDbAsync("1", new List&lt;FileParameter&gt; { file }).Wait();
///// </example>
///// </summary>
///// <param name="uid"></param>
///// <param name="files"></param>
///// <returns></returns>
//[HttpPost]
//[Route("{uid}/db")]
//public IActionResult PostDb(string uid, IFormFileCollection files)
//{
// foreach (var file in files)
// {
// var fileName = string.IsNullOrEmpty(file.FileName)
// ? System.IO.Path.GetTempFileName()
// : file.FileName;
// using (var stream = System.IO.File.Create(fileName))
// file.CopyTo(stream);
// }
// return Ok();
//}
}
}

View File

@ -68,11 +68,12 @@ namespace AsbCloudWebApi.Controllers
/// <param name="begin">дата начала выборки. По умолчанию: текущее время - intervalSec</param>
/// <param name="intervalSec">интервал времени даты начала выборки, секунды</param>
/// <param name="approxPointsCount">желаемое количество точек. Если в выборке точек будет больше, то выборка будет прорежена.</param>
/// <param name="isUtc">Даты в формате UTC или часового пояса скважины</param>
/// <param name="token">Токен завершения задачи</param>
/// <returns></returns>
[HttpGet("{idWell}")]
public virtual async Task<ActionResult<TDto>> GetDataAsync(int idWell, DateTime begin = default,
int intervalSec = 600, int approxPointsCount = 1024, CancellationToken token = default)
int intervalSec = 600, int approxPointsCount = 1024, bool isUtc = false, CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
@ -86,7 +87,7 @@ namespace AsbCloudWebApi.Controllers
return Forbid();
var content = await telemetryDataService.GetAsync(idWell, begin,
intervalSec, approxPointsCount, token).ConfigureAwait(false);
intervalSec, approxPointsCount, isUtc, token).ConfigureAwait(false);
return Ok(content);
}
@ -95,12 +96,13 @@ namespace AsbCloudWebApi.Controllers
/// Возвращает диапазон дат сохраненных данных.
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="isUtc">Смена дат с UTC формата на часовой пояс скважины</param>
/// <param name="token">Токен завершения задачи</param>
/// <returns></returns>
[HttpGet]
[Route("{idWell}/datesRange")]
[ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)]
public virtual async Task<IActionResult> GetDataDatesRangeAsync(int idWell,
public virtual async Task<IActionResult> GetDataDatesRangeAsync(int idWell, bool isUtc = false,
CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
@ -114,7 +116,7 @@ namespace AsbCloudWebApi.Controllers
if (!isCompanyOwnsWell)
return Forbid();
var dataDatesRange = await telemetryDataService.GetDataDatesRangeAsync(idWell,
var dataDatesRange = await telemetryDataService.GetDataDatesRangeAsync(idWell, isUtc,
token).ConfigureAwait(false);
return Ok(dataDatesRange);

View File

@ -0,0 +1,12 @@
# url
https://www.geonames.org/commercial-webservices.html
# учетная запись для аутентификации на сайте
Имя пользователя: asbautodrilling
Пароль: asbautodrilling1!
# имя пользователя для запросов
asbautodrilling
# Пример запроса
http://api.geonames.org/timezoneJSON?lat=60.8705722222222&lng=70.3811888888889&username=asbautodrilling