Commit 0bbb9e7b authored by leon.huang's avatar leon.huang

add channel communication fail times

parent 051dba9a
This diff is collapsed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text.RegularExpressions;
using System.Collections;
using System.Management;
using System.Net.NetworkInformation;
namespace ModbusDemo.Common
{
class ModSearch
{
public struct DeviceInfo
{
public string ModuleName;
public string MacAddr;
public string IpAddr;
public string Netmask;
public string Gateway;
public bool bActive;
};
public UdpClient client;
public IPEndPoint endpoint;
Thread searchth;
ManualResetEvent mre = new ManualResetEvent(false);
public DeviceInfo m_DeviceInfo;
public ArrayList myHMIList = new ArrayList();
string FMAC =null;
string localip = null;
/// <summary>
/// 构造函数
/// </summary>
public ModSearch()
{
myHMIList.Clear();
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
if (adapter.Name == "本地连接") //这里是为了匹配我自己电脑网卡
{
bool Pd1 = (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet); //判断是否是以太网连接
if (Pd1)
{
{
IPInterfaceProperties ip = adapter.GetIPProperties(); //IP配置信息
UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
foreach (UnicastIPAddressInformation ipadd in ipCollection)
{
if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork)
this.localip = ipadd.Address.ToString();//获取ip
}
}
}
}
}
}
public void ThStart()
{
if (mre != null)
mre.Reset();
Console.WriteLine("搜索线程开始....");
searchth = new Thread(ThreadMethod);
searchth.IsBackground = true;
searchth.Start();
}
public void ThStop()
{
Console.WriteLine("搜索线程结束....");
mre.Set();
}
public int HMICount()
{
return myHMIList.Count;
}
private void ThreadMethod()
{
byte[] sendBytes = new byte[] { 0x57, 0x54, 0x04, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x55, 0xAA };
int iReadBytes = 0;
try
{
client = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
// client = new UdpClient(new IPEndPoint(IPAddress.Parse(this.localip), 0));
endpoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 5048);
client.Send(sendBytes, sendBytes.Length, endpoint);
Thread.Sleep(500);
byte[] recvBytes;
client.Client.Blocking = false;
while (!mre.WaitOne(500))
{
iReadBytes = 30;
int buffSizeCurrent;
buffSizeCurrent = client.Client.Available;
if (buffSizeCurrent > 0)
{
recvBytes = client.Receive(ref endpoint);
iReadBytes = recvBytes.Length;
DoRecvDataCallBack(recvBytes, iReadBytes);
}
}
}catch
{
}
}
public Boolean DoRecvDataCallBack(byte[] pcData, int iRecvLength)
{
int i;
int count = 0;
byte[] pBuf = pcData;
int iDataLength = 0;
if (iRecvLength < 8)
return false;
if ((pBuf[0] == (byte)0x57) && (pBuf[1] == (byte)0x54) && (pBuf[iRecvLength - 2] == (byte)0x55) && (pBuf[iRecvLength - 1] == (byte)0xAA))
{
iDataLength = (int)(pBuf[2] & 0xFF)
| (int)((pBuf[3] & 0xFF) << 8)
| (int)((pBuf[4] & 0xFF) << 16)
| (int)((pBuf[5] & 0xFF) << 24);
if ((iDataLength >= 4) && (iRecvLength == 8 + iDataLength))
{
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
m_DeviceInfo.bActive = false;
for (i = 0; i < 100; i++ )
{
if (asciiEncoding.GetString(pBuf, 6 + i, 1) == "\0")
break;
count++;
}
// m_DeviceInfo.ModuleName = String.Format("{0}", asciiEncoding.GetString(pBuf, 6, count));
//脱机
m_DeviceInfo.ModuleName = String.Format("{0}{1}{2}{3}", asciiEncoding.GetString(pBuf, 6, 1),
asciiEncoding.GetString(pBuf, 7, 1),
asciiEncoding.GetString(pBuf, 8, 1),
asciiEncoding.GetString(pBuf, 9, 1));
m_DeviceInfo.MacAddr = String.Format("{0}:{1}:{2}:{3}:{4}:{5}", pBuf[10], pBuf[11], pBuf[12], pBuf[13], pBuf[14], pBuf[15]);
m_DeviceInfo.IpAddr = String.Format("{0}.{1}.{2}.{3}", pBuf[16], pBuf[17], pBuf[18], pBuf[19]);
m_DeviceInfo.Netmask = String.Format("{0}.{1}.{2}.{3}", pBuf[20], pBuf[21], pBuf[22], pBuf[23]);
m_DeviceInfo.Gateway = String.Format("{0}.{1}.{2}.{3}", pBuf[24], pBuf[25], pBuf[26], pBuf[27]);
if (m_DeviceInfo.IpAddr != "0.0.0.0")
{
myHMIList.Add(m_DeviceInfo);
}
return true;
}
}
return false;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ModbusDemo.Common
{
class WTModbus
{
[DllImport(@"LibModbus.dll", EntryPoint = "fnLibModbus", CharSet = CharSet.Unicode)]
public static extern uint fnLibModbus();
[DllImport(@"LibModbus.dll", EntryPoint = "fnReadCoilStatus")]
public static extern int fnReadCoilStatus(uint handle, ushort address, ushort num, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] System.Byte[] dest, byte[] Ip, ushort wTcpPort);
[DllImport(@"LibModbus.dll", EntryPoint = "fnReadInputStatus")]
public static extern int fnReadInputStatus(uint handle, ushort address, ushort num, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] System.Char[] dest, byte[] Ip, ushort wTcpPort);
[DllImport(@"LibModbus.dll", EntryPoint = "fnReadHoldingReg")]
public static extern int fnReadHoldingReg(uint handle, ushort address, ushort num, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] System.UInt16[] dest, byte[] Ip, ushort wTcpPort);
[DllImport(@"LibModbus.dll", EntryPoint = "fnReadInputReg")]
public static extern int fnReadInputReg(uint handle, ushort address, ushort num, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] System.UInt16[] dest, byte[] Ip, ushort wTcpPort);
[DllImport(@"LibModbus.dll", EntryPoint = "fnWriteSingleCoil")]
public static extern int fnWriteSingleCoil(uint handle, ushort address, ushort state, byte[] Ip, ushort wTcpPort);
[DllImport(@"LibModbus.dll", EntryPoint = "fnWriteHoldingReg")]
public static extern int fnWriteHoldingReg(uint handle, ushort address, ushort state, byte[] Ip, ushort wTcpPort);
[DllImport(@"LibModbus.dll", EntryPoint = "fnWriteMultipleCoils")]
public static extern int fnWriteMultipleCoils(uint handle, ushort address, ushort num, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] System.Char[] src, byte[] Ip, ushort wTcpPort);
[DllImport(@"LibModbus.dll", EntryPoint = "fnWriteMultipleRegs")]
public static extern int fnWriteMultipleRegs(uint handle, ushort address, ushort num, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] System.UInt16[] src, byte[] Ip, ushort wTcpPort);
[DllImport(@"LibModbus.dll", EntryPoint = "fnReportSlaveID")]
public static extern int fnReportSlaveID(uint handle, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] System.Char[] src, byte[] Ip, ushort wTcpPort);
[DllImport(@"LibModbus.dll", EntryPoint = "fnMaskWriteReg")]
public static extern int fnMaskWriteReg(uint handle, ushort address, ushort amask, ushort omask, byte[] Ip, ushort wTcpPort);
[DllImport(@"LibModbus.dll", EntryPoint = "fnReadWriteMultipleRegs")]
public static extern int fnReadWriteMultipleRegs(uint handle, ushort waddress, ushort wnum, ushort raddress, ushort rnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] System.UInt16[] dest, byte[] Ip, ushort wTcpPort);
[DllImport(@"LibModbus.dll", EntryPoint = "fnLibModbusClose")]
public static extern void fnLibModbusClose(uint handle);
private uint hModbusHandle;
private System.UInt16[] dest = new System.UInt16[10] { 0, 0, 3, 4, 5, 6, 7, 8, 9, 0 };
public WTModbus()
{
this.hModbusHandle = fnLibModbus();
}
~WTModbus()
{
fnLibModbusClose(hModbusHandle);
}
/// <summary>
/// 读线圈状态
/// </summary>
/// <param name="addr">地址</param>
/// <param name="num">线圈数目</param>
/// <param name="ip">设备IP</param>
/// <param name="wport">端口号 默认502</param>
/// <param name="buf">读取结果</param>
/// <returns>
/// 0 -- no error
/// 1 -- illegal register address.
/// 2 -- illegal argument
/// 3 -- porting layer error
/// 4 -- insufficient resources
/// 5 -- I/O error
/// 6 -- protocol stack in illegal state
/// 7 -- timeout error occurred
/// 8 -- slave address error
/// 9 -- exception error occurred
/// 10-- CRC check error
/// 11-- send data error
/// 12-- receive data error
/// 13-- TCP connect error
/// 14-- close error
/// </returns>
public int ReadCoilStatus(ushort addr, ushort num, String ip, ushort wport, ref byte[] buf)
{
int ret;
byte[] bIp = Encoding.Unicode.GetBytes(ip);
ret = fnReadCoilStatus(hModbusHandle, (ushort)(addr - 1), num, buf, bIp, wport);
return ret;
}
public int ReadInputStatus(ushort addr, ushort num, String ip, ushort wport, ref char[] buf)
{
int ret;
byte[] bIp = Encoding.Unicode.GetBytes(ip);
ret = fnReadInputStatus(hModbusHandle, (ushort)(addr - 1), 1, buf, bIp, 502);
return ret;
}
public int ReadHoldingReg(ushort addr, ushort num, String ip, ushort wport, ref UInt16[] buf)
{
int ret;
byte[] bIp = Encoding.Unicode.GetBytes(ip);
ret = fnReadHoldingReg(hModbusHandle, (ushort)(addr - 1), num, buf, bIp, wport);
return ret;
}
public int ReadInputReg(ushort addr, ushort num, String ip, ushort wport, ref UInt16[] buf)
{
int ret;
byte[] bIp = Encoding.Unicode.GetBytes(ip);
ret = fnReadInputReg(hModbusHandle, (ushort)(addr - 1), 1, dest, bIp, wport);
buf[0] = dest[0];
return ret;
}
public int WriteSingleCoil(ushort addr, ushort state, String ip, ushort wport)
{
int ret = 0;
byte[] bIp = Encoding.Unicode.GetBytes(ip);
ret = fnWriteSingleCoil(hModbusHandle, (ushort)(addr - 1), state, bIp, wport);
return ret;
}
public int WriteHoldingReg(ushort addr, ushort state, String ip, ushort wport)
{
int ret = 0;
byte[] bIp = Encoding.Unicode.GetBytes(ip);
ret = fnWriteHoldingReg(hModbusHandle, (ushort)(addr - 1), state, bIp, wport);
return ret;
}
public int ReadHoldingReg(ushort addr, ushort num, String ip, ushort wport, ref char[] buf)
{
int ret;
byte[] bIp = Encoding.Unicode.GetBytes(ip);
ret = fnWriteMultipleCoils(hModbusHandle, (ushort)(addr - 1), 1, buf, bIp, wport);
return ret;
}
public int WriteMultipleRegs(ushort addr, ushort num, String ip, ushort wport, ref ushort[] buf)
{
int ret;
byte[] bIp = Encoding.Unicode.GetBytes(ip);
ret = fnWriteMultipleRegs(hModbusHandle, (ushort)(addr - 1), num, buf, bIp, wport);
return ret;
}
public int ReportSlaveID(ushort addr, ushort num, String ip, ushort wport, ref char[] buf)
{
int ret;
byte[] bIp = Encoding.Unicode.GetBytes(ip);
ret = fnReportSlaveID(hModbusHandle, buf, bIp, 502);
return ret;
}
public int MaskWriteReg(ushort addr, ushort amask, ushort omask, String ip, ushort wport)
{
int ret = 0;
byte[] bIp = Encoding.Unicode.GetBytes(ip);
ret = fnMaskWriteReg(hModbusHandle, (ushort)(addr - 1), amask, omask, bIp, wport);
return ret;
}
public int ReadWriteMultipleRegs(ushort waddr, ushort wnum, ushort raddr, ushort rnum, String ip, ushort wport, ref UInt16[] buf)
{
int ret = 0;
byte[] bIp = Encoding.Unicode.GetBytes(ip);
ret = fnReadWriteMultipleRegs(hModbusHandle, (ushort)(waddr - 1), wnum, raddr, rnum, buf, bIp, wnum);
return ret;
}
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ModbusDemo.Common;
using System.Threading;
using System.Text.RegularExpressions;
namespace ModbusDemo
{
public partial class MDemo : Form
{
WTModbus ReadTest;
const ushort address = 17;
const ushort num = 6;
const ushort DevicePort = 502;
string DeviceIP;
ManualResetEvent showmre = new ManualResetEvent(false);
public delegate void invokeDelegate();
public MDemo()
{
InitializeComponent();
ReadTest = new WTModbus();
}
Thread t_ReadCoil;
private void TestBtn_Click(object sender, EventArgs e)
{
this.TestBtn.Enabled = false;
if (this.IPsetBox.Text != "")
{
DeviceIP = this.IPsetBox.Text;
}
else
{
MessageBox.Show("请检查IP输入是否正确");
this.TestBtn.Enabled = true;
return;
}
if (showmre != null)
{
showmre.Reset();
}
t_ReadCoil = new Thread(ReadCoilProc);
t_ReadCoil.IsBackground = true;
t_ReadCoil.Start();
}
private void ReadCoilProc(object obj)
{
short allval;
byte[] temp = new byte[6];
int ret;
while (!showmre.WaitOne(500))
{
//读线圈
ret = ReadTest.ReadCoilStatus(address, num, DeviceIP, DevicePort, ref temp);
allval = BitConverter.ToInt16(temp, 0);
invokeDelegate update = () =>
{
foreach (Control control in this.CoilBox.Controls)
{
if(control is PictureBox)
{
if ((allval >> Convert.ToUInt16((control as PictureBox).Tag) & 0x1) == 1)
{
(control as PictureBox).BackColor = Color.Green;
}
else
{
(control as PictureBox).BackColor = Color.Black;
}
}
}
};
Invoke(update);
}
}
private void stopbtn_Click(object sender, EventArgs e)
{
this.TestBtn.Enabled = true;
if (showmre != null)
showmre.Set();
foreach (Control control in this.CoilBox.Controls)
{
if (control is PictureBox)
{
(control as PictureBox).BackColor = Color.Black;
}
}
}
}
}
<?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>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" 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>{7D83EE1F-F3D9-4592-A0ED-A0D92DCF91AB}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ModbusDemo</RootNamespace>
<AssemblyName>ModbusDemo</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>x86</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="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Common\ModSearch.cs" />
<Compile Include="Common\WTModbus.cs" />
<Compile Include="Demo_818X.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Demo_818X.Designer.cs">
<DependentUpon>Demo_818X.cs</DependentUpon>
</Compile>
<Compile Include="MDemo.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="MDemo.Designer.cs">
<DependentUpon>MDemo.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ProTest.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="ProTest.Designer.cs">
<DependentUpon>ProTest.cs</DependentUpon>
</Compile>
<EmbeddedResource Include="Demo_818X.resx">
<DependentUpon>Demo_818X.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="MDemo.resx">
<DependentUpon>MDemo.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<EmbeddedResource Include="ProTest.resx">
<DependentUpon>ProTest.cs</DependentUpon>
</EmbeddedResource>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<Folder Include="Lib\" />
</ItemGroup>
<ItemGroup>
<None Include="Resources\057.png" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
This diff is collapsed.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ModbusDemo.Common;
using System.Threading;
using System.Text.RegularExpressions;
namespace ModbusDemo
{
public partial class ProTest : Form
{
WTModbus ReadTest;
// WTModbus TenReadTest; // = new WTModbus[10];
const ushort address = 1;
const ushort num = 16;
const ushort DevicePort = 502;
string DeviceIP = "192.168.1.57";
ManualResetEvent showmre = new ManualResetEvent(false);
public delegate void invokeDelegate();
//Ten module
string [] TenDeviceIP = new string[10];
public ProTest()
{
InitializeComponent();
setTenIP();
}
private void setTenIP()
{
TenDeviceIP[0] = "192.168.102";
TenDeviceIP[1] = "192.168.113";
TenDeviceIP[2] = "192.168.112";
TenDeviceIP[3] = "192.168.109";
TenDeviceIP[4] = "192.168.110";
TenDeviceIP[5] = "192.168.103";
TenDeviceIP[6] = "192.168.111";
TenDeviceIP[7] = "192.168.107";
TenDeviceIP[8] = "192.168.104";
TenDeviceIP[9] = "192.168.106";
}
Boolean hwstartuse = false;
Thread t_ReadCoil;
bool closethread = false;
private void hwstart_Click(object sender, EventArgs e)
{
if(!hwstartuse)
{
hwstartuse = !hwstartuse;
this.hwstart.Text = "停止";
t_ReadCoil = new Thread(ReadCoilProc);
t_ReadCoil.IsBackground = true;
t_ReadCoil.Start();
closethread = false;
}else
{
hwstartuse = !hwstartuse;
this.hwstart.Text = "开始";
closethread = true;
}
}
private void ReadCoilProc(object obj)
{
short allval;
int readcount = 0;
int failcount = 0;
byte[] temp = new byte[2];
int ret;
ReadTest = new WTModbus();
int starttime = System.Environment.TickCount;
while (true)
{
//读线圈
ret = ReadTest.ReadCoilStatus(address, num, DeviceIP, DevicePort, ref temp);
// allval = BitConverter.ToInt16(temp, 0);
if(ret == 0)
{
readcount++;
}else
{
failcount++;
}
invokeDelegate update = () =>
{
this.label2.Text = readcount.ToString() + "次";
this.label9.Text = failcount.ToString() + "次";
this.label4.Text = (System.Environment.TickCount - starttime).ToString() + "ms";
};
Invoke(update);
if (closethread)
{
break;
}
}
}
bool []tenclosethread = new bool[10];
WTModbus[]TReadTest = new WTModbus[10];
private void eReadCoilProc(object obj)
{
//WTModbus TReadTest;
int readcount = 0;
int failcount = 0;
byte[] temp = new byte[2];
int ret;
int thnum = 0;
thnum = int.Parse(obj.ToString());
this.TReadTest[thnum] = new WTModbus();
int starttime = System.Environment.TickCount;
while (true)
{
//读线圈
ret = TReadTest[thnum].ReadCoilStatus(address, num, TenDeviceIP[thnum], DevicePort, ref temp);
if (ret == 0)
{
readcount++;
}
else
{
failcount++;
}
invokeDelegate update = () =>
{
foreach(Control c in groupBox3.Controls)
{
if(c is Label)
{
if(c.Name == ("label1" + thnum.ToString()) )
c.Text = readcount.ToString() + "次";
if(c.Name == ("label2" + thnum.ToString()))
c.Text = (System.Environment.TickCount - starttime).ToString() + "ms";
}
}
};
Invoke(update);
if (tenclosethread[thnum])
{
break;
}
}
}
private void sfstart_Click(object sender, EventArgs e)
{
}
Thread []ten_ReadCoil = new Thread[10];
private void tenthrun_Click(object sender, EventArgs e)
{
int i = 0;
if (!hwstartuse)
{
hwstartuse = !hwstartuse;
this.tenthrun.Text = "停止";
for (i = 0; i < 10; i++ )
{
tenclosethread[i] = false;
ten_ReadCoil[i] = new Thread(new ParameterizedThreadStart(eReadCoilProc));
ten_ReadCoil[i].IsBackground = true;
ten_ReadCoil[i].Start(i.ToString());
}
}
else
{
hwstartuse = !hwstartuse;
for (i = 0; i < 10; i++)
{
tenclosethread[i] = true;
}
this.tenthrun.Text = "10线程测试";
}
}
private void onethrun_Click(object sender, EventArgs e)
{
if (!hwstartuse)
{
hwstartuse = !hwstartuse;
this.onethrun.Text = "停止";
t_ReadCoil = new Thread(oneReadCoilProc);
t_ReadCoil.IsBackground = true;
t_ReadCoil.Start();
closethread = false;
}
else
{
hwstartuse = !hwstartuse;
this.onethrun.Text = "单一线程测试";
closethread = true;
}
}
WTModbus[] TenReadTest = new WTModbus[10];
private void oneReadCoilProc(object obj)
{
int []readcount = new int[10];
int []failcount = new int[10];
byte[]temp = new byte[2];
int []ret = new int[10];
int i = 0;
int []tenstatrttime = new int[10];
for (i = 0; i < 10; i++)
{
TenReadTest[i] = new WTModbus();
}
for (i = 0; i < 10; i++)
{
tenstatrttime[i] = System.Environment.TickCount;
}
while (true)
{
//读线圈
for (i = 0; i < 10; i++ )
{
ret[i] = TenReadTest[i].ReadCoilStatus(address, num, TenDeviceIP[i], DevicePort, ref temp);
if (ret[i] == 0)
{
readcount[i]++;
}
else
{
failcount[i]++;
}
invokeDelegate update = () =>
{
foreach (Control c in groupBox3.Controls)
{
if (c is Label)
{
if (c.Name == ("label1" + i.ToString()))
c.Text = readcount[i].ToString() + "次";
if (c.Name == ("label2" + i.ToString()))
c.Text = (System.Environment.TickCount - tenstatrttime[i]).ToString() + "ms";
}
}
};
Invoke(update);
}
if (closethread)
{
break;
}
}
}
}
}
<?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>
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace ModbusDemo
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Demo_818X());
//Application.Run(new ProTest());
//Application.Run(new MDemo());
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("ModbusDemo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ModbusDemo")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("61938d34-0efc-49d0-ac79-236cb9be43d2")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace ModbusDemo.Properties {
using System;
/// <summary>
/// 一个强类型的资源类,用于查找本地化的字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// 返回此类使用的缓存的 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ModbusDemo.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 使用此强类型资源类,为所有资源查找
/// 重写当前线程的 CurrentUICulture 属性。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap _057 {
get {
object obj = ResourceManager.GetObject("057", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
<?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>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="057" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\057.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>
\ No newline at end of file
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18408
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ModbusDemo.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
...@@ -36,7 +36,7 @@ namespace ModbusDemo.Modular ...@@ -36,7 +36,7 @@ namespace ModbusDemo.Modular
#if DEBUG_TEST #if DEBUG_TEST
public const byte byX18xNumber = 1; public const byte byX18xNumber = 1;
public static byte[] byX18xIdlist = {13}; public static byte[] byX18xIdlist = {13};
private static modual.eX18xSensorChannelType[,] sX18xChannelType = new modual.eX18xSensorChannelType[byX18xNumber, byX18xReadDataNumber] { { modual.eX18xSensorChannelType.Mike_5, modual.eX18xSensorChannelType.Null, modual.eX18xSensorChannelType.Null, modual.eX18xSensorChannelType.Null, modual.eX18xSensorChannelType.Null, modual.eX18xSensorChannelType.Null, modual.eX18xSensorChannelType.Null, modual.eX18xSensorChannelType.Null }}; private static modual.eX18xSensorChannelType[,] sX18xChannelType = new modual.eX18xSensorChannelType[byX18xNumber, byX18xReadDataNumber] { { modual.eX18xSensorChannelType.Mike_6, modual.eX18xSensorChannelType.Null, modual.eX18xSensorChannelType.Null, modual.eX18xSensorChannelType.Null, modual.eX18xSensorChannelType.Null, modual.eX18xSensorChannelType.Null, modual.eX18xSensorChannelType.Null, modual.eX18xSensorChannelType.Null }};
#else #else
public const byte byX18xNumber = 6; public const byte byX18xNumber = 6;
public static byte[] byX18xIdlist = {3,53,6,12,21,25}; public static byte[] byX18xIdlist = {3,53,6,12,21,25};
...@@ -81,7 +81,7 @@ namespace ModbusDemo.Modular ...@@ -81,7 +81,7 @@ namespace ModbusDemo.Modular
public const byte byX66cRelayRegNumber = 6; public const byte byX66cRelayRegNumber = 6;
public static modual.pcx66C cx66c = new modual.pcx66C(byX66cIdlist); public static modual.pcx66C cx66c = new modual.pcx66C(byX66cIdlist);
public const byte COMMFAILALARM = 3;
public static void vAllNodePoll() public static void vAllNodePoll()
{ {
for (byte i = 0; i < byX14pNumber; i++) for (byte i = 0; i < byX14pNumber; i++)
...@@ -95,7 +95,8 @@ namespace ModbusDemo.Modular ...@@ -95,7 +95,8 @@ namespace ModbusDemo.Modular
{ {
for (byte j = 0; j < byX14pReadTypeNumber; j++) for (byte j = 0; j < byX14pReadTypeNumber; j++)
{ {
cx14P.sX14PAlarmStruct[i].usNowAlarmCode[j] = (ushort)ModualAlarm.eAlarmCode.ChannelCommunError; cx14P.sX14PAlarmStruct[i].usNowAlarmCode[j] |= (ushort)ModualAlarm.eAlarmCode.ChannelCommunError;
cx14P.sX14PAlarmStruct[i].usCommFailTimes[j]++;
} }
} }
else else
...@@ -103,6 +104,7 @@ namespace ModbusDemo.Modular ...@@ -103,6 +104,7 @@ namespace ModbusDemo.Modular
for (byte j = 0; j < byX14pReadTypeNumber; j++) for (byte j = 0; j < byX14pReadTypeNumber; j++)
{ {
cx14P.sX14PAlarmStruct[i].usNowAlarmCode[j] &= (ushort)~ModualAlarm.eAlarmCode.ChannelCommunError; cx14P.sX14PAlarmStruct[i].usNowAlarmCode[j] &= (ushort)~ModualAlarm.eAlarmCode.ChannelCommunError;
cx14P.sX14PAlarmStruct[i].usCommFailTimes[j] = 0;
} }
} }
for (byte j = 0; j < byX14pReadTypeNumber; j++) for (byte j = 0; j < byX14pReadTypeNumber; j++)
...@@ -160,6 +162,7 @@ namespace ModbusDemo.Modular ...@@ -160,6 +162,7 @@ namespace ModbusDemo.Modular
for (sbyte j = 0; j < byX18xReadTypeNumber; j++) for (sbyte j = 0; j < byX18xReadTypeNumber; j++)
{ {
cx18x.sX18xAlarmstruct[i].usNowAlarmCode[j] |= (ushort)ModualAlarm.eAlarmCode.ChannelCommunError; cx18x.sX18xAlarmstruct[i].usNowAlarmCode[j] |= (ushort)ModualAlarm.eAlarmCode.ChannelCommunError;
cx18x.sX18xAlarmstruct[i].usCommFailTimes[j]++;
} }
} }
else else
...@@ -167,6 +170,7 @@ namespace ModbusDemo.Modular ...@@ -167,6 +170,7 @@ namespace ModbusDemo.Modular
for (sbyte j = 0; j < byX18xReadTypeNumber; j++) for (sbyte j = 0; j < byX18xReadTypeNumber; j++)
{ {
cx18x.sX18xAlarmstruct[i].usNowAlarmCode[j] &= (ushort)~ModualAlarm.eAlarmCode.ChannelCommunError; cx18x.sX18xAlarmstruct[i].usNowAlarmCode[j] &= (ushort)~ModualAlarm.eAlarmCode.ChannelCommunError;
cx18x.sX18xAlarmstruct[i].usCommFailTimes[j] = 0;
} }
} }
for (byte j = 0; j < byX18xReadTypeNumber ; j++) for (byte j = 0; j < byX18xReadTypeNumber ; j++)
...@@ -234,6 +238,7 @@ namespace ModbusDemo.Modular ...@@ -234,6 +238,7 @@ namespace ModbusDemo.Modular
for (sbyte j = 0; j < byX78cInputRegNumber + byX78cOutputRegNumber; j++) for (sbyte j = 0; j < byX78cInputRegNumber + byX78cOutputRegNumber; j++)
{ {
cx78c.sX78cAlarmStruct[i].usNowAlarmCode[j] |= (ushort)ModualAlarm.eAlarmCode.ChannelCommunError; cx78c.sX78cAlarmStruct[i].usNowAlarmCode[j] |= (ushort)ModualAlarm.eAlarmCode.ChannelCommunError;
cx78c.sX78cAlarmStruct[i].usCommFailTimes[j] ++;
} }
} }
else else
...@@ -241,6 +246,7 @@ namespace ModbusDemo.Modular ...@@ -241,6 +246,7 @@ namespace ModbusDemo.Modular
for (sbyte j = 0; j < byX78cInputRegNumber + byX78cOutputRegNumber; j++) for (sbyte j = 0; j < byX78cInputRegNumber + byX78cOutputRegNumber; j++)
{ {
cx78c.sX78cAlarmStruct[i].usNowAlarmCode[j] &= (ushort)~ModualAlarm.eAlarmCode.ChannelCommunError; cx78c.sX78cAlarmStruct[i].usNowAlarmCode[j] &= (ushort)~ModualAlarm.eAlarmCode.ChannelCommunError;
cx78c.sX78cAlarmStruct[i].usCommFailTimes[j] = 0;
} }
} }
} }
...@@ -254,6 +260,7 @@ namespace ModbusDemo.Modular ...@@ -254,6 +260,7 @@ namespace ModbusDemo.Modular
for (sbyte j = 0; j < byX66cRelayRegNumber; j++) for (sbyte j = 0; j < byX66cRelayRegNumber; j++)
{ {
cx66c.sX66cAlarmStruct[i].usNowAlarmCode[j] |= (ushort)ModualAlarm.eAlarmCode.ChannelCommunError; cx66c.sX66cAlarmStruct[i].usNowAlarmCode[j] |= (ushort)ModualAlarm.eAlarmCode.ChannelCommunError;
cx66c.sX66cAlarmStruct[i].usCommFailTimes[j] ++;
} }
} }
else else
...@@ -261,6 +268,7 @@ namespace ModbusDemo.Modular ...@@ -261,6 +268,7 @@ namespace ModbusDemo.Modular
for (sbyte j = 0; j < byX66cRelayRegNumber; j++) for (sbyte j = 0; j < byX66cRelayRegNumber; j++)
{ {
cx66c.sX66cAlarmStruct[i].usNowAlarmCode[j] &= (ushort)~ModualAlarm.eAlarmCode.ChannelCommunError; cx66c.sX66cAlarmStruct[i].usNowAlarmCode[j] &= (ushort)~ModualAlarm.eAlarmCode.ChannelCommunError;
cx66c.sX66cAlarmStruct[i].usCommFailTimes[j] = 0;
} }
} }
} }
...@@ -320,6 +328,10 @@ namespace ModbusDemo.Modular ...@@ -320,6 +328,10 @@ namespace ModbusDemo.Modular
List<ushort> usChannelErrorCodeList = new List<ushort>(); List<ushort> usChannelErrorCodeList = new List<ushort>();
for (byte j = 0; j < byX14pReadDataNumber; j++) for (byte j = 0; j < byX14pReadDataNumber; j++)
{ {
if ((cx14P.sX14PAlarmStruct[i].usNowAlarmCode[j] & (ushort)ModualAlarm.eAlarmCode.ChannelCommunError) == (ushort)ModualAlarm.eAlarmCode.ChannelCommunError && cx14P.sX14PAlarmStruct[i].usCommFailTimes[j] < COMMFAILALARM)
{
cx14P.sX14PAlarmStruct[i].usNowAlarmCode[j] &= (ushort)~ModualAlarm.eAlarmCode.ChannelCommunError;
}
if (cx14P.sX14PAlarmStruct[i].usNowAlarmCode[j] != cx14P.sX14PAlarmStruct[i].usBeforeAlarmCode[j]) if (cx14P.sX14PAlarmStruct[i].usNowAlarmCode[j] != cx14P.sX14PAlarmStruct[i].usBeforeAlarmCode[j])
{ {
bOccurErrorChange = true; bOccurErrorChange = true;
...@@ -343,6 +355,10 @@ namespace ModbusDemo.Modular ...@@ -343,6 +355,10 @@ namespace ModbusDemo.Modular
List<ushort> usChannelErrorCodeList = new List<ushort>(); List<ushort> usChannelErrorCodeList = new List<ushort>();
for (byte j = 0; j < byX18xReadTypeNumber; j++) for (byte j = 0; j < byX18xReadTypeNumber; j++)
{ {
if ((cx18x.sX18xAlarmstruct[i].usNowAlarmCode[j] & (ushort)ModualAlarm.eAlarmCode.ChannelCommunError) == (ushort)ModualAlarm.eAlarmCode.ChannelCommunError && cx18x.sX18xAlarmstruct[i].usCommFailTimes[j] < COMMFAILALARM)
{
cx18x.sX18xAlarmstruct[i].usNowAlarmCode[j] &= (ushort)~ModualAlarm.eAlarmCode.ChannelCommunError;
}
if (cx18x.sX18xAlarmstruct[i].usNowAlarmCode[j] != cx18x.sX18xAlarmstruct[i].usBeforeAlarmCode[j]) if (cx18x.sX18xAlarmstruct[i].usNowAlarmCode[j] != cx18x.sX18xAlarmstruct[i].usBeforeAlarmCode[j])
{ {
bX18xError = true; bX18xError = true;
...@@ -367,6 +383,10 @@ namespace ModbusDemo.Modular ...@@ -367,6 +383,10 @@ namespace ModbusDemo.Modular
List<ushort> usChannelErrorCodeList = new List<ushort>(); List<ushort> usChannelErrorCodeList = new List<ushort>();
for (byte j = 0; j < byX78cOutputRegNumber + byX78cInputRegNumber; j++) for (byte j = 0; j < byX78cOutputRegNumber + byX78cInputRegNumber; j++)
{ {
if ((cx78c.sX78cAlarmStruct[i].usNowAlarmCode[j] & (ushort)ModualAlarm.eAlarmCode.ChannelCommunError) == (ushort)ModualAlarm.eAlarmCode.ChannelCommunError && cx78c.sX78cAlarmStruct[i].usCommFailTimes[j] < COMMFAILALARM)
{
cx78c.sX78cAlarmStruct[i].usNowAlarmCode[j] &= (ushort)~ModualAlarm.eAlarmCode.ChannelCommunError;
}
if (cx78c.sX78cAlarmStruct[i].usNowAlarmCode[j] != cx78c.sX78cAlarmStruct[i].usBeforeAlarmCode[j]) if (cx78c.sX78cAlarmStruct[i].usNowAlarmCode[j] != cx78c.sX78cAlarmStruct[i].usBeforeAlarmCode[j])
{ {
bOccurErrorChange = true; bOccurErrorChange = true;
...@@ -391,6 +411,10 @@ namespace ModbusDemo.Modular ...@@ -391,6 +411,10 @@ namespace ModbusDemo.Modular
List<ushort> usChannelErrorCodeList = new List<ushort>(); List<ushort> usChannelErrorCodeList = new List<ushort>();
for (byte j = 0; j < byX66cRelayRegNumber; j++) for (byte j = 0; j < byX66cRelayRegNumber; j++)
{ {
if ((cx66c.sX66cAlarmStruct[i].usNowAlarmCode[j] & (ushort)ModualAlarm.eAlarmCode.ChannelCommunError) == (ushort)ModualAlarm.eAlarmCode.ChannelCommunError && cx66c.sX66cAlarmStruct[i].usCommFailTimes[j] < COMMFAILALARM)
{
cx66c.sX66cAlarmStruct[i].usNowAlarmCode[j] &= (ushort)~ModualAlarm.eAlarmCode.ChannelCommunError;
}
if (cx66c.sX66cAlarmStruct[i].usNowAlarmCode[j] != cx66c.sX66cAlarmStruct[i].usBeforeAlarmCode[j]) if (cx66c.sX66cAlarmStruct[i].usNowAlarmCode[j] != cx66c.sX66cAlarmStruct[i].usBeforeAlarmCode[j])
{ {
bOccurErrorChange = true; bOccurErrorChange = true;
......
...@@ -26,6 +26,7 @@ namespace ModbusDemo.Modular ...@@ -26,6 +26,7 @@ namespace ModbusDemo.Modular
public bool bDataNotFirstIncreaseOrDecrease; public bool bDataNotFirstIncreaseOrDecrease;
public ushort[] usNowAlarmCode; public ushort[] usNowAlarmCode;
public ushort[] usBeforeAlarmCode; public ushort[] usBeforeAlarmCode;
public ushort[] usCommFailTimes;
} }
public class pcx14P public class pcx14P
{ {
...@@ -45,6 +46,7 @@ namespace ModbusDemo.Modular ...@@ -45,6 +46,7 @@ namespace ModbusDemo.Modular
//this.sX14pDataStruct[i].usX14pRegData = new ushort[ModualPoll.byX14pReadDataNumber]; //this.sX14pDataStruct[i].usX14pRegData = new ushort[ModualPoll.byX14pReadDataNumber];
this.sX14PAlarmStruct[i].usBeforeAlarmCode = new ushort[ModualPoll.byX14pReadDataNumber]; this.sX14PAlarmStruct[i].usBeforeAlarmCode = new ushort[ModualPoll.byX14pReadDataNumber];
this.sX14PAlarmStruct[i].usNowAlarmCode = new ushort[ModualPoll.byX14pReadDataNumber]; this.sX14PAlarmStruct[i].usNowAlarmCode = new ushort[ModualPoll.byX14pReadDataNumber];
this.sX14PAlarmStruct[i].usCommFailTimes = new ushort[ModualPoll.byX14pReadDataNumber];
} }
} }
} }
...@@ -83,6 +85,7 @@ namespace ModbusDemo.Modular ...@@ -83,6 +85,7 @@ namespace ModbusDemo.Modular
//this.sX18xDataStruct[i].usTypeData = new ushort[ModualPoll.byX18xReadDataNumber]; //this.sX18xDataStruct[i].usTypeData = new ushort[ModualPoll.byX18xReadDataNumber];
this.sX18xAlarmstruct[i].usBeforeAlarmCode = new ushort[ModualPoll.byX18xReadDataNumber]; this.sX18xAlarmstruct[i].usBeforeAlarmCode = new ushort[ModualPoll.byX18xReadDataNumber];
this.sX18xAlarmstruct[i].usNowAlarmCode = new ushort[ModualPoll.byX18xReadDataNumber]; this.sX18xAlarmstruct[i].usNowAlarmCode = new ushort[ModualPoll.byX18xReadDataNumber];
this.sX18xAlarmstruct[i].usCommFailTimes = new ushort[ModualPoll.byX18xReadDataNumber];
} }
} }
} }
...@@ -105,6 +108,7 @@ namespace ModbusDemo.Modular ...@@ -105,6 +108,7 @@ namespace ModbusDemo.Modular
this.sX78cRegStatusStruct[i].bOutPutRegStatus = new bool[ModualPoll.byX78cOutputRegNumber]; this.sX78cRegStatusStruct[i].bOutPutRegStatus = new bool[ModualPoll.byX78cOutputRegNumber];
this.sX78cAlarmStruct[i].usBeforeAlarmCode = new ushort[ModualPoll.byX78cInputRegNumber + ModualPoll.byX78cOutputRegNumber]; this.sX78cAlarmStruct[i].usBeforeAlarmCode = new ushort[ModualPoll.byX78cInputRegNumber + ModualPoll.byX78cOutputRegNumber];
this.sX78cAlarmStruct[i].usNowAlarmCode = new ushort[ModualPoll.byX78cInputRegNumber + ModualPoll.byX78cOutputRegNumber]; this.sX78cAlarmStruct[i].usNowAlarmCode = new ushort[ModualPoll.byX78cInputRegNumber + ModualPoll.byX78cOutputRegNumber];
this.sX78cAlarmStruct[i].usCommFailTimes = new ushort[ModualPoll.byX78cInputRegNumber + ModualPoll.byX78cOutputRegNumber];
} }
} }
} }
...@@ -125,6 +129,7 @@ namespace ModbusDemo.Modular ...@@ -125,6 +129,7 @@ namespace ModbusDemo.Modular
this.sX66cRegStatusStruct[i].bRegRelayStatus = new bool[ModualPoll.byX66cRelayRegNumber]; this.sX66cRegStatusStruct[i].bRegRelayStatus = new bool[ModualPoll.byX66cRelayRegNumber];
this.sX66cAlarmStruct[i].usBeforeAlarmCode = new ushort[ModualPoll.byX66cRelayRegNumber]; this.sX66cAlarmStruct[i].usBeforeAlarmCode = new ushort[ModualPoll.byX66cRelayRegNumber];
this.sX66cAlarmStruct[i].usNowAlarmCode = new ushort[ModualPoll.byX66cRelayRegNumber]; this.sX66cAlarmStruct[i].usNowAlarmCode = new ushort[ModualPoll.byX66cRelayRegNumber];
this.sX66cAlarmStruct[i].usCommFailTimes = new ushort[ModualPoll.byX66cRelayRegNumber];
} }
} }
} }
......
...@@ -26,18 +26,15 @@ namespace ModbusDemo ...@@ -26,18 +26,15 @@ namespace ModbusDemo
{ {
public partial class Form1 : Form public partial class Form1 : Form
{ {
//Pond FunctionalService = new Pond(); const bool LOCALDEBUG = false;
const bool LOCALDEBUG = true;
private bool bStart = false; private bool bStart = false;
AutoResetEvent exitEvent; AutoResetEvent exitEvent;
private int waitTime; private int waitTime;
private Thread t_UpgradeConn; private Thread t_UpgradeConn;
public delegate void invokeDelegate(); public delegate void invokeDelegate();
System.Timers.Timer timer = new System.Timers.Timer();
System.Timers.Timer MQTTTimer = new System.Timers.Timer(); System.Timers.Timer MQTTTimer = new System.Timers.Timer();
BackgroundWorker m_bgw0 = new BackgroundWorker(); BackgroundWorker m_bgw0 = new BackgroundWorker();
bool m_Isbgw0_CanContinueRun = true; bool m_Isbgw0_CanContinueRun = true;
bool State_enable = true;
bool bCretaThead = false; bool bCretaThead = false;
public static ModbusDemo.windows.Totxt totxt = new windows.Totxt(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt"); public static ModbusDemo.windows.Totxt totxt = new windows.Totxt(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt");
...@@ -86,8 +83,6 @@ namespace ModbusDemo ...@@ -86,8 +83,6 @@ namespace ModbusDemo
string mqttData_Back;//数据 string mqttData_Back;//数据
private IMqttClient mqttClient = null; private IMqttClient mqttClient = null;
private bool isReconnect = true; private bool isReconnect = true;
private void SetMqtt() private void SetMqtt()
{ {
if (LOCALDEBUG == true) if (LOCALDEBUG == true)
...@@ -100,7 +95,7 @@ namespace ModbusDemo ...@@ -100,7 +95,7 @@ namespace ModbusDemo
} }
else else
{ {
mqttIp = "120.27.235.39"; mqttIp = "172.16.1.24";//"120.27.235.39"
mqttClientId = GetTimeStamp() + "sxz"; mqttClientId = GetTimeStamp() + "sxz";
mqttPort = 1883; mqttPort = 1883;
mqttUsername = "pasture"; mqttUsername = "pasture";
...@@ -114,13 +109,11 @@ namespace ModbusDemo ...@@ -114,13 +109,11 @@ namespace ModbusDemo
int _n = 2; int _n = 2;
this.Invoke(new Action(() => this.Invoke(new Action(() =>
{ {
})); }));
Thread.Sleep(1000); Thread.Sleep(1000);
} }
} }
#region 时间戳 #region 时间戳
/// <summary> /// <summary>
/// 获取时间戳 /// 获取时间戳
/// </summary> /// </summary>
...@@ -131,8 +124,9 @@ namespace ModbusDemo ...@@ -131,8 +124,9 @@ namespace ModbusDemo
return Convert.ToUInt64(ts.TotalSeconds); return Convert.ToUInt64(ts.TotalSeconds);
} }
#endregion #endregion
#region mqtt服务
#region mqtt服务
//创建一个委托,是为访问TextBox控件服务的。 //创建一个委托,是为访问TextBox控件服务的。
public delegate void UpdateTxt(string msg); public delegate void UpdateTxt(string msg);
//定义一个委托变量 //定义一个委托变量
...@@ -190,7 +184,6 @@ namespace ModbusDemo ...@@ -190,7 +184,6 @@ namespace ModbusDemo
private async Task ConnectMqttServerAsync() private async Task ConnectMqttServerAsync()
{ {
// Create a new MQTT client. // Create a new MQTT client.
if (mqttClient == null) if (mqttClient == null)
{ {
var factory = new MqttFactory(); var factory = new MqttFactory();
...@@ -240,7 +233,7 @@ namespace ModbusDemo ...@@ -240,7 +233,7 @@ namespace ModbusDemo
{ {
Invoke((new Action(() => Invoke((new Action(() =>
{ {
txtReceiveMessage.Clear(); //txtReceiveMessage.Clear();
txtReceiveMessage.AppendText("已连接到MQTT服务器!" + Environment.NewLine); txtReceiveMessage.AppendText("已连接到MQTT服务器!" + Environment.NewLine);
//totxt.Log("已连接到MQTT服务器!" + Environment.NewLine); //totxt.Log("已连接到MQTT服务器!" + Environment.NewLine);
//Console.WriteLine("已连接到MQTT服务器!" + Environment.NewLine); //Console.WriteLine("已连接到MQTT服务器!" + Environment.NewLine);
...@@ -343,25 +336,23 @@ namespace ModbusDemo ...@@ -343,25 +336,23 @@ namespace ModbusDemo
txtReceiveMessage.AppendText($">> Retain = {e.ApplicationMessage.Retain}{Environment.NewLine}"); txtReceiveMessage.AppendText($">> Retain = {e.ApplicationMessage.Retain}{Environment.NewLine}");
//totxt.Log($">> Retain = {e.ApplicationMessage.Retain}{Environment.NewLine}"); //totxt.Log($">> Retain = {e.ApplicationMessage.Retain}{Environment.NewLine}");
}))); })));
mqttData = null ; mqttData = null;
} }
#endregion #endregion
#region modbus线程 #region modbus线程
private static bool bSetDataIsRunning = false; private static bool bSetDataIsRunning = false;
private Thread ModbusPollThread; private Thread ModbusPollThread;
private bool bModbusPollThreadStart = false;
private void vModbusPoll() private void vModbusPoll()
{ {
while(bModbusPollThreadStart) while (true)
{ {
bSetDataIsRunning = true; bSetDataIsRunning = true;
totxt.Log("开始执行");
ModualPoll.vAllNodePoll(); ModualPoll.vAllNodePoll();
mqttData = ModualPoll.stAll_Poll_Package(); mqttData = ModualPoll.stAll_Poll_Package();
ModualPoll.vCheckAlarm_And_Send(mqttClient); ModualPoll.vCheckAlarm_And_Send(mqttClient);
totxt.Log("执行结束");
label5.Text = ModbusComm.usCommunFailTimes.ToString(); label5.Text = ModbusComm.usCommunFailTimes.ToString();
Thread.Sleep(100);
} }
} }
private void Sendout() private void Sendout()
...@@ -409,18 +400,7 @@ namespace ModbusDemo ...@@ -409,18 +400,7 @@ namespace ModbusDemo
bSetDataIsRunning = false; bSetDataIsRunning = false;
} }
} }
<<<<<<< HEAD
=======
<<<<<<< HEAD
} }
#region PoolTest
=======
}
#region PoolTest
>>>>>>> ae9d62a8c8c10f8339da24024e6330c7ac4ff704
#endregion
//声明委托 //声明委托
private delegate void ShowMessageDelegate(string message); private delegate void ShowMessageDelegate(string message);
private void ShowMessage(string message) private void ShowMessage(string message)
...@@ -436,9 +416,9 @@ namespace ModbusDemo ...@@ -436,9 +416,9 @@ namespace ModbusDemo
//totxt.Log(message); //totxt.Log(message);
} }
} }
#endregion #endregion
#region json字符串转对象 #region json字符串转对象
/// <summary> /// <summary>
/// json字符串转对象 /// json字符串转对象
/// </summary> /// </summary>
...@@ -502,11 +482,10 @@ namespace ModbusDemo ...@@ -502,11 +482,10 @@ namespace ModbusDemo
Console.WriteLine(ex.Message); Console.WriteLine(ex.Message);
return ""; return "";
} }
>>>>>>> origin/master
} }
#endregion #endregion
#region 网络检测 #region 网络检测
ManualResetEvent network = new ManualResetEvent(false); ManualResetEvent network = new ManualResetEvent(false);
Thread MonitorThread; Thread MonitorThread;
...@@ -631,9 +610,9 @@ namespace ModbusDemo ...@@ -631,9 +610,9 @@ namespace ModbusDemo
// isconn = true; // isconn = true;
return isconn; return isconn;
} }
#endregion #endregion
#region 更新线程 #region 更新线程
string ImagefilePath = null; string ImagefilePath = null;
private void bgWorker_DoWork(object sender, DoWorkEventArgs e) private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{ {
...@@ -966,7 +945,7 @@ namespace ModbusDemo ...@@ -966,7 +945,7 @@ namespace ModbusDemo
} }
} }
} }
#endregion #endregion
private void txtReceiveMessage_TextChanged(object sender, EventArgs e) private void txtReceiveMessage_TextChanged(object sender, EventArgs e)
{ {
...@@ -979,7 +958,7 @@ namespace ModbusDemo ...@@ -979,7 +958,7 @@ namespace ModbusDemo
private void button2_Click(object sender, EventArgs e) private void button2_Click(object sender, EventArgs e)
{ {
ModualPoll.vAllNodePoll(); ModualPoll.vAllNodePoll();
mqttData=ModualPoll.stAll_Poll_Package(); mqttData = ModualPoll.stAll_Poll_Package();
} }
private async void SubscribeBut_Click(object sender, EventArgs e) private async void SubscribeBut_Click(object sender, EventArgs e)
...@@ -1034,23 +1013,10 @@ namespace ModbusDemo ...@@ -1034,23 +1013,10 @@ namespace ModbusDemo
comPort.Open(); comPort.Open();
isReconnect = true; isReconnect = true;
SetMqtt(); SetMqtt();
if (bCretaThead == false)
{
bCretaThead = true;
ModbusPollThread = new Thread(vModbusPoll);
ModbusPollThread.Start();
ModbusControlThread = new Thread(ModualControl.vControl_Poll);
ModbusControlThread.Start();
}
else
{
ModbusPollThread.Resume();
}
bModbusPollThreadStart = true;
MQTT_thread = new MethodInvoker(Sendout); MQTT_thread = new MethodInvoker(Sendout);
MQTT_thread.BeginInvoke(null, null); MQTT_thread.BeginInvoke(null, null);
Task.Run(async () => { await ConnectMqttServerAsync(); }); Task.Run(async () => { await ConnectMqttServerAsync(); });
ModbusComm.Modbus = ModbusSerialMaster.CreateRtu(comPort); ModbusComm.Modbus = ModbusSerialMaster.CreateRtu(comPort);
ModbusComm.Modbus.Transport.Retries = 0; ModbusComm.Modbus.Transport.Retries = 0;
ModbusComm.Modbus.Transport.ReadTimeout = 1000; ModbusComm.Modbus.Transport.ReadTimeout = 1000;
...@@ -1061,8 +1027,20 @@ namespace ModbusDemo ...@@ -1061,8 +1027,20 @@ namespace ModbusDemo
modbus_Timer.Enabled = true; modbus_Timer.Enabled = true;
btOpenCOM.Enabled = false; btOpenCOM.Enabled = false;
btCloseCOM.Enabled = true; btCloseCOM.Enabled = true;
totxt.Log(DateTime.Now.ToString() + " =>Open " + comPort.PortName + " sucessfully!"); if (bCretaThead == false)
{
bCretaThead = true;
ModbusPollThread = new Thread (vModbusPoll);
ModbusPollThread.Start();
ModbusControlThread = new Thread(ModualControl.vControl_Poll);
ModbusControlThread.Start();
}
else
{
ModbusPollThread.Resume();
}
totxt.Log(DateTime.Now.ToString() + " =>Open " + comPort.PortName + " sucessfully!");
} }
catch (Exception ex) catch (Exception ex)
{ {
...@@ -1070,13 +1048,13 @@ namespace ModbusDemo ...@@ -1070,13 +1048,13 @@ namespace ModbusDemo
MessageBox.Show("Error: " + ex.Message); MessageBox.Show("Error: " + ex.Message);
return; return;
} }
} }
[Obsolete] [Obsolete]
private void btCloseCOM_Click(object sender, EventArgs e) private void btCloseCOM_Click(object sender, EventArgs e)
{ {
//Close comport first,then stop and dispose slave. //Close comport first,then stop and dispose slave.
bModbusPollThreadStart = false; if (ModbusPollThread.IsAlive == true)
if(ModbusPollThread.IsAlive)
ModbusPollThread.Suspend(); ModbusPollThread.Suspend();
isReconnect = false; isReconnect = false;
modbus_Timer.Enabled = false; modbus_Timer.Enabled = false;
...@@ -1087,4 +1065,5 @@ namespace ModbusDemo ...@@ -1087,4 +1065,5 @@ namespace ModbusDemo
totxt.Log(DateTime.Now.ToString() + " =>Disconnect " + comPort.PortName); totxt.Log(DateTime.Now.ToString() + " =>Disconnect " + comPort.PortName);
} }
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment