添加项目文件。

This commit is contained in:
yanghongwei 2024-07-24 21:30:21 +08:00
parent 8d58753da3
commit 1fc11e499b
82 changed files with 9968 additions and 0 deletions

12
.config/dotnet-tools.json Normal file
View File

@ -0,0 +1,12 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "7.0.11",
"commands": [
"dotnet-ef"
]
}
}
}

25
.dockerignore Normal file
View File

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

View File

@ -0,0 +1,26 @@
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LangGuan.Command.AutoMapper
{
/// <summary>
/// AutoMapperConfig
/// </summary>
public class AutoMapperConfig
{
/// <summary>
///
/// </summary>
/// <returns></returns>
public static MapperConfiguration RegisterMappings()
{
return new MapperConfiguration(cfg =>
{
cfg.AddProfile(new CustomProfile());
});
}
}
}

View File

@ -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
{
/// <summary>
/// CustomProfile
/// </summary>
public class CustomProfile : Profile
{
/// <summary>
/// 配置构造函数,用来创建关系映射
/// </summary>
public CustomProfile()
{
//第一个参数是原对象,第二个是目的对象
CreateMap<RadarView, Radar>();
//CreateMap<AlertSettingRequest, AlertSettingModel>();
}
}
}

View File

@ -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<QuartzUtil>();
services.AddTransient<PlanService>();
Monitor quartz = null;
services.AddSingleton<Monitor>();
quartz = new Monitor(services.BuildServiceProvider());
using (var scope = services.BuildServiceProvider())
{
var myService = scope.GetRequiredService<PlanService>();
var list = myService.GetList().GetAwaiter().GetResult();
if (list.Any())
{
quartz.SetJobs(list);
_ = quartz.StartAsync();
}
}
}
}
}

View File

@ -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
{
/// <summary>
/// 写数据
/// </summary>
/// <param name="ip"></param>
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;
}
/// <summary>
/// SetVal
/// </summary>
/// <param name="ip"></param>
/// <param name="key"></param>
/// <param name="val"></param>
/// <returns></returns>
public async Task<bool> 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;
}
/// <summary>
/// GetVal
/// </summary>
/// <param name="ip"></param>
/// <param name="key"></param>
/// <param name="val"></param>
/// <returns></returns>
public async Task<bool> 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<string> 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 "";
}
/// <summary>
/// 俯仰角度
/// </summary>
/// <param name="ip"></param>
/// <param name="key"></param>
/// <returns></returns>
public async Task<string> 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<object> 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;
}
}
}

View File

@ -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() { }
/// <summary>
/// 设定设备值
/// </summary>
/// <param name="ip"></param>
/// <param name="key"></param>
/// <param name="val"></param>
/// <returns></returns>
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<Int16>(key, val); // set a bit
var result = await plc.GetValue<Int16>(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<bool>("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<Int16>(key, val); // set a bit
var result = await plc.GetValue<Int16>(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<bool>("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<bool>("DB2.DBX0.4", true); // set a bit
await plc.SetValue<int>(key, val); // set a bit
// var bit = await plc.GetValue<int>("DB2.int4"); // get a bit
// create a nofication for data change in the plc
//var notification = plc.CreateNotification<bool>("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();
}
}
/// <summary>
/// 取值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="ip"></param>
/// <param name="key"></param>
/// <returns></returns>
public async Task<T> GetVal<T>(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<bool>("DB2.DBX0.4", true); // set a bit
var bit = await plc.GetValue<T>(key); // get a bit
return bit;
}
}
}
}

View File

@ -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
{
/// <summary>
///
/// </summary>
public static class SocketExtension
{
/// <summary>
///
/// </summary>
/// <param name="services"></param>
public static void AddSocketService(this IServiceCollection services)
{
// services.AddSingleton<MQTTService>();
services.AddScoped<HJ212SocketServer>();
services.AddScoped<PingService>();
IServiceProvider serviceProvider = services.BuildServiceProvider();
_ = serviceProvider.GetService<HJ212SocketServer>().Start();
serviceProvider.GetService<PingService>().CreatTask();
}
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LangGuan.Command.Model
{
/// <summary>
/// Api返回结果
/// </summary>
public class ApiResult
{
/// <summary>
/// code=0成功。1失败
/// </summary>
public int code { get; set; }
/// <summary>
/// 结果
/// </summary>
public object data { get; set; }
/// <summary>
/// 消息
/// </summary>
public string msg { get; set; }
}
}

View File

@ -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
{
/// <summary>
/// base model
/// </summary>
public class BaseModel
{
/// <summary>
/// //标记主键
/// </summary>
[BsonId]
[BsonRepresentation(BsonType.ObjectId)] //参数类型 无需赋值
public string Id { get; set; }
/// <summary>
/// //指明数据库中字段名为CreateDateTime
/// </summary>
[BsonElement(nameof(CreateDateTime))] //指明数据库中字段名为CreateDateTime
public DateTime CreateDateTime { get; set; }
/// <summary>
/// 标记删除
/// </summary>
//[BsonElement(nameof(IsDelete))]
public bool IsDelete { get; set; }
/// <summary>
/// basemodel
/// </summary>
public BaseModel()
{
CreateDateTime = DateTime.Now;
IsDelete = false;
}
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LangGuan.Command.Model.EntityModel
{
/// <summary>
/// 报警
/// </summary>
public class Alert : BaseModel
{
/// <summary>
/// deviceId
/// </summary>
public string deviceId { get; set; }
/// <summary>
/// 别名
/// </summary>
public string NickName { get; set; }
/// <summary>
/// 内容
/// </summary>
public string content { get; set; }
}
}

View File

@ -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
{
/// <summary>
/// 设备信息
/// </summary>
public class Device : BaseModel
{
/// <summary>
/// deviceIp
/// </summary>
public string deviceIp { get; set; }
/// <summary>
/// 设备标识
/// </summary>
public string deviceId { get; set; }
[BsonRepresentation(BsonType.String)]
/// <summary>
/// 经
/// </summary>
public string lng { get; set; }
[BsonRepresentation(BsonType.String)]
/// <summary>
/// 续
/// </summary>
public string lat { get; set; }
/// <summary>
/// 别名
/// </summary>
public string NickName { get; set; }
/// <summary>
/// 角度
/// </summary>
public double angle { get; set; }
/// <summary>
/// 状态 0离线1在线
/// </summary>
public int state { get; set; }
/// <summary>
/// 是否分配组
/// </summary>
public bool InGroup { get; set; }
}
}

View File

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

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LangGuan.Command.Model.EntityModel
{
/// <summary>
///
/// </summary>
public class Employee : BaseModel
{
/// <summary>
/// 登陆名
/// </summary>
public string Account { get; set; }
/// <summary>
/// pwd
/// </summary>
public string Pwd { get; set; }
/// <summary>
/// 别名
/// </summary>
public string NickName { get; set; }
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LangGuan.Command.Model.EntityModel
{
/// <summary>
///
/// </summary>
public class Group : BaseModel
{
/// <summary>
/// 分组名称
/// </summary>
public string GroupName { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; }
/// <summary>
/// 设备列表
/// </summary>
public IEnumerable<string> DeviceIds { get; set; }
}
}

View File

@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LangGuan.Command.Model.EntityModel
{
/// <summary>
///
/// </summary>
public class HJ212 : BaseModel
{
/// <summary>
/// 设备ID
/// </summary>
public string deviceId { get; set; }
/// <summary>
/// PM2.5浓度
/// </summary>
public double a34004 { get; set; }
/// <summary>
/// PM10浓度
/// </summary>
public double a34002 { get; set; }
/// <summary>
/// TSP浓度
/// </summary>
public double a34001 { get; set; }
/// <summary>
/// 温度
/// </summary>
public double a01001 { get; set; }
/// <summary>
/// 湿度
/// </summary>
public double a01002 { get; set; }
/// <summary>
/// 大气压
/// </summary>
public double a01006 { get; set; }
/// <summary>
/// 风速
/// </summary>
public double a01007 { get; set; }
/// <summary>
/// 风向
/// </summary>
public double a01008 { get; set; }
}
}

View File

@ -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; }
/// <summary>
/// 组列表
/// </summary>
public IEnumerable<string> groups { get; set; }
/// <summary>
/// 设备列表
/// </summary>
public IEnumerable<string> deviceIds { get; set; }
/// <summary>
/// 执行计划
/// </summary>
public string cron { get; set; }
/// <summary>
/// 执行时长
/// </summary>
public int execution { get; set; }
/// <summary>
/// 是否启用
/// </summary>
public bool disable { get; set; }
}
}

View File

@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LangGuan.Command.Model.EntityModel
{
/// <summary>
/// 雷达数据
/// </summary>
public class Radar : BaseModel
{
/// <summary>
///设备id
/// </summary>
public string deviceId { get; set; }
/// <summary>
///设备id
/// </summary>
public string deviceIp { get; set; }
/// <summary>
/// 采集时间
/// </summary>
public DateTime AcqTime { get; set; }
/// <summary>
/// 曝光时间
/// </summary>
public int ExposureTime { get; set; }
/// <summary>
/// 系统盲区
/// </summary>
public double SystemBlind { get; set; }
/// <summary>
/// 探测距离
/// </summary>
public double DetectRange { get; set; }
/// <summary>
/// 数据点个数
/// </summary>
public double DataPointNum { get; set; }
/// <summary>
/// ScanAngle
/// </summary>
public IEnumerable<IEnumerable<double>> ScanAngle { get; set; }
}
/// <summary>
///
/// </summary>
public class RadarItems : BaseModel
{
/// <summary>
/// 父ID
/// </summary>
public string pid { get; set; }
/// <summary>
/// 结果
/// </summary>
public IEnumerable<double> Signal;
}
/// <summary>
///
/// </summary>
public class RadarView
{
/// <summary>
///设备id
/// </summary>
public string deviceId { get; set; }
/// <summary>
///
/// </summary>
public string deviceIp { get; set; }
/// <summary>
/// 采集时间
/// </summary>
public DateTime AcqTime { get; set; }
/// <summary>
/// 曝光时间
/// </summary>
public int ExposureTime { get; set; }
/// <summary>
/// 系统盲区
/// </summary>
public double SystemBlind { get; set; }
/// <summary>
/// 探测距离
/// </summary>
public double DetectRange { get; set; }
/// <summary>
/// 数据点个数
/// </summary>
public double DataPointNum { get; set; }
/// <summary>
/// ScanAngle
/// </summary>
public IEnumerable<IEnumerable<double>> ScanAngle { get; set; }
/// <summary>
/// Signal
/// </summary>
public IEnumerable<IEnumerable<double>> Signal { get; set; }
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LangGuan.Command.Model.EntityModel
{
/// <summary>
/// 视频
/// </summary>
public class Video : BaseModel
{
/// <summary>
/// 组名
/// </summary>
public string GroupName { get; set; }
/// <summary>
/// 视频源
/// </summary>
public List<string> Url { get; set; }
}
}

View File

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LangGuan.Command.Model
{
/// <summary>
/// 导出
/// </summary>
public class ExportModel
{
/// <summary>
/// 设备ID
/// </summary>
public string deviceId { get; set; }
/// <summary>
/// PM2.5浓度
/// </summary>
public double a34004 { get; set; }
/// <summary>
/// PM10浓度
/// </summary>
public double a34002 { get; set; }
/// <summary>
/// TSP浓度
/// </summary>
public double a34001 { get; set; }
/// <summary>
/// 温度
/// </summary>
public double a01001 { get; set; }
/// <summary>
/// 湿度
/// </summary>
public double a01002 { get; set; }
/// <summary>
/// 大气压
/// </summary>
public double a01006 { get; set; }
/// <summary>
/// 风速
/// </summary>
public double a01007 { get; set; }
/// <summary>
/// 风向
/// </summary>
public double a01008 { get; set; }
/// <summary>
/// 时间
/// </summary>
public string createtime { get; set; }
}
}

View File

@ -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
{
/// <summary>
/// 分组名称
/// </summary>
public string GroupName { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; }
public List<Device> items { get; set; }
}
}

42
Command/Model/Paging.cs Normal file
View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LangGuan.Command.Model
{
/// <summary>
/// 分页数据
/// </summary>
public class Paging
{
///<summary>
/// Gets or sets CurrentPageIndex.
///</summary>
public int CurrentPageIndex { get; set; }
///<summary>
/// Gets or sets PageCount.
///</summary>
public int Total { get; set; }
/// <summary>
/// data
/// </summary>
public List<object> Items { get; set; }
}
/// <summary>
/// 分页参数
/// </summary>
public class RqeustPaging
{
///<summary>
/// Gets or sets CurrentPageIndex.
///</summary>
public int current { get; set; } = 1;
///<summary>
/// Gets or sets PageCount.
///</summary>
public int pageSize { get; set; } = 10;
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LangGuan.Command.Model.RequestModel
{
/// <summary>
/// 条件
/// </summary>
public class AutoReport
{
/// <summary>
/// 开始
/// </summary>
public DateTime? begin { get; set; }
/// <summary>
/// 结束
/// </summary>
public DateTime? end { get; set; }
/// <summary>
/// PM2.5浓度
/// </summary>
public double a34004 { get; set; }
/// <summary>
/// PM10浓度
/// </summary>
public double a34002 { get; set; }
/// <summary>
/// TSP浓度
/// </summary>
public double a34001 { get; set; }
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LangGuan.Command.Model.RequestModel
{
/// <summary>
/// 登陆
/// </summary>
public class RequestLogin
{
/// <summary>
/// Account
/// </summary>
public string Account { get; set; }
/// <summary>
/// Pwd
/// </summary>
public string Pwd { get; set; }
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LangGuan.Command.Model.RequestModel
{
/// <summary>
///
/// </summary>
public class RequestUpdateAccount
{
/// <summary>
/// Account
/// </summary>
public string Account { get; set; }
/// <summary>
/// Pwd
/// </summary>
public string Pwd { get; set; }
/// <summary>
/// NewPwd
/// </summary>
public string NewPwd { get; set; }
}
}

View File

@ -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
{
/// <summary>
/// scoket
/// </summary>
public class SocketModel
{
/// <summary>
/// 缓冲器
/// </summary>
private byte[] result = new byte[1024];
/// <summary>
/// 最大连接数
/// </summary>
private int maxClientCount;
/// <summary>
/// 服务IP地址
/// </summary>
private string ip;
/// <summary>
/// 服务端口号
/// </summary>
private int port;
// 编码
// private string code;
/// <summary>
/// 客户端列表
/// </summary>
private List<Socket> ClientSockets;
/// <summary>
/// IP终端
/// </summary>
private IPEndPoint ipEndPoint;
/// <summary>
/// 服务端Socket
/// </summary>
private Socket ServerSocket;
/// <summary>
/// 当前客户端Socket
/// </summary>
private Socket ClientSocket;
}
}

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LangGuan.Command.Model
{
/// <summary>
///
/// </summary>
public class columnView
{
/// <summary>
///
/// </summary>
public string hour { get; set; }
/// <summary>
/// a34004=PM2.5浓度,a34002=PM10,a34001=tsp浓度
/// </summary>
public string type { get; set; }
public double value { get; set; }
}
}

View File

@ -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
{
/// <summary>
/// 版本控制
/// </summary>
public class SwaggerConfigureOptions : IConfigureOptions<SwaggerGenOptions>
{
private readonly IApiVersionDescriptionProvider _provider;
/// <summary>
/// provider
/// </summary>
/// <param name="provider"></param>
public SwaggerConfigureOptions(IApiVersionDescriptionProvider provider) => _provider = provider;
/// <summary>
/// config
/// </summary>
/// <param name="options"></param>
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(),
});
}
}
}
}

View File

@ -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;
/// <summary>
///
/// </summary>
/// <param name="alertService"></param>
public AlertController(AlertService alertService)
{
_alertService = alertService;
}
/// <summary>
/// 列表
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpGet("list")]
public async Task<IActionResult> list([FromQuery] RqeustPaging request)
{
var result = await _alertService.GetList(request);
return Ok(result);
}
}
}

View File

@ -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
{
/// <summary>
///
/// </summary>
[ApiVersion("1.0")]
[Route("api/[controller]/v{version:apiVersion}")]
[ApiController]
public class DataController : ControllerBase
{
private Hj212Service _hj212Service;
/// <summary>
///
/// </summary>
/// <param name="hj212Service"></param>
public DataController(Hj212Service hj212Service)
{
_hj212Service = hj212Service;
}
/// <summary>
/// 导出
/// </summary>
/// <returns></returns>
[HttpGet("export")]
public async Task<IActionResult> 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");
}
/// <summary>
/// 列表数据
/// </summary>
/// <returns></returns>
[HttpGet("list")]
public async Task<IActionResult> list(DateTime start, DateTime end, [FromQuery] RqeustPaging request)
{
var result = await _hj212Service.GetPageData(start, end, request);
return Ok(result);
}
/// <summary>
///实时监测
/// </summary>
/// <returns></returns>
[HttpGet("realtime")]
public async Task<IActionResult> realtime()
{
var result = await _hj212Service.Realtime();
return Ok(result);
}
/// <summary>
///自动报表导出
/// </summary>
/// <returns></returns>
[HttpGet("autoreport")]
public async Task<IActionResult> 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);
}
/// <summary>
///自动报表结果
/// </summary>
/// <returns></returns>
[HttpGet("autoReportResult")]
public async Task<IActionResult> autoReportResult([FromQuery] AutoReport request)
{
var result = await _hj212Service.autoReportResult(request);
return Ok(result);
}
}
}

