From 1fc11e499b85a6d4684ffe5a15323809d31adc32 Mon Sep 17 00:00:00 2001 From: yanghongwei Date: Wed, 24 Jul 2024 21:30:21 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=A1=B9=E7=9B=AE=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .config/dotnet-tools.json | 12 + .dockerignore | 25 + Command/AutoMapper/AutoMapperConfig.cs | 26 + Command/AutoMapper/CustomProfile.cs | 25 + Command/Extension/LoadJobListExtension.cs | 35 + Command/Extension/PlcHelper.cs | 212 ++ Command/Extension/PlcHelper2.cs | 138 + Command/Extension/SocketExtension.cs | 30 + Command/Model/ApiResult.cs | 26 + Command/Model/BaseModel.cs | 44 + Command/Model/EntityModel/Alert.cs | 26 + Command/Model/EntityModel/Device.cs | 51 + Command/Model/EntityModel/DeviceUsed.cs | 17 + Command/Model/EntityModel/Employee.cs | 26 + Command/Model/EntityModel/Group.cs | 26 + Command/Model/EntityModel/HJ212.cs | 51 + Command/Model/EntityModel/Plan.cs | 33 + Command/Model/EntityModel/Radar.cs | 103 + Command/Model/EntityModel/Video.cs | 22 + Command/Model/ExportModel.cs | 54 + Command/Model/GroupDevice.cs | 21 + Command/Model/Paging.cs | 42 + Command/Model/RequestModel/AutoReport.cs | 34 + Command/Model/RequestModel/RequestLogin.cs | 22 + .../RequestModel/RequestUpdateAccount.cs | 26 + Command/Model/SocketModel.cs | 51 + Command/Model/columnView.cs | 24 + Configuration/SwaggerConfigureOptions.cs | 41 + Controllers/AlertController.cs | 38 + Controllers/DataController.cs | 88 + Controllers/DeviceController.cs | 222 ++ Controllers/DeviceUsedController.cs | 34 + Controllers/EmployeeController.cs | 108 + Controllers/GroupController.cs | 79 + Controllers/HomeController.cs | 101 + Controllers/PlanController.cs | 89 + Controllers/RadarController.cs | 59 + Controllers/VideoController.cs | 93 + Controllers/WeatherForecastController.cs | 39 + Dockerfile | 21 + LangGuan.csproj | 48 + LangGuan.sln | 25 + LangGuan.xml | 2403 +++++++++++++++++ Middleware/CustomerExceptionFilter.cs | 47 + Middleware/RequestLoggingMiddleware.cs | 97 + Program.cs | 27 + Properties/launchSettings.json | 36 + Services/AlertService.cs | 79 + Services/BaseService.cs | 204 ++ Services/DeviceSerive.cs | 399 +++ Services/DeviceUsedService.cs | 63 + Services/EmployeeService.cs | 104 + Services/GroupService.cs | 136 + Services/HJ212/NetServer.cs | 65 + Services/HJ212/NetSession.cs | 96 + Services/HJ212SocketServer.cs | 339 +++ Services/HJ212_2017.cs | 144 + Services/Hj212Service.cs | 343 +++ Services/Job/JobServiceFactory.cs | 30 + Services/Job/Monitor.cs | 95 + Services/Job/MyJob.cs | 36 + Services/PingService.cs | 89 + Services/PlanService.cs | 219 ++ Services/RadarItemService.cs | 75 + Services/RadarService.cs | 279 ++ Services/VideoService.cs | 90 + Services/models/CommandNumber.cs | 42 + Services/models/CpCommand.cs | 123 + Services/models/DataSegment.cs | 154 ++ Services/models/FactorCode.cs | 426 +++ Services/models/InstrumentationDataFlag.cs | 68 + Services/models/NetPackage.cs | 121 + Services/models/PackageFlag.cs | 121 + Services/models/PollutantInfo.cs | 67 + Services/models/ResponseCode.cs | 52 + Services/models/columnView.cs | 11 + Startup.cs | 163 ++ WeatherForecast.cs | 15 + appsettings.Development.json | 9 + appsettings.json | 17 + wwwroot/model/1.png | Bin 0 -> 128992 bytes wwwroot/model/3.06.txt | 797 ++++++ 82 files changed, 9968 insertions(+) create mode 100644 .config/dotnet-tools.json create mode 100644 .dockerignore create mode 100644 Command/AutoMapper/AutoMapperConfig.cs create mode 100644 Command/AutoMapper/CustomProfile.cs create mode 100644 Command/Extension/LoadJobListExtension.cs create mode 100644 Command/Extension/PlcHelper.cs create mode 100644 Command/Extension/PlcHelper2.cs create mode 100644 Command/Extension/SocketExtension.cs create mode 100644 Command/Model/ApiResult.cs create mode 100644 Command/Model/BaseModel.cs create mode 100644 Command/Model/EntityModel/Alert.cs create mode 100644 Command/Model/EntityModel/Device.cs create mode 100644 Command/Model/EntityModel/DeviceUsed.cs create mode 100644 Command/Model/EntityModel/Employee.cs create mode 100644 Command/Model/EntityModel/Group.cs create mode 100644 Command/Model/EntityModel/HJ212.cs create mode 100644 Command/Model/EntityModel/Plan.cs create mode 100644 Command/Model/EntityModel/Radar.cs create mode 100644 Command/Model/EntityModel/Video.cs create mode 100644 Command/Model/ExportModel.cs create mode 100644 Command/Model/GroupDevice.cs create mode 100644 Command/Model/Paging.cs create mode 100644 Command/Model/RequestModel/AutoReport.cs create mode 100644 Command/Model/RequestModel/RequestLogin.cs create mode 100644 Command/Model/RequestModel/RequestUpdateAccount.cs create mode 100644 Command/Model/SocketModel.cs create mode 100644 Command/Model/columnView.cs create mode 100644 Configuration/SwaggerConfigureOptions.cs create mode 100644 Controllers/AlertController.cs create mode 100644 Controllers/DataController.cs create mode 100644 Controllers/DeviceController.cs create mode 100644 Controllers/DeviceUsedController.cs create mode 100644 Controllers/EmployeeController.cs create mode 100644 Controllers/GroupController.cs create mode 100644 Controllers/HomeController.cs create mode 100644 Controllers/PlanController.cs create mode 100644 Controllers/RadarController.cs create mode 100644 Controllers/VideoController.cs create mode 100644 Controllers/WeatherForecastController.cs create mode 100644 Dockerfile create mode 100644 LangGuan.csproj create mode 100644 LangGuan.sln create mode 100644 LangGuan.xml create mode 100644 Middleware/CustomerExceptionFilter.cs create mode 100644 Middleware/RequestLoggingMiddleware.cs create mode 100644 Program.cs create mode 100644 Properties/launchSettings.json create mode 100644 Services/AlertService.cs create mode 100644 Services/BaseService.cs create mode 100644 Services/DeviceSerive.cs create mode 100644 Services/DeviceUsedService.cs create mode 100644 Services/EmployeeService.cs create mode 100644 Services/GroupService.cs create mode 100644 Services/HJ212/NetServer.cs create mode 100644 Services/HJ212/NetSession.cs create mode 100644 Services/HJ212SocketServer.cs create mode 100644 Services/HJ212_2017.cs create mode 100644 Services/Hj212Service.cs create mode 100644 Services/Job/JobServiceFactory.cs create mode 100644 Services/Job/Monitor.cs create mode 100644 Services/Job/MyJob.cs create mode 100644 Services/PingService.cs create mode 100644 Services/PlanService.cs create mode 100644 Services/RadarItemService.cs create mode 100644 Services/RadarService.cs create mode 100644 Services/VideoService.cs create mode 100644 Services/models/CommandNumber.cs create mode 100644 Services/models/CpCommand.cs create mode 100644 Services/models/DataSegment.cs create mode 100644 Services/models/FactorCode.cs create mode 100644 Services/models/InstrumentationDataFlag.cs create mode 100644 Services/models/NetPackage.cs create mode 100644 Services/models/PackageFlag.cs create mode 100644 Services/models/PollutantInfo.cs create mode 100644 Services/models/ResponseCode.cs create mode 100644 Services/models/columnView.cs create mode 100644 Startup.cs create mode 100644 WeatherForecast.cs create mode 100644 appsettings.Development.json create mode 100644 appsettings.json create mode 100644 wwwroot/model/1.png create mode 100644 wwwroot/model/3.06.txt diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json new file mode 100644 index 0000000..96be437 --- /dev/null +++ b/.config/dotnet-tools.json @@ -0,0 +1,12 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "dotnet-ef": { + "version": "7.0.11", + "commands": [ + "dotnet-ef" + ] + } + } +} \ No newline at end of file diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..3729ff0 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,25 @@ +**/.classpath +**/.dockerignore +**/.env +**/.git +**/.gitignore +**/.project +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/*.*proj.user +**/*.dbmdl +**/*.jfm +**/azds.yaml +**/bin +**/charts +**/docker-compose* +**/Dockerfile* +**/node_modules +**/npm-debug.log +**/obj +**/secrets.dev.yaml +**/values.dev.yaml +LICENSE +README.md \ No newline at end of file diff --git a/Command/AutoMapper/AutoMapperConfig.cs b/Command/AutoMapper/AutoMapperConfig.cs new file mode 100644 index 0000000..b8ad1b6 --- /dev/null +++ b/Command/AutoMapper/AutoMapperConfig.cs @@ -0,0 +1,26 @@ +using AutoMapper; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.AutoMapper +{ + /// + /// AutoMapperConfig + /// + public class AutoMapperConfig + { + /// + /// + /// + /// + public static MapperConfiguration RegisterMappings() + { + return new MapperConfiguration(cfg => + { + cfg.AddProfile(new CustomProfile()); + }); + } + } +} diff --git a/Command/AutoMapper/CustomProfile.cs b/Command/AutoMapper/CustomProfile.cs new file mode 100644 index 0000000..d9b1bd9 --- /dev/null +++ b/Command/AutoMapper/CustomProfile.cs @@ -0,0 +1,25 @@ +using AutoMapper; +using LangGuan.Command.Model.EntityModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.AutoMapper +{ + /// + /// CustomProfile + /// + public class CustomProfile : Profile + { + /// + /// 配置构造函数,用来创建关系映射 + /// + public CustomProfile() + { + //第一个参数是原对象,第二个是目的对象 + CreateMap(); + //CreateMap(); + } + } +} diff --git a/Command/Extension/LoadJobListExtension.cs b/Command/Extension/LoadJobListExtension.cs new file mode 100644 index 0000000..9414cd0 --- /dev/null +++ b/Command/Extension/LoadJobListExtension.cs @@ -0,0 +1,35 @@ +using LangGuan.Services; +using LangGuan.Services.Job; +using Microsoft.Extensions.DependencyInjection; +using Quartz; +using Quartz.Impl; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Extension +{ + public static class LoadJobListExtension + { + public static void AddJobService(this IServiceCollection services) + { + //services.AddSingleton(); + services.AddTransient(); + Monitor quartz = null; + services.AddSingleton(); + quartz = new Monitor(services.BuildServiceProvider()); + + using (var scope = services.BuildServiceProvider()) + { + var myService = scope.GetRequiredService(); + var list = myService.GetList().GetAwaiter().GetResult(); + if (list.Any()) + { + quartz.SetJobs(list); + _ = quartz.StartAsync(); + } + } + } + } +} diff --git a/Command/Extension/PlcHelper.cs b/Command/Extension/PlcHelper.cs new file mode 100644 index 0000000..7e3e26a --- /dev/null +++ b/Command/Extension/PlcHelper.cs @@ -0,0 +1,212 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using HslCommunication; +using HslCommunication.Profinet.Siemens; +namespace LangGuan.Command.Extension +{ + public class PlcHelper + { + /// + /// 写数据 + /// + /// + public Task WriteVal(string ip, string key) + { + try + { + using (var siemensTcpNet = new SiemensS7Net(SiemensPLCS.S200Smart, ip) { ConnectTimeOut = 5000 }) + { + var con = siemensTcpNet.ConnectServer(); + if (con.IsSuccess) + { + var result = siemensTcpNet.Write(key, (ushort)1); + Console.WriteLine($"连接plc成功..{ip},写入key:{key},是否写入成功:{result.IsSuccess},msg:{result.Message}code:{result.ErrorCode}"); + } + + } + } + catch (Exception ex) + { + + Console.WriteLine($"连接plc失败..{ip},msg:{ex.Message}"); + } + return Task.CompletedTask; + } + public Task WriteVal(string ip, string key, int val) + { + try + { + using (var siemensTcpNet = new SiemensS7Net(SiemensPLCS.S200Smart, ip) { ConnectTimeOut = 5000 }) + { + var con = siemensTcpNet.ConnectServer(); + if (con.IsSuccess) + { + var result = siemensTcpNet.Write(key, (ushort)val); + Console.WriteLine($"连接plc成功..{ip},写入key:{key},是否写入成功:{result.IsSuccess},msg:{result.Message}code:{result.ErrorCode}"); + } + } + } + catch (Exception ex) + { + + Console.WriteLine($"连接plc失败..{ip},msg:{ex.Message}"); + } + return Task.CompletedTask; + } + /// + /// SetVal + /// + /// + /// + /// + /// + public async Task SetVal(string ip, string key, bool val) + { + try + { + using (var siemensTcpNet = new SiemensS7Net(SiemensPLCS.S200Smart, ip) { ConnectTimeOut = 5000 }) + { + var con = siemensTcpNet.ConnectServer(); + if (con.IsSuccess) + { + var result = await siemensTcpNet.WriteAsync(key, val); + Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm ss")}" + + $"--- 连接plc成功..{ip},写key:{key},value:{val},是否写入成功:{result.IsSuccess}"); + await siemensTcpNet.ConnectCloseAsync(); + return result.IsSuccess; + } + } + } + catch (Exception ex) + { + + Console.WriteLine($"连接plc失败..{ip},msg:{ex.Message}"); + } + return false; + } + /// + /// GetVal + /// + /// + /// + /// + /// + public async Task GetVal(string ip, string key) + { + try + { + using (var siemensTcpNet = new SiemensS7Net(SiemensPLCS.S200Smart, ip) { ConnectTimeOut = 5000 }) + { + var con = siemensTcpNet.ConnectServer(); + if (con.IsSuccess) + { + var result = await siemensTcpNet.ReadBoolAsync(key); + Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm ss")}" + + $"连接plc成功..{ip},GetVal:{key},value:{result.Content}"); + await siemensTcpNet.ConnectCloseAsync(); + return result.Content; + } + } + } + catch (Exception ex) + { + + Console.WriteLine($"连接plc失败..{ip},msg:{ex.Message}"); + } + return false; + } + public async Task GetAngleVal(string ip, string key) + { + try + { + using (var siemensTcpNet = new SiemensS7Net(SiemensPLCS.S200Smart, ip) { ConnectTimeOut = 2000 }) + { + var con = siemensTcpNet.ConnectServer(); + if (con.IsSuccess) + { + var uint_M100 = await siemensTcpNet.ReadUInt32Async(key); + Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm ss")}" + + $"连接plc成功..{ip},GetVal:{key},value:{uint_M100.Content }"); + await siemensTcpNet.ConnectCloseAsync(); + return (uint_M100.Content / 100).ToString(); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"连接plc失败..{ip},msg:{ex.Message}"); + } + return ""; + } + /// + /// 俯仰角度 + /// + /// + /// + /// + public async Task GetAngleVal1(string ip, string key) + { + try + { + using (var siemensTcpNet = new SiemensS7Net(SiemensPLCS.S200Smart, ip) { ConnectTimeOut = 2000 }) + { + string result = string.Empty; + var con = siemensTcpNet.ConnectServer(); + if (con.IsSuccess) + { + //var int_16 = await siemensTcpNet.ReadInt16Async(key); + //var ushort_M100 = await siemensTcpNet.ReadUInt16Async(key); + //var double_M100 = await siemensTcpNet.ReadDoubleAsync(key); + //var float_M100 = await siemensTcpNet.ReadFloatAsync(key); + if (key == "VD4030") + { + var uint_M100 = await siemensTcpNet.ReadInt32Async(key); + result = (uint_M100.Content / 10.0).ToString(); + } + if (key == "VW4034") + { + var ushort_M100 = await siemensTcpNet.ReadUInt16Async(key); + result = (ushort_M100.Content / 100.0).ToString(); + } + + Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm ss")}" + + $"连接plc成功..{ip},GetVal:{key},value:{result }"); + await siemensTcpNet.ConnectCloseAsync(); + return result; + } + } + } + catch (Exception ex) + { + Console.WriteLine($"连接plc失败..{ip},msg:{ex.Message}"); + } + return ""; + } + + public async Task read(string ip, string key) + { + try + { + using (var siemensTcpNet = new SiemensS7Net(SiemensPLCS.S200Smart, ip) { ConnectTimeOut = 5000 }) + { + var con = siemensTcpNet.ConnectServer(); + if (con.IsSuccess) + { + var result = await siemensTcpNet.ReadUInt16Async(key); + Console.WriteLine($"连接plc成功..{ip},读取key:{key},value{result.Content}"); + return result.Content; + } + + } + } + catch (Exception ex) + { + + Console.WriteLine($"连接plc失败..{ip},msg:{ex.Message}"); + } + return false; + } + } +} diff --git a/Command/Extension/PlcHelper2.cs b/Command/Extension/PlcHelper2.cs new file mode 100644 index 0000000..6cba0ad --- /dev/null +++ b/Command/Extension/PlcHelper2.cs @@ -0,0 +1,138 @@ +using Sharp7; +using Sharp7.Rx; +using Sharp7.Rx.Enums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Disposables; +using System.Reactive.Linq; +using System.Reactive.Threading.Tasks; +using System.Threading.Tasks; + +namespace LangGuan.Command.Extension +{ + public class PlcHelper2 + { + + public PlcHelper2() { } + /// + /// 设定设备值 + /// + /// + /// + /// + /// + public async Task startDevice(string ip, string key, Int16 val) + { + try + { + using (var disposables = new CompositeDisposable()) + { + Console.WriteLine($"开始连接设备,ip:{ip},"); + // create a new PLC + var plc = new Sharp7Plc(ip, 0, 1); + disposables.Add(plc); + // initialize the plc + await plc.InitializeAsync(); + var t = await plc.ConnectionState.FirstAsync(c => c == ConnectionState.Connected).ToTask(); + await plc.SetValue(key, val); // set a bit + var result = await plc.GetValue(key); + Console.WriteLine($"监控写入结果:----- {result}"); + Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm ss")}----plc连接状态:{t}"); + // Console.WriteLine($"plc连接状态:{plc.ConnectionState.FirstAsync(c => c == ConnectionState.Connected).Any()}"); + // await plc.SetValue("DB2.DBX0.4", true); // set a bit + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + public async Task startDevice502(string ip, string key, Int16 val) + { + try + { + using (var disposables = new CompositeDisposable()) + { + Console.WriteLine($"502开始连接设备,ip:{ip},"); + // create a new PLC + var plc = new Sharp7Plc(ip, 0, 1,502); + disposables.Add(plc); + // initialize the plc + await plc.InitializeAsync(); + var t = await plc.ConnectionState.FirstAsync(c => c == ConnectionState.Connected).ToTask(); + await plc.SetValue(key, val); // set a bit + var result = await plc.GetValue(key); + Console.WriteLine($"502监控写入结果:----- {result}"); + Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm ss")}--502--plc连接状态:{t}"); + // Console.WriteLine($"plc连接状态:{plc.ConnectionState.FirstAsync(c => c == ConnectionState.Connected).Any()}"); + // await plc.SetValue("DB2.DBX0.4", true); // set a bit + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + public async Task SetVal(string ip, string key, int val) + { + using (var disposables = new CompositeDisposable()) + { + // create a new PLC + var plc = new Sharp7Plc(ip, 0, 2); + disposables.Add(plc); + + // initialize the plc + await plc.InitializeAsync(); + + //wait for the plc to get connected + await plc.ConnectionState + .FirstAsync(c => c == ConnectionState.Connected) + .ToTask(); + + // await plc.SetValue("DB2.DBX0.4", true); // set a bit + await plc.SetValue(key, val); // set a bit + // var bit = await plc.GetValue("DB2.int4"); // get a bit + + // create a nofication for data change in the plc + //var notification = plc.CreateNotification("DB1.DBX0.2", TransmissionMode.OnChange, TimeSpan.FromMilliseconds(100)) + // .Where(b => b) //select rising edge + // .Do(_ => doStuff()) + // .Subscribe(); + //disposables.Add(notification); + + //wait for enter before ending the program + // Console.ReadLine(); + + } + } + /// + /// 取值 + /// + /// + /// + /// + /// + public async Task GetVal(string ip, string key) + { + using (var disposables = new CompositeDisposable()) + { + // create a new PLC + var plc = new Sharp7Plc(ip, 0, 2); + disposables.Add(plc); + + // initialize the plc + await plc.InitializeAsync(); + + //wait for the plc to get connected + await plc.ConnectionState + .FirstAsync(c => c == ConnectionState.Connected) + .ToTask(); + + // await plc.SetValue("DB2.DBX0.4", true); // set a bit + var bit = await plc.GetValue(key); // get a bit + return bit; + } + } + } +} diff --git a/Command/Extension/SocketExtension.cs b/Command/Extension/SocketExtension.cs new file mode 100644 index 0000000..b06d8c0 --- /dev/null +++ b/Command/Extension/SocketExtension.cs @@ -0,0 +1,30 @@ +using LangGuan.Services; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Extension +{ + /// + /// + /// + public static class SocketExtension + { + /// + /// + /// + /// + public static void AddSocketService(this IServiceCollection services) + { + // services.AddSingleton(); + services.AddScoped(); + services.AddScoped(); + + IServiceProvider serviceProvider = services.BuildServiceProvider(); + _ = serviceProvider.GetService().Start(); + serviceProvider.GetService().CreatTask(); + } + } +} diff --git a/Command/Model/ApiResult.cs b/Command/Model/ApiResult.cs new file mode 100644 index 0000000..a913c31 --- /dev/null +++ b/Command/Model/ApiResult.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model +{ + /// + /// Api返回结果 + /// + public class ApiResult + { + /// + /// code=0成功。1失败 + /// + public int code { get; set; } + /// + /// 结果 + /// + public object data { get; set; } + /// + /// 消息 + /// + public string msg { get; set; } + } +} diff --git a/Command/Model/BaseModel.cs b/Command/Model/BaseModel.cs new file mode 100644 index 0000000..ce0909e --- /dev/null +++ b/Command/Model/BaseModel.cs @@ -0,0 +1,44 @@ +using MongoDB.Bson; +using MongoDB.Bson.Serialization.Attributes; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model +{ + /// + /// base model + /// + public class BaseModel + { + /// + /// //标记主键 + /// + [BsonId] + [BsonRepresentation(BsonType.ObjectId)] //参数类型 , 无需赋值 + public string Id { get; set; } + + /// + /// //指明数据库中字段名为CreateDateTime + /// + [BsonElement(nameof(CreateDateTime))] //指明数据库中字段名为CreateDateTime + + public DateTime CreateDateTime { get; set; } + + /// + /// 标记删除 + /// + //[BsonElement(nameof(IsDelete))] + public bool IsDelete { get; set; } + + /// + /// basemodel + /// + public BaseModel() + { + CreateDateTime = DateTime.Now; + IsDelete = false; + } + } +} diff --git a/Command/Model/EntityModel/Alert.cs b/Command/Model/EntityModel/Alert.cs new file mode 100644 index 0000000..544c63f --- /dev/null +++ b/Command/Model/EntityModel/Alert.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model.EntityModel +{ + /// + /// 报警 + /// + public class Alert : BaseModel + { + /// + /// deviceId + /// + public string deviceId { get; set; } + /// + /// 别名 + /// + public string NickName { get; set; } + /// + /// 内容 + /// + public string content { get; set; } + } +} diff --git a/Command/Model/EntityModel/Device.cs b/Command/Model/EntityModel/Device.cs new file mode 100644 index 0000000..bb1a413 --- /dev/null +++ b/Command/Model/EntityModel/Device.cs @@ -0,0 +1,51 @@ +using MongoDB.Bson; +using MongoDB.Bson.Serialization.Attributes; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model.EntityModel +{ + /// + /// 设备信息 + /// + public class Device : BaseModel + { + /// + /// deviceIp + /// + public string deviceIp { get; set; } + /// + /// 设备标识 + /// + public string deviceId { get; set; } + [BsonRepresentation(BsonType.String)] + /// + /// 经 + /// + public string lng { get; set; } + [BsonRepresentation(BsonType.String)] + /// + /// 续 + /// + public string lat { get; set; } + /// + /// 别名 + /// + public string NickName { get; set; } + /// + /// 角度 + /// + public double angle { get; set; } + /// + /// 状态 0,离线,1在线 + /// + public int state { get; set; } + /// + /// 是否分配组 + /// + public bool InGroup { get; set; } + + } +} diff --git a/Command/Model/EntityModel/DeviceUsed.cs b/Command/Model/EntityModel/DeviceUsed.cs new file mode 100644 index 0000000..a9c67f0 --- /dev/null +++ b/Command/Model/EntityModel/DeviceUsed.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model.EntityModel +{ + public class DeviceUsed : BaseModel + { + public string DeviceId { get; set; } + public DateTime Start { get; set; } + public DateTime End { get; set; } + + public double Power { get; set; } + public double Water { get; set; } + } +} diff --git a/Command/Model/EntityModel/Employee.cs b/Command/Model/EntityModel/Employee.cs new file mode 100644 index 0000000..53f829f --- /dev/null +++ b/Command/Model/EntityModel/Employee.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model.EntityModel +{ + /// + /// + /// + public class Employee : BaseModel + { + /// + /// 登陆名 + /// + public string Account { get; set; } + /// + /// pwd + /// + public string Pwd { get; set; } + /// + /// 别名 + /// + public string NickName { get; set; } + } +} diff --git a/Command/Model/EntityModel/Group.cs b/Command/Model/EntityModel/Group.cs new file mode 100644 index 0000000..774f034 --- /dev/null +++ b/Command/Model/EntityModel/Group.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model.EntityModel +{ + /// + /// + /// + public class Group : BaseModel + { + /// + /// 分组名称 + /// + public string GroupName { get; set; } + /// + /// 描述 + /// + public string Description { get; set; } + /// + /// 设备列表 + /// + public IEnumerable DeviceIds { get; set; } + } +} diff --git a/Command/Model/EntityModel/HJ212.cs b/Command/Model/EntityModel/HJ212.cs new file mode 100644 index 0000000..c02b03c --- /dev/null +++ b/Command/Model/EntityModel/HJ212.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model.EntityModel +{ + /// + /// + /// + public class HJ212 : BaseModel + { + /// + /// 设备ID + /// + public string deviceId { get; set; } + /// + /// PM2.5浓度 + /// + public double a34004 { get; set; } + /// + /// PM10浓度 + /// + public double a34002 { get; set; } + /// + /// TSP浓度 + /// + public double a34001 { get; set; } + /// + /// 温度 + /// + public double a01001 { get; set; } + /// + /// 湿度 + /// + public double a01002 { get; set; } + /// + /// 大气压 + /// + public double a01006 { get; set; } + /// + /// 风速 + /// + public double a01007 { get; set; } + /// + /// 风向 + /// + public double a01008 { get; set; } + + } +} diff --git a/Command/Model/EntityModel/Plan.cs b/Command/Model/EntityModel/Plan.cs new file mode 100644 index 0000000..143f0e0 --- /dev/null +++ b/Command/Model/EntityModel/Plan.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model.EntityModel +{ + public class Plan : BaseModel + { + public string name { get; set; } + public string description { get; set; } + /// + /// 组列表 + /// + public IEnumerable groups { get; set; } + /// + /// 设备列表 + /// + public IEnumerable deviceIds { get; set; } + /// + /// 执行计划 + /// + public string cron { get; set; } + /// + /// 执行时长 + /// + public int execution { get; set; } + /// + /// 是否启用 + /// + public bool disable { get; set; } + } +} diff --git a/Command/Model/EntityModel/Radar.cs b/Command/Model/EntityModel/Radar.cs new file mode 100644 index 0000000..79b36e5 --- /dev/null +++ b/Command/Model/EntityModel/Radar.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model.EntityModel +{ + /// + /// 雷达数据 + /// + public class Radar : BaseModel + { + /// + ///设备id + /// + public string deviceId { get; set; } + /// + ///设备id + /// + public string deviceIp { get; set; } + /// + /// 采集时间 + /// + public DateTime AcqTime { get; set; } + /// + /// 曝光时间 + /// + public int ExposureTime { get; set; } + /// + /// 系统盲区 + /// + public double SystemBlind { get; set; } + /// + /// 探测距离 + /// + public double DetectRange { get; set; } + /// + /// 数据点个数 + /// + public double DataPointNum { get; set; } + /// + /// ScanAngle + /// + public IEnumerable> ScanAngle { get; set; } + + } + /// + /// + /// + public class RadarItems : BaseModel + { + /// + /// 父ID + /// + public string pid { get; set; } + /// + /// 结果 + /// + public IEnumerable Signal; + } + /// + /// + /// + public class RadarView + { + /// + ///设备id + /// + public string deviceId { get; set; } + /// + /// + /// + public string deviceIp { get; set; } + /// + /// 采集时间 + /// + public DateTime AcqTime { get; set; } + /// + /// 曝光时间 + /// + public int ExposureTime { get; set; } + /// + /// 系统盲区 + /// + public double SystemBlind { get; set; } + /// + /// 探测距离 + /// + public double DetectRange { get; set; } + /// + /// 数据点个数 + /// + public double DataPointNum { get; set; } + /// + /// ScanAngle + /// + public IEnumerable> ScanAngle { get; set; } + /// + /// Signal + /// + public IEnumerable> Signal { get; set; } + } +} diff --git a/Command/Model/EntityModel/Video.cs b/Command/Model/EntityModel/Video.cs new file mode 100644 index 0000000..bcb8c46 --- /dev/null +++ b/Command/Model/EntityModel/Video.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model.EntityModel +{ + /// + /// 视频 + /// + public class Video : BaseModel + { + /// + /// 组名 + /// + public string GroupName { get; set; } + /// + /// 视频源 + /// + public List Url { get; set; } + } +} diff --git a/Command/Model/ExportModel.cs b/Command/Model/ExportModel.cs new file mode 100644 index 0000000..55a77c0 --- /dev/null +++ b/Command/Model/ExportModel.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model +{ + /// + /// 导出 + /// + public class ExportModel + { + /// + /// 设备ID + /// + public string deviceId { get; set; } + /// + /// PM2.5浓度 + /// + public double a34004 { get; set; } + /// + /// PM10浓度 + /// + public double a34002 { get; set; } + /// + /// TSP浓度 + /// + public double a34001 { get; set; } + /// + /// 温度 + /// + public double a01001 { get; set; } + /// + /// 湿度 + /// + public double a01002 { get; set; } + /// + /// 大气压 + /// + public double a01006 { get; set; } + /// + /// 风速 + /// + public double a01007 { get; set; } + /// + /// 风向 + /// + public double a01008 { get; set; } + /// + /// 时间 + /// + public string createtime { get; set; } + } +} diff --git a/Command/Model/GroupDevice.cs b/Command/Model/GroupDevice.cs new file mode 100644 index 0000000..c66e249 --- /dev/null +++ b/Command/Model/GroupDevice.cs @@ -0,0 +1,21 @@ +using LangGuan.Command.Model.EntityModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model +{ + public class GroupDevice + { + /// + /// 分组名称 + /// + public string GroupName { get; set; } + /// + /// 描述 + /// + public string Description { get; set; } + public List items { get; set; } + } +} diff --git a/Command/Model/Paging.cs b/Command/Model/Paging.cs new file mode 100644 index 0000000..3a1a54f --- /dev/null +++ b/Command/Model/Paging.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model +{ + /// + /// 分页数据 + /// + public class Paging + { + /// + /// Gets or sets CurrentPageIndex. + /// + public int CurrentPageIndex { get; set; } + + /// + /// Gets or sets PageCount. + /// + public int Total { get; set; } + /// + /// data + /// + public List Items { get; set; } + } + /// + /// 分页参数 + /// + public class RqeustPaging + { + /// + /// Gets or sets CurrentPageIndex. + /// + public int current { get; set; } = 1; + + /// + /// Gets or sets PageCount. + /// + public int pageSize { get; set; } = 10; + } +} diff --git a/Command/Model/RequestModel/AutoReport.cs b/Command/Model/RequestModel/AutoReport.cs new file mode 100644 index 0000000..b9c5e1c --- /dev/null +++ b/Command/Model/RequestModel/AutoReport.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model.RequestModel +{ + /// + /// 条件 + /// + public class AutoReport + { + /// + /// 开始 + /// + public DateTime? begin { get; set; } + /// + /// 结束 + /// + public DateTime? end { get; set; } + /// + /// PM2.5浓度 + /// + public double a34004 { get; set; } + /// + /// PM10浓度 + /// + public double a34002 { get; set; } + /// + /// TSP浓度 + /// + public double a34001 { get; set; } + } +} diff --git a/Command/Model/RequestModel/RequestLogin.cs b/Command/Model/RequestModel/RequestLogin.cs new file mode 100644 index 0000000..933102a --- /dev/null +++ b/Command/Model/RequestModel/RequestLogin.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model.RequestModel +{ + /// + /// 登陆 + /// + public class RequestLogin + { + /// + /// Account + /// + public string Account { get; set; } + /// + /// Pwd + /// + public string Pwd { get; set; } + } +} diff --git a/Command/Model/RequestModel/RequestUpdateAccount.cs b/Command/Model/RequestModel/RequestUpdateAccount.cs new file mode 100644 index 0000000..d2be58e --- /dev/null +++ b/Command/Model/RequestModel/RequestUpdateAccount.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model.RequestModel +{ + /// + /// + /// + public class RequestUpdateAccount + { + /// + /// Account + /// + public string Account { get; set; } + /// + /// Pwd + /// + public string Pwd { get; set; } + /// + /// NewPwd + /// + public string NewPwd { get; set; } + } +} diff --git a/Command/Model/SocketModel.cs b/Command/Model/SocketModel.cs new file mode 100644 index 0000000..d6eb693 --- /dev/null +++ b/Command/Model/SocketModel.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model +{ + /// + /// scoket + /// + public class SocketModel + { + /// + /// 缓冲器 + /// + private byte[] result = new byte[1024]; + /// + /// 最大连接数 + /// + private int maxClientCount; + /// + /// 服务IP地址 + /// + private string ip; + /// + /// 服务端口号 + /// + private int port; + // 编码 + // private string code; + /// + /// 客户端列表 + /// + private List ClientSockets; + /// + /// IP终端 + /// + private IPEndPoint ipEndPoint; + /// + /// 服务端Socket + /// + private Socket ServerSocket; + /// + /// 当前客户端Socket + /// + private Socket ClientSocket; + + } +} diff --git a/Command/Model/columnView.cs b/Command/Model/columnView.cs new file mode 100644 index 0000000..a080728 --- /dev/null +++ b/Command/Model/columnView.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Command.Model +{ + + /// + /// + /// + public class columnView + { + /// + /// + /// + public string hour { get; set; } + /// + /// a34004=PM2.5浓度,a34002=PM10,a34001=tsp浓度 + /// + public string type { get; set; } + public double value { get; set; } + } +} diff --git a/Configuration/SwaggerConfigureOptions.cs b/Configuration/SwaggerConfigureOptions.cs new file mode 100644 index 0000000..54141f4 --- /dev/null +++ b/Configuration/SwaggerConfigureOptions.cs @@ -0,0 +1,41 @@ +using Microsoft.AspNetCore.Mvc.ApiExplorer; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Swashbuckle.AspNetCore.SwaggerGen; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Configuration +{ + /// + /// 版本控制 + /// + public class SwaggerConfigureOptions : IConfigureOptions + { + private readonly IApiVersionDescriptionProvider _provider; + + /// + /// provider + /// + /// + public SwaggerConfigureOptions(IApiVersionDescriptionProvider provider) => _provider = provider; + + /// + /// config + /// + /// + public void Configure(SwaggerGenOptions options) + { + foreach (var desc in _provider.ApiVersionDescriptions) + { + options.SwaggerDoc(desc.GroupName, new Microsoft.OpenApi.Models.OpenApiInfo + { + Title = "LangGuan Api", + Version = desc.ApiVersion.ToString(), + }); + } + } + } +} diff --git a/Controllers/AlertController.cs b/Controllers/AlertController.cs new file mode 100644 index 0000000..29d9af3 --- /dev/null +++ b/Controllers/AlertController.cs @@ -0,0 +1,38 @@ +using LangGuan.Command.Model; +using LangGuan.Services; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Controllers +{ + [ApiVersion("1.0")] + [Route("api/[controller]/v{version:apiVersion}")] + [ApiController] + public class AlertController : ControllerBase + { + private AlertService _alertService; + /// + /// + /// + /// + public AlertController(AlertService alertService) + { + _alertService = alertService; + } + /// + /// 列表 + /// + /// + /// + [HttpGet("list")] + public async Task list([FromQuery] RqeustPaging request) + { + var result = await _alertService.GetList(request); + return Ok(result); + } + } +} diff --git a/Controllers/DataController.cs b/Controllers/DataController.cs new file mode 100644 index 0000000..a3c2302 --- /dev/null +++ b/Controllers/DataController.cs @@ -0,0 +1,88 @@ +using LangGuan.Command.Model; +using LangGuan.Command.Model.RequestModel; +using LangGuan.Services; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; + +namespace LangGuan.Controllers +{ + /// + /// + /// + [ApiVersion("1.0")] + [Route("api/[controller]/v{version:apiVersion}")] + [ApiController] + public class DataController : ControllerBase + { + + private Hj212Service _hj212Service; + /// + /// + /// + /// + public DataController(Hj212Service hj212Service) + { + _hj212Service = hj212Service; + } + /// + /// 导出 + /// + /// + [HttpGet("export")] + public async Task export(DateTime start, DateTime end) + { + start = start > DateTime.Now ? DateTime.Now.AddDays(-1) : start; + end = end > DateTime.Now ? DateTime.Now : end; + var resutl = await _hj212Service.Export(start, end); + return File(resutl, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "环保数据.xlsx"); + } + /// + /// 列表数据 + /// + /// + [HttpGet("list")] + public async Task list(DateTime start, DateTime end, [FromQuery] RqeustPaging request) + { + var result = await _hj212Service.GetPageData(start, end, request); + return Ok(result); + } + /// + ///实时监测 + /// + /// + [HttpGet("realtime")] + public async Task realtime() + { + var result = await _hj212Service.Realtime(); + return Ok(result); + } + + /// + ///自动报表导出 + /// + /// + [HttpGet("autoreport")] + public async Task autoreport([FromQuery] AutoReport request) + { + var result = await _hj212Service.autoReport(request); + string fileName = $"{request.begin.Value.ToString("yyyy-MM-dd")}-{request.end.Value.ToString("yyyy-MM-dd")}污染数据.xlsx"; + return File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName); + } + /// + ///自动报表结果 + /// + /// + [HttpGet("autoReportResult")] + public async Task autoReportResult([FromQuery] AutoReport request) + { + var result = await _hj212Service.autoReportResult(request); + return Ok(result); + } + } +} diff --git a/Controllers/DeviceController.cs b/Controllers/DeviceController.cs new file mode 100644 index 0000000..844f0b7 --- /dev/null +++ b/Controllers/DeviceController.cs @@ -0,0 +1,222 @@ +using CronExpressionDescriptor; +using LangGuan.Command.Model; +using LangGuan.Command.Model.EntityModel; +using LangGuan.Services; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Controllers +{ + /// + /// + /// + [ApiVersion("1.0")] + [Route("api/[controller]/v{version:apiVersion}")] + [ApiController] + public class DeviceController : ControllerBase + { + private DeviceSerive _deviceSerive; + private PlanService _planService; + /// + /// + /// + /// + public DeviceController(DeviceSerive deviceSerive, PlanService planService) + { + _deviceSerive = deviceSerive; + _planService = planService; + } + /// + /// Add + /// + /// + /// + [HttpPost] + public async Task Add(Device input) + { + var result = await _deviceSerive.CreateAsync(input); + return Ok(new ApiResult() { code = 0 }); + } + /// + /// 删除 + /// + /// + /// + [HttpPost("remove")] + public async Task remove(IEnumerable ids) + { + foreach (var item in ids) + { + await _deviceSerive.RemoveAsync(item); + } + return Ok(new ApiResult() { code = 0 }); + } + /// + /// 列表 + /// + /// + /// + [HttpGet("list")] + public async Task list([FromQuery] RqeustPaging request) + { + var result = await _deviceSerive.GetList(request); + return Ok(result); + } + /// + /// 更新 + /// + /// + /// + [HttpPost("update")] + public async Task update(Device request) + { + var result = await _deviceSerive.Update(request); + return Ok(result); + } + /// + /// + /// + /// + [HttpGet("GetListByGroupState")] + public async Task GetListByGroupState(bool Ingroup) + { + var result = await _deviceSerive.GetlistByGroupState(Ingroup); + return Ok(result); + } + /// + /// 设备角度调整 + /// + /// + /// + [HttpPost("SetVal")] + public async Task SetVal(KeyValuePair input) + { + return Ok(new ApiResult() { code = 0, msg = "" }); + } + /// + /// 启动 + /// + /// + /// true,摇摆,false,定点 + /// + [HttpGet("start")] + public async Task start(string id, bool point = false) + { + var result = await _deviceSerive.startdevice(id, point); + return Ok(new ApiResult() { code = 0, msg = "", data = result }); + } + [HttpGet("stop")] + public async Task stop(string id) + { + var result = await _deviceSerive.stopDevice(id); + return Ok(new ApiResult() { code = 0, msg = "", data = result }); + } + /// + /// 判断设备是否在计划中 + /// + /// + /// + [HttpGet("existPlan")] + public async Task existPlan(string id) + { + var result = await _planService.existsPlan(id); + return Ok(new ApiResult() { code = 0, msg = "", data = result }); + } + [HttpGet("getval")] + public async Task getval(string id) + { + var result = await _deviceSerive.getval(id); + return Ok(new ApiResult() { code = 0, msg = "", data = result }); + } + [HttpGet("setval")] + public async Task setval(string id, bool val) + { + var result = await _deviceSerive.setval(id, val); + return Ok(new ApiResult() { code = 0, msg = "" }); + } + [HttpGet("readkey")] + public async Task readkey(string ip, string key) + { + var result = await _deviceSerive.readkey(ip, key); + return Ok(new ApiResult() { code = 0, msg = "", data = result }); + } + [HttpGet("writekey")] + public async Task writekey(string ip, string key, int val) + { + await _deviceSerive.wrirekey(ip, key, val); + return Ok(new ApiResult() { code = 0, msg = "" }); + } + + /// + /// 设置上下俯仰,t=1上,t=2下,val=true,开始,false,停止 + /// + /// + /// 1上,2下 + /// + /// + [HttpGet("upordown")] + public async Task upordown(string id, int t = 1, bool val = true) + { + await _deviceSerive.setUporDown(id, t, val); + return Ok(new ApiResult() { code = 0, msg = "" }); + } + /// + /// 归零 + /// + /// + /// + /// + [HttpGet("zero")] + public async Task Zero(string id, bool val = true) + { + await _deviceSerive.Zero(id, val); + return Ok(new ApiResult() { code = 0, msg = "" }); + } + /// + /// 获取上下角度 + /// + /// + /// + [HttpGet("getupordown")] + public async Task getupordown(string id) + { + var result = await _deviceSerive.GetUpOrDown(id); + return Ok(new ApiResult() { code = 0, msg = "", data = result }); + } + /// + /// 左右,跟上下一样 + /// + /// + /// + /// + /// + [HttpGet("leftorright")] + public async Task leftorright(string id, int t = 1, bool val = true) + { + await _deviceSerive.setLeftorRight(id, t, val); + return Ok(new ApiResult() { code = 0, msg = "" }); + } + /// + /// 获取角度 + /// + /// + /// + [HttpGet("getleftorright")] + public async Task getleftorright(string id) + { + var result = await _deviceSerive.GetLeftOrRight(id); + return Ok(new ApiResult() { code = 0, msg = "", data = result }); + } + + [HttpGet("cron")] + public async Task cron(string cron) + { + var result = ExpressionDescriptor.GetDescription(cron, new Options() { Locale = "zh-CN" }); + return Ok(new ApiResult() { code = 0, msg = "", data = result }); + } + } +} diff --git a/Controllers/DeviceUsedController.cs b/Controllers/DeviceUsedController.cs new file mode 100644 index 0000000..11ac63f --- /dev/null +++ b/Controllers/DeviceUsedController.cs @@ -0,0 +1,34 @@ +using LangGuan.Command.Model.EntityModel; +using LangGuan.Services; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Controllers +{ + [ApiVersion("1.0")] + [Route("api/[controller]/v{version:apiVersion}")] + [ApiController] + public class DeviceUsedController : ControllerBase + { + private DeviceUsedService _deviceUsedService; + public DeviceUsedController(DeviceUsedService deviceUsedService) + { + _deviceUsedService = deviceUsedService; + } + + /// + /// 测试数据 + /// + /// + [HttpPost] + public async Task Test(DeviceUsed input) + { + await _deviceUsedService.AddDeviceUsed(input); + return Ok(); + } + } +} diff --git a/Controllers/EmployeeController.cs b/Controllers/EmployeeController.cs new file mode 100644 index 0000000..0004c80 --- /dev/null +++ b/Controllers/EmployeeController.cs @@ -0,0 +1,108 @@ +using LangGuan.Command.Model; +using LangGuan.Command.Model.EntityModel; +using LangGuan.Command.Model.RequestModel; +using LangGuan.Services; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; + +namespace LangGuan.Controllers +{ + /// + /// + /// + [ApiVersion("1.0")] + [Route("api/[controller]/v{version:apiVersion}")] + [ApiController] + public class EmployeeController : ControllerBase + { + private readonly ILogger _logger; + private readonly EmployeeService _employee; + /// + /// + /// + /// + public EmployeeController(EmployeeService employee) + { + _employee = employee; + } + /// + /// 登录 + /// + /// + /// + [HttpPost("login")] + public async Task Login(RequestLogin request) + { + request.Pwd = ToMD5(request.Pwd); + var result = await _employee.Login(request.Account, request.Pwd); + return Ok(result); + } + /// + /// 列表查询 + /// + /// + /// + [HttpGet("list")] + public async Task Check([FromQuery] RqeustPaging request) + { + var result = await _employee.GetList(request); + return Ok(result); + } + /// + /// 新加 + /// + /// + /// + [HttpPost("add")] + public async Task Add(Employee request) + { + var result = await _employee.Add(request.Account, ToMD5(request.Pwd), request.NickName); + return Ok(result); + } + /// + /// 修改密码 + /// + /// + /// + [HttpPost("Update")] + public async Task Update(RequestUpdateAccount request) + { + request.Pwd = ToMD5(request.Pwd); + request.NewPwd = ToMD5(request.NewPwd); + var result = await _employee.Update(request.Account, request.Pwd, request.NewPwd); + return Ok(result); + } + /// + /// 删除 + /// + /// + /// + [HttpDelete("remove")] + public async Task remove(IEnumerable ids) + { + if (ids.Any()) + { + foreach (var item in ids) + { + await _employee.RemoveAsync(item); + } + } + return Ok(new ApiResult() { code = 0, msg = "" }); + } + + string ToMD5(string strs) + { + MD5 md5 = new MD5CryptoServiceProvider(); + byte[] bytes = Encoding.Default.GetBytes(strs);//将要加密的字符串转换为字节数组 + byte[] encryptdata = md5.ComputeHash(bytes);//将字符串加密后也转换为字符数组 + return Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为加密字符串 + } + } +} diff --git a/Controllers/GroupController.cs b/Controllers/GroupController.cs new file mode 100644 index 0000000..10b59ec --- /dev/null +++ b/Controllers/GroupController.cs @@ -0,0 +1,79 @@ +using LangGuan.Command.Model; +using LangGuan.Command.Model.EntityModel; +using LangGuan.Services; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Controllers +{ + [ApiVersion("1.0")] + [Route("api/[controller]/v{version:apiVersion}")] + [ApiController] + public class GroupController : ControllerBase + { + private GroupService _serive; + public GroupController(GroupService groupService) + { + _serive = groupService; + } + /// + /// 列表 + /// + /// + /// + [HttpGet("list")] + public async Task list([FromQuery] RqeustPaging request) + { + var result = await _serive.GetList(request); + return Ok(result); + } + /// + /// 取单条 + /// + /// + /// + [HttpGet] + public async Task FindOne(string Id) + { + var result = await _serive.FindOne(Id); + return Ok(result); + } + /// + /// 更新 + /// + /// + /// + [HttpPost("update")] + public async Task update(Group request) + { + var result = await _serive.update(request); + return Ok(result); + } + /// + /// 新加 + /// + /// + /// + [HttpPost("add")] + public async Task add(Group input) + { + var result = await _serive.Add(input); + return Ok(result); + } + /// + /// 删除 + /// + /// + /// + [HttpDelete("remove")] + public async Task remove(IEnumerable ids) + { + var result = await _serive.remove(ids); + return Ok(result); + } + } +} diff --git a/Controllers/HomeController.cs b/Controllers/HomeController.cs new file mode 100644 index 0000000..d05a4d2 --- /dev/null +++ b/Controllers/HomeController.cs @@ -0,0 +1,101 @@ +using LangGuan.Command.Model; +using LangGuan.Services; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +namespace LangGuan.Controllers +{ + /// + /// + /// + [ApiVersion("1.0")] + [Route("api/[controller]/v{version:apiVersion}")] + [ApiController] + public class HomeController : ControllerBase + { + private readonly ILogger _logger; + private DeviceSerive _deviceSerive; + private AlertService _alertSerive; + private VideoService _videoService; + private Hj212Service _hj212Service; + private RadarService _radarService; + private readonly IMemoryCache _memoryCache; + private readonly IConfiguration _iconfig; + private readonly DeviceUsedService _deviceUsedService; + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public HomeController(ILogger logger, DeviceSerive deviceSerive, + AlertService alertService, VideoService videoService, Hj212Service hj212Service, + RadarService radarService, IMemoryCache memoryCache, IConfiguration configuration + , DeviceUsedService deviceUsedService) + { + _logger = logger; + _deviceSerive = deviceSerive; + _alertSerive = alertService; + _videoService = videoService; + _hj212Service = hj212Service; + _radarService = radarService; + _memoryCache = memoryCache; + _iconfig = configuration; + _deviceUsedService = deviceUsedService; + } + /// + /// + /// + /// + [HttpGet("view")] + public async Task view() + { + // await _deviceUsedService.UpdateDouble(); + //设备数据 + var devices = await _deviceSerive.GeAllList(); + // var devices = await _memoryCache.GetOrCreate("deviceList", async entity => + //{ + // entity.AbsoluteExpirationRelativeToNow = new TimeSpan(0, 2, 0); + // return entity.Value = await _deviceSerive.GeAllList(); + //}); + //报警 + // var alerts = await _alertSerive.GetToplist(); + //视频 + // var videos = await _videoService.GetAll(); + var deviceUsed = await _deviceUsedService.GetList(DateTime.Now.AddDays(-7), DateTime.Now.AddDays(1)); + var result = new ApiResult() + { + code = 0, + data = new + { + devices, + deviceUsed = deviceUsed, + } + }; + return Ok(result); + } + /// + /// + /// + public class columnView + { + public string hour { get; set; } + /// + /// a34004=PM2.5浓度,a34002=PM10,a34001=tsp浓度 + /// + public string type { get; set; } + public double value { get; set; } + } + } +} diff --git a/Controllers/PlanController.cs b/Controllers/PlanController.cs new file mode 100644 index 0000000..46e13c0 --- /dev/null +++ b/Controllers/PlanController.cs @@ -0,0 +1,89 @@ +using LangGuan.Command.Model; +using LangGuan.Command.Model.EntityModel; +using LangGuan.Services; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Controllers +{ + [ApiVersion("1.0")] + [Route("api/[controller]/v{version:apiVersion}")] + [ApiController] + public class PlanController : ControllerBase + { + private PlanService _planService; + public PlanController(PlanService planService) + { + _planService = planService; + } + /// + /// + /// + /// + /// + [HttpPost("add")] + public async Task add(Plan plan) + { + var result = await _planService.AddPlan(plan); + return Ok(result); + } + /// + /// 启用,禁用状态变更 + /// + /// + /// + [HttpGet("setdis")] + public async Task updatedis(string id) + { + var result = await _planService.setdis(id); + return Ok(result); + } + /// + /// 更新 + /// + /// + [HttpPost("update")] + public async Task update(Plan input) + { + var result = await _planService.updatePlan(input); + return Ok(result); + } + /// + /// remove + /// + /// + /// + [HttpDelete("remove")] + public async Task remove(IEnumerable ids) + { + var result = await _planService.remove(ids); + return Ok(result); + } + /// + /// 列表 + /// + /// + /// + [HttpGet("list")] + public async Task list([FromQuery] RqeustPaging request) + { + var result = await _planService.GetList(request); + return Ok(result); + } + /// + ///findone + /// + /// + /// + [HttpGet] + public async Task findeOne(string id) + { + var result = await _planService.findOne(id); + return Ok(result); + } + } +} diff --git a/Controllers/RadarController.cs b/Controllers/RadarController.cs new file mode 100644 index 0000000..9224e73 --- /dev/null +++ b/Controllers/RadarController.cs @@ -0,0 +1,59 @@ +using LangGuan.Command.Model.EntityModel; +using LangGuan.Services; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Controllers +{ + [ApiVersion("1.0")] + [Route("api/[controller]/v{version:apiVersion}")] + [ApiController] + public class RadarController : ControllerBase + { + private RadarService _radarService; + /// + /// + /// + /// + public RadarController(RadarService radarService) + { + _radarService = radarService; + } + /// + /// 接收客户端雷达 数据 + /// + /// + /// + [HttpPost("receive")] + public async Task receive(RadarView request) + { + if (request.DetectRange < 1 || request.DataPointNum == 0 || request.Signal.Count() < 10) + { + return BadRequest(); + } + var result = await _radarService.Add(request); + return Ok(result); + } + + /// + /// + /// + /// + /// + /// + [HttpGet("list")] + public async Task list([FromQuery] DateTime start, DateTime end) + { + //var txt = "##0190QN=20230331024430001;ST=22;CN=2011;PW=123456;MN=20220916030017;Flag=5;CP=&&DataTime=20230331024400;&&a34004-Rtd=65.7,a34004-Flag=N;a34002-Rtd=168.8,a34002-Flag=N;a34001-Rtd=211,a34001-Flag=N&&1100"; + //HJ212_2017 hj = new HJ212_2017(); + //var t = hj.DecodeData(txt); + var result = await _radarService.GetList(start, end); + return Ok(result); + } + + } +} diff --git a/Controllers/VideoController.cs b/Controllers/VideoController.cs new file mode 100644 index 0000000..4e8af5b --- /dev/null +++ b/Controllers/VideoController.cs @@ -0,0 +1,93 @@ +using LangGuan.Command.Model; +using LangGuan.Command.Model.EntityModel; +using LangGuan.Services; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Threading.Tasks; + +namespace LangGuan.Controllers +{ + [ApiVersion("1.0")] + [Route("api/[controller]/v{version:apiVersion}")] + [ApiController] + public class VideoController : ControllerBase + { + private VideoService _videoService; + /// + /// + /// + /// + public VideoController(VideoService videoService) + { + _videoService = videoService; + } + + //[HttpPost] + //public async Task SaveRecoredFile() + //{ + // if (Request.Form.Files.Any()) + // { + // var file = Request.Form.Files["video-blob"]; + + // string UploadFolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "UploadedFiles"); + // string UniqueFileName = Guid.NewGuid().ToString() + "_" + file.FileName + ".webm"; + // string UploadPath = Path.Combine(UploadFolder, UniqueFileName); + // await file.CopyToAsync(new FileStream(UploadPath, FileMode.Create)); + // } + // return Ok(HttpStatusCode.OK); + //} + /// + /// 列表 + /// + /// + [HttpGet("list")] + public async Task list([FromQuery] RqeustPaging request) + { + var result = await _videoService.GetList(request); + return Ok(result); + } + /// + /// 新加 + /// + /// + /// + [HttpPost("add")] + public async Task Add(Video request) + { + var result = await _videoService.Add(request); + return Ok(result); + } + /// + /// /更新 + /// + /// + [HttpPost("update")] + public async Task update(Video video) + { + var result = await _videoService.Update(video); + return Ok(result); + } + /// + /// 批量删除,传数组 + /// + /// + /// + [HttpDelete("remove")] + public async Task removoe(IEnumerable ids) + { + if (ids.Any()) + { + foreach (var item in ids) + { + await _videoService.RemoveAsync(item); + } + } + return Ok(new ApiResult() { code = 0 }); + } + } +} diff --git a/Controllers/WeatherForecastController.cs b/Controllers/WeatherForecastController.cs new file mode 100644 index 0000000..56b1c9f --- /dev/null +++ b/Controllers/WeatherForecastController.cs @@ -0,0 +1,39 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Controllers +{ + [ApiController] + [Route("[controller]")] + public class WeatherForecastController : ControllerBase + { + private static readonly string[] Summaries = new[] + { + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; + + private readonly ILogger _logger; + + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet] + public IEnumerable Get() + { + var rng = new Random(); + return Enumerable.Range(1, 5).Select(index => new WeatherForecast + { + Date = DateTime.Now.AddDays(index), + TemperatureC = rng.Next(-20, 55), + Summary = Summaries[rng.Next(Summaries.Length)] + }) + .ToArray(); + } + } +} diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..f4d309f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,21 @@ +#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. + +FROM mcr.microsoft.com/dotnet/aspnet:3.1-alpine AS base +WORKDIR /app +EXPOSE 80 + +#FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build +#WORKDIR /src +#COPY ["LangGuan.csproj", "."] +#RUN dotnet restore "./LangGuan.csproj" +COPY . . +#WORKDIR "/src/." +#RUN dotnet build "LangGuan.csproj" -c Release -o /app/build +# +#FROM build AS publish +#RUN dotnet publish "LangGuan.csproj" -c Release -o /app/publish +# +#FROM base AS final +#WORKDIR /app +#COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "LangGuan.dll"] \ No newline at end of file diff --git a/LangGuan.csproj b/LangGuan.csproj new file mode 100644 index 0000000..dc5921c --- /dev/null +++ b/LangGuan.csproj @@ -0,0 +1,48 @@ + + + + netcoreapp3.1 + Linux + . + 8c2d4e67-f295-4332-a573-9c3d12228a49 + + + + true + + + D:\work\LangGuan\LangGuan.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Always + + + + + diff --git a/LangGuan.sln b/LangGuan.sln new file mode 100644 index 0000000..4d2e3bb --- /dev/null +++ b/LangGuan.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.31112.23 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LangGuan", "LangGuan.csproj", "{DE92B294-C31C-441C-93D5-97CF1AFE8ECC}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DE92B294-C31C-441C-93D5-97CF1AFE8ECC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DE92B294-C31C-441C-93D5-97CF1AFE8ECC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DE92B294-C31C-441C-93D5-97CF1AFE8ECC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DE92B294-C31C-441C-93D5-97CF1AFE8ECC}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {EF9B30B3-F933-4EF4-A79E-3A3C7A6A3A9E} + EndGlobalSection +EndGlobal diff --git a/LangGuan.xml b/LangGuan.xml new file mode 100644 index 0000000..5085aba --- /dev/null +++ b/LangGuan.xml @@ -0,0 +1,2403 @@ + + + + LangGuan + + + + + AutoMapperConfig + + + + + + + + + + + CustomProfile + + + + + 配置构造函数,用来创建关系映射 + + + + + 写数据 + + + + + + SetVal + + + + + + + + + GetVal + + + + + + + + + 俯仰角度 + + + + + + + + 设定设备值 + + + + + + + + + 取值 + + + + + + + + + + + + + + + + + + + + Api返回结果 + + + + + code=0成功。1失败 + + + + + 结果 + + + + + 消息 + + + + + base model + + + + + //标记主键 + + + + + //指明数据库中字段名为CreateDateTime + + + + + 标记删除 + + + + + basemodel + + + + + + + + + + + + + + + a34004=PM2.5浓度,a34002=PM10,a34001=tsp浓度 + + + + + 报警 + + + + + deviceId + + + + + 别名 + + + + + 内容 + + + + + 设备信息 + + + + + deviceIp + + + + + 设备标识 + + + + + 别名 + + + + + 角度 + + + + + 状态 0,离线,1在线 + + + + + 是否分配组 + + + + + + + + + + 登陆名 + + + + + pwd + + + + + 别名 + + + + + + + + + + 分组名称 + + + + + 描述 + + + + + 设备列表 + + + + + + + + + + 设备ID + + + + + PM2.5浓度 + + + + + PM10浓度 + + + + + TSP浓度 + + + + + 温度 + + + + + 湿度 + + + + + 大气压 + + + + + 风速 + + + + + 风向 + + + + + 组列表 + + + + + 设备列表 + + + + + 执行计划 + + + + + 执行时长 + + + + + 是否启用 + + + + + 雷达数据 + + + + + 设备id + + + + + 设备id + + + + + 采集时间 + + + + + 曝光时间 + + + + + 系统盲区 + + + + + 探测距离 + + + + + 数据点个数 + + + + + ScanAngle + + + + + + + + + + 父ID + + + + + 结果 + + + + + + + + + + 设备id + + + + + + + + + + 采集时间 + + + + + 曝光时间 + + + + + 系统盲区 + + + + + 探测距离 + + + + + 数据点个数 + + + + + ScanAngle + + + + + Signal + + + + + 视频 + + + + + 组名 + + + + + 视频源 + + + + + 导出 + + + + + 设备ID + + + + + PM2.5浓度 + + + + + PM10浓度 + + + + + TSP浓度 + + + + + 温度 + + + + + 湿度 + + + + + 大气压 + + + + + 风速 + + + + + 风向 + + + + + 时间 + + + + + 分组名称 + + + + + 描述 + + + + + 分页数据 + + + + + Gets or sets CurrentPageIndex. + + + + + Gets or sets PageCount. + + + + + data + + + + + 分页参数 + + + + + Gets or sets CurrentPageIndex. + + + + + Gets or sets PageCount. + + + + + 条件 + + + + + 开始 + + + + + 结束 + + + + + PM2.5浓度 + + + + + PM10浓度 + + + + + TSP浓度 + + + + + 登陆 + + + + + Account + + + + + Pwd + + + + + + + + + + Account + + + + + Pwd + + + + + NewPwd + + + + + scoket + + + + + 缓冲器 + + + + + 最大连接数 + + + + + 服务IP地址 + + + + + 服务端口号 + + + + + 客户端列表 + + + + + IP终端 + + + + + 服务端Socket + + + + + 当前客户端Socket + + + + + 版本控制 + + + + + provider + + + + + + config + + + + + + + + + + + + 列表 + + + + + + + + + + + + + + + + + + 导出 + + + + + + 列表数据 + + + + + + 实时监测 + + + + + + 自动报表导出 + + + + + + 自动报表结果 + + + + + + + + + + + + + + + + + Add + + + + + + + 删除 + + + + + + + 列表 + + + + + + + 更新 + + + + + + + + + + + + + 设备角度调整 + + + + + + + 启动 + + + true,摇摆,false,定点 + + + + + 判断设备是否在计划中 + + + + + + + 设置上下俯仰,t=1上,t=2下,val=true,开始,false,停止 + + + 1上,2下 + + + + + + 归零 + + + + + + + + 获取上下角度 + + + + + + + 左右,跟上下一样 + + + + + + + + + 获取角度 + + + + + + + 测试数据 + + + + + + + + + + + + + + + + + 登录 + + + + + + + 列表查询 + + + + + + + 新加 + + + + + + + 修改密码 + + + + + + + 删除 + + + + + + + 列表 + + + + + + + 取单条 + + + + + + + 更新 + + + + + + + 新加 + + + + + + + 删除 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + a34004=PM2.5浓度,a34002=PM10,a34001=tsp浓度 + + + + + + + + + + + + 启用,禁用状态变更 + + + + + + + 更新 + + + + + + remove + + + + + + + 列表 + + + + + + + findone + + + + + + + + + + + + + 接收客户端雷达 数据 + + + + + + + + + + + + + + + + + + + + + 列表 + + + + + + 新加 + + + + + + + /更新 + + + + + + 批量删除,传数组 + + + + + + + 异常处理中间件 + + + + + 日志 + + + + + 构参 + + + + + + 重写 + + + + + + + 日志中间件 + + + + + 计时器 + + + + + 构建中间件 + + + + + + + task + + + + + + + 获取响应内容 + + + + + + + + + + + + + + + + + + 取前20 + + + + + + + 新加一条数据 + + + + + + + 分页数据 + + + + + + + baseservice + + + + + + 构造 + + + + + + + 获取所有 + + + + + + 获取单个 + + + + + + + 创建 + + + + + + + 更新 + + + + + + + 删除 + + + + + + 根据id删除 + + + + + + 取列表 + + + + + + 取单条 + + + + + + + 新增 + + + + + + + 新增 + + + + + + + 更新 + + + + + + + + 删除 + + + + + + + 表达式取数据 + + + + + + + filter查找 + + + + + + + filterdefinition + + + + + + + 是否存在 + + + + + + + 分页取数据 + + + + + + + + + + + + + + + + + + + + 新加设备 + + + + + + + 取状态 + + + + + + + 更新设备 + + + + + + + 更新设备组的状态 + + + + + + + + 检测是否已经在组中 + + + + + + + 分页数据 + + + + + + + 取多条数据 + + + + + + + 取全部数据 + + + + + + 更新设备状态 + + + + + + + 开启 + + 设备id + 是否定点 + + + + + 停止 + + + + + + + + + + + + + + + + 归零 + + + + + + + + + + + + + + + + + 设备角度 + + + + + + + 设备角度 + + + + + + + + + + + + + + + + + + + + + + + + 登陆 + + + + + + + + 更新密码 + + + + + + + + + 新加用户 + + + + + + + + + 列表页 + + + + + + + 新加分组 + + + + + + + 更新 + + + + + + + + + + + + + + 取单条 + + + + + + + + + + + + + + group 取全部的设备id + + + + + + + + + + + + + + + + + + + 新加数据 + + + + + + + + 最近10个小时的数据 + + + + + + + 实时的数据 + + + + + + 自动报表 + + + + + + + 计算结果 + + + + + + + 分页取数据 + + + + + + + + + 查找数据 + + + + + + + + 导出数据 + + + + + + + + 启动socket + + + + + + + + + + + + 缓冲器 + + + + + 最大连接数 + + + + + 服务IP地址 + + + + + 服务端口号 + + + + + 客户端列表 + + + + + IP终端 + + + + + 服务端Socket + + + + + 启动服务 + + + + + + 后台线程接收数据 + + + + + + 数据帧头 + + + + + 数据长度 + + + + + 数据头 + + + + + + + + + + CRC校验 + + + + + + + + + + + + 判断数据是否通过校验 + + 原始数据 + 是否通过 + + + + + + + + + + + ping service + + + + + + + + + + + + + + + + + + + + + + ping + + + + + + + 取全部可用的plan + + + + + + 更新 + + + + + + + 取单条 + + + + + + + + + + + + + + 新加plan + + + + + + + 更新 + + + + + + + + + + + + + + 取所计划中所有的设备ids + + + + + + + 判断是否在计划中 + + + + + + + 执行 + + + + + + + + + + + + + 批量新加 + + + + + + + 取结果 + + + + + + + 取单条 + + + + + + + + + + + + + + + + + + + + + + + + + + + + 新加数据 + + + + + + + 首页用图 + + + + + + + + + + + + + + + 计算圈数 + + + + + + + + 返回结果 + + + + + 角度 + + + + + 距离 + + + + + 结果 + + + + + + + + + + + + + + + + 首页取全部 + + + + + + 分页数据 + + + + + + + + + + + + + + 更新 + + + + + + + + + + + + 收到数据事件 + + + + + 发送数据事件 + + + + + + + + + + + 引发收到数据事件 + + + + + 引发发送数据事件 + + + + + + + + + + + + + 获取分包缓存 + + + + + + + + + + + 应答 + + + + + 命令编码 + + + + + 心跳包 + + + + + 工控机向上位机上传分钟数据 + + + + + 工控机向上位机上传小时数据 + + + + + 工控机向上位机上传日数据 + + + + + 工控机向上位机上传实时数据 + + + + + 上位机向工控机返回应答 + + + + + CP指令 + + + + + 数据时间信息 + + + + + 污染物信息 + + + + + 解析 + + + + + + + 序列化 + + + + + + 数据段 + + + + + 默认应答系统编码 + + + + + 请求编号 + + + yyyyMMddHHmmssZZZ 取当前系统时间, 精确到毫秒值, 用来唯一标识一次命令交互 + + + + + 系统编号 + + + + + 命令编码 + 详见附录 2 + + + + + 访问密码 + 对接时提供给各个对接站点 + + + + + 设备唯一标识 + 对接时提供给各个对接站点 + + + + + 拆分包及应答标志 + + + + + 总包数 + PNUM 指示本次通讯中总共包含的包数,注:不分包时可以没有本字段,与标志位有关 + + + + + 包号 + PNO 指示当前数据包的包号,注: 不分包时可以没有本字段,与标志位有关 + + + + + 指令 + CP=&&数据区&&( 详见表 5 ) + + + + + 解析 + + + + + + + + 序列化 + + + + + + 污染物因子编码 + + + + + 检测仪器数据标记 + + + + + 正常(有效) + 在线监控(监测)仪器仪表工作正常 + + + + + 无效 + 在线监控(监测)仪器仪表停运 + + + + + 无效 + 在线监控(监测)仪器仪表处于维护期间产生的数据 + + + + + 有效 + 手工输入的设定值 + + + + + 无效 + 在线监控(监测)仪器仪表故障 + + + + + 无效 + 在线监控(监测)仪器仪表处于校准状态 + + + + + 无效 + 在线监控(监测)仪器仪表采样数值超过测量上限 + + + + + 无效 + 在线监控(监测)仪器仪表与数采仪通讯异常 + + + + + 无效(有效数据不足) + + + 按照5分钟、1小时均值计算要求,所获取的有效数据个数不足 + + + + + 通讯包 + + + + + 默认头 + + + + + 默认尾 + + + + + 包头 + + + + + 数据段长度 + + + + + 数据段 + + + + + CRC校验码 + + + + + 包尾 + + + + + CRC16校验 + + 需要校验的字符串 + CRC16 校验码 + + + + 解析 + + + + + + + + 序列化 + + + + + + 污染物信息 + + + + + 约定的无效值 + + + + + 污染物因子编码 + + + + + 污染物实时采样数据 + + + 默认值为约定的无效值 + + + + + 污染物指定时问内平均值 + + + 默认值为约定的无效值 + + + + + 污染物指定时问内最大值 + + + 默认值为约定的无效值 + + + + + 污染物指定时问内最小值 + + + 默认值为约定的无效值 + + + + + 污染物指定时问内累计值 + + + 默认值为约定的无效值 + + + + + 检测仪器数据标记 + + + + + 回应代码集 + + + + + 执行成功 + + + + + 执行失败,但不知道原因 + + + + + 执行失败,命令请求条件错误 + + + + + 通讯超时 + + + + + 系统繁忙不能执行 + + + + + 系统时间异常 + + + + + 没有数据 + + + + + 心跳包 + + + + + 拆分包及应答标志 + + + + + 命令是否应答:1-应答,0-不应答 + + + + + 是否有数据包序号:1 - 数据包中包含包号和总包数两部分,0 - 数据包中不包含包号和总包数两部分 + + + + + 标准版本号 + 000000 表示标准 HJ/T212-2005 + 000001 表示本次标准修订版本号 + + + + + 解析 + + + + + + + 序列化 + + + + + + 获取取第index位 + + + index从0开始 + + + + + + + + 将第index位设为1 + + + index从0开始 + + + + + + + + 将第index位设为0 + + + index从0开始 + + + + + + + + 将第index位取反 + + + index从0开始 + + + + + + + diff --git a/Middleware/CustomerExceptionFilter.cs b/Middleware/CustomerExceptionFilter.cs new file mode 100644 index 0000000..a046075 --- /dev/null +++ b/Middleware/CustomerExceptionFilter.cs @@ -0,0 +1,47 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Middleware +{ + /// + /// 异常处理中间件 + /// + public class CustomerExceptionFilter : IAsyncExceptionFilter + { + /// + /// 日志 + /// + public ILogger _logger; + /// + /// 构参 + /// + /// + public CustomerExceptionFilter(ILoggerFactory loggerFactory) + { + _logger = loggerFactory.CreateLogger(); + } + /// + /// 重写 + /// + /// + /// + public Task OnExceptionAsync(ExceptionContext context) + { + if (context.ExceptionHandled == false) + { + var json = new { cdoe = -1, msg = context.Exception.Message, data = context.Exception.Data }; + context.HttpContext.Response.StatusCode = 400; + context.Result = new JsonResult(json); + } + _logger.LogError($"请求出现异常,地址:{context.HttpContext?.Request?.Path},请求方式:{context.HttpContext.Request.Method},异常信息:{context.Exception.Message}"); + //记录异常已经处理 + context.ExceptionHandled = true; + return Task.CompletedTask; + } + } +} diff --git a/Middleware/RequestLoggingMiddleware.cs b/Middleware/RequestLoggingMiddleware.cs new file mode 100644 index 0000000..99a1ca8 --- /dev/null +++ b/Middleware/RequestLoggingMiddleware.cs @@ -0,0 +1,97 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Middleware +{ + /// + /// 日志中间件 + /// + public class RequestLoggingMiddleware + { + private readonly RequestDelegate _next; + private readonly ILogger _logger; + /// + /// 计时器 + /// + private Stopwatch _stopwatch; + /// + /// 构建中间件 + /// + /// + /// + public RequestLoggingMiddleware(RequestDelegate next, ILogger logger) + { + _next = next; + _logger = logger; + } + /// + /// task + /// + /// + /// + public async Task Invoke(HttpContext context) + { + var startTime = DateTime.Now; + string arguments = string.Empty;//入参 + string result = string.Empty;//结果 + _stopwatch = new Stopwatch(); + _stopwatch.Start(); + var response = context.Response.Body; + long contentLen = context.Request.ContentLength == null ? 0 : context.Request.ContentLength.Value; + if (contentLen > 0) + { + // 启用倒带功能 + context.Request.EnableBuffering(); + // 读取请求体中所有内容 + var stream = context.Request.Body; + byte[] buffer = new byte[contentLen]; + await stream.ReadAsync(buffer, 0, buffer.Length); + // 转化为字符串 + arguments = System.Text.Encoding.UTF8.GetString(buffer); + if (context.Request.Method == "POST" || context.Request.Method == "PUT" || context.Request.Method == "DELETE") context.Request.Body.Position = 0; + } + //返回结果 + using (var responseBody = new MemoryStream()) + { + context.Response.Body = responseBody; + await _next(context); + result = await GetResponse(context.Response); + await responseBody.CopyToAsync(response); + } + context.Response.OnCompleted(() => + { + _stopwatch.Stop(); + _logger.LogInformation($"Client IP:[{context.Connection.RemoteIpAddress}] ,\n" + + $"Request path:[{context.Request.Path}],\nRequest Method:[{context.Request.Method}],\n" + + $"Arguments:[{arguments}],\n Result:[{result}],\nStart time:[{startTime}],\nDuration:[{_stopwatch.ElapsedMilliseconds}]"); + return Task.CompletedTask; + }); + } + /// + /// 获取响应内容 + /// + /// + /// + public async Task GetResponse(HttpResponse response) + { + if (response.Body.Length == 0) + { + response.StatusCode = 204; + return null; + } + else + { + response.Body.Seek(0, SeekOrigin.Begin); + var text = await new StreamReader(response.Body).ReadToEndAsync(); + response.Body.Seek(0, SeekOrigin.Begin); + return text; + } + } + } +} diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..c650338 --- /dev/null +++ b/Program.cs @@ -0,0 +1,27 @@ +using LangGuan.Services; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Quartz; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan +{ + public class Program + { + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + } +} diff --git a/Properties/launchSettings.json b/Properties/launchSettings.json new file mode 100644 index 0000000..5ca7acf --- /dev/null +++ b/Properties/launchSettings.json @@ -0,0 +1,36 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:26818", + "sslPort": 0 + } + }, + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "LangGuan": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "http://localhost:5000" + }, + "Docker": { + "commandName": "Docker", + "launchBrowser": true, + "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/weatherforecast", + "publishAllPorts": true + } + } +} \ No newline at end of file diff --git a/Services/AlertService.cs b/Services/AlertService.cs new file mode 100644 index 0000000..e711e7a --- /dev/null +++ b/Services/AlertService.cs @@ -0,0 +1,79 @@ +using LangGuan.Command.Model; +using LangGuan.Command.Model.EntityModel; +using Microsoft.Extensions.Configuration; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; + +namespace LangGuan.Services +{ + /// + /// + /// + public class AlertService : BaseService + { + /// + /// + /// + /// + public AlertService(IConfiguration config) : base(config, nameof(Alert)) + { + } + /// + /// 取前20 + /// + /// + /// + public async Task GetToplist(int top = 20) + { + Expression> exp = num => true; + var query = await base.GetListWithExp(exp); + var reslut = query.OrderByDescending(s => s.CreateDateTime).Take(top) + .Select(s => new { s.Id, s.NickName, s.content, }).ToList(); + if (reslut.Count > 0) + { + return reslut; + } + return null; + } + /// + ///新加一条数据 + /// + /// + /// + public async Task Add(Alert alert) + { + await base.CreateAsync(alert); + return true; + } + /// + /// 分页数据 + /// + /// + /// + public async Task GetList(RqeustPaging request) + { + request.pageSize = request.pageSize == 0 ? 10 : request.pageSize; + Expression> exp = num => true; + var query = await base.GetListWithExp(exp); + var total = query.Count(); + var items = query.OrderByDescending(s => s.CreateDateTime) + .Skip(request.pageSize * (request.current - 1)).Take(request.pageSize) + .Select(s => new + { + s.Id, + s.deviceId, + s.NickName, + s.content, + CreateDateTime = s.CreateDateTime + }).ToList(); + return new ApiResult() + { + code = 0, + data = new { total = total, items = items } + }; + } + } +} diff --git a/Services/BaseService.cs b/Services/BaseService.cs new file mode 100644 index 0000000..e22c2e4 --- /dev/null +++ b/Services/BaseService.cs @@ -0,0 +1,204 @@ +using LangGuan.Command.Model; +using Microsoft.Extensions.Configuration; +using MongoDB.Driver; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; + +namespace LangGuan.Services +{ + /// + /// baseservice + /// + /// + public class BaseService where T : BaseModel + { + private readonly IMongoCollection _collection; //数据表操作对象 + /// + /// 构造 + /// + /// + /// + public BaseService(IConfiguration config, string tableName) + { + + var client = new MongoClient(config.GetSection("MongoDBConn").Value); //获取链接字符串 + var database = client.GetDatabase(config.GetSection("MongoDBSetting:DBName").Value); + _collection = database.GetCollection(tableName); + } + /// + /// 获取所有 + /// + /// + public List Get() + { + return _collection.Find(T => true).ToList(); + } + /// + /// 获取单个 + /// + /// + /// + public T Get(string id) + { + return _collection.Find(T => T.Id == id).FirstOrDefault(); + } + /// + /// 创建 + /// + /// + /// + public T Create(T T) + { + _collection.InsertOne(T); + return T; + } + + /// + /// 更新 + /// + /// + /// + public void Update(string id, T TIn) + { + _collection.ReplaceOne(T => T.Id == id, TIn); + } + + /// + /// 删除 + /// + /// + public void Remove(T TIn) + { + _collection.DeleteOne(T => T.Id == TIn.Id); + } + + /// + /// 根据id删除 + /// + /// + public void Remove(string id) + { + _collection.DeleteOne(T => T.Id == id); + } + #region 异步操作 + /// + /// 取列表 + /// + /// + public async Task> GetAsync() + { + return await _collection.Find(T => true).ToListAsync(); + } + /// + /// 取单条 + /// + /// + /// + public async Task GetAsync(string id) + { + return await _collection.Find(T => T.Id == id).FirstOrDefaultAsync(); + } + /// + /// 新增 + /// + /// + /// + public async Task CreateAsync(T T) + { + await _collection.InsertOneAsync(T); + return T; + } + /// + /// 新增 + /// + /// + /// + public async Task CreateManyAsync(IEnumerable T) + { + await _collection.InsertManyAsync(T); + } + /// + /// 更新 + /// + /// + /// + /// + public async Task UpdateAsync(string id, T TIn) + { + await _collection.ReplaceOneAsync(T => T.Id == id, TIn); + } + /// + /// 删除 + /// + /// + /// + public async Task RemoveAsync(string id) + { + await _collection.DeleteOneAsync(T => T.Id == id); + } + + #endregion + /// + /// 表达式取数据 + /// + /// + /// + public Task> GetListWithExp(Expression> expression) + { + // var temp = _collection.AsQueryable().Where(expression).ToList(); + return Task.FromResult(_collection.AsQueryable().Where(expression)); + } + /// + /// filter查找 + /// + /// + /// + public async Task> FindListByFilter(Expression> filter) + { + FilterDefinition filters = Builders.Filter.Where(filter); + return await _collection.Find(filters).ToListAsync(); + + } + /// + /// filterdefinition + /// + /// + /// + public async Task> FindListyFilter(FilterDefinition filter) + { + return await _collection.Find(filter).ToListAsync(); + } + /// + /// 是否存在 + /// + /// + /// + public Task Exist(Expression> expression) + { + var result = _collection.AsQueryable().Where(expression).Any(); + return Task.FromResult(result); + } + /// + /// 分页取数据 + /// + /// + /// + /// + public async Task GetPager(RqeustPaging req, Expression> exp = null) + { + req.pageSize = req.pageSize == 0 ? 10 : req.pageSize; + var query = await GetListWithExp(exp); + var total = query.Count(); + var items = query.OrderByDescending(s => s.CreateDateTime) + .Skip(req.pageSize * (req.current - 1)).Take(req.pageSize).ToList(); + return new ApiResult() + { + code = 0, + data = new { total = total, items = items } + }; + } + } +} diff --git a/Services/DeviceSerive.cs b/Services/DeviceSerive.cs new file mode 100644 index 0000000..3b8c2af --- /dev/null +++ b/Services/DeviceSerive.cs @@ -0,0 +1,399 @@ +using LangGuan.Command.Extension; +using LangGuan.Command.Model; +using LangGuan.Command.Model.EntityModel; +using Microsoft.Extensions.Configuration; +using MongoDB.Driver; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Net.NetworkInformation; +using System.Threading.Tasks; + +namespace LangGuan.Services +{ + /// + /// + /// + public class DeviceSerive : BaseService + { + private AlertService _alertService; + private PlcHelper _hslPlc; + /// + /// + /// + /// + /// + public DeviceSerive(IConfiguration config, AlertService alertService, + PlcHelper plcHelper) : base(config, nameof(Device)) + { + _alertService = alertService; + _hslPlc = plcHelper; + } + + + /// + /// 新加设备 + /// + /// + /// + public async Task Add(Device device) + { + Expression> expression = filter => filter.deviceId == device.deviceId; + var entity = (await base.GetListWithExp(expression)).ToList().FirstOrDefault(); + if (entity == null) + { + await base.CreateAsync(device); + return true; + } + return false; + } + /// + /// 取状态 + /// + /// + /// + public async Task GetlistByGroupState(bool Ingroup) + { + Expression> expression = filter => filter.InGroup == Ingroup && filter.IsDelete == false; + var result = (await base.GetListWithExp(expression)).ToList(); + return new ApiResult() { code = 0, msg = "", data = result }; + } + /// + /// 更新设备 + /// + /// + /// + public async Task Update(Device device) + { + Expression> exp = num => num.Id == device.Id; + var entity = (await base.GetListWithExp(exp)).FirstOrDefault(); + if (entity != null) + { + entity.lng = device.lng; + entity.lat = device.lat; + entity.NickName = device.NickName; + entity.deviceIp = device.deviceIp; + entity.deviceId = device.deviceId; + await base.UpdateAsync(entity.Id, entity); + return new ApiResult() { code = 0, msg = "" }; + } + return new ApiResult() { code = 1, msg = "对象为空" }; + } + /// + /// 更新设备组的状态 + /// + /// + /// + /// + public async Task UpdataGroupState(IEnumerable ids, bool Ingroup) + { + Expression> exp = num => ids.Contains(num.Id); + var items = (await base.GetListWithExp(exp)); + foreach (var item in items) + { + item.InGroup = Ingroup; + await base.UpdateAsync(item.Id, item); + } + } + /// + /// 检测是否已经在组中 + /// + /// + /// + public async Task CheckGroupState(IEnumerable ids) + { + Expression> exp = num => ids.Contains(num.Id); + var items = (await base.GetListWithExp(exp)); + foreach (var item in items) + { + if (item.InGroup) + { + return false; + } + } + return true; + + } + /// + /// 分页数据 + /// + /// + /// + public async Task GetList(RqeustPaging request) + { + request.pageSize = request.pageSize == 0 ? 10 : request.pageSize; + Expression> exp = filter => true; + var query = await base.GetListWithExp(exp); + var total = query.Count(); + var items = query.OrderByDescending(s => s.CreateDateTime) + .Skip(request.pageSize * (request.current - 1)).Take(request.pageSize) + .Select(s => new { s.Id, s.deviceId, s.NickName, s.lat, s.lng, s.deviceIp }).ToList(); + return new ApiResult() + { + code = 0, + data = new { total = total, items = items } + }; + } + /// + /// 取多条数据 + /// + /// + /// + public async Task> GetDeviceByIds(IEnumerable ids) + { + FilterDefinitionBuilder builderFilter = Builders.Filter; + FilterDefinition filter = builderFilter.In("Id", ids); + var result = await base.FindListyFilter(filter); + return result; + } + /// + /// 取全部数据 + /// + /// + public async Task> GeAllList() + { + Expression> exp = num => true; + var query = await base.GetListWithExp(exp); + var list = query.OrderByDescending(s => s.CreateDateTime).ToList(); + // .Select(s => new { s.Id, s.deviceId, s.NickName, s.deviceIp, s.lat, s.lng, status = s.state, s.InGroup, s.angle }).ToList(); + List obj = new List(); + foreach (var item in list) + { + Ping pingSender = new Ping(); + PingReply reply = await pingSender.SendPingAsync(item.deviceIp, 500); + // var temp = await _hslPlc.GetAngleVal1(item.deviceIp, "VD4030"); + obj.Add(new + { + item.Id, + item.deviceId, + item.NickName, + item.deviceIp, + item.lat, + item.lng, + angle = "0.0", + online = reply.Status == IPStatus.Success ? true : false + }); + } + + //foreach (var item in list) + //{ + // /// 远程获取设备是否在线 + // var temp = await _hslPlc.GetAngleVal1(item.deviceIp, "VD4030"); + // obj.Add(new indexdevice + // { + // id = item.Id, + // deviceId = item.deviceId, + // NickName = item.NickName, + // lat = item.lat, + // lng = item.lng, + // angle = temp, + // online = temp != "" ? true : false, + // deviceIp = item.deviceIp + // }); + // //obj.Add(new + // //{ + // // item.Id, + // // item.deviceId, + // // item.NickName, + // // item.deviceIp, + // // item.lat, + // // item.lng, + // // angle = temp, + // // online = temp != "" ? true : false + // //}); + //} + return obj; + } + public class indexdevice + { + public string id { get; set; } + public string deviceId { get; set; } + public string NickName { get; set; } + public string deviceIp { get; set; } + public string lat { get; set; } + public string lng { get; set; } + public string angle { get; set; } + public bool online { get; set; } + } + /// + /// 更新设备状态 + /// + /// + /// + public async Task UpdateState(Device device) + { + Expression> expression = filter => filter.deviceId == device.deviceId; + var entity = (await base.GetListWithExp(expression)).ToList().FirstOrDefault(); + if (entity != null) + { + if (entity.state != device.state) + { + string content = "设备离线"; + if (entity.state == 0) + { + content = "设备上线"; + } + entity.state = device.state; + await base.UpdateAsync(device.Id, entity); + await _alertService.Add(new Alert + { + NickName = entity.NickName, + deviceId = entity.deviceId, + content = content + }); + return true; + } + + } + return false; + } + /// + /// 开启 + /// + /// 设备id + /// 是否定点 + /// + public async Task startdevice(string deviceId, bool point = false) + { + Expression> exp = num => num.Id == deviceId; + var entity = await base.GetAsync(deviceId); + if (entity != null) + { + await _hslPlc.SetVal(entity.deviceIp, "V4000.1", true); + return await _hslPlc.SetVal(entity.deviceIp, "V4000.2", point); + } + return false; + } + /// + /// 停止 + /// + /// + /// + public async Task stopDevice(string deviceId) + { + Expression> exp = num => num.Id == deviceId; + var entity = await base.GetAsync(deviceId); + if (entity != null) + { + return await _hslPlc.SetVal(entity.deviceIp, "V4000.1", false); + } + return false; + } + public async Task readkey(string ip, string key) + { + return await _hslPlc.read(ip, key); + } + public async Task wrirekey(string ip, string key, int val) + { + await _hslPlc.WriteVal(ip, key, val); + } + public async Task getval(string deviceId) + { + Expression> exp = num => num.Id == deviceId; + var entity = await base.GetAsync(deviceId); + if (entity != null) + { + return await _hslPlc.GetVal(entity.deviceIp, "V4000.1"); + } + return false; + } + public async Task setval(string deviceId, bool val) + { + Expression> exp = num => num.Id == deviceId; + var entity = await base.GetAsync(deviceId); + if (entity != null) + { + return await _hslPlc.SetVal(entity.deviceIp, "V4000.1", val); + } + return false; + } + /// + /// + /// + /// + /// + /// + /// + public async Task setUporDown(string id, int t = 1, bool val = true) + { + var entity = await base.GetAsync(id); + if (entity != null) + { + string key = "V4000.5";//上 + if (t != 1) + { + key = "V4000.6";//下 + } + return await _hslPlc.SetVal(entity.deviceIp, key, val); + } + return false; + } + /// + /// 归零 + /// + /// + /// + /// + public async Task Zero(string id, bool val = true) + { + var entity = await base.GetAsync(id); + if (entity != null) + { + string key = "V4000.7";//归零 + Console.WriteLine("归零操作"); + return await _hslPlc.SetVal(entity.deviceIp, key, val); + } + return false; + } + /// + /// + /// + /// + /// + /// + /// + public async Task setLeftorRight(string id, int t = 1, bool val = true) + { + var entity = await base.GetAsync(id); + if (entity != null) + { + string key = "V4000.3";//左 + if (t != 1) + { + key = "V4000.4";//右 + } + return await _hslPlc.SetVal(entity.deviceIp, key, val); + } + return false; + } + /// + /// 设备角度 + /// + /// + /// + public async Task GetUpOrDown(string id) + { + var entity = await base.GetAsync(id); + if (entity != null) + { + return await _hslPlc.GetAngleVal1(entity.deviceIp, "VW4034"); + } + return null; + } + /// + /// 设备角度 + /// + /// + /// + public async Task GetLeftOrRight(string id) + { + var entity = await base.GetAsync(id); + if (entity != null) + { + return await _hslPlc.GetAngleVal1(entity.deviceIp, "VD4030"); + } + return null; + } + } +} diff --git a/Services/DeviceUsedService.cs b/Services/DeviceUsedService.cs new file mode 100644 index 0000000..c77b476 --- /dev/null +++ b/Services/DeviceUsedService.cs @@ -0,0 +1,63 @@ +using LangGuan.Command.Model; +using LangGuan.Command.Model.EntityModel; +using Microsoft.Extensions.Configuration; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; + +namespace LangGuan.Services +{ + public class DeviceUsedService : BaseService + { + public IConfiguration _configuration; + public DeviceUsedService(IConfiguration config) : base(config, nameof(DeviceUsed)) + { + _configuration = config; + } + public async Task AddDeviceUsed(DeviceUsed input) + { + //开启时,每小时,用水,用电 + var water = _configuration.GetSection("water").Value; + var power = _configuration.GetSection("power").Value; + var timespan = (input.End - input.Start).TotalSeconds; + input.Water = Math.Round(float.Parse(water) / 3600 * timespan,2); + input.Power = Math.Round((float.Parse(power) / 3600 * timespan),2); + await base.CreateAsync(input); + } + /// + /// + /// + /// + public async Task GetList(DateTime start, DateTime end) + { + Expression> exp = filter => start < filter.CreateDateTime || filter.CreateDateTime <= end.AddDays(1); + var query = (await base.GetListWithExp(exp)).ToList(); + var items = query.OrderByDescending(s => s.CreateDateTime) + .Select(s => new { day = s.CreateDateTime.AddHours(8).ToString("yyyy-MM-dd"), s.Power, s.Water }).ToList(); + + var result = items.GroupBy(s => s.day).Select(m => new + { + day = m.Key, + water = Math.Round(m.Sum(o => o.Water), 2), + power = Math.Round(m.Sum(o => o.Power), 2) + }); + return new + { + items = result + }; + } + public async Task UpdateDouble() + { + Expression> exp = filter => true; + var query = (await base.GetListWithExp(exp)).ToList(); + foreach (var item in query) + { + item.Water = (float)item.Water; + item.Power = (float)item.Power; + await base.UpdateAsync(item.Id, item); + } + } + } +} diff --git a/Services/EmployeeService.cs b/Services/EmployeeService.cs new file mode 100644 index 0000000..0b3d8b7 --- /dev/null +++ b/Services/EmployeeService.cs @@ -0,0 +1,104 @@ +using LangGuan.Command.Model; +using LangGuan.Command.Model.EntityModel; +using Microsoft.Extensions.Configuration; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; + +namespace LangGuan.Services +{ + /// + /// + /// + public class EmployeeService : BaseService + { + /// + /// + /// + /// + public EmployeeService(IConfiguration config) : base(config, nameof(Employee)) + { + } + /// + /// 登陆 + /// + /// + /// + /// + public async Task Login(string Account, string Pwd) + { + Expression> expression = filter => filter.Account == Account && filter.Pwd == Pwd; + var entity = (await base.GetListWithExp(expression)).ToList().FirstOrDefault(); + if (entity != null) return new ApiResult() { code = 0, data = new { account = Account, nickName = entity.NickName }, msg = "" }; + else + return new ApiResult() { code = 1, msg = "登陆失败,请检查用户名跟密码" }; + } + /// + /// 更新密码 + /// + /// + /// + /// + /// + public async Task Update(string Account, string Pwd, string NewPwd) + { + Expression> expression = filter => filter.Account == Account && filter.Pwd == Pwd; + var entity = (await base.GetListWithExp(expression)).ToList().FirstOrDefault(); + if (entity != null) + { + entity.Pwd = NewPwd; + await base.UpdateAsync(entity.Id, entity); + return new ApiResult() { code = 0, msg = "" }; + } + return new ApiResult() { code = 1, msg = "旧密码有误" }; + } + /// + /// 新加用户 + /// + /// + /// + /// + /// + public async Task Add(string Account, string Pwd, string NickName) + { + Expression> expression = filter => filter.Account == Account; + var entity = (await base.GetListWithExp(expression)).ToList().FirstOrDefault(); + if (entity != null) + { + return new ApiResult() { code = 1, msg = $"已经存在{Account},无法重复添加" }; + } + else + { + await base.CreateAsync(new Employee() + { + Account = Account, + Pwd = Pwd, + NickName = NickName + }); + return new ApiResult() { code = 0, msg = "" }; + } + } + /// + /// 列表页 + /// + /// + /// + public async Task GetList(RqeustPaging request) + { + request.pageSize = request.pageSize == 0 ? 10 : request.pageSize; + Expression> exp = num => true; + var query = await base.GetListWithExp(exp); + var total = query.Count(); + var items = query.OrderByDescending(s => s.CreateDateTime) + .Skip(request.pageSize * (request.current - 1)).Take(request.pageSize) + .Select(s => new { s.NickName, s.Account, s.Id }).ToList(); + return new ApiResult() + { + code = 0, + data = new { total = total, items = items } + }; + } + } +} diff --git a/Services/GroupService.cs b/Services/GroupService.cs new file mode 100644 index 0000000..8df853c --- /dev/null +++ b/Services/GroupService.cs @@ -0,0 +1,136 @@ +using LangGuan.Command.Model; +using LangGuan.Command.Model.EntityModel; +using Microsoft.Extensions.Configuration; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; + +namespace LangGuan.Services +{ + public class GroupService : BaseService + { + private DeviceSerive _deviceSerive; + public GroupService(IConfiguration config, DeviceSerive deviceSerive) : base(config, nameof(Group)) + { + _deviceSerive = deviceSerive; + } + /// + /// 新加分组 + /// + /// + /// + public async Task Add(Group input) + { + Expression> expression = filter => filter.GroupName == input.GroupName; + var entity = (await base.GetListWithExp(expression)).ToList().FirstOrDefault(); + if (entity == null) + { + if (await _deviceSerive.CheckGroupState(input.DeviceIds)) + { + await base.CreateAsync(input); + return new ApiResult() { code = 0, msg = "" }; + } + return new ApiResult() { code = 1, msg = "设备已有分组" }; + } + return new ApiResult() { code = 1, msg = "已经存在同名的组" }; + } + /// + /// 更新 + /// + /// + /// + public async Task update(Group input) + { + Expression> exp = num => num.Id == input.Id; + var entity = (await base.GetListWithExp(exp)).FirstOrDefault(); + if (entity != null) + { + //更新设备状态为不在组内 + await _deviceSerive.UpdataGroupState(entity.DeviceIds, false); + entity.GroupName = input.GroupName; + entity.Description = input.Description; + entity.DeviceIds = input.DeviceIds; + await base.UpdateAsync(entity.Id, entity); + await _deviceSerive.UpdataGroupState(input.DeviceIds, true); + return new ApiResult() { code = 0, msg = "" }; + } + return new ApiResult() { code = 1, msg = "对象为空" }; + } + /// + /// + /// + /// + /// + public async Task remove(IEnumerable ids) + { + if (ids.Any()) + { + foreach (var item in ids) + { + await base.RemoveAsync(item); + } + } + return new ApiResult() { code = 0, msg = "" }; + } + /// + /// 取单条 + /// + /// + /// + public async Task FindOne(string id) + { + Expression> exp = num => num.Id == id; + var entity = (await base.GetListWithExp(exp)).FirstOrDefault(); + Expression> exp1 = filter => entity.DeviceIds.Contains(filter.Id); + var deviceItems = (await _deviceSerive.GetListWithExp(exp1)).ToList(); + return new ApiResult() + { + code = 0, + msg = "", + data = new GroupDevice() + { + GroupName = entity.GroupName, + Description = entity.Description, + items = deviceItems + } + }; + } + /// + /// + /// + /// + /// + public async Task GetList(RqeustPaging request) + { + request.pageSize = request.pageSize == 0 ? 10 : request.pageSize; + Expression> exp = num => true; + var query = await base.GetListWithExp(exp); + var total = query.Count(); + var items = query.OrderByDescending(s => s.CreateDateTime) + .Skip(request.pageSize * (request.current - 1)).Take(request.pageSize) + .Select(s => new { s.Id, s.GroupName, s.Description, s.DeviceIds }).ToList(); + return new ApiResult() + { + code = 0, + data = new { total = total, items = items } + }; + } + /// + /// group 取全部的设备id + /// + /// + /// + public async Task> GetDeviceIds(IEnumerable ids) + { + Expression> exp = num => ids.Contains(num.Id); + List result = new List(); + (await base.GetListWithExp(exp)).ToList().Select(s => s.DeviceIds).ToList().ForEach(o => + { + result.AddRange(o); + }); + return result; + } + } +} diff --git a/Services/HJ212/NetServer.cs b/Services/HJ212/NetServer.cs new file mode 100644 index 0000000..b107d7b --- /dev/null +++ b/Services/HJ212/NetServer.cs @@ -0,0 +1,65 @@ +using System; +using System.Net; +using System.Text; +using System.Timers; +using IceCoffee.HJ212.Models; +using IceCoffee.FastSocket; +using IceCoffee.FastSocket.Tcp; + +namespace IceCoffee.HJ212 +{ + /// + /// + /// + public class NetServer : TcpServer + { + /// + /// 收到数据事件 + /// + public event Action ReceivedData; + /// + /// 发送数据事件 + /// + public event Action SendData; + + public NetServer(IPAddress address, int port, TcpServerOptions options = null) + : base(address, port, options ?? new TcpServerOptions() { KeepAlive = true }) + { + } + public NetServer(string address, int port, TcpServerOptions options = null) + : base(address, port, options ?? new TcpServerOptions() { KeepAlive = true }) + { + } + public NetServer(IPEndPoint endPoint, TcpServerOptions options = null) + : base(endPoint, options ?? new TcpServerOptions() { KeepAlive = true }) + { + } + /// + /// + /// + /// + protected override TcpSession CreateSession() + { + return new NetSession(this); + } + + /// + /// 引发收到数据事件 + /// + internal void RaiseReceivedData(NetSession netSession, NetPackage netPackage, string rawText) + { + ReceivedData?.Invoke(netSession, netPackage, rawText); + } + + /// + /// 引发发送数据事件 + /// + /// + /// + /// + internal void RaiseSendData(NetSession netSession, NetPackage netPackage, string rawText) + { + SendData?.Invoke(netSession, netPackage, rawText); + } + } +} diff --git a/Services/HJ212/NetSession.cs b/Services/HJ212/NetSession.cs new file mode 100644 index 0000000..ce50032 --- /dev/null +++ b/Services/HJ212/NetSession.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Sockets; +using System.Text; +using IceCoffee.HJ212.Models; +using IceCoffee.Common.Extensions; +using IceCoffee.FastSocket.Tcp; + +namespace IceCoffee.HJ212 +{ + /// + /// + /// + public class NetSession : TcpSession + { + private StringBuilder _unpackCache; + + public NetSession(TcpServer server) : base(server) + { + } + + protected override void OnClosed() + { + base.OnClosed(); + _unpackCache?.Clear(); + } + + /// + /// 获取分包缓存 + /// + /// + private StringBuilder GetUnpackCache() + { + return _unpackCache ??= new StringBuilder(); + } + /// + /// + /// + protected override void OnReceived() + { + if (ReadBuffer.IndexOf(35) != 0L)// '#' + { + throw new Exception("异常TCP连接 IP: " + RemoteIPEndPoint); + } + + string rawText = null; + while (ReadBuffer.CanReadLine) + { + try + { + byte[] data = ReadBuffer.ReadLine(); + rawText = Encoding.UTF8.GetString(data); + NetPackage netPackage = NetPackage.Parse(rawText, GetUnpackCache); + ((NetServer)Server).RaiseReceivedData(this, netPackage, rawText); + + if (netPackage.DataSegment.PackageFlag != null && netPackage.DataSegment.PackageFlag.A == 1) + { + Response(netPackage); + } + } + catch (Exception ex) + { + throw new Exception("数据报:" + rawText, ex); + } + } + } + + /// + /// 应答 + /// + private void Response(NetPackage netPackage) + { + try + { + netPackage.DataSegment.ST = DataSegment.ResponseST; + netPackage.DataSegment.CN = CommandNumber.DataResponse; + netPackage.DataSegment.PackageFlag.A = 0; + netPackage.DataSegment.PackageFlag.D = 0; + netPackage.DataSegment.CpCommand.ExeRtn = ResponseCode.ExecSucceeded; + + string rawText = netPackage.Serialize(); + byte[] data = Encoding.UTF8.GetBytes(rawText); + + SendAsync(data); + + ((NetServer)Server).RaiseSendData(this, netPackage, rawText); + } + catch (Exception ex) + { + throw new Exception("Error in NetSession", ex); + } + } + } + +} diff --git a/Services/HJ212SocketServer.cs b/Services/HJ212SocketServer.cs new file mode 100644 index 0000000..6cfed4d --- /dev/null +++ b/Services/HJ212SocketServer.cs @@ -0,0 +1,339 @@ +using IceCoffee.FastSocket.Tcp; +using IceCoffee.HJ212; +using IceCoffee.HJ212.Models; +using LangGuan.Command.Model; +using LangGuan.Command.Model.EntityModel; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace LangGuan.Services +{ + /// + /// 启动socket + /// + public class HJ212SocketServer + { + + private Hj212Service _hj212Service; + private DeviceSerive _deviceSerive; + /// + /// + /// + /// + /// + public HJ212SocketServer(Hj212Service hj212Service, DeviceSerive deviceSerive) + { + _hj212Service = hj212Service; + _deviceSerive = deviceSerive; + } + /// + /// 缓冲器 + /// + private byte[] result = new byte[1024]; + /// + /// 最大连接数 + /// + private int maxClientCount; + /// + /// 服务IP地址 + /// + private string ip; + /// + /// 服务端口号 + /// + private int port => 9001; + // 编码 + // private string code; + /// + /// 客户端列表 + /// + private List ClientSockets; + /// + /// IP终端 + /// + private IPEndPoint ipEndPoint; + /// + /// 服务端Socket + /// + private Socket ServerSocket; + private static NetServer server; + private static IceCoffee.FastSocket.Tcp.TcpClient client; + /// + /// 启动服务 + /// + /// + public async Task Start() + { + ip = IPAddress.Any.ToString(); + server = new NetServer(ip, port); + server.Started += OnNetServer_Started; + server.ExceptionCaught += OnNetServer_ExceptionCaught; + server.SessionStarted += OnNetServer_SessionStarted; + server.SessionClosed += OnNetServer_SessionClosed; + server.ReceivedData += OnNetServer_ReceivedData; + server.SendData += OnNetServer_SendData; + server.Start(); + + //client = new IceCoffee.FastSocket.Tcp.TcpClient(ip, port); + //client.ConnectAsync(); + //client.Connected += OnClient_Connected; + + + + + + + + + + + + + + + + + + + //try + //{ + // ip = IPAddress.Any.ToString(); + // maxClientCount = 256; //设定最大连接数 + // ClientSockets = new List(); + // ipEndPoint = new IPEndPoint(IPAddress.Any, port); //初始化IP终端 + // ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //初始化服务端Socket + // ServerSocket.Bind(this.ipEndPoint); //端口绑定 + // ServerSocket.Listen(100); //设置监听数目 + // Console.WriteLine($"socket服务已经启动端口:{port}"); + // var handler = await ServerSocket.AcceptAsync(); + // string data = null; + // byte[] bytes = null; + // while (true) + // { + // bytes = new byte[1024]; + // int bytesRec = handler.Receive(bytes); + // data = Encoding.UTF8.GetString(bytes, 0, bytesRec); + // Console.WriteLine($"客户端发来数据:{data}"); + // if (data.IndexOf("/r/n") > -1) + // { + // break; + // } + // } + // Console.WriteLine($"客户端发来数据:{data}"); + // handler.Send(PackData("1")); + // handler.Shutdown(SocketShutdown.Both); + // handler.Close(); + + + + + // //while (true) + // //{ + // // if (handler.Connected) + // // { + // // var buffer = new byte[1_024]; + // // var received = await handler.ReceiveAsync(buffer, SocketFlags.None); + // // var strData = Encoding.UTF8.GetString(buffer, 0, received); + // // if (!string.IsNullOrEmpty(strData)) + // // { + // // if (!string.IsNullOrEmpty(strData)) + // // { + // // HJ212_2017 hj = new HJ212_2017(); + // // if (hj.DecodeData(strData)) + // // { + // // Console.WriteLine($"客户端发来数据:{strData}"); + // // var body = JsonConvert.SerializeObject(hj.CP); + // // var entity = JsonConvert.DeserializeObject(body); + // // entity.deviceId = hj.DATA_HEAD["MN"]; + // // //校验通过,开始入库 + // // Console.WriteLine($"数据开始入库"); + // // _ = _hj212Service.Add(entity, handler.RemoteEndPoint.ToString()); + // // Console.WriteLine($"数据入库end"); + // // } + // // } + // // } + // // } + // // else + // // { + // // break; + // // } + // //} + // //连接客户端 + //} + //catch (Exception ex) + //{ + // Console.WriteLine($"socket服务异常:{ex}"); + //} + } + private void OnClient_Connected() + { + string message = "##0285QN=20190925181031464;ST=22;CN=2061;PW=BF470F88957588DE902D1A52;MN=Z13401000010301;Flag=5;CP=&&DataTime=20190924220000;a34006-Avg=2.69700,a34006-Flag=N;a34007-Avg=7.96600,a34007-Flag=N;a34048-Avg=3.30600,a34048-Flag=N;a34047-Avg=7.35700,a34047-Flag=N;a34049-Avg=10.66300,a34049-Flag=N&&C181\r\n"; + byte[] data = Encoding.UTF8.GetBytes(message); + client.SendAsync(data); + } + private void OnNetServer_Started() + { + Console.WriteLine($"开始监听: {ip}:{port}"); + } + + private void OnNetServer_SendData(NetSession session, NetPackage netPackage, string rawText) + { + Console.WriteLine($"发送给: {session.RemoteIPEndPoint}: {rawText}"); + } + + private void OnNetServer_SessionClosed(TcpSession session) + { + Console.WriteLine("会话关闭: " + session.RemoteIPEndPoint + ", 当前会话总数: " + server.SessionCount); + } + + private static void OnNetServer_SessionStarted(TcpSession session) + { + Console.WriteLine("会话开始: " + session.RemoteIPEndPoint + ", 当前会话总数: " + server.SessionCount); + } + + private void OnNetServer_ReceivedData(TcpSession session, NetPackage netPackage, string rawText) + { + Console.WriteLine("收到自: " + session.RemoteIPEndPoint + ": " + rawText); + HJ212_2017 hj = new HJ212_2017(); + if (hj.DecodeData(rawText)) + { + var body = JsonConvert.SerializeObject(hj.CP); + var entity = JsonConvert.DeserializeObject(body); + entity.deviceId = hj.DATA_HEAD["MN"]; + //校验通过,开始入库 + Console.WriteLine($"数据开始入库"); + _ = _hj212Service.Add(entity, session.RemoteIPEndPoint.ToString()); + } + + + } + private void OnNetServer_ExceptionCaught(Exception ex) + { + Console.WriteLine("Error in NetServer" + ex); + } + private void Receive(Socket socket) + { + string strData = null; + byte[] bytes = null; + while (true) + { + bytes = new byte[1024]; + int bytesRec = socket.Receive(bytes); + strData = Encoding.UTF8.GetString(bytes, 0, bytesRec); + if (!string.IsNullOrEmpty(strData)) + { + HJ212_2017 hj = new HJ212_2017(); + if (hj.DecodeData(strData)) + { + Console.WriteLine($"客户端发来数据:{strData}"); + var body = JsonConvert.SerializeObject(hj.CP); + var entity = JsonConvert.DeserializeObject(body); + entity.deviceId = hj.DATA_HEAD["MN"]; + //校验通过,开始入库 + Console.WriteLine($"数据开始入库"); + _ = _hj212Service.Add(entity, socket.RemoteEndPoint.ToString()); + } + } + } + } + /// + /// 后台线程接收数据 + /// + /// + private void ReceiveMessage(object obj) + { + Socket _ClientSocket = (Socket)obj; + while (true) + { + try + { + //获取数据长度 + int receiveLength = _ClientSocket.Receive(result); + //获取客户端发来的数据 + string strData = Encoding.UTF8.GetString(result, 0, receiveLength); + if (string.IsNullOrEmpty(strData)) + { + break; + } + HJ212_2017 hj = new HJ212_2017(); + if (hj.DecodeData(strData)) + { + var body = JsonConvert.SerializeObject(hj.CP); + var entity = JsonConvert.DeserializeObject(body); + entity.deviceId = hj.DATA_HEAD["MN"]; + //校验通过,开始入库 + _ = _hj212Service.Add(entity, _ClientSocket.RemoteEndPoint.ToString()); + _ClientSocket.Close(); + _ClientSocket.Dispose(); + + } + } + catch (Exception e)//通讯出现异常 + { + //从客户端列表中移除该客户端 + //this.ClientSockets.Remove(_ClientSocket); + ////断开连接 + Console.WriteLine($"客户端{_ClientSocket.RemoteEndPoint},通讯出现异常:{e.Message}"); + //_ClientSocket.Shutdown(SocketShutdown.Both); + _ClientSocket.Close(); + break; + } + + } + } + byte[] PackData(string data) + { + Encoding gb = Encoding.GetEncoding("gb2312"); + List arr = new List(); + arr.Add(0x23); + arr.Add(0x23);//固定包头## + arr.AddRange(Encoding.ASCII.GetBytes(data.Length.ToString().PadLeft(4, '0')));//数据段字符串长度(长度不足4左补0)的ASCII编码 + byte[] dataSegment = gb.GetBytes(data);//数据段的gb2312编码 + arr.AddRange(dataSegment); + arr.AddRange(CallCRC(dataSegment));// CRC-16/Modbus校验值 4个字节 + arr.Add(0x0D);//回车 + arr.Add(0x0A);//换行 + return arr.ToArray(); + } + byte[] CallCRC(byte[] data) + { + string ccc = Convert.ToString(getCrc(data), 16).PadLeft(4, '0'); + return Encoding.ASCII.GetBytes(ccc.ToUpper()); + } + private int getCrc(byte[] data) + { + int high; + int flag; + + // 16位寄存器,所有数位均为1 + int wcrc = 0xffff; + for (int i = 0; i < data.Length; i++) + { + // 16 位寄存器的高位字节 + high = wcrc >> 8; + // 取被校验串的一个字节与 16 位寄存器的高位字节进行“异或”运算 + wcrc = high ^ data[i]; + + for (int j = 0; j < 8; j++) + { + flag = wcrc & 0x0001; + // 把这个 16 寄存器向右移一位 + wcrc = wcrc >> 1; + // 若向右(标记位)移出的数位是 1,则生成多项式 1010 0000 0000 0001 和这个寄存器进行“异或”运算 + if (flag == 1) + wcrc ^= 0xa001; + } + } + + return wcrc; + } + + } +} diff --git a/Services/HJ212_2017.cs b/Services/HJ212_2017.cs new file mode 100644 index 0000000..0bfd594 --- /dev/null +++ b/Services/HJ212_2017.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LangGuan.Services +{ + public class HJ212_2017 + { + /// + /// 数据帧头 + /// + public string header { get; set; } + /// + /// 数据长度 + /// + public string data_length { get; set; } + + /// + /// 数据头 + /// + public Dictionary DATA_HEAD { get; set; } + /// + /// + /// + public Dictionary CP { get; set; } + /// + /// CRC校验 + /// + public string CRC { get; set; } + /// + /// + /// + /// + /// + public bool DecodeData(string Text) + { + try + { + if (Text.Length < 12 || !Text.StartsWith("##")) + { + Console.WriteLine("不是HJ212协议的报文!"); + return false; + } + Console.WriteLine($"开始解码数据"); + Text = Text.ToUpper().Replace(";CP=", "").Replace(" ", "");//有些厂家协议不很标准,有的大小写不一致,此处强制转大写字母 + header = Text.Substring(0, 2); + data_length = Text.Substring(2, 4); + string[] data_0 = Text.Substring(6, Text.Length - 6).Split(new char[] { '&', '&' }, StringSplitOptions.RemoveEmptyEntries); + string[] data_1 = data_0[0].Split(new char[] { ';' }); + DATA_HEAD = new Dictionary(); + for (int h = 0; h < data_1.Length; h++) + { + string[] d_1 = data_1[h].Split(new char[] { '=' }); + DATA_HEAD.Add(d_1[0], d_1[1]); + } + string[] data_2 = data_0[1].Split(new char[] { ';' }); + CP = new Dictionary(); + for (int i = 0; i < data_2.Length; i++) + { + string[] d_6 = data_2[i].Split(new char[] { ',' }); + for (int j = 0; j < d_6.Length; j++) + { + string[] d_7 = d_6[j].Split(new char[] { '=' }); + CP.Add(d_7[0].Replace("-RTD", ""), d_7[1]); + } + } + CRC = data_0[2]; + return true; + } + catch (Exception ex) + { + //数据接收不完整 + Console.WriteLine($" 解码失败:err:{ex},数据有问题," + Text); + //throw; + return false; + } + } + + + /// + /// 判断数据是否通过校验 + /// + /// 原始数据 + /// 是否通过 + public bool Crc16(string Text) + { + try + { + string CRC = Text.Substring(Text.Length - 4, 4); + + Text = Text.Substring(Text.IndexOf("QN")); + Text = Text.Substring(0, Text.Length - 4); + + byte[] bytes = Encoding.ASCII.GetBytes(Text); + int crcRegister = 0xFFFF; + for (int i = 0; i < bytes.Length; i++) + { + crcRegister = (crcRegister >> 8) ^ bytes[i]; + for (int j = 0; j < 8; j++) + { + int check = crcRegister & 0x0001; + crcRegister >>= 1; + if (check == 0x0001) + { + crcRegister ^= 0xA001; + } + } + } + string result = string.Format("{0:X}", crcRegister);//转十六进制 + for (int i = result.Length; i < 4; i++)//补足 4 位 + { + result = "0" + result; + } + //LogApi.WriteLog("计算校验码:" + result); + if (result == CRC) + { + return true; + } + else + { + Console.WriteLine("校验码有误," + CRC); + Console.WriteLine("待校验数据:" + Text); + Console.WriteLine("计算校验码:" + result); + //LogApi.WriteLog("校验码有误:" + CRC); + //LogApi.WriteLog("待校验数据:" + Text); + //LogApi.WriteLog("计算校验码:" + result); + return false; + + + } + } + catch (Exception) + { + Console.WriteLine("数据校验:数据有问题:" + Text); + //数据接收不完整 + return false; + //throw; + } + + } + } +} diff --git a/Services/Hj212Service.cs b/Services/Hj212Service.cs new file mode 100644 index 0000000..e865ffe --- /dev/null +++ b/Services/Hj212Service.cs @@ -0,0 +1,343 @@ +using LangGuan.Command.Model.EntityModel; +using Microsoft.Extensions.Configuration; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; +using Npoi.Mapper; +using System.IO; +using LangGuan.Command.Model; +using LangGuan.Command.Model.RequestModel; +using MongoDB.Driver; +using MongoDB.Bson; + +namespace LangGuan.Services +{ + /// + /// + /// + public class Hj212Service : BaseService + { + private DeviceSerive _deviceSerive; + /// + /// + /// + /// + /// + public Hj212Service(IConfiguration config, DeviceSerive deviceSerive) : base(config, nameof(HJ212)) + { + _deviceSerive = deviceSerive; + } + /// + /// 新加数据 + /// + /// + /// + /// + public async Task Add(HJ212 hJ212, string deviceIp) + { + //先判断当前设备是否存在 + await _deviceSerive.Add(new Device() + { + deviceId = hJ212.deviceId, + deviceIp = deviceIp, + state = 1 + }); + await base.CreateAsync(hJ212); + } + /// + /// 最近10个小时的数据 + /// + /// + /// + public async Task> GetViewTop(int hours = -10) + { + var date = DateTime.Now.AddHours(-8).AddHours(hours); + Expression> exp = filter => filter.CreateDateTime >= date; + var result = (await base.GetListWithExp(exp)).ToList(); + + return result; + } + + /// + /// 实时的数据 + /// + /// + public async Task> Realtime() + { + Expression> exp = filter => true; + var result = (await base.GetListWithExp(exp)) + .OrderByDescending(s => s.CreateDateTime) + .Take(60).OrderBy(s => s.CreateDateTime).ToList(); + List list = new List(); + var temp = result.Select(s => new + { + s.a34001, + s.a34002, + s.a34004, + hour = s.CreateDateTime.AddHours(8).ToString("yyyy-MM-dd HH:mm") + }).ToList(); + + temp.GroupBy(g => new { g.hour }).ToList().ForEach(s => + { + var v1 = temp.Where(m => m.hour == s.Key.hour).Sum(t => t.a34001); + var v2 = temp.Where(m => m.hour == s.Key.hour).Sum(t => t.a34002); + var v3 = temp.Where(m => m.hour == s.Key.hour).Sum(t => t.a34004); + list.Add(new columnView() { hour = s.Key.hour, type = "a34001", value = v1 }); + list.Add(new columnView() { hour = s.Key.hour, type = "a34002", value = Math.Round(v2, 2) }); + list.Add(new columnView() { hour = s.Key.hour, type = "a34004", value = Math.Round(v3, 2) }); + }); + + return list; + } + + /// + /// 自动报表 + /// + /// + /// + public async Task autoReport(AutoReport autoReport) + { + autoReport = convertDateTime(autoReport); + Expression> exp = filter => (filter.CreateDateTime >= autoReport.begin && + filter.CreateDateTime <= autoReport.end) && + filter.a34001 >= autoReport.a34001 || filter.a34002 >= autoReport.a34002 || filter.a34004 >= autoReport.a34004; + var result = (await base.GetListWithExp(exp)).OrderBy(s => s.CreateDateTime).ToList() + .Select(s => new ExportModel + { + deviceId = s.deviceId, + a01001 = s.a01001, + a01002 = s.a01002, + a01006 = s.a01006, + a01007 = s.a01007, + a01008 = s.a01008, + a34001 = s.a34001, + a34002 = s.a34002, + a34004 = s.a34004, + createtime = s.CreateDateTime.AddHours(8).ToString("yyyy-MM-dd HH:mm") + }).ToList(); + var mapper = new Mapper(); + mapper.Map("设备编号", s => s.deviceId) + .Map("温度", s => s.a01001) + .Map("湿度", s => s.a01002) + .Map("大气压", s => s.a01006) + .Map("风速", s => s.a01007) + .Map("风向", s => s.a01008) + .Map("TSP浓度", s => s.a34001) + .Map("PM2.5", s => s.a34002) + .Map("PM10", s => s.a34004) + .Map("创建时间", s => s.createtime); + mapper.Put(result, "sheet1"); + MemoryStream stream = new MemoryStream(); + mapper.Save(stream); + return stream.ToArray(); + } + + AutoReport convertDateTime(AutoReport autoReport) + { + DateTime AssemblDate = Convert.ToDateTime(DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + "01"); // 组装当前指定月份 + autoReport.begin = autoReport.begin.HasValue ? autoReport.begin.Value : AssemblDate; + autoReport.end = autoReport.end.HasValue ? autoReport.end.Value.AddDays(1).AddHours(-8) : DateTime.Now.AddDays(1); + return autoReport; + } + /// + /// 计算结果 + /// + /// + /// + public async Task> autoReportResult(AutoReport autoReport) + { + + List result = new List(); + string date = autoReport.begin.Value.ToString("yyyy年MM月dd") + "-" + autoReport.end.Value.ToString("yyyy年MM月dd"); + result.Add(date); + var days = (int)(autoReport.end.Value.AddDays(1) - autoReport.begin).Value.TotalDays; + result.Add(days.ToString());//查询总天数 + autoReport = convertDateTime(autoReport); + Expression> exp = filter => (filter.CreateDateTime > autoReport.begin && + filter.CreateDateTime <= autoReport.end) && + (filter.a34001 >= autoReport.a34001 || filter.a34002 >= autoReport.a34002 || filter.a34004 >= autoReport.a34004); + //var builder = Builders.Filter; + //var filter = builder.Gte("CreateDateTime", autoReport.begin.Value) & builder.Lte("CreateDateTime", autoReport.end.Value); + //var fil = await base.FindListyFilter(filter); + //Expression> exp1 = filter => autoReport.begin.Value < filter.CreateDateTime && autoReport.end.Value > filter.CreateDateTime; + + //var t1 = (await base.GetListWithExp(exp1)).ToList(); + //var o1 = t1.Where(s => s.a34001 >= autoReport.a34001 || s.a34002 >= autoReport.a34002 || s.a34004 >= autoReport.a34004).ToList(); + + + var otemp = (await base.GetListWithExp(exp)).OrderBy(s => s.CreateDateTime).ToList(); + var temp = otemp.Select(s => new ExportModel + { + deviceId = s.deviceId, + a01001 = s.a01001, + a01002 = s.a01002, + a01006 = s.a01006, + a01007 = s.a01007, + a01008 = s.a01008, + a34001 = s.a34001, + a34002 = s.a34002, + a34004 = s.a34004, + createtime = s.CreateDateTime.AddHours(8).ToString("yyyy-MM-dd HH:mm") + }).ToList(); + //天数 + //string date = autoReport.begin.Value.ToString("yyyy年MM月dd") + "-" + autoReport.end.Value.ToString("yyyy年MM月dd"); + //result.Add(date); + //var days = (int)(autoReport.end - autoReport.begin).Value.TotalDays; + //result.Add(days.ToString());//查询总天数 + var total = temp.Select(s => new { date = s.createtime.Substring(0, 10) }).Distinct().Count(); + result.Add(total.ToString());// 污染天数 + + //计算持续时间最长的一天 + + HJ212 current = null; + HJ212 pre = otemp.First(); + TimeSpan longestDuration = TimeSpan.Zero; + HJ212 longestDurationStart = pre; + HJ212 longestDurationEnd = null; + foreach (HJ212 t in otemp) + { + current = t; + //如果间隔大于2分钟,就是新的数据上来了 + if ((current.CreateDateTime - pre.CreateDateTime) > TimeSpan.FromMinutes(2)) + { + //如果持续时间大于上一条就取新的时间 + if (pre.CreateDateTime - longestDurationStart.CreateDateTime > longestDuration) + { + longestDurationStart = current; + } + } + else + { + longestDurationEnd = current; + longestDuration = current.CreateDateTime - longestDurationStart.CreateDateTime; + } + pre = current; + } + + result.Add(longestDurationStart.CreateDateTime.AddHours(8).ToString("yyyy年MM月dd")); + result.Add(((int)longestDuration.TotalMinutes).ToString()); + + + + //计算最多次的天数 + var groupedResult = otemp.GroupBy(t => t.CreateDateTime.AddHours(8).ToString("yyyy年MM月dd")); + Dictionary dic = new Dictionary(); + foreach (var group in groupedResult) + { + int count = 1; + var previous = otemp.First(); + foreach (var curr in group.Skip(1)) + { + TimeSpan duration = curr.CreateDateTime - previous.CreateDateTime; + if (duration > TimeSpan.FromMinutes(1)) + { + count++; + } + previous = current; + } + dic.Add(group.Key, count); + } + var sortdic = dic.OrderBy(s => s.Value); + result.Add(sortdic.First().Key); + result.Add(sortdic.First().Value.ToString()); + + var a34004 = temp.OrderByDescending(s => s.a34004).First();//pm 2.5 + result.Add(DateTime.Parse(a34004.createtime).ToString("yyyy年MM月dd")); + result.Add(a34004.a34004.ToString()); + var a34002 = temp.OrderByDescending(s => s.a34002).First();//pm 10 + result.Add(DateTime.Parse(a34002.createtime).ToString("yyyy年MM月dd")); + result.Add(a34002.a34002.ToString()); + result.Add("斗轮机上料过程中,粉尘溢散较大,时间较长 \r\n 料棚北门3号位置货车卸料频繁,粉尘溢散较大"); + result.Add("斗轮机工作时,增加移动雾炮机在上风口出喷淋 \r\n 料棚北门3号位置货车卸料时,增加移动雾炮机从上风口出喷淋"); + // var a34001 = temp.OrderByDescending(s => s.a34004).First();//tsp + return result; + } + /// + /// 分页取数据 + /// + /// + /// + /// + /// + public async Task GetPageData(DateTime start, DateTime end, RqeustPaging request) + { + + start = start.AddHours(-8); + end = end.AddHours(-8).AddDays(1); + Expression> exp = filter => filter.CreateDateTime >= start && filter.CreateDateTime < end; + var query = await base.GetListWithExp(exp); + var total = query.Count(); + var items = query.Skip(request.pageSize * (request.current - 1)).Take(request.pageSize).ToList() + .Select(s => new ExportModel + { + deviceId = s.deviceId, + a01001 = s.a01001, + a01002 = s.a01002, + a01006 = s.a01006, + a01007 = s.a01007, + a01008 = s.a01008, + a34001 = s.a34001, + a34002 = s.a34002, + a34004 = s.a34004, + createtime = s.CreateDateTime.AddHours(8).ToString("yyyy-MM-dd HH mm") + }).ToList(); + return new ApiResult() { data = new { total = total, items = items } }; + } + /// + /// 查找数据 + /// + /// + /// + /// + async Task> GetPage(DateTime start, DateTime end) + { + start = start.AddHours(-8); + end = end.AddHours(-8).AddDays(1); + Expression> exp = filter => filter.CreateDateTime >= start && filter.CreateDateTime < end; + var temp = await base.GetListWithExp(exp); + return (await base.GetListWithExp(exp)).ToList().Select(s => new ExportModel + { + deviceId = s.deviceId, + a01001 = s.a01001, + a01002 = s.a01002, + a01006 = s.a01006, + a01007 = s.a01007, + a01008 = s.a01008, + a34001 = s.a34001, + a34002 = s.a34002, + a34004 = s.a34004, + createtime = s.CreateDateTime.AddHours(8).ToString("yyyy-MM-dd HH mm") + }).ToList(); + + } + /// + /// 导出数据 + /// + /// + /// + /// + public async Task Export(DateTime start, DateTime end) + { + var result = (await GetPage(start, end)).ToList(); + var mapper = new Mapper(); + mapper.Map("设备编号", s => s.deviceId) + .Map("温度", s => s.a01001) + .Map("湿度", s => s.a01002) + .Map("大气压", s => s.a01006) + .Map("风速", s => s.a01007) + .Map("风向", s => s.a01008) + .Map("TSP浓度", s => s.a34001) + .Map("PM2.5", s => s.a34002) + .Map("PM10", s => s.a34004) + .Map("创建时间", s => s.createtime); + mapper.Put(result, "sheet1"); + MemoryStream stream = new MemoryStream(); + mapper.Save(stream); + return stream.ToArray(); + } + + + } +} diff --git a/Services/Job/JobServiceFactory.cs b/Services/Job/JobServiceFactory.cs new file mode 100644 index 0000000..77d1b7c --- /dev/null +++ b/Services/Job/JobServiceFactory.cs @@ -0,0 +1,30 @@ +using Quartz; +using Quartz.Spi; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Services.Job +{ + public class JobServiceFactory : IJobFactory + { + private readonly IServiceProvider _serviceProvider; + + public JobServiceFactory(IServiceProvider serviceProvider) + { + _serviceProvider = serviceProvider; + } + public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler) + { + var job = _serviceProvider.GetService(bundle.JobDetail.JobType); + return job as IJob; + } + + public void ReturnJob(IJob job) + { + + } + } +} + diff --git a/Services/Job/Monitor.cs b/Services/Job/Monitor.cs new file mode 100644 index 0000000..867ba90 --- /dev/null +++ b/Services/Job/Monitor.cs @@ -0,0 +1,95 @@ +using LangGuan.Command.Model.EntityModel; +using Quartz; +using Quartz.Impl; +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Services.Job +{ + public class Monitor + { + private IScheduler _scheduler; + + private List<(IJobDetail, ITrigger)> _jobTriggers = new List<(IJobDetail, ITrigger)>(); + + private readonly IServiceProvider container; + public Monitor(IServiceProvider container) + { + this.container = container; + // SetJobs(configuration); + } + public void SetJobs(List list) + { + foreach (var item in list) + { + IJobDetail job = JobBuilder.Create() + .WithIdentity("job_" + item.Id) + .UsingJobData("PlanId", item.Id) + .UsingJobData("PlanName", item.name) + .Build(); + ITrigger trigger = TriggerBuilder.Create() + .WithIdentity("trigger_" + item.Id) + .WithCronSchedule(item.cron).StartNow() + .ForJob("job_" + item.Id).Build(); + _jobTriggers.Add((job, trigger)); + } + } + + public async Task StartAsync() + { + //Logging.LogManager.Adapter = new Logging.Simple.ConsoleOutLoggerFactoryAdapter { Level = Logging.LogLevel.Info }; + try + { + NameValueCollection props = new NameValueCollection + { + { "quartz.serializer.type", "binary" } + }; + StdSchedulerFactory factory = new StdSchedulerFactory(); + _scheduler = await factory.GetScheduler(); + _scheduler.JobFactory = new JobServiceFactory(this.container); + await AddJobsAsync(); + await _scheduler.Start(); + + + } + catch (SchedulerException se) + { + Console.WriteLine(se); + } + } + + public async Task AddJobsAsync() + { + foreach ((IJobDetail, ITrigger) jt in _jobTriggers) + { + await _scheduler.ScheduleJob(jt.Item1, jt.Item2); + } + } + public void PauseTrigger(string triggerName, string triggerGroup) + { + if (_scheduler != null) + { + _scheduler.PauseTrigger(new TriggerKey(triggerName, triggerGroup)); + } + } + + public void ResumeTrigger(string triggerName, string triggerGroup) + { + if (_scheduler != null) + { + _scheduler.ResumeTrigger(new TriggerKey(triggerName, triggerGroup)); + } + } + + public void Stop() + { + if (_scheduler != null) + { + _scheduler.Shutdown(); + } + } + } +} diff --git a/Services/Job/MyJob.cs b/Services/Job/MyJob.cs new file mode 100644 index 0000000..8868a72 --- /dev/null +++ b/Services/Job/MyJob.cs @@ -0,0 +1,36 @@ +using LangGuan.Command.Extension; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Quartz; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace LangGuan.Services.Job +{ + public class MyJob : IJob + { + public const string PlanId = ""; + public const string PlanName = ""; + private PlanService _planService; + public MyJob(PlanService planService) + { + _planService = planService; + } + /// + /// + /// + /// + /// + public async Task Execute(IJobExecutionContext context) + { + JobDataMap datamap = context.JobDetail.JobDataMap; + string id = datamap.GetString("PlanId"); + string PlanName = datamap.GetString("PlanName"); + Console.WriteLine($"定时任务当前时间:{DateTime.Now},计划名称 :{PlanName}传参:{id}--"); + await _planService.exec(id); + + } + } +} diff --git a/Services/PingService.cs b/Services/PingService.cs new file mode 100644 index 0000000..694531c --- /dev/null +++ b/Services/PingService.cs @@ -0,0 +1,89 @@ +using LangGuan.Command.Model.EntityModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Net.NetworkInformation; +using System.Threading; +using System.Threading.Tasks; + +namespace LangGuan.Services +{ + /// + /// ping service + /// + public class PingService + { + + private DeviceSerive _deviceSerive; + + /// + /// + /// + /// + public PingService(DeviceSerive deviceSerive) + { + _deviceSerive = deviceSerive; + + } + /// + /// + /// + public void CreatTask() + { + //5分钟执行一次 + + Timer myTimer = new Timer(new TimerCallback(Execute), null, 2000, 300000); + // Timer myTimer = new Timer(new TimerCallback(Execute), "ping service", 2000, 10000); + } + + /// + /// + /// + /// + public async void Execute(object b) + { + var deviceList = await _deviceSerive.GetAsync(); + if (deviceList.Any()) + { + foreach (var item in deviceList) + { + if (!string.IsNullOrEmpty(item.deviceIp)) + { + var ip = item.deviceIp.Split(":")[0]; + var res = await PingIp(ip); + item.state = res == true ? 1 : 0; + await _deviceSerive.UpdateState(item); + } + } + } + + Console.WriteLine("{0} ping running.", (string)b); + + } + /// + /// ping + /// + /// + /// + public async Task PingIp(string ip) + { + try + { + //Ping 实例对象; + Ping pingSender = new Ping(); + PingReply pingReply = await pingSender.SendPingAsync(ip); + if (pingReply.Status == IPStatus.Success) + { + return true; + } + } + catch (Exception) + { + + return false; + } + return false; + } + } +} diff --git a/Services/PlanService.cs b/Services/PlanService.cs new file mode 100644 index 0000000..07a86c0 --- /dev/null +++ b/Services/PlanService.cs @@ -0,0 +1,219 @@ +using LangGuan.Command.Extension; +using LangGuan.Command.Model; +using LangGuan.Command.Model.EntityModel; +using LangGuan.Services.Job; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Quartz; +using Quartz.Impl; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; + +namespace LangGuan.Services +{ + public class PlanService : BaseService + { + private GroupService _groupService; + private DeviceSerive _device; + private DeviceUsedService _deviceUsedService; + private PlcHelper _plcHelper; + public PlanService(IConfiguration config, + GroupService group, DeviceSerive deviceSerive, + DeviceUsedService deviceUsedService, PlcHelper plcHelper) : base(config, nameof(Plan)) + { + _groupService = group; + _device = deviceSerive; + _deviceUsedService = deviceUsedService; + _plcHelper = plcHelper; + } + /// + /// 取全部可用的plan + /// + /// + public async Task> GetList() + { + Expression> exp = filter => filter.disable == false; + return (await base.GetListWithExp(exp)).ToList(); + } + + /// + /// 更新 + /// + /// + /// + public async Task updatePlan(Plan input) + { + await base.UpdateAsync(input.Id, input); + if (input.disable) + { + // QuartzUtil.DeleteJob(input.Id); + } + else + { + // QuartzUtil.StartJobWithCron(input.Id, input.name, input.cron); + } + return new ApiResult() { code = 0 }; + } + /// + /// 取单条 + /// + /// + /// + public async Task findOne(string id) + { + var entity = await base.GetAsync(id); + var ids = await GetDeviceIds(new[] { entity.Id }); + var items = await _device.GetDeviceByIds(ids); + + return new ApiResult() { code = 0, data = new { plan = entity, deviceItems = items } }; + } + /// + /// + /// + /// + /// + public async Task remove(IEnumerable ids) + { + foreach (var item in ids) + { + var entity = await base.GetAsync(item); + await base.RemoveAsync(item); + await Reload(); + } + return new ApiResult() { code = 0 }; + } + /// + /// 新加plan + /// + /// + /// + public async Task AddPlan(Plan input) + { + var temp = await base.CreateAsync(input); + await Reload(); + return new ApiResult() + { + code = 0, + }; + } + /// + /// 更新 + /// + /// + /// + public async Task setdis(string id) + { + var entity = await base.GetAsync(id); + if (entity != null) + { + entity.disable = entity.disable == true ? false : true; + await base.UpdateAsync(id, entity); + await Reload(); + } + return new ApiResult() { code = 0 }; + } + /// + /// + /// + /// + /// + public async Task GetList(RqeustPaging request) + { + Expression> exp = filter => true; + return await base.GetPager(request, exp); + } + /// + /// 取所计划中所有的设备ids + /// + /// + /// + public async Task> GetDeviceIds(IEnumerable ids) + { + Expression> expression = filter => ids.Contains(filter.Id); + var items = (await base.GetListWithExp(expression)).ToList(); + List groupIds = new List(); + //取设备分组列表 + // var deviceIds = items.Select(s => s.deviceIds).ToList(); + items.Select(s => s.groups).ToList().ForEach(s => + { + groupIds.AddRange(s); + }); + //取设备 + var deviceIds = (await _groupService.GetDeviceIds(groupIds)).ToList(); + items.Select(s => s.deviceIds).ToList().ForEach(o => + { + deviceIds.AddRange(o); + }); + return deviceIds; + } + private async Task Reload() + { + IServiceCollection services = new ServiceCollection(); + Monitor monitor = null; + monitor = new Monitor(services.BuildServiceProvider()); + monitor.SetJobs(await GetList()); + } + /// + /// 判断是否在计划中 + /// + /// + /// + public async Task existsPlan(string id) + { + Expression> expression = filter => true; + List groupIds = new List(); + var items = (await base.GetListWithExp(expression)).ToList(); + items.Select(s => s.groups).ForEach(s => + { + groupIds.AddRange(s); + }); + var deviceIds = (await _groupService.GetDeviceIds(groupIds)).ToList(); + items.Select(s => s.deviceIds).ToList().ForEach(o => + { + deviceIds.AddRange(o); + }); + return deviceIds.Any(s => s == id); + } + + + /// + /// 执行 + /// + /// + /// + public async Task exec(string id) + { + var plan = await base.GetAsync(id); + var devices = await GetDeviceIds(new[] { id }); + foreach (var item in devices) + { + Console.WriteLine($"开启命令:---{id}"); + //开启远程控制,再发送命令 + var entity = await _device.GetAsync(item); + if (entity == null) + { + Console.WriteLine($"id:{item},没有找到该条数据"); + continue; + } + await _plcHelper.SetVal(entity.deviceIp, "V4000.1", true); + await _deviceUsedService.AddDeviceUsed(new DeviceUsed() + { + DeviceId = item, + Start = DateTime.Now, + End = DateTime.Now.AddSeconds(plan.execution), + }); + _ = Task.Run(async () => + { + await Task.Delay(plan.execution); + + Console.WriteLine($"关闭命令:---{id}"); + await _plcHelper.SetVal(entity.deviceIp, "V4000.1", false); + }); + } + } + + } +} diff --git a/Services/RadarItemService.cs b/Services/RadarItemService.cs new file mode 100644 index 0000000..012e76d --- /dev/null +++ b/Services/RadarItemService.cs @@ -0,0 +1,75 @@ +using LangGuan.Command.Model.EntityModel; +using Microsoft.Extensions.Configuration; +using MongoDB.Bson; +using MongoDB.Driver; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; + +namespace LangGuan.Services +{ + public class RadarItemService : BaseService + { + /// + /// + /// + /// + public RadarItemService(IConfiguration config) : base(config, nameof(RadarItems)) + { + } + /// + /// 批量新加 + /// + /// + /// + public async Task AddMany(IEnumerable radarItems) + { + await base.CreateManyAsync(radarItems); + } + /// + /// 取结果 + /// + /// + /// + public async Task> GetByPids(IEnumerable ids) + { + FilterDefinitionBuilder builderFilter = Builders.Filter; + FilterDefinition filter = builderFilter.In("pid", ids); + var result = await base.FindListyFilter(filter); + return result; + } + /// + /// 取单条 + /// + /// + /// + public async Task>> GetByPid(string id) + { + Expression> exp = num => num.pid == id; + var result = (await base.GetListWithExp(exp)).ToList().Select(s => s.Signal).ToList(); ; + return result; + } + /// + /// + /// + /// + /// + public async Task getcount(string id) + { + Expression> exp = num => num.pid == id; + var query = await base.GetListWithExp(exp); + var ids = query.Select(s => s.Id).ToList(); + if (ids.Count > 36) + { + ids = ids.Take(ids.Count - 36).ToList(); + foreach (var item in ids) + { + await base.RemoveAsync(item); + } + } + return query.Count(); + } + } +} diff --git a/Services/RadarService.cs b/Services/RadarService.cs new file mode 100644 index 0000000..b3a7449 --- /dev/null +++ b/Services/RadarService.cs @@ -0,0 +1,279 @@ +using AutoMapper; +using LangGuan.Command.AutoMapper; +using LangGuan.Command.Model; +using LangGuan.Command.Model.EntityModel; +using Microsoft.Extensions.Configuration; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; + +namespace LangGuan.Services +{ + /// + /// + /// + public class RadarService : BaseService + { + private readonly IMapper _mapper; + private DeviceSerive _deviceSerive; + private RadarItemService _radarItemService; + /// + /// + /// + /// + /// + /// + /// + public RadarService(IConfiguration config, IMapper mapper, + DeviceSerive deviceSerive, RadarItemService radarItemService) : base(config, nameof(Radar)) + { + _mapper = mapper; + _deviceSerive = deviceSerive; + _radarItemService = radarItemService; + } + + /// + /// 新加数据 + /// + /// + /// + public async Task Add(RadarView request) + { + var entity = _mapper.Map(request); + await _deviceSerive.Add(new Device() + { + deviceId = request.deviceId, + deviceIp = request.deviceIp, + state = 1 + }); + + //数据量过大,这里要分开存储 + var result = await base.CreateAsync(entity); + List items = new List(); + foreach (var item in request.Signal) + { + items.Add(new RadarItems() { pid = result.Id, Signal = item }); + } + await _radarItemService.AddMany(items); + return new ApiResult() { code = 0, msg = "" }; + } + /// + /// 首页用图 + /// + /// + /// + public async Task> Top(int n) + { + Expression> exp = filter => true; + var query = await base.GetListWithExp(exp); + var items = query.OrderByDescending(s => s.AcqTime).Take(n) + .Select(s => new + { + s.Id, + s.deviceId, + s.AcqTime, + s.DataPointNum, + s.DetectRange, + s.ExposureTime, + s.ScanAngle, + s.SystemBlind + }).ToList(); + List result = new List(); + Parallel.ForEach(items, async entry => + { + result.Add(new + { + datetime = entry.AcqTime.AddHours(8).ToString("yyyy-MM-dd HH mm "), + items = await ConvertData(entry.DetectRange, entry.DataPointNum, entry.SystemBlind, entry.Id) + }); + }); + return result; + } + /// + /// + /// + /// + /// + /// + public async Task GetList(DateTime start, DateTime end) + { + //Stopwatch stopwatch = new Stopwatch(); + //var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "radar", "Signal_2023.json"); + //stopwatch.Start(); + //FileStream fileStream = new FileStream(path, FileMode.Open); + //using (StreamReader reader = new StreamReader(fileStream)) + //{ + // string line = await reader.ReadToEndAsync(); + //} + //stopwatch.Stop(); + //Console.WriteLine("StreamReader:" + stopwatch.ElapsedMilliseconds); + //string txt = ""; + //byte[] allBytes = null; + //byte[] buffer = new byte[1024];//一个1K的缓冲字节容器 + //stopwatch.Reset(); + //stopwatch.Start(); + //using (MemoryStream ms = new MemoryStream()) + //{ + // using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) + // { + // int positon = 0; + // while ((positon = await fs.ReadAsync(buffer, 0, buffer.Length)) > 0) + // { + // await ms.WriteAsync(buffer, 0, positon); + // } + // allBytes = ms.ToArray(); + // } + + //} + //if (null != allBytes) + //{ + // //尝试将字节转成字符串 + // txt = System.Text.Encoding.UTF8.GetString(allBytes); + // // this.richTextBox_Result.Text = txt; + + //} + //var path1 = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "radar", DateTime.Now.ToString("yyyy-MM-dd") + ".txt"); + //using (FileStream fs = new FileStream(path1, FileMode.OpenOrCreate, FileAccess.Write)) + //{ + // await fs.WriteAsync(allBytes, 0, allBytes.Length); + //} + + //// string[] txtToArray = txt.Split('\r'); + //// ReadData_List.Add(txtToArray); + //stopwatch.Stop(); + //Console.WriteLine("MemoryStream" + stopwatch.ElapsedMilliseconds); + + end = end.AddDays(1); + Expression> exp = filter => filter.AcqTime >= start && filter.AcqTime < end; + var query = await base.GetListWithExp(exp); + var items = query.OrderByDescending(s => s.AcqTime) + .Select(s => new + { + s.Id, + s.deviceId, + s.AcqTime, + s.DataPointNum, + s.DetectRange, + s.ExposureTime, + s.ScanAngle, + s.SystemBlind + }).ToList(); + List result = new List(); + Parallel.ForEach(items, async entry => + { + result.Add(new + { + datetime = entry.AcqTime.ToString("yyyy-MM-dd HH mm "), + items = await ConvertData(entry.DetectRange, entry.DataPointNum, entry.SystemBlind, entry.Id) + }); + }); + //var result = items.Select(async s => new + //{ + // datetime = s.AcqTime.AddHours(8).ToString("yyyy-MM-dd HH mm "), + // items = await ConvertData(s.DetectRange, s.DataPointNum, s.SystemBlind, s.Id) + //}).ToList(); + + return new ApiResult() + { + code = 0, + data = new { items = result } + }; + } + private async Task> ConvertData(double rang, double DataPointNum, double SystemBlind, string id) + { + + // var count = await _radarItemService.getcount(id); + List radarModels = new List(); + //里面先取度数 + //取1000米的数, 1000/3 + List> vs = new List>(); + vs = await _radarItemService.GetByPid(id); + + + //角度, + var t1 = convertangle(); + var t2 = convertDistance(rang, SystemBlind); + for (int i = 0; i < t1.Length; i++) + { + var temp = (vs[i]).ToList(); + int m = 0; + foreach (var v in t2) + { + //如果有第一个,就直接取, + m = v == SystemBlind ? m : (int)((v - SystemBlind) / 3); + m = m == 0 ? m : m - 1; + radarModels.Add(new radarModel() + { + angle = t1[i], + distance = v, + value = Math.Round(m > temp.Count() ? temp[temp.Count() - 1] : temp[m], 2) + }); + } + } + return radarModels; + } + private int[] convertangle() + { + List reuslt = new List(); + int i = 0; + while (i < 360) + { + reuslt.Add(i); + i = i + 10; + + } + return reuslt.ToArray(); + + } + /// + /// 计算圈数 + /// + /// + /// + /// + private int[] convertDistance(double DetectRange, double SystemBlind) + { + List reuslt = new List(); + reuslt.Add((int)SystemBlind); + var d1 = DetectRange - SystemBlind; + int n = 1; + while (d1 - 1000 > 0) + { + if (n == 1) + { + reuslt.Add(1000); + } + else + { + reuslt.Add(n * 1000); + } + d1 = d1 - 1000; + n++; + } + reuslt.Add((int)DetectRange); + return reuslt.ToArray(); + } + /// + /// 返回结果 + /// + public class radarModel + { + /// + /// 角度 + /// + public int angle { get; set; } + /// + /// 距离 + /// + public int distance { get; set; } + /// + /// 结果 + /// + public double value { get; set; } + } + } +} diff --git a/Services/VideoService.cs b/Services/VideoService.cs new file mode 100644 index 0000000..8f35c1c --- /dev/null +++ b/Services/VideoService.cs @@ -0,0 +1,90 @@ +using LangGuan.Command.Model; +using LangGuan.Command.Model.EntityModel; +using Microsoft.Extensions.Configuration; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; + +namespace LangGuan.Services +{ + /// + /// + /// + public class VideoService : BaseService