添加项目文件。

This commit is contained in:
Administrator
2026-08-04 18:36:40 +08:00
parent 16fb9e4f5a
commit a2ecbc795d
616 changed files with 149853 additions and 0 deletions
+62
View File
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<appSettings>
<!--//日志配置 开启日志-->
<add key="EnableLogging" value="true" />
<!--//日志配置 日志存储周期 默认30天-->
<add key="LogRetentionDays" value="30" />
<!--//日志配置 日志存储路径 暂未使用,存储在跟目录-->
<add key="LogDirectory" value="D:\APILog\MQTTService" />
<!--//日志配置 按日存储-->
<add key="LogSplitStrategy" value="ByDay" />
<!--//日志配置 存储文件大小-->
<add key="MaxLogFileSizeBytes" value="10485760" />
<!--//PLC IP地址 192.168.1.50-->
<add key="PlcIpAddress" value="192.168.1.50" />
<!--//PLC 端口-->
<add key="PlcPort" value="9600" />
<!--//MQTT服务器IP地址 10.22.160.144-->
<add key="MQTTServerAddress" value="10.22.160.144" />
<!--//MQTT服务器端口-->
<add key="MQTTServerPort" value="1883" />
<!--//MQTT服务器发布ID-->
<add key="ClientId" value="601UPW01" />
<!--//MQTT服务发布主题PPM-->
<add key="Topic" value="EVE/60J/EQP/NEW_PPM/601UPW01" />
<!--PPM其他数据-->
<add key="Topic1" value="eve/60J/EQP/601UPW01"/>
<!--直角坐标机械臂-->
<add key="LRobotTopic" value="EVE/60J/LRobot/601PWM01_LUR01"/>
<!--关节机械臂-->
<add key="JRobotTopic" value="EVE/60J/JRobot/601PWM01_STR01"/>
<!--//参数设置 事业部-->
<add key="BU_id" value="EVE2BU" />
<!--//参数设置 地区-->
<add key="District_id" value="JM" />
<!--//参数设置 工厂-->
<add key="Factory_id" value="60J" />
<!--//参数设置 线体号-->
<add key="Production_line_id" value="MW-601" />
<!--//参数设置 设备编号-->
<add key="Device_name" value="601UPW01" />
<!--//线程循环间隔 ms单位-->
<add key="ThreadInterval" value="50" />
<add key="SwitchLog" value="True" />
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<system.web>
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
</providers>
</roleManager>
</system.web>
</configuration>
File diff suppressed because it is too large Load Diff
+127
View File
@@ -0,0 +1,127 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{242400F4-9B01-4AEE-A6F7-05083757FCDD}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>IOT.Services</RootNamespace>
<AssemblyName>IOT.Services</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<LangVersion>10.0</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="DataConvertLib, Version=6.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>Lib\DataConvertLib.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>Lib\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="NLog, Version=6.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\packages\NLog.6.0.2\lib\net46\NLog.dll</HintPath>
</Reference>
<Reference Include="PLCCommunication, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>Lib\PLCCommunication.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Core" />
<Reference Include="System.Management" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Logger.cs" />
<Compile Include="Models.cs" />
<Compile Include="MqttClientWrapper.cs" />
<Compile Include="MqttDataService.cs" />
<Compile Include="PLCDataReader.cs" />
<Compile Include="PLCWrapper.cs" />
<Compile Include="Service1.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="Service1.Designer.cs">
<DependentUpon>Service1.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="StationDataComparer.cs" />
<Compile Include="XmlConfigReader.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="NLog.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Content Include="Lib\DataConvertLib.dll" />
<Content Include="Lib\Newtonsoft.Json.dll" />
<Content Include="Lib\PLCCommunication.dll" />
<Content Include="Config.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.8">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.8 %28x86 和 x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
Binary file not shown.
Binary file not shown.
+135
View File
@@ -0,0 +1,135 @@
using NLog;
using System;
using System.IO;
using System.Timers;
public class Logger
{
private static readonly NLog.Logger loginfo = LogManager.GetLogger("loginfo");
private static readonly NLog.Logger logerror = LogManager.GetLogger("logerror");
private static readonly NLog.Logger logmqtt = LogManager.GetLogger("logmqtt");
private static readonly NLog.Logger logsInfo = LogManager.GetLogger("logsInfo");
private static readonly NLog.Logger logsMEStIME = LogManager.GetLogger("logsMEStIME");
private static readonly NLog.Logger logsSql = LogManager.GetLogger("logsSql");
private static readonly NLog.Logger logsSysErrorLog = LogManager.GetLogger("logsSysErrorLog");
private static readonly NLog.Logger logsSysErrorLogcn = LogManager.GetLogger("logsSysErrorLogcn");
private static readonly Timer cleanupTimer;
private const int MAX_DAYS = 7;
private const string LOG_BASE_PATH = "Log";
static Logger()
{
try
{
// 创建一个每天执行一次的定时器
cleanupTimer = new Timer(24 * 60 * 60 * 1000); // 24小时
cleanupTimer.Elapsed += CleanupOldLogs;
cleanupTimer.Start();
// 启动时执行一次清理
CleanupOldLogs(null, null);
}
catch (Exception ex)
{
WriteError("Failed to initialize logger cleanup timer", ex);
}
}
public static void WriteInfo(string info)
{
if (loginfo.IsInfoEnabled)
{
loginfo.Info(info);
}
}
public static void WriteMqtt(string info)
{
if (logmqtt.IsInfoEnabled)
{
logmqtt.Info(info);
}
}
public static void WriteError(string error)
{
if (logerror.IsErrorEnabled)
{
logerror.Error(error);
}
}
public static void WriteError(string info, Exception ex)
{
if (logerror.IsErrorEnabled)
{
logerror.Error(info, ex);
}
}
private static void CleanupOldLogs(object sender, ElapsedEventArgs e)
{
try
{
if (!Directory.Exists(LOG_BASE_PATH))
return;
string[] logTypes = { "LogError", "LogInfo", "LogMqtt" };
DateTime cutoffDate = DateTime.Now.AddDays(-MAX_DAYS);
foreach (string logType in logTypes)
{
string logTypeDir = Path.Combine(LOG_BASE_PATH, logType);
if (!Directory.Exists(logTypeDir))
continue;
// 获取所有日期文件夹
string[] dateDirs = Directory.GetDirectories(logTypeDir);
foreach (string dateDir in dateDirs)
{
string dirName = Path.GetFileName(dateDir);
if (DateTime.TryParseExact(dirName, "yyyyMMdd", null,
System.Globalization.DateTimeStyles.None, out DateTime dirDate))
{
if (dirDate < cutoffDate)
{
try
{
Directory.Delete(dateDir, true);
WriteInfo($"Deleted old log directory: {dateDir}");
}
catch (Exception ex)
{
WriteError($"Failed to delete log directory: {dateDir}", ex);
}
}
}
}
}
}
catch (Exception ex)
{
WriteError("Error during log cleanup", ex);
}
}
// 提供手动清理方法
public static void ForceCleanupOldLogs()
{
CleanupOldLogs(null, null);
}
// 在应用程序退出时调用此方法
public static void Shutdown()
{
if (cleanupTimer != null)
{
cleanupTimer.Stop();
cleanupTimer.Dispose();
}
}
}
+85
View File
@@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
namespace WindowsService1
{
#region 1、系统内部
public enum AcquisitionType
{
PPM,
Axis,
Cylinder,
LRobot
}
public enum PLCDataType
{
Short,
Float
}
public class StationData
{
public string Name { get; set; }
public object MainValue { get; set; }
public DateTime Timestamp { get; set; }
}
public class TypeConfig
{
public string Name { get; set; }
public string Address { get; set; }
public string DataType { get; set; }
}
public class CollectionGroupConfig
{
public string Name { get; set; }
public string StartAddress { get; set; }
public int Length { get; set; }
public string DefaultDataType { get; set; }
public Dictionary<string, TypeConfig> Types { get; set; }
}
#endregion
#region 2、PPM点位
#endregion
#region 3、预测性点位
#endregion
#region 4、机械臂
//直角坐标机械臂
public class LRobot
{
public string bu_id { get; set; }
public string district_id { get; set; }
public string factory_id { get; set; }
public string production_line_id { get; set; }
public string production_processes_id { get; set; }
public string work_center_id { get; set; }
public string station_id { get; set; }
public string device_name { get; set; } = "601PWM01";
public string robot_name { get; set; }
public List<Taglist> taglist { get; set; }
}
public class Taglist
{
public string device_time { get; set; }
public Collection collections_items { get; set; }
}
public class Collection
{
public string robot_status { get; set; } = "1";
public string x_value { get; set; }
public string y_value { get; set; }
public string z_value { get; set; }
public string time_span { get; set; } = "2.5";
public string hand_status { get; set; } = "1";
}
#endregion
}
+376
View File
@@ -0,0 +1,376 @@
using Newtonsoft.Json.Linq;
using PLCCommunication;
using PLCCommunication.LogNet;
using PLCCommunication.MQTT;
using System;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace WindowsService1
{
public class MqttClientWrapper
{
private MqttClient mqttClient;
private bool mqttIsConnected;
private const int MaxReconnectAttempts = 5;
private const int ReconnectDelay = 5000; // 5 seconds
private MqttConnectionOptions options;
public event Action<string, string, string> OnMessageReceived;
public long ReceiveCount { get; private set; }
public PLCCommunication.LogNet.ILogNet LogNet = new LogNetDateTime("D:\\APILog\\Logs\\MQTTLogs", GenerateMode.ByEveryDay, 20);
public enum MessageFormat
{
Binary,
Text,
Xml,
Json
}
public MqttClientWrapper(string ipAddress, int port, string clientId, MqttCredential credentials)
{
InitializeMqttOptions(ipAddress, port, clientId, credentials);
}
private void InitializeMqttOptions(string ipAddress, int port, string clientId, MqttCredential credentials)
{
options = new MqttConnectionOptions
{
IpAddress = ipAddress,
Port = port,
ClientId = clientId,
Credentials = credentials,
UseRSAProvider = false,
CleanSession = false,
UseSSL = false,
SSLSecure = false,
CertificateFile = "",
KeepAlivePeriod = TimeSpan.FromSeconds(30),
KeepAliveSendInterval = TimeSpan.FromSeconds(10),
ConnectTimeout = 5,
WillMessage = null
};
}
public async Task InitializeAndConnectAsync()
{
try
{
mqttClient = new MqttClient(options);
Logger.WriteMqtt("MQTT 初始化成功");
await ConnectMqttAsync();
}
catch (Exception ex)
{
Logger.WriteError($"MQTT 初始化失败: {ex.Message}");
}
}
private async Task ConnectMqttAsync()
{
try
{
JYResult connect = await mqttClient.ConnectServerAsync();
if (connect.IsSuccess)
{
mqttIsConnected = true;
Logger.WriteMqtt("MQTT 连接服务器成功");
}
else
{
Logger.WriteError("MQTT 无法连接到服务器");
}
}
catch (Exception ex)
{
Logger.WriteError($"MQTT 无法连接到服务器: {ex.Message}");
}
}
public async Task SendMessageAsync(string source, string publishTopic, string type, JObject messageObj)
{
if (!mqttClient.IsConnected)
{
mqttIsConnected = false;
Logger.WriteMqtt("客户端未连接到服务器。正在尝试重新连接...");
await ReconnectWithRetry();
if (!mqttClient.IsConnected)
{
throw new InvalidOperationException("无法与 MQTT 代理建立连接.");
}
}
try
{
if (messageObj != null)
{
string json = messageObj.ToString();
//string json = JsonConvert.SerializeObject(messageObj);
JYResult result = await mqttClient.PublishMessageAsync(new MqttApplicationMessage
{
Topic = publishTopic,
QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
Payload = Encoding.UTF8.GetBytes(json),
Retain = false,
});
if (result.IsSuccess)
{
if (Service1.SwitchLog)
{
Logger.WriteMqtt($"线程 [{source}] 发送 [{type}] 消息到主题 [{publishTopic}]: {json}");
}
}
else
{
Logger.WriteMqtt($"线程 [{source}] 发送 [{type}] 消息到主题 [{publishTopic}] 失败: {result.Message}");
}
}
}
catch (Exception ex)
{
Logger.WriteError($"发送消息错误: {ex.Message}");
}
}
public async Task SendMessageAsync(string source, string publishTopic, string type, string messageObj)
{
if (!mqttClient.IsConnected)
{
mqttIsConnected = false;
Logger.WriteMqtt("客户端未连接到服务器。正在尝试重新连接...");
await ReconnectWithRetry();
if (!mqttClient.IsConnected)
{
throw new InvalidOperationException("无法与 MQTT 代理建立连接.");
}
}
try
{
if (messageObj != null)
{
JYResult result = await mqttClient.PublishMessageAsync(new MqttApplicationMessage
{
Topic = publishTopic,
QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
Payload = Encoding.UTF8.GetBytes(messageObj),
Retain = false,
});
if (result.IsSuccess)
{
if (Service1.SwitchLog)
{
Logger.WriteMqtt($"线程 [{source}] 发送 [{type}] 消息到主题 [{publishTopic}]: {messageObj}");
}
}
else
{
Logger.WriteMqtt($"线程 [{source}] 发送 [{type}] 消息到主题 [{publishTopic}] 失败: {result.Message}");
}
}
}
catch (Exception ex)
{
Logger.WriteError($"发送消息错误: {ex.Message}");
}
}
public void SubscribeMessage(string topic, MessageFormat format = MessageFormat.Text, bool truncateLongMessage = false)
{
if (!mqttIsConnected)
{
ConnectMqttAsync().Wait();
}
try
{
JYResult operateResult = mqttClient.SubscribeMessage(new string[] { topic });
if (!operateResult.IsSuccess)
{
Logger.WriteMqtt($"订阅消息失败: {operateResult.Message}");
return;
}
SubscribeTopic subscribeTopic = mqttClient.GetSubscribeTopic(topic);
if (subscribeTopic != null)
{
subscribeTopic.OnMqttMessageReceived += (sender, args) =>
{
HandleReceivedMessage(args.Topic, args.Payload, format, truncateLongMessage);
};
Logger.WriteMqtt($"成功订阅主题: {topic}");
}
else
{
Logger.WriteMqtt($"无法获取订阅主题 {topic}");
}
}
catch (Exception ex)
{
Logger.WriteError($"订阅主题时出错 {topic}: {ex.Message}");
}
}
private void HandleReceivedMessage(string topic, byte[] payload, MessageFormat format, bool truncateLongMessage)
{
ReceiveCount++;
string text = string.Empty;
try
{
switch (format)
{
case MessageFormat.Binary:
text = BitConverter.ToString(payload).Replace("-", " ");
break;
case MessageFormat.Text:
text = Encoding.UTF8.GetString(payload);
break;
case MessageFormat.Xml:
try
{
text = XElement.Parse(Encoding.UTF8.GetString(payload)).ToString();
}
catch
{
text = Encoding.UTF8.GetString(payload);
}
break;
case MessageFormat.Json:
try
{
text = JObject.Parse(Encoding.UTF8.GetString(payload)).ToString();
}
catch
{
text = Encoding.UTF8.GetString(payload);
}
break;
}
//if (Service1.SwitchLog)
//{
// LogNet.WriteDebug($"收到主题 {topic}: {text}");
//}
//if (truncateLongMessage && text.Length > 200)
//{
// text = text.Substring(0, 200) + "...";
//}
string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
OnMessageReceived?.Invoke(timestamp, topic, text);
}
catch (Exception ex)
{
Logger.WriteError($"处理收到的消息时出错: {ex.Message}");
}
}
public void UnsubscribeMessage(string topic)
{
try
{
JYResult operateResult = mqttClient.UnSubscribeMessage(new string[] { topic });
if (operateResult.IsSuccess)
{
Logger.WriteMqtt($"成功取消订阅主题: {topic}");
}
else
{
Logger.WriteMqtt($"取消订阅主题失败 {topic}: {operateResult.Message}");
}
}
catch (Exception ex)
{
Logger.WriteError($"取消订阅主题时出错 {topic}: {ex.Message}");
}
}
/// <summary>
/// 重连
/// </summary>
/// <returns></returns>
private async Task ReconnectWithRetry()
{
int attempts = 0;
while (!mqttClient.IsConnected && attempts < MaxReconnectAttempts)
{
try
{
await mqttClient.ConnectServerAsync();
Logger.WriteMqtt("重新连接成功.");
return;
}
catch (Exception ex)
{
attempts++;
Logger.WriteMqtt($"重新连接尝试 {attempts} 失败的: {ex.Message}");
await Task.Delay(ReconnectDelay);
}
}
if (!mqttClient.IsConnected)
{
Logger.WriteMqtt("尝试次数达到上限后仍无法重新连接.");
}
}
private async Task ReconnectAsync()
{
Logger.WriteMqtt("正在尝试重新连接...");
mqttIsConnected = false;
int retryCount = 0;
const int maxRetries = 5;
const int retryDelayMs = 5000;
while (!mqttIsConnected && retryCount < maxRetries)
{
try
{
await ConnectMqttAsync();
if (mqttIsConnected)
{
Logger.WriteMqtt("重新连接成功");
return;
}
}
catch (Exception ex)
{
Logger.WriteMqtt($"重新连接尝试 {retryCount + 1} 失败的: {ex.Message}");
}
retryCount++;
await Task.Delay(retryDelayMs);
}
if (!mqttIsConnected)
{
Logger.WriteMqtt("多次尝试后仍无法重新连接");
}
}
public async Task Disconnect()
{
await mqttClient.ConnectCloseAsync();
mqttIsConnected = false;
Logger.WriteMqtt("与 MQTT服务端断开连接!!!");
}
}
}
+730
View File
@@ -0,0 +1,730 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
namespace WindowsService1
{
public class MqttDataService
{
public static string BU_id;
public static string District_id;
public static string Factory_id;
public static string Production_line_id;
public static string Device_name;
public static string Topic;
public static string Work_Center_id;
public class OperationData
{
public int Item_Value { get; set; }
public string Start_Time { get; set; }
public string End_Time { get; set; }
}
public class MqttMessage
{
public string bu_id { get; set; }
public string district_id { get; set; }
public string factory_id { get; set; }
public string production_line_id { get; set; }
public string production_processes_id { get; set; }
public string work_center_id { get; set; }
public string station_id { get; set; }
public string device_name { get; set; }
public List<TagList> taglist { get; set; }
}
public class TagList
{
public string device_time { get; set; }
public Dictionary<string, OperationData> collection_items { get; set; }
}
/// <summary>
///
/// </summary>
/// <param name="source"></param>
/// <param name="type"></param>
/// <param name="processedValues"></param>
/// <param name="_plcAddresses"></param>
/// <param name="_collectionGroups"></param>
/// <returns></returns>
public static MqttMessage CreateMqttMessage(string source, AcquisitionType type, List<StationData> processedValues,
Dictionary<AcquisitionType, Dictionary<string, string>> _plcAddresses,
Dictionary<AcquisitionType, CollectionGroupConfig> _collectionGroups)
{
try
{
Logger.WriteInfo($"开始创建 MQTT 消息, 类型: {type}, 数据点数量: {processedValues?.Count ?? 0}");
if (processedValues == null || processedValues.Count == 0)
{
Logger.WriteInfo("没有需要处理的数据,返回 null");
return null;
}
var addresses = _plcAddresses[type];
var config = _collectionGroups[type];
var collectionItems = new Dictionary<string, OperationData>();
// 获取当前时间作为设备时间
var currentTime = DateTime.Now;
var deviceTimeStr = currentTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
Logger.WriteInfo($"处理数据类型: {type}, 当前时间: {deviceTimeStr}");
switch (type)
{
case AcquisitionType.PPM:
ProcessPPMData(processedValues, addresses, config, collectionItems);
break;
case AcquisitionType.Axis:
case AcquisitionType.Cylinder:
ProcessFloatData(processedValues, addresses, config, currentTime, collectionItems);
break;
default:
Logger.WriteError($"未知的数据类型: {type}");
return null;
}
if (collectionItems.Count == 0)
{
Logger.WriteInfo("没有有效的采集项,返回 null");
return null;
}
var message = new MqttMessage
{
bu_id = BU_id,
district_id = District_id,
factory_id = Factory_id,
production_line_id = Production_line_id,
production_processes_id = string.Empty,
work_center_id = Work_Center_id,
station_id = "1",
device_name = Device_name,
taglist = new List<TagList>
{
new TagList
{
device_time = deviceTimeStr,
collection_items = collectionItems
}
}
};
// 记录创建的消息内容
Logger.WriteInfo($"MQTT 消息创建完成: {JsonConvert.SerializeObject(message, Formatting.None)}");
return message;
}
catch (Exception ex)
{
Logger.WriteError($"创建 MQTT 消息时发生错误: {ex.Message}");
return null;
}
}
/// <summary>
/// PPM点位数据
/// </summary>
/// <param name="processedValues"></param>
/// <param name="addresses"></param>
/// <param name="config"></param>
/// <param name="collectionItems"></param>
///
// 添加静态字段来存储上次发送的数据
private static Dictionary<string, OperationData> _lastSentData = new Dictionary<string, OperationData>();
public static void ProcessPPMData(List<StationData> processedValues, Dictionary<string, string> addresses, CollectionGroupConfig config, Dictionary<string, OperationData> collectionItems)
{
try
{
Logger.WriteInfo($"开始处理 PPM 数据,数据点数量: {processedValues.Count}");
// 创建临时字典存储当前所有数据点
var tempItems = new Dictionary<string, OperationData>();
foreach (var value in processedValues)
{
var addressPair = addresses.FirstOrDefault(x => x.Key == value.Name);
if (!string.IsNullOrEmpty(addressPair.Key))
{
int itemValue = Convert.ToInt32(ConvertToIntegerWithThreeDecimals(value.MainValue));
// 计算开始时间 (结束时间 - 时长)
var startTime = value.Timestamp.AddMilliseconds(-itemValue);
var operationData = new OperationData
{
Item_Value = itemValue,
Start_Time = startTime.ToString("yyyy-MM-dd HH:mm:ss.fff"),
End_Time = value.Timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff")
};
// 检查数据是否发生变化
bool shouldAdd = true;
// 检查是否与上次发送的数据重复
if (_lastSentData.TryGetValue(addressPair.Key, out var lastData))
{
var currentEndTime = operationData.End_Time.ToString();
var lastEndTime = lastData.End_Time.ToString();
if (string.Equals(lastEndTime, currentEndTime, StringComparison.OrdinalIgnoreCase))
{
shouldAdd = false;
Logger.WriteInfo($"跳过重复数据点: {addressPair.Key}");
continue;
}
}
if (shouldAdd)
{
tempItems[addressPair.Key] = operationData;
Logger.WriteInfo($"处理数据点: {addressPair.Key}, 值: {itemValue}, " +
$"开始时间: {startTime:yyyy-MM-dd HH:mm:ss.fff}, " +
$"结束时间: {operationData.End_Time}");
}
//if (shouldAdd)
//{
// // 检查是否与当前批次的其他数据有重复的结束时间
// var duplicateEndTimeItem = tempItems.FirstOrDefault(x =>
// string.Equals(x.Value.End_Time.ToString(), operationData.End_Time.ToString(), StringComparison.OrdinalIgnoreCase));
// if (duplicateEndTimeItem.Key != null)
// {
// Logger.WriteError($"检测到结束时间重复: {operationData.End_Time} 对应地址: {addressPair.Key}, " +
// $"与地址 {duplicateEndTimeItem.Key} 的数据重复");
// // 根据地址的字母顺序决定哪个需要调整时间,确保调整的一致性
// if (string.Compare(addressPair.Key, duplicateEndTimeItem.Key) > 0)
// {
// operationData.End_Time = value.Timestamp.AddMilliseconds(1).ToString("yyyy-MM-dd HH:mm:ss.fff");
// Logger.WriteInfo($"调整后的结束时间: {operationData.End_Time}");
// }
// }
// tempItems[addressPair.Key] = operationData;
// Logger.WriteInfo($"处理数据点: {addressPair.Key}, 值: {itemValue}, " +
// $"开始时间: {startTime:yyyy-MM-dd HH:mm:ss.fff}, " +
// $"结束时间: {operationData.End_Time}");
//}
}
else
{
Logger.WriteError($"未找到数据点 {value.Name} 对应的地址配置");
}
}
// 将处理后的数据添加到最终结果并更新上次发送的数据
foreach (var item in tempItems)
{
collectionItems[item.Key] = item.Value;
_lastSentData[item.Key] = item.Value; // 更新上次发送的数据
}
Logger.WriteInfo($"PPM 数据处理完成,处理后的数据点数量: {collectionItems.Count}");
}
catch (Exception ex)
{
Logger.WriteError($"处理 PPM 数据时出错: {ex.Message}");
throw;
}
}
private static bool IsDataEqual(OperationData data1, OperationData data2, string addressKey)
{
if (data1 == null || data2 == null)
return false;
bool isEqual = data1.Item_Value == data2.Item_Value &&
data1.Start_Time == data2.Start_Time &&
data1.End_Time == data2.End_Time;
if (isEqual)
{
Logger.WriteInfo($"检测到重复数据 - 地址: {addressKey}, " +
$"值: {data1.Item_Value}, " +
$"开始时间: {data1.Start_Time}, " +
$"结束时间: {data1.End_Time}");
}
return isEqual;
}
/// <summary>
/// 预测性点位
/// </summary>
/// <param name="processedValues"></param>
/// <param name="addresses"></param>
/// <param name="config"></param>
/// <param name="endTime"></param>
/// <param name="collectionItems"></param>
public static void ProcessFloatData(List<StationData> processedValues, Dictionary<string, string> addresses, CollectionGroupConfig config, DateTime endTime, Dictionary<string, OperationData> collectionItems)
{
for (int i = 0; i < processedValues.Count && i < config.Length; i++)
{
string address = $"D{int.Parse(config.StartAddress.Substring(1)) + i * 2}";
if (addresses.ContainsValue(address))
{
var key = addresses.FirstOrDefault(x => x.Value == address).Key;
int itemValue = Convert.ToInt32(ConvertToIntegerWithThreeDecimals(processedValues[i].MainValue));
// 计算开始时间 (结束时间 - 时长)
//var startTime = endTime.AddMilliseconds(-itemValue);
collectionItems[key] = new OperationData
{
Item_Value = (int)itemValue,
Start_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
End_Time = endTime.ToString("yyyy-MM-dd HH:mm:ss.fff")
};
}
}
}
/// <summary>
/// 机械臂数据
/// </summary>
/// <param name="source"></param>
/// <param name="type"></param>
/// <param name="processedValues"></param>
/// <param name="_plcAddresses"></param>
/// <param name="_collectionGroups"></param>
/// <returns></returns>
public static LRobot LRobotMessage(string source, AcquisitionType type, List<StationData> processedValues, Dictionary<AcquisitionType, Dictionary<string, string>> _plcAddresses,
Dictionary<AcquisitionType, CollectionGroupConfig> _collectionGroups)
{
if (processedValues == null || processedValues.Count == 0)
{
return null;
}
var addresses = _plcAddresses[type];
var config = _collectionGroups[type];
return new LRobot()
{
bu_id = BU_id,
district_id = District_id,
factory_id = Factory_id,
production_line_id = Production_line_id,
production_processes_id = "",
work_center_id = "",
station_id = "",
device_name = "601PWM01",
robot_name = "LUR01",
taglist = new List<Taglist>
{
new Taglist//上料动子1
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[0].MainValue.ToString(),
y_value="0",
z_value=processedValues[1].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//上料动子2
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[2].MainValue.ToString(),
y_value="0",
z_value=processedValues[3].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//上料动子3
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[4].MainValue.ToString(),
y_value="0",
z_value=processedValues[5].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//上料动子4
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[6].MainValue.ToString(),
y_value="0",
z_value=processedValues[7].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//上料动子5
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[8].MainValue.ToString(),
y_value="0",
z_value=processedValues[9].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//上料动子6
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[10].MainValue.ToString(),
y_value="0",
z_value=processedValues[11].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//上料动子7
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[13].MainValue.ToString(),
y_value="0",
z_value=processedValues[14].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//上料动子8
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[16].MainValue.ToString(),
y_value="0",
z_value=processedValues[17].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//上料动子9
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[18].MainValue.ToString(),
y_value="0",
z_value=processedValues[19].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//焊机1
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[20].MainValue.ToString(),
y_value=processedValues[21].MainValue.ToString(),
z_value=processedValues[22].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//焊机2
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[23].MainValue.ToString(),
y_value=processedValues[24].MainValue.ToString(),
z_value=processedValues[25].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//焊机3
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[26].MainValue.ToString(),
y_value=processedValues[27].MainValue.ToString(),
z_value=processedValues[28].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//焊机4
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[29].MainValue.ToString(),
y_value=processedValues[30].MainValue.ToString(),
z_value=processedValues[31].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//焊机5
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[32].MainValue.ToString(),
y_value=processedValues[33].MainValue.ToString(),
z_value=processedValues[34].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//焊机6
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[35].MainValue.ToString(),
y_value=processedValues[36].MainValue.ToString(),
z_value=processedValues[37].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//焊机7
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[38].MainValue.ToString(),
y_value=processedValues[39].MainValue.ToString(),
z_value=processedValues[40].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//焊机8
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[41].MainValue.ToString(),
y_value=processedValues[42].MainValue.ToString(),
z_value=processedValues[43].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//焊机9
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[44].MainValue.ToString(),
y_value=processedValues[45].MainValue.ToString(),
z_value=processedValues[46].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//焊机10
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[47].MainValue.ToString(),
y_value=processedValues[48].MainValue.ToString(),
z_value=processedValues[49].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//焊机11
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[50].MainValue.ToString(),
y_value=processedValues[51].MainValue.ToString(),
z_value=processedValues[52].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//焊机12
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[53].MainValue.ToString(),
y_value=processedValues[54].MainValue.ToString(),
z_value=processedValues[55].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//下料动子1
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[56].MainValue.ToString(),
y_value="0",
z_value=processedValues[57].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//下料动子2
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[58].MainValue.ToString(),
y_value="0",
z_value=processedValues[59].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//下料动子3
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[61].MainValue.ToString(),
y_value="0",
z_value=processedValues[62].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//下料动子4
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[63].MainValue.ToString(),
y_value="0",
z_value=processedValues[64].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//下料动子5
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[65].MainValue.ToString(),
y_value="0",
z_value=processedValues[66].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
},
new Taglist//下料动子6
{
device_time=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
collections_items=new Collection()
{
robot_status = "1",
x_value=processedValues[67].MainValue.ToString(),
y_value="0",
z_value=processedValues[68].MainValue.ToString(),
time_span="2.5",
hand_status="1",
}
}
}
};
}
// 辅助方法
private static List<short> ConvertToShortList(object[] data)
{
return data.Select(x => Convert.ToInt16(x)).ToList();
}
private static List<float> ConvertToFloatList(object[] data)
{
return data.Select(x => Convert.ToSingle(x)).ToList();
}
private static object ConvertToIntegerWithThreeDecimals(object value)
{
try
{
if (value == null) return 0;
if (value is float floatValue)
{
return (int)Math.Round(floatValue * 1000);
}
else if (value is double doubleValue)
{
return (int)Math.Round(doubleValue * 1000);
}
else if (value is decimal decimalValue)
{
return (int)Math.Round(decimalValue * 1000);
}
else
{
// 尝试转换其他类型
float converted = Convert.ToSingle(value);
return (int)Math.Round(converted * 1000);
}
}
catch (Exception ex)
{
Logger.WriteError($"转换值到整数时出错: {ex.Message}, 值: {value}");
return 0;
}
}
}
}
+62
View File
@@ -0,0 +1,62 @@
<?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"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<variable name="variable1" value="${newline}date: ${date}${newline}level: ${level}${newline}logger: ${logger}${newline}machinename: ${machinename}
${newline}clientip:${local-ip}${newline}message: ${message} ${newline}exception:${exception}
${newline}appdomain: ${appdomain}${newline}assembly-version: ${assembly-version}${newline}basedir: ${basedir}
${newline}callsite: ${callsite}${newline}callsite-linenumber: ${callsite-linenumber}${newline}counter: ${counter}${newline}nlogdir: ${nlogdir}
${newline}processid: ${processid}${newline}processname: ${processname}
${newline}traceid: ${aspnet-traceidentifier}
${newline}specialfolder: ${specialfolder}
${newline}stacktrace: ${stacktrace}${newline}-----------------------------------------------------------" />
<variable name="variable2" value="日志时间:${longdate}${newline}日志来源:${callsite}${newline}日志级别:${uppercase:${level}}${newline}消息内容:${message}${newline}异常信息:${exception}${newline}stacktrace: ${stacktrace}${newline}==============================================================${newline}" />
<variable name="variable3" value="${longdate}消息内容:${message}${newline}==============================================================${newline}" />
<variable name="variable_info" value="&lt;HR COLOR=blue&gt;${newline}日志时间:${longdate} &lt;BR&gt;${newline}日志级别:${level} &lt;BR&gt;${newline}日 志 类:log_info &lt;BR&gt;${newline}${message} &lt;BR&gt;${newline} &lt;HR Size=1&gt;" />
<variable name="variable_error" value="&lt;HR COLOR=blue&gt;${newline}日志时间:${longdate} &lt;BR&gt;${newline}日志级别:${level} &lt;BR&gt;${newline}日 志 类:log_error &lt;BR&gt;${newline}${message} &lt;BR&gt;${newline} &lt;HR Size=1&gt;" />
<variable name="variable_mqtt" value="&lt;HR COLOR=blue&gt;${newline}日志时间:${longdate} &lt;BR&gt;${newline}日志级别:${level} &lt;BR&gt;${newline}日 志 类:log_mqtt &lt;BR&gt;${newline}${message} &lt;BR&gt;${newline} &lt;HR Size=1&gt;" />
<variable name="variable_Infos" value="${longdate}消息内容:${message}${newline}==============================================================${newline}" />
<variable name="variable_MEStIME" value="${longdate}消息内容:${message}${newline}==============================================================${newline}" />
<variable name="variable_sql" value="${longdate}消息内容:${message}${newline}==============================================================${newline}" />
<variable name="variable_SysErrorLog" value="${longdate}消息内容:${message}${newline}==============================================================${newline}" />
<variable name="variable_SysErrorLogcn" value="${longdate}消息内容:${message}${newline}==============================================================${newline}" />
<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->
<targets>
<!--
Write events to a file with the date in the filename. -->
<!--<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />-->
<target name="log_file" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
<target xsi:type="File" fileName="${basedir}/logs/${shortdate}/${shortdate}.${level}.log"
layout="${variable2}" archiveAboveSize="2097152" archiveEvery="Day" />
</target>
<!--<target name="log_file" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log" layout="${variable1}" />-->
<target name="log_info" xsi:type="File" fileName="${basedir}/Log/${shortdate}/LogInfo.${level}.html" layout="${variable_info}" archiveAboveSize="2097152" archiveEvery="Day"/>
<target name="log_error" xsi:type="File" fileName="${basedir}/Log/${shortdate}/LogError.${level}.html" layout="${variable_error}" archiveAboveSize="2097152" archiveEvery="Day"/>
<target name="log_mqtt" xsi:type="File" fileName="${basedir}/Log/${shortdate}/LogMqtt.${level}.html" layout="${variable_mqtt}" archiveAboveSize="2097152" archiveEvery="Day"/>
<target name="logs_Infos" xsi:type="File" fileName="${basedir}/Logs/Info/${shortdate}/${level}.log" layout="${variable_Infos}" archiveAboveSize="2097152" archiveEvery="Day"/>
<target name="logs_MEStIME" xsi:type="File" fileName="${basedir}/Logs/MESTime/${shortdate}/${level}.log" layout="${variable_MEStIME}" archiveAboveSize="2097152" archiveEvery="Day"/>
<target name="logs_Sql" xsi:type="File" fileName="${basedir}/Logs/SQL执行/${shortdate}/${level}.log" layout="${variable_sql}" archiveAboveSize="2097152" archiveEvery="Day"/>
<target name="logs_SysErrorLog" xsi:type="File" fileName="${basedir}/Logs/SysErrorLog/${shortdate}/${level}.log" layout="${variable_SysErrorLog}" archiveAboveSize="2097152" archiveEvery="Day"/>
<target name="logs_SysErrorLogcn" xsi:type="File" fileName="${basedir}/Logs/系统报错/${shortdate}/${level}.log" layout="${variable_SysErrorLogcn}" archiveAboveSize="2097152" archiveEvery="Day"/>
<target name="log_ReadPlcInt" xsi:type="File" fileName="${basedir}/hslLogs/${shortdate}/ReadPlcInt.${level}.log" layout="${Heartvariable}" archiveAboveSize="2097152" archiveEvery="Day"/>
</targets>
<rules>
<logger name="loginfo" minlevel="Info" writeTo="log_info" final="true"/>
<logger name="logerror" minlevel="Info" writeTo="log_error" final="true"/>
<logger name="logmqtt" minlevel="Info" writeTo="log_mqtt" final="true"/>
<logger name="logsInfo" minlevel="Info" writeTo="logs_Infos" final="true"/>
<logger name="logsMEStIME" minlevel="Info" writeTo="logs_MEStIME" final="true"/>
<logger name="logsSql" minlevel="Info" writeTo="logs_Sql" final="true"/>
<logger name="logsSysErrorLog" minlevel="Info" writeTo="logs_SysErrorLog" final="true"/>
<logger name="logsSysErrorLogcn" minlevel="Info" writeTo="logs_SysErrorLogcn" final="true"/>
<logger name="*" minlevel="Info" writeTo="log_info" final="true"/>
</rules>
</nlog>
+155
View File
@@ -0,0 +1,155 @@
using JinYuan.DataConvertLib;
using PLCCommunication.PLCType.Omron;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace WindowsService1
{
/// <summary>
/// 定义每个数据读取请求的参数。
/// </summary>
public class PLCDataReadRequest
{
/// <summary>
/// PLC起始地址
/// </summary>
public string StartAddress { get; set; }
/// <summary>
/// 读取长度
/// </summary>
public ushort Length { get; set; }
/// <summary>
/// 读取区域名称
/// </summary>
public string StorageName { get; set; }
/// <summary>
/// 读取数据类型
/// </summary>
public PLCDataType DataType { get; set; }
}
/// <summary>
/// 存储每次读取操作的结果。
/// </summary>
public class PLCDataResult
{
/// <summary>
/// 读取区域名称
/// </summary>
public string StorageName { get; set; }
/// <summary>
/// 读取数据类型
/// </summary>
public PLCDataType DataType { get; set; }
/// <summary>
/// 数据
/// </summary>
public byte[] Data { get; set; }
/// <summary>
/// 是否读取成功
/// </summary>
public bool IsSuccess { get; set; }
/// <summary>
/// 读取失败的错误信息
/// </summary>
public string ErrorMessage { get; set; }
}
public class PLCDataReader
{
private readonly OmronFinsNet _plc;
public PLCDataReader(OmronFinsNet plc)
{
_plc = plc ?? throw new ArgumentNullException(nameof(plc));
}
public async Task<PLCDataResult> ReadDataAsync(PLCDataReadRequest request)
{
try
{
var data = await _plc.ReadAsync(request.StartAddress, request.Length);
if (data.IsSuccess && data.Content.Length > 0)
{
Logger.WriteInfo($"成功读取PLC数据,起始地址:{request.StartAddress},长度:{request.Length},类型:{request.DataType}");
return new PLCDataResult
{
StorageName = request.StorageName,
DataType = request.DataType,
Data = data.Content,
IsSuccess = true
};
}
else
{
Logger.WriteInfo($"读取PLC数据失败,起始地址:{request.StartAddress},长度:{request.Length},类型:{request.DataType}");
return new PLCDataResult
{
StorageName = request.StorageName,
DataType = request.DataType,
IsSuccess = false,
ErrorMessage = "读取PLC数据失败"
};
}
}
catch (Exception ex)
{
Logger.WriteError($"读取PLC数据时发生错误:{ex.Message}");
return new PLCDataResult
{
StorageName = request.StorageName,
DataType = request.DataType,
IsSuccess = false,
ErrorMessage = ex.Message
};
}
}
private object[] ParseData(byte[] content, PLCDataType dataType)
{
switch (dataType)
{
case PLCDataType.Short:
return ParseShortData(content);
case PLCDataType.Float:
return ParseFloatData(content);
default:
throw new ArgumentException($"不支持的数据类型:{dataType}");
}
}
private object[] ParseShortData(byte[] content)
{
int count = content.Length / 2;
return Enumerable.Range(0, count)
.Select(i => (object)ShortLib.GetShortFromByteArray(content, i * 2))
.ToArray();
}
private object[] ParseFloatData(byte[] content)
{
int count = content.Length / 4;
return Enumerable.Range(0, count)
.Select(i => (object)FloatLib.GetFloatFromByteArray(content, i * 4))
.ToArray();
}
}
public static class ConvertHelper
{
/// <summary>
/// 字节数组高低位转换
/// </summary>
/// <param name="Arrbyte"></param>
/// <returns></returns>
public static byte[] ByteReverse(this byte[] Arrbyte)
{
byte[] ArrByte = Arrbyte.Select((x, i) => new { x, i }).GroupBy(x => x.i / 2).SelectMany(x => new byte[] { x.Last().x, x.First().x }).ToArray();
return ArrByte;
}
}
}
+104
View File
@@ -0,0 +1,104 @@
using PLCCommunication.PLCType.Omron;
using System;
using System.Threading.Tasks;
namespace WindowsService1
{
public class PLCWrapper
{
private OmronFinsNet _plc;
public bool _plcIsConnected;
private readonly string _ipAddress;
private readonly int _port;
private readonly int _maxReconnectAttempts;
private readonly int _reconnectDelay;
public PLCDataReader _dataReader;
public PLCWrapper(string ipAddress, int port, int maxReconnectAttempts = 3, int reconnectDelay = 5000)
{
_ipAddress = ipAddress;
_port = port;
_maxReconnectAttempts = maxReconnectAttempts;
_reconnectDelay = reconnectDelay;
}
public async Task<bool> ConnectAsync()
{
try
{
_plc = new OmronFinsNet
{
IpAddress = _ipAddress,
Port = _port
};
var connectResult = await Task.Run(() => _plc.ConnectServer());
_plcIsConnected = connectResult.IsSuccess;
if (_plcIsConnected)
{
_dataReader = new PLCDataReader(GetPLCClient());
Logger.WriteInfo("PLC连接成功");
}
else
{
Logger.WriteInfo("PLC连接失败");
}
return _plcIsConnected;
}
catch (Exception ex)
{
Logger.WriteError($"PLC连接失败: {ex.Message}");
return false;
}
}
public void Disconnect()
{
if (_plcIsConnected)
{
_plc.ConnectClose();
_plcIsConnected = false;
Logger.WriteInfo("与PLC断开连接");
}
}
public OmronFinsNet GetPLCClient()
{
if (!_plcIsConnected || _plc == null)
{
throw new InvalidOperationException("PLC 未连接或未初始化。请先调用 ConnectAsync()。");
}
return _plc;
}
public async Task<bool> ReconnectAsync()
{
if (_plcIsConnected)
{
Logger.WriteInfo("PLC已连接,无需重连");
return true;
}
for (int attempt = 1; attempt <= _maxReconnectAttempts; attempt++)
{
Logger.WriteInfo($"尝试重新连接PLC,第 {attempt} 次尝试");
if (await ConnectAsync())
{
Logger.WriteInfo("PLC重新连接成功");
return true;
}
if (attempt < _maxReconnectAttempts)
{
await Task.Delay(_reconnectDelay);
}
}
Logger.WriteError($"PLC重新连接失败,已尝试 {_maxReconnectAttempts} 次");
return false;
}
public bool IsConnected()
{
return _plcIsConnected;
}
}
}
+20
View File
@@ -0,0 +1,20 @@
using System.ServiceProcess;
namespace WindowsService1
{
internal static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
}
+35
View File
@@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("WindowsService1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WindowsService1")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("242400f4-9b01-4aee-a6f7-05083757fcdd")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+38
View File
@@ -0,0 +1,38 @@
namespace WindowsService1
{
partial class Service1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
Logger.Shutdown();
}
base.Dispose(disposing);
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}
#endregion
}
}
File diff suppressed because it is too large Load Diff
+94
View File
@@ -0,0 +1,94 @@
using System;
using System.Collections.Generic;
namespace WindowsService1
{
/// <summary>
/// 判断工位耗时变化
/// </summary>
public class StationDataComparer : IEqualityComparer<StationData>
{
private const float FloatEpsilon = 0.000001f; // 可以调整精度
public bool Equals(StationData x, StationData y)
{
if (ReferenceEquals(x, y)) return true;
if (x is null || y is null) return false;
// 比较名称
if (x.Name != y.Name) return false;
// 比较主值
if (x.MainValue is float xFloat && y.MainValue is float yFloat)
{
if (Math.Abs(xFloat - yFloat) > FloatEpsilon) return false;
}
else if (x.MainValue is double xDouble && y.MainValue is double yDouble)
{
if (Math.Abs(xDouble - yDouble) > FloatEpsilon) return false;
}
else if (!Equals(x.MainValue, y.MainValue))
{
return false;
}
// 比较时间戳(可以选择是否忽略毫秒)
return Math.Abs((x.Timestamp - y.Timestamp).TotalMilliseconds) < 1;
}
public int GetHashCode(StationData obj)
{
if (obj is null) return 0;
unchecked
{
int hash = 17;
hash = hash * 23 + (obj.Name?.GetHashCode() ?? 0);
// 对于浮点数,可以先转换为整数再计算哈希
if (obj.MainValue is float f)
{
hash = hash * 23 + ((int)(f * 1000000)).GetHashCode();
}
else
{
hash = hash * 23 + (obj.MainValue?.GetHashCode() ?? 0);
}
hash = hash * 23 + obj.Timestamp.GetHashCode();
return hash;
}
}
}
/// <summary>
/// 判断时间戳变化
/// </summary>
public class StationDataComparer2 : IEqualityComparer<StationData>
{
public bool Equals(StationData x, StationData y)
{
if (ReferenceEquals(x, y)) return true;
if (x is null || y is null) return false;
// 只比较名称和时间戳
if (x.Name != y.Name) return false;
// 比较时间戳,检查是否完全相同
return x.Timestamp == y.Timestamp;
}
public int GetHashCode(StationData obj)
{
if (obj is null) return 0;
unchecked
{
int hash = 17;
hash = hash * 23 + (obj.Name?.GetHashCode() ?? 0);
hash = hash * 23 + obj.Timestamp.GetHashCode();
return hash;
}
}
}
}
+74
View File
@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Xml.Linq;
namespace WindowsService1
{
public class XmlConfigReader
{
private Dictionary<string, Dictionary<string, Dictionary<string, string>>> deviceData;
public XmlConfigReader(string xmlContent)
{
XDocument doc = XDocument.Parse(xmlContent);
deviceData = ReadXmlToNestedDictionary(doc);
}
public XmlConfigReader(XDocument doc)
{
deviceData = ReadXmlToNestedDictionary(doc);
}
private Dictionary<string, Dictionary<string, Dictionary<string, string>>> ReadXmlToNestedDictionary(XDocument doc)
{
var result = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
var mainDevice = doc.Root.Element("Device");
string mainDeviceName = mainDevice.Attribute("name").Value;
result[mainDeviceName] = new Dictionary<string, Dictionary<string, string>>();
foreach (var subDevice in mainDevice.Elements("Device"))
{
string subDeviceName = subDevice.Attribute("name").Value;
result[mainDeviceName][subDeviceName] = new Dictionary<string, string>();
foreach (var type in subDevice.Elements("Type"))
{
string typeName = type.Attribute("name").Value;
string typeValue = type.Value;
result[mainDeviceName][subDeviceName][typeName] = typeValue;
}
}
return result;
}
public void PrintStructure()
{
foreach (var mainDevice in deviceData)
{
Console.WriteLine($"Main Device: {mainDevice.Key}");
foreach (var subDevice in mainDevice.Value)
{
Console.WriteLine($" Sub Device: {subDevice.Key}");
foreach (var type in subDevice.Value)
{
Console.WriteLine($" Type: {type.Key}, Value: {type.Value}");
}
}
}
}
public bool TryGetValue(string mainDeviceName, string subDeviceName, string typeName, out string value)
{
value = null;
return deviceData.TryGetValue(mainDeviceName, out var mainDevice) &&
mainDevice.TryGetValue(subDeviceName, out var subDevice) &&
subDevice.TryGetValue(typeName, out value);
}
public Dictionary<string, Dictionary<string, Dictionary<string, string>>> GetAllData()
{
return deviceData;
}
}
}
+62
View File
@@ -0,0 +1,62 @@
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<!-- 错误日志类 -->
<logger name="logerror">
<level value="ALL" />
<appender-ref ref="ErrorAppender" />
</logger>
<!-- 信息日志类 -->
<logger name="loginfo">
<level value="ALL" />
<appender-ref ref="InfoAppender" />
</logger>
<!-- MQTT日志类 -->
<logger name="logmqtt">
<level value="ALL" />
<appender-ref ref="MqttAppender" />
</logger>
<!-- MQTT日志附加介质 -->
<appender name="MqttAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\\LogMqtt\\" />
<param name="AppendToFile" value="true" />
<param name="StaticLogFileName" value="false" />
<param name="RollingStyle" value="Composite" />
<param name="DatePattern" value="'\\\\' yyyyMMdd'\\\\log_'HH'.htm'" />
<param name="LockingModel" type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="&lt;HR COLOR=blue&gt;%n日志时间:%d [%t] &lt;BR&gt;%n日志级别:%-5p &lt;BR&gt;%n日 志 类:%c [%x] &lt;BR&gt;%n%m &lt;BR&gt;%n &lt;HR Size=1&gt;" />
</layout>
</appender>
<!-- 错误日志附加介质 -->
<appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\\LogError\\" />
<param name="AppendToFile" value="true" />
<param name="StaticLogFileName" value="false" />
<param name="RollingStyle" value="Composite" />
<param name="DatePattern" value="'\\\\' yyyyMMdd'\\\\log_'HH'.htm'" />
<param name="LockingModel" type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="&lt;HR COLOR=red&gt;%n异常时间:%d [%t] &lt;BR&gt;%n异常级别:%-5p &lt;BR&gt;%n异 常 类:%c [%x] &lt;BR&gt;%n%m &lt;BR&gt;%n &lt;HR Size=1&gt;" />
</layout>
</appender>
<!-- 信息日志附加介质 -->
<appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\\LogInfo\\" />
<param name="AppendToFile" value="true" />
<param name="StaticLogFileName" value="false" />
<param name="RollingStyle" value="Composite" />
<param name="DatePattern" value="'\\\\' yyyyMMdd'\\\\log_'HH'.htm'" />
<param name="LockingModel" type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="&lt;HR COLOR=blue&gt;%n日志时间:%d [%t] &lt;BR&gt;%n日志级别:%-5p &lt;BR&gt;%n日 志 类:%c [%x] &lt;BR&gt;%n%m &lt;BR&gt;%n &lt;HR Size=1&gt;" />
</layout>
</appender>
</log4net>
</configuration>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="NLog" version="6.0.2" targetFramework="net48" />
</packages>