View File

@ -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
{
/// <summary>
///
/// </summary>
[ApiVersion("1.0")]
[Route("api/[controller]/v{version:apiVersion}")]
[ApiController]
public class DeviceController : ControllerBase
{
private DeviceSerive _deviceSerive;
private PlanService _planService;
/// <summary>
///
/// </summary>
/// <param name="deviceSerive"></param>
public DeviceController(DeviceSerive deviceSerive, PlanService planService)
{
_deviceSerive = deviceSerive;
_planService = planService;
}
/// <summary>
/// Add
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> Add(Device input)
{
var result = await _deviceSerive.CreateAsync(input);
return Ok(new ApiResult() { code = 0 });
}
/// <summary>
/// 删除
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[HttpPost("remove")]
public async Task<IActionResult> remove(IEnumerable<string> ids)
{
foreach (var item in ids)
{
await _deviceSerive.RemoveAsync(item);
}
return Ok(new ApiResult() { code = 0 });
}
/// <summary>
/// 列表
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpGet("list")]
public async Task<IActionResult> list([FromQuery] RqeustPaging request)
{
var result = await _deviceSerive.GetList(request);
return Ok(result);
}
/// <summary>
/// 更新
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("update")]
public async Task<IActionResult> update(Device request)
{
var result = await _deviceSerive.Update(request);
return Ok(result);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
[HttpGet("GetListByGroupState")]
public async Task<IActionResult> GetListByGroupState(bool Ingroup)
{
var result = await _deviceSerive.GetlistByGroupState(Ingroup);
return Ok(result);
}
/// <summary>
/// 设备角度调整
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpPost("SetVal")]
public async Task<IActionResult> SetVal(KeyValuePair<string, int> input)
{
return Ok(new ApiResult() { code = 0, msg = "" });
}
/// <summary>
/// 启动
/// </summary>
/// <param name="id"></param>
/// <param name="point">true摇摆false定点</param>
/// <returns></returns>
[HttpGet("start")]
public async Task<IActionResult> 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<IActionResult> stop(string id)
{
var result = await _deviceSerive.stopDevice(id);
return Ok(new ApiResult() { code = 0, msg = "", data = result });
}
/// <summary>
/// 判断设备是否在计划中
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("existPlan")]
public async Task<IActionResult> existPlan(string id)
{
var result = await _planService.existsPlan(id);
return Ok(new ApiResult() { code = 0, msg = "", data = result });
}
[HttpGet("getval")]
public async Task<IActionResult> getval(string id)
{
var result = await _deviceSerive.getval(id);
return Ok(new ApiResult() { code = 0, msg = "", data = result });
}
[HttpGet("setval")]
public async Task<IActionResult> setval(string id, bool val)
{
var result = await _deviceSerive.setval(id, val);
return Ok(new ApiResult() { code = 0, msg = "" });
}
[HttpGet("readkey")]
public async Task<IActionResult> 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<IActionResult> writekey(string ip, string key, int val)
{
await _deviceSerive.wrirekey(ip, key, val);
return Ok(new ApiResult() { code = 0, msg = "" });
}
/// <summary>
/// 设置上下俯仰,t=1上t=2下val=true,开始false停止
/// </summary>
/// <param name="id"></param>
/// <param name="t">1上2下</param>
/// <param name="val"></param>
/// <returns></returns>
[HttpGet("upordown")]
public async Task<IActionResult> upordown(string id, int t = 1, bool val = true)
{
await _deviceSerive.setUporDown(id, t, val);
return Ok(new ApiResult() { code = 0, msg = "" });
}
/// <summary>
/// 归零
/// </summary>
/// <param name="id"></param>
/// <param name="val"></param>
/// <returns></returns>
[HttpGet("zero")]
public async Task<IActionResult> Zero(string id, bool val = true)
{
await _deviceSerive.Zero(id, val);
return Ok(new ApiResult() { code = 0, msg = "" });
}
/// <summary>
/// 获取上下角度
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("getupordown")]
public async Task<IActionResult> getupordown(string id)
{
var result = await _deviceSerive.GetUpOrDown(id);
return Ok(new ApiResult() { code = 0, msg = "", data = result });
}
/// <summary>
/// 左右,跟上下一样
/// </summary>
/// <param name="id"></param>
/// <param name="t"></param>
/// <param name="val"></param>
/// <returns></returns>
[HttpGet("leftorright")]
public async Task<IActionResult> leftorright(string id, int t = 1, bool val = true)
{
await _deviceSerive.setLeftorRight(id, t, val);
return Ok(new ApiResult() { code = 0, msg = "" });
}
/// <summary>
/// 获取角度
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("getleftorright")]
public async Task<IActionResult> getleftorright(string id)
{
var result = await _deviceSerive.GetLeftOrRight(id);
return Ok(new ApiResult() { code = 0, msg = "", data = result });
}
[HttpGet("cron")]
public async Task<IActionResult> cron(string cron)
{
var result = ExpressionDescriptor.GetDescription(cron, new Options() { Locale = "zh-CN" });
return Ok(new ApiResult() { code = 0, msg = "", data = result });
}
}
}

View File

@ -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;
}
/// <summary>
/// 测试数据
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> Test(DeviceUsed input)
{
await _deviceUsedService.AddDeviceUsed(input);
return Ok();
}
}
}

View File

@ -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
{
/// <summary>
///
/// </summary>
[ApiVersion("1.0")]
[Route("api/[controller]/v{version:apiVersion}")]
[ApiController]
public class EmployeeController : ControllerBase
{
private readonly ILogger<EmployeeController> _logger;
private readonly EmployeeService _employee;
/// <summary>
///
/// </summary>
/// <param name="employee"></param>
public EmployeeController(EmployeeService employee)
{
_employee = employee;
}
/// <summary>
/// 登录
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("login")]
public async Task<IActionResult> Login(RequestLogin request)
{
request.Pwd = ToMD5(request.Pwd);
var result = await _employee.Login(request.Account, request.Pwd);
return Ok(result);
}
/// <summary>
/// 列表查询
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpGet("list")]
public async Task<IActionResult> Check([FromQuery] RqeustPaging request)
{
var result = await _employee.GetList(request);
return Ok(result);
}
/// <summary>
/// 新加
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("add")]
public async Task<IActionResult> Add(Employee request)
{
var result = await _employee.Add(request.Account, ToMD5(request.Pwd), request.NickName);
return Ok(result);
}
/// <summary>
/// 修改密码
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("Update")]
public async Task<IActionResult> 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);
}
/// <summary>
/// 删除
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[HttpDelete("remove")]
public async Task<IActionResult> remove(IEnumerable<string> 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);//将加密后的字节数组转换为加密字符串
}
}
}

View File

@ -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;
}
/// <summary>
/// 列表
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpGet("list")]
public async Task<IActionResult> list([FromQuery] RqeustPaging request)
{
var result = await _serive.GetList(request);
return Ok(result);
}
/// <summary>
/// 取单条
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> FindOne(string Id)
{
var result = await _serive.FindOne(Id);
return Ok(result);
}
/// <summary>
/// 更新
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("update")]
public async Task<IActionResult> update(Group request)
{
var result = await _serive.update(request);
return Ok(result);
}
/// <summary>
/// 新加
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost("add")]
public async Task<IActionResult> add(Group input)
{
var result = await _serive.Add(input);
return Ok(result);
}
/// <summary>
/// 删除
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[HttpDelete("remove")]
public async Task<IActionResult> remove(IEnumerable<string> ids)
{
var result = await _serive.remove(ids);
return Ok(result);
}
}
}

View File

@ -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
{
/// <summary>
///
/// </summary>
[ApiVersion("1.0")]
[Route("api/[controller]/v{version:apiVersion}")]
[ApiController]
public class HomeController : ControllerBase
{
private readonly ILogger<HomeController> _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;
/// <summary>
///
/// </summary>
/// <param name="logger"></param>
/// <param name="deviceSerive"></param>
/// <param name="alertService"></param>
/// <param name="videoService"></param>
/// <param name="hj212Service"></param>
/// <param name="radarService"></param>
/// <param name="memoryCache"></param>
public HomeController(ILogger<HomeController> 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;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
[HttpGet("view")]
public async Task<IActionResult> 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);
}
/// <summary>
///
/// </summary>
public class columnView
{
public string hour { get; set; }
/// <summary>
/// a34004=PM2.5浓度,a34002=PM10,a34001=tsp浓度
/// </summary>
public string type { get; set; }
public double value { get; set; }
}
}
}

View File

@ -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;
}
/// <summary>
///
/// </summary>
/// <param name="plan"></param>
/// <returns></returns>
[HttpPost("add")]
public async Task<IActionResult> add(Plan plan)
{
var result = await _planService.AddPlan(plan);
return Ok(result);
}
/// <summary>
/// 启用,禁用状态变更
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("setdis")]
public async Task<IActionResult> updatedis(string id)
{
var result = await _planService.setdis(id);
return Ok(result);
}
/// <summary>
/// 更新
/// </summary>
/// <returns></returns>
[HttpPost("update")]
public async Task<IActionResult> update(Plan input)
{
var result = await _planService.updatePlan(input);
return Ok(result);
}
/// <summary>
/// remove
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[HttpDelete("remove")]
public async Task<IActionResult> remove(IEnumerable<string> ids)
{
var result = await _planService.remove(ids);
return Ok(result);
}
/// <summary>
/// 列表
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpGet("list")]
public async Task<IActionResult> list([FromQuery] RqeustPaging request)
{
var result = await _planService.GetList(request);
return Ok(result);
}
/// <summary>
///findone
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> findeOne(string id)
{
var result = await _planService.findOne(id);
return Ok(result);
}
}
}

View File

@ -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;
/// <summary>
///
/// </summary>
/// <param name="radarService"></param>
public RadarController(RadarService radarService)
{
_radarService = radarService;
}
/// <summary>
/// 接收客户端雷达 数据
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("receive")]
public async Task<IActionResult> 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);
}
/// <summary>
///
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
[HttpGet("list")]
public async Task<IActionResult> 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);
}
}
}

View File

@ -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;
/// <summary>
///
/// </summary>
/// <param name="videoService"></param>
public VideoController(VideoService videoService)
{
_videoService = videoService;
}
//[HttpPost]
//public async Task<IActionResult> 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);
//}
/// <summary>
/// 列表
/// </summary>
/// <returns></returns>
[HttpGet("list")]
public async Task<IActionResult> list([FromQuery] RqeustPaging request)
{
var result = await _videoService.GetList(request);
return Ok(result);
}
/// <summary>
/// 新加
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("add")]
public async Task<IActionResult> Add(Video request)
{
var result = await _videoService.Add(request);
return Ok(result);
}
/// <summary>
/// /更新
/// </summary>
/// <returns></returns>
[HttpPost("update")]
public async Task<IActionResult> update(Video video)
{
var result = await _videoService.Update(video);
return Ok(result);
}
/// <summary>
/// 批量删除,传数组
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[HttpDelete("remove")]
public async Task<IActionResult> removoe(IEnumerable<string> ids)
{
if (ids.Any())
{
foreach (var item in ids)
{
await _videoService.RemoveAsync(item);
}
}
return Ok(new ApiResult() { code = 0 });
}
}
}

View File

@ -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<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> 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();
}
}
}

21
Dockerfile Normal file
View File

@ -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"]

48
LangGuan.csproj Normal file
View File

@ -0,0 +1,48 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerfileContext>.</DockerfileContext>
<UserSecretsId>8c2d4e67-f295-4332-a573-9c3d12228a49</UserSecretsId>
</PropertyGroup>
<!--生成时包含xml文件-->
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DocumentationFile>D:\work\LangGuan\LangGuan.xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="11.0.1" />
<PackageReference Include="CronExpressionDescriptor" Version="2.21.0" />
<PackageReference Include="HslCommunication" Version="11.7.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.32" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="5.0.0" />
<PackageReference Include="MongoDB.Bson" Version="2.14.0" />
<PackageReference Include="MongoDB.Driver" Version="2.14.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="NPOI" Version="2.5.6" />
<PackageReference Include="Npoi.Mapper" Version="3.5.1" />
<PackageReference Include="Quartz.Extensions.Hosting" Version="3.7.0" />
<PackageReference Include="Sharp7" Version="1.1.84" />
<PackageReference Include="Sharp7.Rx" Version="1.1.8" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="IceCoffee.FastSocket" Version="1.0.3" />
</ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\model\" />
<Folder Include="wwwroot\radar\" />
</ItemGroup>
<ItemGroup>
<None Update="Dockerfile">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

25
LangGuan.sln Normal file
View File

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

2403
LangGuan.xml Normal file

File diff suppressed because it is too large Load Diff

View File

@ -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
{
/// <summary>
/// 异常处理中间件
/// </summary>
public class CustomerExceptionFilter : IAsyncExceptionFilter
{
/// <summary>
/// 日志
/// </summary>
public ILogger _logger;
/// <summary>
/// 构参
/// </summary>
/// <param name="loggerFactory"></param>
public CustomerExceptionFilter(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<CustomerExceptionFilter>();
}
/// <summary>
/// 重写
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
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;
}
}
}

View File

@ -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
{
/// <summary>
/// 日志中间件
/// </summary>
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestLoggingMiddleware> _logger;
/// <summary>
/// 计时器
/// </summary>
private Stopwatch _stopwatch;
/// <summary>
/// 构建中间件
/// </summary>
/// <param name="next"></param>
/// <param name="logger"></param>
public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger)
{
_next = next;
_logger = logger;
}
/// <summary>
/// task
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
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;
});
}
/// <summary>
/// 获取响应内容
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public async Task<string> 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;
}
}
}
}

27
Program.cs Normal file
View File

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

View File

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

79
Services/AlertService.cs Normal file
View File

@ -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
{
/// <summary>
///
/// </summary>
public class AlertService : BaseService<Alert>
{
/// <summary>
///
/// </summary>
/// <param name="config"></param>
public AlertService(IConfiguration config) : base(config, nameof(Alert))
{
}
/// <summary>
/// 取前20
/// </summary>
/// <param name="top"></param>
/// <returns></returns>
public async Task<object> GetToplist(int top = 20)
{
Expression<Func<Alert, bool>> 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;
}
/// <summary>
///新加一条数据
/// </summary>
/// <param name="alert"></param>
/// <returns></returns>
public async Task<bool> Add(Alert alert)
{
await base.CreateAsync(alert);
return true;
}
/// <summary>
/// 分页数据
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<ApiResult> GetList(RqeustPaging request)
{
request.pageSize = request.pageSize == 0 ? 10 : request.pageSize;
Expression<Func<Alert, bool>> 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 }
};
}
}
}

204
Services/BaseService.cs Normal file
View File

@ -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
{
/// <summary>
/// baseservice
/// </summary>
/// <typeparam name="T"></typeparam>
public class BaseService<T> where T : BaseModel
{
private readonly IMongoCollection<T> _collection; //数据表操作对象
/// <summary>
/// 构造
/// </summary>
/// <param name="config"></param>
/// <param name="tableName"></param>
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<T>(tableName);
}
/// <summary>
/// 获取所有
/// </summary>
/// <returns></returns>
public List<T> Get()
{
return _collection.Find(T => true).ToList();
}
/// <summary>
/// 获取单个
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public T Get(string id)
{
return _collection.Find<T>(T => T.Id == id).FirstOrDefault();
}
/// <summary>
/// 创建
/// </summary>
/// <param name="T"></param>
/// <returns></returns>
public T Create(T T)
{
_collection.InsertOne(T);
return T;
}
/// <summary>
/// 更新
/// </summary>
/// <param name="id"></param>
/// <param name="TIn"></param>
public void Update(string id, T TIn)
{
_collection.ReplaceOne(T => T.Id == id, TIn);
}
/// <summary>
/// 删除
/// </summary>
/// <param name="TIn"></param>
public void Remove(T TIn)
{
_collection.DeleteOne(T => T.Id == TIn.Id);
}
/// <summary>
/// 根据id删除
/// </summary>
/// <param name="id"></param>
public void Remove(string id)
{
_collection.DeleteOne(T => T.Id == id);
}
#region
/// <summary>
/// 取列表
/// </summary>
/// <returns></returns>
public async Task<List<T>> GetAsync()
{
return await _collection.Find(T => true).ToListAsync();
}
/// <summary>
/// 取单条
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<T> GetAsync(string id)
{
return await _collection.Find<T>(T => T.Id == id).FirstOrDefaultAsync();
}
/// <summary>
/// 新增
/// </summary>
/// <param name="T"></param>
/// <returns></returns>
public async Task<T> CreateAsync(T T)
{
await _collection.InsertOneAsync(T);
return T;
}
/// <summary>
/// 新增
/// </summary>
/// <param name="T"></param>
/// <returns></returns>
public async Task CreateManyAsync(IEnumerable<T> T)
{
await _collection.InsertManyAsync(T);
}
/// <summary>
/// 更新
/// </summary>
/// <param name="id"></param>
/// <param name="TIn"></param>
/// <returns></returns>
public async Task UpdateAsync(string id, T TIn)
{
await _collection.ReplaceOneAsync(T => T.Id == id, TIn);
}
/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task RemoveAsync(string id)
{
await _collection.DeleteOneAsync(T => T.Id == id);
}
#endregion
/// <summary>
/// 表达式取数据
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public Task<IQueryable<T>> GetListWithExp(Expression<Func<T, bool>> expression)
{
// var temp = _collection.AsQueryable<T>().Where(expression).ToList();
return Task.FromResult(_collection.AsQueryable<T>().Where(expression));
}
/// <summary>
/// filter查找
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public async Task<List<T>> FindListByFilter(Expression<Func<T, bool>> filter)
{
FilterDefinition<T> filters = Builders<T>.Filter.Where(filter);
return await _collection.Find(filters).ToListAsync();
}
/// <summary>
/// filterdefinition
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public async Task<List<T>> FindListyFilter(FilterDefinition<T> filter)
{
return await _collection.Find(filter).ToListAsync();
}
/// <summary>
/// 是否存在
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public Task<bool> Exist(Expression<Func<T, bool>> expression)
{
var result = _collection.AsQueryable().Where(expression).Any();
return Task.FromResult(result);
}
/// <summary>
/// 分页取数据
/// </summary>
/// <param name="req"></param>
/// <param name="exp"></param>
/// <returns></returns>
public async Task<ApiResult> GetPager(RqeustPaging req, Expression<Func<T, bool>> 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 }
};
}
}
}

399
Services/DeviceSerive.cs Normal file
View File

@ -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
{
/// <summary>
///
/// </summary>
public class DeviceSerive : BaseService<Device>
{
private AlertService _alertService;
private PlcHelper _hslPlc;
/// <summary>
///
/// </summary>
/// <param name="config"></param>
/// <param name="alertService"></param>
public DeviceSerive(IConfiguration config, AlertService alertService,
PlcHelper plcHelper) : base(config, nameof(Device))
{
_alertService = alertService;
_hslPlc = plcHelper;
}
/// <summary>
/// 新加设备
/// </summary>
/// <param name="device"></param>
/// <returns></returns>
public async Task<bool> Add(Device device)
{
Expression<Func<Device, bool>> 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;
}
/// <summary>
/// 取状态
/// </summary>
/// <param name="Ingroup"></param>
/// <returns></returns>
public async Task<ApiResult> GetlistByGroupState(bool Ingroup)
{
Expression<Func<Device, bool>> expression = filter => filter.InGroup == Ingroup && filter.IsDelete == false;
var result = (await base.GetListWithExp(expression)).ToList();
return new ApiResult() { code = 0, msg = "", data = result };
}
/// <summary>
/// 更新设备
/// </summary>
/// <param name="device"></param>
/// <returns></returns>
public async Task<ApiResult> Update(Device device)
{
Expression<Func<Device, bool>> 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 = "对象为空" };
}
/// <summary>
/// 更新设备组的状态
/// </summary>
/// <param name="ids"></param>
/// <param name="Ingroup"></param>
/// <returns></returns>
public async Task UpdataGroupState(IEnumerable<string> ids, bool Ingroup)
{
Expression<Func<Device, bool>> 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);
}
}
/// <summary>
/// 检测是否已经在组中
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public async Task<bool> CheckGroupState(IEnumerable<string> ids)
{
Expression<Func<Device, bool>> exp = num => ids.Contains(num.Id);
var items = (await base.GetListWithExp(exp));
foreach (var item in items)
{
if (item.InGroup)
{
return false;
}
}
return true;
}
/// <summary>
/// 分页数据
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<ApiResult> GetList(RqeustPaging request)
{
request.pageSize = request.pageSize == 0 ? 10 : request.pageSize;
Expression<Func<Device, bool>> 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 }
};
}
/// <summary>
/// 取多条数据
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public async Task<List<Device>> GetDeviceByIds(IEnumerable<string> ids)
{
FilterDefinitionBuilder<Device> builderFilter = Builders<Device>.Filter;
FilterDefinition<Device> filter = builderFilter.In("Id", ids);
var result = await base.FindListyFilter(filter);
return result;
}
/// <summary>
/// 取全部数据
/// </summary>
/// <returns></returns>
public async Task<List<object>> GeAllList()
{
Expression<Func<Device, bool>> 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<object> obj = new List<object>();
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; }
}
/// <summary>
/// 更新设备状态
/// </summary>
/// <param name="device"></param>
/// <returns></returns>
public async Task<bool> UpdateState(Device device)
{
Expression<Func<Device, bool>> 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;
}
/// <summary>
/// 开启
/// </summary>
/// <param name="deviceId">设备id</param>
/// <param name="point">是否定点</param>
/// <returns></returns>
public async Task<bool> startdevice(string deviceId, bool point = false)
{
Expression<Func<Device, bool>> 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;
}
/// <summary>
/// 停止
/// </summary>
/// <param name="deviceId"></param>
/// <returns></returns>
public async Task<bool> stopDevice(string deviceId)
{
Expression<Func<Device, bool>> 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<object> 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<object> getval(string deviceId)
{
Expression<Func<Device, bool>> 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<object> setval(string deviceId, bool val)
{
Expression<Func<Device, bool>> 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;
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="t"></param>
/// <param name="val"></param>
/// <returns></returns>
public async Task<object> 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;
}
/// <summary>
/// 归零
/// </summary>
/// <param name="id"></param>
/// <param name="val"></param>
/// <returns></returns>
public async Task<object> 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;
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="t"></param>
/// <param name="val"></param>
/// <returns></returns>
public async Task<object> 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;
}
/// <summary>
/// 设备角度
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<object> GetUpOrDown(string id)
{
var entity = await base.GetAsync(id);
if (entity != null)
{
return await _hslPlc.GetAngleVal1(entity.deviceIp, "VW4034");
}
return null;
}
/// <summary>
/// 设备角度
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<object> GetLeftOrRight(string id)
{
var entity = await base.GetAsync(id);
if (entity != null)
{
return await _hslPlc.GetAngleVal1(entity.deviceIp, "VD4030");
}
return null;
}
}
}

View File

@ -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<DeviceUsed>
{
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);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public async Task<object> GetList(DateTime start, DateTime end)
{
Expression<Func<DeviceUsed, bool>> 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<Func<DeviceUsed, bool>> 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);
}
}
}
}

104
Services/EmployeeService.cs Normal file
View File

@ -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
{
/// <summary>
///
/// </summary>
public class EmployeeService : BaseService<Employee>
{
/// <summary>
///
/// </summary>
/// <param name="config"></param>
public EmployeeService(IConfiguration config) : base(config, nameof(Employee))
{
}
/// <summary>
/// 登陆
/// </summary>
/// <param name="Account"></param>
/// <param name="Pwd"></param>
/// <returns></returns>
public async Task<ApiResult> Login(string Account, string Pwd)
{
Expression<Func<Employee, bool>> 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 = "登陆失败,请检查用户名跟密码" };
}
/// <summary>
/// 更新密码
/// </summary>
/// <param name="Account"></param>
/// <param name="Pwd"></param>
/// <param name="NewPwd"></param>
/// <returns></returns>
public async Task<ApiResult> Update(string Account, string Pwd, string NewPwd)
{
Expression<Func<Employee, bool>> 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 = "旧密码有误" };
}
/// <summary>
/// 新加用户
/// </summary>
/// <param name="Account"></param>
/// <param name="Pwd"></param>
/// <param name="NickName"></param>
/// <returns></returns>
public async Task<ApiResult> Add(string Account, string Pwd, string NickName)
{
Expression<Func<Employee, bool>> 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 = "" };
}
}
/// <summary>
/// 列表页
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<ApiResult> GetList(RqeustPaging request)
{
request.pageSize = request.pageSize == 0 ? 10 : request.pageSize;
Expression<Func<Employee, bool>> 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 }
};
}
}
}

136
Services/GroupService.cs Normal file
View File

@ -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<Group>
{
private DeviceSerive _deviceSerive;
public GroupService(IConfiguration config, DeviceSerive deviceSerive) : base(config, nameof(Group))
{
_deviceSerive = deviceSerive;
}
/// <summary>
/// 新加分组
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task<ApiResult> Add(Group input)
{
Expression<Func<Group, bool>> 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 = "已经存在同名的组" };
}
/// <summary>
/// 更新
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task<ApiResult> update(Group input)
{
Expression<Func<Group, bool>> 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 = "对象为空" };
}
/// <summary>
///
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public async Task<ApiResult> remove(IEnumerable<string> ids)
{
if (ids.Any())
{
foreach (var item in ids)
{
await base.RemoveAsync(item);
}
}
return new ApiResult() { code = 0, msg = "" };
}
/// <summary>
/// 取单条
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<ApiResult> FindOne(string id)
{
Expression<Func<Group, bool>> exp = num => num.Id == id;
var entity = (await base.GetListWithExp(exp)).FirstOrDefault();
Expression<Func<Device, bool>> 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
}
};
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<ApiResult> GetList(RqeustPaging request)
{
request.pageSize = request.pageSize == 0 ? 10 : request.pageSize;
Expression<Func<Group, bool>> 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 }
};
}
/// <summary>
/// group 取全部的设备id
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public async Task<IEnumerable<string>> GetDeviceIds(IEnumerable<string> ids)
{
Expression<Func<Group, bool>> exp = num => ids.Contains(num.Id);
List<string> result = new List<string>();
(await base.GetListWithExp(exp)).ToList().Select(s => s.DeviceIds).ToList().ForEach(o =>
{
result.AddRange(o);
});
return result;
}
}
}

