using Application.Domain.Entities; using Infrastructure.Data; using Infrastructure.Extensions; using IoT.Shared.Infrastructure; using Microsoft.AspNetCore.SignalR.Client; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace FBeeService { public class ClientService : BaseClientService { public ClientService(IServiceProvider applicationServices, IConfiguration configuration) : base(applicationServices, configuration) { } public override void Connected() { using (var scope = this.applicationServices.CreateScope()) { var deviceInfoRepo = scope.ServiceProvider.GetService>(); var deviceInfos = deviceInfoRepo.ReadOnlyTable().ToList(); foreach (var item in deviceInfos) { this.SendDeviceInfo(item); } var deviceRepo = scope.ServiceProvider.GetService>(); var devices = deviceRepo.ReadOnlyTable().Include(o => o.Data).ToList(); foreach (var item in devices) { this.SendDevice(item); } } } public void SendDeviceInfo(DeviceInfo deviceInfo) { Task.Run(() => { try { Console.WriteLine("send device info to server"); this.Connection.SendAsync("ClientToServer", "UpdateDeviceInfo", deviceInfo.ToJson(), null); } catch (Exception ex) { ex.PrintStack(); } }); } public void SendDevice(Device device) { Task.Run(() => { try { Console.WriteLine("send device to server"); this.Connection.SendAsync("ClientToServer", "UpdateDevice", device.ToJson(), null); } catch (Exception ex) { ex.PrintStack(); } }); } public override void ConnectionOn() { this.Connection.On("ServerToClient", (string path, string queryString, string connectionId) => { using (var scope = this.applicationServices.CreateScope()) { var serviceProvider = scope.ServiceProvider; var cfg = serviceProvider.GetService(); var port = cfg["server.urls"].Split(':')[2]; var url = $"http://localhost:{port}{path}{queryString}"; var httpClient = serviceProvider.GetService().CreateClient(); var result = httpClient.GetStringAsync(url).Result; this.Connection.SendAsync("ClientToServer", "ApiCallback", result, connectionId); } }); } } }