-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm1.cs
More file actions
286 lines (249 loc) · 9.63 KB
/
Form1.cs
File metadata and controls
286 lines (249 loc) · 9.63 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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
using System;
using System.IO.Ports;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BleSerialTool
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
RefreshSerialPorts();
cbBaudRate.SelectedItem = "230400"; // Default per requirement
}
private void RefreshSerialPorts()
{
string[] ports = SerialPort.GetPortNames();
string lastPort = cbSerialPort.Text;
cbSerialPort.Items.Clear();
cbSerialPort.Items.AddRange(ports);
if (ports.Length > 0)
{
if (!string.IsNullOrEmpty(lastPort) && Array.IndexOf(ports, lastPort) >= 0)
{
cbSerialPort.Text = lastPort;
}
else
{
cbSerialPort.SelectedIndex = 0;
}
}
}
private void btnRefreshPort_Click(object sender, EventArgs e)
{
RefreshSerialPorts();
}
private void btnOpenClose_Click(object sender, EventArgs e)
{
try
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
btnOpenClose.Text = "打开串口";
lblStatus.Text = "串口已关闭";
ToggleControls(true);
}
else
{
if (string.IsNullOrEmpty(cbSerialPort.Text))
{
MessageBox.Show("请先选择串口!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
serialPort1.PortName = cbSerialPort.Text;
serialPort1.BaudRate = int.Parse(cbBaudRate.Text);
serialPort1.DataBits = 8;
serialPort1.StopBits = StopBits.One;
serialPort1.Parity = Parity.None;
serialPort1.DtrEnable = true; // Many USB-TTL adapters need DTR/RTS enabled
serialPort1.RtsEnable = true;
// Enable DataReceived event
serialPort1.DataReceived -= SerialPort1_DataReceived; // Ensure no double subscription
serialPort1.DataReceived += SerialPort1_DataReceived;
serialPort1.Open();
btnOpenClose.Text = "关闭串口";
lblStatus.Text = "串口已打开";
ToggleControls(false);
}
}
catch (Exception ex)
{
MessageBox.Show($"串口操作失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ToggleControls(bool enabled)
{
cbSerialPort.Enabled = enabled;
cbBaudRate.Enabled = enabled;
btnRefreshPort.Enabled = enabled;
}
// Helper to check if port is open
private bool CheckSerialPort()
{
if (!serialPort1.IsOpen)
{
MessageBox.Show("请先打开串口!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
return true;
}
// Helper to send data (string)
private void SendData(string data)
{
if (!CheckSerialPort()) return;
try
{
// Write string directly as per requirement (no auto newline unless part of data)
if (chkSendNewLine.Checked)
{
data += "\r\n";
}
// Show sent data in receive box for debugging (optional but helpful)
// txtReceive.AppendText($"[Send] {data}");
serialPort1.Write(data);
// Update status to show what was sent
lblStatus.Text = $"已发送: {data.Trim()}";
}
catch (Exception ex)
{
MessageBox.Show($"发送失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Async One-Key Configuration
private async void btnOneKeyConfig_Click(object sender, EventArgs e)
{
if (!CheckSerialPort()) return;
btnOneKeyConfig.Enabled = false;
lblStatus.Text = "正在配置...";
try
{
// 1. AT+RENEW
AppendSystemMessage("发送: AT+RENEW");
serialPort1.Write("AT+RENEW");
await Task.Delay(500);
// 2. AT+RESET
AppendSystemMessage("发送: AT+RESET (等待重启...)");
serialPort1.Write("AT+RESET");
await Task.Delay(2000); // Wait 2s for reboot
// 3. AT+SERVFFE0
AppendSystemMessage("发送: AT+SERVFFE0");
serialPort1.Write("AT+SERVFFE0");
await Task.Delay(500);
// 4. AT+CHRXFFE1
AppendSystemMessage("发送: AT+CHRXFFE1");
serialPort1.Write("AT+CHRXFFE1");
await Task.Delay(500);
// 5. AT+CHTXFFE1
AppendSystemMessage("发送: AT+CHTXFFE1");
serialPort1.Write("AT+CHTXFFE1");
await Task.Delay(500);
lblStatus.Text = "配置完成";
MessageBox.Show("一键配置完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"配置过程中出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
lblStatus.Text = "配置出错";
}
finally
{
btnOneKeyConfig.Enabled = true;
}
}
private void btnScan_Click(object sender, EventArgs e)
{
if (!CheckSerialPort()) return;
lblStatus.Text = "正在扫描...";
SendData("AT+SCAN?");
}
private void btnConnect_Click(object sender, EventArgs e)
{
if (!CheckSerialPort()) return;
string mac = txtTargetMac.Text.Trim();
if (string.IsNullOrEmpty(mac))
{
MessageBox.Show("请输入目标MAC地址!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
lblStatus.Text = "正在连接...";
// Command format: AT+CON + MAC (e.g., AT+CON442C05E63936)
SendData("AT+CON" + mac);
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
if (!CheckSerialPort()) return;
lblStatus.Text = "断开连接...";
SendData("AT+DISCON");
}
private void btnSend_Click(object sender, EventArgs e)
{
if (!CheckSerialPort()) return;
string data = txtSend.Text;
if (string.IsNullOrEmpty(data)) return;
SendData(data);
// Requirement says: do not clear input box
}
private void btnClear_Click(object sender, EventArgs e)
{
txtReceive.Clear();
}
private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
// Read existing data
string data = serialPort1.ReadExisting();
if (string.IsNullOrEmpty(data)) return;
// Invoke UI update
this.Invoke(new Action(() =>
{
AppendReceivedData(data);
}));
}
catch (Exception)
{
// Handle potential closing errors
}
}
private void AppendReceivedData(string text)
{
if (chkShowTimestamp.Checked)
{
// If showing timestamp, maybe we want to prepend it to new lines?
// Or just once per chunk?
// Simple approach: [Time] Data
// But data might be fragmented.
// For a simple terminal, just appending is fine.
// Or we can append [HH:mm:ss.fff] before the block.
txtReceive.AppendText($"[{DateTime.Now:HH:mm:ss.fff}] ");
}
txtReceive.AppendText(text);
// Auto scroll
txtReceive.SelectionStart = txtReceive.Text.Length;
txtReceive.ScrollToCaret();
// Check for specific responses to update status (Optional but good for UX)
if (text.Contains("Connected") || text.Contains("OK+CON")) // Adjust based on actual device response
{
lblStatus.Text = "已连接";
}
else
{
lblStatus.Text = $"接收数据: {text.Length} 字节";
}
}
private void AppendSystemMessage(string msg)
{
// Optional: Show system actions in receive window for debugging?
// Or just keep it clean. Let's keep receive window for RX only as per req.
// But user might want to see what was sent during config.
// "右侧:多行TextBox(只读),用于显示接收到的数据" -> Only received data.
// So I will NOT append sent data to the RX window.
}
}
}