Former-commit-id: 5022ef120dc093db65c61b5239f86aea2223be2c
TangShanKaiPing
wanggang 6 years ago
parent f034fe5f11
commit 47898a2d54

@ -2,19 +2,11 @@ using System;
namespace Infrastructure.Domain
{
public abstract class BaseEntity
public abstract class BaseEntity : EntityBase<Guid>
{
public BaseEntity()
{
this.Id = Guid.NewGuid();
}
public Guid Id { get; set; }
public string IsDeleted { get; set; }
public override string ToString()
{
return $"{ GetType().FullName}[{Id}]";
}
}
}

@ -0,0 +1,13 @@
namespace Infrastructure.Domain
{
public class EntityBase<TKey>
{
public TKey Id { get; set; }
public string IsDeleted { get; set; }
public override string ToString()
{
return $"{ GetType().FullName}[{Id}]";
}
}
}

@ -39,7 +39,7 @@ namespace Application.Domain.Entities
[Display(Name = "设备")]
public Device Device { get; set; }
public List<Tigger> Tiggers { get; set; } = new List<Tigger>();
public List<IoTTigger> Tiggers { get; set; } = new List<IoTTigger>();
public dynamic GetValue()
{

@ -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; }

@ -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; }

@ -49,7 +49,7 @@ namespace Application.Domain.Entities
public List<Device> Devices { get; set; } = new List<Device>();
public List<Scene> Scenes { get; set; } = new List<Scene>();
public List<Timer> Timers { get; set; } = new List<Timer>();
public List<Tigger> Tiggers { get; set; } = new List<Tigger>();
public List<IoTTimer> Timers { get; set; } = new List<IoTTimer>();
public List<IoTTigger> Tiggers { get; set; } = new List<IoTTigger>();
}
}

@ -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; }
}
}

@ -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; }
}
}

@ -22,7 +22,7 @@ using System.Threading.Tasks;
namespace IoT.Shared.DeviceServices.FBee
{
public class FBeeService : BaseDeviceService
public class FBeeService : DeviceService
{
private readonly ConcurrentDictionary<string, TcpClientWrapper> Clients = new ConcurrentDictionary<string, TcpClientWrapper>();
@ -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

@ -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<string, (Device camera, Process local, Process remote)> _list = new ConcurrentDictionary<string, (Device camera, Process local, Process remote)>();
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()

@ -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)
{

@ -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<bool>("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();
}
}
}

@ -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 = "<挂起>")]

@ -1,13 +0,0 @@
using System;
namespace IoT.Shared.Infrastructure
{
public interface IDeviceService : IDisposable
{
void Start();
void Stop();
void Execute();
}
}

@ -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<bool>("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<EditTimerModel>();
var nodeRepo = scope.ServiceProvider.GetService<IRepository<Node>>();
var timerRepo = scope.ServiceProvider.GetService<IRepository<Timer>>();
var timerRepo = scope.ServiceProvider.GetService<IRepository<IoTTimer>>();
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<IEventPublisher>().Publish(new EntityUpdatedEvent<Timer>(timer));
scope.ServiceProvider.GetService<IEventPublisher>().Publish(new EntityUpdatedEvent<IoTTimer>(timer));
this.ClientToServer(Methods.EditTimerResponse, message);
}
else if (method == Methods.DeleteTimerRequest)
{
var model = message.FromJson<EditTimerModel>();
var timerRepo = scope.ServiceProvider.GetService<IRepository<Timer>>();
var timerRepo = scope.ServiceProvider.GetService<IRepository<IoTTimer>>();
var timer = timerRepo.Table().FirstOrDefault(o => o.Id == model.Id);
if (timer != null)
{
timerRepo.Delete(timer);
timerRepo.SaveChanges();
scope.ServiceProvider.GetService<IEventPublisher>().Publish(new EntityDeletedEvent<Timer>(timer));
scope.ServiceProvider.GetService<IEventPublisher>().Publish(new EntityDeletedEvent<IoTTimer>(timer));
}
this.ClientToServer(Methods.DeleteTimerResponse, message);
}
@ -282,11 +426,11 @@ namespace IoT.Shared.Infrastructure
{
var model = message.FromJson<EditTiggerModel>();
var nodeRepo = scope.ServiceProvider.GetService<IRepository<Node>>();
var repo = scope.ServiceProvider.GetService<IRepository<Tigger>>();
var repo = scope.ServiceProvider.GetService<IRepository<IoTTigger>>();
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<IEventPublisher>().Publish(new EntityUpdatedEvent<Tigger>(entity));
scope.ServiceProvider.GetService<IEventPublisher>().Publish(new EntityUpdatedEvent<IoTTigger>(entity));
this.ClientToServer(Methods.EditTiggerResponse, message);
}
else if (method == Methods.DeleteTiggerRequest)
{
var model = message.FromJson<EditTiggerModel>();
var repo = scope.ServiceProvider.GetService<IRepository<Tigger>>();
var repo = scope.ServiceProvider.GetService<IRepository<IoTTigger>>();
var entity = repo.Table().FirstOrDefault(o => o.Id == model.Id);
if (entity != null)
{
repo.Delete(entity);
repo.SaveChanges();
scope.ServiceProvider.GetService<IEventPublisher>().Publish(new EntityDeletedEvent<Tigger>(entity));
scope.ServiceProvider.GetService<IEventPublisher>().Publish(new EntityDeletedEvent<IoTTigger>(entity));
}
this.ClientToServer(Methods.DeleteTiggerResponse, message);
}

