初始化

This commit is contained in:
2025-11-21 08:48:01 +08:00
commit b4d684a84c
202 changed files with 28585 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "9.0.7",
"commands": [
"dotnet-ef"
],
"rollForward": false
}
}
}

View File

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Services\KafkaConsume1.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Confluent.Kafka" Version="2.11.0" />
<PackageReference Include="MongoDB.Driver" Version="3.4.1" />
<PackageReference Include="NLog" Version="6.0.2" />
<PackageReference Include="NLog.Schema" Version="6.0.2" />
<PackageReference Include="NPOI" Version="2.7.4" />
<PackageReference Include="RestSharp" Version="112.1.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CommonEntity\CommonEntity.csproj" />
<ProjectReference Include="..\CommonTools\CommonTools.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<NameOfLastUsedPublishProfile>E:\tian\BLS\BLWLogServer\BLWLogServer\Properties\PublishProfiles\FolderProfile.pubxml</NameOfLastUsedPublishProfile>
<Controller_SelectedScaffolderID>ApiControllerEmptyScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Common/Api</Controller_SelectedScaffolderCategoryPath>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,6 @@
@BLWLogServer_HostAddress = http://localhost:5245
GET {{BLWLogServer_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@@ -0,0 +1,54 @@
using CommonEntity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver;
namespace BLWLogServer.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class PowerController : ControllerBase
{
public IMongoClient _client;
public PowerController(IMongoClient mongo)
{
this._client = mongo;
}
[HttpPost()]
public ReturnInfo GetPowerAnalysis([FromBody] QueryDate query)
{
ReturnInfo r = new ReturnInfo();
try
{
int size = query.PageSize;
int index = query.PageIndex;
string st = query.Start_Time;
string et = query.End_Time;
DateTime sst = DateTime.Parse(st);
DateTime eet = DateTime.Parse(et);
var collection = _client.GetDatabase("udppackage").GetCollection<NengHao_db>("powermonitor");
//构建查询条件
long code = 0;
long.TryParse(query.HotelCode,out code);
var filter = Builders<NengHao_db>.Filter.And(
Builders<NengHao_db>.Filter.Gt(x => x.ReportTime, sst),
Builders<NengHao_db>.Filter.Lt(x => x.ReportTime, eet),
Builders<NengHao_db>.Filter.Eq(x => x.HotelCode, code)
);
long totalCount = collection.CountDocuments(filter);
var results = collection.Find(filter).ToList(); // 跳过前面的记录
r.isok = true;
r.response = results;
}
catch (Exception ex)
{
r.isok = false;
r.message = ex.Message;
}
return r;
}
}
}

View File

@@ -0,0 +1,977 @@
using System;
using CommonEntity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Newtonsoft.Json;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using RestSharp;
namespace BLWLogServer.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class UDPPackageController : ControllerBase
{
public IMongoClient _client;
public UDPPackageController(IMongoClient mongo)
{
this._client = mongo;
}
[HttpPost()]
public ReturnInfo GetUDPTotalAnalysis([FromBody] QueryDate query)
{
ReturnInfo r = new ReturnInfo();
try
{
int size = query.PageSize;
int index = query.PageIndex;
string st = query.Start_Time;
string et = query.End_Time;
DateTime sst = DateTime.Parse(st);
DateTime eet = DateTime.Parse(et);
var collection = _client.GetDatabase("udppackage").GetCollection<UDPPackage_db>("totalcount");
//构建查询条件
var filter = Builders<UDPPackage_db>.Filter.And(
Builders<UDPPackage_db>.Filter.Gt(x => x.RemoveTime, sst),
Builders<UDPPackage_db>.Filter.Lt(x => x.RemoveTime, eet)
);
// 获取总记录数(可选,用于前端分页显示总页数)
long totalCount = collection.CountDocuments(filter);
// //执行查询
//var results = collection.Find(filter).Skip((index - 1) * size) // 跳过前面的记录
//.Limit(size).ToList(); // 限制返回的记录数.ToList();
var results = collection.Find(filter).ToList(); // 跳过前面的记录
r.isok = true;
r.response = results;
}
catch (Exception ex)
{
r.isok = false;
r.message = ex.Message;
}
return r;
}
[HttpPost()]
public ReturnInfo GetUDPPackageTimeAnalysis([FromBody] QueryDate query)
{
ReturnInfo r = new ReturnInfo();
try
{
int size = query.PageSize;
int index = query.PageIndex;
string st = query.Start_Time;
string et = query.End_Time;
DateTime sst = DateTime.Parse(st);
DateTime eet = DateTime.Parse(et);
var collection = _client.GetDatabase("udppackage").GetCollection<StepInfo_db>("zeroe_stepmonitor");
//构建查询条件
var filter = Builders<StepInfo_db>.Filter.And(
Builders<StepInfo_db>.Filter.Gt(x => x.TriggerTime, sst),
Builders<StepInfo_db>.Filter.Lt(x => x.TriggerTime, eet)
);
// 获取总记录数(可选,用于前端分页显示总页数)
long totalCount = collection.CountDocuments(filter);
// //执行查询
//var results = collection.Find(filter).Skip((index - 1) * size) // 跳过前面的记录
//.Limit(size).ToList(); // 限制返回的记录数.ToList();
// 使用聚合管道实现分组、排序和分页
//var aggregation = collection.Aggregate()
// .Match(filter) // 先筛选时间范围内的文档
// .Group(
// x => x.MessageId, // 按MessageId分组
// g => new
// {
// MessageId = g.Key, // 分组键
// Items = g.ToList() // 分组内的所有文档
// //Count = g.Count() // 每组的文档数
// })
// .Skip((index - 1) * size) // 分页跳过
// .Limit(size); // 分页限制
var results = collection.Find(filter).ToList().OrderByDescending(A => A.TriggerTime); // 跳过前面的记录
//var results = aggregation.ToList();
var USA = results.GroupBy(A => A.MessageId);
r.isok = true;
r.response = USA.ToList();
}
catch (Exception ex)
{
r.isok = false;
r.message = ex.Message;
}
return r;
}
/// <summary>
/// 获取语音IOT平台的数据
/// </summary>
/// <param name="QueryData"></param>
/// <returns></returns>
[HttpPost()]
public ReturnInfo Get_IOTLog([FromBody] LogQuery q)
{
ReturnInfo info = new ReturnInfo();
info.isok = true;
try
{
List<IOTMonitorData_db> lg = new List<IOTMonitorData_db>();
string? st = q?.Start_Time;
string? et = q?.End_Time;
int PageSize = q.PageSize;
int PageIndex = q.PageIndex;
List<string> c11 = q.CommandType;
int AAA = (PageIndex - 1) * PageSize;
DateTime sst = DateTime.Parse(st);
DateTime eet = DateTime.Parse(et);
string? st1 = q?.Start_Time_Really;
string? et1 = q?.End_Time_Really;
DateTime sst1 = DateTime.Parse(st1);
DateTime eet1 = DateTime.Parse(et1);
if (eet < sst)
{
info.isok = false;
info.message = "结束时间不能大于开始时间";
return info;
}
var qqqq = q?.Data;
IAggregateFluent<IOTMonitorData_db> NNN = null;
var collection = _client.GetDatabase("udppackage").GetCollection<IOTMonitorData_db>("voiceiotlog");
var pipeline = collection.Aggregate();
NNN = pipeline.Match(s => s.CreateTime >= sst && s.CreateTime <= eet);
if (qqqq?.Count > 0)
{
var orConditions = new List<FilterDefinition<IOTMonitorData_db>>();
foreach (var item in qqqq)
{
if (!string.IsNullOrEmpty(item.HotelCode) && !string.IsNullOrEmpty(item.RoomNumber))
{
var andCondition = Builders<IOTMonitorData_db>.Filter.And(
Builders<IOTMonitorData_db>.Filter.Eq("HotelCode", item.HotelCode),
Builders<IOTMonitorData_db>.Filter.Eq("RoomNumber", item.RoomNumber)
);
orConditions.Add(andCondition);
}
else if (!string.IsNullOrEmpty(item.HotelCode) && string.IsNullOrEmpty(item.RoomNumber))
{
var andCondition = Builders<IOTMonitorData_db>.Filter.And(
Builders<IOTMonitorData_db>.Filter.Eq("HotelCode", item.HotelCode)
);
orConditions.Add(andCondition);
}
else
{
}
}
var orFilter = Builders<IOTMonitorData_db>.Filter.Or(orConditions);
NNN = NNN.Match(orFilter);
}
var results = NNN.ToList().OrderByDescending(A => A.CreateTime);
var Q = results.ToList();
DevMonitorIOTLogResult_WITH_Count c = new DevMonitorIOTLogResult_WITH_Count();
c.devMonitorLogResults = Q;
c.TotalCount = Q.Count;
info.response = c;
}
catch (Exception ex)
{
info.isok = false;
info.message = ex.Message;
}
return info;
}
[HttpPost()]
public ReturnInfo Get_IOTLogCount([FromBody] LogQuery q)
{
ReturnInfo info = new ReturnInfo();
info.isok = true;
try
{
List<IOTMonitorData_db> lg = new List<IOTMonitorData_db>();
string? st1 = q?.Start_Time_Really;
string? et1 = q?.End_Time_Really;
DateTime sst1 = DateTime.Parse(st1);
DateTime eet1 = DateTime.Parse(et1);
if (eet1 < sst1)
{
info.isok = false;
info.message = "结束时间不能大于开始时间";
return info;
}
var qqqq = q?.Data;
//var h11 = qqqq?.Select(x => x.HotelCode).Distinct().Where(A => !string.IsNullOrEmpty(A)).ToList();
//var r11 = qqqq?.Select(x => x.RoomNumber).Distinct().Where(A => !string.IsNullOrEmpty(A)).ToList();
DevMonitorIOTLogResult_WITH_Count c = new DevMonitorIOTLogResult_WITH_Count();
var collection = _client.GetDatabase("udppackage").GetCollection<IOTMonitorData_db>("voiceiotlog");
//构建查询条件
if (q.IsQuery_Really)
{
IAggregateFluent<IOTMonitorData_db> NNN = null;
var pipeline = collection.Aggregate();
NNN = pipeline.Match(s => s.CreateTime >= sst1 && s.CreateTime <= eet1);
//if (h11.Count > 0 && r11.Count == 0)
//{
// NNN = pipeline.Match(s => s.CreateTime >= sst1 && s.CreateTime <= eet1 && h11.Contains(s.HotelCode.ToString()));
//}
//if (h11.Count > 0 && r11.Count > 0)
//{
// NNN = pipeline.Match(s => s.CreateTime >= sst1 && s.CreateTime <= eet1 && h11.Contains(s.HotelCode.ToString()) && r11.Contains(s.RoomNumber));
//}
// 2. 动态生成 HotelCode 和 HostNUMBER 的 OR 条件
if (qqqq?.Count > 0)
{
var orConditions = new List<FilterDefinition<IOTMonitorData_db>>();
foreach (var item in qqqq)
{
if (!string.IsNullOrEmpty(item.HotelCode) && !string.IsNullOrEmpty(item.RoomNumber))
{
var andCondition = Builders<IOTMonitorData_db>.Filter.And(
Builders<IOTMonitorData_db>.Filter.Eq("HotelCode", item.HotelCode),
Builders<IOTMonitorData_db>.Filter.Eq("RoomNumber", item.RoomNumber)
);
orConditions.Add(andCondition);
}
else if (!string.IsNullOrEmpty(item.HotelCode) && string.IsNullOrEmpty(item.RoomNumber))
{
var andCondition = Builders<IOTMonitorData_db>.Filter.And(
Builders<IOTMonitorData_db>.Filter.Eq("HotelCode", item.HotelCode)
);
orConditions.Add(andCondition);
}
else
{
}
}
// 将 OR 条件添加到管道
var orFilter = Builders<IOTMonitorData_db>.Filter.Or(orConditions);
NNN = NNN.Match(orFilter);
}
var MMM = NNN.Group(
s => s.RequestId,
g => new
{
RequestId = g.Key,
Count = g.Count(),
ContainsFive = g.Any(x => x.Step == 5)
}
)
.SortByDescending(x => x.RequestId)
.ToList();
var NotContainStep5 = MMM.Where(A => !A.ContainsFive).Count();
var C = MMM.Sum(A => A.Count);
c.RequestIdCount = C;
c.RequestNotContainerCount = NotContainStep5;
}
else
{
c.RequestIdCount = 0;
}
info.response = c;
}
catch (Exception ex)
{
info.isok = false;
info.message = ex.Message;
}
return info;
}
/// <summary>
///获取取电状态
/// </summary>
/// <param name="q"></param>
/// <returns></returns>
[HttpPost()]
public async Task<ReturnInfo> Get_TakeCardStatus([FromBody] LogQuery q)
{
ReturnInfo info = new ReturnInfo();
info.isok = true;
try
{
List<IOTMonitorData_db> lg = new List<IOTMonitorData_db>();
string? st1 = q?.Start_Time;
string? et1 = q?.End_Time;
DateTime sst1 = DateTime.Parse(st1);
DateTime eet1 = DateTime.Parse(et1);
if (eet1 < sst1)
{
info.isok = false;
info.message = "结束时间不能大于开始时间";
return info;
}
var qqqq = q?.Data;
var collection = _client.GetDatabase("udppackage").GetCollection<MTakeCardData_db>("takecardlog");
// 定义多个条件组合
// 动态条件列表
FilterDefinition<MTakeCardData_db> filter = Builders<MTakeCardData_db>.Filter.And(
Builders<MTakeCardData_db>.Filter.Gt(x => x.LastUpdateTime, sst1),
Builders<MTakeCardData_db>.Filter.Lt(x => x.LastUpdateTime, eet1)
);
var conditions = new List<FilterDefinition<MTakeCardData_db>>();
foreach (var item in qqqq)
{
if (!string.IsNullOrEmpty(item.HotelCode) && !string.IsNullOrEmpty(item.Key_HostNumber))
{
var q1 = Builders<MTakeCardData_db>.Filter.And(
Builders<MTakeCardData_db>.Filter.Eq("HotelCode", item.HotelCode),
Builders<MTakeCardData_db>.Filter.Eq("HostNUMBER", item.Key_HostNumber)
);
conditions.Add(q1);
}
else if (!string.IsNullOrEmpty(item.HotelCode))
{
var q1 = Builders<MTakeCardData_db>.Filter.And(
Builders<MTakeCardData_db>.Filter.Eq("HotelCode", item.HotelCode)
);
conditions.Add(q1);
}
else
{
}
}
// 组合所有 HotelCode 和 HostNUMBER 的条件为 OR
var combinedHotelHostFilter = conditions.Count > 0
? Builders<MTakeCardData_db>.Filter.Or(conditions)
: Builders<MTakeCardData_db>.Filter.Empty; // 如果没有条件,则不限制
// 最终条件:时间范围 AND (HotelCode + HostNUMBER 的 OR 组合)
var finalFilter = Builders<MTakeCardData_db>.Filter.And(
filter,
combinedHotelHostFilter
);
var dynamicResults = await collection.Find(finalFilter).ToListAsync();
info.response = dynamicResults;
}
catch (Exception ex)
{
info.isok = false;
info.message = ex.Message;
}
return info;
}
[HttpPost()]
public async Task<ReturnInfo> Get_BeforeTakeCardStatus([FromBody] LogQuery q)
{
ReturnInfo info = new ReturnInfo();
info.isok = true;
try
{
string? st1 = q?.Start_Time;
string? et1 = q?.End_Time;
DateTime sst1 = DateTime.Parse(st1);
DateTime eet1 = DateTime.Parse(et1);
if (eet1 < sst1)
{
info.isok = false;
info.message = "结束时间不能大于开始时间";
return info;
}
var qqqq = q?.Data;
if (qqqq.Count > 1)
{
info.isok = false;
info.message = "只能查询单个房间";
return info;
}
string? hotelcode = qqqq.FirstOrDefault()?.HotelCode;
string? hostnumber = qqqq.FirstOrDefault()?.Key_HostNumber;
var collection1 = _client.GetDatabase("udppackage").GetCollection<MTakeCardData_db>("takecardlog");
var collection2 = _client.GetDatabase("udppackage").GetCollection<OnOffLineData_db>("rcustatuslog");
FilterDefinition<MTakeCardData_db> filter1 = Builders<MTakeCardData_db>.Filter.And(
Builders<MTakeCardData_db>.Filter.Lt(x => x.LastUpdateTime, sst1),
Builders<MTakeCardData_db>.Filter.Eq(x => x.HotelCode, hotelcode),
Builders<MTakeCardData_db>.Filter.Eq(x => x.HostNUMBER, hostnumber)
);
var finalFilter1 = Builders<MTakeCardData_db>.Filter.And(filter1);
var dynamicResults1 = await collection1.Find(finalFilter1).SortByDescending(x => x.LastUpdateTime).Limit(1).FirstOrDefaultAsync();
FilterDefinition<OnOffLineData_db> filter2 = Builders<OnOffLineData_db>.Filter.And(
Builders<OnOffLineData_db>.Filter.Lt(x => x.CurrentTime, sst1),
Builders<OnOffLineData_db>.Filter.Eq(x => x.HotelCode, hotelcode),
Builders<OnOffLineData_db>.Filter.Eq(x => x.HostNumber, hostnumber)
);
var finalFilter2 = Builders<OnOffLineData_db>.Filter.And(filter2);
var dynamicResults2 = await collection2.Find(finalFilter2).SortByDescending(A => A.CurrentTime).Limit(1).FirstOrDefaultAsync();
info.response = new { RCUStatus = dynamicResults2, TakeCardStatus = dynamicResults1 };
}
catch (Exception ex)
{
info.isok = false;
info.message = ex.Message;
}
return info;
}
private static bool CreatePredicate(List<QueryData> items, string hotelcode, string hostnumber)
{
List<bool> bools = new List<bool>();
foreach (var item in items)
{
bool KKK = item.HotelCode.Equals(hotelcode) && item.Key_HostNumber.Equals(hostnumber);
bools.Add(KKK);
}
// 使用 Aggregate 将列表中的布尔值用 || 连接
bool result = bools.Aggregate((current, next) => current || next);
return result;
}
/// <summary>
/// RCU 连线,断线状态
/// </summary>
/// <param name="q"></param>
/// <returns></returns>
[HttpPost()]
public async Task<ReturnInfo> Get_RCUStatus([FromBody] LogQuery q)
{
ReturnInfo info = new ReturnInfo();
info.isok = true;
try
{
string? st1 = q?.Start_Time;
string? et1 = q?.End_Time;
DateTime sst1 = DateTime.Parse(st1);
DateTime eet1 = DateTime.Parse(et1);
if (eet1 < sst1)
{
info.isok = false;
info.message = "结束时间不能大于开始时间";
return info;
}
var qqq = q?.Data;
var collection = _client.GetDatabase("udppackage").GetCollection<OnOffLineData_db>("rcustatuslog");
FilterDefinition<OnOffLineData_db> filter = Builders<OnOffLineData_db>.Filter.And(
Builders<OnOffLineData_db>.Filter.Gt(x => x.CurrentTime, sst1),
Builders<OnOffLineData_db>.Filter.Lt(x => x.CurrentTime, eet1)
);
var conditions = new List<FilterDefinition<OnOffLineData_db>>();
conditions.Add(filter);
foreach (var item in qqq)
{
if (!string.IsNullOrEmpty(item.HotelCode) && string.IsNullOrEmpty(item.Key_HostNumber))
{
var q1 = Builders<OnOffLineData_db>.Filter.And(
Builders<OnOffLineData_db>.Filter.Eq("HotelCode", item.HotelCode)
);
conditions.Add(q1);
}
else if (!string.IsNullOrEmpty(item.HotelCode) && !string.IsNullOrEmpty(item.Key_HostNumber))
{
var q1 = Builders<OnOffLineData_db>.Filter.And(
Builders<OnOffLineData_db>.Filter.Eq("HotelCode", item.HotelCode),
Builders<OnOffLineData_db>.Filter.Eq("HostNumber", item.Key_HostNumber)
);
conditions.Add(q1);
}
else
{
}
}
// 组合所有条件为 AND 关系(时间范围 + 其他条件)
var finalFilter = Builders<OnOffLineData_db>.Filter.And(conditions);
// 执行查询
var dynamicResults = await collection.Find(finalFilter).ToListAsync();
info.response = dynamicResults;
}
catch (Exception ex)
{
info.isok = false;
info.message = ex.Message;
}
return info;
}
public static string BaseUrl = "https://www.boonlive-rcu.com/";
/// <summary>
/// 设置时间
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
[HttpPost()]
public async Task<ReturnInfo> TongJiTimerIntervalSet(TimerData data)
{
ReturnInfo r = new ReturnInfo();
try
{
var options = new RestClientOptions(BaseUrl);
var client = new RestClient(options);
var request = new RestRequest("api/TongJiTimerIntervalSet");
request.AddParameter("interval_Minutes", data.interval_Minutes);
RestResponse response = await client.PostAsync(request);
string? str1 = response.Content;
r.isok = true;
r.response = str1;
}
catch (Exception ex)
{
r.isok = false;
r.response = ex.Message;
}
return r;
}
/// <summary>
/// 间隔多久的数据会被丢弃
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
[HttpPost()]
public async Task<ReturnInfo> UDPLostDataIntervalSet(TimerData data)
{
ReturnInfo r = new ReturnInfo();
try
{
var options = new RestClientOptions(BaseUrl);
var client = new RestClient(options);
var request = new RestRequest("api/DefineUDPLostDataInterval");
request.AddParameter("Interval", data.interval_Minutes);
RestResponse response = await client.PostAsync(request);
string? str1 = response.Content;
r.isok = true;
r.response = str1;
}
catch (Exception ex)
{
r.isok = false;
r.response = ex.Message;
}
return r;
}
/// <summary>
/// UDP 几包数据丢一包
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
[HttpPost()]
public async Task<ReturnInfo> UDPLostDataRateSet(TimerData data)
{
ReturnInfo r = new ReturnInfo();
try
{
var options = new RestClientOptions(BaseUrl);
var client = new RestClient(options);
var request = new RestRequest("api/DefineUDPLostDataRate");
request.AddParameter("LostHz", data.interval_Minutes);
RestResponse response = await client.PostAsync(request);
string? str1 = response.Content;
r.isok = true;
r.response = str1;
}
catch (Exception ex)
{
r.isok = false;
r.response = ex.Message;
}
return r;
}
/// <summary>
/// 同时设置3个数据
/// </summary>
/// <param name="dataList"></param>
/// <returns></returns>
[HttpPost()]
public async Task<ReturnInfo> ConfigParameterSet(List<TTT> dataList)
{
ReturnInfo r = new ReturnInfo();
try
{
var options = new RestClientOptions(BaseUrl);
var client = new RestClient(options);
foreach (var item in dataList)
{
string Key = item.key;
int V = item.value;
if (Key.Equals("超时08"))
{
var request = new RestRequest("api/DefineUDPLostDataInterval");
request.AddParameter("Interval", V);
RestResponse response = await client.PostAsync(request);
}
if (Key.Equals("丢弃比例"))
{
var request = new RestRequest("api/DefineUDPLostDataRate");
request.AddParameter("LostHz", V);
RestResponse response = await client.PostAsync(request);
}
if (Key.Equals("统计周期"))
{
var request = new RestRequest("api/TongJiTimerIntervalSet");
request.AddParameter("interval_Minutes", V);
RestResponse response = await client.PostAsync(request);
}
}
r.isok = true;
r.response = "success";
}
catch (Exception ex)
{
r.isok = false;
r.response = ex.Message;
}
return r;
}
[HttpPost()]
[HttpPost()]
public IActionResult ExportUDPTotalAnalysis([FromBody] QueryDate query)
{
string tempFilePath = null;
try
{
string st = query.Start_Time;
string et = query.End_Time;
DateTime sst = DateTime.Parse(st);
DateTime eet = DateTime.Parse(et);
var collection = _client.GetDatabase("udppackage").GetCollection<UDPPackage_db>("totalcount");
// 构建查询条件
var filter = Builders<UDPPackage_db>.Filter.And(
Builders<UDPPackage_db>.Filter.Gt(x => x.RemoveTime, sst),
Builders<UDPPackage_db>.Filter.Lt(x => x.RemoveTime, eet)
);
// 获取所有记录
var allResults = collection.Find(filter).ToList();
if (allResults == null || allResults.Count == 0)
{
return NotFound("没有找到数据");
}
// 转换数据为二维表格格式
var transformedData = TransformDataForExport(allResults);
// 创建临时文件
tempFilePath = Path.GetTempFileName() + ".xlsx";
// 生成Excel文件到临时文件
using (var fileStream = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write))
{
var workbook = CreateExcelWorkbook(transformedData);
workbook.Write(fileStream);
}
// 读取临时文件内容到内存流
var fileBytes = System.IO.File.ReadAllBytes(tempFilePath);
var memoryStream = new MemoryStream(fileBytes);
// 返回Excel文件
return File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
$"UDP数据统计_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx");
}
catch (Exception ex)
{
return StatusCode(500, $"导出失败: {ex.Message}");
}
finally
{
// 清理临时文件
if (tempFilePath != null && System.IO.File.Exists(tempFilePath))
{
try
{
System.IO.File.Delete(tempFilePath);
}
catch
{
// 忽略删除失败的情况
}
}
}
}
// 数据转换方法类似前端的transformData逻辑
private List<ExportDataRow> TransformDataForExport(List<UDPPackage_db> data)
{
// 提取所有唯一的commandType
var types = data.Select(item => item.CommandType).Distinct().ToList();
// 按分钟间隔分组
var groupedByTime = new Dictionary<string, ExportDataRow>();
foreach (var item in data)
{
// 获取时间对象
var time = item.RemoveTime;
// 精确到分钟的时间格式
var repTime = time.ToString("yyyy-MM-dd HH:mm");
if (!groupedByTime.ContainsKey(repTime))
{
groupedByTime[repTime] = new ExportDataRow
{
RemoveTime = repTime,
// 初始化所有类型为0L (使用long类型)
TypeValues = types.ToDictionary(type => type, _ => 0L)
};
}
// 累加对应类型的值 - 使用long类型
if (groupedByTime[repTime].TypeValues.ContainsKey(item.CommandType))
{
groupedByTime[repTime].TypeValues[item.CommandType] += item.TotalCount;
}
}
// 排序时间(从最新到最早)
return groupedByTime.Values
.OrderByDescending(row => DateTime.Parse(row.RemoveTime))
.ToList();
}
// 创建Excel工作簿
// 创建Excel工作簿 - 美化版本
private IWorkbook CreateExcelWorkbook(List<ExportDataRow> data)
{
var workbook = new XSSFWorkbook();
// 创建单元格样式
var headerStyle = CreateHeaderStyle(workbook);
var evenRowStyle = CreateCellStyle(workbook, IndexedColors.LightCornflowerBlue.Index);
var oddRowStyle = CreateCellStyle(workbook, IndexedColors.White.Index);
var dateStyle = CreateCellStyle(workbook, IndexedColors.White.Index, true);
var sheet = workbook.CreateSheet("UDP数据统计");
// 获取所有唯一的命令类型
var allTypes = data.SelectMany(row => row.TypeValues.Keys).Distinct().ToList();
// 创建表头
var headerRow = sheet.CreateRow(0);
headerRow.HeightInPoints = 20; // 设置行高
// 时间段列
var timeCell = headerRow.CreateCell(0);
timeCell.SetCellValue("时间段");
timeCell.CellStyle = headerStyle;
// 命令类型列
for (int i = 0; i < allTypes.Count; i++)
{
var cell = headerRow.CreateCell(i + 1);
cell.SetCellValue(GetShortTypeName(allTypes[i]));
cell.CellStyle = headerStyle;
}
// 填充数据
for (int i = 0; i < data.Count; i++)
{
var dataRow = sheet.CreateRow(i + 1);
dataRow.HeightInPoints = 18; // 设置数据行高度
// 时间段单元格
var timeDataCell = dataRow.CreateCell(0);
timeDataCell.SetCellValue(data[i].RemoveTime);
timeDataCell.CellStyle = dateStyle;
// 交替行颜色 - 斑马纹效果
var rowStyle = (i % 2 == 0) ? evenRowStyle : oddRowStyle;
for (int j = 0; j < allTypes.Count; j++)
{
var type = allTypes[j];
var value = data[i].TypeValues.ContainsKey(type) ? data[i].TypeValues[type] : 0L;
var dataCell = dataRow.CreateCell(j + 1);
dataCell.SetCellValue(value);
dataCell.CellStyle = rowStyle;
}
}
// 设置列宽 - 更精确的自适应
sheet.SetColumnWidth(0, 20 * 256); // 时间段列固定宽度
for (int i = 0; i < allTypes.Count; i++)
{
// 根据列名长度设置宽度
var colName = GetShortTypeName(allTypes[i]);
int width = Math.Max(10, Math.Min(25, colName.Length + 2)) * 256;
sheet.SetColumnWidth(i + 1, width);
}
// 冻结表头行
sheet.CreateFreezePane(0, 1, 0, 1);
return workbook;
}
// 创建表头样式
private ICellStyle CreateHeaderStyle(IWorkbook workbook)
{
var style = workbook.CreateCellStyle();
// 设置背景色
style.FillForegroundColor = IndexedColors.DarkBlue.Index;
style.FillPattern = FillPattern.SolidForeground;
// 设置字体
var font = workbook.CreateFont();
font.FontName = "Arial";
font.FontHeightInPoints = 11;
font.Boldweight = (short)FontBoldWeight.Bold;
font.Color = IndexedColors.White.Index;
style.SetFont(font);
// 设置边框
style.BorderBottom = BorderStyle.Medium;
style.BorderLeft = BorderStyle.Medium;
style.BorderRight = BorderStyle.Medium;
style.BorderTop = BorderStyle.Medium;
style.BottomBorderColor = IndexedColors.Black.Index;
style.LeftBorderColor = IndexedColors.Black.Index;
style.RightBorderColor = IndexedColors.Black.Index;
style.TopBorderColor = IndexedColors.Black.Index;
// 设置对齐方式
style.Alignment = HorizontalAlignment.Center;
style.VerticalAlignment = VerticalAlignment.Center;
return style;
}
// 创建单元格样式
private ICellStyle CreateCellStyle(IWorkbook workbook, short backgroundColor, bool isDateCell = false)
{
var style = workbook.CreateCellStyle();
// 设置背景色
style.FillForegroundColor = backgroundColor;
style.FillPattern = FillPattern.SolidForeground;
// 设置字体
var font = workbook.CreateFont();
font.FontName = "Arial";
font.FontHeightInPoints = 10;
style.SetFont(font);
// 设置边框
style.BorderBottom = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
style.BorderTop = BorderStyle.Thin;
style.BottomBorderColor = IndexedColors.Grey40Percent.Index;
style.LeftBorderColor = IndexedColors.Grey40Percent.Index;
style.RightBorderColor = IndexedColors.Grey40Percent.Index;
style.TopBorderColor = IndexedColors.Grey40Percent.Index;
// 设置对齐方式
if (isDateCell)
{
style.Alignment = HorizontalAlignment.Left;
}
else
{
style.Alignment = HorizontalAlignment.Center;
}
style.VerticalAlignment = VerticalAlignment.Center;
// 设置数据格式
if (!isDateCell)
{
var format = workbook.CreateDataFormat();
style.DataFormat = format.GetFormat("0"); // 数字格式,不显示小数
}
return style;
}
// 获取简化的类型名称类似前端的getShortType方法
private string GetShortTypeName(string type)
{
// 这里实现您的类型名称简化逻辑
// 例如可以基于您的keyValueMap进行映射
if (type.Contains('_'))
{
return type.Split('_').Last();
}
return type;
}
}
// 导出数据行类
public class ExportDataRow
{
public string RemoveTime { get; set; }
public Dictionary<string, long> TypeValues { get; set; }
}
public class TTT
{
public string key { get; set; }
public int value { get; set; }
}
}