View File

@ -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
{
/// <summary>
///
/// </summary>
public class NetServer : TcpServer
{
/// <summary>
/// 收到数据事件
/// </summary>
public event Action<NetSession, NetPackage, string> ReceivedData;
/// <summary>
/// 发送数据事件
/// </summary>
public event Action<NetSession, NetPackage, string> 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 })
{
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected override TcpSession CreateSession()
{
return new NetSession(this);
}
/// <summary>
/// 引发收到数据事件
/// </summary>
internal void RaiseReceivedData(NetSession netSession, NetPackage netPackage, string rawText)
{
ReceivedData?.Invoke(netSession, netPackage, rawText);
}
/// <summary>
/// 引发发送数据事件
/// </summary>
/// <param name="netSession"></param>
/// <param name="netPackage"></param>
/// <param name="rawText"></param>
internal void RaiseSendData(NetSession netSession, NetPackage netPackage, string rawText)
{
SendData?.Invoke(netSession, netPackage, rawText);
}
}
}

View File

@ -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
{
/// <summary>
///
/// </summary>
public class NetSession : TcpSession
{
private StringBuilder _unpackCache;
public NetSession(TcpServer server) : base(server)
{
}
protected override void OnClosed()
{
base.OnClosed();
_unpackCache?.Clear();
}
/// <summary>
/// 获取分包缓存
/// </summary>
/// <returns></returns>
private StringBuilder GetUnpackCache()
{
return _unpackCache ??= new StringBuilder();
}
/// <summary>
///
/// </summary>
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);
}
}
}
/// <summary>
/// 应答
/// </summary>
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);
}
}
}
}

View File

@ -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
{
/// <summary>
/// 启动socket
/// </summary>
public class HJ212SocketServer
{
private Hj212Service _hj212Service;
private DeviceSerive _deviceSerive;
/// <summary>
///
/// </summary>
/// <param name="hj212Service"></param>
/// <param name="deviceSerive"></param>
public HJ212SocketServer(Hj212Service hj212Service, DeviceSerive deviceSerive)
{
_hj212Service = hj212Service;
_deviceSerive = deviceSerive;
}
/// <summary>
/// 缓冲器
/// </summary>
private byte[] result = new byte[1024];
/// <summary>
/// 最大连接数
/// </summary>
private int maxClientCount;
/// <summary>
/// 服务IP地址
/// </summary>
private string ip;
/// <summary>
/// 服务端口号
/// </summary>
private int port => 9001;
// 编码
// private string code;
/// <summary>
/// 客户端列表
/// </summary>
private List<Socket> ClientSockets;
/// <summary>
/// IP终端
/// </summary>
private IPEndPoint ipEndPoint;
/// <summary>
/// 服务端Socket
/// </summary>
private Socket ServerSocket;
private static NetServer server;
private static IceCoffee.FastSocket.Tcp.TcpClient client;
/// <summary>
/// 启动服务
/// </summary>
/// <returns></returns>
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<Socket>();
// 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<HJ212>(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<HJ212>(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<HJ212>(body);
entity.deviceId = hj.DATA_HEAD["MN"];
//校验通过,开始入库
Console.WriteLine($"数据开始入库");
_ = _hj212Service.Add(entity, socket.RemoteEndPoint.ToString());
}
}
}
}
/// <summary>
/// 后台线程接收数据
/// </summary>
/// <param name="obj"></param>
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<HJ212>(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<byte> arr = new List<byte>();
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;
}
}
}

144
Services/HJ212_2017.cs Normal file
View File

@ -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
{
/// <summary>
/// 数据帧头
/// </summary>
public string header { get; set; }
/// <summary>
/// 数据长度
/// </summary>
public string data_length { get; set; }
/// <summary>
/// 数据头
/// </summary>
public Dictionary<string, string> DATA_HEAD { get; set; }
/// <summary>
///
/// </summary>
public Dictionary<string, string> CP { get; set; }
/// <summary>
/// CRC校验
/// </summary>
public string CRC { get; set; }
/// <summary>
///
/// </summary>
/// <param name="Text"></param>
/// <returns></returns>
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<string, string>();
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<string, string>();
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;
}
}
/// <summary>
/// 判断数据是否通过校验
/// </summary>
/// <param name="Text">原始数据</param>
/// <returns>是否通过</returns>
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;
}
}
}
}

343
Services/Hj212Service.cs Normal file
View File

@ -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
{
/// <summary>
///
/// </summary>
public class Hj212Service : BaseService<HJ212>
{
private DeviceSerive _deviceSerive;
/// <summary>
///
/// </summary>
/// <param name="config"></param>
/// <param name="deviceSerive"></param>
public Hj212Service(IConfiguration config, DeviceSerive deviceSerive) : base(config, nameof(HJ212))
{
_deviceSerive = deviceSerive;
}
/// <summary>
/// 新加数据
/// </summary>
/// <param name="hJ212"></param>
/// <param name="deviceIp"></param>
/// <returns></returns>
public async Task Add(HJ212 hJ212, string deviceIp)
{
//先判断当前设备是否存在
await _deviceSerive.Add(new Device()
{
deviceId = hJ212.deviceId,
deviceIp = deviceIp,
state = 1
});
await base.CreateAsync(hJ212);
}
/// <summary>
/// 最近10个小时的数据
/// </summary>
/// <param name="hours"></param>
/// <returns></returns>
public async Task<List<HJ212>> GetViewTop(int hours = -10)
{
var date = DateTime.Now.AddHours(-8).AddHours(hours);
Expression<Func<HJ212, bool>> exp = filter => filter.CreateDateTime >= date;
var result = (await base.GetListWithExp(exp)).ToList();
return result;
}
/// <summary>
/// 实时的数据
/// </summary>
/// <returns></returns>
public async Task<List<columnView>> Realtime()
{
Expression<Func<HJ212, bool>> exp = filter => true;
var result = (await base.GetListWithExp(exp))
.OrderByDescending(s => s.CreateDateTime)
.Take(60).OrderBy(s => s.CreateDateTime).ToList();
List<columnView> list = new List<columnView>();
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;
}
/// <summary>
/// 自动报表
/// </summary>
/// <param name="autoReport"></param>
/// <returns></returns>
public async Task<byte[]> autoReport(AutoReport autoReport)
{
autoReport = convertDateTime(autoReport);
Expression<Func<HJ212, bool>> 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<ExportModel>("设备编号", s => s.deviceId)
.Map<ExportModel>("温度", s => s.a01001)
.Map<ExportModel>("湿度", s => s.a01002)
.Map<ExportModel>("大气压", s => s.a01006)
.Map<ExportModel>("风速", s => s.a01007)
.Map<ExportModel>("风向", s => s.a01008)
.Map<ExportModel>("TSP浓度", s => s.a34001)
.Map<ExportModel>("PM2.5", s => s.a34002)
.Map<ExportModel>("PM10", s => s.a34004)
.Map<ExportModel>("创建时间", s => s.createtime);
mapper.Put<ExportModel>(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;
}
/// <summary>
/// 计算结果
/// </summary>
/// <param name="autoReport"></param>
/// <returns></returns>
public async Task<List<string>> autoReportResult(AutoReport autoReport)
{
List<string> result = new List<string>();
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<Func<HJ212, bool>> 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<HJ212>.Filter;
//var filter = builder.Gte("CreateDateTime", autoReport.begin.Value) & builder.Lte("CreateDateTime", autoReport.end.Value);
//var fil = await base.FindListyFilter(filter);
//Expression<Func<HJ212, bool>> 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<string, int> dic = new Dictionary<string, int>();
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;
}
/// <summary>
/// 分页取数据
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="request"></param>
/// <returns></returns>
public async Task<ApiResult> GetPageData(DateTime start, DateTime end, RqeustPaging request)
{
start = start.AddHours(-8);
end = end.AddHours(-8).AddDays(1);
Expression<Func<HJ212, bool>> 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 } };
}
/// <summary>
/// 查找数据
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
async Task<List<ExportModel>> GetPage(DateTime start, DateTime end)
{
start = start.AddHours(-8);
end = end.AddHours(-8).AddDays(1);
Expression<Func<HJ212, bool>> 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();
}
/// <summary>
/// 导出数据
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public async Task<byte[]> Export(DateTime start, DateTime end)
{
var result = (await GetPage(start, end)).ToList();
var mapper = new Mapper();
mapper.Map<ExportModel>("设备编号", s => s.deviceId)
.Map<ExportModel>("温度", s => s.a01001)
.Map<ExportModel>("湿度", s => s.a01002)
.Map<ExportModel>("大气压", s => s.a01006)
.Map<ExportModel>("风速", s => s.a01007)
.Map<ExportModel>("风向", s => s.a01008)
.Map<ExportModel>("TSP浓度", s => s.a34001)
.Map<ExportModel>("PM2.5", s => s.a34002)
.Map<ExportModel>("PM10", s => s.a34004)
.Map<ExportModel>("创建时间", s => s.createtime);
mapper.Put<ExportModel>(result, "sheet1");
MemoryStream stream = new MemoryStream();
mapper.Save(stream);
return stream.ToArray();
}
}
}

View File

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

95
Services/Job/Monitor.cs Normal file
View File

@ -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<Plan> list)
{
foreach (var item in list)
{
IJobDetail job = JobBuilder.Create<MyJob>()
.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();
}
}
}
}

36
Services/Job/MyJob.cs Normal file
View File

@ -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;
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
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);
}
}
}

89
Services/PingService.cs Normal file
View File

@ -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
{
/// <summary>
/// ping service
/// </summary>
public class PingService
{
private DeviceSerive _deviceSerive;
/// <summary>
///
/// </summary>
/// <param name="deviceSerive"></param>
public PingService(DeviceSerive deviceSerive)
{
_deviceSerive = deviceSerive;
}
/// <summary>
///
/// </summary>
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);
}
/// <summary>
///
/// </summary>
/// <param name="b"></param>
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);
}
/// <summary>
/// ping
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public async Task<bool> 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;
}
}
}

219
Services/PlanService.cs Normal file
View File

@ -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<Plan>
{
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;
}
/// <summary>
/// 取全部可用的plan
/// </summary>
/// <returns></returns>
public async Task<List<Plan>> GetList()
{
Expression<Func<Plan, bool>> exp = filter => filter.disable == false;
return (await base.GetListWithExp(exp)).ToList();
}
/// <summary>
/// 更新
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task<ApiResult> updatePlan(Plan input)
{
await base.UpdateAsync(input.Id, input);
if (input.disable)
{
// QuartzUtil.DeleteJob(input.Id);
}
else
{
// QuartzUtil.StartJobWithCron<MyJob>(input.Id, input.name, input.cron);
}
return new ApiResult() { code = 0 };
}
/// <summary>
/// 取单条
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<ApiResult> 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 } };
}
/// <summary>
///
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public async Task<ApiResult> remove(IEnumerable<string> ids)
{
foreach (var item in ids)
{
var entity = await base.GetAsync(item);
await base.RemoveAsync(item);
await Reload();
}
return new ApiResult() { code = 0 };
}
/// <summary>
/// 新加plan
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task<ApiResult> AddPlan(Plan input)
{
var temp = await base.CreateAsync(input);
await Reload();
return new ApiResult()
{
code = 0,
};
}
/// <summary>
/// 更新
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<ApiResult> 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 };
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<ApiResult> GetList(RqeustPaging request)
{
Expression<Func<Plan, bool>> exp = filter => true;
return await base.GetPager(request, exp);
}
/// <summary>
/// 取所计划中所有的设备ids
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public async Task<IEnumerable<string>> GetDeviceIds(IEnumerable<string> ids)
{
Expression<Func<Plan, bool>> expression = filter => ids.Contains(filter.Id);
var items = (await base.GetListWithExp(expression)).ToList();
List<string> groupIds = new List<string>();
//取设备分组列表
// 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());
}
/// <summary>
/// 判断是否在计划中
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<bool> existsPlan(string id)
{
Expression<Func<Plan, bool>> expression = filter => true;
List<string> groupIds = new List<string>();
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);
}
/// <summary>
/// 执行
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
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);
});
}
}
}
}

View File

@ -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<RadarItems>
{
/// <summary>
///
/// </summary>
/// <param name="config"></param>
public RadarItemService(IConfiguration config) : base(config, nameof(RadarItems))
{
}
/// <summary>
/// 批量新加
/// </summary>
/// <param name="radarItems"></param>
/// <returns></returns>
public async Task AddMany(IEnumerable<RadarItems> radarItems)
{
await base.CreateManyAsync(radarItems);
}
/// <summary>
/// 取结果
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public async Task<IEnumerable<RadarItems>> GetByPids(IEnumerable<string> ids)
{
FilterDefinitionBuilder<RadarItems> builderFilter = Builders<RadarItems>.Filter;
FilterDefinition<RadarItems> filter = builderFilter.In("pid", ids);
var result = await base.FindListyFilter(filter);
return result;
}
/// <summary>
/// 取单条
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<List<IEnumerable<double>>> GetByPid(string id)
{
Expression<Func<RadarItems, bool>> exp = num => num.pid == id;
var result = (await base.GetListWithExp(exp)).ToList().Select(s => s.Signal).ToList(); ;
return result;
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<int> getcount(string id)
{
Expression<Func<RadarItems, bool>> 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();
}
}
}

279
Services/RadarService.cs Normal file
View File