@ -111,9 +111,9 @@ namespace IoT.UI.Shard
modelBuilder.Entity<LiveRecord>().Property(o => o.DeviceNumber).IsRequired();
modelBuilder.Entity<Command>().HasOne(o => o.Api).WithMany(o => o.Commands).HasForeignKey(o => o.ApiId);
modelBuilder.Entity<Scene>().HasOne(o => o.Node).WithMany(o => o.Scenes).HasForeignKey(o => o.NodeId);
modelBuilder.Entity<Timer>().HasOne(o => o.Node).WithMany(o => o.Timers).HasForeignKey(o => o.NodeId);
modelBuilder.Entity<Tigger>().HasOne(o => o.Node).WithMany(o => o.Tiggers).HasForeignKey(o => o.NodeId);
modelBuilder.Entity<Tigger>().HasOne(o => o.Data).WithMany(o => o.Tiggers).HasForeignKey(o => o.DataId);
modelBuilder.Entity<IoTTimer>().HasOne(o => o.Node).WithMany(o => o.Timers).HasForeignKey(o => o.NodeId);
modelBuilder.Entity<IoTTigger>().HasOne(o => o.Node).WithMany(o => o.Tiggers).HasForeignKey(o => o.NodeId);
modelBuilder.Entity<IoTTigger>().HasOne(o => o.Data).WithMany(o => o.Tiggers).HasForeignKey(o => o.DataId);
modelBuilder.Entity<SceneCommand>().HasOne(o => o.Scene).WithMany(o => o.SceneCommands).HasForeignKey(o => o.SceneId);
modelBuilder.Entity<SceneCommand>().HasOne(o => o.Command).WithMany(o => o.SceneCommands).HasForeignKey(o => o.CommandId);
modelBuilder.Entity<TimerCommand>().HasOne(o => o.Timer).WithMany(o => o.TimerCommands).HasForeignKey(o => o.TimerId);
@ -189,11 +189,11 @@ namespace IoT.UI.Shard
});
dbContext.SaveChanges();
dbContext.Set<Category>().Add(new Category { Number = "00", Name = "网关", Icon = "gateway" });
dbContext.Set<Category>().Add(new Category { Number = "10", Name = "安防", Icon = "safe" });
dbContext.Set<Category>().Add(new Category { Number = "20", Name = "电器", Icon = "electric" });
dbContext.Set<Category>().Add(new Category { Number = "30", Name = "照明", Icon = "lighting" });
dbContext.Set<Category>().Add(new Category { Number = "40", Name = "监测", Icon = "monitor" });
dbContext.Set<Category>().Add(new Category { Id = Guid.Parse("BA92B82B-1E92-428B-92ED-28AD93FB7514"), Number = "00", Name = "网关", Icon = "gateway" });
dbContext.Set<Category>().Add(new Category { Id = Guid.Parse("8E271914-622C-4B4D-BD33-78993F99BE43"), Number = "10", Name = "安防", Icon = "safe" });
dbContext.Set<Category>().Add(new Category { Id = Guid.Parse("F510E634-5D1E-4398-A121-6945D43B5A5C"), Number = "20", Name = "电器", Icon = "electric" });
dbContext.Set<Category>().Add(new Category { Id = Guid.Parse("AC2A427C-173C-4277-B9C5-3B73FFE841C9"), Number = "30", Name = "照明", Icon = "lighting" });
dbContext.Set<Category>().Add(new Category { Id = Guid.Parse("67FC5B9D-6479-4714-8D07-E24EF0AEB502"), Number = "40", Name = "监测", Icon = "monitor" });
dbContext.SaveChanges();
}
}

