添加项目文件。

This commit is contained in:
xyy
2026-01-26 20:49:59 +08:00
parent 2763a5b7fc
commit 514e8869d9
13 changed files with 1941 additions and 0 deletions

12
App.config Normal file
View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/>
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="modbusDll/NModbus4.dll;"/>
</assemblyBinding>
</runtime>
</configuration>

74
Data/DataChange.cs Normal file
View File

@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace
{
public class DataChange
{
/// <summary>
/// ushort转为float类型
/// </summary>
/// <param name="P1"></param>
/// <param name="P2"></param>
/// <returns>float型数据</returns>
public float UshortToFloat(ushort P1, ushort P2)
{
int intSign, intSignRest, intExponent, intExponentRest;
float faResult, faDigit;
intSign = P1 / 32768;
intSignRest = P1 % 32768;
intExponent = intSignRest / 128;
intExponentRest = intSignRest % 128;
faDigit = (float)(intExponentRest * 65536 + P2) / 8388608;
faResult = (float)Math.Pow(-1, intSign) * (float)Math.Pow(2, intExponent - 127) * (faDigit + 1);
return faResult;
}
/// <summary>
/// ushort转为int类型
/// </summary>
/// <param name="u1"></param>
/// <param name="u2"></param>
/// <returns>返回int型数据</returns>
public int UshortToInt1(ushort u1, ushort u2)
{
ushort[] maidong = new ushort[2] { u1, u2 };
byte[] bytes = new byte[maidong.Length * 2];
Buffer.BlockCopy(maidong, 0, bytes, 0, bytes.Length);
int result = BitConverter.ToInt32(bytes, 0);
// 将字节数组转换为32位无符号整数
return result;
}
/// <summary>
/// Float转为Ushort数组发送
/// </summary>
/// <param name="value"></param>
/// <returns>返回ushort数组</returns>
public ushort[] SplitFloatToUShortArray(float value)
{
byte[] floatBytes = BitConverter.GetBytes(value);
ushort[] ushortArray = new ushort[floatBytes.Length / 2];
for (int i = 0, j = 0; i < floatBytes.Length; i += 2, j++)
{
ushortArray[j] = BitConverter.ToUInt16(floatBytes, i);
}
return ushortArray;
}
/// <summary>
/// Int转为ushort数组发送
/// </summary>
/// <param name="res"></param>
/// <returns>返回ushort数组</returns>
public ushort[] intToushorts(int res)
{
ushort ust1 = (ushort)(res >> 16);
ushort ust2 = (ushort)res;
return new ushort[] { ust2, ust1 };
}
}
}

234
Data/Function.cs Normal file
View File

