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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
using Newtonsoft.Json;
using RJCP.IO.Ports;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace LB_VisionProcesses.Communicators.TCom
{
    [JsonObject(MemberSerialization.OptOut)]
    public class UARTPort : BaseCommunicator
    {
        private RJCP.IO.Ports.SerialPortStream SerialPort = new RJCP.IO.Ports.SerialPortStream();
 
        // 构造函数
        public UARTPort(string name = "UART串口")
        {
            CommunicatorConnections.Add("地址", "COM1");
            CommunicatorConnections.Add("端口", "9600");
            CommunicatorBrand = CommunicatorBrand.UARTPort;
            CommunicatorName = name;
        }
 
        /// <summary>
        /// 配置串口参数
        /// </summary>
        /// <param name="portName"></param>
        /// <param name="baudRate"></param>
        /// <param name="parity"></param>
        /// <param name="dataBits"></param>
        /// <param name="stopBits"></param>
        public void SetConfigure(string portName, int baudRate = 9600, RJCP.IO.Ports.Parity parity = RJCP.IO.Ports.Parity.None,
            int dataBits = 8, RJCP.IO.Ports.StopBits stopBits = RJCP.IO.Ports.StopBits.One)
        {
            SerialPort.PortName = portName;
            SerialPort.BaudRate = baudRate;
            SerialPort.Parity = parity;
            SerialPort.DataBits = dataBits;
            SerialPort.StopBits = stopBits;
            SerialPort.NewLine = "\r\n";  // 设置行结束符
            SerialPort.ReadTimeout = 500; // 设置读取超时
            SerialPort.WriteTimeout = 500; // 设置写入超时
        }
 
        public override bool Connect()
        {
            try
            {
                Disconnect();
 
                //波特率
                int PORT = 0;
                if (!int.TryParse(this.CommunicatorConnections["端口"].ToString(), out PORT))
                {
                    Msg = string.Format("端口未设置");
                    return false;
                }
                if (!CommunicatorConnections.Contains("地址"))
                {
                    Msg = string.Format("地址未设置");
                    return false;
                }
                //串口号
                string IP = CommunicatorConnections["地址"].ToString();
 
                if (!SerialPort.IsOpen)
                {
                    SerialPort = new SerialPortStream();
                    SetConfigure(IP, PORT);
                    SerialPort.Open();
                    bConnected = true;
                    SerialPort.DataReceived += SerialPort_DataReceived;
 
                    // 启动心跳线程
                    heartbeatThread = new Thread(SendHeartbeat);
                    heartbeatThread.IsBackground = true;
                    heartbeatThread.Start();
 
                    bConnected = true;
                    return true;
                }
                else
                {
                    Msg = $"原串口关闭失败无法重新打开";
                    return false;
                }
            }
            catch (Exception ex)
            {
                Msg = $"失败,串口已经启动: {ex.Message}";
                return false;
            }
        }
 
        public override bool Disconnect()
        {
            try
            {
                bConnected = false;
                if (SerialPort == null)
                {
                    SerialPort = new SerialPortStream();
                    return true;
                }
 
                if (SerialPort.IsOpen)
                {
                    SerialPort.DataReceived -= SerialPort_DataReceived;
                    SerialPort.Close(); // 关闭串口
                }
 
                SerialPort = new SerialPortStream();
                return true;
            }
            catch (Exception ex)
            {
                bConnected = false;
                Msg = $"断开串口时出错: {ex.Message}";
                return true;
            }
        }
 
        public bool SendMessageBytes(byte[] sBytes)
        {
            bool bret = false;
            if (SerialPort == null || !SerialPort.IsOpen) return bret;
            try
            {
                SerialPort.Write(sBytes, 0, sBytes.Length);
                bret = true;
            }
            catch { }
            return bret;
        }
 
        public override bool SendMessage(string message)
        {
            if (bConnected)
            {
                try
                {
                    //空消息不发送
                    if (string.IsNullOrEmpty(message) || message.Trim() == "")
                        return true;
 
                    //发送前清空接收消息
                    strReceiveMsg = string.Empty;
                    SerialPort.Write(message); // 发送消息
                    return true;
                }
                catch (Exception ex)
                {
                    Msg = $"发送消息时出错: {ex.Message}";
                    return false;
                }
            }
            else
            {
                Msg = "串口未打开";
                return false;
            }
        }
 
        private void ReadSerialData()
        {
            while (bConnected)
            {
                try
                {
                    string message = SerialPort.ReadLine(); // 读取一行数据
                    if (message != null)
                    {
                        strReceiveMsg = message;
                        MessageReceived?.Invoke(message); // 触发回调
                        TriggerRunMessageReceived?.Invoke(CommunicatorName, strReceiveMsg);  // 触发运行事件
                    }
                }
                //catch (TimeoutException) { /* 读取超时,可以忽略 */ }
                catch (Exception ex)
                {
                    Msg = $"读取串口数据时出错: {ex.Message}";
                }
            }
        }
 
        private System.Threading.Timer _clearTimer;  // 用于延时清空的计时器
 
        private void SerialPort_DataReceived(object? sender, RJCP.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                if (SerialPort == null || !SerialPort.IsOpen)
                    return;
 
                string message = SerialPort.ReadExisting();
                if (string.IsNullOrEmpty(message))
                    return;
 
                if (string.IsNullOrEmpty(strReceiveMsg))
                {
                    // 重置或启动计时器(1秒后清空)
                    _clearTimer?.Dispose();  // 取消之前的计时器
                    _clearTimer = new System.Threading.Timer(
                        _ => ClearMessage(),
                        null,
                        TimeSpan.FromSeconds(1),  // 1秒后触发
                        Timeout.InfiniteTimeSpan  // 只触发一次
                    );
                }
 
                //串口回调用累加的方式
                lock (strReceiveMsg)
                {
                    strReceiveMsg += message;
                    MessageReceived?.Invoke(strReceiveMsg); // 触发回调
                    TriggerRunMessageReceived?.Invoke(CommunicatorName, strReceiveMsg);  // 触发运行事件
                }
            }
            catch (Exception ex)
            {
                Msg = $"读取串口数据时出错: {ex.Message}";
            }
        }
 
        public override string ReceiveMsg()
        {
            string msg = string.Empty;
            for (int i = 0; i <= 3; i++)
            {
                if (string.IsNullOrEmpty(strReceiveMsg))
                    Thread.Sleep(50);
                else
                {
                    lock (strReceiveMsg)
                    {
                        msg += strReceiveMsg;
                        strReceiveMsg = string.Empty;
                    }
                    //串口数据需要使用累加方式
                    //return msg;
                }
            }
            return msg;
        }
    }
}