View File

@@ -0,0 +1,16 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace BLWLogServer.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpPost()]
public string HeartBeat()
{
return "hello";
}
}
}

View File

@@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Mvc;
namespace BLWLogServer.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()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}

5069
BLWLogServer/NLog.xsd Normal file

File diff suppressed because it is too large Load Diff

49
BLWLogServer/Program.cs Normal file
View File

@@ -0,0 +1,49 @@
using BLWLogServer.Services;
using MongoDB.Driver;
namespace BLWLogServer
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "KuaYu",
policy =>
{
policy
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
builder.Services.AddScoped<IMongoClient>(ppp =>
{
string? connectionString = builder.Configuration["Mongodb:Connectstr"];
//var connectionString = "mongodb://localhost:27017/";
var client = new MongoClient(connectionString);
return client;
});
builder.Services.AddHostedService<KafkaConsume>();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseCors("KuaYu");
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
}

View File

@@ -0,0 +1,31 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:52553",
"sslPort": 0
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "weatherforecast",
"applicationUrl": "http://localhost:5245",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,469 @@
using System.Text;
using Common;
using CommonEntity;
using CommonTools;
using Confluent.Kafka;
using MongoDB.Driver;
using NLog;
using System.Collections.Generic;
namespace BLWLogServer.Services
{
public class KafkaConsume : BackgroundService
{
public IConfiguration Configuration { get; set; }
public KafkaConsume(IConfiguration configuration)
{
Configuration = configuration;
}
public static Logger logger = NLog.LogManager.GetCurrentClassLogger();
// 添加两个队列用于存储最近10条TotalCount
private static Queue<long> _cpuMaxQueue = new(10);
private static Queue<long> _cpuAvgQueue = new(10);
private static Queue<long> _cpuMinQueue = new(10);
private static Queue<long> _TotalSendPackage = new(10);
private static Queue<long> _TotalRecvPackage = new(10);
private static Queue<long> _RCUOnLine = new(10);
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
await Task.Factory.StartNew(async () =>
{
var consumers = new List<Task>();
for (int i = 0; i < 3; i++)
{
consumers.Add(Task.Run(() => StartConsumer(stoppingToken)));
}
await Task.WhenAll(consumers);
//await StartConsumer(stoppingToken);
}, TaskCreationOptions.LongRunning);
}
private async Task StartConsumer(CancellationToken stoppingToken)
{
string? ipport = Configuration["Kafka:EndPoint"];
string? user = Configuration["Kafka:UserName"];
string? pwd = Configuration["Kafka:PassWord"];
string? mongodbconnectstr = Configuration["Mongodb:Connectstr"];
while (!stoppingToken.IsCancellationRequested)
{
var config = new ConsumerConfig
{
GroupId = "blwlogserver-consumer-group",
AutoOffsetReset = AutoOffsetReset.Earliest,
BootstrapServers = ipport,
SecurityProtocol = SecurityProtocol.SaslPlaintext,
SaslMechanism = SaslMechanism.Plain,
SaslUsername = user,
SaslPassword = pwd
};
var c = new ConsumerBuilder<string, byte[]>(config).Build();
c.Subscribe(KafkaKey.BLWLog_RCU_Topic);
var connectionString = mongodbconnectstr;
var client = new MongoClient(connectionString);
try
{
while (true)
{
var cr = c.Consume(stoppingToken);
try
{
var k = cr.Message.Key;
var v = cr.Message.Value;
if (k.Equals(KafkaKey.UDPPackageKey))
{
//var UUU = Encoding.UTF8.GetString(v);
//Console.WriteLine($"Consumed message '{k} {v}' at: '{cr.TopicPartitionOffset}'.");
var collection = client.GetDatabase("udppackage").GetCollection<UDPPackage_db>("totalcount");
UDPPackage UDPPPP = MyMessagePacker.FastDeserialize<UDPPackage>(v);
UDPPackage_db us = new UDPPackage_db();
us.TotalCount = UDPPPP.TotalCount;
us.CommandType = UDPPPP.CommandType;
us.FenLei = UDPPPP.FenLei;
us.ExtraData = UDPPPP.ExtraData;
us.RemoveTimeString = UDPPPP.RemoveTime;
us.RemoveTime = DateTime.Parse(UDPPPP.RemoveTime);
await collection.InsertOneAsync(us);
// xu修改20250908
// 修改CPUMax处理逻辑
if (UDPPPP.CommandType == "UDPPackage_CPUMax")
{
// 维护队列长度不超过10
if (_cpuMaxQueue.Count >= 10)
{
_cpuMaxQueue.Dequeue();
}
_cpuMaxQueue.Enqueue(UDPPPP.TotalCount);
// 将队列转为逗号分隔字符串
string arrayString = string.Join(",", _cpuMaxQueue);
CSRedisCacheHelper.Set("UDPPackage_CPUMax", arrayString, 10);
}
if (UDPPPP.CommandType == "UDPPackage_CPUMin")
{
// 维护队列长度不超过10
if (_cpuMinQueue.Count >= 10)
{
_cpuMinQueue.Dequeue();
}
_cpuMinQueue.Enqueue(UDPPPP.TotalCount);
// 将队列转为逗号分隔字符串
string arrayString = string.Join(",", _cpuMinQueue);
CSRedisCacheHelper.Set("UDPPackage_CPUMin", arrayString, 10);
}
// 修改CPUAvg处理逻辑
if (UDPPPP.CommandType == "UDPPackage_CPUAvg")
{
// 维护队列长度不超过10
if (_cpuAvgQueue.Count >= 10)
{
_cpuAvgQueue.Dequeue();
}
_cpuAvgQueue.Enqueue(UDPPPP.TotalCount);
// 将队列转为逗号分隔字符串
string arrayString = string.Join(",", _cpuAvgQueue);
CSRedisCacheHelper.Set("UDPPackage_CPUAvg", arrayString, 10);
CSRedisCacheHelper.Set("UDPPackage_DetectTime", DateTime.UtcNow.ToString("o"), 10);
}
if (UDPPPP.CommandType == "UDPPackage_TotalSendPackage")
{
// 维护队列长度不超过10
if (_TotalSendPackage.Count >= 10)
{
_TotalSendPackage.Dequeue();
}
_TotalSendPackage.Enqueue(UDPPPP.TotalCount);
// 将队列转为逗号分隔字符串
string arrayString = string.Join(",", _TotalSendPackage);
CSRedisCacheHelper.Set("UDPPackage_TotalSendPackage", arrayString, 10);
}
if (UDPPPP.CommandType == "UDPPackage_TotalRecvPackage")
{
// 维护队列长度不超过10
if (_TotalRecvPackage.Count >= 10)
{
_TotalRecvPackage.Dequeue();
}
_TotalRecvPackage.Enqueue(UDPPPP.TotalCount);
// 将队列转为逗号分隔字符串
string arrayString = string.Join(",", _TotalRecvPackage);
CSRedisCacheHelper.Set("UDPPackage_TotalRecvPackage", arrayString, 10);
}
if (UDPPPP.CommandType == "RCUOnLine")
{
// 维护队列长度不超过10
if (_RCUOnLine.Count >= 10)
{
_RCUOnLine.Dequeue();
}
_RCUOnLine.Enqueue(UDPPPP.TotalCount);
// 将队列转为逗号分隔字符串
string arrayString = string.Join(",", _RCUOnLine);
CSRedisCacheHelper.Set("RCUOnLine", arrayString, 10);
}
}
else if (k.Equals(KafkaKey.UDPPackageStepMonitor))
{
var collection = client.GetDatabase("udppackage").GetCollection<StepInfo_db>("zeroe_stepmonitor");
StepInfo UDPPPP = MyMessagePacker.FastDeserialize<StepInfo>(v);
StepInfo_db us = new StepInfo_db();
us.MessageId = UDPPPP.MessageId;
us.Step = UDPPPP.Step;
us.StepDescription = UDPPPP.StepDescription;
us.Content = UDPPPP.Content;
us.TriggerTime = DateTime.Parse(UDPPPP.TriggerTime);
us.TriggerTimeString = UDPPPP.TriggerTime;
us.EveryMessageId = UDPPPP.EveryMessageId;
us.Monitor_0E_01 = UDPPPP.Monitor_0E_01;
us.HostNumber = UDPPPP.HostNumber;
us.HotelCode = UDPPPP.HotelCode;
await collection.InsertOneAsync(us);
}
else if (k.Equals(KafkaKey.UDPPackagePowerMonitor))
{
var collection = client.GetDatabase("udppackage").GetCollection<NengHao_db>("powermonitor");
NengHao UDPPPP = MyMessagePacker.FastDeserialize<NengHao>(v);
NengHao_db us = new NengHao_db();
us.Version = UDPPPP.Version;
us.HotelCode = UDPPPP.HotelCode;
us.HostNumber = UDPPPP.HostNumber;
us.Mac = UDPPPP.Mac;
us.EndPoint = UDPPPP.EndPoint;
us.V = UDPPPP.V;
us.A = UDPPPP.A;
us.P = UDPPPP.P;
us.Energy_Consumption = UDPPPP.Energy_Consumption;
us.Sum_Energy_Consumption = UDPPPP.Sum_Energy_Consumption;
us.IsTakeCard = UDPPPP.IsTakeCard;
us.CreateTime = UDPPPP.CreateTime;
us.ReportTime = DateTime.Parse(UDPPPP.ReportTime);
us.RoomNumber = UDPPPP.RoomNumber;
us.CarbonVIP = UDPPPP.CarbonVIP;
us.AllDeviceData = UDPPPP.AllDeviceData;
us.IdentityInfo = UDPPPP.IdentityInfo;
await collection.InsertOneAsync(us);
}
else if (k.Equals(KafkaKey.IotMonitor))
{
var collection = client.GetDatabase("udppackage").GetCollection<IOTMonitorData_db>("voiceiotlog");
IOTMonitorData UDPPPP = MyMessagePacker.FastDeserialize<IOTMonitorData>(v);
IOTMonitorData_db us = new IOTMonitorData_db();
us.Step = UDPPPP.Step;
us.TriggerTime = UDPPPP.TriggerTime;
us.HotelCode = UDPPPP.HotelCode;
us.HotelId = UDPPPP.HotelId;
us.HotelName = UDPPPP.HotelName;
us.RoomNumber = UDPPPP.RoomNumber;
us.RequestId = UDPPPP.RequestId;
us.CommandDescription = UDPPPP.CommandDescription;
us.Platform = UDPPPP.Platform;
us.CreateTime = UDPPPP.CreateTime;
us.RemoteIP = UDPPPP.RemoteIP;
us.ControlClass = UDPPPP.ControlClass;
us.SceneName = UDPPPP.SceneName;
us.WhichOneDevice = UDPPPP.WhichOneDevice;
await collection.InsertOneAsync(us);
}
//
else if (k.Equals(KafkaKey.RCUOnLineStatus))
{
var collection = client.GetDatabase("udppackage").GetCollection<OnOffLineData_db>("rcustatuslog");
OnOffLineData UDPPPP = MyMessagePacker.FastDeserialize<OnOffLineData>(v);
OnOffLineData_db us = new OnOffLineData_db();
us.MAC = UDPPPP.MAC;
us.HostNumber = UDPPPP.HostNumber;
us.CurrentStatus = UDPPPP.CurrentStatus;
us.HotelCode = UDPPPP.HotelCode;
us.CurrentTime = UDPPPP.CurrentTime;
us.EndPoint = UDPPPP.EndPoint;
await collection.InsertOneAsync(us);
}
else if (k.Equals(KafkaKey.InvokceThirdHttpInterface))
{
var collection = client.GetDatabase("udppackage").GetCollection<Interface3Log_db>("invokehttpinterfacelog");
Interface3Log UDPPPP = MyMessagePacker.FastDeserialize<Interface3Log>(v);
Interface3Log_db us = new Interface3Log_db();
us.HotelCode = UDPPPP.HotelCode;
us.HostNumber = UDPPPP.HostNumber;
us.RoomNumber = UDPPPP.RoomNumber;
us.TriggerTime = UDPPPP.TriggerTime;
us.CommandType = UDPPPP.CommandType;
us.ActionData = UDPPPP.ActionData;
await collection.InsertOneAsync(us);
}
else if (k.Equals(KafkaKey.TakeCardStatus))
{
var collection = client.GetDatabase("udppackage").GetCollection<MTakeCardData_db>("takecardlog");
MTakeCardData UDPPPP = MyMessagePacker.FastDeserialize<MTakeCardData>(v);
MTakeCardData_db us = new MTakeCardData_db();
us.Status = UDPPPP.Status;
us.HostNUMBER = UDPPPP.HostNUMBER;
us.LastUpdateTime = UDPPPP.LastUpdateTime;
us.HotelCode = UDPPPP.HotelCode;
us.Status = UDPPPP.Status;
await collection.InsertOneAsync(us);
}
else if (k.Equals(KafkaKey.ServiceInfoStatus))
{
var collection = client.GetDatabase("udppackage").GetCollection<OtherServiceInfo_db>("serviceinfolog");
OtherServiceInfo UDPPPP = MyMessagePacker.FastDeserialize<OtherServiceInfo>(v);
OtherServiceInfo_db us = new OtherServiceInfo_db();
us.HotelCode = UDPPPP.HotelCode;
us.HostNumber = UDPPPP.HostNumber;
us.Address = UDPPPP.Address;
us.StatusReceiver = UDPPPP.StatusReceiver;
us.LastUpdateTime = UDPPPP.LastUpdateTime;
await collection.InsertOneAsync(us);
}
else if (k.Equals(KafkaKey.PMSLogMonitor))
{
//Console.WriteLine("收到了 PMSData");
var collection = client.GetDatabase("udppackage").GetCollection<CheckInYuanShidata_db>("pmslog");
CheckInYuanShidata UDPPPP = MyMessagePacker.FastDeserialize<CheckInYuanShidata>(v);
CheckInYuanShidata_db us = new CheckInYuanShidata_db();
us.Step = UDPPPP.Step;
us.IP = UDPPPP.IP;
us.RequestId = UDPPPP.RequestId;
us.CurrentTime = UDPPPP.CurrentTime;
us.CommandType = UDPPPP.CommandType;
us.JianJieData = UDPPPP.JianJieData;
us.ZhiJieData = UDPPPP.ZhiJieData;
await collection.InsertOneAsync(us);
}
#region
else if (k.Equals(KafkaKey.RCUNewVersion_Register))
{
//P0~P3子网掩码4Byte
//P4~P7网关4Byte
//P8~P9RCU端口2Byte
//P10~P15Mac地址6Byte
//P16~P35软件版本号20Byte
//P36~P38配置版本号3Byte
//P39~P42DNS服务器1 IP4Byte
//P43~P58房型备注16Byte
//P59~P74房号备注16Byte
//P75~P78房型4Byte
//P79~P82房号4Byte
var collection = client.GetDatabase("udppackage").GetCollection<NewVersionHexData_db>("rcu_hexdata");
NewVersionHexData UDPPPP = MyMessagePacker.FastDeserialize<NewVersionHexData>(v);
//byte[] hexdata = Tools.GetBytesFromString(UDPPPP.HexData);
//var 子网掩码 = hexdata[0..4];
//string subnet_mask = String.Join(".", 子网掩码);//子网掩码
//var 网关 = hexdata[4..8];
//string gateway = string.Join(".", 网关);
//var RCU端口 = hexdata[8..10];
//int lan_port = BitConverter.ToInt32(RCU端口);//局域网端口
//var MAC = hexdata[10..16];
//var 软件版本号 = hexdata[16..36];
//var 配置版本 = hexdata[36..39];
//var DNS服务器 = hexdata[39..43];
//var 房型备注 = hexdata[43..59];
//var 房号备注 = hexdata[59..75];
//var 房型 = hexdata[75..79];
//var 房号 = hexdata[79..83];
//int ipType = reader.ReadByte();//IP类型
//string type_number = Encoding.GetEncoding("GBK").GetString(reader.ReadBytes(16)).Replace(@"\u0000", "").Replace("", "").Trim();//机型编码
//string lan_ip = String.Join(".", reader.ReadBytes(4));//局域网IP
//string server_ip = String.Join(".", reader.ReadBytes(4));//服务器IP
//string subnet_mask = String.Join(".", reader.ReadBytes(4));//子网掩码
//string gateway = String.Join(".", reader.ReadBytes(4));//网关
//int lan_port = BitConverter.ToInt32(reader.ReadBytes(4), 0);//局域网端口
//string dns = String.Join(".", reader.ReadBytes(4));//DNS
//string software_version = Encoding.GetEncoding("GBK").GetString(reader.ReadBytes(20)).Replace(@"\u0000", "").Replace("", "").Trim();//软件版本号
NewVersionHexData_db cv = new NewVersionHexData_db();
cv.HotelCode = UDPPPP.HotelCode;
cv.HostNumber = UDPPPP.HostNumber;
cv.RoomNumber = UDPPPP.RoomNumber;
cv.CurrentTime = UDPPPP.CurrentTime;
cv.RemoteEndPoint = UDPPPP.RemoteEndPoint;
cv.CmdType = UDPPPP.CmdType;
cv.HexData = UDPPPP.HexData;
cv.CurrentTime = UDPPPP.CurrentTime;
await collection.InsertOneAsync(cv);
}
else if (k.Equals(KafkaKey.RCUNewVersion_RestartReason))
{
var collection = client.GetDatabase("udppackage").GetCollection<NewVersionHexData_db>("rcu_hexdata");
NewVersionHexData UDPPPP = MyMessagePacker.FastDeserialize<NewVersionHexData>(v);
NewVersionHexData_db cv = new NewVersionHexData_db();
cv.HotelCode = UDPPPP.HotelCode;
cv.HostNumber = UDPPPP.HostNumber;
cv.RoomNumber = UDPPPP.RoomNumber;
cv.CurrentTime = UDPPPP.CurrentTime;
cv.RemoteEndPoint = UDPPPP.RemoteEndPoint;
cv.CmdType = UDPPPP.CmdType;
cv.HexData = UDPPPP.HexData;
cv.CurrentTime = UDPPPP.CurrentTime;
await collection.InsertOneAsync(cv);
}
else if (k.Equals(KafkaKey.RCUNewVersion_0E))
{
var collection = client.GetDatabase("udppackage").GetCollection<NewVersionHexData_db>("rcu_hexdata");
NewVersionHexData UDPPPP = MyMessagePacker.FastDeserialize<NewVersionHexData>(v);
int length = 30 - 15 - 2;
using MemoryStream stream = new MemoryStream(null, 15, length);
NewVersionHexData_db cv = new NewVersionHexData_db();
cv.HotelCode = UDPPPP.HotelCode;
cv.HostNumber = UDPPPP.HostNumber;
cv.RoomNumber = UDPPPP.RoomNumber;
cv.CurrentTime = UDPPPP.CurrentTime;
cv.RemoteEndPoint = UDPPPP.RemoteEndPoint;
cv.CmdType = UDPPPP.CmdType;
cv.HexData = UDPPPP.HexData;
cv.CurrentTime = UDPPPP.CurrentTime;
await collection.InsertOneAsync(cv);
}
else if (k.Equals(KafkaKey.RCUNewVersion_TakeCard))
{
var collection = client.GetDatabase("udppackage").GetCollection<NewVersionHexData_db>("rcu_hexdata");
NewVersionHexData UDPPPP = MyMessagePacker.FastDeserialize<NewVersionHexData>(v);
NewVersionHexData_db cv = new NewVersionHexData_db();
cv.HotelCode = UDPPPP.HotelCode;
cv.HostNumber = UDPPPP.HostNumber;
cv.RoomNumber = UDPPPP.RoomNumber;
cv.CurrentTime = UDPPPP.CurrentTime;
cv.RemoteEndPoint = UDPPPP.RemoteEndPoint;
cv.CmdType = UDPPPP.CmdType;
cv.HexData = UDPPPP.HexData;
cv.CurrentTime = UDPPPP.CurrentTime;
await collection.InsertOneAsync(cv);
}
else if (k.Equals(KafkaKey.RCUNewTimerData))
{
}
else
{
}
#endregion
//Console.WriteLine($"消费者1收到消息: [分区{cr.Partition}] " +
// $"偏移量{cr.Offset}");
//默认是开着的
//c.Commit(cr);
}
catch (ConsumeException e)
{
logger.Error("出错:" + e.Message);
Console.WriteLine(111111111111111);
}
catch (Exception ex)
{
logger.Error("Ex出错" + ex.Message);
Console.WriteLine(22222222222222);
}
}
}
catch (OperationCanceledException)
{
logger.Error("操作出错");
Console.WriteLine("操作错误");
}
catch (Exception ex)
{
Console.WriteLine("未知错误" + ex.Message);
logger.Error("未知错误" + ex.Message);
}
}
}
}
}

