using Microsoft.AspNetCore.Mvc; using GreenHome.Application; namespace GreenHome.Api.Controllers; [ApiController] [Route("api/[controller]")] public class TelemetryController : ControllerBase { private readonly ITelemetryService telemetryService; private readonly IAlertService alertService; public TelemetryController(ITelemetryService telemetryService, IAlertService alertService) { this.telemetryService = telemetryService; this.alertService = alertService; } [HttpGet] public async Task>> List([FromQuery] int? deviceId, [FromQuery] DateTime? startUtc, [FromQuery] DateTime? endUtc, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken cancellationToken = default) { var filter = new TelemetryFilter { DeviceId = deviceId, StartDateUtc = startUtc, EndDateUtc = endUtc, Page = page, PageSize = pageSize }; var result = await telemetryService.ListAsync(filter, cancellationToken); return Ok(result); } [HttpGet("AddData")] public async Task> Create([FromQuery] TelemetryDto telementry, CancellationToken cancellationToken) { telementry.TimestampUtc = DateTime.UtcNow; var id = await telemetryService.AddAsync(telementry, cancellationToken); string? message; var deviceId = telementry.DeviceId; if(deviceId > 0) { message = await alertService.CheckAndSendAlertsAsync(deviceId, telementry, cancellationToken); if(!string.IsNullOrEmpty(message)) { return Ok(message); } } // Check and send alerts if needed (fire and forget) // _ = Task.Run(async () => // { // try // { // // Get deviceId from the saved telemetry record // var deviceId = telementry.DeviceId; // if (deviceId > 0) // { // await alertService.CheckAndSendAlertsAsync(deviceId, telementry, cancellationToken); // } // } // catch // { // // Log error but don't fail the request // // Errors are logged in AlertService // } // }, cancellationToken); return Ok(id + ""); } [HttpGet("minmax")] public async Task> MinMax([FromQuery] int deviceId, [FromQuery] DateTime? startUtc, [FromQuery] DateTime? endUtc, CancellationToken cancellationToken) { var result = await telemetryService.GetMinMaxAsync(deviceId, startUtc, endUtc, cancellationToken); return Ok(result); } [HttpGet("days")] public async Task>> Days([FromQuery] int deviceId, [FromQuery] int year, [FromQuery] int month, CancellationToken cancellationToken) { var result = await telemetryService.GetMonthDaysAsync(deviceId, year, month, cancellationToken); return Ok(result); } [HttpGet("months")] public async Task>> Months([FromQuery] int deviceId, [FromQuery] int year, CancellationToken cancellationToken) { var result = await telemetryService.GetActiveMonthsAsync(deviceId, year, cancellationToken); return Ok(result); } }