@@ -0,0 +1,234 @@
using Modbus.Device;
using Modbus;
using Sunny.UI;
using System;
using System.Threading;
using System.Windows.Forms;
namespace
{
public class Function
{
ModbusMaster master;
IModbusMaster modbusMaster;
DataChange dc = new DataChange();
public enum ButtonType
{
,
,
,
}
public enum DataType
{
,
}
public Function(ModbusMaster master_in)
{
this.master = master_in;
}
public Function(IModbusMaster modbusMaster)
{
this.modbusMaster = modbusMaster;
}
public void BtnClickFunction(ButtonType buttonType, ushort address)
{
try
{
switch (buttonType)
{
case ButtonType.:
master.WriteSingleCoil(1, address, true);
Thread.Sleep(100);
master.WriteSingleCoil(1, address, false);
Thread.Sleep(100);
break;
case ButtonType.:
if (master.ReadCoils(1, address, 1)[0])
{
master.WriteSingleCoil(1, address, false); Thread.Sleep(100);
}
else
{ master.WriteSingleCoil(1, address, true); Thread.Sleep(100); }
break;
case ButtonType.:
master.WriteSingleCoil(1, address, true);
Thread.Sleep(100);
break;
case ButtonType.:
master.WriteSingleCoil(1, address, false);
Thread.Sleep(100);
break;
default:
break;
}
}
catch (Exception ex)
{
MessageBox.Show("操作失败!" + "\n" + "\n" + ex.Message, "错误");
}
}
public void BtnClickFunctionForNew(ButtonType buttonType, ushort address)
{
try
{
switch (buttonType)
{
case ButtonType.:
modbusMaster.WriteSingleCoil(1, address, true);
Thread.Sleep(100);
modbusMaster.WriteSingleCoil(1, address, false);
Thread.Sleep(100);
break;
case ButtonType.:
if (modbusMaster.ReadCoils(1, address, 1)[0])
{
modbusMaster.WriteSingleCoil(1, address, false); Thread.Sleep(100);
}
else
{ modbusMaster.WriteSingleCoil(1, address, true); Thread.Sleep(100); }
break;
case ButtonType.:
modbusMaster.WriteSingleCoil(1, address, true);
Thread.Sleep(100);
break;
case ButtonType.:
modbusMaster.WriteSingleCoil(1, address, false);
Thread.Sleep(100);
break;
default:
break;
}
}
catch (Exception ex)
{
MessageBox.Show("操作失败!" + "\n" + "\n" + ex.Message, "错误");
}
}
public void WriteToPLC(string inPutValue, ushort address, DataType dataType)
{
try
{
switch (dataType)
{
case DataType.:
double value = inPutValue.ToDouble();
if (UIInputDialog.ShowInputDoubleDialog(ref value, UIStyle.Inherited, desc: "请输入值", showMask: false))
{
master.WriteMultipleRegisters(1, address, dc.SplitFloatToUShortArray((float)value));
}
break;
case DataType.:
int value_int = inPutValue.ToInt();
if (UIInputDialog.ShowInputIntegerDialog(ref value_int, UIStyle.Inherited, desc: "请输入数据:"))
{
master.WriteMultipleRegisters(1, address, dc.intToushorts(value_int));
}
break;
default:
break;
}
}
catch (Exception ex)
{
MessageBox.Show("操作失败!" + "\n" + "\n" + ex.Message, "错误");
}
}
public void WriteToPLCForNew(string inPutValue, ushort address, DataType dataType, bool isok=false,float max=0,float min=0)
{
try
{
//KeyboardHelper.ShowSoftKeyboard();
switch (dataType)
{
case DataType.:
double value = inPutValue.ToDouble();
if (UIInputDialog.ShowInputDoubleDialog(ref value, UIStyle.Inherited, desc: "请输入值", showMask: false))
{
if ( isok&&value > max || value < min)
{
MessageBox.Show("数据不正确");
return;
}
modbusMaster.WriteMultipleRegisters(1, address, dc.SplitFloatToUShortArray((float)value));
}
break;
case DataType.:
int value_int = inPutValue.ToInt();
if (UIInputDialog.ShowInputIntegerDialog(ref value_int, UIStyle.Inherited, desc: "请输入数据:"))
{
modbusMaster.WriteMultipleRegisters(1, address, dc.intToushorts(value_int));
//if (isok)
//{ modbusMaster.WriteSingleCoil(1, 25, true); }
}
break;
default:
break;
}
//KeyboardHelper.HideSoftKeyboard();
}
catch (Exception ex)
{
MessageBox.Show("操作失败!" + "\n" + "\n" + ex.Message, "错误");
}
}
public void WriteToPLCForNew(string inPutValue, ushort address, DataType dataType, int d)
{
try
{
//KeyboardHelper.ShowSoftKeyboard();
switch (dataType)
{
case DataType.:
double value = inPutValue.ToDouble();
if (UIInputDialog.ShowInputDoubleDialog(ref value, UIStyle.Inherited, d, desc: "请输入值", showMask: false))
{
modbusMaster.WriteMultipleRegisters(1, address, dc.SplitFloatToUShortArray((float)value));
}
break;
case DataType.:
int value_int = inPutValue.ToInt();
if (UIInputDialog.ShowInputIntegerDialog(ref value_int, UIStyle.Inherited, desc: "请输入数据:"))
{
modbusMaster.WriteMultipleRegisters(1, address, dc.intToushorts(value_int));
//if (isok)
//{ modbusMaster.WriteSingleCoil(1, 25, true); }
}
break;
default:
break;
}
//KeyboardHelper.HideSoftKeyboard();
}
catch (Exception ex)
{
MessageBox.Show("操作失败!" + "\n" + "\n" + ex.Message, "错误");
}
}
}
}

View File