View File

@@ -0,0 +1,154 @@
using System.Text;
using Common;
using CommonEntity;
using CommonTools;
using Confluent.Kafka;
using MongoDB.Driver;
using NLog;
using System.Collections.Generic;
using Confluent.Kafka.Admin;
using static Confluent.Kafka.ConfigPropertyNames;
using System.Configuration;
namespace BLWLogServer.Services
{
public class KafkaConsume1 : BackgroundService
{
public IConfiguration Configuration { get; set; }
public KafkaConsume1(IConfiguration configuration)
{
Configuration = configuration;
}
public static Logger logger = NLog.LogManager.GetCurrentClassLogger();
private async Task StartConsumer(CancellationToken stoppingToken)
{
string? ipport = Configuration["Kafka:EndPoint"];
string? user = Configuration["Kafka:UserName"];
string? pwd = Configuration["Kafka:PassWord"];
string? mongodbconnectstr = Configuration["Mongodb:Connectstr"];
while (!stoppingToken.IsCancellationRequested)
{
var conf = new ConsumerConfig
{
GroupId = "blwlogserver-consumer-group",
AutoOffsetReset = AutoOffsetReset.Earliest,
BootstrapServers = ipport,
SecurityProtocol = SecurityProtocol.SaslPlaintext,
SaslMechanism = SaslMechanism.Plain,
EnableAutoCommit = true,
SaslUsername = user,
SaslPassword = pwd
};
var c = new ConsumerBuilder<string, byte[]>(conf)
.SetErrorHandler((_, e) =>
{
logger.Error($"消费者错误: {e.Reason}");
}).SetPartitionsAssignedHandler((c, partitions) =>
{
logger.Error($"消费者分配到分区: {string.Join(", ", partitions)}");
}).Build();
//c.Subscribe(KafkaKey.BLWLog_RCU_Topic_Partition);
c.Subscribe(KafkaKey.BLWLog_RCU_Topic);
var connectionString = mongodbconnectstr;
var client = new MongoClient(connectionString);
try
{
while (true)
{
var consumeResult = c.Consume(stoppingToken);
try
{
var k = consumeResult.Message.Key;
var v = consumeResult.Message.Value;
if (k.Equals("testtest"))
{
Console.WriteLine("11111111111111111111");
}
if (k.Equals(KafkaKey.InvokceThirdHttpInterface))
{
var collection = client.GetDatabase("udppackage").GetCollection<Interface3Log_db>("invokehttpinterfacelog");
Interface3Log UDPPPP = MyMessagePacker.FastDeserialize<Interface3Log>(v);
Interface3Log_db us = new Interface3Log_db();
us.HotelCode = UDPPPP.HotelCode;
us.HostNumber = UDPPPP.HostNumber;
us.RoomNumber = UDPPPP.RoomNumber;
us.TriggerTime = UDPPPP.TriggerTime;
us.ActionData = UDPPPP.ActionData;
await collection.InsertOneAsync(us);
}
else if (k.Equals(KafkaKey.TakeCardStatus))
{
var collection = client.GetDatabase("udppackage").GetCollection<MTakeCardData_db>("takecardlog");
MTakeCardData UDPPPP = MyMessagePacker.FastDeserialize<MTakeCardData>(v);
MTakeCardData_db us = new MTakeCardData_db();
us.Status = UDPPPP.Status;
us.HostNUMBER = UDPPPP.HostNUMBER;
us.LastUpdateTime = UDPPPP.LastUpdateTime;
us.HotelCode = UDPPPP.HotelCode;
us.Status = UDPPPP.Status;
await collection.InsertOneAsync(us);
}
else if (k.Equals(KafkaKey.ServiceInfoStatus))
{
var collection = client.GetDatabase("udppackage").GetCollection<OtherServiceInfo_db>("serviceinfolog");
OtherServiceInfo UDPPPP = MyMessagePacker.FastDeserialize<OtherServiceInfo>(v);
OtherServiceInfo_db us = new OtherServiceInfo_db();
us.HotelCode = UDPPPP.HotelCode;
us.HostNumber = UDPPPP.HostNumber;
us.Address = UDPPPP.Address;
us.StatusReceiver = UDPPPP.StatusReceiver;
us.LastUpdateTime = UDPPPP.LastUpdateTime;
await collection.InsertOneAsync(us);
}
else
{
Console.WriteLine( "11111111111111111");
}
if (consumeResult.IsPartitionEOF)
{
Console.WriteLine($"消费者1到达分区末尾: {consumeResult.TopicPartitionOffset}");
}
//Console.WriteLine($"消费者1收到消息: [分区{consumeResult.Partition}] " +
// $"偏移量{consumeResult.Offset}: {consumeResult.Message.Value}");
// 手动提交偏移量
//c.Commit(consumeResult);
}
catch (ConsumeException e)
{
logger.Error(e.Message);
}
}
}
catch (OperationCanceledException)
{
c.Close();
}
}
}
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
await Task.Factory.StartNew(async () =>
{
var consumers = new List<Task>();
for (int i = 0; i < 2; i++)
{
consumers.Add(Task.Run(() => StartConsumer(stoppingToken)));
}
await Task.WhenAll(consumers);
}, TaskCreationOptions.LongRunning);
await Task.CompletedTask;
}
}
}