@ -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
{
/// <summary>
///
/// </summary>
public class RadarService : BaseService<Radar>
{
private readonly IMapper _mapper;
private DeviceSerive _deviceSerive;
private RadarItemService _radarItemService;
/// <summary>
///
/// </summary>
/// <param name="config"></param>
/// <param name="mapper"></param>
/// <param name="deviceSerive"></param>
/// <param name="radarItemService"></param>
public RadarService(IConfiguration config, IMapper mapper,
DeviceSerive deviceSerive, RadarItemService radarItemService) : base(config, nameof(Radar))
{
_mapper = mapper;
_deviceSerive = deviceSerive;
_radarItemService = radarItemService;
}
/// <summary>
/// 新加数据
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<ApiResult> Add(RadarView request)
{
var entity = _mapper.Map<Radar>(request);
await _deviceSerive.Add(new Device()
{
deviceId = request.deviceId,
deviceIp = request.deviceIp,
state = 1
});
//数据量过大,这里要分开存储
var result = await base.CreateAsync(entity);
List<RadarItems> items = new List<RadarItems>();
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 = "" };
}
/// <summary>
/// 首页用图
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
public async Task<List<object>> Top(int n)
{
Expression<Func<Radar, bool>> 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<object> result = new List<object>();
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;
}
/// <summary>
///
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public async Task<ApiResult> 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<Func<Radar, bool>> 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<object> result = new List<object>();
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<List<radarModel>> ConvertData(double rang, double DataPointNum, double SystemBlind, string id)
{
// var count = await _radarItemService.getcount(id);
List<radarModel> radarModels = new List<radarModel>();
//里面先取度数
//取1000米的数 1000/3
List<IEnumerable<double>> vs = new List<IEnumerable<double>>();
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<int> reuslt = new List<int>();
int i = 0;
while (i < 360)
{
reuslt.Add(i);
i = i + 10;
}
return reuslt.ToArray();
}
/// <summary>
/// 计算圈数
/// </summary>
/// <param name="DetectRange"></param>
/// <param name="SystemBlind"></param>
/// <returns></returns>
private int[] convertDistance(double DetectRange, double SystemBlind)
{
List<int> reuslt = new List<int>();
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();
}
/// <summary>
/// 返回结果
/// </summary>
public class radarModel
{
/// <summary>
/// 角度
/// </summary>
public int angle { get; set; }
/// <summary>
/// 距离
/// </summary>
public int distance { get; set; }
/// <summary>
/// 结果
/// </summary>
public double value { get; set; }
}
}
}

90
Services/VideoService.cs Normal file
View File

@ -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
{
/// <summary>
///
/// </summary>
public class VideoService : BaseService<Video>
{
/// <summary>
///
/// </summary>
/// <param name="config"></param>
public VideoService(IConfiguration config) : base(config, nameof(Video))
{
}
/// <summary>
/// 首页取全部
/// </summary>
/// <returns></returns>
public async Task<object> GetAll()
{
Expression<Func<Video, bool>> exp = num => true;
var query = await base.GetListWithExp(exp);
var reslut = query.OrderByDescending(s => s.CreateDateTime)
.Select(s => new { s.GroupName, s.Url, }).ToList();
if (reslut.Count > 0)
{
return reslut;
}
return Task.FromResult(new { });
}
/// <summary>
/// 分页数据
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<ApiResult> GetList(RqeustPaging request)
{
request.pageSize = request.pageSize == 0 ? 10 : request.pageSize;
Expression<Func<Video, bool>> 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.Url, }).ToList();
return new ApiResult()
{
code = 0,
data = new { total = total, items = items }
};
}
/// <summary>
///
/// </summary>
/// <param name="video"></param>
/// <returns></returns>
public async Task<ApiResult> Add(Video video)
{
await base.CreateAsync(video);
return new ApiResult() { code = 0, msg = "" };
}
/// <summary>
/// 更新
/// </summary>
/// <param name="video"></param>
/// <returns></returns>
public async Task<ApiResult> Update(Video video)
{
var entity = await base.GetAsync(video.Id);
if (entity != null)
{
entity.GroupName = video.GroupName;
entity.Url = video.Url;
await base.UpdateAsync(video.Id, entity);
return new ApiResult() { code = 0, msg = "" };
}
return new ApiResult() { code = 1, msg = "修改失败" };
}
}
}

View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace IceCoffee.HJ212.Models
{
/// <summary>
/// 命令编码
/// </summary>
public enum CommandNumber
{
/// <summary>
/// 心跳包
/// </summary>
HeartbeatPackage = 1062,
/// <summary>
/// 工控机向上位机上传分钟数据
/// </summary>
UploadMinuteData = 2051,
/// <summary>
/// 工控机向上位机上传小时数据
/// </summary>
UploadHourlyData = 2061,
/// <summary>
/// 工控机向上位机上传日数据
/// </summary>
UploadDailyData = 2031,
/// <summary>
/// 工控机向上位机上传实时数据
/// </summary>
UploadRealTimeData = 2011,
/// <summary>
/// 上位机向工控机返回应答
/// </summary>
DataResponse = 9014
}
}

View File

