forked from scream3r/java-simple-serial-connector
-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathjssc.cpp
759 lines (727 loc) · 24.8 KB
/
jssc.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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
/* jSSC (Java Simple Serial Connector) - serial port communication library.
* © Alexey Sokolov (scream3r), 2010-2014.
*
* This file is part of jSSC.
*
* jSSC is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* jSSC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with jSSC. If not, see <http://www.gnu.org/licenses/>.
*
* If you use jSSC in public project you can inform me about this by e-mail,
* of course if you want it.
*
* e-mail: [email protected]
* web-site: http://scream3r.org | http://code.google.com/p/java-simple-serial-connector/
*/
#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
#include <jssc_SerialNativeInterface.h>
#include "version.h"
//#include <iostream>
#define MAX_PORT_NAME_STR_LEN 32
/*
* Get native library version
*/
JNIEXPORT jstring JNICALL Java_jssc_SerialNativeInterface_getNativeLibraryVersion(JNIEnv *env, jclass) {
return env->NewStringUTF(JSSC_VERSION);
}
/*
* Port opening.
*
* In 2.2.0 added useTIOCEXCL (not used in Windows, only for compatibility with _nix version)
*/
JNIEXPORT jlong JNICALL Java_jssc_SerialNativeInterface_openPort(JNIEnv *env, jobject, jstring portName, jboolean){
char prefix[] = "\\\\.\\";
const char* port = env->GetStringUTFChars(portName, JNI_FALSE);
//since 2.1.0 -> string concat fix
char portFullName[MAX_PORT_NAME_STR_LEN];
if(strlen(prefix) + strlen(port) + 1 > sizeof(portFullName)){
return (jlong)((HANDLE)jssc_SerialNativeInterface_ERR_PORT_NOT_FOUND);
}
strcpy_s(portFullName, prefix);
strcat_s(portFullName, port);
//<- since 2.1.0
HANDLE hComm = CreateFile(portFullName,
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
0);
env->ReleaseStringUTFChars(portName, port);
//since 2.3.0 ->
if(hComm != INVALID_HANDLE_VALUE){
DCB *dcb = new DCB();
if(!GetCommState(hComm, dcb)){
CloseHandle(hComm);//since 2.7.0
hComm = (HANDLE)jssc_SerialNativeInterface_ERR_INCORRECT_SERIAL_PORT;//(-4)Incorrect serial port
}
delete dcb;
}
else {
DWORD errorValue = GetLastError();
if(errorValue == ERROR_ACCESS_DENIED){
hComm = (HANDLE)jssc_SerialNativeInterface_ERR_PORT_BUSY;//(-1)Port busy
}
else if(errorValue == ERROR_FILE_NOT_FOUND){
hComm = (HANDLE)jssc_SerialNativeInterface_ERR_PORT_NOT_FOUND;//(-2)Port not found
}
}
//<- since 2.3.0
return (jlong)hComm;//since 2.4.0 changed to jlong
}
/*
* Setting serial port params.
*
* In 2.6.0 added flags (not used in Windows, only for compatibility with _nix version)
*/
JNIEXPORT jboolean JNICALL Java_jssc_SerialNativeInterface_setParams
(JNIEnv *, jobject, jlong portHandle, jint baudRate, jint byteSize, jint stopBits, jint parity, jboolean setRTS, jboolean setDTR, jint){
HANDLE hComm = (HANDLE)portHandle;
DCB *dcb = new DCB();
jboolean returnValue = JNI_FALSE;
if(GetCommState(hComm, dcb)){
dcb->BaudRate = static_cast<DWORD>(baudRate);
dcb->ByteSize = static_cast<BYTE>(byteSize);
dcb->StopBits = static_cast<BYTE>(stopBits);
dcb->Parity = static_cast<BYTE>(parity);
//since 0.8 ->
if(setRTS == JNI_TRUE){
dcb->fRtsControl = RTS_CONTROL_ENABLE;
}
else {
dcb->fRtsControl = RTS_CONTROL_DISABLE;
}
if(setDTR == JNI_TRUE){
dcb->fDtrControl = DTR_CONTROL_ENABLE;
}
else {
dcb->fDtrControl = DTR_CONTROL_DISABLE;
}
dcb->fOutxCtsFlow = FALSE;
dcb->fOutxDsrFlow = FALSE;
dcb->fDsrSensitivity = FALSE;
dcb->fTXContinueOnXoff = TRUE;
dcb->fOutX = FALSE;
dcb->fInX = FALSE;
dcb->fErrorChar = FALSE;
dcb->fNull = FALSE;
dcb->fAbortOnError = FALSE;
dcb->XonLim = 2048;
dcb->XoffLim = 512;
dcb->XonChar = (char)17; //DC1
dcb->XoffChar = (char)19; //DC3
//<- since 0.8
if(SetCommState(hComm, dcb)){
//since 2.1.0 -> timeouts set previously by another application should be cleared
COMMTIMEOUTS *lpCommTimeouts = new COMMTIMEOUTS();
lpCommTimeouts->ReadIntervalTimeout = 0;
lpCommTimeouts->ReadTotalTimeoutConstant = 0;
lpCommTimeouts->ReadTotalTimeoutMultiplier = 0;
lpCommTimeouts->WriteTotalTimeoutConstant = 0;
lpCommTimeouts->WriteTotalTimeoutMultiplier = 0;
if(SetCommTimeouts(hComm, lpCommTimeouts)){
returnValue = JNI_TRUE;
}
delete lpCommTimeouts;
//<- since 2.1.0
}
}
delete dcb;
return returnValue;
}
/*
* PurgeComm
*/
JNIEXPORT jboolean JNICALL Java_jssc_SerialNativeInterface_purgePort
(JNIEnv *, jobject, jlong portHandle, jint flags){
HANDLE hComm = (HANDLE)portHandle;
DWORD dwFlags = (DWORD)flags;
return (PurgeComm(hComm, dwFlags) ? JNI_TRUE : JNI_FALSE);
}
/*
* Port closing
*/
JNIEXPORT jboolean JNICALL Java_jssc_SerialNativeInterface_closePort
(JNIEnv *, jobject, jlong portHandle){
HANDLE hComm = (HANDLE)portHandle;
return (CloseHandle(hComm) ? JNI_TRUE : JNI_FALSE);
}
/*
* Set events mask
*/
JNIEXPORT jboolean JNICALL Java_jssc_SerialNativeInterface_setEventsMask
(JNIEnv *, jobject, jlong portHandle, jint mask){
HANDLE hComm = (HANDLE)portHandle;
DWORD dwEvtMask = (DWORD)mask;
return (SetCommMask(hComm, dwEvtMask) ? JNI_TRUE : JNI_FALSE);
}
/*
* Get events mask
*/
JNIEXPORT jint JNICALL Java_jssc_SerialNativeInterface_getEventsMask
(JNIEnv *, jobject, jlong portHandle){
HANDLE hComm = (HANDLE)portHandle;
DWORD lpEvtMask;
if(GetCommMask(hComm, &lpEvtMask)){
return (jint)lpEvtMask;
}
else {
return -1;
}
}
/*
* Change RTS line state (ON || OFF)
*/
JNIEXPORT jboolean JNICALL Java_jssc_SerialNativeInterface_setRTS
(JNIEnv *, jobject, jlong portHandle, jboolean enabled){
HANDLE hComm = (HANDLE)portHandle;
if(enabled == JNI_TRUE){
return (EscapeCommFunction(hComm, SETRTS) ? JNI_TRUE : JNI_FALSE);
}
else {
return (EscapeCommFunction(hComm, CLRRTS) ? JNI_TRUE : JNI_FALSE);
}
}
/*
* Change DTR line state (ON || OFF)
*/
JNIEXPORT jboolean JNICALL Java_jssc_SerialNativeInterface_setDTR
(JNIEnv *, jobject, jlong portHandle, jboolean enabled){
HANDLE hComm = (HANDLE)portHandle;
if(enabled == JNI_TRUE){
return (EscapeCommFunction(hComm, SETDTR) ? JNI_TRUE : JNI_FALSE);
}
else {
return (EscapeCommFunction(hComm, CLRDTR) ? JNI_TRUE : JNI_FALSE);
}
}
/*
* Write data to port
* portHandle - port handle
* buffer - byte array for sending
*/
JNIEXPORT jboolean JNICALL Java_jssc_SerialNativeInterface_writeBytes
(JNIEnv *env, jobject, jlong portHandle, jbyteArray buffer){
HANDLE hComm = (HANDLE)portHandle;
DWORD lpNumberOfBytesTransferred;
DWORD lpNumberOfBytesWritten;
jboolean returnValue = JNI_FALSE;
if( buffer == NULL ){
jclass exClz = env->FindClass("java/lang/NullPointerException");
if( exClz != NULL ) env->ThrowNew(exClz, "buffer");
return 0;
}
jbyte* jBuffer = env->GetByteArrayElements(buffer, JNI_FALSE);
if( jBuffer == NULL ){
jclass exClz = env->FindClass("java/lang/RuntimeException");
if( exClz != NULL ) env->ThrowNew(exClz, "jni->GetByteArrayElements() failed");
return 0;
}
OVERLAPPED *overlapped = new OVERLAPPED();
overlapped->hEvent = CreateEventA(NULL, true, false, NULL);
if(WriteFile(hComm, jBuffer, (DWORD)env->GetArrayLength(buffer), &lpNumberOfBytesWritten, overlapped)){
returnValue = JNI_TRUE;
}
else if(GetLastError() == ERROR_IO_PENDING){
if(WaitForSingleObject(overlapped->hEvent, INFINITE) == WAIT_OBJECT_0){
if(GetOverlappedResult(hComm, overlapped, &lpNumberOfBytesTransferred, false)){
returnValue = JNI_TRUE;
}
}
}
env->ReleaseByteArrayElements(buffer, jBuffer, 0);
CloseHandle(overlapped->hEvent);
delete overlapped;
return returnValue;
}
/*
* Read data from port
* portHandle - port handle
* byteCount - count of bytes for reading
*/
JNIEXPORT jbyteArray JNICALL Java_jssc_SerialNativeInterface_readBytes
(JNIEnv *env, jobject, jlong portHandle, jint byteCount){
HANDLE hComm = (HANDLE)portHandle;
DWORD lpNumberOfBytesTransferred;
DWORD lpNumberOfBytesRead;
jbyte *lpBuffer = NULL;
jbyteArray returnArray = env->NewByteArray(byteCount);
lpBuffer = (jbyte *)malloc(byteCount * sizeof(jbyte));
if(lpBuffer == NULL){
// return an empty array
return returnArray;
}
OVERLAPPED *overlapped = new OVERLAPPED();
overlapped->hEvent = CreateEventA(NULL, true, false, NULL);
if(ReadFile(hComm, lpBuffer, (DWORD)byteCount, &lpNumberOfBytesRead, overlapped)){
env->SetByteArrayRegion(returnArray, 0, byteCount, lpBuffer);
}
else if(GetLastError() == ERROR_IO_PENDING){
if(WaitForSingleObject(overlapped->hEvent, INFINITE) == WAIT_OBJECT_0){
if(GetOverlappedResult(hComm, overlapped, &lpNumberOfBytesTransferred, false)){
env->SetByteArrayRegion(returnArray, 0, byteCount, lpBuffer);
}
}
}
else if(GetLastError() == ERROR_INVALID_HANDLE){
jclass exClz = env->FindClass("java/lang/IllegalArgumentException");
if( exClz != NULL ) env->ThrowNew(exClz, "EBADF");
}
CloseHandle(overlapped->hEvent);
delete overlapped;
free(lpBuffer);
return returnArray;
}
/*
* Get bytes count in serial port buffers (Input and Output)
*/
JNIEXPORT jintArray JNICALL Java_jssc_SerialNativeInterface_getBuffersBytesCount
(JNIEnv *env, jobject, jlong portHandle){
HANDLE hComm = (HANDLE)portHandle;
jint returnValues[2];
returnValues[0] = -1;
returnValues[1] = -1;
jintArray returnArray = env->NewIntArray(2);
DWORD lpErrors;
COMSTAT *comstat = new COMSTAT();
if(ClearCommError(hComm, &lpErrors, comstat)){
returnValues[0] = (jint)comstat->cbInQue;
returnValues[1] = (jint)comstat->cbOutQue;
}
else {
returnValues[0] = -1;
returnValues[1] = -1;
}
delete comstat;
env->SetIntArrayRegion(returnArray, 0, 2, returnValues);
return returnArray;
}
//since 0.8 ->
const jint FLOWCONTROL_NONE = 0;
const jint FLOWCONTROL_RTSCTS_IN = 1;
const jint FLOWCONTROL_RTSCTS_OUT = 2;
const jint FLOWCONTROL_XONXOFF_IN = 4;
const jint FLOWCONTROL_XONXOFF_OUT = 8;
//<- since 0.8
/*
* Setting flow control mode
*
* since 0.8
*/
JNIEXPORT jboolean JNICALL Java_jssc_SerialNativeInterface_setFlowControlMode
(JNIEnv *, jobject, jlong portHandle, jint mask){
HANDLE hComm = (HANDLE)portHandle;
jboolean returnValue = JNI_FALSE;
DCB *dcb = new DCB();
if(GetCommState(hComm, dcb)){
dcb->fRtsControl = RTS_CONTROL_ENABLE;
dcb->fOutxCtsFlow = FALSE;
dcb->fOutX = FALSE;
dcb->fInX = FALSE;
if(mask != FLOWCONTROL_NONE){
if((mask & FLOWCONTROL_RTSCTS_IN) == FLOWCONTROL_RTSCTS_IN){
dcb->fRtsControl = RTS_CONTROL_HANDSHAKE;
}
if((mask & FLOWCONTROL_RTSCTS_OUT) == FLOWCONTROL_RTSCTS_OUT){
dcb->fOutxCtsFlow = TRUE;
}
if((mask & FLOWCONTROL_XONXOFF_IN) == FLOWCONTROL_XONXOFF_IN){
dcb->fInX = TRUE;
}
if((mask & FLOWCONTROL_XONXOFF_OUT) == FLOWCONTROL_XONXOFF_OUT){
dcb->fOutX = TRUE;
}
}
if(SetCommState(hComm, dcb)){
returnValue = JNI_TRUE;
}
}
delete dcb;
return returnValue;
}
/*
* Getting flow control mode
*
* since 0.8
*/
JNIEXPORT jint JNICALL Java_jssc_SerialNativeInterface_getFlowControlMode
(JNIEnv *, jobject, jlong portHandle){
HANDLE hComm = (HANDLE)portHandle;
jint returnValue = 0;
DCB *dcb = new DCB();
if(GetCommState(hComm, dcb)){
if(dcb->fRtsControl == RTS_CONTROL_HANDSHAKE){
returnValue |= FLOWCONTROL_RTSCTS_IN;
}
if(dcb->fOutxCtsFlow == TRUE){
returnValue |= FLOWCONTROL_RTSCTS_OUT;
}
if(dcb->fInX == TRUE){
returnValue |= FLOWCONTROL_XONXOFF_IN;
}
if(dcb->fOutX == TRUE){
returnValue |= FLOWCONTROL_XONXOFF_OUT;
}
}
delete dcb;
return returnValue;
}
/*
* Send break for set duration
*
* since 0.8
*/
JNIEXPORT jboolean JNICALL Java_jssc_SerialNativeInterface_sendBreak
(JNIEnv *, jobject, jlong portHandle, jint duration){
HANDLE hComm = (HANDLE)portHandle;
jboolean returnValue = JNI_FALSE;
if(duration > 0){
if(SetCommBreak(hComm) > 0){
Sleep(duration);
if(ClearCommBreak(hComm) > 0){
returnValue = JNI_TRUE;
}
}
}
return returnValue;
}
/*
* Wait event
* portHandle - port handle
*/
JNIEXPORT jobjectArray JNICALL Java_jssc_SerialNativeInterface_waitEvents
(JNIEnv *env, jobject, jlong portHandle) {
HANDLE hComm = (HANDLE)portHandle;
DWORD lpEvtMask = 0;
DWORD lpNumberOfBytesTransferred = 0;
OVERLAPPED *overlapped = new OVERLAPPED();
jclass intClass = env->FindClass("[I");
jobjectArray returnArray;
boolean functionSuccessful = false;
overlapped->hEvent = CreateEventA(NULL, true, false, NULL);
if(WaitCommEvent(hComm, &lpEvtMask, overlapped)){
functionSuccessful = true;
}
else if(GetLastError() == ERROR_IO_PENDING){
if(WaitForSingleObject(overlapped->hEvent, INFINITE) == WAIT_OBJECT_0){
if(GetOverlappedResult(hComm, overlapped, &lpNumberOfBytesTransferred, false)){
functionSuccessful = true;
}
}
}
if(functionSuccessful){
boolean executeGetCommModemStatus = false;
boolean executeClearCommError = false;
DWORD events[9];//fixed since 0.8 (old value is 8)
jint eventsCount = 0;
if((EV_BREAK & lpEvtMask) == EV_BREAK){
events[eventsCount] = EV_BREAK;
eventsCount++;
}
if((EV_CTS & lpEvtMask) == EV_CTS){
events[eventsCount] = EV_CTS;
eventsCount++;
executeGetCommModemStatus = true;
}
if((EV_DSR & lpEvtMask) == EV_DSR){
events[eventsCount] = EV_DSR;
eventsCount++;
executeGetCommModemStatus = true;
}
if((EV_ERR & lpEvtMask) == EV_ERR){
events[eventsCount] = EV_ERR;
eventsCount++;
executeClearCommError = true;
}
if((EV_RING & lpEvtMask) == EV_RING){
events[eventsCount] = EV_RING;
eventsCount++;
executeGetCommModemStatus = true;
}
if((EV_RLSD & lpEvtMask) == EV_RLSD){
events[eventsCount] = EV_RLSD;
eventsCount++;
executeGetCommModemStatus = true;
}
if((EV_RXCHAR & lpEvtMask) == EV_RXCHAR){
events[eventsCount] = EV_RXCHAR;
eventsCount++;
executeClearCommError = true;
}
if((EV_RXFLAG & lpEvtMask) == EV_RXFLAG){
events[eventsCount] = EV_RXFLAG;
eventsCount++;
executeClearCommError = true;
}
if((EV_TXEMPTY & lpEvtMask) == EV_TXEMPTY){
events[eventsCount] = EV_TXEMPTY;
eventsCount++;
executeClearCommError = true;
}
/*
* Execute GetCommModemStatus function if it's needed (get lines status)
*/
jint statusCTS = 0;
jint statusDSR = 0;
jint statusRING = 0;
jint statusRLSD = 0;
boolean successGetCommModemStatus = false;
if(executeGetCommModemStatus){
DWORD lpModemStat;
if(GetCommModemStatus(hComm, &lpModemStat)){
successGetCommModemStatus = true;
if((MS_CTS_ON & lpModemStat) == MS_CTS_ON){
statusCTS = 1;
}
if((MS_DSR_ON & lpModemStat) == MS_DSR_ON){
statusDSR = 1;
}
if((MS_RING_ON & lpModemStat) == MS_RING_ON){
statusRING = 1;
}
if((MS_RLSD_ON & lpModemStat) == MS_RLSD_ON){
statusRLSD = 1;
}
}
else {
jint lastError = (jint)GetLastError();
statusCTS = lastError;
statusDSR = lastError;
statusRING = lastError;
statusRLSD = lastError;
}
}
/*
* Execute ClearCommError function if it's needed (get count of bytes in buffers and errors)
*/
jint bytesCountIn = 0;
jint bytesCountOut = 0;
jint communicationsErrors = 0;
boolean successClearCommError = false;
if(executeClearCommError){
DWORD lpErrors;
COMSTAT *comstat = new COMSTAT();
if(ClearCommError(hComm, &lpErrors, comstat)){
successClearCommError = true;
bytesCountIn = (jint)comstat->cbInQue;
bytesCountOut = (jint)comstat->cbOutQue;
communicationsErrors = (jint)lpErrors;
}
else {
jint lastError = (jint)GetLastError();
bytesCountIn = lastError;
bytesCountOut = lastError;
communicationsErrors = lastError;
}
delete comstat;
}
/*
* Create int[][] for events values
*/
returnArray = env->NewObjectArray(eventsCount, intClass, NULL);
/*
* Set events values
*/
for(jint i = 0; i < eventsCount; i++){
jint returnValues[2];
switch(events[i]){
case EV_BREAK:
returnValues[0] = (jint)events[i];
returnValues[1] = 0;
goto forEnd;
case EV_CTS:
returnValues[1] = statusCTS;
goto modemStatus;
case EV_DSR:
returnValues[1] = statusDSR;
goto modemStatus;
case EV_ERR:
returnValues[1] = communicationsErrors;
goto bytesAndErrors;
case EV_RING:
returnValues[1] = statusRING;
goto modemStatus;
case EV_RLSD:
returnValues[1] = statusRLSD;
goto modemStatus;
case EV_RXCHAR:
returnValues[1] = bytesCountIn;
goto bytesAndErrors;
case EV_RXFLAG:
returnValues[1] = bytesCountIn;
goto bytesAndErrors;
case EV_TXEMPTY:
returnValues[1] = bytesCountOut;
goto bytesAndErrors;
default:
returnValues[0] = (jint)events[i];
returnValues[1] = 0;
goto forEnd;
};
modemStatus: {
if(successGetCommModemStatus){
returnValues[0] = (jint)events[i];
}
else {
returnValues[0] = -1;
}
goto forEnd;
}
bytesAndErrors: {
if(successClearCommError){
returnValues[0] = (jint)events[i];
}
else {
returnValues[0] = -1;
}
goto forEnd;
}
forEnd: {
jintArray singleResultArray = env->NewIntArray(2);
env->SetIntArrayRegion(singleResultArray, 0, 2, returnValues);
env->SetObjectArrayElement(returnArray, i, singleResultArray);
};
}
}
else {
returnArray = env->NewObjectArray(1, intClass, NULL);
jint returnValues[2];
returnValues[0] = -1;
returnValues[1] = (jint)GetLastError();
jintArray singleResultArray = env->NewIntArray(2);
env->SetIntArrayRegion(singleResultArray, 0, 2, returnValues);
env->SetObjectArrayElement(returnArray, 0, singleResultArray);
};
CloseHandle(overlapped->hEvent);
delete overlapped;
return returnArray;
}
/*
* Get serial port names
*/
JNIEXPORT jobjectArray JNICALL Java_jssc_SerialNativeInterface_getSerialPortNames
(JNIEnv *env, jobject){
HKEY phkResult = NULL;
LPCSTR lpSubKey = "HARDWARE\\DEVICEMAP\\SERIALCOMM\\";
jobjectArray returnArray = NULL;
byte lpDataOnStack[256];
byte *lpData = lpDataOnStack;
DWORD lpData_capacity = 256;
char valueName[256];
DWORD valueNameSize;
DWORD enumResult;
boolean hasMoreElements = true;
DWORD keysCount = 0;
if(RegOpenKeyExA(HKEY_LOCAL_MACHINE, lpSubKey, 0, KEY_READ, &phkResult) != ERROR_SUCCESS){
returnArray = NULL;
goto Finally;
}
/* Iterate a 1st time to see how long our resulting array has to be. */
while(hasMoreElements){
valueNameSize = 256;
enumResult = RegEnumValueA(phkResult, keysCount, valueName, &valueNameSize, NULL, NULL, NULL, NULL);
if(enumResult == ERROR_SUCCESS){
keysCount++;
}
else if(enumResult == ERROR_NO_MORE_ITEMS){
hasMoreElements = false;
}
else {
hasMoreElements = false;
}
}
if(keysCount > 0){
jclass stringClass = env->FindClass("java/lang/String");
returnArray = env->NewObjectArray((jsize)keysCount, stringClass, NULL);
DWORD lpcbData;
DWORD result;
/* iterate 2nd time but this time our array is ready to catch results. */
for(DWORD i = 0; i < keysCount; i++){
valueNameSize = 256;
lpcbData = lpData_capacity;
result = RegEnumValueA(phkResult, i, valueName, &valueNameSize, NULL, NULL, lpData, &lpcbData);
if(result == ERROR_SUCCESS){
env->SetObjectArrayElement(returnArray, i, env->NewStringUTF((char*)lpData));
}else if(result == ERROR_MORE_DATA && lpData_capacity < UINT_MAX){
/* whops our supplied buffer was not large enough. Fallback to a heap
* allocd one. RegEnumValueA was kind enough to set 'lpcbData' to the
* required length before return. */
lpData = (lpData == lpDataOnStack) ? NULL : lpData;
/* MS doc is unclear to me if returned size includes the required
* zero-term. So to stay safe, we provide one byte more. */
if(lpcbData < UINT_MAX) lpcbData += 1;
byte *tmp = (byte*)realloc(lpData, lpcbData*sizeof*tmp);
if(tmp == NULL){
jclass exClz = env->FindClass("java/lang/OutOfMemoryError");
if(exClz != NULL) env->ThrowNew(exClz, NULL);
returnArray = NULL;
goto Finally;
}
/* install new buffer and reset 'i' so we try the same element again. */
lpData_capacity = lpcbData;
lpData = tmp;
i -= 1;
}else{
char exMsg[128];
snprintf(exMsg, sizeof exMsg, "RegEnumValueA(): Code %ld: "
"https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes#system-error-codes",
result);
jclass exClz = env->FindClass("java/lang/RuntimeException");
if(exClz != NULL) env->ThrowNew(exClz, exMsg);
returnArray = NULL;
goto Finally;
}
}
}
Finally:
if(lpData != NULL && lpData != lpDataOnStack) free(lpData);
if(phkResult != NULL) CloseHandle(phkResult);
return returnArray;
}
/*
* Get lines status
*
* returnValues[0] - CTS
* returnValues[1] - DSR
* returnValues[2] - RING
* returnValues[3] - RLSD
*
*/
JNIEXPORT jintArray JNICALL Java_jssc_SerialNativeInterface_getLinesStatus
(JNIEnv *env, jobject, jlong portHandle){
HANDLE hComm = (HANDLE)portHandle;
DWORD lpModemStat;
jint returnValues[4];
for(jint i = 0; i < 4; i++){
returnValues[i] = 0;
}
jintArray returnArray = env->NewIntArray(4);
if(GetCommModemStatus(hComm, &lpModemStat)){
if((MS_CTS_ON & lpModemStat) == MS_CTS_ON){
returnValues[0] = 1;
}
if((MS_DSR_ON & lpModemStat) == MS_DSR_ON){
returnValues[1] = 1;
}
if((MS_RING_ON & lpModemStat) == MS_RING_ON){
returnValues[2] = 1;
}
if((MS_RLSD_ON & lpModemStat) == MS_RLSD_ON){
returnValues[3] = 1;
}
}
env->SetIntArrayRegion(returnArray, 0, 4, returnValues);
return returnArray;
}