246
BLWLogServer/Services/S.cs Normal file
View File

@@ -0,0 +1,246 @@
using System.Collections.Concurrent;
namespace BLWLogServer.Services
{
public class Device
{
/// <summary>
/// 设备地址
/// </summary>
public string Address { get; set; }
/// <summary>
/// 地址类型
/// </summary>
//public AddressType AddressType { get; set; }
/// <summary>
/// 设备开关状态1开2关6停窗帘下发1个字节
/// </summary>
public byte Status { get; set; }
/// <summary>
/// 设备开关状态1开2关6停窗帘,接收2个字节
/// </summary>
public ushort StatusReceiver { get; set; }
/// <summary>
/// 亮度值
/// </summary>
public byte Brightness { get; set; }
/// <summary>
/// 温度
/// </summary>
public byte Temperature { get; set; }
/// <summary>
/// 风速
/// </summary>
public byte FanSpeed { get; set; }
/// <summary>
/// 模式
/// </summary>
public byte Mode { get; set; }
/// <summary>
/// 阀门开关
/// </summary>
public byte Valve { get; set; }
/// <summary>
/// 空调执行方式和内容
/// </summary>
public Int32 AirExecMode { get; set; }
/// <summary>
/// 地暖执行方式和内容
/// </summary>
public Int32 FloorHotExecMode { get; set; }
/// <summary>
/// 背景音乐执行方式和内容
/// </summary>
public Int32 MusicExecMode { get; set; }
/// <summary>
/// 色温执行方式和内容
/// </summary>
//public Int32 ColorTempExecMode { get; set; }
}
public class Status
{
/// <summary>
/// RCU是否锁定
/// </summary>
public bool SysLock { get; set; }
/// <summary>
/// 房卡类型
/// </summary>
public byte CardType { get; set; }
/// <summary>
/// 房门开关
/// </summary>
public bool Door { get; set; }
/// <summary>
/// 电量
/// </summary>
public ushort ElecQty { get; set; }
/// <summary>
/// 主机温度
/// </summary>
public byte HostTemp { get; set; }
/// <summary>
/// 空调状态
/// </summary>
public ConcurrentDictionary<byte, AirConditionStatus> AirConditions = new ConcurrentDictionary<byte, AirConditionStatus>();
/// <summary>
/// 设备状态
/// </summary>
public ConcurrentDictionary<string, Device> Devices = new ConcurrentDictionary<string, Device>();
/// <summary>
/// 故障列表
/// </summary>
public ConcurrentDictionary<string, FaultStaus> Faults = new ConcurrentDictionary<string, FaultStaus>();
}
/// <summary>
/// 空调状态
/// </summary>
public class AirConditionStatus
{
/// <summary>
/// 空调号
/// </summary>
public byte AirNo { get; set; }
/// <summary>
/// 当前温度
/// </summary>
public int CurrentTemp { get; set; }
/// <summary>
/// 设定温度
/// </summary>
public int SettingTemp { get; set; }
/// <summary>
/// 风机开关
/// </summary>
public bool OnOff { get; set; }
/// <summary>
/// 风速0/停止, 1/低速, 2/中速, 3/高速, 4/自动
/// </summary>
public int Speed { get; set; }
/// <summary>
/// 模式: 0/制冷1/制热2/送风3/除湿
/// </summary>
public int Mode { get; set; }
/// <summary>
/// 阀状态: 1/阀开2/阀关
/// </summary>
public int Valve { get; set; }
/// <summary>
/// 补偿温度,范围-6.0~6.0
/// </summary>
public float CompensatoryTemp { get; set; }
/// <summary>
/// 保温温度
/// </summary>
public int KeepTemp { get; set; }
/// <summary>
/// 冷热模式0/手动1/自动
/// </summary>
public int ColdHotMode { get; set; }
/// <summary>
/// 死区温度
/// </summary>
public int DeadTemp { get; set; }
/// <summary>
/// 热偏差
/// </summary>
public int HotDevition { get; set; }
/// <summary>
/// 冷偏差
/// </summary>
public int ColdDevition { get; set; }
}
public class FaultStaus
{
/// <summary>
/// 故障号
/// </summary>
public string FaultNo { get; set; }
/// <summary>
/// 类型1在线状态0在线1离线2电量0~100%3电流4 1901故障检测次数5设备单个回路状态0正常1损坏
/// </summary>
public byte Type { get; set; }
/// <summary>
/// 内容
/// </summary>
public byte Data { get; set; }
}
public class S
{
public static Status NewStatusParse(Stream stream)
{
Status roomStatus = new Status();
try
{
using (BinaryReader reader = new BinaryReader(stream))
{
roomStatus.SysLock = reader.ReadBoolean(); //RCU是否锁定0/否1/是
roomStatus.CardType = reader.ReadByte(); //房卡类型0/无人1/有人2/客人3/经理4/服务员
roomStatus.Door = reader.ReadBoolean(); //门磁开关1/开2/关
roomStatus.ElecQty = reader.ReadUInt16(); //门锁电量单位MV
roomStatus.HostTemp = reader.ReadByte(); //主机温度
//空调数量默认0新的回路方式此处无用兼容老版本
int airConditionNumber = reader.ReadByte();
for (int i = 0; i < airConditionNumber; i++)
{
byte airNo = reader.ReadByte();
if (!roomStatus.AirConditions.ContainsKey(airNo))
{
roomStatus.AirConditions[airNo] = new AirConditionStatus();
}
roomStatus.AirConditions[airNo].AirNo = airNo;
roomStatus.AirConditions[airNo].CurrentTemp = reader.ReadSByte();
roomStatus.AirConditions[airNo].SettingTemp = reader.ReadSByte();
roomStatus.AirConditions[airNo].OnOff = reader.ReadBoolean();
roomStatus.AirConditions[airNo].Speed = reader.ReadByte();
roomStatus.AirConditions[airNo].Mode = reader.ReadByte();
roomStatus.AirConditions[airNo].Valve = reader.ReadByte();
roomStatus.AirConditions[airNo].CompensatoryTemp = reader.ReadByte();
roomStatus.AirConditions[airNo].KeepTemp = reader.ReadByte();
roomStatus.AirConditions[airNo].ColdHotMode = reader.ReadByte();
roomStatus.AirConditions[airNo].DeadTemp = reader.ReadByte();
roomStatus.AirConditions[airNo].HotDevition = reader.ReadByte();
roomStatus.AirConditions[airNo].ColdDevition = reader.ReadByte();
}
//设备状态数量,包含所有回路状态
int deviceNumber = reader.ReadByte();
long originalPosition = reader.BaseStream.Position;
// 读取前先记录当前位置
try
{
//0x19数据缓冲区异常问题处理
//0x19 取电数据不处理
//非0x19 取电数据处理,但是不触发 欢迎词
for (int i = 0; i < deviceNumber; i++)
{
var QA = reader.ReadBytes(4);
var Status = reader.ReadUInt16();
string address = String.Format("{0:000}{1:000}{2:000}", QA[0], QA[1], QA[0]);
if (!roomStatus.Devices.ContainsKey(address))
{
roomStatus.Devices[address] = new Device();
}
roomStatus.Devices[address].Address = address;//设备地址
roomStatus.Devices[address].StatusReceiver = Status;//设备状态改为2个字节,Modified By 20181213
originalPosition = reader.BaseStream.Position;
}
}
catch (Exception)
{
// 发生异常时回退到原始位置
reader.BaseStream.Position = originalPosition;
}
return roomStatus;
}
}
catch (Exception)
{
return null;
}
}
}
}