@ -7,45 +7,45 @@ using System.Collections.Concurrent;
namespace IoTNode.Services
{
public class EventHandler : IEventHander<EntityInsertedEvent<Timer>>,
IEventHander<EntityUpdatedEvent<Timer>>,
IEventHander<EntityDeletedEvent<Timer>>,
IEventHander<EntityInsertedEvent<Tigger>>,
IEventHander<EntityUpdatedEvent<Tigger>>,
IEventHander<EntityDeletedEvent<Tigger>>,
public class EventHandler : IEventHander<EntityInsertedEvent<IoTTimer>>,
IEventHander<EntityUpdatedEvent<IoTTimer>>,
IEventHander<EntityDeletedEvent<IoTTimer>>,
IEventHander<EntityInsertedEvent<IoTTigger>>,
IEventHander<EntityUpdatedEvent<IoTTigger>>,
IEventHander<EntityDeletedEvent<IoTTigger>>,
IEventHander<EntityUpdatedEvent<Data>>
{
public static ConcurrentDictionary<Guid, Tigger> Tiggers = new ConcurrentDictionary<Guid, Tigger>();
public static ConcurrentDictionary<Guid, IoTTigger> Tiggers = new ConcurrentDictionary<Guid, IoTTigger>();
public void Handle(EntityInsertedEvent<Timer> message)
public void Handle(EntityInsertedEvent<IoTTimer> message)
{
RecurringJob.AddOrUpdate<EventJob>(message.Message.Id.ToString(), o => o.TimerHanle(message.Message.Id), message.Message.Cron);
}
public void Handle(EntityUpdatedEvent<Timer> message)
public void Handle(EntityUpdatedEvent<IoTTimer> message)
{
RecurringJob.AddOrUpdate<EventJob>(message.Message.Id.ToString(), o => o.TimerHanle(message.Message.Id), message.Message.Cron);
}
public void Handle(EntityDeletedEvent<Timer> message)
public void Handle(EntityDeletedEvent<IoTTimer> message)
{
RecurringJob.RemoveIfExists(message.Message.Id.ToString());
}
public void Handle(EntityInsertedEvent<Tigger> message)
public void Handle(EntityInsertedEvent<IoTTigger> message)
{
Tiggers.TryAdd(message.Message.Id, message.Message);
}
public void Handle(EntityUpdatedEvent<Tigger> message)
public void Handle(EntityUpdatedEvent<IoTTigger> 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<Tigger> message)
public void Handle(EntityDeletedEvent<IoTTigger> message)
{
Tiggers.TryRemove(message.Message.Id, out Tigger tigger);
Tiggers.TryRemove(message.Message.Id, out IoTTigger tigger);
}
public void Handle(EntityUpdatedEvent<Data> message)

@ -7,9 +7,9 @@ namespace IoTNode.Services
{
public class EventJob
{
private readonly IRepository<Timer> _timerRepo;
private readonly IRepository<IoTTimer> _timerRepo;
public EventJob(IRepository<Timer> timerRepo)
public EventJob(IRepository<IoTTimer> timerRepo)
{
this._timerRepo = timerRepo;
}

@ -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<INodeService, NodeService>();
services.AddSingleton<IoT.Shared.Infrastructure.NodeService>();
//services.AddSingleton<SerialPortService>();
services.AddSingleton<NodeService>();
services.AddSingleton<OnvifService>();
services.AddSingleton<FBeeService>();
//services.AddSingleton<SerialPortService>();
services.AddHostedService(o => o.GetService<NodeService>());
services.AddHostedService(o => o.GetService<OnvifService>());
services.AddHostedService(o => o.GetService<FBeeService>());
//services.AddHostedService(o => o.GetService<SerialPortService>());
base.ConfigureServices(services);
}
public override void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
base.Configure(app, env, loggerFactory);
Task.Run(() =>
{
app.ApplicationServices.GetService<IoT.Shared.Infrastructure.NodeService>().Start();
//app.ApplicationServices.GetService<SerialPortService>()?.Start();
app.ApplicationServices.GetService<OnvifService>()?.Start();
app.ApplicationServices.GetService<FBeeService>()?.Start();
});
}
public override void Seed(DbContext dbContext, IServiceProvider serviceProvider, IConfiguration configuration)
{
var cpuid = Helper.Instance.GetCPUNumber();

@ -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; }
}
}