@@ -0,0 +1,69 @@
using System;
using Modbus.Device;
using System.Net.Sockets;
namespace .Data
{
// 单例模式:全局唯一资源管理器
public class ModbusResourceManager
{
// 私有构造函数禁止外部new
private ModbusResourceManager() { }
// 唯一实例
private static readonly Lazy<ModbusResourceManager> _instance = new Lazy<ModbusResourceManager>(() => new ModbusResourceManager());
public static ModbusResourceManager Instance => _instance.Value;
// 共享资源
public TcpClient TcpClient { get; private set; }
public IModbusMaster ModbusMaster { get; private set; }
// 初始化资源在程序启动时调用如MainWindow加载时
public bool Init(string ip, int port)
{
try
{
// 先释放旧资源
ReleaseResource();
// 创建新连接
TcpClient = new TcpClient();
TcpClient.Connect(ip, port);
ModbusMaster = ModbusIpMaster.CreateIp(TcpClient);
return true;
}
catch (Exception ex)
{
Console.WriteLine($"资源初始化失败:{ex.Message}");
ReleaseResource();
return false;
}
}
public void Dispose()
{
try
{
ModbusMaster?.Dispose();
TcpClient?.Close();
}
catch
{
// 忽略清理时的异常
}
}
// 释放资源(统一释放,避免重复关闭)
public void ReleaseResource()
{
ModbusMaster?.Dispose();
ModbusMaster = null;
//if (TcpClient?.Connected ?? false)
//{
// TcpClient.Close();
//}
TcpClient?.Dispose();
TcpClient = null;
}
}
}

13
Data/PLC_Data.cs Normal file
View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace .Data
{
internal class PLC_Data
{
}
}

82
ModbusDemo4CS.csproj Normal file
View File

@@ -0,0 +1,82 @@
<?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>{7401784B-5723-4579-B056-A6F23EC80C9A}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>ModbusDemo4CS</RootNamespace>
<AssemblyName>ModbusDemo4CS</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</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>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="NModbus4">
<HintPath>modbusDll\NModbus4.dll</HintPath>
</Reference>
<Reference Include="SunnyUI, Version=3.9.1.0, Culture=neutral, PublicKeyToken=3f4ebed4237db5e1, processorArchitecture=MSIL">
<HintPath>packages\SunnyUI.3.9.1\lib\net472\SunnyUI.dll</HintPath>
</Reference>
<Reference Include="SunnyUI.Common, Version=3.9.1.0, Culture=neutral, PublicKeyToken=3f4ebed4237db5e1, processorArchitecture=MSIL">
<HintPath>packages\SunnyUI.Common.3.9.1\lib\net472\SunnyUI.Common.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Design" />
<Reference Include="System.Drawing" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Windows.Forms" />
<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.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Data\DataChange.cs" />
<Compile Include="Data\Function.cs" />
<Compile Include="Data\ModbusResourceManager.cs" />
<Compile Include="Data\PLC_Data.cs" />
<Compile Include="Program.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Program.resx">
<DependentUpon>Program.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

BIN
ModbusDemo4CS.rar Normal file

Binary file not shown.

25
ModbusDemo4CS.sln Normal file
View File

@@ -0,0 +1,25 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.33328.57
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModbusDemo4CS", "ModbusDemo4CS.csproj", "{7401784B-5723-4579-B056-A6F23EC80C9A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7401784B-5723-4579-B056-A6F23EC80C9A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7401784B-5723-4579-B056-A6F23EC80C9A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7401784B-5723-4579-B056-A6F23EC80C9A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7401784B-5723-4579-B056-A6F23EC80C9A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4466B61D-22CF-464B-9262-15854D7702F4}
EndGlobalSection
EndGlobal

1271
Program.cs Normal file

File diff suppressed because it is too large Load Diff

120
Program.resx Normal file
View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("P_RTU_TEST")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("P_RTU_TEST")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("7401784b-5723-4579-b056-a6f23ec80c9a")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

BIN
modbusDll/NModbus4.dll Normal file

Binary file not shown.

5
packages.config Normal file
View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="SunnyUI" version="3.9.1" targetFramework="net48" />
<package id="SunnyUI.Common" version="3.9.1" targetFramework="net48" />
</packages>