SerialPortSetting.cs
7.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
//´æ´¢ÁË´®¿ÚµÄ³õʼ»¯µÄÉèÖÃÊý¾Ý,ÒÔ¼°·â×°ÁË´®¿ÚµÄÒ»²¿·Ö·½·¨
using System;
using System.IO.Ports;
using System.Windows.Forms;
using System.Timers;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Dal;
namespace MachineDll
{
public class SerialPortSetting
{
public static string PortName;
public static int BautRate = 9600;
public static int DataBits = 8;
public static Parity Parity = Parity.None;
public static StopBits StopBits = StopBits.One;
private SerialPort _ItsSerialPort;
private string Message;
public static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public string TestConnection()
{
string port="";
for (int i = 1; i < 9;i++ )
{
_ItsSerialPort = new SerialPort("COM"+i.ToString(), BautRate, Parity, DataBits, StopBits);
try
{
_ItsSerialPort.Open();
port = "COM" + i.ToString() + " "+port;
_ItsSerialPort.Close();
}
catch(Exception es)
{
//MessageBox.Show(_ItsSerialPort.PortName + "¶Ë¿ÚÒѾ±»ÆäËû³ÌÐòËùÕ¼ÓÃ");
}
}
return port;
}
public bool StartConnection()
{
_ItsSerialPort = new SerialPort(PortName, BautRate, Parity, DataBits, StopBits);
_ItsSerialPort.ErrorReceived += new SerialErrorReceivedEventHandler(SerialPort_ErrorReceived);
_ItsSerialPort.RtsEnable = true;
try
{
_ItsSerialPort.Open();
return true;
}
catch(Exception ex)
{
MessageBox.Show(_ItsSerialPort.PortName + "端口已经被其他程序所占用\r\n"+ ex);
return false;
}
}
private void SerialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
this.Message = e.ToString();
}
public bool PortIsOpen()
{
return _ItsSerialPort.IsOpen;
}
public void CloseConnection()
{
try
{
if (PortIsOpen())
{
_ItsSerialPort.Close();
}
}
catch(Exception ex)
{
MessageBox.Show("关闭连接失败");
LOGGER.Error("CloseConnection", ex);
}
}
public Byte[] ReadByte()
{
Byte[] data=new Byte[1];
try
{
data = new Byte[_ItsSerialPort.BytesToRead];
_ItsSerialPort.Read(data, 0, _ItsSerialPort.BytesToRead);
}
catch
{ }
return data;
}
public void SendByteNew(byte[] s)
{
try
{
_ItsSerialPort.Write(s, 0, 1);
}
catch
{
}
}
public void SendByte(string s)
{
_ItsSerialPort.Write(s);
}
public void SendString(string s)
{
byte[] btAppend = { 0x0D };
_ItsSerialPort.Write(s);
_ItsSerialPort.Write(btAppend, 0, btAppend.Length);
}
public void SendIOString(string s)
{
try
{
string[] stringData = s.Split(' ');
byte[] byteData = new byte[stringData.Length];
//_ItsSerialPort.Write(s);
int i = 0;
foreach (string data in stringData)
{
byteData[i++] = Convert.ToByte(data, 16);
}
_ItsSerialPort.Write(byteData, 0, byteData.Length);
}
catch (Exception ex)
{
LOGGER.Error("SendIOString", ex);
}
}
public double ReadAIString(string s)
{
//LOGGER.Debug("serialPortSetting into readAIString");
string[] dataString = s.Split(' ');
byte slaveID = byte.Parse(dataString[0], System.Globalization.NumberStyles.HexNumber);//485地址
byte fuctionType = byte.Parse(dataString[1], System.Globalization.NumberStyles.HexNumber);//功能码
ushort registerAdd = ushort.Parse(dataString[2] + dataString[3], System.Globalization.NumberStyles.HexNumber);//寄存器地址
ushort registerQty = ushort.Parse(dataString[4] + dataString[5], System.Globalization.NumberStyles.HexNumber);//寄存器个数
byte[] values = new byte[registerQty];
Modbus mb = new Modbus(_ItsSerialPort);
//LOGGER.Debug("serialPortSetting ,before into sendFuction");
//while (!mb.SendFuction(slaveID, fuctionType, registerAdd, registerQty, ref values)) ;
var re = mb.SendFuction(slaveID, fuctionType, registerAdd, registerQty, ref values);
byte[] doubleBytes =
{
values[4], values[3],values[6],values[5]
};
float dataToFloat = BitConverter.ToSingle(doubleBytes, 0);
var dataConvert = CurrentConversion(dataToFloat);
LOGGER.Debug($"IO Return: {re}, org:{dataToFloat},cov:{dataConvert},");
////AI1通道
//string data = values[1].ToString("X").PadLeft(4,'0') + "" + values[0].ToString("X").PadLeft(4,'0');
////AI2通道
////string data = values[3].ToString("X").PadLeft(4, '0') + "" + values[2].ToString("X").PadLeft(4, '0');
//float dataToFloat = StringToFloat(data);
return dataConvert;
//return dataToFloat;
}
private double CurrentConversion(float dataToFloat)
{
/**
* returnValue = (IO返回数据-4000)/16000*1
* IO的量程为4000-20000,跳线设置量程为0-1
* (IO返回数据-IO起始数据)/(量程一共分为多少格)*跳线设置量程
*/
//LOGGER.Debug("IO Value: " + dataToFloat);
if (dataToFloat < 4000)
dataToFloat = 4000;
Fuction fuction = new Fuction();
double liangcheng = double.Parse(fuction.GetParameterByParaName("liangcheng", "currency"), System.Globalization.CultureInfo.InvariantCulture);
double returnValue = (dataToFloat - 4000) / 16000 * liangcheng;
//LOGGER.Info(returnValue + " = (" + dataToFloat + " - 4000) / 16000 * " + liangcheng);
return returnValue;
}
public static float StringToFloat(String data)
{
if (data.Length < 8 || data.Length > 8)
{
//throw new NotEnoughDataInBufferException(data.length(), 8);
return 0;
}
else
{
byte[] intBuffer = new byte[4];
// 将16进制串按字节逆序化(一个字节2个ASCII码)
for (int i = 0; i < 4; i++)
{
intBuffer[i] = Convert.ToByte(data.Substring((3 - i) * 2, 2), 16);
}
return BitConverter.ToSingle(intBuffer, 0);
}
}
public string ReadExisting()
{
_ItsSerialPort.DiscardInBuffer();
_ItsSerialPort.DiscardOutBuffer();
return _ItsSerialPort.ReadExisting();
}
}
}