/
SerialImp.c
6318 lines (5669 loc) · 175 KB
/
SerialImp.c
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
| RXTX License v 2.1 - LGPL v 2.1 + Linking Over Controlled Interface.
| RXTX is a native interface to serial ports in java.
| Copyright 1997-2009 by Trent Jarvi tjarvi@qbang.org and others who
| actually wrote it. See individual source files for more information.
|
| A copy of the LGPL v 2.1 may be found at
| http://www.gnu.org/licenses/lgpl.txt on March 4th 2007. A copy is
| here for your convenience.
|
| This library 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 2.1 of the License, or (at your option) any later version.
|
| This library 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.
|
| An executable that contains no derivative of any portion of RXTX, but
| is designed to work with RXTX by being dynamically linked with it,
| is considered a "work that uses the Library" subject to the terms and
| conditions of the GNU Lesser General Public License.
|
| The following has been added to the RXTX License to remove
| any confusion about linking to RXTX. We want to allow in part what
| section 5, paragraph 2 of the LGPL does not permit in the special
| case of linking over a controlled interface. The intent is to add a
| Java Specification Request or standards body defined interface in the
| future as another exception but one is not currently available.
|
| http://www.fsf.org/licenses/gpl-faq.html#LinkingOverControlledInterface
|
| As a special exception, the copyright holders of RXTX give you
| permission to link RXTX with independent modules that communicate with
| RXTX solely through the Sun Microsytems CommAPI interface version 2,
| regardless of the license terms of these independent modules, and to copy
| and distribute the resulting combined work under terms of your choice,
| provided that every copy of the combined work is accompanied by a complete
| copy of the source code of RXTX (the version of RXTX used to produce the
| combined work), being distributed under the terms of the GNU Lesser General
| Public License plus this exception. An independent module is a
| module which is not derived from or based on RXTX.
|
| Note that people who make modified versions of RXTX are not obligated
| to grant this special exception for their modified versions; it is
| their choice whether to do so. The GNU Lesser General Public License
| gives permission to release a modified version without this exception; this
| exception also makes it possible to release a modified version which
| carries forward this exception.
|
| You should have received a copy of the GNU Lesser General Public
| License along with this library; if not, write to the Free
| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
| All trademarks belong to their respective owners.
--------------------------------------------------------------------------*/
#if defined(__MWERKS__) /* dima */
#include "RXTXPort.h" /* dima */
#else /* dima */
#ifndef WIN32
# include "config.h"
#endif
#include "gnu_io_RXTXPort.h"
#endif /* dima */
#ifdef __LCC__ /* windows lcc compiler for fd_set. probably wrong */
# include<winsock.h>
#endif /* __LCC__ */
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <sys/stat.h>
#ifndef WIN32
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/utsname.h>
#include <pthread.h>
#else
# include "win32termios.h"
/* FIXME returns 0 in all cases on win32
#define S_ISCHR(m) (((m)&S_IFMT) == S_IFCHR)
*/
# if !defined(S_ISCHR)
# define S_ISCHR(m) (1)
# endif /* S_ISCHR(m) */
#endif /* WIN32 */
#ifdef HAVE_TERMIOS_H
# include <termios.h>
#endif /* HAVE_TERMIOS_H */
# include <signal.h>
#ifdef HAVE_SIGNAL_H
# include <signal.h>
#endif /* HAVE_SIGNAL_H */
#ifdef HAVE_SYS_SIGNAL_H
# include <sys/signal.h>
#endif /* HAVE_SYS_SIGNAL_H */
#include <sys/types.h>
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif /* HAVE_SYS_TIME_H */
# include <fcntl.h>
#ifdef HAVE_SYS_FCNTL_H
# include <sys/fcntl.h>
#endif /* HAVE_SYS_FCNTL_H */
#ifdef HAVE_SYS_FILE_H
# include <sys/file.h>
#endif /* HAVE_SYS_FILE_H */
#ifdef LFS /* File Lock Server */
# include <sys/socket.h>
# include <netinet/in.h>
# include <arpa/inet.h>
#endif /* FLS */
#if defined(__linux__)
# include <linux/types.h> /* fix for linux-2.3.4? kernels */
#undef major
#undef minor
#include <sys/sysmacros.h>
# include <linux/serial.h>
# include <linux/version.h>
#endif /* __linux__ */
#if defined(__sun__)
# include <sys/filio.h>
# include <sys/mkdev.h>
#endif /* __sun__ */
#if defined(__hpux__)
# include <sys/modem.h>
#endif /* __hpux__ */
/* FIXME -- new file */
#if defined(__APPLE__)
# include <CoreFoundation/CoreFoundation.h>
# include <IOKit/IOKitLib.h>
# include <IOKit/serial/IOSerialKeys.h>
# include <IOKit/IOBSD.h>
#endif /* __APPLE__ */
#ifdef __unixware__
# include <sys/filio.h>
#endif /* __unixware__ */
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif /* HAVE_PWD_H */
#ifdef HAVE_GRP_H
#include <grp.h>
#endif /* HAVE_GRP_H */
#include <math.h>
#ifdef LIBLOCKDEV
#include <lockdev.h>
#endif /* LIBLOCKDEV */
extern int errno;
#include "SerialImp.h"
JavaVM *javaVM = NULL;
struct preopened *preopened_port = NULL;
/* this is so diff will not generate noise when merging 1.4 and 1.5 changes
* It will eventually be removed.
* */
#define RXTXPort(foo) Java_gnu_io_RXTXPort_ ## foo
#define RXTXVersion(foo) Java_gnu_io_RXTXVersion_ ## foo
#define RXTXCommDriver(foo) Java_gnu_io_RXTXCommDriver_ ## foo
#if defined(__sun__) || defined(__hpux__)
/*----------------------------------------------------------
cfmakeraw
accept: termios to be set to raw
perform: initializes the termios structure.
return: int 0 on success
exceptions: none
comments: this is how linux cfmakeraw works.
termios(3) manpage
----------------------------------------------------------*/
int cfmakeraw ( struct termios *term )
{
ENTER( "cfmakeraw" );
term->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
term->c_oflag &= ~OPOST;
term->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
term->c_cflag &= ~(CSIZE|PARENB);
term->c_cflag |= CS8;
LEAVE( "cfmakeraw" );
return( 0 );
}
#endif /* __sun__ || __hpux__ */
struct event_info_struct *master_index = NULL;
int localOpen(const char * name,int flags){
int result=OPEN(name,flags);
return result;
}
int localClose(int fd){
#if defined(__linux__)
if(!(fcntl(fd, F_GETFL) != -1 || errno != EBADF)){
//report_error("\nlocalClose: File Descriptor error, not closing\n");
return -1;
}
#endif
int result=CLOSE(fd);
return result;
}
/*----------------------------------------------------------
RXTXPort.Initialize
accept: The JNIEnv and jobj of the thread, the original eis.
perform: fill in the needed variables with this threads values
return: none
exceptions: none
comments: java variables (especially JNIEnv) should not be shared
between threads. Right now we build a local struct with
the thread's info before using the variabls. This is
especially true for send_event.
See also JNI_OnLoad() if the thread does not have the values
----------------------------------------------------------*/
struct event_info_struct build_threadsafe_eis(
JNIEnv *env,
jobject *jobj,
struct event_info_struct *eis
)
{
struct event_info_struct myeis = *eis;
myeis.env = env;
myeis.jclazz = (*env)->GetObjectClass( env, *jobj );
myeis.jobj = jobj;
myeis.fd = get_java_var( env, *jobj, "fd", "I" );
myeis.send_event = (*env)->GetMethodID(
env,
myeis.jclazz,
"sendEvent",
"(IZ)Z"
);
return( myeis );
}
/*----------------------------------------------------------
RXTXPort.Initialize
accept: none
perform: Initialize the native library
return: none
exceptions: none
comments: Basically this just causes rxtx to ignore signals. signal
handlers where tried but the VM (circa 1.1) did not like it.
It also allows for some sanity checks on linux boxes if DEBUG
is enabled.
----------------------------------------------------------*/
JNIEXPORT void JNICALL RXTXPort(Initialize)(
JNIEnv *env,
jclass jclazz
)
{
/* This bit of code checks to see if there is a signal handler installed
for SIGIO, and installs SIG_IGN if there is not. This is necessary
for the native threads jdk, but we don't want to do it with green
threads, because it slows things down. Go figure. */
/* POSIX signal handling functions */
#if !defined(WIN32)
struct sigaction old_action;
sigaction(SIGIO, NULL, &old_action);
/* green threads already has handler, no touch */
if (old_action.sa_handler == NULL) {
/* no handler when using native threads, set to ignore */
struct sigaction new_action;
sigset_t block_mask;
sigemptyset(&block_mask);
new_action.sa_handler = SIG_IGN;
#ifdef SA_RESTART
new_action.sa_flags = SA_RESTART;
#endif /* SA_RESTART */
new_action.sa_mask = block_mask;
sigaction(SIGIO, &new_action, NULL);
}
#endif /* !WIN32 */
ENTER( "RXTXPort:Initialize" );
#ifdef PRERELEASE
/* this is just for avoiding confusion while testing new libraries */
printf("RXTX Prerelease for testing Thu Feb 21 19:31:38\n");
#endif /* PRERELEASE */
#if defined(DEBUG_TIMING) && ! defined(WIN32)
/* WIN32 does not have gettimeofday() */
gettimeofday(&seloop, NULL);
#endif /* DEBUG_TIMING && ! WIN32 */
LEAVE( "RXTXPort:Initialize" );
}
/*----------------------------------------------------------
RXTXPort.find_preopened_ports
accept: The device to find if preopened. ie "/dev/ttyS0"
perform: find the filedescriptor if preopened
return: fd
exceptions: none
comments: see
RXTXPort.nativeStaticSetDSR
RXTXPort.nativeStaticSetDTR
RXTXPort.nativeStaticSetRTS
RXTXPort.nativeStaticSetSerialPortParams
This is used so people can setDTR low before calling the
Java open().
----------------------------------------------------------*/
int find_preopened_ports( const char *filename )
{
int fd;
struct preopened *p = preopened_port;
if( !p )
{
return(0);
}
for(;;)
{
if( !strcmp( p->filename, filename) )
{
fd = p->fd;
if( p->prev && p->next )
{
p->prev->next = p->next;
p->next->prev = p->prev;
}
else if ( p->prev )
{
p->prev->next = NULL;
}
else if ( p->next )
{
p->next->prev = NULL;
}
else
{
free( p );
preopened_port = NULL;
return( fd );
}
free( p );
return( fd );
}
if( p->next )
{
p = p->next;
}
else
{
return(0);
}
}
}
/*----------------------------------------------------------
configure_port
accept: env, file descriptor
perform: set the termios struct to sane settings and
return: 0 on success
exceptions: IOExcepiton
comments: Very often people complain about not being able to get past
this function and it turns out to be permissions on the
device file or bios has the device disabled.
----------------------------------------------------------*/
int configure_port( int fd )
{
struct termios ttyset;
if( fd < 0 ) goto fail;
if( tcgetattr( fd, &ttyset ) < 0 ) goto fail;
ttyset.c_iflag = INPCK;
ttyset.c_lflag = 0;
ttyset.c_oflag = 0;
ttyset.c_cflag = CREAD | CS8 | CLOCAL;
ttyset.c_cc[ VMIN ] = 0;
ttyset.c_cc[ VTIME ] = 0;
#ifdef __FreeBSD__
if( cfsetspeed( &ttyset, B9600 ) < 0 ) goto fail;
#else
if( cfsetispeed( &ttyset, B9600 ) < 0 ) goto fail;
if( cfsetospeed( &ttyset, B9600 ) < 0 ) goto fail;
#endif
if( tcsetattr( fd, TCSANOW, &ttyset ) < 0 ) goto fail;
#ifndef WIN32
fcntl( fd, F_SETOWN, getpid() );
#endif /* WIN32 */
#ifdef FASYNC
fcntl( fd, F_SETFL, FASYNC );
#endif /* FASYNC */
return 0;
fail:
return 1;
}
/*----------------------------------------------------------
get_java_baudrate
accept: the native speed setting
perform: translate the native speed to a Java speed
return: the Java speed
exceptions: none
comments: This is used by open() (indirectly) and
nativeStaticGetBaudRate()
----------------------------------------------------------*/
int get_java_baudrate( int native_speed )
{
switch( native_speed )
{
case B0: return 0;
case B50: return 50;
case B75: return 75;
case B110: return 110;
case B134: return 134;
case B150: return 150;
case B200: return 200;
case B300: return 300;
case B600: return 600;
case B1200: return 1200;
case B1800: return 1800;
case B2400: return 2400;
case B4800: return 4800;
case B9600: return 9600;
#ifdef B14400
case B14400: return 14400;
#endif /* B14400 */
case B19200: return 19200;
#ifdef B28800
case B28800: return 28800;
#endif /* B28800 */
case B38400: return 38400;
case B57600: return 57600;
/* I don't think this is universal.. older UARTs never did these. taj */
#ifdef B115200
case B115200: return 115200;
#endif /* B115200 */
#ifdef B128000 /* dima */
case B128000: return 128000;
#endif /* dima */
#ifdef B230400
case B230400: return 230400;
#endif /* B230400 */
#ifdef B256000 /* dima */
case B256000: return 256000;
#endif /* dima */
#ifdef B460800
case B460800: return 460800;
#endif /* B460800 */
#ifdef B500000
case B500000: return 500000;
#endif /* B500000 */
#ifdef B576000
case B576000: return 576000;
#endif /* B576000 */
#ifdef B921600
case B921600: return 921600;
#endif /* B921600 */
#ifdef B1000000
case B1000000: return 1000000;
#endif /* B1000000 */
#ifdef B1152000
case B1152000: return 1152000;
#endif /* B1152000 */
#ifdef B1500000
case B1500000: return 1500000;
#endif /* B1500000 */
#ifdef B2000000
case B2000000: return 2000000;
#endif /* B2000000 */
#ifdef B2500000
case B2500000: return 2500000;
#endif /* B2500000 */
#ifdef B3000000
case B3000000: return 3000000;
#endif /* B3000000 */
#ifdef B3500000
case B3500000: return 3500000;
#endif /* B3500000 */
#ifdef B4000000
case B4000000: return 4000000;
#endif /* B4000000 */
default: return -1;
}
}
/*----------------------------------------------------------
set_java_vars
accept: fd of the preopened device
perform: Now that the object is instatiated, set the Java variables
to the preopened states.
return: none
exceptions: none
comments: preopened refers to the fact that the serial port has
been configured before the Java open() has been called.
----------------------------------------------------------*/
void set_java_vars( JNIEnv *env, jobject jobj, int fd )
{
struct termios ttyset;
int databits = -1;
int jparity = -1;
int stop_bits = STOPBITS_1_5;
int baudrate;
jclass jclazz = (*env)->GetObjectClass( env, jobj );
jfieldID jfspeed = (*env)->GetFieldID( env, jclazz, "speed", "I" );
jfieldID jfdataBits =
(*env)->GetFieldID( env, jclazz, "dataBits", "I" );
jfieldID jfstopBits =
(*env)->GetFieldID( env, jclazz, "stopBits", "I" );
jfieldID jfparity =
(*env)->GetFieldID( env, jclazz, "parity", "I" );
(*env)->DeleteLocalRef( env, jclazz );
if( tcgetattr( fd, &ttyset ) < 0 )
{
report( "Cannot Get Serial Port Settings\n" );
(*env)->DeleteLocalRef( env, jclazz );
return;
}
switch( ttyset.c_cflag&CSIZE ) {
case CS5: databits = JDATABITS_5; break;
case CS6: databits = JDATABITS_6; break;
case CS7: databits = JDATABITS_7; break;
case CS8: databits = JDATABITS_8; break;
}
#ifdef CMSPAR
switch( ttyset.c_cflag&(PARENB|PARODD|CMSPAR ) ) {
#else
switch( ttyset.c_cflag&(PARENB|PARODD) ) {
#endif /* CMSPAR */
case 0: jparity = JPARITY_NONE; break;
case PARENB: jparity = JPARITY_EVEN; break;
case PARENB | PARODD: jparity = JPARITY_ODD; break;
#ifdef CMSPAR
case PARENB | PARODD | CMSPAR: jparity = JPARITY_MARK; break;
case PARENB | CMSPAR: jparity = JPARITY_SPACE; break;
#endif /* CMSPAR */
}
switch( ttyset.c_cflag&(CSTOPB) ) {
case 0: stop_bits = STOPBITS_1; break;
case CSTOPB:
if ( (ttyset.c_cflag & CSIZE) == CS5 ) {
stop_bits = STOPBITS_1_5;
}
else {
stop_bits = STOPBITS_2;
}
break;
}
/*
dima writes:
Trent, here is something I found with google:
(freebsd list freebsd-current@freebsd.org)
Andrzej Bialecki <abial@korin.warman.org.pl> asked:
I tried to compile a piece of software, probably for Linux, and I noticed
that we don't define CBAUD constant. I'm not sure, but I think POSIX
defines and uses it. Should(n't) we?
Bruce Evans <bde@zeta.org.au> answered:
CBAUD is for SYSV compatibility. It is considerably inferior to POSIX's
cf{get,set}{i,o}speed and shouldn't be provided or used.
*/
#if defined(CBAUD)/* dima */
baudrate = ttyset.c_cflag&CBAUD;
#else
baudrate = cfgetispeed(&ttyset);
#endif
(*env)->SetIntField(env, jobj, jfspeed,
( jint ) get_java_baudrate(baudrate) );
(*env)->SetIntField(env, jobj, jfdataBits, ( jint ) databits );
(*env)->SetIntField(env, jobj, jfstopBits, ( jint ) stop_bits );
(*env)->SetIntField(env, jobj, jfparity, ( jint ) jparity );
}
/*----------------------------------------------------------
RXTXPort.controlRs485
accept: fd of the preopened device,
boolean if the bus enable (RTS) is active low,
delay of RTS edge to first data edge (not supported by all serial drivers),
delay of RTS edge after end of transmission (not supported by all serial drivers)
perform: set the rs485 config via ioctl
return: return code of ioctl
----------------------------------------------------------*/
JNIEXPORT jint JNICALL RXTXPort(controlRs485)(
JNIEnv *env,
jobject jobj,
jint fd,
jboolean enable,
jboolean busEnableActiveLow,
jint delayRtsBeforeSendMs,
jint delayRtsAfterSendMs
)
{
#if defined(__linux__)
struct serial_rs485 rs485conf;
memset(&rs485conf, 0, sizeof(struct serial_rs485));
if(enable) {
rs485conf.flags |= SER_RS485_ENABLED;
}
if(busEnableActiveLow) {
rs485conf.flags |= SER_RS485_RTS_AFTER_SEND;
} else {
rs485conf.flags |= SER_RS485_RTS_ON_SEND;
}
rs485conf.delay_rts_before_send = delayRtsBeforeSendMs;
rs485conf.delay_rts_after_send = delayRtsAfterSendMs;
return ioctl (fd, TIOCSRS485, &rs485conf);
#else
return -1;
#endif
}
/*----------------------------------------------------------
RXTXPort.open
accept: The device to open. ie "/dev/ttyS0"
perform: open the device, set the termios struct to sane settings and
return the filedescriptor
return: fd
exceptions: IOExcepiton
comments: Very often people complain about not being able to get past
this function and it turns out to be permissions on the
device file or bios has the device disabled.
----------------------------------------------------------*/
JNIEXPORT jint JNICALL RXTXPort(open)(
JNIEnv *env,
jobject jobj,
jstring jstr
)
{
int fd;
int pid = -1;
char message[256];
const char *filename;
jclass jclazz = (*env)->GetObjectClass( env, jobj );
jfieldID jfid = (*env)->GetFieldID( env, jclazz, "pid", "I" );
report_time_start( );
if( !jfid ) {
(*env)->ExceptionDescribe( env );
(*env)->ExceptionClear( env );
(*env)->DeleteLocalRef( env, jclazz );
return -1;
}
#ifndef WIN32
pid = getpid();
#endif /* WIN32 */
(*env)->SetIntField(env, jobj, jfid, ( jint ) pid );
(*env)->DeleteLocalRef( env, jclazz );
filename = (*env)->GetStringUTFChars( env, jstr, 0 );
/*
LOCK is one of three functions defined in SerialImp.h
uucp_lock Solaris
fhs_lock Linux
system_does_not_lock Win32
*/
ENTER( "RXTXPort:open" );
//report_warning("\nopen() Attempting to lock: ");
if ( LOCK( filename, pid ) )
{
snprintf( message, sizeof(message), "open: locking has failed for %s\n",
filename );
report_error( message );
goto fail;
}
// else
// {
// snprintf( message, sizeof(message), "open: locking worked for %s\n", filename );
// report( message );
// }
/* This is used so DTR can remain low on 'open()' */
fd = find_preopened_ports( filename );
if( fd )
{
report_warning( "open: port is open already" );
set_java_vars( env, jobj, fd );
(*env)->ReleaseStringUTFChars( env, jstr, filename );
return (jint)fd;
}
//report_warning("\nopen() Attempting to open: ");
//report_warning(filename);
do {
fd=localOpen (filename, O_RDWR | O_NOCTTY | O_NONBLOCK );
} while (fd < 0 && errno==EINTR);
//report_warning("\nopen() ...Opened! ");
#ifdef OPEN_EXCL
/*
Note that open() follows POSIX semantics: multiple open() calls to
the same file will succeed unless the TIOCEXCL ioctl is issued.
This will prevent additional opens except by root-owned processes.
See tty(4) ("man 4 tty") and ioctl(2) ("man 2 ioctl") for details.
*/
#if defined(__linux__)
int ret;
//report_error("\nnative open(): Setting ownership flags");
ret= fcntl(fd,F_SETOWN,getpid());
//report_error( strerror(errno) );
//report_error("\nnativec(): Forcing unlock flags");
ret = fcntl(fd,F_UNLCK);
//report_error( strerror(errno) );
//report_error("\nnative open(): Setting read/write flags");
ret= fcntl(fd,F_SETFL,O_CLOEXEC|O_RDWR|O_NONBLOCK);
//report_error( strerror(errno) );
#endif
if (fd >= 0 && (ioctl(fd, TIOCEXCL) == -1))
{
snprintf( message, sizeof(message), "open: exclusive access denied for %s\n",
filename );
report( message );
report_error( message );
close(fd);
goto fail;
}
#endif /* OPEN_EXCL */
if( configure_port( fd ) ) goto fail;
(*env)->ReleaseStringUTFChars( env, jstr, filename );
snprintf( message, sizeof(message), "open: fd returned is %i\n", fd );
report( message );
LEAVE( "RXTXPort:open" );
report_time_end( );
return (jint)fd;
fail:
(*env)->ReleaseStringUTFChars( env, jstr, filename );
LEAVE( "RXTXPort:open" );
throw_java_exception( env, PORT_IN_USE_EXCEPTION, "open",
strerror( errno ) );
return -1;
}
/*----------------------------------------------------------
RXTXPort.nativeClose
accept: none
perform: get the fd from the java end and close it
return: none
exceptions: none
----------------------------------------------------------*/
JNIEXPORT void JNICALL RXTXPort(nativeClose)( JNIEnv *env,
jobject jobj,jstring jstr )
{
int result, pid;
int fd = get_java_var( env, jobj,"fd","I" );
const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
jclass jclazz = (*env)->GetObjectClass( env, jobj );
report_time_start( );
pid = get_java_var( env, jobj,"pid","I" );
//report_warning("nativeClose() Attempting Close pid\n");
/*
usleep(10000);
*/
if( !pid ) {
(*env)->ExceptionDescribe( env );
(*env)->ExceptionClear( env );
(*env)->DeleteLocalRef( env, jclazz );
report_warning("nativeClose(): Close not detecting thread pid");
return;
}
report("<nativeClose: pid\n");
/*
UNLOCK is one of three functions defined in SerialImp.h
uucp_unlock Solaris
fhs_unlock Linux
system_does_not_unlock Win32
*/
ENTER( "RXTXPort:nativeClose" );
if (fd > 0)
{
//report_warning("nativeClose: discarding remaining data (tcflush)\n");
report("nativeClose: discarding remaining data (tcflush)\n");
/* discard any incoming+outgoing data not yet read/sent */
tcflush(fd, TCIOFLUSH);
int x=0;
do {
//report_warning("nativeClose: Attempting to close\n");
report("nativeClose: calling close\n");
result=localClose(fd);
//report_warning("nativeClose: Close OK\n");
x++;
if(x>10){
report_error("\nnativeClose(): Close failed 10 times!");
report_error( strerror(errno) );
return;
}
} while ( result < 0 && errno == EINTR );
//report_warning("nativeClose() Attempt to unlock\n");
UNLOCK( filename, pid );
//report_warning("nativeClose() Unlock OK\n");
}else{
//report_warning("nativeClose(): Close not detecting File Descriptor");
}
//report_warning("nativeClose() Attempt OK\n");
report("nativeClose: Delete jclazz\n");
(*env)->DeleteLocalRef( env, jclazz );
report("nativeClose: release filename\n");
(*env)->ReleaseStringUTFChars( env, jstr, filename );
LEAVE( "RXTXPort:nativeClose" );
report_time_end( );
return;
}
/*----------------------------------------------------------
RXTXPort.set_port_params
accept: env, fd, speed, data bits, stop bits, parity
perform: set the serial port parameters
return: 1 on error
exceptions: UnsupportedCommOperationException
comments: There is a static method and an instance method that use this
function. The static method gets a fd first. The instance
method can get the fd from the object.
see: nativeSetSerialPortParams & nativeStaticSerialPortParams
----------------------------------------------------------*/
int set_port_params( JNIEnv *env, int fd, int cspeed, int dataBits,
int stopBits, int parity )
{
struct termios ttyset;
int result = 0;
#if defined(TIOCGSERIAL)
struct serial_struct sstruct;
#endif /* TIOCGSERIAL */
if( tcgetattr( fd, &ttyset ) < 0 )
{
report( "set_port_params: Cannot Get Serial Port Settings\n" );
return(1);
}
if( translate_data_bits( env, &(ttyset.c_cflag), dataBits ) )
{
report( "set_port_params: Invalid Data Bits Selected\n" );
return(1);
}
if( translate_stop_bits( env, &(ttyset.c_cflag), stopBits ) )
{
report( "set_port_params: Invalid Stop Bits Selected\n" );
return(1);
}
if( translate_parity( env, &(ttyset.c_cflag), parity ) )
{
report( "set_port_params: Invalid Parity Selected\n" );
return(1);
}
#ifdef __FreeBSD__
if( cfsetspeed( &ttyset, cspeed ) < 0 )
{
report( "set_port_params: Cannot Set Speed\n" );
return( 1 );
}
#endif /* __FreeBSD__ */
if( !cspeed )
{
/* hang up the modem aka drop DTR */
/* Unix should handle this */
/*
printf("dropping DTR\n");
*/
ioctl( fd, TIOCMGET, &result );
result &= ~TIOCM_DTR;
ioctl( fd, TIOCMSET, &result );
}
if( cfsetispeed( &ttyset, cspeed ) < 0 ||
cfsetospeed( &ttyset, cspeed ) < 0 )
{
/*
Some people need to set the baud rate to ones not defined
in termios.h
This includes some baud rates which are supported by CommAPI
in Unix ( 14400, 28800, 128000, 256000 )
If the above fails, we assume this is not a defined
baud rate on Unix. With Win32, It is assumed the kernel
will do this for us.
The baud_base and desired speed are used to
calculate a custom divisor.
On linux the setserial man page covers this.
*/
#if defined(TIOCGSERIAL)
sstruct.custom_divisor = ( sstruct.baud_base/cspeed );
cspeed = B38400;
#endif /* TIOCGSERIAL */
if( cfsetispeed( &ttyset, cspeed ) < 0 ||
cfsetospeed( &ttyset, cspeed ) < 0 )
{
/* OK, we tried everything */
report( "nativeSetSerialPortParams: Cannot Set Speed\n" );
return( 1 );
}
#if defined(TIOCSSERIAL)
/* It is assumed Win32 does this for us */
if ( sstruct.baud_base < 1 ||
ioctl( fd, TIOCSSERIAL, &sstruct ) < 0 )
{
return( 1 );
}
#endif /* TIOCSSERIAL */
}
if( tcsetattr( fd, TCSANOW, &ttyset ) < 0 )
{
report("tcsetattr returns nonzero value!\n");
return( 1 );
}
return(0);
}
/*----------------------------------------------------------
RXTXPort.nativeSetSerialPortParams
accept: speed, data bits, stop bits, parity
perform: set the serial port parameters
return: jboolean 1 on error
exceptions: UnsupportedCommOperationException
----------------------------------------------------------*/
JNIEXPORT jboolean JNICALL RXTXPort(nativeSetSerialPortParams)(
JNIEnv *env, jobject jobj, jint speed, jint dataBits, jint stopBits,
jint parity )
{
int fd = get_java_var( env, jobj,"fd","I" );
int cspeed = translate_speed( env, speed );
ENTER( "RXTXPort:nativeSetSerialPortParams" );
report_time_start( );
if (cspeed < 0 )
{
report(" invalid cspeed\n");
/*
For some reason the native exceptions are not being caught. Moving this
to the Java side fixed the issue. taj.
throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
"", "BaudRate could not be set to the specified value" );
*/
return(1);
}
if( set_port_params( env, fd, cspeed, dataBits, stopBits, parity ) )
{
report("set_port_params failed\n");
LEAVE( "RXTXPort:nativeSetSerialPortParams" );
/*
For some reason the native exceptions are not being caught. Moving this
to the Java side fixed the issue. taj.
throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
"nativeSetSerialPortParams", strerror( errno ) );
*/
return(1);
}
LEAVE( "RXTXPort:nativeSetSerialPortParams" );
report_time_end( );
return(0);
}
/*----------------------------------------------------------
translate_speed
accept: speed in bits-per-second