View File

@@ -0,0 +1,13 @@
namespace BLWLogServer
{
public class WeatherForecast
{
public DateOnly 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,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@@ -0,0 +1,20 @@
{
"Mongodb": {
"Connectstr": "mongodb://blv-rd-admin:A*%26(y*DG%26v(AS%26Di7gct@10.8.8.210:27017/"
},
"Kafka": {
"EndPoint": "43.138.217.154:9092",
"UserName": "blwmomo",
"PassWord": "blwmomo"
//"EndPoint": "172.16.4.132:9092",
//"UserName": "blwmomo",
//"PassWord": "blwmomo"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

35
BLWLogServer/nlog.config Normal file
View File

@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- enable asp.net core layout renderers -->
<targets>
<!--项目日志保存文件路径说明fileName="${basedir}/保存目录,以年月日的格式创建/${shortdate}/${记录器名称}-${单级记录}-${shortdate}.txt"-->
<target name="info_file" xsi:type="File"
fileName="${basedir}/Logs/${shortdate}/info_${shortdate}.txt"
layout="${longdate}|${level:uppercase=true}|${logger}|${message}|${exception:format=ToString} ${newline} ${stacktrace} ${newline}"
archiveFileName="${basedir}/archives/info_${shortdate}-{#####}.txt"
archiveAboveSize="102400"
archiveNumbering="Sequence"
concurrentWrites="true"
keepFileOpen="false" />
<target name="error_file" xsi:type="File"
fileName="${basedir}/Logs/${shortdate}/error_${shortdate}.txt"
layout="${longdate}|${level:uppercase=true}|${logger}|${message}|${exception:format=ToString} ${newline} ${stacktrace} ${newline}"
archiveFileName="${basedir}/archives/error_${shortdate}-{#####}.txt"
archiveAboveSize="102400"
archiveNumbering="Sequence"
concurrentWrites="true"
keepFileOpen="false" />
</targets>
<!--规则配置,final - 最终规则匹配后不处理任何规则-->
<!--规则配置,final - 最终规则匹配后不处理任何规则-->
<!--定义使用哪个target输出-->
<rules>
<!-- 优先级从高到低依次为OFF、FATAL、ERROR、WARN、INFO、DEBUG、TRACE、 ALL -->
<!-- 将所有日志输出到文件 -->
<logger name="*" minlevel="FATAL" maxlevel="FATAL" writeTo="info_file" />
<logger name="*" minlevel="Error" writeTo="error_file" />
</rules>
</nlog>