@ -0,0 +1,123 @@
using IceCoffee.Common.Extensions;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace IceCoffee.HJ212.Models
{
/// <summary>
/// CP指令
/// </summary>
public class CpCommand
{
public ResponseCode ExeRtn { get; set; }
/// <summary>
/// 数据时间信息
/// </summary>
public DateTime DataTime { get; set; }
/// <summary>
/// 污染物信息
/// </summary>
public List<PollutantInfo> PollutantInfo { get; set; }
/// <summary>
/// 解析
/// </summary>
/// <param name="cp"></param>
/// <returns></returns>
public static CpCommand Parse(string cp)
{
try
{
var cpCommand = new CpCommand();
cpCommand.PollutantInfo = new List<PollutantInfo>();
cpCommand.DataTime = DateTime.ParseExact(cp.GetMidStr("DataTime=", ";"), "yyyyMMddHHmmss", null);
cp = cp.Substring(24);
#if NET462
foreach (string project in cp.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
#else
foreach (string project in cp.Split(';', StringSplitOptions.RemoveEmptyEntries))
#endif
{
var pollutantInfo = new PollutantInfo();
string[] classes = project.Split(',');
foreach (string @class in classes)
{
string[] keyValue = @class.Split('=');
string key = keyValue[0];
string value = keyValue[1];
string[] factorCodeType = key.Split('-');
string factorCode = factorCodeType[0];
string type = factorCodeType[1];
pollutantInfo.FactorCode = (FactorCode)Enum.Parse(typeof(FactorCode), factorCode);
switch (type)
{
case nameof(Models.PollutantInfo.Rtd):
if (string.IsNullOrEmpty(value) == false && decimal.TryParse(value, out decimal rtd))
{
pollutantInfo.Rtd = rtd;
}
break;
case nameof(Models.PollutantInfo.Avg):
if (string.IsNullOrEmpty(value) == false && decimal.TryParse(value, out decimal avg))
{
pollutantInfo.Avg = avg;
}
break;
case nameof(Models.PollutantInfo.Max):
if (string.IsNullOrEmpty(value) == false && decimal.TryParse(value, out decimal max))
{
pollutantInfo.Max = max;
}
break;
case nameof(Models.PollutantInfo.Min):
if (string.IsNullOrEmpty(value) == false && decimal.TryParse(value, out decimal min))
{
pollutantInfo.Min = min;
}
break;
case nameof(Models.PollutantInfo.Cou):
if (string.IsNullOrEmpty(value) == false && decimal.TryParse(value, out decimal cou))
{
pollutantInfo.Cou = cou;
}
break;
case nameof(Models.PollutantInfo.Flag):
pollutantInfo.Flag = (InstrumentationDataFlag)Enum.Parse(typeof(InstrumentationDataFlag), value);
break;
default:
throw new Exception("无效的CP指令字段名");
}
}
cpCommand.PollutantInfo.Add(pollutantInfo);
}
return cpCommand;
}
catch (Exception ex)
{
throw new Exception("Error in CpCommand.Parse", ex);
}
}
/// <summary>
/// 序列化
/// </summary>
/// <returns></returns>
public string Serialize()
{
return "ExeRtn=" + (int)ExeRtn;
}
}
}

View File

@ -0,0 +1,154 @@
using IceCoffee.Common.Extensions;
using System;
using System.Collections.Generic;
using System.Text;
namespace IceCoffee.HJ212.Models
{
/// <summary>
/// 数据段
/// </summary>
public class DataSegment
{
/// <summary>
/// 默认应答系统编码
/// </summary>
public const string ResponseST = "91";
/// <summary>
/// 请求编号
/// </summary>
/// <remarks>
/// yyyyMMddHHmmssZZZ 取当前系统时间, 精确到毫秒值, 用来唯一标识一次命令交互
/// </remarks>
public string QN { get; set; }
/// <summary>
/// 系统编号
/// </summary>
public string ST { get; set; }
/// <summary>
/// 命令编码
/// <para>详见附录 2</para>
/// </summary>
public CommandNumber CN { get; set; }
/// <summary>
/// 访问密码
/// <para>对接时提供给各个对接站点</para>
/// </summary>
public string PW { get; set; }
/// <summary>
/// 设备唯一标识
/// <para>对接时提供给各个对接站点</para>
/// </summary>
public string MN { get; set; }
/// <summary>
/// 拆分包及应答标志
/// </summary>
public PackageFlag PackageFlag { get; set; }
/// <summary>
/// 总包数
/// <para>PNUM 指示本次通讯中总共包含的包数,注:不分包时可以没有本字段,与标志位有关</para>
/// </summary>
public int PNUM { get; set; }
/// <summary>
/// 包号
/// <para>PNO 指示当前数据包的包号,注: 不分包时可以没有本字段,与标志位有关</para>
/// </summary>
public int PNO { get; set; }
/// <summary>
/// 指令
/// <para>CP=&&数据区&&( 详见表 5 )</para>
/// </summary>
public CpCommand CpCommand { get; set; }
/// <summary>
/// 解析
/// </summary>
/// <param name="data"></param>
/// <param name="unpackCacheFunc"></param>
/// <returns></returns>
public static DataSegment Parse(string data, Func<StringBuilder> unpackCacheFunc)
{
try
{
DataSegment dataSegment = new DataSegment();
int outEnd;
dataSegment.QN = data.GetMidStr("QN=", ";", out outEnd);
if(outEnd < 0)
{
outEnd = 0;
}
dataSegment.ST = data.GetMidStr("ST=", ";", out outEnd, outEnd);
dataSegment.CN = (CommandNumber)int.Parse(data.GetMidStr("CN=", ";", out outEnd, outEnd));
dataSegment.PW = data.GetMidStr("PW=", ";", out outEnd, outEnd);
dataSegment.MN = data.GetMidStr("MN=", ";", out outEnd, outEnd);
string packageFlag = data.GetMidStr("Flag=", ";", out outEnd, outEnd);
if (string.IsNullOrEmpty(packageFlag) || int.TryParse(packageFlag, out _) == false || outEnd < 0)
{
outEnd = 0;
}
else
{
dataSegment.PackageFlag = PackageFlag.Parse(packageFlag);
}
if (dataSegment.PackageFlag != null && dataSegment.PackageFlag.D == 1)
{
// 分包
dataSegment.PNUM = int.Parse(data.GetMidStr("PNUM=", ";", out outEnd, outEnd));
dataSegment.PNO = int.Parse(data.GetMidStr("PNO=", ";", out outEnd, outEnd));
string cp = data.GetMidStr("CP=&&", "&&", out outEnd, outEnd);
var cache = unpackCacheFunc.Invoke();
if(dataSegment.PNO == 1)// 第一个包
{
cache.Append(cp);
}
else if (dataSegment.PNUM == dataSegment.PNO)// 最后一个包
{
cache.Append(cp.Substring(23));
dataSegment.CpCommand = CpCommand.Parse(cache.ToString());
cache.Clear();
}
else// 中间的包
{
cache.Append(cp.Substring(23));// 23 - DataTime=20170920100000; 留分号
}
}
else
{
string cp = data.GetMidStr("CP=&&", "&&", out outEnd, outEnd);
// 过滤心跳包
dataSegment.CpCommand = dataSegment.CN == CommandNumber.HeartbeatPackage ? new CpCommand() : CpCommand.Parse(cp);
}
return dataSegment;
}
catch (Exception ex)
{
throw new Exception("Error in DataSegment.Parse", ex);
}
}
/// <summary>
/// 序列化
/// </summary>
/// <returns></returns>
public string Serialize()
{
return $"QN={QN};ST={ST};CN={(int)CN};PW={PW};MN={MN};Flag={PackageFlag.Serialize()};CP=&&{CpCommand.Serialize()}&&";
}
}
}

View File

@ -0,0 +1,426 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace IceCoffee.HJ212.Models
{
/// <summary>
/// 污染物因子编码
/// </summary>
public enum FactorCode
{
#region VOCs 线
a24901,
a24904,
a24905,
a24042,
a25002,
a24036,
a24908,
a24909,
a24910,
a24012,
a24043,
a24084,
a24911,
a25003,
a24912,
a24913,
a24070,
a25004,
a25008,
a25038,
a25006,
a24044,
a25034,
a25033,
a25902,
a25014,
a25021,
a25901,
a25019,
a24068,
a25020,
a25903,
a25904,
a24914,
a24915,
a24001,
a24045,
a24002,
a24053,
a24038,
a24037,
a24079,
a24064,
a24919,
a24063,
a24902,
a24041,
a24039,
a24077,
a24074,
a24076,
a24907,
a24903,
a24011,
a24061,
a24906,
a31002,
a31005,
#region
a05002,
a99999,
a24088,
#endregion
a24072,
a05009,
a05014,
a24099,
a24058,
a24046,
a24078,
a24008,
a24015,
a24916,
a31004,
a31003,
a24047,
a05013,
a31024,
a99009,
a24003,
a28006,
a31015,
a24016,
a31900,
a24111,
a24004,
a24018,
a24005,
a24017,
a24049,
a24917,
a24027,
a31010,
a31026,
a24007,
a24112,
a24054,
a24019,
a24050,
a31009,
a24034,
a25010,
a24009,
a24020,
a25012,
a25011,
a30003,
a30008,
a99051,
a29026,
a29017,
a31025,
a24110,
a25072,
a29015,
a31030,
a31027,
a24006,
a25013,
a25068,
a25015,
a24113,
a25059,
a31001,
a31016,
a31018,
a31020,
a24102,
a30001,
a25905,
a24918,
a28900,
a28010,
a30002,
a30023,
a28001,
a24059,
a24944,
#endregion
#region 线
a01030,
a01004,
a01007,
a01008,
a06001,
a01001,
#endregion
#region
a21003,
a21004,
a21002,
a21029,
#endregion
#region
a34004,
a34002,
a21026,
// a21004,
a21005,
#endregion
#region 线
a06010,
a06011,
a06013,
a06009,
a06012,
a06005,
a06006,
a06019,
a06008,
a21001,
a20109,
// a21026,
a20110,
a21024,
// a21004,
a06007,
a06015,
a06018,
a06021,
a06017,
a06022,
a06023,
a06024,
a06025,
a06026,
a06027,
a06028,
a06029,
a06030,
a06031,
a06032,
a06033,
a34007,
a34006,
a34047,
a34048,
a34049,
a20044,
a20072,
a20058,
a20033,
a20026,
a20104,
a20041,
a20064,
a20111,
a20055,
a20095,
a20004,
a20092,
a20101,
a20012,
a20007,
a20029,
a20068,
a20038,
a20061,
a20112,
a20113,
a20089,
a20114,
a20115,
a20086,
a20116,
a20117,
a20118,
a20119,
a20079,
a20120,
a20002,
a20121,
a20075,
a20052,
a20122,
a20123,
a21012,
a20124,
a20107,
a20125,
a20126,
a20127,
a20128,
a20129,
a20098,
a20020,
a01031,
a01032,
a01029,
a01033,
a01034,
a01035,
a01036,
a01037,
// a01001,
// a01004,
a01038,
a01039,
// a06001,
a01022,
a01023,
// a34002,
// a34004,
a01024,
a19006,
a01025,
a01026,
a01020,
a01027,
a01028,
// a01029,
// a01022,
// a01023,
a05024,
a19999,
a19998,
a19997,
a19996,
a19995,
a19994,
a19993,
#endregion
#region HJ 524-2009
a00000,
//a01001,
a01002,
a01006,
//a01007,
//a01008,
a01010,
a01011,
a01012,
a01013,
a01014,
a01015,
a01016,
a01017,
a01901,
a01902,
a05001,
//a05002,
a05008,
//a05009,
//a05013,
a19001,
//a20007,
a20016,
a20025,
//a20026,
a20043,
//a20044,
a20057,
//a20058,
a20063,
a20091,
//a21001,
//a21002,
//a21003,
//a21004,
//a21005,
a21017,
a21018,
a21022,
//a21024,
//a21026,
a21028,
a23001,
//a24003,
//a24004,
//a24005,
//a24006,
//a24007,
//a24008,
//a24009,
//a24015,
//a24016,
//a24017,
//a24018,
//a24019,
//a24020,
//a24027,
//a24034,
//a24036,
//a24042,
//a24043,
//a24046,
//a24047,
//a24049,
//a24050,
//a24053,
//a24054,
//a24072,
//a24078,
a24087,
//a24088,
//a24099,
//a24110,
//a24111,
//a24112,
//a24113,
//a25002,
//a25003,
//a25004,
a25005,
//a25006,
a25007,
//a25008,
//a25010,
//a25011,
//a25012,
//a25013,
//a25014,
//a25015,
//a25019,
//a25020,
//a25021,
a25023,
//a25038,
a25044,
//a25072,
a26001,
//a29017,
//a29026,
//a30001,
//a30008,
a30022,
//a31001,
//a31002,
//a31024,
//a31025,
//a31030,
a34001,
//a34002,
//a34004,
a34005,
a34011,
a34013,
a34017,
a34038,
a34039,
a34040,
a99010,
a99049,
//a99051,
#endregion
}
}

View File

@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace IceCoffee.HJ212.Models
{
/// <summary>
/// 检测仪器数据标记
/// </summary>
public enum InstrumentationDataFlag
{
/// <summary>
/// 正常(有效)
/// <para>在线监控(监测)仪器仪表工作正常</para>
/// </summary>
N,
/// <summary>
/// 无效
/// <para>在线监控(监测)仪器仪表停运</para>
/// </summary>
F,
/// <summary>
/// 无效
/// <para>在线监控(监测)仪器仪表处于维护期间产生的数据 </para>
/// </summary>
M,
/// <summary>
/// 有效
/// <para>手工输入的设定值</para>
/// </summary>
S,
/// <summary>
/// 无效
/// <para>在线监控(监测)仪器仪表故障</para>
/// </summary>
D,
/// <summary>
/// 无效
/// <para>在线监控(监测)仪器仪表处于校准状态</para>
/// </summary>
C,
/// <summary>
/// 无效
/// <para>在线监控(监测)仪器仪表采样数值超过测量上限</para>
/// </summary>
T,
/// <summary>
/// 无效
/// <para>在线监控(监测)仪器仪表与数采仪通讯异常</para>
/// </summary>
B,
/// <summary>
/// 无效(有效数据不足)
/// </summary>
/// <remarks>
/// 按照5分钟、1小时均值计算要求所获取的有效数据个数不足
/// </remarks>
H
}
}

View File

@ -0,0 +1,121 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace IceCoffee.HJ212.Models
{
/// <summary>
/// 通讯包
/// </summary>
public class NetPackage
{
/// <summary>
/// 默认头
/// </summary>
public const string FixedHead = "##";
/// <summary>
/// 默认尾
/// </summary>
public const string FixedTail = "\r\n";
/// <summary>
/// 包头
/// </summary>
public string Head { get; set; }
/// <summary>
/// 数据段长度
/// </summary>
public int DataSegmentLength { get; set; }
/// <summary>
/// 数据段
/// </summary>
public DataSegment DataSegment { get; set; }
/// <summary>
/// CRC校验码
/// </summary>
public string CrcCode { get; set; }
/// <summary>
/// 包尾
/// </summary>
public string Tail { get; set; }
/// <summary>
/// CRC16校验
/// </summary>
/// <param name="arg">需要校验的字符串</param>
/// <returns>CRC16 校验码</returns>
private static string CRC16(string arg)
{
char[] puchMsg = arg.ToCharArray();
uint i, j, crc_reg, check;
crc_reg = 0xFFFF;
for (i = 0; i < puchMsg.Length; i++)
{
crc_reg = (crc_reg >> 8) ^ puchMsg[i];
for (j = 0; j < 8; j++)
{
check = crc_reg & 0x0001;
crc_reg >>= 1;
if (check == 0x0001)
{
crc_reg ^= 0xA001;
}
}
}
return crc_reg.ToString("X2").PadLeft(4, '0');
}
/// <summary>
/// 解析
/// </summary>
/// <param name="line"></param>
/// <param name="unpackCacheFunc"></param>
/// <returns></returns>
public static NetPackage Parse(string line, Func<StringBuilder> unpackCacheFunc = null)
{
try
{
NetPackage netPackage = new NetPackage();
netPackage.Head = line.Substring(0, 2);
netPackage.DataSegmentLength = int.Parse(line.Substring(2, 4));
string dataSegment = line.Substring(6, netPackage.DataSegmentLength);
string crcCode = line.Substring(6 + netPackage.DataSegmentLength, 4);
string calcCrcCode = CRC16(dataSegment);
if (crcCode != calcCrcCode)
{
throw new Exception("CRC校验失败 " + line);
}
netPackage.DataSegment = DataSegment.Parse(dataSegment, unpackCacheFunc);
netPackage.CrcCode = crcCode;
netPackage.Tail = line.Substring(10 + netPackage.DataSegmentLength);
return netPackage;
}
catch (Exception ex)
{
throw new Exception("Error in NetPackage.Parse", ex);
}
}
/// <summary>
/// 序列化
/// </summary>
/// <returns></returns>
public string Serialize()
{
string dataSegment = DataSegment.Serialize();
DataSegmentLength = dataSegment.Length;
CrcCode = CRC16(dataSegment);
return $"{Head}{DataSegmentLength.ToString().PadLeft(4, '0')}{dataSegment}{CrcCode}{Tail}";
}
}
}

View File

@ -0,0 +1,121 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace IceCoffee.HJ212
{
/// <summary>
/// 拆分包及应答标志
/// </summary>
public class PackageFlag
{
public byte V5 { get; set; }
public byte V4 { get; set; }
public byte V3 { get; set; }
public byte V2 { get; set; }
public byte V1 { get; set; }
public byte V0 { get; set; }
/// <summary>
/// 命令是否应答1应答0不应答
/// </summary>
public byte A { get; set; }
/// <summary>
/// 是否有数据包序号1 - 数据包中包含包号和总包数两部分0 - 数据包中不包含包号和总包数两部分
/// </summary>
public byte D { get; set; }
/// <summary>
/// 标准版本号
/// <para>000000 表示标准 HJ/T212-2005</para>
/// <para>000001 表示本次标准修订版本号</para>
/// </summary>
public string Version
{
get
{
return $"{V5}{V4}{V3}{V2}{V1}{V0}";
}
}
/// <summary>
/// 解析
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static PackageFlag Parse(string data)
{
byte flag = byte.Parse(data);
return new PackageFlag()
{
V5 = GetBit(flag, 7),
V4 = GetBit(flag, 6),
V3 = GetBit(flag, 5),
V2 = GetBit(flag, 4),
V1 = GetBit(flag, 3),
V0 = GetBit(flag, 2),
D = GetBit(flag, 1),
A = GetBit(flag, 0)
};
}
/// <summary>
/// 序列化
/// </summary>
/// <returns></returns>
public string Serialize()
{
return Convert.ToInt32($"{V5}{V4}{V3}{V2}{V1}{V0}{D}{A}", 2).ToString();
}
/// <summary>
/// 获取取第index位
/// </summary>
/// <remarks>
/// index从0开始
/// </remarks>
/// <param name="b"></param>
/// <param name="index"></param>
/// <returns></returns>
private static byte GetBit(byte b, int index)
{
// (byte)((from & (0xFF << (index * 8))) >> (index * 8))
return ((b & (1 << index)) > 0) ? (byte)1 : (byte)0;
}
/// <summary>
/// 将第index位设为1
/// </summary>
/// <remarks>
/// index从0开始
/// </remarks>
/// <param name="b"></param>
/// <param name="index"></param>
/// <returns></returns>
private static byte SetBit(byte b, int index) { return (byte)(b | (1 << index)); }
/// <summary>
/// 将第index位设为0
/// </summary>
/// <remarks>
/// index从0开始
/// </remarks>
/// <param name="b"></param>
/// <param name="index"></param>
/// <returns></returns>
private static byte ClearBit(byte b, int index) { return (byte)(b & (byte.MaxValue - (1 << index))); }
/// <summary>
/// 将第index位取反
/// </summary>
/// <remarks>
/// index从0开始
/// </remarks>
/// <param name="b"></param>
/// <param name="index"></param>
/// <returns></returns>
private static byte ReverseBit(byte b, int index) { return (byte)(b ^ (byte)(1 << index)); }
}
}

View File

@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace IceCoffee.HJ212.Models
{
/// <summary>
/// 污染物信息
/// </summary>
public class PollutantInfo
{
/// <summary>
/// 约定的无效值
/// </summary>
public const decimal InvaildValue = -9999;
/// <summary>
/// 污染物因子编码
/// </summary>
public FactorCode FactorCode { get; set; }
/// <summary>
/// 污染物实时采样数据
/// </summary>
/// <remarks>
/// 默认值为约定的无效值 <see cref="InvaildValue"/>
/// </remarks>
public decimal Rtd { get; set; } = InvaildValue;
/// <summary>
/// 污染物指定时问内平均值
/// </summary>
/// <remarks>
/// 默认值为约定的无效值 <see cref="InvaildValue"/>
/// </remarks>
public decimal Avg { get; set; } = InvaildValue;
/// <summary>
/// 污染物指定时问内最大值
/// </summary>
/// <remarks>
/// 默认值为约定的无效值 <see cref="InvaildValue"/>
/// </remarks>
public decimal Max { get; set; } = InvaildValue;
/// <summary>
/// 污染物指定时问内最小值
/// </summary>
/// <remarks>
/// 默认值为约定的无效值 <see cref="InvaildValue"/>
/// </remarks>
public decimal Min { get; set; } = InvaildValue;
/// <summary>
/// 污染物指定时问内累计值
/// </summary>
/// <remarks>
/// 默认值为约定的无效值 <see cref="InvaildValue"/>
/// </remarks>
public decimal Cou { get; set; } = InvaildValue;
/// <summary>
/// 检测仪器数据标记
/// </summary>
public InstrumentationDataFlag Flag { get; set; }
}
}

View File

@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace IceCoffee.HJ212.Models
{
/// <summary>
/// 回应代码集
/// </summary>
public enum ResponseCode
{
/// <summary>
/// 执行成功
/// </summary>
ExecSucceeded = 1,
/// <summary>
/// 执行失败,但不知道原因
/// </summary>
ExecutionFailed_DoNotKnowReason = 2,
/// <summary>
/// 执行失败,命令请求条件错误
/// </summary>
ExecutionFailed_InvalidCommand = 3,
/// <summary>
/// 通讯超时
/// </summary>
CommunicationTimeout = 4,
/// <summary>
/// 系统繁忙不能执行
/// </summary>
SystemBusy = 5,
/// <summary>
/// 系统时间异常
/// </summary>
InvalidSystemTime = 6,
/// <summary>
/// 没有数据
/// </summary>
NoneData = 100,
/// <summary>
/// 心跳包
/// </summary>
HeartbeatPackage = 300
}
}

View File

@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LangGuan.Services.models
{
public class columnView
{
}
}

163
Startup.cs Normal file
View File

@ -0,0 +1,163 @@
using AutoMapper;
using LangGuan.Command.AutoMapper;
using LangGuan.Command.Extension;
using LangGuan.Configuration;
using LangGuan.Middleware;
using LangGuan.Services;
using LangGuan.Services.Job;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
namespace LangGuan
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(options =>
{
options.Filters.Add<CustomerExceptionFilter>();
}).AddNewtonsoftJson(option =>
{
//option.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
//option.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
}).AddJsonOptions(option =>
{
//userName
option.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});
services.AddMemoryCache();
//请求地址转成小写
services.AddRouting(options => options.LowercaseUrls = true);
#region 使AutoMapper
var mapperConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new CustomProfile());
});
IMapper mapper = mapperConfig.CreateMapper();
services.AddSingleton(mapper);
#endregion
//cors
services.AddCors(options =>
{
options.AddPolicy("cors", builder =>
{
builder.AllowAnyOrigin();
builder.AllowAnyMethod();
builder.AllowAnyHeader();
});
});
//版本号
#region API versioning
services.AddApiVersioning(options =>
{
options.ReportApiVersions = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
});
services.AddVersionedApiExplorer(options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
#endregion
//Swagger 配置
services.AddTransient<IConfigureOptions<SwaggerGenOptions>, SwaggerConfigureOptions>();
services.AddSwaggerGen(options =>
{
options.IncludeXmlComments(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LangGuan.xml"));
});
#region
services.AddTransient<Hj212Service>();
services.AddTransient<EmployeeService>();
services.AddTransient<AlertService>();
services.AddTransient<DeviceSerive>();
services.AddTransient<VideoService>();
services.AddTransient<RadarService>();
services.AddTransient<GroupService>();
services.AddTransient<RadarItemService>(); //定时任务
services.AddTransient<GroupService>();
services.AddTransient<PlcHelper2>();
services.AddTransient<PlcHelper>();
services.AddTransient<DeviceUsedService>();
services.AddSingleton<MyJob>();
services.AddJobService();
#endregion
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
IApiVersionDescriptionProvider apiVersionDescriptionProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseRouting();
app.UseCors("cors");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSwagger(options =>
{
options.PreSerializeFilters.Add((swagger, req) =>
{
swagger.Servers = new List<OpenApiServer>() { new OpenApiServer() { Url = $"http://{req.Host}" } };
});
});
app.UseSwaggerUI(options =>
{
foreach (var desc in apiVersionDescriptionProvider.ApiVersionDescriptions)
{
//配置swagger.json
options.SwaggerEndpoint($"/swagger/{desc.GroupName}/swagger.json", desc.ApiVersion.ToString());
options.DefaultModelsExpandDepth(-1);
options.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
//配置swagger访问首页
options.RoutePrefix = "api/LangGuan";
}
});
}
}
}

