change - 修改采集逻辑

master
wenjy 4 weeks ago
parent 59eaa8bc33
commit 54151e8536

@ -40,11 +40,11 @@ public class DeviceCollectionBusiness
private readonly BaseDeviceInfoCacheService _cacheService; private readonly BaseDeviceInfoCacheService _cacheService;
private readonly List<IOpcService> _opcs; private readonly Dictionary<BaseDeviceInfo, IOpcService> _opcs;
private readonly IBaseService<BaseDeviceParamVal> _paramValService; private readonly IBaseService<BaseDeviceParamVal> _paramValService;
public DeviceCollectionBusiness(SerilogHelper serilogHelper, BaseDeviceInfoCacheService cacheService, List<IOpcService> opcs, IBaseService<BaseDeviceParamVal> paramValService) public DeviceCollectionBusiness(SerilogHelper serilogHelper, BaseDeviceInfoCacheService cacheService, Dictionary<BaseDeviceInfo, IOpcService> opcs, IBaseService<BaseDeviceParamVal> paramValService)
{ {
_serilog = serilogHelper; _serilog = serilogHelper;
_cacheService = cacheService; _cacheService = cacheService;
@ -54,69 +54,109 @@ public class DeviceCollectionBusiness
//this.Handle(); //this.Handle();
} }
public async Task Handle2() public async Task Handle()
{ {
bool isFalg = true; bool isFlag = true;
var deviceInfos = await _cacheService.GetValueAsync("BaseDeviceInfoCache");
_opcs.
}
public async Task Handle(IOpcService opcUa)
{
bool isFalg = true;
var deviceInfos = await _cacheService.GetValueAsync("BaseDeviceInfoCache");
int i = 0; int i = 0;
do do
{ {
i++; i++;
foreach (var item in deviceInfos)
foreach (var (item, opcua) in _opcs)
{ {
//bool result = await _opcUaService.ConnectAsync(item.networkAddress);
//if (!result)
//{
// throw new ArgumentNullException($"设备未连接");
//}
//Task.Run(async () =>
//{
// //_opcUaService.DisconnectAsync();
//});
try try
{ {
_serilog.Info($"开始采集{item.deviceName},设备数据,第{i}次"); _serilog.Info($"开始采集{item.deviceName}");
var opcItemValues = await this.ReadParam(item, opcUa); var opcItemValues = await this.ReadParam(item, opcua);
//this.SaveParam(item, opcItemValues, out List<DeviceParamValueDto> paramValues); this.SaveParam(item, opcItemValues, out List<BaseDeviceParamVal> paramValues);
_serilog.Info($"{item.deviceName}数据采集完成:{JsonConvert.SerializeObject(opcItemValues)}"); _serilog.Info($"{item.deviceName}数据采集完成:{JsonConvert.SerializeObject(opcItemValues)}");
if(i == 10)
{
isFlag = false;
opcua.DisconnectAsync().Wait();
_serilog.Info($"读取完成断开连接");
}
} }
catch (Exception e) catch (Exception e)
{ {
_serilog.Info($"{item.deviceName}数据读取异常:{e.Message}"); _serilog.Info($"{item.deviceName}数据读取异常:{e.Message}");
isFlag = false;
opcua.DisconnectAsync().Wait();
} }
} }
if (i == 1000)
{
isFalg = false;
await opcUa.DisconnectAsync();
_serilog.Info($"读取完成断开连接");
}
await Task.Delay(1000 * 1); Thread.Sleep(2000);
} while (isFalg);
} while (isFlag);
} }
//public async Task Handle(IOpcService opcUa)
//{
// bool isFalg = true;
// var deviceInfos = await _cacheService.GetValueAsync("BaseDeviceInfoCache");
// int i = 0;
// do
// {
// i++;
// foreach (var item in deviceInfos)
// {
// //bool result = await _opcUaService.ConnectAsync(item.networkAddress);
// //if (!result)
// //{
// // throw new ArgumentNullException($"设备未连接");
// //}
// //Task.Run(async () =>
// //{
// // //_opcUaService.DisconnectAsync();
// //});
// try
// {
// _serilog.Info($"开始采集{item.deviceName},设备数据,第{i}次");
// var opcItemValues = await this.ReadParam(item, opcUa);
// //this.SaveParam(item, opcItemValues, out List<DeviceParamValueDto> paramValues);
// _serilog.Info($"{item.deviceName}数据采集完成:{JsonConvert.SerializeObject(opcItemValues)}");
// }
// catch (Exception e)
// {
// _serilog.Info($"{item.deviceName}数据读取异常:{e.Message}");
// }
// }
// if (i == 1000)
// {
// isFalg = false;
// await opcUa.DisconnectAsync();
// _serilog.Info($"读取完成断开连接");
// }
// await Task.Delay(1000 * 1);
// } while (isFalg);
//}
/// <summary> /// <summary>
/// 读取设备参数 /// 读取设备参数
/// </summary> /// </summary>
@ -132,20 +172,8 @@ public class DeviceCollectionBusiness
List<string> deviceParams = device.deviceParams.Select(x => x.paramAddr).ToList(); List<string> deviceParams = device.deviceParams.Select(x => x.paramAddr).ToList();
//bool result = await _opcUaService.ConnectAsync(device.networkAddress);
//if (!result)
//{
// throw new ArgumentNullException($"设备未连接");
//}
List<OpcNode> infos = await opcUa.ReadNodeAsync(deviceParams); List<OpcNode> infos = await opcUa.ReadNodeAsync(deviceParams);
//var infos = _opcService.BrowseNodesAsync("ns=2;s=Devices/分厂一/车间一/测试空设备");
//await _opcUaService.DisconnectAsync();
return infos; return infos;
} }
@ -162,67 +190,34 @@ public class DeviceCollectionBusiness
/// <param name="opcItemValues">OPC节点值列表</param> /// <param name="opcItemValues">OPC节点值列表</param>
/// <param name="paramValues">输出参数值DTO列表</param> /// <param name="paramValues">输出参数值DTO列表</param>
public void SaveParam(BaseDeviceInfo device, List<OpcNode> opcItemValues, public void SaveParam(BaseDeviceInfo device, List<OpcNode> opcItemValues,
out List<DeviceParamValueDto> paramValues) out List<BaseDeviceParamVal> paramValues)
{ {
var deviceParams = device.deviceParams.ToList(); paramValues = new List<BaseDeviceParamVal>();
var now = DateTime.Now; try
// 使用字典提高查找效率
var opcValueDict = opcItemValues.ToDictionary(v => v.NodeId, v => v);
// 构建参数值列表和数据库实体列表
var paramValueList = new List<DeviceParamValueDto>();
var dbEntityList = new List<BaseDeviceParamVal>();
foreach (var param in deviceParams)
{ {
// 查找对应的OPC值 foreach (OpcNode opcItem in opcItemValues)
opcValueDict.TryGetValue(param.paramAddr, out var opcNode);
var paramValue = opcNode?.Value?.ToString() ?? string.Empty;
// 构建DTO
paramValueList.Add(new DeviceParamValueDto
{ {
deviceCode = param.deviceCode, BaseDeviceParamVal deviceParamVal = new BaseDeviceParamVal();
paramCode = param.paramCode,
paramName = param.paramName,
netWork = param.netWork,
paramAddr = param.paramAddr,
paramType = param.paramType,
isFlag = param.isFlag,
paramValue = paramValue,
});
// 构建数据库实体(批量插入) var paramInfo = device.deviceParams.Where(x => x.paramAddr == opcItem.NodeId).FirstOrDefault();
dbEntityList.Add(new BaseDeviceParamVal if (paramInfo != null)
{ {
DEVICE_ID = device.objid, deviceParamVal.paramCode = paramInfo.paramCode;
DEVICE_CODE = device.deviceCode, deviceParamVal.paramName = paramInfo.paramName;
PARAM_CODE = param.paramCode, }
PARAM_NAME = param.paramName, deviceParamVal.deviceCode = device.deviceCode;
PARAM_VALUE = paramValue, deviceParamVal.deviceId = device.objid;
COLLECT_TIME = now, deviceParamVal.paramValue = opcItem.Value.ToString();
RECORD_TIME = now, deviceParamVal.paramType = opcItem.DataType;
PARAM_TYPE = param.paramType, deviceParamVal.collectTime = DateTime.Now;
});
paramValues.Add(deviceParamVal);
}
_paramValService.Insert(paramValues);
}catch (Exception e)
{
throw new InvalidOperationException($"设备参数保存异常:{e.Message}");
} }
paramValues = paramValueList;
// 批量保存到数据库(最高效的方式)
if (dbEntityList.Count > 0)
{
try
{
_paramValService.Insert(dbEntityList);
_serilog.Info($"设备{device.deviceCode}成功保存{dbEntityList.Count}条参数值到数据库");
}
catch (Exception ex)
{
_serilog.Info($"设备{device.deviceCode}保存参数值到数据库失败:{ex.Message}");
throw;
}
}
} }
} }