@ -18,14 +18,14 @@ namespace IoTCenter.Areas.Admin.Controllers
{
[Authorize]
[Area(nameof(Admin))]
public class TiggerController : CrudController<Tigger, PagedListModel<Tigger>, Tigger, EditTiggerModel>
public class TiggerController : CrudController<IoTTigger, PagedListModel<IoTTigger>, IoTTigger, EditTiggerModel>
{
private readonly IRepository<Node> _nodeRepo;
private readonly IRepository<Tigger> _repo;
private readonly IRepository<IoTTigger> _repo;
private readonly AjaxController _ajax;
private readonly IHubContext<PageHub> _pageHubContext;
public TiggerController(IRepository<Node> nodeRepo, IRepository<Tigger> repo, AjaxController ajax, IHubContext<PageHub> pageHubContext) : base(repo)
public TiggerController(IRepository<Node> nodeRepo, IRepository<IoTTigger> repo, AjaxController ajax, IHubContext<PageHub> pageHubContext) : base(repo)
{
this._repo = repo;
this._nodeRepo = nodeRepo;
@ -33,17 +33,17 @@ namespace IoTCenter.Areas.Admin.Controllers
this._pageHubContext = pageHubContext;
}
public override IQueryable<Tigger> Include(IQueryable<Tigger> query)
public override IQueryable<IoTTigger> Include(IQueryable<IoTTigger> query)
{
return query.Include(o => o.Node).Include(o => o.Data).ThenInclude(o => o.Device);
}
public override IQueryable<Tigger> Query(PagedListModel<Tigger> model, IQueryable<Tigger> query)
public override IQueryable<IoTTigger> Query(PagedListModel<IoTTigger> model, IQueryable<IoTTigger> 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)
{

@ -18,14 +18,14 @@ namespace IoTCenter.Areas.Admin.Controllers
{
[Authorize]
[Area(nameof(Admin))]
public class TimerController : CrudController<Timer, PagedListModel<Timer>, Timer, EditTimerModel>
public class TimerController : CrudController<IoTTimer, PagedListModel<IoTTimer>, IoTTimer, EditTimerModel>
{
private readonly IRepository<Node> _nodeRepo;
private readonly IRepository<Timer> _repo;
private readonly IRepository<IoTTimer> _repo;
private readonly AjaxController _ajax;
private readonly IHubContext<PageHub> _pageHubContext;
public TimerController(IRepository<Node> nodeRepo, IRepository<Timer> repo, AjaxController ajax, IHubContext<PageHub> pageHubContext) : base(repo)
public TimerController(IRepository<Node> nodeRepo, IRepository<IoTTimer> repo, AjaxController ajax, IHubContext<PageHub> pageHubContext) : base(repo)
{
this._repo = repo;
this._nodeRepo = nodeRepo;
@ -33,17 +33,17 @@ namespace IoTCenter.Areas.Admin.Controllers
this._pageHubContext = pageHubContext;
}
public override IQueryable<Timer> Include(IQueryable<Timer> query)
public override IQueryable<IoTTimer> Include(IQueryable<IoTTimer> query)
{
return query.Include(o => o.Node);
}
public override IQueryable<Timer> Query(PagedListModel<Timer> model, IQueryable<Timer> query)
public override IQueryable<IoTTimer> Query(PagedListModel<IoTTimer> model, IQueryable<IoTTimer> 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);

@ -7,45 +7,45 @@ using System.Collections.Concurrent;
namespace IoTCenter.Services
{
public class EventHandler : IEventHander<EntityInsertedEvent<Timer>>,
IEventHander<EntityUpdatedEvent<Timer>>,
IEventHander<EntityDeletedEvent<Timer>>,
IEventHander<EntityInsertedEvent<Tigger>>,
IEventHander<EntityUpdatedEvent<Tigger>>,
IEventHander<EntityDeletedEvent<Tigger>>,
public class EventHandler : IEventHander<EntityInsertedEvent<IoTTimer>>,
IEventHander<EntityUpdatedEvent<IoTTimer>>,
IEventHander<EntityDeletedEvent<IoTTimer>>,
IEventHander<EntityInsertedEvent<IoTTigger>>,
IEventHander<EntityUpdatedEvent<IoTTigger>>,
IEventHander<EntityDeletedEvent<IoTTigger>>,
IEventHander<EntityUpdatedEvent<Data>>
{
public static ConcurrentDictionary<Guid, Tigger> Tiggers = new ConcurrentDictionary<Guid, Tigger>();
public static ConcurrentDictionary<Guid, IoTTigger> Tiggers = new ConcurrentDictionary<Guid, IoTTigger>();
public void Handle(EntityInsertedEvent<Timer> message)
public void Handle(EntityInsertedEvent<IoTTimer> message)
{
RecurringJob.AddOrUpdate<EventJob>(message.Message.Id.ToString(), o => o.TimerHanle(message.Message.Id), message.Message.Cron);
}
public void Handle(EntityUpdatedEvent<Timer> message)
public void Handle(EntityUpdatedEvent<IoTTimer> message)
{
RecurringJob.AddOrUpdate<EventJob>(message.Message.Id.ToString(), o => o.TimerHanle(message.Message.Id), message.Message.Cron);
}
public void Handle(EntityDeletedEvent<Timer> message)
public void Handle(EntityDeletedEvent<IoTTimer> message)
{
RecurringJob.RemoveIfExists(message.Message.Id.ToString());
}
public void Handle(EntityInsertedEvent<Tigger> message)
public void Handle(EntityInsertedEvent<IoTTigger> message)
{
Tiggers.TryAdd(message.Message.Id, message.Message);
}
public void Handle(EntityUpdatedEvent<Tigger> message)
public void Handle(EntityUpdatedEvent<IoTTigger> 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<Tigger> message)
public void Handle(EntityDeletedEvent<IoTTigger> message)
{
Tiggers.TryRemove(message.Message.Id, out Tigger tigger);
Tiggers.TryRemove(message.Message.Id, out IoTTigger tigger);
}
public void Handle(EntityUpdatedEvent<Data> message)

@ -7,9 +7,9 @@ namespace IoTCenter.Services
{
public class EventJob
{
private readonly IRepository<Timer> _timerRepo;
private readonly IRepository<IoTTimer> _timerRepo;
public EventJob(IRepository<Timer> timerRepo)
public EventJob(IRepository<IoTTimer> timerRepo)
{
this._timerRepo = timerRepo;
}

@ -28,8 +28,8 @@ namespace IoTCenter.Services
private readonly IRepository<Product> _productRepo;
private readonly IRepository<Scene> _sceneRepo;
private readonly IRepository<SceneCommand> _sceneCommandRepo;
private readonly IRepository<Timer> _timerRepo;
private readonly IRepository<Tigger> _tiggerRepo;
private readonly IRepository<IoTTimer> _timerRepo;
private readonly IRepository<IoTTigger> _tiggerRepo;
public PageHub(IConfiguration cfg,
IRepository<Node> nodeRepo,
@ -41,8 +41,8 @@ namespace IoTCenter.Services
IRepository<Product> productRepo,
IRepository<Scene> sceneRepo,
IRepository<SceneCommand> sceneCommandRepo,
IRepository<Timer> timerRepo,
IRepository<Tigger> tiggerRepo)
IRepository<IoTTimer> timerRepo,
IRepository<IoTTigger> tiggerRepo)
{
this._cfg = cfg;
this._nodeRepo = nodeRepo;

@ -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<PageHub>(endpoints);
}
public override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder?.Entity<Setting>();
base.OnModelCreating(modelBuilder);
}
public override void Seed(DbContext dbContext, IServiceProvider serviceProvider, IConfiguration configuration)
{
dbContext?.Set<Setting>().Add(new Setting
{
Longitude = 116.54296875m,
Latitude = 41.77131167974391m,
Altitude = 0m
});
dbContext?.SaveChanges();
base.Seed(dbContext, serviceProvider, configuration);
}
}
}
Loading…
Cancel
Save