15
WeatherForecast.cs Normal file
View File

@ -0,0 +1,15 @@
using System;
namespace LangGuan
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
}

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

17
appsettings.json Normal file
View File

@ -0,0 +1,17 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"MongoDBConn": "mongodb://admin:adminn@101.43.201.20:8017", //ip
//"MongoDBConn": "mongodb://admin:adminn@:db", //ip
"MongoDBSetting": {
"DBName": "langguan"
},
"water": 1, //
"power": 10.5 //
}

BIN
wwwroot/model/1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

797
wwwroot/model/3.06.txt Normal file
View File

@ -0,0 +1,797 @@
水稻 15% 401010100000676
乌龟 15% 401010100000676
山鸡 15% 401010100002273
兔子 15% 401010100003113
胡萝卜 15% 401010100004099
山羊 15% 401010100006006
水稻 15% 401010100006392
山鸡 15% 401010100009678
山鸡 15% 401010100017929
胡萝卜 15% 401010100018194
山鸡 15% 401010100018797
黄瓜 15% 401010100020825
家猪 15% 401010100021433
山羊 15% 401010200006444
向日葵 15% 401010200007942
毛驴 15% 401010200010435
兔子 15% 401010200014231
土豆 15% 401010200014603
奶牛 15% 401010200014631乌龟 15% 401010200014850
毛驴 15% 401010200015520
毛驴 15% 401010200018907
土豆 15% 401010200019452
土豆 15% 401010200021384
兔子 15% 401010200026957
茄子 15% 401010300003462
毛驴 15% 401010300004457
向日葵 15% 401010300008187
橘猫 15% 401010300008713
兔子 15% 401010300012233
胡萝卜 15% 401010300015192
兔子 15% 401010300015740
兔子 15% 401010300017252
兔子 15% 401010300017470
向日葵 15% 401010300018120
西红柿 15% 401010500003984
向日葵 15% 401010500004722
鸳鸯 15% 401010500007227
水稻 15% 401010500009002
山鸡 15% 401010500009703
毛驴 15% 401010500010224
山鸡 15% 401010700021716
兔子 15% 401010700022738
鸳鸯 15% 401011000015179
土狗 15% 401011100004215
土狗 15% 401011100010938
鹅 15% 401011300002977
红薯 15% 401011300003154
兔子 15% 401011300003154
鹅 15% 401011300004386
鹅 15% 401011300004413
山鸡 15% 401011500000576
乌龟 15% 401011500001942
水稻 15% 401011500001974
鸳鸯 15% 401011500002179
水稻 15% 401011500002586
山羊 15% 401011500002586
玉米 15% 401011500002682
胡萝卜 15% 401011500003102
水稻 15% 401011500004720
小麦 15% 401011500005426
兔子 15% 401011500006142
茄子 15% 401011500006872
红薯 15% 401011500007085
红薯 15% 401011500007934
胡萝卜 15% 401011500008034
向日葵 15% 401011500010833
鸳鸯 15% 401011500012059
红薯 15% 401011500012086
胡萝卜 15% 401011500012624
红薯 15% 401011500012798
兔子 15% 401011500015141
兔子 15% 401011500016264
胡萝卜 15% 401011500016340
胡萝卜 15% 401011500016779
小麦 15% 401011500017399
山鸡 15% 401011500017399
胡萝卜 15% 401011500018048
土狗 15% 401011500018689
水稻 15% 401011500019046
向日葵 15% 401011500020718
山鸡 15% 401011500020795
兔子 15% 401011500020970
兔子 15% 401011500021574
橘猫 15% 401011500021617
鹅 15% 401011500021753
向日葵 15% 401011500021890
胡萝卜 15% 401011500021968
鸳鸯 15% 401011500022234
胡萝卜 15% 401011500022537
胡萝卜 15% 401011500024525
山鸡 15% 401011500024597
土狗 15% 401010300019757
毛驴 15% 401010300020310
小麦 15% 401010300021986
兔子 15% 401010400000282
向日葵 15% 401010400000830
兔子 15% 401010400001807
鹅 15% 401010400002007
胡萝卜 15% 401010400004616
西红柿 15% 401010400009171
乌龟 15% 401010400010870
家猪 15% 401010400011461
水稻 15% 401010400011623
鹅 15% 401010400012272
花菜 15% 401010400014505
毛驴 15% 401010400014779
水稻 15% 401011500024802
红薯 15% 401011500024979
家猪 15% 401011500025745
胡萝卜 15% 401011500026418
鹅 15% 401011600000068
山鸡 15% 401011600000168
小麦 15% 401011600000194
向日葵 15% 401011600000502
兔子 15% 401011600000870
水稻 15% 401011600001527
小麦 15% 401011600002008
山鸡 15% 401011600002130
西红柿 15% 401011600003106
山鸡 15% 401011600003433
小麦 15% 401011600003650
胡萝卜 15% 401011600003696
鸳鸯 15% 401011600003841
土狗 15% 401011600004199
向日葵 15% 401011600004510
水稻 15% 401011600004658
向日葵 15% 401011600005037
小麦 15% 401011600006376
水稻 15% 401011600006661
西红柿 15% 401011600007689
鹅 15% 401011600007989
鸳鸯 15% 401011600013629
茄子 15% 401011600013808
山鸡 15% 401011600014772
向日葵 15% 401011600017057
乌龟 15% 401011600017363
向日葵 15% 401011600017468
水稻 15% 401011700000173
山鸡 15% 401011700000328
山鸡 15% 401011700000359
山鸡 15% 401011700000567
鸳鸯 15% 401011700000597
乌龟 15% 401011700001098
乌龟 15% 401011800008517
鹅 15% 401011900008531
奶牛 15% 401012100003020
小麦 15% 401012100003595
茄子 15% 401012100004450
家猪 15% 401012100007649
胡萝卜 15% 401012100008454
山鸡 30% 401012100011702
鸳鸯 15% 401012100013669
花菜 15% 401012100016149
鹅 15% 401012100020736
山鸡 15% 401012100026846
红薯 15% 401012200001562
鹅 15% 401012200002286
向日葵 15% 401012200003733
鹅 15% 401012200003733
花菜 15% 401012200005631
鸳鸯 15% 401012200012368
水稻 15% 401012200013218
土豆 15% 401012200013218
兔子 15% 401012200015212
大白菜 15% 401012200015612
山羊 15% 401012200017383
山鸡 15% 401012200019066
茄子 15% 401012200023923
玉米 15% 401012200025134
山羊 15% 401012200025134
乌龟 15% 401012200025413
兔子 15% 401012200026870西红柿 15% 401012300017643
小麦 15% 401012300020328
鹅 15% 401012300020774
水稻 15% 401012300021652
毛驴 15% 401012300022320
胡萝卜 15% 401012300022946
小麦 15% 401012400002097
鹅 15% 401012400005562
茄子 15% 401012400006022
小麦 15% 401012400007539
胡萝卜 15% 401012400009308
鹅 15% 401012400009568
山鸡 15% 401012400009822
大白菜 15% 401012400013579
橘猫 15% 401012400014022
鸳鸯 15% 401012400016808
黄瓜 30% 401012400020219
山鸡 15% 401012400020483
鹅 15% 401012400021972
土豆 15% 401012400022196
水稻 15% 401012400022762
胡萝卜 15% 401012400024225
鹅 15% 401012400024351
红薯 15% 401012400024654
山鸡 15% 401012400026541
红薯 15% 401012400026935
橘猫 15% 401012400027692
水稻 15% 401012400028997
山鸡 15% 401012400032575
家猪 15% 401012500001155
家猪 15% 401012500009510
土狗 15% 401012500012710
山鸡 15% 401012500013416
鹅 15% 401012500013925
橘猫 15% 401012500014475
鹅 15% 401012500016517
橘猫 15% 401012500018581
向日葵 15% 401012500022651
家猪 15% 401012500023764
土豆 15% 401012500024268
家猪 15% 401012600001612
土狗 15% 401012600002304
向日葵 15% 401012200027034
小麦 30% 401012300003289
西红柿 15% 401012300004947
鸳鸯 15% 401012300006881
鸳鸯 30% 401012300007694
山鸡 15% 401012300007932
胡萝卜 15% 401012300014916
向日葵 15% 401012300015128
土豆 15% 401012300015128
橘猫 15% 401012300015383
橘猫 15% 401012300016169
山羊 15% 401012300016169
胡萝卜 15% 401012600004429
西红柿 15% 401012600006071
西红柿 15% 401012600006272
山鸡 15% 401012600006654
毛驴 15% 401012600009017
红薯 15% 401012600019514
橘猫 15% 401012700008219
西红柿 15% 401012700010047
红薯 15% 401012700012098
小麦 15% 401012700013881
兔子 15% 401012700013881
小麦 15% 401012700018042
水稻 15% 401012700018566
兔子 15% 401012700018618
乌龟 15% 401012700019161
毛驴 15% 401012700021724
水稻 15% 401012700022495
小麦 30% 401012700022557
山羊 15% 401012700022557
家猪 15% 401012700022665
黄牛 15% 401012700023352
向日葵 15% 401012700025684
西红柿 15% 401012800001863
胡萝卜 15% 401012800003446
西红柿 15% 401012800003446
胡萝卜 15% 401012800003797
水稻 15% 401012800004230
山鸡 15% 401012800004230
黄牛 15% 401012800005777
山羊 15% 401012800007304
鹅 15% 401012800010706
小麦 15% 401012800010870
山鸡 15% 401012800014400
西红柿 15% 401012800015923
大白菜 15% 401012800018678
西红柿 15% 401012800018899
花菜 15% 401012800019137
黄牛 15% 401012800019137
水稻 15% 401012800021434
玉米 15% 401012800022497
兔子 15% 401012900000815
鹅 15% 401012900001791
小麦 15% 401012900006709
鸳鸯 15% 401012900007456
向日葵 15% 401012900009599
西红柿 15% 401012900014153
家猪 15% 401012900015077
山鸡 15% 401012900015341
鸳鸯 15% 401012900016224
家猪 15% 401012900018748
向日葵 15% 401012900020477
黄瓜 15% 401012900020477
橘猫 15% 401013000001618
小麦 15% 401013000003150
向日葵 15% 401013000003990
向日葵 15% 401013000004134
山羊 15% 401013000004173
兔子 15% 401013000007827
家猪 30% 401013000007899
黄牛 15% 401013000009541
向日葵 15% 401013000009556
鹅 15% 401013000011241
水稻 15% 401013000013217
红薯 15% 401013000014593
小麦 15% 401013000014886
茄子 15% 401013000019274
土狗 15% 401013000021835
鸳鸯 15% 401013000021883
鹅 15% 401013000024363
兔子 15% 401013100000235
家猪 15% 401013100004283
向日葵 15% 401013100005521
兔子 15% 401013100006327
水稻 15% 401013100007819
水稻 15% 401013100010127
山羊 15% 401013100010369
西红柿 15% 401013100012122
橘猫 15% 401013100015119
向日葵 15% 401013100017842
胡萝卜 15% 401013100020927
小麦 15% 401013100022958
橘猫 15% 401013100024262
花菜 15% 401013200000336
黄牛 15% 401013200000336
鸳鸯 15% 401013200001007
花菜 15% 401013200001548
鸳鸯 15% 401013200003150
向日葵 15% 401013200008701
鸳鸯 15% 401013600001319
鸳鸯 15% 401013600002112
橘猫 15% 401013600003324
鸳鸯 15% 401013600004286
胡萝卜 15% 401013600005040
葫芦 15% 401013600005653
兔子 15% 401013600006204
西红柿 15% 401013600009034
向日葵 15% 401013600009205
山鸡 15% 401013600014505
土狗 15% 401013600014928
鹅 15% 401013600016554
胡萝卜 15% 401013600017228
兔子 15% 401013600018032
向日葵 15% 401013600018118
山鸡 15% 401013600018900
土豆 15% 401013600018999
向日葵 15% 401013600019655
小麦 15% 401013600020800
水稻 15% 401013600021203
向日葵 15% 401013600022003
水稻 15% 401013600025707
兔子 15% 401013700000186
茄子 15% 401013700001711
山鸡 15% 401013700003208
兔子 15% 401013700003218
山鸡 15% 401013700005360
鹅 15% 401013700007519
土狗 15% 401013700007696
水稻 15% 401013700018019
大白菜 15% 401013700019293
山羊 15% 401013700020271
山羊 15% 401013700023942
土狗 15% 401013800003618
山鸡 15% 401013800005098
玉米 15% 401013800007551
鸳鸯 15% 401013800007551
小麦 15% 401013800007999
乌龟 15% 401013800012291
茄子 15% 401013800012291
家猪 15% 401013800014184
鸳鸯 15% 401013800017045
鸳鸯 15% 401013800017535
西红柿 15% 401013800019650
山鸡 15% 401013800022533
西红柿 15% 401013800023982
鸳鸯 15% 401013800024172
橘猫 15% 401013800025062
鸳鸯 15% 401013900000234
花菜 15% 401013900000234
红薯 15% 401013900003336
家猪 15% 401013900003571
山鸡 15% 401013900003608
山羊 15% 401013900003757
土豆 15% 401013900003831
黄瓜 30% 401013900004160
向日葵 15% 401013900004676
红薯 15% 401013900005326
兔子 15% 401013900005697
茄子 30% 401013900005697
鸳鸯 15% 401013900006951
花菜 15% 401013900007854
鹅 15% 401013900008179
毛驴 15% 401013900008412
西红柿 15% 401013900009988
小麦 15% 401013900010032
小麦 15% 401013900011392
黄瓜 15% 401013900011936
小麦 15% 401013900016960
鸳鸯 15% 401013900018128
花菜 15% 401013900020433
胡萝卜 15% 401013900023962
向日葵 15% 401013900024110
大白菜 15% 401013900024510
土狗 15% 401013900024510
红薯 15% 401013900026511
橘猫 15% 401013900026511
向日葵 15% 401013900027129
兔子 15% 401014000000377
向日葵 15% 401014000001057
山鸡 15% 401014000002028
山羊 15% 401014000003108
乌龟 15% 401014000003511
乌龟 15% 401014000004793
橘猫 15% 401014000005508
土狗 15% 401014000007792
黄瓜 15% 401014000007830
茄子 15% 401014000008622
鹅 15% 401014000008672
土狗 15% 401014000008672
兔子 15% 401014100005536
奶牛 15% 401014100008727
山鸡 15% 401014100016671
玉米 15% 401014100022557
乌龟 15% 401014200016687
鸳鸯 15% 401014200023213
橘猫 30% 401014200024104
鸳鸯 15% 401014300009509
小麦 15% 401014300011074
鹅 15% 401014300011202
家猪 15% 401014300011566
向日葵 15% 401014300013894
鹅 15% 401014300016790
小麦 15% 401014300020097
花菜 15% 401014300020097
胡萝卜 15% 401014300020180
兔子 15% 401014300023161
山鸡 15% 401014300024404
花菜 15% 401014300025056
土狗 15% 401014300025920
胡萝卜 30% 401014400003470
鸳鸯 15% 401014400009953
向日葵 15% 401014400016662
橘猫 15% 401014400026933
小麦 15% 401014400027604
小麦 15% 401014500007548
大白菜 15% 401014500010021
山羊 15% 401014500015724
西红柿 15% 401014600008160
玉米 15% 401014700004447
山鸡 15% 401014800000368
山鸡 30% 401014800000478
绵羊 15% 401014800000600
向日葵 15% 401014800002253
小麦 15% 401014800002897
兔子 15% 401014800003646
鹅 15% 401014800003996
小麦 15% 401014800004844
山鸡 15% 401014800005559
胡萝卜 15% 401014800006065
兔子 15% 401014800006134
水稻 15% 401014800006230
兔子 15% 401014800017324
鹅 15% 401014800017383
兔子 15% 401014800018155
鹅 15% 401014800021811
胡萝卜 15% 401014800023507
向日葵 15% 401014800024228
乌龟 15% 401014900000462
家猪 15% 401014900012523
兔子 15% 401015000015606
土狗 15% 401015000016929
鹅 15% 401015000021888
兔子 15% 401015100014796
黄牛 15% 401015100018460
兔子 15% 401015100019940
兔子 15% 401015100023156
土狗 15% 401015200009515
山鸡 15% 401015200009535
兔子 30% 401015200013485
乌龟 15% 401015300001732
乌龟 15% 401015300003933
兔子 15% 401015300006282
橘猫 15% 401015300008727
胡萝卜 15% 401015400003735
向日葵 15% 401015400005528
家猪 15% 401015400005528
兔子 15% 401015400013910
鸳鸯 15% 401015400015165
山鸡 15% 401015400015923
鸳鸯 15% 401015400025750
花菜 15% 401015500000205
胡萝卜 15% 401015500004579
毛驴 15% 401015500005661
花菜 15% 401015600001892
大白菜 15% 401015600012275
水稻 15% 401015600021845
胡萝卜 15% 401015700002701
鸳鸯 15% 401015700005676
胡萝卜 15% 401015700007938
土狗 15% 401015700017319
水稻 15% 401015700025141
玉米 15% 401015800002905
黄瓜 15% 401015800012360
乌龟 15% 401015800012959
土豆 15% 401015900005317
土狗 15% 401015900020663
黄牛 15% 401015900020869
小麦 15% 401016000005543
水稻 15% 401016000007007
玉米 15% 401016100005989
胡萝卜 15% 401016100007118
兔子 15% 401016100007619
红薯 15% 401016100010239
花菜 15% 401016100010773
鹅 15% 401016100019475
黄牛 15% 401016100019941
兔子 15% 401016100020762
山羊 15% 401016100022073
水稻 15% 401016100022332
橘猫 15% 401016100023170
土豆 15% 401016100024498
小麦 15% 401016200000999
红薯 15% 401016200001643
西红柿 15% 401016200001643
土狗 30% 401016200001756
胡萝卜 15% 401016200016352
家猪 15% 401016200020104
红薯 15% 401016200021057
家猪 15% 401016200024147
西红柿 15% 401016300006194
兔子 15% 401016300006395
毛驴 15% 401016300008820
花菜 15% 401016300009133
橘猫 15% 401016300016374
小麦 15% 401016300016445
水稻 15% 401016300018664
土豆 15% 401016300018834
向日葵 15% 401016300022222
花菜 15% 401016300022222
胡萝卜 15% 401016300025811
鹅 15% 401016300025811
西红柿 15% 401016300026311
小麦 15% 401016400000652
红薯 15% 401016400005827
山鸡 15% 401016400006585
小麦 15% 401016400008395
向日葵 15% 401016400009163
橘猫 15% 401016400009620
兔子 15% 401016400010807
家猪 15% 401016400014291
小麦 15% 401016400015205
鸳鸯 15% 401016400017103
水稻 15% 401016400019860
土豆 15% 401016400019860
鹅 15% 401016400021647
向日葵 15% 401016400022730
家猪 15% 401016400023466
橘猫 15% 401016400025039
鸳鸯 15% 401016400025079
茄子 15% 401016400025810
兔子 15% 401016400026861
橘猫 15% 401016400027825
小麦 15% 401016500000042
小麦 15% 401016500001005
胡萝卜 15% 401016500001095
向日葵 15% 401016500004345
山鸡 15% 401016500004714
红薯 15% 401016500006290
山鸡 15% 401016500006856
土狗 15% 401016500006856
玉米 15% 401016500007481
玉米 15% 401016500007960
兔子 15% 401016500012564
水稻 15% 401016500013601
玉米 15% 401016500013960
鸳鸯 15% 401016500015963
鸳鸯 15% 401016500021524
向日葵 15% 401016500022319
山鸡 15% 401016500022880
兔子 15% 401016500024323
红薯 15% 401016600003031
小麦 15% 401016600004943
鹅 15% 401016600008151
土狗 15% 401016600008151
橘猫 15% 401016600008193
西红柿 15% 401016600009552
向日葵 15% 401016600013429
花菜 15% 401016600016923
橘猫 15% 401016600017342
山鸡 30% 401016600018173
向日葵 15% 401016600021243
红薯 15% 401016600021450
橘猫 15% 401016600021454
兔子 15% 401016600021599
西红柿 15% 401016600021754
鸳鸯 15% 401016600025146
茄子 15% 401016700000811
土狗 15% 401016700000811
茄子 15% 401016700001226
红薯 15% 401016700003130
水稻 15% 401016700003783
兔子 15% 401016700003783
胡萝卜 15% 401016700008442
茄子 15% 401016700008568
鹅 15% 401016700011033
小麦 15% 401016700012938
向日葵 15% 401016700013137
水稻 15% 401016700013182
乌龟 15% 401016700013452
红薯 15% 401016700013605
土狗 15% 401016700017897
鹅 15% 401016700018572
家猪 15% 401016700018614
橘猫 15% 401016700021912
鸳鸯 15% 401016700023669
橘猫 15% 401016700024658
红薯 15% 401016700025839
鸳鸯 15% 401016700026579
山鸡 15% 401016700027720
小麦 15% 401016700030039
水稻 15% 401016700032136
茄子 15% 401016700032136
胡萝卜 15% 401016800001281
山羊 15% 401016800001477
土豆 15% 401016800002055
向日葵 15% 401016800011964
胡萝卜 15% 401016800018769
小麦 15% 401016800019652
鸳鸯 15% 401016800020179
乌龟 15% 401016800020388
山羊 15% 401016800021775
玉米 15% 401016800021946
兔子 15% 401016800024229
鸳鸯 15% 401016800024698
胡萝卜 15% 401016800025891
黄牛 15% 401016800030447
鸳鸯 15% 401016800032332
绵羊 15% 401016800032332
茄子 15% 401016800032636
向日葵 15% 401016800033285
家猪 15% 401016800033646
向日葵 15% 401016800037149
大白菜 15% 401016800037581
西红柿 15% 401016900001737
西红柿 15% 401016900001811
红薯 15% 401016900002854
大白菜 15% 401016900005989
红薯 15% 401016900006402
水稻 15% 401016900006950
兔子 15% 401016900011867
葫芦 15% 401016900014439
橘猫 15% 401016900015496
胡萝卜 15% 401016900016058
奶牛 15% 401016900020353
茄子 15% 401016900024024
西红柿 15% 401016900027051
兔子 15% 401016900027964
茄子 15% 401017000005988
兔子 15% 401017000008538
水稻 15% 401017000013251
黄牛 15% 401017000013659
玉米 15% 401017000013986
小麦 15% 401017000019042
黄瓜 15% 401017000020020
小麦 15% 401017000020259
兔子 15% 401017000020259
水稻 15% 401017000020324
兔子 15% 401017000020324
土狗 15% 401017000021808
大白菜 15% 401017000022734
向日葵 15% 401017000023821
橘猫 15% 401017000025339
家猪 15% 401017000026123
山羊 15% 401017100000773
土狗 15% 401017100003037
橘猫 15% 401017100004259
毛驴 15% 401017100012182
茄子 15% 401017100012545
胡萝卜 15% 401017100013605
鸳鸯 15% 401017100015523
鸳鸯 15% 401017100017831
胡萝卜 15% 401017100018522
家猪 15% 401017100019488
玉米 15% 401017100020558
红薯 15% 401017100023041
土狗 15% 401017200003047
土豆 15% 401017200005912
鹅 15% 401017200008746
橘猫 15% 401017200013513
玉米 15% 401017200017602
水稻 15% 401017200021009
土狗 15% 401017200024089
红薯 15% 401017200025866
土狗 15% 401017300001865
山鸡 15% 401017300003401
家猪 15% 401017300005369
鹅 15% 401017300005686
西红柿 15% 401017300006344
向日葵 15% 401017300006433
土狗 15% 401017300006433
山羊 15% 401017300006458
土狗 15% 401017300007078
胡萝卜 15% 401017300008093
兔子 30% 401017300008098
花菜 15% 401017300008098
土狗 15% 401017300008382
橘猫 15% 401017300010265
土狗 15% 401017300012216
土狗 15% 401017300012521
水稻 15% 401017300013174
花菜 15% 401017300013623
向日葵 15% 401017300016310
土狗 15% 401017300019133
土狗 15% 401017300021558
向日葵 15% 401017300021676
家猪 15% 401017300022215
家猪 15% 401017300026859
花菜 15% 401017300028823
山鸡 15% 401017400003211
小麦 30% 401017400008259
西红柿 15% 401017400009627
西红柿 15% 401017400010843
家猪 15% 401017400011319
土狗 15% 401017400013961
橘猫 15% 401017400015375
山鸡 15% 401017400019397
胡萝卜 15% 401017400022025
胡萝卜 15% 401017400022637
橘猫 15% 401017400022637
绵羊 15% 401017400022637
鸳鸯 15% 401017400023168
黄瓜 15% 401017400023218
胡萝卜 15% 401017400024221
小麦 30% 401017400024255
鹅 15% 401017400025088
毛驴 15% 401017400026596
红薯 15% 401017400027825
土狗 15% 401017400029871
鹅 15% 401017400030114
黄瓜 15% 401017400031736
鸳鸯 15% 401017500000934
橘猫 15% 401017500001649
乌龟 15% 401017500002591
胡萝卜 15% 401017500002909
胡萝卜 15% 401017500006134
胡萝卜 15% 401017500008494
土狗 15% 401017500008824
小麦 15% 401017500009186
兔子 15% 401017500009597
绵羊 15% 401017500009787
向日葵 15% 401017500009882
鸳鸯 15% 401017500010239
胡萝卜 15% 401017500010663
小麦 15% 401017500011284
小麦 15% 401017500011773
向日葵 15% 401017500016743
向日葵 15% 401017500016800
红薯 15% 401017500017021
花菜 15% 401017500017355
水稻 15% 401017500017884
胡萝卜 15% 401017500019379
西红柿 15% 401017500020947
西红柿 30% 401017500022358
土狗 15% 401017500025210
山羊 15% 401017500025307
山羊 15% 401017500025461
橘猫 15% 401017500025727
小麦 15% 401017500027130
鸳鸯 15% 401017500027130
红薯 15% 401017600001676
向日葵 15% 401017600002649
乌龟 15% 401017600004566
山鸡 15% 401017600004836
毛驴 15% 401017600004836
兔子 15% 401017600009053
小麦 15% 401017600011222
家猪 15% 401017600013873
鸳鸯 15% 401017600015748
橘猫 15% 401017600017103
小麦 15% 401017600018584
鸳鸯 15% 401017600018779
家猪 15% 401017600022655
胡萝卜 15% 401017600023092
胡萝卜 15% 401017600024517
鹅 15% 401017600026643
胡萝卜 15% 401017600027506
土狗 15% 401017700000690
小麦 15% 401017700000932
鸳鸯 15% 401017700001390
胡萝卜 15% 401017700001636
玉米 15% 401017700003706
鸳鸯 30% 401017700007439
鸳鸯 15% 401017700007835
胡萝卜 15% 401017700012740
鹅 15% 401017700013474
向日葵 15% 401017700015605
小麦 15% 401017700016228
向日葵 15% 401017700016254
土狗 15% 401017700016254
红薯 15% 401017700019101
兔子 15% 401017700019795
家猪 15% 401017700019795
橘猫 15% 401017700021052
红薯 15% 401019000019106
毛驴 15% 401019300011412
山羊 15% 401019300021797
小麦 15% 401019500002518
西红柿 15% 401019500017604
花菜 15% 401019600003195
土狗 15% 401019700020084
西红柿 15% 401019900015888
鹅 15% 401020000021356