@ -15,54 +15,54 @@ public class BaseDeviceParamVal
/// 备 注:主键 /// 备 注:主键
///</summary> ///</summary>
[SugarColumn(ColumnName = "RECORD_ID", IsPrimaryKey = true)] [SugarColumn(ColumnName = "RECORD_ID", IsPrimaryKey = true)]
public decimal RECORD_ID { get; set; } public decimal objId { get; set; }
/// <summary> /// <summary>
/// 备 注:参数编号 /// 备 注:参数编号
///</summary> ///</summary>
[SugarColumn(ColumnName = "PARAM_CODE")] [SugarColumn(ColumnName = "PARAM_CODE")]
public string? PARAM_CODE { get; set; } public string? paramCode { get; set; }
/// <summary> /// <summary>
/// 备 注:设备编号 /// 备 注:设备编号
///</summary> ///</summary>
[SugarColumn(ColumnName = "DEVICE_CODE")] [SugarColumn(ColumnName = "DEVICE_CODE")]
public string? DEVICE_CODE { get; set; } public string? deviceCode { get; set; }
/// <summary> /// <summary>
/// 备 注:设备ID /// 备 注:设备ID
///</summary> ///</summary>
[SugarColumn(ColumnName = "DEVICE_ID")] [SugarColumn(ColumnName = "DEVICE_ID")]
public decimal? DEVICE_ID { get; set; } public decimal? deviceId { get; set; }
/// <summary> /// <summary>
/// 备 注:参数名称 /// 备 注:参数名称
///</summary> ///</summary>
[SugarColumn(ColumnName = "PARAM_NAME")] [SugarColumn(ColumnName = "PARAM_NAME")]
public string? PARAM_NAME { get; set; } public string? paramName { get; set; }
/// <summary> /// <summary>
/// 备 注:参数值 /// 备 注:参数值
///</summary> ///</summary>
[SugarColumn(ColumnName = "PARAM_VALUE")] [SugarColumn(ColumnName = "PARAM_VALUE")]
public string? PARAM_VALUE { get; set; } public string? paramValue { get; set; }
/// <summary> /// <summary>
/// 备 注:采集时间 /// 备 注:采集时间
///</summary> ///</summary>
[SugarColumn(ColumnName = "COLLECT_TIME")] [SugarColumn(ColumnName = "COLLECT_TIME")]
public DateTime? COLLECT_TIME { get; set; } public DateTime? collectTime { get; set; }
/// <summary> /// <summary>
/// 备 注:记录时间(默认当前时间) /// 备 注:记录时间(默认当前时间)
///</summary> ///</summary>
[SugarColumn(ColumnName = "RECORD_TIME")] [SugarColumn(ColumnName = "RECORD_TIME")]
public DateTime RECORD_TIME { get; set; } public DateTime recordTime { get; set; }
/// <summary> /// <summary>
/// 备 注:参数类型 /// 备 注:参数类型
///</summary> ///</summary>
[SugarColumn(ColumnName = "PARAM_TYPE")] [SugarColumn(ColumnName = "PARAM_TYPE")]
public string? PARAM_TYPE { get; set; } public string? paramType { get; set; }
} }

