using FluentValidation; using InfluxDB.Client.Api.Domain; using InfluxDB.Client.Writes; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; 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.Controllers.V1.Base; using PARR.Constants; using PARR.DAL.InfluxDbServices; using PARR.DAL.Settings; namespace PARR.API.Controllers.V1.Statistics { /// /// Статистика доступности роботов /// [Authorize(Roles = ParrRoles.EsppRobot.RoleOrAdmin)] public class StatRobotStateController : BaseApiController { private readonly IInfluxDbService influxDbService; private readonly IValidator validator; private readonly InfluxDbSettings influxDbSettings; public StatRobotStateController( IInfluxDbService influxDbService, IValidator validator, InfluxDbSettings influxDbSettings ) { this.influxDbService = influxDbService; this.validator = validator; this.influxDbSettings = influxDbSettings; } /// /// Доступность робота /// /// [HttpGet(ApiRoutes.StatRobotState.Get)] public async Task Get([FromRoute] RobotsAllEnum robot, [FromQuery] RobotStateGetQuery query) { var result = await influxDbService.QueryAsync(async handler => { //var flux = "from(bucket:\"robots\") " + // "|> range(start: 0) " + // "|> filter(fn: (r) => " + // "r._measurement == \"altitude\" and " + // "r._value > 3500)"; var query = $"from(bucket:\"{influxDbSettings.Robots!.Bucket}\") " + $"|> range(start: -3h) " + $"|> filter(fn: (r) => " + $"r._measurement == \"robots\" " + $"and r.robot == \"{robot.ToString()}\"" + $")"; 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 ""; }, influxDbSettings.Robots!.Token); if (result == null) return BadRequest(new Response(false, new List { new ErrorModel { Message = $"Ошибка при получении статистики" } })); return Ok(); } /// /// Статистика доступности роботов. Передать инф-у о доступности /// /// /// [HttpPost(ApiRoutes.StatRobotState.Send)] public async Task Send([FromBody] RobotStateRequest request) { var resultValidate = await validator.ValidateAsync(request); if (!resultValidate.IsValid) return BadRequest(new Response(resultValidate.Errors)); var result = influxDbService.Write(write => { var point = PointData.Measurement("robots") .Tag("robot", request.Robot.ToString()) //.Field("robot", (int)request.Robot) .Field("isUp", 1) .Timestamp(DateTime.UtcNow, WritePrecision.Ns); write.WritePoint(point, bucket: influxDbSettings.Robots!.Bucket, org: influxDbSettings.Organization); }, influxDbSettings.Robots!.Token); if (!result) return BadRequest(new Response(false, new List { new ErrorModel { Message = $"Ошибка при отправке данных" } })); return Ok(new Response("", true)); } } }