using Application.Domain.Entities; using Application.Models; using Infrastructure.Data; using Infrastructure.Extensions; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace IoTCenter.Services { public class HealthCheckService : IDisposable { protected readonly IServiceProvider _applicationServices; protected readonly IConfiguration _configuration; protected CancellationTokenSource _tokenSource; public HealthCheckService(IServiceProvider applicationServices, IConfiguration configuration) { this._applicationServices = applicationServices; this._configuration = configuration; this._tokenSource = new CancellationTokenSource(); } public virtual void Start() { Task.Run(async () => { while (!_tokenSource.IsCancellationRequested) { try { Execute(); } catch (Exception ex) { ex.PrintStack(); } await Task.Delay(5 * 1000); } }); } private void Execute() { using (var scope = _applicationServices.CreateScope()) { var nodeRepo = scope.ServiceProvider.GetService>(); var nodes = nodeRepo.ReadOnlyTable().ToList(); var pageHubContext = scope.ServiceProvider.GetService>(); foreach (var node in nodes) { try { pageHubContext.Clients.Group(node.Number).SendAsync(Methods.ServerToClient, Methods.HealthCheckRequest, "", null); } catch (Exception ex) { ex.PrintStack(); var tempNode = nodeRepo.Table().FirstOrDefault(o => o.Number == node.Number); tempNode.IsOnline = false; nodeRepo.SaveChanges(); } } } } public void Dispose() { this._tokenSource.Cancel(); } } }