-
Notifications
You must be signed in to change notification settings - Fork 22
/
SerialPortApi.cpp
432 lines (393 loc) · 9.45 KB
/
SerialPortApi.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
#include "StdAfx.h"
#include "SerialPortApi.h"
CSerialPortApi::CSerialPortApi(void)
{
m_hCom = INVALID_HANDLE_VALUE;
PortNum = 0;
b_portIsOpen = FALSE;
ReceiveFlag = FALSE;
m_hSendEvent = CreateEvent(
NULL, // no security attributes
TRUE, // manual-reset event
FALSE, // initial state is nosignaled
NULL // object name
);
// if(m_hSendEvent==NULL)
// return false;
Str4Send = NULL;
getExistPort();
}
CSerialPortApi::~CSerialPortApi(void)
{
}
void CSerialPortApi::getExistPort()
{
PortNum = 0;
CString str;
HKEY hKey;
str=_T("HARDWARE\\DEVICEMAP\\SERIALCOMM");
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, str,0,KEY_ALL_ACCESS, &hKey) != ERROR_SUCCESS)
{
RegCloseKey( hKey );
return;
}
TCHAR achClass[MAX_PATH] = _T(""); // buffer for class name
DWORD cchClassName = MAX_PATH; // size of class string
DWORD cSubKeys; // number of subkeys
DWORD cbMaxSubKey; // longest subkey size
DWORD cchMaxClass; // longest class string
DWORD cValues; // number of values for key
DWORD cchMaxValue; // longest value name
DWORD cbMaxValueData; // longest value data
DWORD cbSecurityDescriptor; // size of security descriptor
FILETIME ftLastWriteTime; // last write time
TCHAR achValue[MAX_PATH];
DWORD cchValue = MAX_PATH;
BYTE achBuff[80];
DWORD chValue = 60;
DWORD type = REG_SZ;
// Get the class name and the value count.
if(RegQueryInfoKey(hKey, // key handle
achClass, // buffer for class name
&cchClassName, // size of class string
NULL, // reserved
&cSubKeys, // number of subkeys
&cbMaxSubKey, // longest subkey size
&cchMaxClass, // longest class string
&cValues, // number of values for this key
&cchMaxValue, // longest value name
&cbMaxValueData, // longest value data
&cbSecurityDescriptor, // security descriptor
&ftLastWriteTime)!=ERROR_SUCCESS) // last write time
{
RegCloseKey( hKey );
return;
}
if (cValues)
{
for (DWORD j = 0, retValue = ERROR_SUCCESS;
j < cValues; j++)
{
chValue = 60;
cchValue = 60;
retValue = RegEnumValue(hKey, j, achValue,
&cchValue,
NULL,
&type, // &dwType,
achBuff, // &bData,
&chValue); // &bcData
if(retValue == ERROR_SUCCESS)
{
PortList[PortNum++] = (LPTSTR)(achBuff);
}
}
}
RegCloseKey( hKey );
return;
}
INT CSerialPortApi::OpenPort( CString sPort,DWORD dwBaudRate,BYTE byDataBits,BYTE byParity,BYTE byStopBits )
{
if(!IsPortValid(sPort)) return PORT_NUM_INVALID;
if(!IsBaudrateValid(dwBaudRate)) return BAUDRATE_INVALID;
if(!IsDataBitValid(byDataBits)) return DATABITS_INVALID;
if(!IsParityValid(byParity)) return PARITY_INVALID;
if(!IsStopbitValid(byStopBits)) return STOPBIT_INVALID;
m_hCom = m_port.OpenPort(sPort,dwBaudRate,byDataBits,byParity,byStopBits);
if(m_hCom != INVALID_HANDLE_VALUE)
{
b_portIsOpen = TRUE;
AfxBeginThread(SendThreadProc,this,THREAD_PRIORITY_NORMAL,0,0,NULL);
AfxBeginThread(RevThreadProc,this,THREAD_PRIORITY_NORMAL,0,0,NULL);
return OPEN_PORT_SUCCESS;
}
else
{
if(PORT_DEBUG_MODE)
{
CString str = m_port.GetError();
AfxMessageBox(str);
}
return OPEN_PORT_FAIL;
}
}
BOOL CSerialPortApi::IsPortValid( CString sCom )
{
for(size_t i = 0;i < PortNum;i++)
{
if(PortList[i].Compare(sCom)==0)
return TRUE;
}
if(PORT_DEBUG_MODE)
{
CString str;
str.Format("Port Num(%s) is Invalid!",sCom);
AfxMessageBox(str);
}
return FALSE;
}
size_t CSerialPortApi::GetPortNum()
{
return PortNum;
}
BOOL CSerialPortApi::IsBaudrateValid( DWORD dwBaudRate )
{
for(size_t i = 0;i < sizeof BAUDRATE;i++)
{
if(BAUDRATE[i] == dwBaudRate)
return TRUE;
}
if(PORT_DEBUG_MODE)
{
CString str;
str.Format("Baud rate(%d) is Invalid!",dwBaudRate);
AfxMessageBox(str);
}
return FALSE;
}
BOOL CSerialPortApi::IsDataBitValid( BYTE byDataBits )
{
if(byDataBits == 6 || byDataBits == 7 || byDataBits == 8)
return TRUE;
if(PORT_DEBUG_MODE)
{
CString str;
str.Format("Data bits(%d) is Invalid!",byDataBits);
AfxMessageBox(str);
}
return FALSE;
}
BOOL CSerialPortApi::IsParityValid( BYTE byParity )
{
for(size_t i = 0;i < sizeof PARITY;i++)
{
if(PARITY[i] == byParity)
return TRUE;
}
if(PORT_DEBUG_MODE)
{
CString str;
str.Format("Parity bit(%d) is Invalid!",byParity);
AfxMessageBox(str);
}
return FALSE;
}
BOOL CSerialPortApi::IsStopbitValid( BYTE byStopBits )
{
for(size_t i = 0;i < sizeof STOPBITS;i++)
{
if(STOPBITS[i] == byStopBits)
return TRUE;
}
if(PORT_DEBUG_MODE)
{
CString str;
str.Format("Stop bit(%d) is Invalid!",byStopBits);
AfxMessageBox(str);
}
return FALSE;
}
void CSerialPortApi::Send( CString str )
{
mSendLength = str.GetLength();
if(!Str4Send)
Str4Send = new uchar[mSendLength];
char* temp = str.GetBuffer();
for(size_t i = 0;i < mSendLength;i++)
{
Str4Send[i] = temp[i];
}
SetEvent(m_hSendEvent);
}
void CSerialPortApi::Send( uchar str[], size_t SendLength)
{
if(!Str4Send)
Str4Send = new uchar[SendLength];
for(size_t i = 0;i < SendLength;i++)
{
Str4Send[i] = str[i];
}
mSendLength = SendLength;
SetEvent(m_hSendEvent);
}
UINT CSerialPortApi::SendThreadProc(LPVOID pParam)
{
CSerialPortApi *capi = (CSerialPortApi *)pParam;
HANDLE hEvent = 0;
OVERLAPPED overlapped;
memset(&overlapped,0,sizeof(OVERLAPPED));
DWORD dwWrite = 0;
static _SEND send;
hEvent = CreateEvent(
NULL, // no security attributes
TRUE, // manual-reset event
FALSE, // initial state is nosignaled
NULL // object name
);
overlapped.hEvent = hEvent;
while(capi->b_portIsOpen)
{
::WaitForSingleObject(capi->m_hSendEvent,0xFFFFFFFF);
::ResetEvent(capi->m_hSendEvent);
if(capi->m_hCom==INVALID_HANDLE_VALUE)
return 0;
WriteFile(capi->m_hCom,capi->Str4Send,capi->mSendLength,&dwWrite,&overlapped);
}
return 0;
}
UINT CSerialPortApi::RevThreadProc(LPVOID pParam)
{
HANDLE h_gEvent;
DWORD dwBytesRead;
OVERLAPPED Overlapped;
CSerialPortApi *capi = (CSerialPortApi *)pParam;
BOOL bReadStatus = FALSE;
dwBytesRead = 0;
memset(&Overlapped,0,sizeof(OVERLAPPED));
h_gEvent = NULL;
h_gEvent = CreateEvent(
NULL,
TRUE, //手工设置事件有无信号
FALSE, //初始化事件为无信号状态
NULL
);
if(h_gEvent == NULL) return 0;
Overlapped.hEvent = h_gEvent;
BYTE data[BUFSIZE];
ZeroMemory(data,BUFSIZE);
DWORD dwEvtMask=0;
GetCommMask(capi->m_hCom,&dwEvtMask);
dwEvtMask |= EV_RXCHAR;
SetCommMask(capi->m_hCom,dwEvtMask);
while(capi->b_portIsOpen)
{
WaitCommEvent(capi->m_hCom,&dwEvtMask,NULL);
if(capi->m_hCom==INVALID_HANDLE_VALUE)
return 0;
if ((dwEvtMask & EV_RXCHAR) == EV_RXCHAR){
COMSTAT ComStat ;
DWORD dwLength,dwErrorFlags;
ClearCommError(capi->m_hCom, &dwErrorFlags, &ComStat ) ;
dwLength = ComStat.cbInQue ; //输入缓冲区有多少数据?
if (dwLength > 0){
bReadStatus = ReadFile( capi->m_hCom, data,dwLength, &dwBytesRead, &Overlapped); //读数据
if(!bReadStatus)
{
if(GetLastError()==ERROR_IO_PENDING)
{
while(!GetOverlappedResult(capi->m_hCom, &Overlapped, &dwBytesRead, TRUE ))
{
if(GetLastError() == ERROR_IO_INCOMPLETE)
continue;
}
capi->m_bRevCS.Lock();
for(unsigned int i = 0;i<dwBytesRead;i++)
{
capi->m_dequeRevData.push_back(data[i]);
}
capi->ReceiveFlag = TRUE;
capi->m_bRevCS.Unlock();
}
}
else
{
capi->m_bRevCS.Lock();
for(unsigned int i = 0;i<dwLength;i++)
{
capi->m_dequeRevData.push_back(data[i]);
}
capi->ReceiveFlag = TRUE;
capi->m_bRevCS.Unlock();
}
}
}
}
return 0;
}
CString CSerialPortApi::ReadRecv()
{
if(!ReceiveFlag)
return "";
CString str,strTemp;
str.Empty();
m_bRevCS.Lock();
while(m_dequeRevData.size() != 0)
{
strTemp.Format(_T("%c"),m_dequeRevData[0]);
m_dequeRevData.pop_front();
str += strTemp;
}
ReceiveFlag = FALSE;
m_bRevCS.Unlock();
return str;
}
INT CSerialPortApi::ClosePort()
{
if(m_hCom == INVALID_HANDLE_VALUE)
return CLOSE_PORT_SUCCESS;
b_portIsOpen = FALSE;
if(m_port.ClosePort())
{
m_hCom = INVALID_HANDLE_VALUE;
::SetEvent(m_hSendEvent);
/*调用串口记得KillTimer*/
return CLOSE_PORT_SUCCESS;
}
return CLOSR_PORT_FAIL;
}
CString CSerialPortApi::ErrorMsg()
{
return m_port.GetError();
}
deque<BYTE> CSerialPortApi::ReadRecvByte()
{
deque<BYTE> result;
if(!ReceiveFlag)
return result;
m_bRevCS.Lock();
while(m_dequeRevData.size() != 0)
{
result.push_back(m_dequeRevData[0]);
m_dequeRevData.pop_front();
}
ReceiveFlag = FALSE;
m_bRevCS.Unlock();
return result;
}
vector<CString> CSerialPortApi::ReadRecvByteSplite(char ch)
{
vector<CString> result;
CString str_temp = "";
if(!ReceiveFlag)
return result;
m_bRevCS.Lock();
while(m_dequeRevData.size() != 0)
{
int lineflag = 0;
for (deque<BYTE>::iterator iter = m_dequeRevData.begin();iter!=m_dequeRevData.end();iter++)
{
if(*iter == ch)
{
lineflag = 1;
break;
}
}
if(!lineflag)
break;
else
{
int endflag = 1;
while(endflag)
{
str_temp += m_dequeRevData[0];
if(m_dequeRevData[0] == ch)
endflag = 0;
m_dequeRevData.pop_front();
}
result.push_back(str_temp);
str_temp.Empty();
}
}
ReceiveFlag = FALSE;
m_bRevCS.Unlock();
return result;
}