forked from ngscopeclient/xptools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUART.cpp
More file actions
437 lines (391 loc) · 12.6 KB
/
UART.cpp
File metadata and controls
437 lines (391 loc) · 12.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
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/***********************************************************************************************************************
* *
* xptools *
* *
* Copyright (c) 2012-2025 Andrew D. Zonenberg and contributors *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *
* following conditions are met: *
* *
* * Redistributions of source code must retain the above copyright notice, this list of conditions, and the *
* following disclaimer. *
* *
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *
* following disclaimer in the documentation and/or other materials provided with the distribution. *
* *
* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *
* POSSIBILITY OF SUCH DAMAGE. *
* *
***********************************************************************************************************************/
/**
@file
@author Andrew D. Zonenberg
@brief Implementation of UART
*/
#include "UART.h"
#include <stdio.h>
#include <memory.h>
#ifndef _WIN32
#include <fcntl.h>
#include <unistd.h>
#include <filesystem>
#ifdef USE_TERMIOS2
#include <asm/termios.h>
//asm/termios.h seems to conflict with sys/ioctl.h and termios.h
//so just pull these by hand. musl libc doesn't define __THROW so define it as blank
#ifndef __THROW
#define __THROW
#endif
extern "C" int tcflush (int __fd, int __queue_selector) __THROW;
extern "C" int ioctl (int __fd, unsigned long int __request, ...) __THROW;
#else
#include <termios.h>
#endif // __linux__
#else
#include <Windows.h>
#include <setupapi.h>
#include <devguid.h>
#endif
using namespace std;
/**
@brief Connects to a serial port
@throw JtagException on failure
@param devfile The device file
@param baud Baud rate to use (in bits per second)
*/
UART::UART(const std::string& devfile, int baud)
: m_networked(false)
, m_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
{
Connect(devfile, baud);
}
/**
@brief Constructor
*/
UART::UART()
: m_networked(false)
, m_fd(INVALID_FILE_DESCRIPTOR)
, m_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
{
}
/**
@brief Destructor
*/
UART::~UART() {
Close();
}
/**
@brief Connects to a serial port
@throw JtagException on failure
@param devfile The device file
@param baud Baud rate to use (in bits per second)
@param dtrEnable True if DTR line should be enabled (needed by some devices like the NanoVNA to communicate)
*/
bool UART::Connect(const std::string& devfile, int baud, [[maybe_unused]] bool dtrEnable)
{
if(devfile.find(":") != string::npos)
{
//It's a socket, connect to it
m_networked = true;
char host[128];
unsigned int port;
fflush(stdout);
sscanf(devfile.c_str(), "%127[^:]:%6u", host, &port);
//LogTrace("Connecting to %s:%d\n", host, port);
return m_socket.Connect(host, port);
}
else
{
#ifdef _WIN32
m_fd = CreateFileA(devfile.c_str(), // port name
GENERIC_READ | GENERIC_WRITE, // Read/Write
0, // No Sharing
NULL, // No Security
OPEN_EXISTING,// Open existing port only
0, // Non Overlapped I/O
NULL); // Null for Comm Devices
if (m_fd == INVALID_HANDLE_VALUE)
{
LogError("Could not open COM port %s\n", devfile.c_str());
return false;
}
// Configure port
DCB dcbSerialParams; // Initializing DCB structure
SecureZeroMemory(&dcbSerialParams, sizeof(DCB));
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
// Read current config
bool result = GetCommState(m_fd, &dcbSerialParams);
if(!result)
{
LogError("Could not get state for COM port %s\n", devfile.c_str());
return false;
}
// Set values
dcbSerialParams.BaudRate = baud; // Setting BaudRate
dcbSerialParams.ByteSize = 8; // Setting ByteSize = 8
dcbSerialParams.StopBits = ONESTOPBIT; // Setting StopBits = 1
dcbSerialParams.Parity = NOPARITY; // Setting Parity = None
if(dtrEnable)
dcbSerialParams.fDtrControl = DTR_CONTROL_ENABLE; // Needed by some devices like the NanoVNA to communicate
// Set port configuration
result = SetCommState(m_fd, &dcbSerialParams);
if(!result)
{
LogError("Could not set state for COM port %s\n", devfile.c_str());
return false;
}
// Set timeouts
COMMTIMEOUTS timeouts;
SecureZeroMemory(&timeouts, sizeof(COMMTIMEOUTS));
timeouts.ReadIntervalTimeout = 50; // Timeout between each byte (in milliseconds)
timeouts.ReadTotalTimeoutConstant = 500;// Total timeout for a read operation (in milliseconds)
timeouts.ReadTotalTimeoutMultiplier = 1; // Multiplier for each byte
timeouts.WriteTotalTimeoutConstant = 50; // in milliseconds
timeouts.WriteTotalTimeoutMultiplier = 10;// in milliseconds
result = SetCommTimeouts(m_fd, &timeouts);
if(!result)
{
LogError("Could not set timeouts for COM port %s\n", devfile.c_str());
return false;
}
return true;
#else
//Open the UART
//LogTrace("Opening TTY %s\n", devfile.c_str());
m_fd = open(devfile.c_str(), O_RDWR);
if(m_fd < 0)
{
LogError("Could not open UART file %s\n", devfile.c_str());
return false;
}
//Set flags - linux doesn't support custom bauds in termios
#ifdef USE_TERMIOS2
termios2 flags;
memset(&flags, 0, sizeof(flags));
ioctl(m_fd, TCGETS2, &flags);
flags.c_cflag = CS8 | CLOCAL | CREAD | BOTHER;
flags.c_iflag = IGNBRK | IGNPAR;
flags.c_oflag = 0;
flags.c_cc[VMIN] = 1;
flags.c_ispeed = baud;
flags.c_ospeed = baud;
if(0 != tcflush(m_fd, TCIFLUSH))
{
LogError("Fail to flush tty\n");
return false;
}
if(0 != ioctl(m_fd, TCSETS2, &flags))
{
LogError("Fail to set attr\n");
return false;
}
#else
termios flags;
memset(&flags, 0, sizeof(flags));
tcgetattr(m_fd, &flags);
flags.c_cflag = CS8 | CLOCAL | CREAD;
flags.c_iflag = IGNBRK | IGNPAR;
flags.c_oflag = 0;
flags.c_cc[VMIN] = 1;
flags.c_ispeed = baud;
flags.c_ospeed = baud;
if(0 != tcflush(m_fd, TCIFLUSH))
{
LogError("Fail to flush tty\n");
return false;
}
if(0 != tcsetattr(m_fd, TCSANOW, &flags))
{
LogError("Fail to set attr\n");
return false;
}
#endif
/*
//Put the file in nonblocking mode temporarily
int f = fcntl(m_fd, F_GETFL, 0);
if(f >= 0)
fcntl(m_fd, F_SETFL, f | O_NONBLOCK);
//Do nonblocking reads for 500ms to clear out junk left over from board reset
//TODO: see if this should be default or not?
double t = GetTime() + 0.5;
unsigned char unused;
while(GetTime() < t)
read(m_fd, &unused, 1);
//Return to blocking mode
fcntl(m_fd, F_SETFL, f);
*/
#endif
}
return true;
}
/**
@brief Disconnects from the serial port
*/
void UART::Close()
{
if (m_networked)
return m_socket.Close();
#ifdef _WIN32
// Closing the Serial Port
CloseHandle(m_fd);
#else
close(m_fd);
#endif
m_fd = INVALID_FILE_DESCRIPTOR;
}
bool UART::Read(unsigned char* data, int len)
{
if(m_networked)
return m_socket.RecvLooped(data, len);
else
{
#ifdef _WIN32
long unsigned int x = 0;
while(ReadFile( m_fd, //Handle of the Serial port
(char*)data, //Temporary character
len, //Size of TempChar
&x, //Number of bytes read
NULL)
&& (x != 0)) // Stop when stream is empty
{
len -= x;
data += x;
if(len == 0)
break;
}
if(x == 0)
{
//LogWarning("Socket closed unexpectedly\n");
return false;
}
return true;
#else
int x = 0;
while( (x = read(m_fd, (char*)data, len)) > 0)
{
len -= x;
data += x;
if(len == 0)
break;
}
if(x < 0)
{
LogWarning("UART read failed\n");
return false;
}
else if(x == 0)
{
//LogWarning("Socket closed unexpectedly\n");
return false;
}
return true;
#endif
}
}
bool UART::Write(const unsigned char* data, int len)
{
if(m_networked)
return m_socket.SendLooped(data, len);
else
{
#ifdef _WIN32
long unsigned int x = 0;
while(WriteFile( m_fd, // Handle to the Serial port
(const char*)data, // Data to be written to the port
len, //No of bytes to write
&x, //Bytes written
NULL))
{
len -= x;
data += x;
if(len == 0)
break;
}
if(x == 0)
{
//LogWarning("Socket closed unexpectedly\n");
return false;
}
return true;
#else
int x = 0;
while( (x = write(m_fd, (const char*)data, len)) > 0)
{
len -= x;
data += x;
if(len == 0)
break;
}
if(x < 0)
{
LogWarning("UART write failed\n");
return false;
}
else if(x == 0)
{
//LogWarning("Socket closed unexpectedly\n");
return false;
}
return true;
#endif
}
}
std::vector<UartDescriptor> UART::EnumerateUarts()
{
std::vector<UartDescriptor> ports;
#ifdef _WIN32
HDEVINFO deviceInfoSet = SetupDiGetClassDevs(
&GUID_DEVCLASS_PORTS,
nullptr,
nullptr,
DIGCF_PRESENT
);
if (deviceInfoSet == INVALID_HANDLE_VALUE)
return ports;
SP_DEVINFO_DATA devInfo;
devInfo.cbSize = sizeof(SP_DEVINFO_DATA);
for (DWORD i = 0; SetupDiEnumDeviceInfo(deviceInfoSet, i, &devInfo); i++)
{
char desc[256] = {0};
SetupDiGetDeviceRegistryPropertyA(
deviceInfoSet,
&devInfo,
SPDRP_FRIENDLYNAME,
nullptr,
(PBYTE)desc,
sizeof(desc),
nullptr
);
// FriendlyName has the form "USB-SERIAL CH340 (COM3)"
std::string friendly(desc);
size_t begin = friendly.find("(COM");
size_t end = friendly.find(")");
if (begin != std::string::npos && end != std::string::npos)
{
UartDescriptor info;
info.port = friendly.substr(begin + 1, end - begin - 1); // "COM3"
info.description = friendly.substr(0, begin - 1); // Description without "(COM3)"
ports.push_back(info);
}
}
SetupDiDestroyDeviceInfoList(deviceInfoSet);
#else
for (const auto& entry : std::filesystem::directory_iterator("/dev/serial/by-id"))
{
UartDescriptor info;
info.description = entry.path().filename().string();
info.port = std::filesystem::read_symlink(entry.path()).string();
ports.push_back(info);
}
#endif
return ports;
}