@ -16,13 +16,13 @@ namespace Sln.Imm.Daemon.Opc
{ {
public static void AddOpcDeviceFactorySetup(this IServiceCollection services) public static void AddOpcDeviceFactorySetup(this IServiceCollection services)
{ {
services.AddSingleton<List<IOpcService>>(x => services.AddSingleton<Dictionary<BaseDeviceInfo, IOpcService>>(x =>
{ {
var _cacheService = x.GetService<BaseDeviceInfoCacheService>(); var _cacheService = x.GetService<BaseDeviceInfoCacheService>();
List<BaseDeviceInfo> deviceInfos = _cacheService.GetValueAsync("BaseDeviceInfoCache").Result; List<BaseDeviceInfo> deviceInfos = _cacheService.GetValueAsync("BaseDeviceInfoCache").Result;
List<IOpcService> opcs = new List<IOpcService>(); Dictionary<BaseDeviceInfo, IOpcService> opcs = new Dictionary<BaseDeviceInfo, IOpcService>();
if (deviceInfos != null) if (deviceInfos != null)
{ {
foreach (var item in deviceInfos) foreach (var item in deviceInfos)
@ -39,7 +39,7 @@ namespace Sln.Imm.Daemon.Opc
opcDev = x.GetService<OpcDaService>(); opcDev = x.GetService<OpcDaService>();
} }
if(opcDev != null) if (opcDev != null)
{ {
var res = opcDev.ConnectAsync(item.networkAddress).Result; var res = opcDev.ConnectAsync(item.networkAddress).Result;
@ -50,7 +50,7 @@ namespace Sln.Imm.Daemon.Opc
} }
else else
{ {
opcs.Add(opcDev); opcs.Add(item, opcDev);
} }
} }
} }

@ -6,6 +6,7 @@ using Newtonsoft.Json;
using Sln.Imm.Daemon.Business; using Sln.Imm.Daemon.Business;
using Sln.Imm.Daemon.Cache; using Sln.Imm.Daemon.Cache;
using Sln.Imm.Daemon.Config; using Sln.Imm.Daemon.Config;
using Sln.Imm.Daemon.Model.dao;
using Sln.Imm.Daemon.Model.dto; using Sln.Imm.Daemon.Model.dto;
using Sln.Imm.Daemon.Opc; using Sln.Imm.Daemon.Opc;
using Sln.Imm.Daemon.Opc.Impl; using Sln.Imm.Daemon.Opc.Impl;
@ -36,30 +37,30 @@ namespace Sln.Imm.Daemon
var deviceCollectionBusiness = ServiceProvider.GetService<DeviceCollectionBusiness>(); var deviceCollectionBusiness = ServiceProvider.GetService<DeviceCollectionBusiness>();
//deviceCollectionBusiness?.Handle(); deviceCollectionBusiness?.Handle();
List<IOpcService> opcs = ServiceProvider.GetService<List<IOpcService>>(); //List<IOpcService> opcs = ServiceProvider.GetService<List<IOpcService>>();
if( opcs != null ) //if( opcs != null )
{ //{
foreach( var opc in opcs) // foreach( var opc in opcs)
{ // {
var res = opc.ReadNodeAsync(new List<string>() // var res = opc.ReadNodeAsync(new List<string>()
{ // {
"ns=4;s=APPL.Core1.sv_CoreOutput.NormalIn.Velocity.Output.rOutputValue", // "ns=4;s=APPL.Core1.sv_CoreOutput.NormalIn.Velocity.Output.rOutputValue",
"ns=4;s=APPL.Core1.sv_CoreSetTimes.MoveIn.dSetMoveTime" // "ns=4;s=APPL.Core1.sv_CoreSetTimes.MoveIn.dSetMoveTime"
}); // });
Console.WriteLine($"数据采集完成:{JsonConvert.SerializeObject(res)}"); // Console.WriteLine($"数据采集完成:{JsonConvert.SerializeObject(res)}");
Thread.Sleep(5000); // Thread.Sleep(5000);
opc.DisconnectAsync(); // opc.DisconnectAsync();
Console.WriteLine($"断开设备连接"); // Console.WriteLine($"断开设备连接");
} // }
} //}
Task.Delay(-1).Wait(); Task.Delay(-1).Wait();
@ -105,7 +106,6 @@ namespace Sln.Imm.Daemon
new SqliteCache(new SqliteCacheOptions new SqliteCache(new SqliteCacheOptions
{ {
CachePath = "D:\\working_area\\project\\澳柯玛注塑采集\\cache\\FusionCache.db" CachePath = "D:\\working_area\\project\\澳柯玛注塑采集\\cache\\FusionCache.db"
//CachePath = "/Users/wenxiansheng/Public/WorkSpace/Mesnac/项目资料/澳柯玛注塑车间MES项目/数据缓存/FusionCache.db"
})); }));
services.AddOpcDeviceFactorySetup(); services.AddOpcDeviceFactorySetup();

Loading…
Cancel
Save