feat(api): получение статистики по работе роботов, StatRobotStateController -> Get
This commit is contained in:
@@ -7,7 +7,9 @@ using PARR.API.Contracts.V1;
|
||||
using PARR.API.Contracts.V1.Requests;
|
||||
using PARR.API.Contracts.V1.Requests.Queries;
|
||||
using PARR.API.Contracts.V1.Responses.Base;
|
||||
using PARR.API.Contracts.V1.Responses.Statistics;
|
||||
using PARR.API.Controllers.V1.Base;
|
||||
using PARR.API.Settings;
|
||||
using PARR.Constants;
|
||||
using PARR.DAL.InfluxDbServices;
|
||||
using PARR.DAL.Settings;
|
||||
@@ -23,16 +25,19 @@ namespace PARR.API.Controllers.V1.Statistics
|
||||
private readonly IInfluxDbService influxDbService;
|
||||
private readonly IValidator<RobotStateRequest> validator;
|
||||
private readonly InfluxDbSettings influxDbSettings;
|
||||
private readonly MonitoringSettings monitoringSettings;
|
||||
|
||||
public StatRobotStateController(
|
||||
IInfluxDbService influxDbService,
|
||||
IValidator<RobotStateRequest> validator,
|
||||
InfluxDbSettings influxDbSettings
|
||||
InfluxDbSettings influxDbSettings,
|
||||
MonitoringSettings monitoringSettings
|
||||
)
|
||||
{
|
||||
this.influxDbService = influxDbService;
|
||||
this.validator = validator;
|
||||
this.influxDbSettings = influxDbSettings;
|
||||
this.monitoringSettings = monitoringSettings;
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +48,15 @@ namespace PARR.API.Controllers.V1.Statistics
|
||||
[HttpGet(ApiRoutes.StatRobotState.Get)]
|
||||
public async Task<IActionResult> Get([FromRoute] RobotsAllEnum robot, [FromQuery] RobotStateGetQuery query)
|
||||
{
|
||||
var startAt = string.IsNullOrEmpty(query.StartAt) ? "-2h" : query.StartAt;
|
||||
|
||||
var robotSettings = monitoringSettings.Robots.FirstOrDefault(t => t.Name == robot.ToString());
|
||||
if (robotSettings == null)
|
||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при получении статистики. Неверно указаны настройки мониторинга." } }));
|
||||
|
||||
// var inaccessibilityTime = TimeSpan.Parse("00:03:00");
|
||||
var inaccessibilityTime = robotSettings.InaccessibilityTime;
|
||||
|
||||
|
||||
var result = await influxDbService.QueryAsync(async handler =>
|
||||
{
|
||||
@@ -53,7 +67,8 @@ namespace PARR.API.Controllers.V1.Statistics
|
||||
// "r._value > 3500)";
|
||||
|
||||
var query = $"from(bucket:\"{influxDbSettings.Robots!.Bucket}\") " +
|
||||
$"|> range(start: -3h) " +
|
||||
//$"|> range(start: -3h) " +
|
||||
$"|> range(start: {startAt}) " +
|
||||
$"|> filter(fn: (r) => " +
|
||||
$"r._measurement == \"robots\" " +
|
||||
$"and r.robot == \"{robot.ToString()}\"" +
|
||||
@@ -62,28 +77,25 @@ namespace PARR.API.Controllers.V1.Statistics
|
||||
|
||||
var tables = await handler.QueryAsync(query, influxDbSettings.Organization);
|
||||
|
||||
|
||||
//return tables.SelectMany(table =>
|
||||
// table.Records.Select(record =>
|
||||
// new AltitudeModel
|
||||
// {
|
||||
// Time = record.GetTime().ToString(),
|
||||
// Altitude = int.Parse(record.GetValue()?.ToString() ?? "0")
|
||||
// }));
|
||||
|
||||
|
||||
return "";
|
||||
return tables.SelectMany(table =>
|
||||
table.Records.Select(record => new StatRobotStateResponse
|
||||
{
|
||||
Date = (DateTimeOffset)record.GetTimeInDateTime(),
|
||||
IsUp = int.Parse(record.GetValue()?.ToString() ?? "0")
|
||||
})
|
||||
);
|
||||
}, influxDbSettings.Robots!.Token);
|
||||
|
||||
if (result == null)
|
||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при получении статистики" } }));
|
||||
|
||||
var listWithInaccessTime = CalcInaccessTime(result.ToList(), inaccessibilityTime);
|
||||
|
||||
return Ok();
|
||||
|
||||
return Ok(new Response<List<StatRobotStateResponse>>(listWithInaccessTime, true));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Статистика доступности роботов. Передать инф-у о доступности
|
||||
/// </summary>
|
||||
@@ -112,5 +124,63 @@ namespace PARR.API.Controllers.V1.Statistics
|
||||
|
||||
return Ok(new Response<string>("", true));
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Рассчитывает время когда робот был недоступен
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
/// <param name="inaccessibilityTime"></param>
|
||||
/// <returns></returns>
|
||||
private List<StatRobotStateResponse> CalcInaccessTime(List<StatRobotStateResponse> data, TimeSpan inaccessibilityTime)
|
||||
{
|
||||
|
||||
var inaccessTimeList = new List<StatRobotStateResponse>();
|
||||
|
||||
DateTimeOffset? lastTime = null;
|
||||
foreach (var item in data.OrderBy(t => t.Date))
|
||||
{
|
||||
if (!lastTime.HasValue)
|
||||
{
|
||||
lastTime = item.Date;
|
||||
continue;
|
||||
}
|
||||
|
||||
lastTime = lastTime.Value.Add(inaccessibilityTime);
|
||||
while (lastTime < item.Date)
|
||||
{
|
||||
//есть время когда робот был недоступен, добаляем в список недоступности
|
||||
inaccessTimeList.Add(new StatRobotStateResponse { Date = lastTime.Value, IsUp = 0 });
|
||||
lastTime = lastTime.Value.Add(inaccessibilityTime);
|
||||
}
|
||||
|
||||
// робот был доступен, все ок
|
||||
lastTime = item.Date;
|
||||
}
|
||||
|
||||
|
||||
//if (lastTime == null)
|
||||
//{
|
||||
// // не было вообще никакой статистики, считаем что он недоступен
|
||||
// inaccessTimeList.Add(new StatRobotStateResponse { Date = DateTimeOffset.UtcNow, IsUp = 0 });
|
||||
//}
|
||||
|
||||
// Проверяем, вдруг с последней даты активности до сейчас прошло уже много времени и он не доступен
|
||||
if (lastTime.HasValue)
|
||||
{
|
||||
lastTime = lastTime.Value.Add(inaccessibilityTime);
|
||||
while (lastTime.Value < DateTimeOffset.UtcNow)
|
||||
{
|
||||
inaccessTimeList.Add(new StatRobotStateResponse { Date = lastTime.Value, IsUp = 0 });
|
||||
lastTime = lastTime.Value.Add(inaccessibilityTime);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
data.AddRange(inaccessTimeList);
|
||||
|
||||
return data.OrderBy(t => t.Date).ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user