diff --git a/projects/Infrastructure/Domain/BaseEntity.cs b/projects/Infrastructure/Domain/BaseEntity.cs index d4ee1f98..9a72e467 100644 --- a/projects/Infrastructure/Domain/BaseEntity.cs +++ b/projects/Infrastructure/Domain/BaseEntity.cs @@ -2,19 +2,11 @@ using System; namespace Infrastructure.Domain { - public abstract class BaseEntity + public abstract class BaseEntity : EntityBase { public BaseEntity() { this.Id = Guid.NewGuid(); } - - public Guid Id { get; set; } - public string IsDeleted { get; set; } - - public override string ToString() - { - return $"{ GetType().FullName}[{Id}]"; - } } } \ No newline at end of file diff --git a/projects/Infrastructure/Domain/EntityBase.cs b/projects/Infrastructure/Domain/EntityBase.cs new file mode 100644 index 00000000..9004f8b6 --- /dev/null +++ b/projects/Infrastructure/Domain/EntityBase.cs @@ -0,0 +1,13 @@ +namespace Infrastructure.Domain +{ + public class EntityBase + { + public TKey Id { get; set; } + public string IsDeleted { get; set; } + + public override string ToString() + { + return $"{ GetType().FullName}[{Id}]"; + } + } +} \ No newline at end of file diff --git a/projects/IoT/IoT.Shared/Application/Domain/Entities/Data.cs b/projects/IoT/IoT.Shared/Application/Domain/Entities/Data.cs index 8103f07e..e42f118a 100644 --- a/projects/IoT/IoT.Shared/Application/Domain/Entities/Data.cs +++ b/projects/IoT/IoT.Shared/Application/Domain/Entities/Data.cs @@ -39,7 +39,7 @@ namespace Application.Domain.Entities [Display(Name = "设备")] public Device Device { get; set; } - public List Tiggers { get; set; } = new List(); + public List Tiggers { get; set; } = new List(); public dynamic GetValue() { diff --git a/projects/IoT/IoT.Shared/Application/Domain/Entities/Tigger.cs b/projects/IoT/IoT.Shared/Application/Domain/Entities/IoTTigger.cs similarity index 93% rename from projects/IoT/IoT.Shared/Application/Domain/Entities/Tigger.cs rename to projects/IoT/IoT.Shared/Application/Domain/Entities/IoTTigger.cs index ca28a9ec..987a8479 100644 --- a/projects/IoT/IoT.Shared/Application/Domain/Entities/Tigger.cs +++ b/projects/IoT/IoT.Shared/Application/Domain/Entities/IoTTigger.cs @@ -6,7 +6,7 @@ using System.ComponentModel.DataAnnotations; namespace Application.Domain.Entities { [Display(Name = "定时器")] - public class Tigger : BaseEntity + public class IoTTigger : BaseEntity { public string Name { get; set; } diff --git a/projects/IoT/IoT.Shared/Application/Domain/Entities/Timer.cs b/projects/IoT/IoT.Shared/Application/Domain/Entities/IoTTimer.cs similarity index 93% rename from projects/IoT/IoT.Shared/Application/Domain/Entities/Timer.cs rename to projects/IoT/IoT.Shared/Application/Domain/Entities/IoTTimer.cs index f73cef91..e4153a1c 100644 --- a/projects/IoT/IoT.Shared/Application/Domain/Entities/Timer.cs +++ b/projects/IoT/IoT.Shared/Application/Domain/Entities/IoTTimer.cs @@ -6,7 +6,7 @@ using System.ComponentModel.DataAnnotations; namespace Application.Domain.Entities { [Display(Name = "定时器")] - public class Timer : BaseEntity + public class IoTTimer : BaseEntity { public string Name { get; set; } diff --git a/projects/IoT/IoT.Shared/Application/Domain/Entities/Node.cs b/projects/IoT/IoT.Shared/Application/Domain/Entities/Node.cs index df0b8e2b..d259c63e 100644 --- a/projects/IoT/IoT.Shared/Application/Domain/Entities/Node.cs +++ b/projects/IoT/IoT.Shared/Application/Domain/Entities/Node.cs @@ -49,7 +49,7 @@ namespace Application.Domain.Entities public List Devices { get; set; } = new List(); public List Scenes { get; set; } = new List(); - public List Timers { get; set; } = new List(); - public List Tiggers { get; set; } = new List(); + public List Timers { get; set; } = new List(); + public List Tiggers { get; set; } = new List(); } } \ No newline at end of file diff --git a/projects/IoT/IoT.Shared/Application/Domain/Entities/TiggerCommand.cs b/projects/IoT/IoT.Shared/Application/Domain/Entities/TiggerCommand.cs index 5dda0699..4c671cc6 100644 --- a/projects/IoT/IoT.Shared/Application/Domain/Entities/TiggerCommand.cs +++ b/projects/IoT/IoT.Shared/Application/Domain/Entities/TiggerCommand.cs @@ -9,7 +9,7 @@ namespace Application.Domain.Entities { public Guid TiggerId { get; set; } public Guid CommandId { get; set; } - public Tigger Tigger { get; set; } + public IoTTigger Tigger { get; set; } public Command Command { get; set; } } } \ No newline at end of file diff --git a/projects/IoT/IoT.Shared/Application/Domain/Entities/TimerCommand.cs b/projects/IoT/IoT.Shared/Application/Domain/Entities/TimerCommand.cs index d12a0da1..81ea15b9 100644 --- a/projects/IoT/IoT.Shared/Application/Domain/Entities/TimerCommand.cs +++ b/projects/IoT/IoT.Shared/Application/Domain/Entities/TimerCommand.cs @@ -9,7 +9,7 @@ namespace Application.Domain.Entities { public Guid TimerId { get; set; } public Guid CommandId { get; set; } - public Timer Timer { get; set; } + public IoTTimer Timer { get; set; } public Command Command { get; set; } } } \ No newline at end of file diff --git a/projects/IoT/IoT.Shared/DeviceServices/FBee/FBeeService.cs b/projects/IoT/IoT.Shared/DeviceServices/FBee/FBeeService.cs index 0d444dc6..b05e543b 100644 --- a/projects/IoT/IoT.Shared/DeviceServices/FBee/FBeeService.cs +++ b/projects/IoT/IoT.Shared/DeviceServices/FBee/FBeeService.cs @@ -22,7 +22,7 @@ using System.Threading.Tasks; namespace IoT.Shared.DeviceServices.FBee { - public class FBeeService : BaseDeviceService + public class FBeeService : DeviceService { private readonly ConcurrentDictionary Clients = new ConcurrentDictionary(); @@ -31,39 +31,11 @@ namespace IoT.Shared.DeviceServices.FBee { } - #region impl interface - - public override void Start() - { - base.Start(); - this.HealthCheck(); - } - - public override void Execute() - { - Refresh(); - } - - public override void Stop() - { - foreach (var item in Clients) - { - if (item.Value.Client != null) - { - item.Value.Client.Dispose(); - } - } - } - - #endregion impl interface - - #region private - - private void HealthCheck() + public override Task StartAsync(CancellationToken cancellationToken) { Task.Run(async () => { - while (!_tokenSource.IsCancellationRequested) + while (!cancellationToken.IsCancellationRequested) { foreach (var item in this.Clients) { @@ -80,9 +52,10 @@ namespace IoT.Shared.DeviceServices.FBee await Task.Delay(1000 * 60); } }); + return base.StartAsync(cancellationToken); } - private void Refresh() + public override void Execute() { var ips = NetworkInterface.GetAllNetworkInterfaces() .Where(nic => nic.OperationalStatus == OperationalStatus.Up && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback) @@ -219,6 +192,31 @@ namespace IoT.Shared.DeviceServices.FBee } } + public override Task StopAsync(CancellationToken cancellationToken) + { + try + { + foreach (var item in Clients) + { + if (item.Value.Client != null) + { + item.Value.Client.Dispose(); + } + } + } + catch (Exception ex) + { + ex.PrintStack(); + } + finally + { + Console.WriteLine($"{this.GetType().Name} Service Stopd"); + } + return Task.CompletedTask; + } + + #region private + private void Connect(TcpClientWrapper client) { try diff --git a/projects/IoT/IoT.Shared/DeviceServices/Onvif/OnvifService.cs b/projects/IoT/IoT.Shared/DeviceServices/Onvif/OnvifService.cs index c7b696d0..5dc2a6fb 100644 --- a/projects/IoT/IoT.Shared/DeviceServices/Onvif/OnvifService.cs +++ b/projects/IoT/IoT.Shared/DeviceServices/Onvif/OnvifService.cs @@ -20,10 +20,11 @@ using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; +using System.Threading.Tasks; namespace IoT.Shared.DeviceServices.Onvif { - public class OnvifService : BaseDeviceService + public class OnvifService : DeviceService { private readonly ConcurrentDictionary _list = new ConcurrentDictionary(); private readonly IWebHostEnvironment _env; @@ -38,21 +39,12 @@ namespace IoT.Shared.DeviceServices.Onvif this._onvifDeviceManagement = new OnvifDeviceManagement(httpClientFactory); } - #region impl interface - public override void Execute() - { - Refresh(); - } - - public override void Stop() { try { - foreach (var item in this._list.Keys.ToList()) - { - this.Remove(item); - } + Search(); + Notify(); } catch (Exception ex) { @@ -60,19 +52,24 @@ namespace IoT.Shared.DeviceServices.Onvif } } - #endregion impl interface - - private void Refresh() + public override Task StopAsync(CancellationToken cancellationToken) { try { - Search(); - Notify(); + foreach (var item in this._list.Keys.ToList()) + { + this.Remove(item); + } } catch (Exception ex) { ex.PrintStack(); } + finally + { + Console.WriteLine($"{this.GetType().Name} Service Stopd"); + } + return Task.CompletedTask; } public void Search() diff --git a/projects/IoT/IoT.Shared/DeviceServices/SerialPort/SerialPortService.cs b/projects/IoT/IoT.Shared/DeviceServices/SerialPort/SerialPortService.cs index 3c978352..9f0f096e 100644 --- a/projects/IoT/IoT.Shared/DeviceServices/SerialPort/SerialPortService.cs +++ b/projects/IoT/IoT.Shared/DeviceServices/SerialPort/SerialPortService.cs @@ -12,23 +12,19 @@ using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Runtime.InteropServices; +using System.Threading; using System.Threading.Tasks; namespace IoT.Shared.DeviceServices.SerialPort { - public class SerialPortService : BaseDeviceService + public class SerialPortService : DeviceService { - private readonly IServiceProvider _applicationServices; - public SerialPortService(IServiceProvider applicationServices, IConfiguration configuration) : base(applicationServices, configuration) { - this._applicationServices = applicationServices; } - #region impl interface - - public override void Start() + public override Task StartAsync(CancellationToken cancellationToken) { Task.Run(() => { @@ -51,7 +47,7 @@ namespace IoT.Shared.DeviceServices.SerialPort productRepo.SaveChanges(); } }); - base.Start(); + return base.StartAsync(cancellationToken); } public override void Execute() @@ -59,7 +55,10 @@ namespace IoT.Shared.DeviceServices.SerialPort Notify(); } - #endregion impl interface + public override Task StopAsync(CancellationToken cancellationToken) + { + return base.StopAsync(cancellationToken); + } public void Exec(string id, string code) { diff --git a/projects/IoT/IoT.Shared/Infrastructure/BaseNodeService.cs b/projects/IoT/IoT.Shared/Infrastructure/BaseNodeService.cs index 7d04781e..6ea5ef44 100644 --- a/projects/IoT/IoT.Shared/Infrastructure/BaseNodeService.cs +++ b/projects/IoT/IoT.Shared/Infrastructure/BaseNodeService.cs @@ -8,162 +8,7 @@ using System.Threading.Tasks; namespace IoT.Shared.Infrastructure { - public class BaseNodeService : INodeService + public class BaseNodeService { - internal string _notifyHost; - internal HubConnection Connection; - internal readonly IServiceProvider applicationServices; - internal readonly IConfiguration _cfg; - internal CancellationTokenSource _tokenSource; - public string ConnectionId { get; private set; } - - public BaseNodeService(IServiceProvider applicationServices, IConfiguration configuration) - { - this.applicationServices = applicationServices; - this._cfg = configuration; - this._tokenSource = new CancellationTokenSource(); - this.ConnectionId = Guid.NewGuid().ToBase62(); - } - - public void Start() - { - Task.Run(async () => - { - while (!_tokenSource.IsCancellationRequested) - { - this.Connect(); - await Task.Delay(10 * 1000).ConfigureAwait(true); - } - }); - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:不捕获常规异常类型", Justification = "<挂起>")] - public void Connect() - { - if (this._cfg.GetValue("notify:enabled", false)) - { - Console.WriteLine("notify is enabled"); - try - { - if (Connection == null) - { - Console.WriteLine("connection is null"); - InitConnection(); - } - if (Connection.State == HubConnectionState.Disconnected) - { - Console.WriteLine("start connect"); - if (this._notifyHost != this._cfg["notify:host"]) - { - InitConnection(); - } - Connection.StartAsync().Wait(); - this.OnConnected(); - } - else - { - if (this._notifyHost != this._cfg["notify:host"]) - { - this.ReConnect(null); - } - else - { - Console.WriteLine($"connection has connected"); - } - } - } - catch (Exception ex) - { - ex.PrintStack(); - } - } - else - { - Console.WriteLine("notify is disabled"); - this.Close(); - } - } - - public virtual void OnConnected() - { - } - - public virtual void ConnectionOn() - { - } - - public void Close() - { - if (this.Connection != null) - { - if (this.Connection.State == HubConnectionState.Connected) - { - this.Connection.StopAsync(); - } - this.Connection.DisposeAsync(); - this.Connection = null; - } - } - - private Task ReConnect(Exception arg) - { - this.Close(); - this.Connect(); - return Task.CompletedTask; - } - - private void InitConnection() - { - this._notifyHost = this._cfg["notify:host"]; - var url = $"http://{this._notifyHost}/hub?group={this._cfg["sn"]}"; - Console.WriteLine($"init connection for {url}"); - if (this.Connection != null) - { - this.Connection.DisposeAsync(); - } - this.Connection = new HubConnectionBuilder().WithUrl(url).Build(); - this.Connection.Closed += ReConnect; - this.Connection.On(Methods.ServerToClient, (string method, string message, string fromConnectionId) => this.OnServerToClient(method, message, fromConnectionId)); - this.ConnectionOn(); - } - - public virtual void OnServerToClient(string method, string message, string fromConnectionId) - { - } - - public void ServerToClient(string method, string message, string fromConnectionId) - { - this.OnServerToClient(method, method, fromConnectionId); - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:不捕获常规异常类型", Justification = "<挂起>")] - public void ClientToServer(string method, string message, string fromConnectionId = null) - { - Task.Run(() => - { - try - { - if (this.Connection != null && this.Connection.State == HubConnectionState.Connected) - { - this.Connection.SendAsync(Methods.ClientToServer, method, message, fromConnectionId ?? this._cfg["sn"]); - } - else - { - Console.WriteLine($"{_notifyHost} not connected"); - } - } - catch (Exception ex) - { - ex.PrintStack(); - } - }); - } - - public void Dispose() - { - this._tokenSource.Cancel(); - this.Close(); - this._tokenSource.Dispose(); - } } } \ No newline at end of file diff --git a/projects/IoT/IoT.Shared/Infrastructure/BaseDeviceService.cs b/projects/IoT/IoT.Shared/Infrastructure/DeviceService.cs similarity index 78% rename from projects/IoT/IoT.Shared/Infrastructure/BaseDeviceService.cs rename to projects/IoT/IoT.Shared/Infrastructure/DeviceService.cs index 6907ef0d..154e08c3 100644 --- a/projects/IoT/IoT.Shared/Infrastructure/BaseDeviceService.cs +++ b/projects/IoT/IoT.Shared/Infrastructure/DeviceService.cs @@ -1,6 +1,7 @@ using Infrastructure.Extensions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; @@ -11,25 +12,22 @@ using System.Threading.Tasks; namespace IoT.Shared.Infrastructure { - public abstract class BaseDeviceService : IDeviceService + public abstract class DeviceService : IHostedService { internal readonly IServiceProvider _applicationServices; internal readonly IConfiguration _configuration; - internal CancellationTokenSource _tokenSource; - public BaseDeviceService(IServiceProvider applicationServices, IConfiguration configuration) + public DeviceService(IServiceProvider applicationServices, IConfiguration configuration) { this._applicationServices = applicationServices; this._configuration = configuration; - this._tokenSource = new CancellationTokenSource(); } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "<挂起>")] - public virtual void Start() + public virtual Task StartAsync(CancellationToken cancellationToken) { Task.Run(async () => { - while (!_tokenSource.IsCancellationRequested) + while (!cancellationToken.IsCancellationRequested) { try { @@ -42,21 +40,14 @@ namespace IoT.Shared.Infrastructure await Task.Delay(_configuration.GetValue("timer.seconds", 60) * 1000).ConfigureAwait(true); } }); + return Task.CompletedTask; } - public virtual void Execute() - { - } - - public virtual void Stop() - { - } + public abstract void Execute(); - public virtual void Dispose() + public virtual Task StopAsync(CancellationToken cancellationToken) { - this._tokenSource.Cancel(); - this.Stop(); - this._tokenSource.Dispose(); + return Task.CompletedTask; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:不捕获常规异常类型", Justification = "<挂起>")] diff --git a/projects/IoT/IoT.Shared/Infrastructure/IDeviceService.cs b/projects/IoT/IoT.Shared/Infrastructure/IDeviceService.cs deleted file mode 100644 index 98011825..00000000 --- a/projects/IoT/IoT.Shared/Infrastructure/IDeviceService.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace IoT.Shared.Infrastructure -{ - public interface IDeviceService : IDisposable - { - void Start(); - - void Stop(); - - void Execute(); - } -} \ No newline at end of file diff --git a/projects/IoT/IoT.Shared/Infrastructure/NodeService.cs b/projects/IoT/IoT.Shared/Infrastructure/NodeService.cs index b195b59a..2ed6f55d 100644 --- a/projects/IoT/IoT.Shared/Infrastructure/NodeService.cs +++ b/projects/IoT/IoT.Shared/Infrastructure/NodeService.cs @@ -7,28 +7,172 @@ using Microsoft.AspNetCore.SignalR.Client; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; +using System.Threading; using System.Threading.Tasks; namespace IoT.Shared.Infrastructure { - public class NodeService : BaseNodeService + public class NodeService : IHostedService, IDisposable { - public NodeService(IServiceProvider applicationServices, IConfiguration configuration) : base(applicationServices, configuration) + private string _notifyHost; + private HubConnection Connection; + private readonly IServiceProvider applicationServices; + private readonly IConfiguration _cfg; + public string ConnectionId { get; private set; } + + public NodeService(IServiceProvider applicationServices, IConfiguration configuration) + { + this.applicationServices = applicationServices; + this._cfg = configuration; + this.ConnectionId = Guid.NewGuid().ToBase62(); + } + + public Task StartAsync(CancellationToken cancellationToken) + { + Task.Run(async () => + { + while (!cancellationToken.IsCancellationRequested) + { + this.Connect(); + await Task.Delay(10 * 1000).ConfigureAwait(true); + } + }); + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:不捕获常规异常类型", Justification = "<挂起>")] + public void Connect() + { + if (this._cfg.GetValue("notify:enabled", false)) + { + Console.WriteLine("notify is enabled"); + try + { + if (Connection == null) + { + Console.WriteLine("connection is null"); + InitConnection(); + } + if (Connection.State == HubConnectionState.Disconnected) + { + Console.WriteLine("start connect"); + if (this._notifyHost != this._cfg["notify:host"]) + { + InitConnection(); + } + Connection.StartAsync().Wait(); + this.OnConnected(); + } + else + { + if (this._notifyHost != this._cfg["notify:host"]) + { + this.ReConnect(null); + } + else + { + Console.WriteLine($"connection has connected"); + } + } + } + catch (Exception ex) + { + ex.PrintStack(); + } + } + else + { + Console.WriteLine("notify is disabled"); + this.Close(); + } + } + + public void Close() + { + if (this.Connection != null) + { + if (this.Connection.State == HubConnectionState.Connected) + { + this.Connection.StopAsync(); + } + this.Connection.DisposeAsync(); + this.Connection = null; + } + } + + private Task ReConnect(Exception arg) + { + this.Close(); + this.Connect(); + return Task.CompletedTask; + } + + private void InitConnection() + { + this._notifyHost = this._cfg["notify:host"]; + var url = $"http://{this._notifyHost}/hub?group={this._cfg["sn"]}"; + Console.WriteLine($"init connection for {url}"); + if (this.Connection != null) + { + this.Connection.DisposeAsync(); + } + this.Connection = new HubConnectionBuilder().WithUrl(url).Build(); + this.Connection.Closed += ReConnect; + this.Connection.On(Methods.ServerToClient, (string method, string message, string fromConnectionId) => this.OnServerToClient(method, message, fromConnectionId)); + } + + public void ServerToClient(string method, string message, string fromConnectionId) + { + this.OnServerToClient(method, method, fromConnectionId); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:不捕获常规异常类型", Justification = "<挂起>")] + public void ClientToServer(string method, string message, string fromConnectionId = null) + { + Task.Run(() => + { + try + { + if (this.Connection != null && this.Connection.State == HubConnectionState.Connected) + { + this.Connection.SendAsync(Methods.ClientToServer, method, message, fromConnectionId ?? this._cfg["sn"]); + } + else + { + Console.WriteLine($"{_notifyHost} not connected"); + } + } + catch (Exception ex) + { + ex.PrintStack(); + } + }); + } + + public void Dispose() { + this.Close(); } - public override void OnConnected() + ///////////////////////////// + public void OnConnected() { Console.WriteLine($"{_notifyHost} OnConnected"); this.UpdateServer(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:不捕获常规异常类型", Justification = "<挂起>")] - public override void OnServerToClient(string method, string message, string fromConnectionId) + public void OnServerToClient(string method, string message, string fromConnectionId) { using var scope = this.applicationServices.CreateScope(); if (method == Methods.HealthCheckRequest) @@ -249,11 +393,11 @@ namespace IoT.Shared.Infrastructure { var model = message.FromJson(); var nodeRepo = scope.ServiceProvider.GetService>(); - var timerRepo = scope.ServiceProvider.GetService>(); + var timerRepo = scope.ServiceProvider.GetService>(); var timer = timerRepo.Table().FirstOrDefault(o => o.Id == model.Id); if (timer == null) { - timer = new Timer + timer = new IoTTimer { Id = model.Id }; @@ -262,19 +406,19 @@ namespace IoT.Shared.Infrastructure timer.FromDto(model); timer.NodeId = nodeRepo.ReadOnlyTable().FirstOrDefault(o => o.Number == model.NodeNumber).Id; timerRepo.SaveChanges(); - scope.ServiceProvider.GetService().Publish(new EntityUpdatedEvent(timer)); + scope.ServiceProvider.GetService().Publish(new EntityUpdatedEvent(timer)); this.ClientToServer(Methods.EditTimerResponse, message); } else if (method == Methods.DeleteTimerRequest) { var model = message.FromJson(); - var timerRepo = scope.ServiceProvider.GetService>(); + var timerRepo = scope.ServiceProvider.GetService>(); var timer = timerRepo.Table().FirstOrDefault(o => o.Id == model.Id); if (timer != null) { timerRepo.Delete(timer); timerRepo.SaveChanges(); - scope.ServiceProvider.GetService().Publish(new EntityDeletedEvent(timer)); + scope.ServiceProvider.GetService().Publish(new EntityDeletedEvent(timer)); } this.ClientToServer(Methods.DeleteTimerResponse, message); } @@ -282,11 +426,11 @@ namespace IoT.Shared.Infrastructure { var model = message.FromJson(); var nodeRepo = scope.ServiceProvider.GetService>(); - var repo = scope.ServiceProvider.GetService>(); + var repo = scope.ServiceProvider.GetService>(); var entity = repo.Table().FirstOrDefault(o => o.Id == model.Id); if (entity == null) { - entity = new Tigger + entity = new IoTTigger { Id = model.Id }; @@ -295,19 +439,19 @@ namespace IoT.Shared.Infrastructure entity.FromDto(model); entity.NodeId = nodeRepo.ReadOnlyTable().FirstOrDefault(o => o.Number == model.NodeNumber).Id; repo.SaveChanges(); - scope.ServiceProvider.GetService().Publish(new EntityUpdatedEvent(entity)); + scope.ServiceProvider.GetService().Publish(new EntityUpdatedEvent(entity)); this.ClientToServer(Methods.EditTiggerResponse, message); } else if (method == Methods.DeleteTiggerRequest) { var model = message.FromJson(); - var repo = scope.ServiceProvider.GetService>(); + var repo = scope.ServiceProvider.GetService>(); var entity = repo.Table().FirstOrDefault(o => o.Id == model.Id); if (entity != null) { repo.Delete(entity); repo.SaveChanges(); - scope.ServiceProvider.GetService().Publish(new EntityDeletedEvent(entity)); + scope.ServiceProvider.GetService().Publish(new EntityDeletedEvent(entity)); } this.ClientToServer(Methods.DeleteTiggerResponse, message); } diff --git a/projects/IoT/IoT.Shared/IoTServiceStartup.cs b/projects/IoT/IoT.Shared/IoTServiceStartup.cs index 9274bb9c..6f3a76f5 100644 --- a/projects/IoT/IoT.Shared/IoTServiceStartup.cs +++ b/projects/IoT/IoT.Shared/IoTServiceStartup.cs @@ -111,9 +111,9 @@ namespace IoT.UI.Shard modelBuilder.Entity().Property(o => o.DeviceNumber).IsRequired(); modelBuilder.Entity().HasOne(o => o.Api).WithMany(o => o.Commands).HasForeignKey(o => o.ApiId); modelBuilder.Entity().HasOne(o => o.Node).WithMany(o => o.Scenes).HasForeignKey(o => o.NodeId); - modelBuilder.Entity().HasOne(o => o.Node).WithMany(o => o.Timers).HasForeignKey(o => o.NodeId); - modelBuilder.Entity().HasOne(o => o.Node).WithMany(o => o.Tiggers).HasForeignKey(o => o.NodeId); - modelBuilder.Entity().HasOne(o => o.Data).WithMany(o => o.Tiggers).HasForeignKey(o => o.DataId); + modelBuilder.Entity().HasOne(o => o.Node).WithMany(o => o.Timers).HasForeignKey(o => o.NodeId); + modelBuilder.Entity().HasOne(o => o.Node).WithMany(o => o.Tiggers).HasForeignKey(o => o.NodeId); + modelBuilder.Entity().HasOne(o => o.Data).WithMany(o => o.Tiggers).HasForeignKey(o => o.DataId); modelBuilder.Entity().HasOne(o => o.Scene).WithMany(o => o.SceneCommands).HasForeignKey(o => o.SceneId); modelBuilder.Entity().HasOne(o => o.Command).WithMany(o => o.SceneCommands).HasForeignKey(o => o.CommandId); modelBuilder.Entity().HasOne(o => o.Timer).WithMany(o => o.TimerCommands).HasForeignKey(o => o.TimerId); @@ -189,11 +189,11 @@ namespace IoT.UI.Shard }); dbContext.SaveChanges(); - dbContext.Set().Add(new Category { Number = "00", Name = "网关", Icon = "gateway" }); - dbContext.Set().Add(new Category { Number = "10", Name = "安防", Icon = "safe" }); - dbContext.Set().Add(new Category { Number = "20", Name = "电器", Icon = "electric" }); - dbContext.Set().Add(new Category { Number = "30", Name = "照明", Icon = "lighting" }); - dbContext.Set().Add(new Category { Number = "40", Name = "监测", Icon = "monitor" }); + dbContext.Set().Add(new Category { Id = Guid.Parse("BA92B82B-1E92-428B-92ED-28AD93FB7514"), Number = "00", Name = "网关", Icon = "gateway" }); + dbContext.Set().Add(new Category { Id = Guid.Parse("8E271914-622C-4B4D-BD33-78993F99BE43"), Number = "10", Name = "安防", Icon = "safe" }); + dbContext.Set().Add(new Category { Id = Guid.Parse("F510E634-5D1E-4398-A121-6945D43B5A5C"), Number = "20", Name = "电器", Icon = "electric" }); + dbContext.Set().Add(new Category { Id = Guid.Parse("AC2A427C-173C-4277-B9C5-3B73FFE841C9"), Number = "30", Name = "照明", Icon = "lighting" }); + dbContext.Set().Add(new Category { Id = Guid.Parse("67FC5B9D-6479-4714-8D07-E24EF0AEB502"), Number = "40", Name = "监测", Icon = "monitor" }); dbContext.SaveChanges(); } } diff --git a/projects/IoT/IoTNode/Services/EventHandler.cs b/projects/IoT/IoTNode/Services/EventHandler.cs index 7dd611e1..d75cdee4 100644 --- a/projects/IoT/IoTNode/Services/EventHandler.cs +++ b/projects/IoT/IoTNode/Services/EventHandler.cs @@ -7,45 +7,45 @@ using System.Collections.Concurrent; namespace IoTNode.Services { - public class EventHandler : IEventHander>, - IEventHander>, - IEventHander>, - IEventHander>, - IEventHander>, - IEventHander>, + public class EventHandler : IEventHander>, + IEventHander>, + IEventHander>, + IEventHander>, + IEventHander>, + IEventHander>, IEventHander> { - public static ConcurrentDictionary Tiggers = new ConcurrentDictionary(); + public static ConcurrentDictionary Tiggers = new ConcurrentDictionary(); - public void Handle(EntityInsertedEvent message) + public void Handle(EntityInsertedEvent message) { RecurringJob.AddOrUpdate(message.Message.Id.ToString(), o => o.TimerHanle(message.Message.Id), message.Message.Cron); } - public void Handle(EntityUpdatedEvent message) + public void Handle(EntityUpdatedEvent message) { RecurringJob.AddOrUpdate(message.Message.Id.ToString(), o => o.TimerHanle(message.Message.Id), message.Message.Cron); } - public void Handle(EntityDeletedEvent message) + public void Handle(EntityDeletedEvent message) { RecurringJob.RemoveIfExists(message.Message.Id.ToString()); } - public void Handle(EntityInsertedEvent message) + public void Handle(EntityInsertedEvent message) { Tiggers.TryAdd(message.Message.Id, message.Message); } - public void Handle(EntityUpdatedEvent message) + public void Handle(EntityUpdatedEvent message) { - Tiggers.TryRemove(message.Message.Id, out Tigger tigger); + Tiggers.TryRemove(message.Message.Id, out IoTTigger tigger); Tiggers.TryAdd(message.Message.Id, message.Message); } - public void Handle(EntityDeletedEvent message) + public void Handle(EntityDeletedEvent message) { - Tiggers.TryRemove(message.Message.Id, out Tigger tigger); + Tiggers.TryRemove(message.Message.Id, out IoTTigger tigger); } public void Handle(EntityUpdatedEvent message) diff --git a/projects/IoT/IoTNode/Services/EventJob.cs b/projects/IoT/IoTNode/Services/EventJob.cs index 58b02500..d2cad5fc 100644 --- a/projects/IoT/IoTNode/Services/EventJob.cs +++ b/projects/IoT/IoTNode/Services/EventJob.cs @@ -7,9 +7,9 @@ namespace IoTNode.Services { public class EventJob { - private readonly IRepository _timerRepo; + private readonly IRepository _timerRepo; - public EventJob(IRepository timerRepo) + public EventJob(IRepository timerRepo) { this._timerRepo = timerRepo; } diff --git a/projects/IoT/IoTNode/Startup.cs b/projects/IoT/IoTNode/Startup.cs index 8ba4b5da..19edfa1d 100644 --- a/projects/IoT/IoTNode/Startup.cs +++ b/projects/IoT/IoTNode/Startup.cs @@ -2,12 +2,15 @@ using Application.Domain.Entities; using Infrastructure.Extensions; using IoT.Shared.DeviceServices.FBee; using IoT.Shared.DeviceServices.Onvif; +using IoT.Shared.DeviceServices.SerialPort; +using IoT.Shared.Infrastructure; using IoT.UI.Shard; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; @@ -22,26 +25,17 @@ namespace IoTNode public override void ConfigureServices(IServiceCollection services) { - //services.AddSingleton(); - services.AddSingleton(); - //services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + //services.AddSingleton(); + services.AddHostedService(o => o.GetService()); + services.AddHostedService(o => o.GetService()); + services.AddHostedService(o => o.GetService()); + //services.AddHostedService(o => o.GetService()); base.ConfigureServices(services); } - public override void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) - { - base.Configure(app, env, loggerFactory); - Task.Run(() => - { - app.ApplicationServices.GetService().Start(); - //app.ApplicationServices.GetService()?.Start(); - app.ApplicationServices.GetService()?.Start(); - app.ApplicationServices.GetService()?.Start(); - }); - } - public override void Seed(DbContext dbContext, IServiceProvider serviceProvider, IConfiguration configuration) { var cpuid = Helper.Instance.GetCPUNumber(); diff --git a/projects/IoTCenter/Application/Domain/Entities/Setting.cs b/projects/IoTCenter/Application/Domain/Entities/Setting.cs deleted file mode 100644 index a18e0f40..00000000 --- a/projects/IoTCenter/Application/Domain/Entities/Setting.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Infrastructure.Domain; - -namespace Application.Domain.Entities -{ - public class Setting : BaseEntity - { - public decimal Longitude { get; set; } - public decimal Latitude { get; set; } - public decimal Altitude { get; set; } - } -} \ No newline at end of file diff --git a/projects/IoTCenter/Areas/Admin/Controllers/IoT/TiggerController.cs b/projects/IoTCenter/Areas/Admin/Controllers/IoT/TiggerController.cs index 1147b087..c6ae732f 100644 --- a/projects/IoTCenter/Areas/Admin/Controllers/IoT/TiggerController.cs +++ b/projects/IoTCenter/Areas/Admin/Controllers/IoT/TiggerController.cs @@ -18,14 +18,14 @@ namespace IoTCenter.Areas.Admin.Controllers { [Authorize] [Area(nameof(Admin))] - public class TiggerController : CrudController, Tigger, EditTiggerModel> + public class TiggerController : CrudController, IoTTigger, EditTiggerModel> { private readonly IRepository _nodeRepo; - private readonly IRepository _repo; + private readonly IRepository _repo; private readonly AjaxController _ajax; private readonly IHubContext _pageHubContext; - public TiggerController(IRepository nodeRepo, IRepository repo, AjaxController ajax, IHubContext pageHubContext) : base(repo) + public TiggerController(IRepository nodeRepo, IRepository repo, AjaxController ajax, IHubContext pageHubContext) : base(repo) { this._repo = repo; this._nodeRepo = nodeRepo; @@ -33,17 +33,17 @@ namespace IoTCenter.Areas.Admin.Controllers this._pageHubContext = pageHubContext; } - public override IQueryable Include(IQueryable query) + public override IQueryable Include(IQueryable query) { return query.Include(o => o.Node).Include(o => o.Data).ThenInclude(o => o.Device); } - public override IQueryable Query(PagedListModel model, IQueryable query) + public override IQueryable Query(PagedListModel model, IQueryable query) { return query.Where(o => o.NodeId != null); } - public override void ToDisplayModel(Tigger entity, Tigger model) + public override void ToDisplayModel(IoTTigger entity, IoTTigger model) { //model.NodeName = entity.Node.Name; } @@ -94,7 +94,7 @@ namespace IoTCenter.Areas.Admin.Controllers return RedirectTo(); } - public override void ToModel(Tigger entity, EditTiggerModel model) + public override void ToModel(IoTTigger entity, EditTiggerModel model) { if (entity != null) { diff --git a/projects/IoTCenter/Areas/Admin/Controllers/IoT/TimerController.cs b/projects/IoTCenter/Areas/Admin/Controllers/IoT/TimerController.cs index b6981b8e..889ac80c 100644 --- a/projects/IoTCenter/Areas/Admin/Controllers/IoT/TimerController.cs +++ b/projects/IoTCenter/Areas/Admin/Controllers/IoT/TimerController.cs @@ -18,14 +18,14 @@ namespace IoTCenter.Areas.Admin.Controllers { [Authorize] [Area(nameof(Admin))] - public class TimerController : CrudController, Timer, EditTimerModel> + public class TimerController : CrudController, IoTTimer, EditTimerModel> { private readonly IRepository _nodeRepo; - private readonly IRepository _repo; + private readonly IRepository _repo; private readonly AjaxController _ajax; private readonly IHubContext _pageHubContext; - public TimerController(IRepository nodeRepo, IRepository repo, AjaxController ajax, IHubContext pageHubContext) : base(repo) + public TimerController(IRepository nodeRepo, IRepository repo, AjaxController ajax, IHubContext pageHubContext) : base(repo) { this._repo = repo; this._nodeRepo = nodeRepo; @@ -33,17 +33,17 @@ namespace IoTCenter.Areas.Admin.Controllers this._pageHubContext = pageHubContext; } - public override IQueryable Include(IQueryable query) + public override IQueryable Include(IQueryable query) { return query.Include(o => o.Node); } - public override IQueryable Query(PagedListModel model, IQueryable query) + public override IQueryable Query(PagedListModel model, IQueryable query) { return query.Where(o => o.NodeId != null); } - public override void ToDisplayModel(Timer entity, Timer model) + public override void ToDisplayModel(IoTTimer entity, IoTTimer model) { //model.NodeName = entity.Node.Name; } @@ -94,7 +94,7 @@ namespace IoTCenter.Areas.Admin.Controllers return RedirectTo(); } - public override void ToModel(Timer entity, EditTimerModel model) + public override void ToModel(IoTTimer entity, EditTimerModel model) { ViewData.SelectList(o => model.NodeId, () => this._ajax.GetNodeSelectList(model.NodeId)); base.ToModel(entity, model); diff --git a/projects/IoTCenter/Services/EventHandler.cs b/projects/IoTCenter/Services/EventHandler.cs index 553e7ec1..c02d803e 100644 --- a/projects/IoTCenter/Services/EventHandler.cs +++ b/projects/IoTCenter/Services/EventHandler.cs @@ -7,45 +7,45 @@ using System.Collections.Concurrent; namespace IoTCenter.Services { - public class EventHandler : IEventHander>, - IEventHander>, - IEventHander>, - IEventHander>, - IEventHander>, - IEventHander>, + public class EventHandler : IEventHander>, + IEventHander>, + IEventHander>, + IEventHander>, + IEventHander>, + IEventHander>, IEventHander> { - public static ConcurrentDictionary Tiggers = new ConcurrentDictionary(); + public static ConcurrentDictionary Tiggers = new ConcurrentDictionary(); - public void Handle(EntityInsertedEvent message) + public void Handle(EntityInsertedEvent message) { RecurringJob.AddOrUpdate(message.Message.Id.ToString(), o => o.TimerHanle(message.Message.Id), message.Message.Cron); } - public void Handle(EntityUpdatedEvent message) + public void Handle(EntityUpdatedEvent message) { RecurringJob.AddOrUpdate(message.Message.Id.ToString(), o => o.TimerHanle(message.Message.Id), message.Message.Cron); } - public void Handle(EntityDeletedEvent message) + public void Handle(EntityDeletedEvent message) { RecurringJob.RemoveIfExists(message.Message.Id.ToString()); } - public void Handle(EntityInsertedEvent message) + public void Handle(EntityInsertedEvent message) { Tiggers.TryAdd(message.Message.Id, message.Message); } - public void Handle(EntityUpdatedEvent message) + public void Handle(EntityUpdatedEvent message) { - Tiggers.TryRemove(message.Message.Id, out Tigger tigger); + Tiggers.TryRemove(message.Message.Id, out IoTTigger tigger); Tiggers.TryAdd(message.Message.Id, message.Message); } - public void Handle(EntityDeletedEvent message) + public void Handle(EntityDeletedEvent message) { - Tiggers.TryRemove(message.Message.Id, out Tigger tigger); + Tiggers.TryRemove(message.Message.Id, out IoTTigger tigger); } public void Handle(EntityUpdatedEvent message) diff --git a/projects/IoTCenter/Services/EventJob.cs b/projects/IoTCenter/Services/EventJob.cs index 3bfe8d51..32d04c4b 100644 --- a/projects/IoTCenter/Services/EventJob.cs +++ b/projects/IoTCenter/Services/EventJob.cs @@ -7,9 +7,9 @@ namespace IoTCenter.Services { public class EventJob { - private readonly IRepository _timerRepo; + private readonly IRepository _timerRepo; - public EventJob(IRepository timerRepo) + public EventJob(IRepository timerRepo) { this._timerRepo = timerRepo; } diff --git a/projects/IoTCenter/Services/PageHub.cs b/projects/IoTCenter/Services/PageHub.cs index 158d7bac..a92be284 100644 --- a/projects/IoTCenter/Services/PageHub.cs +++ b/projects/IoTCenter/Services/PageHub.cs @@ -28,8 +28,8 @@ namespace IoTCenter.Services private readonly IRepository _productRepo; private readonly IRepository _sceneRepo; private readonly IRepository _sceneCommandRepo; - private readonly IRepository _timerRepo; - private readonly IRepository _tiggerRepo; + private readonly IRepository _timerRepo; + private readonly IRepository _tiggerRepo; public PageHub(IConfiguration cfg, IRepository nodeRepo, @@ -41,8 +41,8 @@ namespace IoTCenter.Services IRepository productRepo, IRepository sceneRepo, IRepository sceneCommandRepo, - IRepository timerRepo, - IRepository tiggerRepo) + IRepository timerRepo, + IRepository tiggerRepo) { this._cfg = cfg; this._nodeRepo = nodeRepo; diff --git a/projects/IoTCenter/Startup.cs b/projects/IoTCenter/Startup.cs index 3788e099..b9f4308e 100644 --- a/projects/IoTCenter/Startup.cs +++ b/projects/IoTCenter/Startup.cs @@ -1,6 +1,5 @@ -using Application.Domain.Entities; -using Infrastructure.Events; using Infrastructure.Email; +using Infrastructure.Events; using Infrastructure.Sms; using Infrastructure.UI; using IoT.UI.Shard; @@ -8,14 +7,11 @@ using IoTCenter.Services; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Routing; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; -using System.Linq; -using System.Reflection; using System.Threading.Tasks; namespace IoTCenter @@ -58,23 +54,5 @@ namespace IoTCenter { this.UseSignalR(endpoints); } - - public override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder?.Entity(); - base.OnModelCreating(modelBuilder); - } - - public override void Seed(DbContext dbContext, IServiceProvider serviceProvider, IConfiguration configuration) - { - dbContext?.Set().Add(new Setting - { - Longitude = 116.54296875m, - Latitude = 41.77131167974391m, - Altitude = 0m - }); - dbContext?.SaveChanges(); - base.Seed(dbContext, serviceProvider, configuration); - } } } \ No newline at end of file