-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathjuce_serialport_Windows.cpp
470 lines (434 loc) · 15.3 KB
/
juce_serialport_Windows.cpp
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//win32_SerialPort.cpp
//Serial Port classes in a Juce stylee, by graffiti
//see SerialPort.h for details
//
// Updated for current Juce API 8/1/13 Marc Lindahl
//
#include "../JuceLibraryCode/JuceHeader.h"
#if JUCE_WINDOWS
using namespace juce;
#include <windows.h>
#include <stdio.h>
#include "juce_serialport.h"
class CAutoHeapAlloc
{
public:
//Constructors / Destructors
CAutoHeapAlloc(HANDLE hHeap = GetProcessHeap(), DWORD dwHeapFreeFlags = 0) : m_pData(NULL),
m_hHeap(hHeap),
m_dwHeapFreeFlags(dwHeapFreeFlags)
{
}
BOOL Allocate(SIZE_T dwBytes, DWORD dwFlags = 0)
{
//Validate our parameters
jassert(m_pData == NULL);
m_pData = HeapAlloc(m_hHeap, dwFlags, dwBytes);
return (m_pData != NULL);
}
~CAutoHeapAlloc()
{
if (m_pData != NULL)
{
HeapFree(m_hHeap, m_dwHeapFreeFlags, m_pData);
m_pData = NULL;
}
}
//Methods
//Member variables
LPVOID m_pData;
HANDLE m_hHeap;
DWORD m_dwHeapFreeFlags;
};
StringPairArray SerialPort::getSerialPortPaths()
{
StringPairArray SerialPortPaths;
HKEY hSERIALCOMM;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM", 0, KEY_QUERY_VALUE, &hSERIALCOMM) == ERROR_SUCCESS)
{
//Get the max value name and max value lengths
DWORD dwMaxValueNameLen;
DWORD dwMaxValueLen;
DWORD dwQueryInfo = RegQueryInfoKey(hSERIALCOMM, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &dwMaxValueNameLen, &dwMaxValueLen, NULL, NULL);
if (dwQueryInfo == ERROR_SUCCESS)
{
DWORD dwMaxValueNameSizeInChars = dwMaxValueNameLen + 1; //Include space for the NULL terminator
DWORD dwMaxValueNameSizeInBytes = dwMaxValueNameSizeInChars * sizeof(TCHAR);
DWORD dwMaxValueDataSizeInChars = dwMaxValueLen / sizeof(TCHAR) + 1; //Include space for the NULL terminator
DWORD dwMaxValueDataSizeInBytes = dwMaxValueDataSizeInChars * sizeof(TCHAR);
//Allocate some space for the value name and value data
CAutoHeapAlloc valueName;
CAutoHeapAlloc valueData;
if (valueName.Allocate(dwMaxValueNameSizeInBytes) && valueData.Allocate(dwMaxValueDataSizeInBytes))
{
//Enumerate all the values underneath HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM
DWORD dwIndex = 0;
DWORD dwType;
DWORD dwValueNameSize = dwMaxValueNameSizeInChars;
DWORD dwDataSize = dwMaxValueDataSizeInBytes;
std::memset(valueName.m_pData, 0, dwMaxValueNameSizeInBytes);
std::memset(valueData.m_pData, 0, dwMaxValueDataSizeInBytes);
TCHAR* szValueName = static_cast<TCHAR*>(valueName.m_pData);
BYTE* byValue = static_cast<BYTE*>(valueData.m_pData);
LONG nEnum = RegEnumValue(hSERIALCOMM, dwIndex, szValueName, &dwValueNameSize, NULL, &dwType, byValue, &dwDataSize);
while (nEnum == ERROR_SUCCESS)
{
//If the value is of the correct type, then add it to the array
if (dwType == REG_SZ)
{
TCHAR* szPort = reinterpret_cast<TCHAR*>(byValue);
SerialPortPaths.set(szPort, String("\\\\.\\") + String(szPort));
}
//Prepare for the next time around
dwValueNameSize = dwMaxValueNameSizeInChars;
dwDataSize = dwMaxValueDataSizeInBytes;
std::memset(valueName.m_pData, 0, dwMaxValueNameSizeInBytes);
std::memset(valueData.m_pData, 0, dwMaxValueDataSizeInBytes);
++dwIndex;
nEnum = RegEnumValue(hSERIALCOMM, dwIndex, szValueName, &dwValueNameSize, NULL, &dwType, byValue, &dwDataSize);
}
}
else
SetLastError(ERROR_OUTOFMEMORY);
}
//Close the registry key now that we are finished with it
RegCloseKey(hSERIALCOMM);
if (dwQueryInfo != ERROR_SUCCESS)
SetLastError(dwQueryInfo);
}
return SerialPortPaths;
}
void SerialPort::close()
{
if (portHandle)
{
CloseHandle(portHandle);
portHandle = 0;
}
}
bool SerialPort::exists()
{
return portHandle ? true : false;
}
bool SerialPort::open (const String & newPortPath)
{
canceled = false;
portPath = newPortPath;
portHandle = CreateFile((const char*)portPath.toUTF8(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
if (portHandle == INVALID_HANDLE_VALUE)
{
//DBG_PRINTF((T("(SerialPort::open) CreateFile failed with error %d.\n"), GetLastError()));
portHandle = 0;
return false;
}
COMMTIMEOUTS commTimeout;
if (GetCommTimeouts(portHandle, &commTimeout))
{
commTimeout.ReadIntervalTimeout = MAXDWORD;
commTimeout.ReadTotalTimeoutConstant = 0;
commTimeout.ReadTotalTimeoutMultiplier = 0;
commTimeout.WriteTotalTimeoutConstant = 0;
commTimeout.WriteTotalTimeoutMultiplier = 0;
}
else
DebugLog ("SerialPort::open", "GetCommTimeouts error");
if (!SetCommTimeouts (portHandle, &commTimeout))
DebugLog ("SerialPort::open", "SetCommTimeouts error");
if (!SetCommMask (portHandle, EV_RXCHAR))
DebugLog ("SerialPort::open", "SetCommMask error");
return true;
}
void SerialPort::cancel ()
{
if (! canceled)
{
canceled = true;
// if (portHandle != nullptr)
// const auto result = CancelIoEx (portHandle, nullptr);
}
}
bool SerialPort::setConfig(const SerialPortConfig & config)
{
if (!portHandle)return false;
DCB dcb;
memset(&dcb, 0, sizeof(DCB));
dcb.DCBlength = sizeof(DCB);
dcb.fBinary = 1;
dcb.XonLim = 2048;
dcb.XoffLim = 512;
dcb.BaudRate = config.bps;
dcb.ByteSize = (BYTE)config.databits;
dcb.fParity = true;
switch (config.parity)
{
case SerialPortConfig::SERIALPORT_PARITY_ODD:
dcb.Parity = ODDPARITY;
break;
case SerialPortConfig::SERIALPORT_PARITY_EVEN:
dcb.Parity = EVENPARITY;
break;
case SerialPortConfig::SERIALPORT_PARITY_MARK:
dcb.Parity = MARKPARITY;
break;
case SerialPortConfig::SERIALPORT_PARITY_SPACE:
dcb.Parity = SPACEPARITY;
break;
case SerialPortConfig::SERIALPORT_PARITY_NONE:
default:
dcb.Parity = NOPARITY;
dcb.fParity = false;
break;
}
switch (config.stopbits)
{
case SerialPortConfig::STOPBITS_1:
default:
dcb.StopBits = ONESTOPBIT;
break;
case SerialPortConfig::STOPBITS_1ANDHALF:
dcb.StopBits = ONE5STOPBITS;
break;
case SerialPortConfig::STOPBITS_2:
dcb.StopBits = TWOSTOPBITS;
break;
}
switch (config.flowcontrol)
{
case SerialPortConfig::FLOWCONTROL_XONXOFF:
dcb.fOutxCtsFlow = 0;
dcb.fOutxDsrFlow = 0;
dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fOutX = 1;
dcb.fInX = 1;
dcb.fRtsControl = RTS_CONTROL_ENABLE;
break;
case SerialPortConfig::FLOWCONTROL_HARDWARE:
dcb.fOutxCtsFlow = 1;
dcb.fOutxDsrFlow = 1;
dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
dcb.fOutX = 0;
dcb.fInX = 0;
dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
break;
case SerialPortConfig::FLOWCONTROL_NONE:
default:
dcb.fOutxCtsFlow = 0;
dcb.fOutxDsrFlow = 0;
dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fOutX = 0;
dcb.fInX = 0;
dcb.fRtsControl = RTS_CONTROL_ENABLE;
break;
}
return (SetCommState(portHandle, &dcb) ? true : false);
}
bool SerialPort::getConfig(SerialPortConfig & config)
{
if (!portHandle)return false;
DCB dcb;
if (!GetCommState(portHandle, &dcb))
return false;
config.bps = dcb.BaudRate;
config.databits = dcb.ByteSize;
switch (dcb.Parity)
{
case ODDPARITY:
config.parity = SerialPortConfig::SERIALPORT_PARITY_ODD;
break;
case EVENPARITY:
config.parity = SerialPortConfig::SERIALPORT_PARITY_EVEN;
break;
case MARKPARITY:
config.parity = SerialPortConfig::SERIALPORT_PARITY_MARK;
break;
case SPACEPARITY:
config.parity = SerialPortConfig::SERIALPORT_PARITY_SPACE;
break;
case NOPARITY:
default:
config.parity = SerialPortConfig::SERIALPORT_PARITY_NONE;
break;
}
switch (dcb.StopBits)
{
case ONESTOPBIT:
default:
config.stopbits = SerialPortConfig::STOPBITS_1;
break;
case ONE5STOPBITS:
config.stopbits = SerialPortConfig::STOPBITS_1ANDHALF;
break;
case TWOSTOPBITS:
config.stopbits = SerialPortConfig::STOPBITS_2;
break;
}
if (dcb.fOutX && dcb.fInX)
config.flowcontrol = SerialPortConfig::FLOWCONTROL_XONXOFF;
else if ((dcb.fDtrControl == DTR_CONTROL_HANDSHAKE) && (dcb.fRtsControl == RTS_CONTROL_HANDSHAKE))
config.flowcontrol = SerialPortConfig::FLOWCONTROL_HARDWARE;
else
config.flowcontrol = SerialPortConfig::FLOWCONTROL_NONE;
return true;
}
/////////////////////////////////
// SerialPortInputStream
/////////////////////////////////
void SerialPortInputStream::run()
{
//port->DebugLog ("SerialPortInputStream::run", "starting");
DWORD dwEventMask = 0;
//overlapped structure for the wait
OVERLAPPED ov;
memset(&ov, 0, sizeof(ov));
ov.hEvent = CreateEvent(0, true, 0, 0);
bool ioPending = false;
//overlapped structure for the read
while (port && port->portHandle && !threadShouldExit())
{
if (!ioPending)
{
const auto wceReturn = WaitCommEvent (port->portHandle, &dwEventMask, &ov);
if (dwEventMask != 0 && !(dwEventMask & 0x400) && !(dwEventMask & 0x4) && !(dwEventMask & 0x1))
juce::Logger::outputDebugString (" dwEventMask: " + String::toHexString (dwEventMask));
if (wceReturn == 0 && GetLastError () != ERROR_IO_PENDING)
{
port->DebugLog ("SerialPortInputStream::run", "error" );
port->close ();
break;
}
}
ioPending = true;
DCB handleDCB;
auto success { GetCommState (port->portHandle, &handleDCB) };
if (success == 0 && GetLastError () == ERROR_BAD_COMMAND)
{
//port->DebugLog ("SerialPortInputStream::run", "[GetCommState failed - GetLastError () = " + juce::String::toHexString(GetLastError()) + "]");
port->close ();
break;
}
if (/*(dwEventMask & EV_RXCHAR) && */WAIT_OBJECT_0 == WaitForSingleObject(ov.hEvent, 100))
{
DWORD dwMask;
if (GetCommMask(port->portHandle, &dwMask))
{
OVERLAPPED ovRead;
memset (&ovRead, 0, sizeof (ovRead));
ovRead.hEvent = CreateEvent (0, true, 0, 0);
//if (dwMask & EV_RXCHAR)
{
DWORD bytesread = 0;
do
{
unsigned char c;
ResetEvent(ovRead.hEvent);
ReadFile(port->portHandle, &c, 1, &bytesread, &ovRead);
if (GetLastError () != ERROR_SUCCESS)
port->DebugLog("SerialPortInputStream::run", "[getLastError:" + String (GetLastError ()) + "]");
if (bytesread == 1)
{
const ScopedLock l(bufferCriticalSection);
buffer.ensureSize(bufferedbytes + 1);
buffer[bufferedbytes] = c;
bufferedbytes++;
if (notify == NOTIFY_ALWAYS || ((notify == NOTIFY_ON_CHAR) && (c == notifyChar)))
sendChangeMessage();
}
} while (bytesread);
}
CloseHandle (ovRead.hEvent);
ioPending = false;
}
ResetEvent(ov.hEvent);
}
}
CloseHandle(ov.hEvent);
//port->DebugLog ("SerialPortInputStream::run", "exiting");
}
void SerialPortInputStream::cancel ()
{
if (!port || port->portHandle == 0)
return;
port->cancel ();
}
int SerialPortInputStream::read(void *destBuffer, int maxBytesToRead)
{
if (!port || port->portHandle == 0)
return -1;
const ScopedLock l (bufferCriticalSection);
if (maxBytesToRead > bufferedbytes)maxBytesToRead = bufferedbytes;
memcpy (destBuffer, buffer.getData (), maxBytesToRead);
buffer.removeSection (0, maxBytesToRead);
bufferedbytes -= maxBytesToRead;
return maxBytesToRead;
}
/////////////////////////////////
// SerialPortOutputStream
/////////////////////////////////
void SerialPortOutputStream::run()
{
//port->DebugLog ("SerialPortOutputStream::run", "starting");
unsigned char tempbuffer[writeBufferSize];
OVERLAPPED ov;
memset(&ov, 0, sizeof(ov));
ov.hEvent = CreateEvent(0, true, 0, 0);
while (port && port->portHandle && !threadShouldExit())
{
if (!bufferedbytes)
triggerWrite.wait(100);
if (bufferedbytes)
{
DWORD byteswritten = 0;
bufferCriticalSection.enter ();
DWORD bytestowrite = bufferedbytes > writeBufferSize ? writeBufferSize : bufferedbytes;
memcpy (tempbuffer, buffer.getData (), bytestowrite);
bufferCriticalSection.exit ();
ResetEvent (ov.hEvent);
int iRet = WriteFile (port->portHandle, tempbuffer, bytestowrite, &byteswritten, &ov);
auto const lastError = GetLastError ();
if (lastError == ERROR_BAD_COMMAND)
{
port->DebugLog ("SerialPortOutputStream::run", "error");
port->close ();
break;
}
if (threadShouldExit () || (lastError != ERROR_SUCCESS && lastError != ERROR_IO_PENDING))
{
port->DebugLog ("SerialPortOutputStream::run", "[getLastError:" + String (lastError) + "]");
continue;
}
if (iRet == 0 && lastError == ERROR_IO_PENDING)
{
DWORD waitResult = WaitForSingleObject (ov.hEvent, 1000);
if (threadShouldExit () || waitResult != WAIT_OBJECT_0)
continue;
}
GetOverlappedResult (port->portHandle, &ov, &byteswritten, TRUE);
if (byteswritten)
{
const ScopedLock l (bufferCriticalSection);
buffer.removeSection (0, byteswritten);
bufferedbytes -= byteswritten;
}
}
}
CloseHandle(ov.hEvent);
//port->DebugLog ("SerialPortOutputStream::run", "starting");
}
void SerialPortOutputStream::cancel ()
{
if (!port || port->portHandle == 0)
return;
port->cancel ();
}
bool SerialPortOutputStream::write(const void *dataToWrite, size_t howManyBytes)
{
if (! port || port->portHandle == 0)
return false;
bufferCriticalSection.enter();
buffer.append(dataToWrite, howManyBytes);
bufferedbytes += (int)howManyBytes;
bufferCriticalSection.exit();
triggerWrite.signal();
return true;
}
#endif // JUCE_WIN