Debian Codegraph @

src/SerialImp.c

raw symbols ◀ ▶ SCIP
Source reconstructed at patch state 3 of 8 — not the installed (fully patched) source.
8 Debian patches touch this file
1 /*-------------------------------------------------------------------------
2 | RXTX License v 2.1 - LGPL v 2.1 + Linking Over Controlled Interface.
3 | RXTX is a native interface to serial ports in java.
4 | Copyright 1997-2008 by Trent Jarvi [email protected] and others who
5 | actually wrote it. See individual source files for more information.
6 |
7 | A copy of the LGPL v 2.1 may be found at
8 | http://www.gnu.org/licenses/lgpl.txt on March 4th 2007. A copy is
9 | here for your convenience.
10 |
11 | This library is free software; you can redistribute it and/or
12 | modify it under the terms of the GNU Lesser General Public
13 | License as published by the Free Software Foundation; either
14 | version 2.1 of the License, or (at your option) any later version.
15 |
16 | This library is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 | Lesser General Public License for more details.
20 |
21 | An executable that contains no derivative of any portion of RXTX, but
22 | is designed to work with RXTX by being dynamically linked with it,
23 | is considered a "work that uses the Library" subject to the terms and
24 | conditions of the GNU Lesser General Public License.
25 |
26 | The following has been added to the RXTX License to remove
27 | any confusion about linking to RXTX. We want to allow in part what
28 | section 5, paragraph 2 of the LGPL does not permit in the special
29 | case of linking over a controlled interface. The intent is to add a
30 | Java Specification Request or standards body defined interface in the
31 | future as another exception but one is not currently available.
32 |
33 | http://www.fsf.org/licenses/gpl-faq.html#LinkingOverControlledInterface
34 |
35 | As a special exception, the copyright holders of RXTX give you
36 | permission to link RXTX with independent modules that communicate with
37 | RXTX solely through the Sun Microsytems CommAPI interface version 2,
38 | regardless of the license terms of these independent modules, and to copy
39 | and distribute the resulting combined work under terms of your choice,
40 | provided that every copy of the combined work is accompanied by a complete
41 | copy of the source code of RXTX (the version of RXTX used to produce the
42 | combined work), being distributed under the terms of the GNU Lesser General
43 | Public License plus this exception. An independent module is a
44 | module which is not derived from or based on RXTX.
45 |
46 | Note that people who make modified versions of RXTX are not obligated
47 | to grant this special exception for their modified versions; it is
48 | their choice whether to do so. The GNU Lesser General Public License
49 | gives permission to release a modified version without this exception; this
50 | exception also makes it possible to release a modified version which
51 | carries forward this exception.
52 |
53 | You should have received a copy of the GNU Lesser General Public
54 | License along with this library; if not, write to the Free
55 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
56 | All trademarks belong to their respective owners.
57 --------------------------------------------------------------------------*/
58 #define _GNU_SOURCE
59 #if defined(__MWERKS__) /* dima */
60 #include "RXTXPort.h" /* dima */
61 #else /* dima */
62 #ifndef WIN32
63 # include "config.h"
64 #endif
65 #include "gnu_io_RXTXPort.h"
66 #endif /* dima */
67 #ifdef __LCC__ /* windows lcc compiler for fd_set. probably wrong */
68 # include<winsock.h>
69 #endif /* __LCC__ */
70 #include <time.h>
71 #include <stdio.h>
72 #include <string.h>
73 #include <stdlib.h>
74 #include <errno.h>
75 #include <limits.h>
76 #include <sys/stat.h>
77 #ifndef WIN32
78 #include <unistd.h>
79 #include <sys/ioctl.h>
80 #include <sys/param.h>
81 #include <sys/utsname.h>
82 #include <pthread.h>
83 #else
84 # include "win32termios.h"
85 /* FIXME returns 0 in all cases on win32
86 #define S_ISCHR(m) (((m)&S_IFMT) == S_IFCHR)
87 */
88 # if !defined(S_ISCHR)
89 # define S_ISCHR(m) (1)
90 # endif /* S_ISCHR(m) */
91 #endif /* WIN32 */
92 #ifdef HAVE_TERMIOS_H
93 # include <termios.h>
94 #endif /* HAVE_TERMIOS_H */
95 # include <signal.h>
96 #ifdef HAVE_SIGNAL_H
97 # include <signal.h>
98 #endif /* HAVE_SIGNAL_H */
99 #ifdef HAVE_SYS_SIGNAL_H
100 # include <sys/signal.h>
101 #endif /* HAVE_SYS_SIGNAL_H */
102 #include <sys/types.h>
103 #ifdef HAVE_SYS_TIME_H
104 # include <sys/time.h>
105 #endif /* HAVE_SYS_TIME_H */
106 # include <fcntl.h>
107 #ifdef HAVE_SYS_FCNTL_H
108 # include <sys/fcntl.h>
109 #endif /* HAVE_SYS_FCNTL_H */
110 #ifdef HAVE_SYS_FILE_H
111 # include <sys/file.h>
112 #endif /* HAVE_SYS_FILE_H */
113 #ifdef LFS /* File Lock Server */
114 # include <sys/socket.h>
115 # include <netinet/in.h>
116 # include <arpa/inet.h>
117 #endif /* FLS */
118 #if defined(__linux__)
119 # include <linux/types.h> /* fix for linux-2.3.4? kernels */
120 # include <linux/serial.h>
121 # include <linux/version.h>
122 #endif /* __linux__ */
123 #if defined(__sun__)
124 # include <sys/filio.h>
125 # include <sys/mkdev.h>
126 #endif /* __sun__ */
127 #if defined(__hpux__)
128 # include <sys/modem.h>
129 #endif /* __hpux__ */
130 /* FIXME -- new file */
131 #if defined(__APPLE__)
132 # include <CoreFoundation/CoreFoundation.h>
133 # include <IOKit/IOKitLib.h>
134 # include <IOKit/serial/IOSerialKeys.h>
135 # include <IOKit/IOBSD.h>
136 #endif /* __APPLE__ */
137 #ifdef __unixware__
138 # include <sys/filio.h>
139 #endif /* __unixware__ */
140 #ifdef HAVE_PWD_H
141 #include <pwd.h>
142 #endif /* HAVE_PWD_H */
143 #ifdef HAVE_GRP_H
144 #include <grp.h>
145 #endif /* HAVE_GRP_H */
146 #include <math.h>
147 #ifdef LIBLOCKDEV
148 #include <lockdev.h>
149 #endif /* LIBLOCKDEV */
150 #include <sys/sysmacros.h>
151
152 extern int errno;
153
154 #include "SerialImp.h"
155
156 JavaVM *javaVM = NULL;
157
158
159 struct preopened *preopened_port = NULL;
160
161 /* this is so diff will not generate noise when merging 1.4 and 1.5 changes
162 * It will eventually be removed.
163 * */
164 #define RXTXPort(foo) Java_gnu_io_RXTXPort_ ## foo
165 #define RXTXVersion(foo) Java_gnu_io_RXTXVersion_ ## foo
166 #define RXTXCommDriver(foo) Java_gnu_io_RXTXCommDriver_ ## foo
167
168 #if defined(__sun__) || defined(__hpux__)
169 /*----------------------------------------------------------
170 cfmakeraw
171
172 accept: termios to be set to raw
173 perform: initializes the termios structure.
174 return: int 0 on success
175 exceptions: none
176 comments: this is how linux cfmakeraw works.
177 termios(3) manpage
178 ----------------------------------------------------------*/
179
180 int cfmakeraw ( struct termios *term )
181 {
182 ENTER( "cfmakeraw" );
183 term->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
184 term->c_oflag &= ~OPOST;
185 term->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
186 term->c_cflag &= ~(CSIZE|PARENB);
187 term->c_cflag |= CS8;
188 LEAVE( "cfmakeraw" );
189 return( 0 );
190 }
191 #endif /* __sun__ || __hpux__ */
192
193 #ifdef DEBUG_TIMING
194 struct timeval snow, enow, seloop, eeloop;
195 #define report_time_eventLoop( ) { \
196 if ( seloop.tv_sec == eeloop.tv_sec && seloop.tv_usec == eeloop.tv_usec ) \
197 { \
198 gettimeofday(&eeloop, NULL); \
199 seloop.tv_sec = eeloop.tv_sec; \
200 seloop.tv_usec = eeloop.tv_usec; \
201 printf("%8i sec : %8i usec\n", eeloop.tv_sec - seloop.tv_sec, eeloop.tv_usec - seloop.tv_usec); \
202 } \
203 }
204 #define report_time( ) \
205 { \
206 struct timeval now; \
207 gettimeofday(&now, NULL); \
208 mexPrintf("%8s : %5i : %8i sec : %8i usec\n", __TIME__, __LINE__, now.tv_sec, now.tv_usec); \
209 }
210 #define report_time_start( ) \
211 { \
212 gettimeofday(&snow, NULL); \
213 mexPrintf("%8s : %5i : %8i sec : %8i usec", __TIME__, __LINE__, snow.tv_sec, snow.tv_usec); \
214 }
215 #define report_time_end( ) \
216 { \
217 gettimeofday(&enow, NULL); \
218 mexPrintf("%8i sec : %8i usec\n", enow.tv_sec - snow.tv_sec, enow.tv_sec - snow.tv_sec?snow.tv_usec-enow.tv_usec:enow.tv_usec - snow.tv_usec); \
219 }
220 #else
221 #define report_time_eventLoop( ){};
222 #define report_time( ) {}
223 #define report_time_start( ) {}
224 #define report_time_end( ) {}
225 #endif /* DEBUG_TIMING */
226
227
228 struct event_info_struct *master_index = NULL;
229
230
231 /*----------------------------------------------------------
232 RXTXPort.Initialize
233
234 accept: The JNIEnv and jobj of the thread, the original eis.
235 perform: fill in the needed variables with this threads values
236 return: none
237 exceptions: none
238 comments: java variables (especially JNIEnv) should not be shared
239 between threads. Right now we build a local struct with
240 the thread's info before using the variabls. This is
241 especially true for send_event.
242
243 See also JNI_OnLoad() if the thread does not have the values
244 ----------------------------------------------------------*/
245 struct event_info_struct build_threadsafe_eis(
246 JNIEnv *env,
247 jobject *jobj,
248 struct event_info_struct *eis
249 )
250 {
251 struct event_info_struct myeis = *eis;
252
253 myeis.env = env;
254 myeis.jclazz = (*env)->GetObjectClass( env, *jobj );
255 myeis.jobj = jobj;
256 myeis.fd = get_java_var( env, *jobj, "fd", "I" );
257 myeis.send_event = (*env)->GetMethodID(
258 env,
259 myeis.jclazz,
260 "sendEvent",
261 "(IZ)Z"
262 );
263 return( myeis );
264 }
265
266 /*----------------------------------------------------------
267 RXTXPort.Initialize
268
269 accept: none
270 perform: Initialize the native library
271 return: none
272 exceptions: none
273 comments: Basically this just causes rxtx to ignore signals. signal
274 handlers where tried but the VM (circa 1.1) did not like it.
275
276 It also allows for some sanity checks on linux boxes if DEBUG
277 is enabled.
278 ----------------------------------------------------------*/
279 JNIEXPORT void JNICALL RXTXPort(Initialize)(
280 JNIEnv *env,
281 jclass jclazz
282 )
283 {
284 #if defined DEBUG && defined(__linux__)
285 struct utsname name;
286 char message[80];
287 #endif /* DEBUG && __linux__ */
288 /* This bit of code checks to see if there is a signal handler installed
289 for SIGIO, and installs SIG_IGN if there is not. This is necessary
290 for the native threads jdk, but we don't want to do it with green
291 threads, because it slows things down. Go figure. */
292
293 /* POSIX signal handling functions */
294 #if !defined(WIN32)
295 struct sigaction old_action;
296 sigaction(SIGIO, NULL, &old_action);
297 /* green threads already has handler, no touch */
298 if (old_action.sa_handler == NULL) {
299 /* no handler when using native threads, set to ignore */
300 struct sigaction new_action;
301 sigset_t block_mask;
302 sigemptyset(&block_mask);
303 new_action.sa_handler = SIG_IGN;
304 #ifdef SA_RESTART
305 new_action.sa_flags = SA_RESTART;
306 #endif /* SA_RESTART */
307 new_action.sa_mask = block_mask;
308 sigaction(SIGIO, &new_action, NULL);
309 }
310 #endif /* !WIN32 */
311 ENTER( "RXTXPort:Initialize" );
312 #ifdef PRERELEASE
313 /* this is just for avoiding confusion while testing new libraries */
314 #ifdef DEBUG_MW
315 mexPrintf("RXTX Prerelease for testing Tue Feb 19 18:00:27 EST 2002\n");
316 #else
317 printf("RXTX Prerelease for testing Thu Feb 21 19:31:38\n");
318 #endif /* DEBUG_MW */
319 #endif /* PRERELEASE */
320 #if DEBUG_TIMING
321 gettimeofday(&seloop, NULL);
322 #endif /* DEBUG_TIMING */
323 #if defined(DEBUG) && defined(__linux__)
324 /* Lets let people who upgraded kernels know they may have problems */
325 /*
326 if (uname (&name) == -1)
327 {
328 report( "RXTX WARNING: cannot get system name\n" );
329 LEAVE( "RXTXPort:Initialize" );
330 return;
331 }
332 if(strcmp(name.release,UTS_RELEASE)!=0)
333 {
334 sprintf( message, LINUX_KERNEL_VERSION_ERROR, UTS_RELEASE,
335 name.release );
336 report( message );
337 getchar();
338 }
339 */
340 LEAVE( "RXTXPort:Initialize" );
341 #endif /* DEBUG && __linux__ */
342 }
343
344 /*----------------------------------------------------------
345 RXTXPort.find_preopened_ports
346 accept: The device to find if preopened. ie "/dev/ttyS0"
347 perform: find the filedescriptor if preopened
348 return: fd
349 exceptions: none
350 comments: see
351 RXTXPort.nativeStaticSetDSR
352 RXTXPort.nativeStaticSetDTR
353 RXTXPort.nativeStaticSetRTS
354 RXTXPort.nativeStaticSetSerialPortParams
355 This is used so people can setDTR low before calling the
356 Java open().
357 ----------------------------------------------------------*/
358 int find_preopened_ports( const char *filename )
359 {
360 int fd;
361 struct preopened *p = preopened_port;
362
363 if( !p )
364 {
365 return(0);
366 }
367 for(;;)
368 {
369 if( !strcmp( p->filename, filename) )
370 {
371 fd = p->fd;
372 if( p->prev && p->next )
373 {
374 p->prev->next = p->next;
375 p->next->prev = p->prev;
376 }
377 else if ( p->prev )
378 {
379 p->prev->next = NULL;
380 }
381 else if ( p->next )
382 {
383 p->next->prev = NULL;
384 }
385 else
386 {
387 free( p );
388 preopened_port = NULL;
389 return( fd );
390 }
391 free( p );
392 return( fd );
393 }
394 if( p->next )
395 {
396 p = p->next;
397 }
398 else
399 {
400 return(0);
401 }
402 }
403 }
404
405 /*----------------------------------------------------------
406 configure_port
407
408 accept: env, file descriptor
409 perform: set the termios struct to sane settings and
410 return: 0 on success
411 exceptions: IOExcepiton
412 comments: Very often people complain about not being able to get past
413 this function and it turns out to be permissions on the
414 device file or bios has the device disabled.
415 ----------------------------------------------------------*/
416 int configure_port( int fd )
417 {
418 struct termios ttyset;
419
420 if( fd < 0 ) goto fail;
421
422 if( tcgetattr( fd, &ttyset ) < 0 ) goto fail;
423 ttyset.c_iflag = INPCK;
424 ttyset.c_lflag = 0;
425 ttyset.c_oflag = 0;
426 ttyset.c_cflag = CREAD | CS8 | CLOCAL;
427 ttyset.c_cc[ VMIN ] = 0;
428 ttyset.c_cc[ VTIME ] = 0;
429
430 #ifdef __FreeBSD_kernel__
431 if( cfsetspeed( &ttyset, B9600 ) < 0 ) goto fail;
432 #else
433 if( cfsetispeed( &ttyset, B9600 ) < 0 ) goto fail;
434 if( cfsetospeed( &ttyset, B9600 ) < 0 ) goto fail;
435 #endif
436 if( tcsetattr( fd, TCSANOW, &ttyset ) < 0 ) goto fail;
437 #ifndef WIN32
438 fcntl( fd, F_SETOWN, getpid() );
439 #endif /* WIN32 */
440 #ifdef FASYNC
441 fcntl( fd, F_SETFL, FASYNC );
442 #endif /* FASYNC */
443
444 return 0;
445
446 fail:
447 return 1;
448 }
449
450 /*----------------------------------------------------------
451 get_java_baudrate
452
453 accept: the native speed setting
454 perform: translate the native speed to a Java speed
455 return: the Java speed
456 exceptions: none
457 comments: This is used by open() (indirectly) and
458 nativeStaticGetBaudRate()
459 ----------------------------------------------------------*/
460 int get_java_baudrate( int native_speed )
461 {
462 switch( native_speed )
463 {
464 case B0: return 0;
465 case B50: return 50;
466 case B75: return 75;
467 case B110: return 110;
468 case B134: return 134;
469 case B150: return 150;
470 case B200: return 200;
471 case B300: return 300;
472 case B600: return 600;
473 case B1200: return 1200;
474 case B1800: return 1800;
475 case B2400: return 2400;
476 case B4800: return 4800;
477 case B9600: return 9600;
478 #ifdef B14400
479 case B14400: return 14400;
480 #endif /* B14400 */
481 case B19200: return 19200;
482 #ifdef B28800
483 case B28800: return 28800;
484 #endif /* B28800 */
485 case B38400: return 38400;
486 case B57600: return 57600;
487 /* I don't think this is universal.. older UARTs never did these. taj */
488 #ifdef B115200
489 case B115200: return 115200;
490 #endif /* B115200 */
491 #ifdef B128000 /* dima */
492 case B128000: return 128000;
493 #endif /* dima */
494 #ifdef B230400
495 case B230400: return 230400;
496 #endif /* B230400 */
497 #ifdef B256000 /* dima */
498 case B256000: return 256000;
499 #endif /* dima */
500 #ifdef B460800
501 case B460800: return 460800;
502 #endif /* B460800 */
503 #ifdef B500000
504 case B500000: return 500000;
505 #endif /* B500000 */
506 #ifdef B576000
507 case B576000: return 576000;
508 #endif /* B576000 */
509 #ifdef B921600
510 case B921600: return 921600;
511 #endif /* B921600 */
512 #ifdef B1000000
513 case B1000000: return 1000000;
514 #endif /* B1000000 */
515 #ifdef B1152000
516 case B1152000: return 1152000;
517 #endif /* B1152000 */
518 #ifdef B1500000
519 case B1500000: return 1500000;
520 #endif /* B1500000 */
521 #ifdef B2000000
522 case B2000000: return 2000000;
523 #endif /* B2000000 */
524 #ifdef B2500000
525 case B2500000: return 2500000;
526 #endif /* B2500000 */
527 #ifdef B3000000
528 case B3000000: return 3000000;
529 #endif /* B3000000 */
530 #ifdef B3500000
531 case B3500000: return 3500000;
532 #endif /* B3500000 */
533 #ifdef B4000000
534 case B4000000: return 4000000;
535 #endif /* B4000000 */
536 default: return -1;
537 }
538 }
539
540 /*----------------------------------------------------------
541 set_java_vars
542
543 accept: fd of the preopened device
544 perform: Now that the object is instatiated, set the Java variables
545 to the preopened states.
546 return: none
547 exceptions: none
548 comments: preopened refers to the fact that the serial port has
549 been configured before the Java open() has been called.
550 ----------------------------------------------------------*/
551
552 void set_java_vars( JNIEnv *env, jobject jobj, int fd )
553 {
554 struct termios ttyset;
555 int databits = -1;
556 int jparity = -1;
557 int stop_bits = STOPBITS_1_5;
558 int baudrate;
559 jclass jclazz = (*env)->GetObjectClass( env, jobj );
560 jfieldID jfspeed = (*env)->GetFieldID( env, jclazz, "speed", "I" );
561 jfieldID jfdataBits =
562 (*env)->GetFieldID( env, jclazz, "dataBits", "I" );
563 jfieldID jfstopBits =
564 (*env)->GetFieldID( env, jclazz, "stopBits", "I" );
565 jfieldID jfparity =
566 (*env)->GetFieldID( env, jclazz, "parity", "I" );
567 (*env)->DeleteLocalRef( env, jclazz );
568 if( tcgetattr( fd, &ttyset ) < 0 )
569 {
570 report( "Cannot Get Serial Port Settings\n" );
571 (*env)->DeleteLocalRef( env, jclazz );
572 return;
573 }
574
575
576 switch( ttyset.c_cflag&CSIZE ) {
577 case CS5: databits = JDATABITS_5; break;
578 case CS6: databits = JDATABITS_6; break;
579 case CS7: databits = JDATABITS_7; break;
580 case CS8: databits = JDATABITS_8; break;
581 }
582 #ifdef CMSPAR
583 switch( ttyset.c_cflag&(PARENB|PARODD|CMSPAR ) ) {
584 #else
585 switch( ttyset.c_cflag&(PARENB|PARODD) ) {
586 #endif /* CMSPAR */
587 case 0: jparity = JPARITY_NONE; break;
588 case PARENB: jparity = JPARITY_EVEN; break;
589 case PARENB | PARODD: jparity = JPARITY_ODD; break;
590 #ifdef CMSPAR
591 case PARENB | PARODD | CMSPAR: jparity = JPARITY_MARK; break;
592 case PARENB | CMSPAR: jparity = JPARITY_SPACE; break;
593 #endif /* CMSPAR */
594 }
595 switch( ttyset.c_cflag&(CSTOPB) ) {
596 case 0: stop_bits = STOPBITS_1; break;
597 case CSTOPB:
598 if ( (ttyset.c_cflag & CSIZE) == CS5 ) {
599 stop_bits = STOPBITS_1_5;
600 }
601 else {
602 stop_bits = STOPBITS_2;
603 }
604 break;
605 }
606 /*
607 dima writes:
608
609 Trent, here is something I found with google:
610 (freebsd list [email protected])
611
612 Andrzej Bialecki <[email protected]> asked:
613 I tried to compile a piece of software, probably for Linux, and I noticed
614 that we don't define CBAUD constant. I'm not sure, but I think POSIX
615 defines and uses it. Should(n't) we?
616
617 Bruce Evans <[email protected]> answered:
618 CBAUD is for SYSV compatibility. It is considerably inferior to POSIX's
619 cf{get,set}{i,o}speed and shouldn't be provided or used.
620
621 */
622 #if defined(CBAUD)/* dima */
623 baudrate = ttyset.c_cflag&CBAUD;
624 #else
625 baudrate = cfgetispeed(&ttyset);
626 #endif
627 (*env)->SetIntField(env, jobj, jfspeed,
628 ( jint ) get_java_baudrate(baudrate) );
629 (*env)->SetIntField(env, jobj, jfdataBits, ( jint ) databits );
630 (*env)->SetIntField(env, jobj, jfstopBits, ( jint ) stop_bits );
631 (*env)->SetIntField(env, jobj, jfparity, ( jint ) jparity );
632 }
633 /*----------------------------------------------------------
634 RXTXPort.open
635
636 accept: The device to open. ie "/dev/ttyS0"
637 perform: open the device, set the termios struct to sane settings and
638 return the filedescriptor
639 return: fd
640 exceptions: IOExcepiton
641 comments: Very often people complain about not being able to get past
642 this function and it turns out to be permissions on the
643 device file or bios has the device disabled.
644 ----------------------------------------------------------*/
645 JNIEXPORT jint JNICALL RXTXPort(open)(
646 JNIEnv *env,
647 jobject jobj,
648 jstring jstr
649 )
650 {
651 int fd;
652 int pid = -1;
653 char message[80];
654 const char *filename;
655 jclass jclazz = (*env)->GetObjectClass( env, jobj );
656 jfieldID jfid = (*env)->GetFieldID( env, jclazz, "pid", "I" );
657 report_time_start( );
658
659 if( !jfid ) {
660 (*env)->ExceptionDescribe( env );
661 (*env)->ExceptionClear( env );
662 (*env)->DeleteLocalRef( env, jclazz );
663 return -1;
664 }
665
666 #ifndef WIN32
667 pid = getpid();
668 #endif /* WIN32 */
669
670 (*env)->SetIntField(env, jobj, jfid, ( jint ) pid );
671 (*env)->DeleteLocalRef( env, jclazz );
672
673 filename = (*env)->GetStringUTFChars( env, jstr, 0 );
674
675 /*
676 LOCK is one of three functions defined in SerialImp.h
677
678 uucp_lock Solaris
679 fhs_lock Linux
680 system_does_not_lock Win32
681 */
682
683 ENTER( "RXTXPort:open" );
684 if ( LOCK( filename, pid ) )
685 {
686 sprintf( message, "open: locking has failed for %s\n",
687 filename );
688 report( message );
689 goto fail;
690 }
691 else
692 {
693 sprintf( message, "open: locking worked for %s\n", filename );
694 report( message );
695 }
696 /* This is used so DTR can remain low on 'open()' */
697 fd = find_preopened_ports( filename );
698 if( fd )
699 {
700 set_java_vars( env, jobj, fd );
701 (*env)->ReleaseStringUTFChars( env, jstr, filename );
702 return (jint)fd;
703 }
704
705 do {
706 fd=OPEN (filename, O_RDWR | O_NOCTTY | O_NONBLOCK );
707 } while (fd < 0 && errno==EINTR);
708
709 #ifdef OPEN_EXCL
710 /*
711 Note that open() follows POSIX semantics: multiple open() calls to
712 the same file will succeed unless the TIOCEXCL ioctl is issued.
713 This will prevent additional opens except by root-owned processes.
714 See tty(4) ("man 4 tty") and ioctl(2) ("man 2 ioctl") for details.
715 */
716
717 if (fd >= 0 && (ioctl(fd, TIOCEXCL) == -1))
718 {
719 sprintf( message, "open: exclusive access denied for %s\n",
720 filename );
721 report( message );
722 report_error( message );
723
724 close(fd);
725 goto fail;
726 }
727 #endif /* OPEN_EXCL */
728
729 if( configure_port( fd ) ) goto fail;
730 (*env)->ReleaseStringUTFChars( env, jstr, filename );
731 sprintf( message, "open: fd returned is %i\n", fd );
732 report( message );
733 LEAVE( "RXTXPort:open" );
734 report_time_end( );
735 return (jint)fd;
736
737 fail:
738 (*env)->ReleaseStringUTFChars( env, jstr, filename );
739 LEAVE( "RXTXPort:open" );
740 throw_java_exception( env, PORT_IN_USE_EXCEPTION, "open",
741 strerror( errno ) );
742 return -1;
743 }
744
745 /*----------------------------------------------------------
746 RXTXPort.nativeClose
747
748 accept: none
749 perform: get the fd from the java end and close it
750 return: none
751 exceptions: none
752 ----------------------------------------------------------*/
753 JNIEXPORT void JNICALL RXTXPort(nativeClose)( JNIEnv *env,
754 jobject jobj,jstring jstr )
755 {
756 int result, pid;
757 int fd = get_java_var( env, jobj,"fd","I" );
758 const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
759 jclass jclazz = (*env)->GetObjectClass( env, jobj );
760 report_time_start( );
761 pid = get_java_var( env, jobj,"pid","I" );
762
763 report(">nativeClose pid\n");
764 /*
765 usleep(10000);
766 */
767 if( !pid ) {
768 (*env)->ExceptionDescribe( env );
769 (*env)->ExceptionClear( env );
770 (*env)->DeleteLocalRef( env, jclazz );
771 report("nativeClose: Close not detecting thread pid");
772 return;
773 }
774 report("<nativeClose: pid\n");
775
776 /*
777 UNLOCK is one of three functions defined in SerialImp.h
778
779 uucp_unlock Solaris
780 fhs_unlock Linux
781 system_does_not_unlock Win32
782 */
783
784 ENTER( "RXTXPort:nativeClose" );
785 if (fd > 0)
786 {
787 report("nativeClose: discarding remaining data (tcflush)\n");
788 /* discard any incoming+outgoing data not yet read/sent */
789 tcflush(fd, TCIOFLUSH);
790 do {
791 report("nativeClose: calling close\n");
792 result=CLOSE (fd);
793 } while ( result < 0 && errno == EINTR );
794 UNLOCK( filename, pid );
795 }
796 report("nativeClose: Delete jclazz\n");
797 (*env)->DeleteLocalRef( env, jclazz );
798 report("nativeClose: release filename\n");
799 (*env)->ReleaseStringUTFChars( env, jstr, filename );
800 LEAVE( "RXTXPort:nativeClose" );
801 report_time_end( );
802 return;
803 }
804
805 /*----------------------------------------------------------
806 RXTXPort.set_port_params
807
808 accept: env, fd, speed, data bits, stop bits, parity
809 perform: set the serial port parameters
810 return: 1 on error
811 exceptions: UnsupportedCommOperationException
812 comments: There is a static method and an instance method that use this
813 function. The static method gets a fd first. The instance
814 method can get the fd from the object.
815
816 see: nativeSetSerialPortParams & nativeStaticSerialPortParams
817 ----------------------------------------------------------*/
818 int set_port_params( JNIEnv *env, int fd, int cspeed, int dataBits,
819 int stopBits, int parity )
820 {
821 struct termios ttyset;
822 int result = 0;
823 #if defined(TIOCGSERIAL)
824 struct serial_struct sstruct;
825 #endif /* TIOCGSERIAL */
826
827 if( tcgetattr( fd, &ttyset ) < 0 )
828 {
829 report( "set_port_params: Cannot Get Serial Port Settings\n" );
830 return(1);
831 }
832
833 if( translate_data_bits( env, &(ttyset.c_cflag), dataBits ) )
834 {
835 report( "set_port_params: Invalid Data Bits Selected\n" );
836 return(1);
837 }
838
839 if( translate_stop_bits( env, &(ttyset.c_cflag), stopBits ) )
840 {
841 report( "set_port_params: Invalid Stop Bits Selected\n" );
842 return(1);
843 }
844
845 if( translate_parity( env, &(ttyset.c_cflag), parity ) )
846 {
847 report( "set_port_params: Invalid Parity Selected\n" );
848 return(1);
849 }
850
851 #ifdef __FreeBSD_kernel__
852 if( cfsetspeed( &ttyset, cspeed ) < 0 )
853 {
854 report( "set_port_params: Cannot Set Speed\n" );
855 return( 1 );
856 }
857 #endif /* __FreeBSD_kernel__ */
858 if( !cspeed )
859 {
860 /* hang up the modem aka drop DTR */
861 /* Unix should handle this */
862 /*
863 mexPrintf("dropping DTR\n");
864 printf("dropping DTR\n");
865 */
866 ioctl( fd, TIOCMGET, &result );
867 result &= ~TIOCM_DTR;
868 ioctl( fd, TIOCMSET, &result );
869 }
870 /*
871 B38400 is a special case in Linux for custom baud rates.
872
873 We just treat this as a custom speed for now. If you take this ifdef
874 out and select baud rates 38400 then 28800 then 38400, you will get
875 a final baud rate of 28800 because you did not update the divisor.
876
877 However, if the serial port doesn't support TIOCGSERIAL or custom speeds,
878 don't fail: In this case, just use B38400 and assume that there is no way
879 to set a custom speed on this port.
880
881 See the next ifdef below for the divisor.
882 */
883 #if defined(TIOCGSERIAL)
884 if ( cspeed == B38400 && ioctl( fd, TIOCGSERIAL, &sstruct ) == 0 )
885 cspeed = 38400;
886 #endif /* TIOCGSERIAL */
887 if( cfsetispeed( &ttyset, cspeed ) < 0 ||
888 cfsetospeed( &ttyset, cspeed ) < 0 )
889 {
890 /*
891 Some people need to set the baud rate to ones not defined
892 in termios.h
893
894 This includes some baud rates which are supported by CommAPI
895 in Unix ( 14400, 28800, 128000, 256000 )
896
897 If the above fails, we assume this is not a defined
898 baud rate on Unix. With Win32, It is assumed the kernel
899 will do this for us.
900
901 The baud_base and desired speed are used to
902 calculate a custom divisor.
903
904 On linux the setserial man page covers this.
905 */
906
907 #if defined(TIOCGSERIAL)
908 if ( ioctl( fd, TIOCGSERIAL, &sstruct ) < 0 )
909 {
910 report( "set_port_params: Cannot Get Serial Port Settings\n" );
911 return(1);
912 }
913 sstruct.custom_divisor = ( sstruct.baud_base/cspeed );
914 #endif /* TIOCGSERIAL */
915 if( cfsetispeed( &ttyset, B38400 ) < 0 ||
916 cfsetospeed( &ttyset, B38400 ) < 0 )
917 {
918 /* OK, we tried everything */
919 report( "nativeSetSerialPortParams: Cannot Set Speed\n" );
920 return( 1 );
921 }
922 #if defined(TIOCSSERIAL)
923 /* It is assumed Win32 does this for us */
924 /* Ignore errors if the target speed is 38400: In this case,
925 * just assume TIOCSSERIAL is not supported and custom speeds are
926 * not available. */
927 if ( sstruct.baud_base < 1 ||
928 ioctl( fd, TIOCSSERIAL, &sstruct ) < 0 && cspeed != 38400 )
929 {
930 return( 1 );
931 }
932 #endif /* TIOCSSERIAL */
933 }
934
935 if( tcsetattr( fd, TCSANOW, &ttyset ) < 0 )
936 {
937 report("tcsetattr returns nonzero value!\n");
938 return( 1 );
939 }
940 return(0);
941 }
942
943 /*----------------------------------------------------------
944 RXTXPort.nativeSetSerialPortParams
945
946 accept: speed, data bits, stop bits, parity
947 perform: set the serial port parameters
948 return: jboolean 1 on error
949 exceptions: UnsupportedCommOperationException
950 ----------------------------------------------------------*/
951 JNIEXPORT jboolean JNICALL RXTXPort(nativeSetSerialPortParams)(
952 JNIEnv *env, jobject jobj, jint speed, jint dataBits, jint stopBits,
953 jint parity )
954 {
955 int fd = get_java_var( env, jobj,"fd","I" );
956 int cspeed = translate_speed( env, speed );
957
958 ENTER( "RXTXPort:nativeSetSerialPortParams" );
959 report_time_start( );
960
961 if (cspeed < 0 )
962 {
963 report(" invalid cspeed\n");
964 /*
965 For some reason the native exceptions are not being caught. Moving this
966 to the Java side fixed the issue. taj.
967 throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
968 "", "BaudRate could not be set to the specified value" );
969 */
970 return(1);
971 }
972
973
974 if( set_port_params( env, fd, cspeed, dataBits, stopBits, parity ) )
975 {
976 report("set_port_params failed\n");
977 LEAVE( "RXTXPort:nativeSetSerialPortParams" );
978 /*
979 For some reason the native exceptions are not being caught. Moving this
980 to the Java side fixed the issue. taj.
981 throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
982 "nativeSetSerialPortParams", strerror( errno ) );
983 */
984 return(1);
985 }
986
987 LEAVE( "RXTXPort:nativeSetSerialPortParams" );
988 report_time_end( );
989 return(0);
990 }
991
992 /*----------------------------------------------------------
993 translate_speed
994
995 accept: speed in bits-per-second
996 perform: convert bits-per-second to a speed_t constant
997 return: speed_t constant
998 exceptions: returns -1 and the calling method throws the exception so
999 it may be caught in java.
1000 comments: Only the lowest level code should know about
1001 the magic constants.
1002 ----------------------------------------------------------*/
1003 int translate_speed( JNIEnv *env, jint speed )
1004 {
1005 LEAVE( "RXTXPort:translate_speed" );
1006 switch( speed ) {
1007 case 0: return B0;
1008 case 50: return B50;
1009 case 75: return B75;
1010 case 110: return B110;
1011 case 134: return B134;
1012 case 150: return B150;
1013 case 200: return B200;
1014 case 300: return B300;
1015 case 600: return B600;
1016 case 1200: return B1200;
1017 case 1800: return B1800;
1018 case 2400: return B2400;
1019 case 4800: return B4800;
1020 case 9600: return B9600;
1021 #ifdef B14400
1022 case 14400: return B14400;
1023 #endif /* B14400 */
1024 case 19200: return B19200;
1025 #ifdef B28800
1026 case 28800: return B28800;
1027 #endif /* B28800 */
1028 case 38400: return B38400;
1029 case 57600: return B57600;
1030 /* I don't think this is universal.. older UARTs never did these. taj */
1031 #ifdef B115200
1032 case 115200: return B115200;
1033 #endif /* B115200 */
1034 #ifdef B128000 /* dima */
1035 case 128000: return B128000;
1036 #endif /* dima */
1037 #ifdef B230400
1038 case 230400: return B230400;
1039 #endif /* B230400 */
1040 #ifdef B256000 /* dima */
1041 case 256000: return B256000;
1042 #endif /* dima */
1043 #ifdef B460800
1044 case 460800: return B460800;
1045 #endif /* B460800 */
1046 #ifdef B500000
1047 case 500000: return B500000;
1048 #endif /* B500000 */
1049 #ifdef B576000
1050 case 576000: return B576000;
1051 #endif /* B57600 */
1052 #ifdef B921600
1053 case 921600: return B921600;
1054 #endif /* B921600 */
1055 #ifdef B1000000
1056 case 1000000: return B1000000;
1057 #endif /* B1000000 */
1058 #ifdef B1152000
1059 case 1152000: return B1152000;
1060 #endif /* B1152000 */
1061 #ifdef B1500000
1062 case 1500000: return B1500000;
1063 #endif /* B1500000 */
1064 #ifdef B2000000
1065 case 2000000: return B2000000;
1066 #endif /* B2000000 */
1067 #ifdef B2500000
1068 case 2500000: return B2500000;
1069 #endif /* B2500000 */
1070 #ifdef B3000000
1071 case 3000000: return B3000000;
1072 #endif /* B3000000 */
1073 #ifdef B3500000
1074 case 3500000: return B3500000;
1075 #endif /* B3500000 */
1076 #ifdef B4000000
1077 case 4000000: return B4000000;
1078 #endif /* B4000000 */
1079 }
1080
1081 /* Handle custom speeds */
1082 if( speed >= 0 ) return speed;
1083 else
1084 {
1085 LEAVE( "RXTXPort:translate_speed: Error condition" );
1086 return -1;
1087 }
1088 }
1089
1090 /*----------------------------------------------------------
1091 translate_data_bits
1092
1093 accept: gnu.io.SerialPort.DATABITS_* constant
1094 perform: set proper termios c_cflag bits
1095 return: 1 on error
1096 exceptions: UnsupportedCommOperationException
1097 ----------------------------------------------------------*/
1098 int translate_data_bits( JNIEnv *env, tcflag_t *cflag, jint dataBits )
1099 {
1100 int temp = (*cflag) & ~CSIZE;
1101
1102 ENTER( "translate_date_bits" );
1103 switch( dataBits ) {
1104 case JDATABITS_5:
1105 (*cflag) = temp | CS5;
1106 return 0;
1107 case JDATABITS_6:
1108 (*cflag) = temp | CS6;
1109 return 0;
1110 case JDATABITS_7:
1111 (*cflag) = temp | CS7;
1112 return 0;
1113 case JDATABITS_8:
1114 (*cflag) = temp | CS8;
1115 return 0;
1116 }
1117
1118 LEAVE( "RXTXPort:translate_date_bits" );
1119 /*
1120 For some reason the native exceptions are not being caught. Moving this
1121 to the Java side fixed the issue. taj.
1122 throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
1123 "", "databit value not supported" );
1124 */
1125 return 1;
1126 }
1127
1128 /*----------------------------------------------------------
1129 translate_stop_bits
1130
1131 accept: gnu.io.SerialPort.STOPBITS_* constant
1132 perform: set proper termios c_cflag bits
1133 return: 1 on error
1134 exceptions: UnsupportedCommOperationException
1135 comments: If you specify 5 data bits and 2 stop bits, the port will
1136 allegedly use 1.5 stop bits. Does anyone care?
1137 ----------------------------------------------------------*/
1138 int translate_stop_bits( JNIEnv *env, tcflag_t *cflag, jint stopBits )
1139 {
1140 ENTER( "translate_stop_bits" );
1141 switch( stopBits ) {
1142 case STOPBITS_1:
1143 (*cflag) &= ~CSTOPB;
1144 LEAVE( "RXTXPort:translate_stop_bits" );
1145 return 0;
1146 /* ok.. lets try putting it in and see if anyone notices */
1147 case STOPBITS_1_5:
1148 (*cflag) |= CSTOPB;
1149 if ( translate_data_bits( env, cflag, JDATABITS_5 ) )
1150 return( 1 );
1151 return 0;
1152 case STOPBITS_2:
1153 (*cflag) |= CSTOPB;
1154 LEAVE( "RXTXPort:translate_stop_bits" );
1155 return 0;
1156 }
1157
1158 LEAVE( "RXTXPort:translate_stop_bits" );
1159 /*
1160 For some reason the native exceptions are not being caught. Moving this
1161 to the Java side fixed the issue. taj.
1162 throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
1163 "", "stopbit value not supported" );
1164 */
1165 return 1;
1166 }
1167 JNIEXPORT jint JNICALL RXTXPort(nativeGetFlowControlMode)(JNIEnv *env, jobject jobj, jint fd)
1168 {
1169 struct termios ttyset;
1170 int ret = 0;
1171
1172 tcgetattr( fd, &ttyset );
1173
1174 if( ttyset.c_cflag & HARDWARE_FLOW_CONTROL )
1175 {
1176 ret |= ( FLOWCONTROL_RTSCTS_IN | FLOWCONTROL_RTSCTS_OUT );
1177 }
1178 if ( ttyset.c_iflag & IXOFF )
1179 {
1180 ret |= FLOWCONTROL_XONXOFF_IN;
1181 }
1182 if ( ttyset.c_iflag & IXON )
1183 {
1184 ret |= FLOWCONTROL_XONXOFF_OUT;
1185 }
1186 return( (jint) ret );
1187 }
1188 JNIEXPORT jint JNICALL RXTXPort(nativeGetParity)(JNIEnv *env, jobject jobj, jint fd)
1189 {
1190 struct termios ttyset;
1191
1192 if( tcgetattr( fd, &ttyset ) < 0 )
1193 {
1194 report("nativeGetParity: tcgetattr failed\n");
1195 return( -1 );
1196 }
1197 #ifdef CMSPAR
1198 if ( ( ttyset.c_cflag & PARENB ) &&
1199 ( ttyset.c_cflag & PARODD ) &&
1200 ( ttyset.c_cflag & CMSPAR ) )
1201 {
1202 return( JPARITY_MARK );
1203 }
1204 else if ( ttyset.c_cflag & ( PARENB &&
1205 ttyset.c_cflag & CMSPAR ) )
1206 {
1207 return( JPARITY_SPACE );
1208 }
1209 #endif /* CMSPAR */
1210 if ( ttyset.c_cflag & PARENB &&
1211 ttyset.c_cflag & PARODD )
1212 {
1213 return( JPARITY_ODD );
1214 }
1215 else if ( ttyset.c_cflag & PARENB )
1216 {
1217 return( JPARITY_EVEN );
1218 }
1219 else
1220 {
1221 return( JPARITY_NONE );
1222 }
1223 }
1224
1225 /*----------------------------------------------------------
1226 translate_parity
1227
1228 accept: javax.comm.SerialPort.PARITY_* constant
1229 perform: set proper termios c_cflag bits
1230 return: 1 on error
1231 exceptions: UnsupportedCommOperationException
1232 comments: The CMSPAR bit should be used for 'mark' and 'space' parity,
1233 but it's not in glibc's includes. Oh well, rarely used anyway.
1234 ----------------------------------------------------------*/
1235 int translate_parity( JNIEnv *env, tcflag_t *cflag, jint parity )
1236 {
1237 ENTER( "translate_parity" );
1238 #ifdef CMSPAR
1239 (*cflag) &= ~(PARENB | PARODD | CMSPAR );
1240 #endif /* CMSPAR */
1241 switch( parity ) {
1242 case JPARITY_NONE:
1243 LEAVE( "translate_parity" );
1244 return 0;
1245 case JPARITY_EVEN:
1246 (*cflag) |= PARENB;
1247 LEAVE( "translate_parity" );
1248 return 0;
1249 case JPARITY_ODD:
1250 (*cflag) |= PARENB | PARODD;
1251 LEAVE( "translate_parity" );
1252 return 0;
1253 #ifdef CMSPAR
1254 case JPARITY_MARK:
1255 (*cflag) |= PARENB | PARODD | CMSPAR;
1256 LEAVE( "translate_parity" );
1257 return 0;
1258 case JPARITY_SPACE:
1259 (*cflag) |= PARENB | CMSPAR;
1260 LEAVE( "translate_parity" );
1261 return 0;
1262 #endif /* CMSPAR */
1263 default:
1264 printf("Parity missed %i\n", (int) parity );
1265 }
1266
1267 LEAVE( "translate_parity" );
1268 /*
1269 For some reason the native exceptions are not being caught. Moving this
1270 to the Java side fixed the issue. taj.
1271 throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
1272 "", "parity value not supported" );
1273 */
1274 return 1;
1275 }
1276 #if !defined(TIOCSERGETLSR) && !defined(WIN32)
1277 /*----------------------------------------------------------
1278 drain_loop()
1279
1280 accept:
1281 perform: call tcdrain() and report an event when it succeds
1282 return: none
1283 exceptions:
1284 comments:
1285 ----------------------------------------------------------*/
1286 void *drain_loop( void *arg )
1287 {
1288 struct event_info_struct *eis = ( struct event_info_struct * ) arg;
1289 /* char msg[80]; */
1290 int i;
1291 pthread_detach( pthread_self() );
1292
1293 for(i=0;;i++)
1294 {
1295 report_verbose("drain_loop: looping\n");
1296 if( eis->eventloop_interrupted )
1297 {
1298 goto end;
1299 }
1300 #if defined(__sun__)
1301 /* FIXME: No time to test on all OS's for production */
1302 if (usleep(5000)) {
1303 report("drain_loop: received EINTR");
1304 }
1305 #else
1306 if (usleep(1000000)) {
1307 report("drain_loop: received EINTR");
1308 }
1309 #endif /* __sun__ */
1310 /*
1311 system_wait();
1312 */
1313 if( eis->eventloop_interrupted )
1314 {
1315 goto end;
1316 }
1317 if( tcdrain( eis->fd ) == 0 )
1318 {
1319 if( eis && eis->writing )
1320 {
1321 /*
1322 sprintf(msg, "drain_loop: setting OUTPUT_BUFFER_EMPTY\n" );
1323 report( msg );
1324 */
1325 eis->output_buffer_empty_flag = 1;
1326 eis->writing=JNI_FALSE;
1327 }
1328 else
1329 {
1330 if( !eis )
1331 {
1332 goto end;
1333 }
1334 report_verbose("drain_loop: writing not set\n");
1335 }
1336 }
1337 else if (errno != EINTR)
1338 {
1339 report("drain_loop: tcdrain bad fd\n");
1340 goto end;
1341 }
1342 else
1343 {
1344 report("drain_loop: received EINTR in tcdrain\n");
1345 }
1346 }
1347 end:
1348 report("------------------ drain_loop exiting ---------------------\n");
1349 eis->closing = 1;
1350 pthread_exit( NULL );
1351 return( NULL );
1352 }
1353 #endif /* !defined(TIOCSERGETLSR) && !defined(WIN32) */
1354 /*----------------------------------------------------------
1355 finalize_threads( )
1356
1357 accept: event_info_struct used to access java and communicate with
1358 eventLoop().
1359 perform: see comments
1360 return: none
1361 exceptions: none
1362 comments:
1363 The is the pthread spawned on systems that can't access the
1364 LSR (Line Status Register). Without access to the LSR rxtx
1365 cannot detect when the output buffer is empty in the Monitor
1366 Thread. The solution is to return the value of write's return
1367 but hang around in this thread waiting for tcdrain to finish.
1368
1369 once the drain has finished, we let the eventLoop know that the
1370 output buffer is empty and the Signal is sent.
1371 ----------------------------------------------------------*/
1372 void finalize_threads( struct event_info_struct *eis )
1373 {
1374 #if !defined(TIOCSERGETLSR) && !defined( WIN32 )
1375 /* used to shut down any remaining write threads */
1376
1377 eis->output_buffer_empty_flag = 0;
1378 ENTER("finalize_threads\n");
1379
1380 /* need to clean up again after working events */
1381 LEAVE("---------------- finalize_threads ---------------");
1382 #endif /* TIOCSERGETLSR & !WIN32 */
1383 }
1384
1385 #if !defined(TIOCSERGETLSR) && !defined( WIN32 )
1386 static void warn_sig_abort( int signo )
1387 {
1388 /*
1389 char msg[80];
1390 sprintf( msg, "RXTX Recieved Signal %i\n", signo );
1391 report_error( msg );
1392 */
1393 }
1394 #endif /* TIOCSERGETLSR */
1395
1396 /*----------------------------------------------------------
1397 init_threads( )
1398
1399 accept: none
1400 perform:
1401 return: none
1402 exceptions: none
1403 comments:
1404 this function is called from the event_loop or in other words
1405 from the monitor thread. On systems !WIN32 and without TIOCSERGETLSR
1406 it will create a new thread looping a call to tcdrain.
1407 ----------------------------------------------------------*/
1408 int init_threads( struct event_info_struct *eis )
1409 {
1410 jfieldID jeis;
1411 #if !defined(TIOCSERGETLSR) & !defined(WIN32)
1412 sigset_t newmask, oldmask;
1413 struct sigaction newaction, oldaction;
1414 pthread_t tid;
1415
1416 report_time_start( );
1417 report("init_threads: start\n");
1418 /* ignore child thread status changes */
1419 sigemptyset(&newmask);
1420 sigaddset(&newmask, SIGCHLD);
1421
1422 /* install our own signal hander */
1423 newaction.sa_handler = warn_sig_abort;
1424 sigemptyset( &newaction.sa_mask );
1425 #ifdef SA_INTERRUPT
1426 newaction.sa_flags = SA_INTERRUPT;
1427 #endif /* SA_INTERRUPT */
1428 #ifdef SA_RESTART
1429 /* JOE: do not demand restart! we are handling EINTR */
1430 /* newaction.sa_flags = SA_RESTART;*/
1431 #endif /* SA_RESTART */
1432
1433 sigaction(SIGABRT, &newaction, &oldaction);
1434 sigaction(SIGCHLD, &newaction, &oldaction);
1435 sigaction(SIGALRM, &newaction, &oldaction);
1436 sigaction(SIGCONT, &newaction, &oldaction);
1437 /*
1438 sigaction(SIGPOLL, &newaction, &oldaction);
1439 sigaction(SIGTRAP, &newaction, &oldaction);
1440 sigaction(SIGBUS, &newaction, &oldaction);
1441 sigaction(SIGSEGV, &newaction, &oldaction);
1442 sigaction(SIGFPE, &newaction, &oldaction);
1443 sigaction(SIGILL, &newaction, &oldaction);
1444
1445 sigfillset(&newmask);
1446 sigprocmask( SIG_SETMASK, &newmask, &oldmask );
1447 pthread_sigmask( SIG_BLOCK, &newmask, &oldmask );
1448 */
1449 sigprocmask( SIG_SETMASK, &newmask, &oldmask );
1450
1451 report("init_threads: creating drain_loop\n");
1452 pthread_create( &tid, NULL, drain_loop, (void *) eis );
1453 pthread_detach( tid );
1454 eis->drain_tid = tid;
1455 #endif /* TIOCSERGETLSR */
1456 report("init_threads: get eis\n");
1457 jeis = (*eis->env)->GetFieldID( eis->env, eis->jclazz, "eis", "J" );
1458 report("init_threads: set eis\n");
1459 (*eis->env)->SetIntField(eis->env, *eis->jobj, jeis, ( size_t ) eis );
1460 report("init_threads: stop\n");
1461 report_time_end( );
1462 return( 1 );
1463 }
1464
1465 /*----------------------------------------------------------
1466 RXTXPort.writeByte
1467
1468 accept: byte to write (passed as int)
1469 jboolean interrupted (no events if true)
1470 perform: write a single byte to the port
1471 return: none
1472 exceptions: IOException
1473 ----------------------------------------------------------*/
1474 JNIEXPORT void JNICALL RXTXPort(writeByte)( JNIEnv *env,
1475 jobject jobj, jint ji, jboolean interrupted )
1476 {
1477 #ifndef TIOCSERGETLSR
1478 struct event_info_struct *index = master_index;
1479 #endif
1480 unsigned char byte = (unsigned char)ji;
1481 int fd = get_java_var( env, jobj,"fd","I" );
1482 int result;
1483 char msg[80];
1484 #if defined ( __sun__ )
1485 int count;
1486 #endif /* __sun__ */
1487
1488 report_time_start();
1489 ENTER( "RXTXPort:writeByte" );
1490 do {
1491 sprintf( msg, "writeByte %c>>\n", byte );
1492 report( msg );
1493 result=WRITE (fd, (void * ) &byte, sizeof(unsigned char));
1494 } while (result < 0 && errno==EINTR);
1495 if( result < 0 )
1496 {
1497 /* mexPrintf("GOT IT!!!\n"); */
1498 goto fail;
1499 }
1500 /*
1501 This makes write for win32, glinux and Sol behave the same
1502 #if defined ( __sun__ )
1503 do {
1504 report_verbose( "nativeDrain: trying tcdrain\n" );
1505 result=tcdrain(fd);
1506 count++;
1507 } while (result && errno==EINTR && count <3);
1508 #endif */ /* __sun __ */
1509 #ifndef TIOCSERGETLSR
1510 if( ! interrupted )
1511 {
1512 index = master_index;
1513 if( index )
1514 {
1515 while( index->fd != fd &&
1516 index->next ) index = index->next;
1517 }
1518 index->writing = 1;
1519 report( "writeByte: index->writing = 1" );
1520 }
1521 #endif
1522 sprintf( msg, "RXTXPort:writeByte %i\n", result );
1523 report( msg );
1524 LEAVE( "RXTXPort:writeByte" );
1525 if(result >= 0)
1526 {
1527 report_time_end();
1528 return;
1529 }
1530 fail:
1531 throw_java_exception( env, IO_EXCEPTION, "writeByte",
1532 strerror( errno ) );
1533 }
1534
1535 /*----------------------------------------------------------
1536 RXTXPort.writeArray
1537
1538 accept: jbarray: bytes used for writing
1539 offset: offset in array to start writing
1540 count: Number of bytes to write
1541 jboolean interrupted (no events if true)
1542 perform: write length bytes of jbarray
1543 return: none
1544 exceptions: IOException
1545 ----------------------------------------------------------*/
1546 JNIEXPORT void JNICALL RXTXPort(writeArray)( JNIEnv *env,
1547 jobject jobj, jbyteArray jbarray, jint offset, jint count,
1548 jboolean interrupted )
1549 {
1550 #ifndef TIOCSERGETLSR
1551 struct event_info_struct *index = master_index;
1552 #endif /* TIOCSERGETLSR */
1553 int fd;
1554 int result=0,total=0;
1555 jbyte *body;
1556 #if defined ( __sun__ )
1557 int icount;
1558 #endif /* __sun__ */
1559 /*
1560 char message[1000];
1561 */
1562 #if defined ( __sun__ )
1563 struct timespec retspec;
1564
1565 retspec.tv_sec = 0;
1566 retspec.tv_nsec = 50000;
1567 #endif /* __sun__ */
1568 fd = get_java_var( env, jobj,"fd","I" );
1569 body = (*env)->GetByteArrayElements( env, jbarray, 0 );
1570 /* result=WRITE (fd, body + total + offset, count - total);
1571 (*env)->ReleaseByteArrayElements( env, jbarray, body, 0 ); */
1572 /* return; OH CRAP */
1573
1574 report_time_start();
1575 ENTER( "writeArray" );
1576 /* warning Roy Rogers */
1577 /*
1578 sprintf( message, "::::RXTXPort:writeArray(%s);\n", (char *) body );
1579 report_verbose( message );
1580 */
1581
1582 do {
1583 result=WRITE (fd, (void * ) ((char *) body + total + offset), count - total); /* dima */
1584 if(result >0){
1585 total += result;
1586 }
1587 report("writeArray()\n");
1588 } while ( ( total < count ) && (result < 0 && errno==EINTR ) );
1589 if( result < 0 )
1590 {
1591 /* mexPrintf("GOT IT!!!\n"); */
1592 goto fail;
1593 }
1594 /*
1595 This makes write for win32, glinux and Sol behave the same
1596 #if defined ( __sun__ )
1597 do {
1598 report_verbose( "nativeDrain: trying tcdrain\n" );
1599 result=tcdrain(fd);
1600 icount++;
1601 } while (result && errno==EINTR && icount <3);
1602 #endif */ /* __sun__ */
1603 (*env)->ReleaseByteArrayElements( env, jbarray, body, 0 );
1604 #ifndef TIOCSERGETLSR
1605 if( !interrupted )
1606 {
1607 if( index )
1608 {
1609 while( index->fd != fd &&
1610 index->next ) index = index->next;
1611 }
1612 index->writing = 1;
1613 report( "writeArray: index->writing = 1" );
1614 }
1615 #endif /* TIOCSERGETLSR */
1616 /*
1617 50 ms sleep to make sure read can get in
1618
1619 what I think is happening here is the data writen is causing
1620 signals, the event loop can't select with data available
1621
1622 I think things like BlackBox with 2 ports open are getting
1623 signals for both the reciever and transmitter since they
1624 are the same PID.
1625
1626 Things just start spinning out of control after that.
1627 */
1628 LEAVE( "RXTXPort:writeArray" );
1629 report_time_end();
1630 fail:
1631 if( result < 0 ) throw_java_exception( env, IO_EXCEPTION,
1632 "writeArray", strerror( errno ) );
1633 }
1634
1635 /*----------------------------------------------------------
1636 RXTXPort.nativeDrain
1637
1638 accept: jboolean interrupted (no events if true)
1639 perform: wait until all data is transmitted
1640 return: none
1641 exceptions: IOException
1642 comments: java.io.OutputStream.flush() is equivalent to tcdrain,
1643 not tcflush, which throws away unsent bytes
1644
1645 count logic added to avoid infinite loops when EINTR is
1646 true... Thread.yeild() was suggested.
1647 ----------------------------------------------------------*/
1648 JNIEXPORT jboolean JNICALL RXTXPort(nativeDrain)( JNIEnv *env,
1649 jobject jobj, jboolean interrupted )
1650 {
1651 int fd = get_java_var( env, jobj,"fd","I" );
1652 struct event_info_struct *eis = ( struct event_info_struct * ) get_java_var( env, jobj, "eis", "J" );
1653 int result, count=0;
1654
1655 char message[80];
1656
1657 ENTER( "SerialImp.c:drain()" );
1658 report_time_start( );
1659 do {
1660 report_verbose( "nativeDrain: trying tcdrain\n" );
1661 result=tcdrain(fd);
1662 count++;
1663 } while (result && errno==EINTR && count <3);
1664
1665 sprintf( message, "RXTXPort:drain() returns: %i\n", result );
1666 report_verbose( message );
1667 #if defined(__sun__)
1668 /* FIXME: No time to test on all OS's for production */
1669 return( JNI_TRUE );
1670 #endif /* __sun__ */
1671 LEAVE( "RXTXPort:drain()" );
1672 if( result ) throw_java_exception( env, IO_EXCEPTION, "nativeDrain",
1673 strerror( errno ) );
1674 if( interrupted ) return( JNI_FALSE );
1675 #if !defined(TIOCSERGETLSR) && !defined(WIN32)
1676 if( eis && eis->writing )
1677 {
1678 eis->writing=JNI_FALSE;
1679 eis->output_buffer_empty_flag = 0;
1680 }
1681 #endif /* !TIOCSERGETLSR !WIN32 */
1682 if( eis && eis->eventflags[SPE_OUTPUT_BUFFER_EMPTY] )
1683 {
1684 struct event_info_struct myeis =
1685 build_threadsafe_eis( env, &jobj, eis );
1686 send_event( &myeis, SPE_OUTPUT_BUFFER_EMPTY, 1 );
1687 }
1688 report_time_end( );
1689 return( JNI_FALSE );
1690 }
1691
1692 /*----------------------------------------------------------
1693 RXTXPort.sendBreak
1694
1695 accept: duration in milliseconds.
1696 perform: send break for actual time. not less than 0.25 seconds.
1697 exceptions: none
1698 comments: not very precise
1699 ----------------------------------------------------------*/
1700 JNIEXPORT void JNICALL RXTXPort(sendBreak)( JNIEnv *env,
1701 jobject jobj, jint duration )
1702 {
1703 int fd = get_java_var( env, jobj,"fd","I" );
1704 report_time_start( );
1705 ENTER( "RXTXPort:sendBreak()" );
1706 tcsendbreak( fd, (int)( duration / 250 ) );
1707 report_time_end( );
1708 LEAVE( "RXTXPort:sendBreak()" );
1709 }
1710
1711 /*----------------------------------------------------------
1712 RXTXPort.NativegetReceiveTimeout
1713
1714 accept: none
1715 perform: get termios.c_cc[VTIME]
1716 return: VTIME
1717 comments: see NativeEnableReceiveTimeoutThreshold
1718 ----------------------------------------------------------*/
1719 JNIEXPORT jint JNICALL RXTXPort(NativegetReceiveTimeout)(
1720 JNIEnv *env,
1721 jobject jobj
1722 )
1723 {
1724 int fd = get_java_var( env, jobj,"fd","I" );
1725 struct termios ttyset;
1726
1727 ENTER( "RXTXPort:nativegetRecieveTimeout()" );
1728 if( tcgetattr( fd, &ttyset ) < 0 ) goto fail;
1729 LEAVE( "RXTXPort:nativegetRecieveTimeout()" );
1730 return(ttyset.c_cc[ VTIME ] * 100);
1731 fail:
1732 LEAVE( "RXTXPort:nativegetRecieveTimeout()" );
1733 throw_java_exception( env, IO_EXCEPTION, "getReceiveTimeout",
1734 strerror( errno ) );
1735 return -1;
1736 }
1737
1738 /*----------------------------------------------------------
1739 RXTXPort.NativeisReceiveTimeoutEnabled
1740
1741 accept: none
1742 perform: determine if VTIME is none 0
1743 return: JNI_TRUE if VTIME > 0 else JNI_FALSE
1744 comments: see NativeEnableReceiveTimeoutThreshold
1745 ----------------------------------------------------------*/
1746 JNIEXPORT jboolean JNICALL RXTXPort(NativeisReceiveTimeoutEnabled)(
1747 JNIEnv *env,
1748 jobject jobj
1749 )
1750 {
1751 int fd = get_java_var( env, jobj,"fd","I" );
1752 struct termios ttyset;
1753 ENTER( "RXTXPort:NativeisRecieveTimeoutEnabled()" );
1754 if( tcgetattr( fd, &ttyset ) < 0 ) goto fail;
1755 LEAVE( "RXTXPort:NativeisRecieveTimeoutEnabled()" );
1756 return(ttyset.c_cc[ VTIME ] > 0 ? JNI_TRUE:JNI_FALSE);
1757 fail:
1758 LEAVE( "RXTXPort:NativeisRecieveTimeoutEnabled()" );
1759 throw_java_exception( env, IO_EXCEPTION, "isReceiveTimeoutEnabled",
1760 strerror( errno ) );
1761 return JNI_FALSE;
1762 }
1763
1764 /*----------------------------------------------------------
1765 RXTXPort.isDSR
1766
1767 accept: none
1768 perform: check status of DSR
1769 return: true if TIOCM_DSR is set
1770 false if TIOCM_DSR is not set
1771 exceptions: none
1772 comments: DSR stands for Data Set Ready
1773 ----------------------------------------------------------*/
1774 JNIEXPORT jboolean JNICALL RXTXPort(isDSR)( JNIEnv *env,
1775 jobject jobj )
1776 {
1777 unsigned int result = 0;
1778 int fd = get_java_var( env, jobj,"fd","I" );
1779 char message[80];
1780
1781 ENTER( "RXTXPort:isDSR" );
1782 ioctl( fd, TIOCMGET, &result );
1783 sprintf( message, "RXTXPort:isDSR returns %i\n", result & TIOCM_DSR );
1784 report( message );
1785 LEAVE( "RXTXPort:isDSR" );
1786 if( result & TIOCM_DSR ) return JNI_TRUE;
1787 else return JNI_FALSE;
1788 }
1789
1790 /*----------------------------------------------------------
1791 RXTXPort.isCD
1792
1793 accept: none
1794 perform: check status of CD
1795 return: true if TIOCM_CD is set
1796 false if TIOCM_CD is not set
1797 exceptions: none
1798 comments: CD stands for Carrier Detect
1799 The following comment has been made...
1800 "well, it works, there might ofcourse be a bug, but making DCD
1801 permanently on fixed it for me so I don't care"
1802
1803 ----------------------------------------------------------*/
1804 JNIEXPORT jboolean JNICALL RXTXPort(isCD)( JNIEnv *env,
1805 jobject jobj )
1806 {
1807 unsigned int result = 0;
1808 int fd = get_java_var( env, jobj,"fd","I" );
1809 char message[80];
1810
1811 ENTER( "RXTXPort:isCD" );
1812 ioctl( fd, TIOCMGET, &result );
1813 sprintf( message, "RXTXPort:isCD returns %i\n", result & TIOCM_CD );
1814 LEAVE( "RXTXPort:isCD" );
1815 if( result & TIOCM_CD ) return JNI_TRUE;
1816 else return JNI_FALSE;
1817 }
1818
1819 /*----------------------------------------------------------
1820 RXTXPort.isCTS
1821
1822 accept: none
1823 perform: check status of CTS
1824 return: true if TIOCM_CTS is set
1825 false if TIOCM_CTS is not set
1826 exceptions: none
1827 comments: CTS stands for Clear To Send.
1828 ----------------------------------------------------------*/
1829 JNIEXPORT jboolean JNICALL RXTXPort(isCTS)( JNIEnv *env,
1830 jobject jobj )
1831 {
1832 unsigned int result = 0;
1833 int fd = get_java_var( env, jobj,"fd","I" );
1834 char message[80];
1835
1836 ENTER( "RXTXPort:isCTS" );
1837 ioctl( fd, TIOCMGET, &result );
1838 sprintf( message, "RXTXPort:isCTS returns %i\n", result & TIOCM_CTS );
1839 report( message );
1840 LEAVE( "RXTXPort:isCTS" );
1841 if( result & TIOCM_CTS ) return JNI_TRUE;
1842 else return JNI_FALSE;
1843 }
1844
1845 /*----------------------------------------------------------
1846 RXTXPort.isRI
1847
1848 accept: none
1849 perform: check status of RI
1850 return: true if TIOCM_RI is set
1851 false if TIOCM_RI is not set
1852 exceptions: none
1853 comments: RI stands for Ring Indicator
1854 ----------------------------------------------------------*/
1855 JNIEXPORT jboolean JNICALL RXTXPort(isRI)( JNIEnv *env,
1856 jobject jobj )
1857 {
1858 unsigned int result = 0;
1859 int fd = get_java_var( env, jobj,"fd","I" );
1860 char message[80];
1861
1862 ENTER( "RXTXPort:isRI" );
1863 ioctl( fd, TIOCMGET, &result );
1864 sprintf( message, "RXTXPort:isRI returns %i\n", result & TIOCM_RI );
1865 report( message );
1866 LEAVE( "RXTXPort:isRI" );
1867 if( result & TIOCM_RI ) return JNI_TRUE;
1868 else return JNI_FALSE;
1869 }
1870
1871 /*----------------------------------------------------------
1872 RXTXPort.isRTS
1873
1874 accept: none
1875 perform: check status of RTS
1876 return: true if TIOCM_RTS is set
1877 false if TIOCM_RTS is not set
1878 exceptions: none
1879 comments: tcgetattr with c_cflag CRTS_IFLOW
1880 ----------------------------------------------------------*/
1881 JNIEXPORT jboolean JNICALL RXTXPort(isRTS)( JNIEnv *env,
1882 jobject jobj )
1883 {
1884 unsigned int result = 0;
1885 int fd = get_java_var( env, jobj,"fd","I" );
1886 char message[80];
1887
1888 ENTER( "RXTXPort:isRTS" );
1889 ioctl( fd, TIOCMGET, &result );
1890 sprintf( message, "RXTXPort:isRTS returns %i\n", result & TIOCM_RTS );
1891 report( message );
1892 LEAVE( "RXTXPort:isRTS" );
1893 if( result & TIOCM_RTS ) return JNI_TRUE;
1894 else return JNI_FALSE;
1895 }
1896
1897 /*----------------------------------------------------------
1898 RXTXPort.setRTS
1899
1900 accept: state flag to set/unset.
1901 perform: depends on the state flag
1902 if true TIOCM_RTS is set
1903 if false TIOCM_RTS is unset
1904 return: none
1905 exceptions: none
1906 comments: tcsetattr with c_cflag CRTS_IFLOW
1907 ----------------------------------------------------------*/
1908 JNIEXPORT void JNICALL RXTXPort(setRTS)( JNIEnv *env,
1909 jobject jobj, jboolean state )
1910 {
1911 unsigned int result = 0;
1912 int fd = get_java_var( env, jobj,"fd","I" );
1913 char message[80];
1914
1915 ENTER( "RXTXPort:setRTS" );
1916 ioctl( fd, TIOCMGET, &result );
1917 if( state == JNI_TRUE ) result |= TIOCM_RTS;
1918 else result &= ~TIOCM_RTS;
1919 ioctl( fd, TIOCMSET, &result );
1920 sprintf( message, "setRTS( %i )\n", state );
1921 report( message );
1922 LEAVE( "RXTXPort:setRTS" );
1923 return;
1924 }
1925
1926 /*----------------------------------------------------------
1927 RXTXPort.setDSR
1928
1929 accept: state flag to set/unset.
1930 perform: depends on the state flag
1931 if true TIOCM_DSR is set
1932 if false TIOCM_DSR is unset
1933 return: none
1934 exceptions: none
1935 comments: tcsetattr with c_cflag CRTS_IFLOW
1936 ----------------------------------------------------------*/
1937 JNIEXPORT void JNICALL RXTXPort(setDSR)( JNIEnv *env,
1938 jobject jobj, jboolean state )
1939 {
1940 unsigned int result = 0;
1941 int fd = get_java_var( env, jobj,"fd","I" );
1942 char message[80];
1943
1944 ENTER( "RXTXPort:setDSR()" );
1945 ioctl( fd, TIOCMGET, &result );
1946
1947 sprintf( message, "setDSR( %i )\n", state );
1948 if( state == JNI_TRUE ) result |= TIOCM_DSR;
1949 else result &= ~TIOCM_DSR;
1950 ioctl( fd, TIOCMSET, &result );
1951 sprintf( message, "setDSR( %i )\n", state );
1952 report( message );
1953 LEAVE( "RXTXPort:setDSR()" );
1954 return;
1955 }
1956
1957 /*----------------------------------------------------------
1958 RXTXPort.isDTR
1959
1960 accept: none
1961 perform: check status of DTR
1962 return: true if TIOCM_DTR is set
1963 false if TIOCM_DTR is not set
1964 exceptions: none
1965 comments: DTR stands for Data Terminal Ready
1966 ----------------------------------------------------------*/
1967 JNIEXPORT jboolean JNICALL RXTXPort(isDTR)( JNIEnv *env,
1968 jobject jobj )
1969 {
1970 unsigned int result = 0;
1971 int fd = get_java_var( env, jobj,"fd","I" );
1972 char message[80];
1973
1974 ENTER( "RXTXPort:isDTR" );
1975 ioctl( fd, TIOCMGET, &result );
1976 sprintf( message, "isDTR( ) returns %i\n", result& TIOCM_DTR );
1977 report( message );
1978 LEAVE( "RXTXPort:isDTR" );
1979 if( result & TIOCM_DTR ) return JNI_TRUE;
1980 else return JNI_FALSE;
1981 }
1982
1983 /*----------------------------------------------------------
1984 RXTXPort.setDTR
1985
1986 accept: new DTR state
1987 perform: if state is true, TIOCM_DTR is set
1988 if state is false, TIOCM_DTR is unset
1989 return: none
1990 exceptions: none
1991 comments: DTR stands for Data Terminal Ready
1992 ----------------------------------------------------------*/
1993 JNIEXPORT void JNICALL RXTXPort(setDTR)( JNIEnv *env,
1994 jobject jobj, jboolean state )
1995 {
1996 unsigned int result = 0;
1997 int fd = get_java_var( env, jobj,"fd","I" );
1998 char message[80];
1999
2000 ENTER( "RXTXPort:setDTR" );
2001 ioctl( fd, TIOCMGET, &result );
2002 if( state == JNI_TRUE ) result |= TIOCM_DTR;
2003 else result &= ~TIOCM_DTR;
2004 ioctl( fd, TIOCMSET, &result );
2005 sprintf( message, "setDTR( %i )\n", state );
2006 report( message );
2007 LEAVE( "RXTXPort:setDTR" );
2008 return;
2009 }
2010 /*----------------------------------------------------------
2011 RXTXPort.static_add_filename
2012
2013 accept: filename and fd to save
2014 perform: add a struct holding the info to a linked list
2015 return: none
2016 exceptions: none
2017 comments: the info is checked on open() if its in the list no
2018 changes are performed on the file on open()
2019
2020 comments: see
2021 RXTXPort.nativeStaticSetDSR
2022 RXTXPort.nativeStaticSetDTR
2023 RXTXPort.nativeStaticSetRTS
2024 RXTXPort.nativeStaticSetSerialPortParams
2025 This is used so people can setDTR low before calling the
2026 -----------------------------------------------------------*/
2027
2028 void static_add_filename( const char *filename, int fd)
2029 {
2030 struct preopened *newp, *p = preopened_port;
2031
2032 newp = malloc( sizeof( struct preopened ) );
2033 strcpy( newp->filename, filename );
2034 newp->fd = fd;
2035
2036 if( !p )
2037 {
2038 newp->next = NULL;
2039 newp->prev = NULL;
2040 preopened_port = newp;
2041 return;
2042 }
2043 for(;;)
2044 {
2045 if( !strcmp( p->filename, filename) )
2046 {
2047 /* already open */
2048 return;
2049 }
2050 if( p->next )
2051 {
2052 p = p->next;
2053 }
2054 else
2055 {
2056 /* end of list */
2057 newp->next = NULL;
2058 newp->prev = p;
2059 p->next = newp;
2060 preopened_port = p;
2061 return;
2062 }
2063 }
2064 }
2065 /*----------------------------------------------------------
2066 RXTXPort.nativeSetBaudBase
2067
2068 accept: The Baud Base for custom speeds
2069 perform: set the Baud Base
2070 return: 0 on success
2071 exceptions: Unsupported Comm Operation on systems not supporting
2072 TIOCGSERIAL
2073 comments:
2074 Set baud rate to 38400 before using this
2075 First introduced in rxtx-2.1-3
2076 ----------------------------------------------------------*/
2077 JNIEXPORT jboolean JNICALL RXTXPort(nativeSetBaudBase)(
2078 JNIEnv *env,
2079 jobject jobj,
2080 jint BaudBase
2081 )
2082 {
2083
2084 #if defined(TIOCGSERIAL)
2085
2086 int fd = get_java_var( env, jobj,"fd","I" );
2087 struct serial_struct sstruct;
2088
2089 if ( ioctl( fd, TIOCGSERIAL, &sstruct ) < 0 )
2090 {
2091 goto fail;
2092 }
2093
2094 sstruct.baud_base = (int) BaudBase;
2095
2096 if ( sstruct.baud_base < 1 ||
2097 ioctl( fd, TIOCSSERIAL, &sstruct ) < 0 )
2098 {
2099 goto fail;
2100 }
2101 return( ( jboolean ) 0 );
2102 fail:
2103 throw_java_exception( env, IO_EXCEPTION, "nativeSetBaudBase",
2104 strerror( errno ) );
2105 return( ( jboolean ) 1 );
2106 #else
2107 throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
2108 "nativeSetBaudBase", strerror( errno ) );
2109 return( ( jboolean ) 1 );
2110 #endif /* TIOCGSERIAL */
2111 }
2112
2113 /*----------------------------------------------------------
2114 RXTXPort.nativeGetBaudBase
2115
2116 accept: the Baud Base used for custom speeds
2117 perform:
2118 return: Baud Base
2119 exceptions: Unsupported Comm Operation on systems not supporting
2120 TIOCGSERIAL
2121 comments:
2122 First introduced in rxtx-2.1-3
2123 ----------------------------------------------------------*/
2124 JNIEXPORT jint JNICALL RXTXPort(nativeGetBaudBase)(
2125 JNIEnv *env,
2126 jobject jobj
2127 )
2128 {
2129
2130 #if defined(TIOCGSERIAL)
2131
2132 int fd = get_java_var( env, jobj,"fd","I" );
2133 struct serial_struct sstruct;
2134
2135 if ( ioctl( fd, TIOCGSERIAL, &sstruct ) < 0 )
2136 {
2137 goto fail;
2138 }
2139 return( ( jint ) ( sstruct.baud_base ) );
2140 fail:
2141 throw_java_exception( env, IO_EXCEPTION, "nativeGetBaudBase",
2142 strerror( errno ) );
2143 return( ( jint ) -1 );
2144 #else
2145 throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
2146 "nativeGetBaudBase", strerror( errno ) );
2147 return( ( jint ) -1 );
2148 #endif /* TIOCGSERIAL */
2149 }
2150
2151 /*----------------------------------------------------------
2152 RXTXPort.nativeSetDivisor
2153
2154 accept: Divisor for custom speeds
2155 perform: set the Divisor for custom speeds
2156 return: 0 on success
2157 exceptions: Unsupported Comm Operation on systems not supporting
2158 TIOCGSERIAL
2159 comments:
2160 Set baud rate to 38400 before using this
2161 First introduced in rxtx-2.1-3
2162 ----------------------------------------------------------*/
2163 JNIEXPORT jboolean JNICALL RXTXPort(nativeSetDivisor)(
2164 JNIEnv *env,
2165 jobject jobj,
2166 jint Divisor
2167 )
2168 {
2169
2170 #if defined(TIOCGSERIAL)
2171
2172 int fd = get_java_var( env, jobj,"fd","I" );
2173 struct serial_struct sstruct;
2174
2175 if ( ioctl( fd, TIOCGSERIAL, &sstruct ) < 0 )
2176 {
2177 goto fail;
2178 }
2179
2180 if ( sstruct.custom_divisor < 1 ||
2181 ioctl( fd, TIOCSSERIAL, &sstruct ) < 0 )
2182 {
2183 goto fail;
2184 }
2185 return( ( jboolean ) 0 );
2186 fail:
2187 throw_java_exception( env, IO_EXCEPTION, "nativeSetDivisor",
2188 strerror( errno ) );
2189 return( ( jboolean ) 1 );
2190 #else
2191 throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
2192 "nativeSetDivisor", strerror( errno ) );
2193 return( ( jboolean ) 1 );
2194 #endif /* TIOCGSERIAL */
2195 }
2196
2197 /*----------------------------------------------------------
2198 RXTXPort.nativeGetDivisor
2199
2200 accept: none
2201 perform: Find the Divisor used for custom speeds
2202 return: Divisor negative value on error.
2203 exceptions: Unsupported Comm Operation on systems not supporting
2204 TIOCGSERIAL
2205 comments:
2206 First introduced in rxtx-2.1-3
2207 ----------------------------------------------------------*/
2208 JNIEXPORT jint JNICALL RXTXPort(nativeGetDivisor)(
2209 JNIEnv *env,
2210 jobject jobj
2211 )
2212 {
2213
2214 #if defined(TIOCGSERIAL)
2215
2216 int fd = get_java_var( env, jobj,"fd","I" );
2217 struct serial_struct sstruct;
2218
2219 if ( ioctl( fd, TIOCGSERIAL, &sstruct ) < 0 )
2220 {
2221 goto fail;
2222 }
2223
2224 return( ( jint ) sstruct.custom_divisor );
2225 fail:
2226 throw_java_exception( env, IO_EXCEPTION, "nativeGetDivisor",
2227 strerror( errno ) );
2228 return( ( jint ) -1 );
2229 #else
2230 throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
2231 "nativeGetDivisor", strerror( errno ) );
2232 return( ( jint ) -1 );
2233 #endif /* TIOCGSERIAL */
2234 }
2235
2236 /*----------------------------------------------------------
2237 RXTXPort.nativeStaticSetDSR
2238
2239 accept: new RTS state
2240 perform: if flag is true, TIOCM_DSR is set
2241 if flag is false, TIOCM_DSR is unset
2242 return: none
2243 exceptions: none
2244 comments: Set the DSR so it does not raise on the next open
2245 needed for some funky test boards?
2246
2247 This is static so we can not call the open() setDSR()
2248 we dont have the jobject.
2249
2250 First introduced in rxtx-1.5-9
2251 ----------------------------------------------------------*/
2252 JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticSetDSR) (JNIEnv *env,
2253 jclass jclazz, jstring jstr, jboolean flag)
2254 {
2255 int fd;
2256 int pid = -1;
2257 int result;
2258 const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
2259
2260 ENTER( "RXTXPort:nativeStaticSetDSR" );
2261 #ifndef WIN32
2262 pid = getpid();
2263 #endif /* WIN32 */
2264
2265 /* Open and lock the port so nothing else changes the setting */
2266
2267 if ( LOCK( filename, pid ) ) goto fail;
2268
2269 fd = find_preopened_ports( filename );
2270 if( !fd )
2271 {
2272 do {
2273 fd = OPEN (filename, O_RDWR | O_NOCTTY | O_NONBLOCK );
2274 } while (fd < 0 && errno==EINTR);
2275 if ( configure_port( fd ) ) goto fail;
2276 }
2277 if ( fd < 0 ) goto fail;
2278
2279 /* raise the DSR */
2280
2281 ioctl( fd, TIOCMGET, &result );
2282 if( flag == JNI_TRUE ) result |= TIOCM_DSR;
2283 else result &= ~TIOCM_DSR;
2284 ioctl( fd, TIOCMSET, &result );
2285
2286 /* Unlock the port. Good luck! :) */
2287
2288 UNLOCK( filename, pid );
2289
2290 static_add_filename( filename, fd );
2291
2292 /* dont close the port. Its not clear if the DSR would remain high */
2293 (*env)->ReleaseStringUTFChars( env, jstr, filename );
2294 LEAVE( "RXTXPort:nativeStaticSetDSR" );
2295 return( JNI_TRUE );
2296 fail:
2297 (*env)->ReleaseStringUTFChars( env, jstr, filename );
2298 LEAVE( "RXTXPort:nativeStaticSetDSR" );
2299 return( JNI_FALSE );
2300 }
2301
2302 /*----------------------------------------------------------
2303 RXTXPort.nativeStaticSetRTS
2304
2305 accept: new RTS state
2306 perform: if flag is true, TIOCM_RTS is set
2307 if flag is false, TIOCM_RTS is unset
2308 return: none
2309 exceptions: none
2310 comments: Set the RTS so it does not raise on the next open
2311 needed for some funky test boards?
2312
2313 This is static so we can not call the open() setDTR()
2314 we dont have the jobject.
2315
2316 First introduced in rxtx-1.5-9
2317 ----------------------------------------------------------*/
2318 JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticSetRTS) (JNIEnv *env,
2319 jclass jclazz, jstring jstr, jboolean flag)
2320 {
2321 int fd;
2322 int pid = -1;
2323 int result;
2324 const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
2325
2326 ENTER( "RXTXPort:nativeStaticSetRTS" );
2327 #ifndef WIN32
2328 pid = getpid();
2329 #endif /* WIN32 */
2330
2331 /* Open and lock the port so nothing else changes the setting */
2332
2333 if ( LOCK( filename, pid ) ) goto fail;;
2334
2335 fd = find_preopened_ports( filename );
2336 if( !fd )
2337 {
2338 do {
2339 fd = OPEN (filename, O_RDWR | O_NOCTTY | O_NONBLOCK );
2340 } while (fd < 0 && errno==EINTR);
2341 if ( configure_port( fd ) ) goto fail;
2342 }
2343 if ( fd < 0 ) goto fail;
2344
2345 /* raise the RTS */
2346
2347 ioctl( fd, TIOCMGET, &result );
2348 if( flag == JNI_TRUE ) result |= TIOCM_RTS;
2349 else result &= ~TIOCM_RTS;
2350 ioctl( fd, TIOCMSET, &result );
2351
2352 /* Unlock the port. Good luck! :) */
2353
2354 UNLOCK( filename, pid );
2355
2356 static_add_filename( filename, fd );
2357
2358 /* dont close the port. Its not clear if the RTS would remain high */
2359 (*env)->ReleaseStringUTFChars( env, jstr, filename );
2360 LEAVE( "RXTXPort:nativeStaticSetRTS" );
2361 return( JNI_TRUE );
2362 fail:
2363 (*env)->ReleaseStringUTFChars( env, jstr, filename );
2364 LEAVE( "RXTXPort:nativeStaticSetRTS" );
2365 return( JNI_FALSE );
2366 }
2367
2368 /*----------------------------------------------------------
2369 RXTXPort.nativeStaticSetSerialPortParams
2370
2371 accept: string for the filename, int baudrate, int databits,
2372 int stopbits, int parity
2373 perform: set the serial port, set the params, save the fd in a linked
2374 list.
2375 return: none
2376 exceptions: none
2377 comments: Not set the speed on the next 'open'
2378
2379 This is static so we can not call the open() setDTR()
2380 we dont have the jobject.
2381
2382 First introduced in rxtx-1.5-9
2383 ----------------------------------------------------------*/
2384 JNIEXPORT void JNICALL RXTXPort(nativeStaticSetSerialPortParams) (JNIEnv *env,
2385 jclass jclazz, jstring jstr, jint baudrate, jint dataBits, jint stopBits, jint parity )
2386 {
2387 int fd;
2388 int pid = -1;
2389 const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
2390 int cspeed = translate_speed( env, baudrate );
2391
2392
2393 ENTER( "RXTXPort:nativeStaticSetSerialPortParams" );
2394 #ifndef WIN32
2395 pid = getpid();
2396 #endif /* WIN32 */
2397 /* Open and lock the port so nothing else changes the setting */
2398
2399 if ( LOCK( filename, pid ) ) goto fail;
2400
2401 fd = find_preopened_ports( filename );
2402 if( !fd )
2403 {
2404 do {
2405 fd = OPEN (filename, O_RDWR | O_NOCTTY | O_NONBLOCK );
2406 } while (fd < 0 && errno==EINTR);
2407 if ( configure_port( fd ) ) goto fail;
2408 }
2409
2410 if ( fd < 0 )
2411 {
2412 (*env)->ReleaseStringUTFChars( env, jstr, filename );
2413 LEAVE( "RXTXPort:nativeStaticSetSerialPortParams" );
2414 throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
2415 "nativeStaticSetSerialPortParams", strerror( errno ) );
2416 return;
2417 }
2418
2419 if (cspeed == -1)
2420 {
2421 (*env)->ReleaseStringUTFChars( env, jstr, filename );
2422 throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
2423 "", "BaudRate could not be set to the specified value" );
2424 return;
2425 }
2426
2427 if( set_port_params( env, fd, cspeed, dataBits, stopBits, parity ) )
2428 {
2429 (*env)->ReleaseStringUTFChars( env, jstr, filename );
2430 LEAVE( "RXTXPort:nativeStatic SetSerialPortParams" );
2431 throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
2432 "nativeStaticSetSerialPortParams", strerror( errno ) );
2433 return;
2434 }
2435
2436 /* Unlock the port. Good luck! :) */
2437
2438 UNLOCK( filename, pid );
2439
2440 static_add_filename( filename, fd );
2441 /* dont close the port. */
2442
2443 (*env)->ReleaseStringUTFChars( env, jstr, filename );
2444 LEAVE( "RXTXPort:nativeStaticSetSerialPortParams" );
2445 return;
2446 fail:
2447 (*env)->ReleaseStringUTFChars( env, jstr, filename );
2448 LEAVE( "RXTXPort:nativeStaticSetSerialPortParams" );
2449 return;
2450 }
2451
2452 /*----------------------------------------------------------
2453 RXTXPort.nativeStaticSetDTR
2454
2455 accept: new DTR state
2456 perform: if flag is true, TIOCM_DTR is set
2457 if flag is false, TIOCM_DTR is unset
2458 return: none
2459 exceptions: none
2460 comments: Set the DTR so it does not raise on the next open
2461 needed for some funky test boards?
2462
2463 This is static so we can not call the open() setDTR()
2464 we dont have the jobject.
2465
2466 First introduced in rxtx-1.5-9
2467 ----------------------------------------------------------*/
2468 JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticSetDTR) (JNIEnv *env,
2469 jclass jclazz, jstring jstr, jboolean flag)
2470 {
2471 int fd;
2472 int pid = -1;
2473 const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
2474 int result;
2475
2476 ENTER( "RXTXPort:nativeStaticSetDTR" );
2477 #ifndef WIN32
2478 pid = getpid();
2479 #endif /* WIN32 */
2480
2481 /* Open and lock the port so nothing else changes the setting */
2482
2483 if ( LOCK( filename, pid ) ) goto fail;;
2484
2485 fd = find_preopened_ports( filename );
2486 if( !fd )
2487 {
2488 do {
2489 fd = OPEN (filename, O_RDWR | O_NOCTTY | O_NONBLOCK );
2490 } while (fd < 0 && errno==EINTR);
2491 if ( configure_port( fd ) ) goto fail;
2492 }
2493 if ( fd < 0 ) goto fail;
2494
2495 /* raise the DTR */
2496
2497 ioctl( fd, TIOCMGET, &result );
2498 if( flag == JNI_TRUE ) result |= TIOCM_DTR;
2499 else result &= ~TIOCM_DTR;
2500 ioctl( fd, TIOCMSET, &result );
2501
2502 /* Unlock the port. Good luck! :) */
2503
2504 UNLOCK( filename, pid );
2505
2506 static_add_filename( filename, fd );
2507 /* dont close the port. Its not clear if the DTR would remain high */
2508
2509 (*env)->ReleaseStringUTFChars( env, jstr, filename );
2510 LEAVE( "RXTXPort:nativeStaticSetDTR" );
2511 return( JNI_TRUE );
2512 fail:
2513 (*env)->ReleaseStringUTFChars( env, jstr, filename );
2514 LEAVE( "RXTXPort:nativeStaticSetDTR" );
2515 return( JNI_FALSE );
2516 }
2517
2518 /*----------------------------------------------------------
2519 RXTXPort.nativeStaticIsRTS
2520
2521 accept: filename
2522 perform: check status of RTS of preopened ports (setting lines/params
2523 before calling the Java open()
2524 return: true if TIOCM_RTS is set
2525 false if TIOCM_RTS is not set
2526 exceptions: none
2527 comments: RTS stands for Request to Send
2528 ----------------------------------------------------------*/
2529 JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsRTS)( JNIEnv *env,
2530 jobject jobj, jstring jstr )
2531 {
2532 unsigned int result = 0;
2533 const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
2534 int fd = find_preopened_ports( filename );
2535 char message[80];
2536
2537 ENTER( "RXTXPort:nativeStaticIsRTS" );
2538 if( !fd )
2539 {
2540 /* Exception? FIXME */
2541 return JNI_FALSE;
2542 }
2543 ioctl( fd, TIOCMGET, &result );
2544 sprintf( message, "nativeStaticIsRTS( ) returns %i\n", result& TIOCM_RTS );
2545 report( message );
2546 LEAVE( "RXTXPort:nativeStaticIsRTS" );
2547 if( result & TIOCM_RTS ) return JNI_TRUE;
2548 else return JNI_FALSE;
2549 }
2550 /*----------------------------------------------------------
2551 RXTXPort.nativeStaticIsDSR
2552
2553 accept: filename
2554 perform: check status of DSR of preopened ports (setting lines/params
2555 before calling the Java open()
2556 return: true if TIOCM_DSR is set
2557 false if TIOCM_DSR is not set
2558 exceptions: none
2559 comments:
2560 ----------------------------------------------------------*/
2561 JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsDSR)( JNIEnv *env,
2562 jobject jobj, jstring jstr )
2563 {
2564 unsigned int result = 0;
2565 const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
2566 int fd = find_preopened_ports( filename );
2567 char message[80];
2568
2569 ENTER( "RXTXPort:nativeStaticIsDSR" );
2570 if( !fd )
2571 {
2572 /* Exception? FIXME */
2573 return JNI_FALSE;
2574 }
2575 ioctl( fd, TIOCMGET, &result );
2576 sprintf( message, "nativeStaticIsDSR( ) returns %i\n", result& TIOCM_DSR );
2577 report( message );
2578 LEAVE( "RXTXPort:nativeStaticIsDSR" );
2579 if( result & TIOCM_DSR ) return JNI_TRUE;
2580 else return JNI_FALSE;
2581 }
2582 /*----------------------------------------------------------
2583 RXTXPort.nativeStaticIsDTR
2584
2585 accept: filename
2586 perform: check status of DTR of preopened ports (setting lines/params
2587 before calling the Java open()
2588 return: true if TIOCM_DTR is set
2589 false if TIOCM_DTR is not set
2590 exceptions: none
2591 comments: DTR stands for Data Terminal Ready
2592 ----------------------------------------------------------*/
2593 JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsDTR)( JNIEnv *env,
2594 jobject jobj, jstring jstr )
2595 {
2596 unsigned int result = 0;
2597 const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
2598 int fd = find_preopened_ports( filename );
2599 char message[80];
2600
2601 ENTER( "RXTXPort:nativeStaticIsDTR" );
2602 if( !fd )
2603 {
2604 /* Exception? FIXME */
2605 return JNI_FALSE;
2606 }
2607 ioctl( fd, TIOCMGET, &result );
2608 sprintf( message, "nativeStaticIsDTR( ) returns %i\n", result& TIOCM_DTR );
2609 report( message );
2610 LEAVE( "RXTXPort:nativeStaticIsDTR" );
2611 if( result & TIOCM_DTR ) return JNI_TRUE;
2612 else return JNI_FALSE;
2613 }
2614 /*----------------------------------------------------------
2615 RXTXPort.nativeStaticIsCD
2616
2617 accept: filename
2618 perform: check status of CD of preopened ports (setting lines/params
2619 before calling the Java open()
2620 return: true if TIOCM_CD is set
2621 false if TIOCM_CD is not set
2622 exceptions: none
2623 comments: CD stands for carrier detect
2624 ----------------------------------------------------------*/
2625 JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsCD)( JNIEnv *env,
2626 jobject jobj, jstring jstr )
2627 {
2628 unsigned int result = 0;
2629 const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
2630 int fd = find_preopened_ports( filename );
2631 char message[80];
2632
2633 ENTER( "RXTXPort:nativeStaticIsCD" );
2634 if( !fd )
2635 {
2636 /* Exception? FIXME */
2637 return JNI_FALSE;
2638 }
2639 ioctl( fd, TIOCMGET, &result );
2640 sprintf( message, "nativeStaticIsCD( ) returns %i\n", result& TIOCM_CD );
2641 report( message );
2642 LEAVE( "RXTXPort:nativeStaticIsCD" );
2643 if( result & TIOCM_CD ) return JNI_TRUE;
2644 else return JNI_FALSE;
2645 }
2646 /*----------------------------------------------------------
2647 RXTXPort.nativeStaticIsCTS
2648
2649 accept: filename
2650 perform: check status of CTS of preopened ports (setting lines/params
2651 before calling the Java open()
2652 return: true if TIOCM_CTS is set
2653 false if TIOCM_CTS is not set
2654 exceptions: none
2655 comments: CTS stands for Clear To Send
2656 ----------------------------------------------------------*/
2657 JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsCTS)( JNIEnv *env,
2658 jobject jobj, jstring jstr )
2659 {
2660 unsigned int result = 0;
2661 const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
2662 int fd = find_preopened_ports( filename );
2663 char message[80];
2664
2665 ENTER( "RXTXPort:nativeStaticIsCTS" );
2666 if( !fd )
2667 {
2668 /* Exception? FIXME */
2669 return JNI_FALSE;
2670 }
2671 ioctl( fd, TIOCMGET, &result );
2672 sprintf( message, "nativeStaticIsCTS( ) returns %i\n", result& TIOCM_CTS );
2673 report( message );
2674 LEAVE( "RXTXPort:nativeStaticIsCTS" );
2675 if( result & TIOCM_CTS ) return JNI_TRUE;
2676 else return JNI_FALSE;
2677 }
2678 /*----------------------------------------------------------
2679 RXTXPort.nativeStaticIsRI
2680
2681 accept: filename
2682 perform: check status of RI of preopened ports (setting lines/params
2683 before calling the Java open()
2684 return: true if TIOCM_RI is set
2685 false if TIOCM_RI is not set
2686 exceptions: none
2687 comments: RI stands for carrier detect
2688 ----------------------------------------------------------*/
2689 JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsRI)( JNIEnv *env,
2690 jobject jobj, jstring jstr )
2691 {
2692 unsigned int result = 0;
2693 const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
2694 int fd = find_preopened_ports( filename );
2695 char message[80];
2696
2697 ENTER( "RXTXPort:nativeStaticIsRI" );
2698 if( !fd )
2699 {
2700 /* Exception? FIXME */
2701 return JNI_FALSE;
2702 }
2703 ioctl( fd, TIOCMGET, &result );
2704 sprintf( message, "nativeStaticRI( ) returns %i\n", result& TIOCM_RI );
2705 report( message );
2706 LEAVE( "RXTXPort:nativeStaticIsRI" );
2707 if( result & TIOCM_RI ) return JNI_TRUE;
2708 else return JNI_FALSE;
2709 }
2710
2711 /*----------------------------------------------------------
2712 RXTXPort.nativeStaticGetBaudRate
2713
2714 accept: filename
2715 perform: find the baud rate (not all buads are handled yet)
2716 return: return the baud rate or -1 if not supported yet.
2717 exceptions:
2718 comments: simple test for preopened ports
2719 ----------------------------------------------------------*/
2720 JNIEXPORT jint JNICALL RXTXPort(nativeStaticGetBaudRate)( JNIEnv *env, jobject jobj, jstring jstr )
2721 {
2722 const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
2723 int fd = find_preopened_ports( filename );
2724 struct termios ttyset;
2725 int baudrate;
2726 (*env)->ReleaseStringUTFChars( env, jstr, filename );
2727
2728 ENTER( "RXTXPort:nativeStaticGetBaudRate" );
2729 if( !fd )
2730 {
2731 /* Exception? FIXME */
2732 return -1;
2733 }
2734 if( tcgetattr( fd, &ttyset ) < 0 )
2735 {
2736 report( "nativeStaticGetBaudRate: Cannot Get Serial Port Settings\n" );
2737 return(-1);
2738 }
2739 /*
2740 dima writes:
2741
2742 Trent, here is something I found with google:
2743 (freebsd list [email protected])
2744
2745 Andrzej Bialecki <[email protected]> asked:
2746 I tried to compile a piece of software, probably for Linux, and I noticed
2747 that we don't define CBAUD constant. I'm not sure, but I think POSIX
2748 defines and uses it. Should(n't) we?
2749
2750 Bruce Evans <[email protected]> answered:
2751 CBAUD is for SYSV compatibility. It is considerably inferior to POSIX's
2752 cf{get,set}{i,o}speed and shouldn't be provided or used.
2753
2754 */
2755 #if defined(CBAUD)/* dima */
2756 baudrate = ttyset.c_cflag&CBAUD;
2757 #else
2758 if(cfgetispeed(&ttyset) != cfgetospeed(&ttyset)) return -1;
2759 baudrate = cfgetispeed(&ttyset);
2760 #endif
2761 return( get_java_baudrate(baudrate) );
2762 }
2763 /*----------------------------------------------------------
2764 RXTXPort.nativeStaticGetDataBits
2765
2766 accept: filename
2767 perform: find the data bits (not all buads are handled yet)
2768 return: return the data bits
2769 exceptions:
2770 comments: simple test for preopened ports
2771 ----------------------------------------------------------*/
2772 JNIEXPORT jint JNICALL RXTXPort(nativeStaticGetDataBits)( JNIEnv *env, jobject jobj, jstring jstr )
2773 {
2774 const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
2775 int fd = find_preopened_ports( filename );
2776 struct termios ttyset;
2777 (*env)->ReleaseStringUTFChars( env, jstr, filename );
2778
2779 ENTER( "RXTXPort:nativeStaticGetDataBits" );
2780 if( !fd )
2781 {
2782 /* Exception? FIXME */
2783 return -1;
2784 }
2785 if( tcgetattr( fd, &ttyset ) < 0 )
2786 {
2787 report( "nativeStaticGetDataBits: Cannot Get Serial Port Settings\n" );
2788 return(-1);
2789 }
2790 switch( ttyset.c_cflag&CSIZE ) {
2791 case CS5: return JDATABITS_5;
2792 case CS6: return JDATABITS_6;
2793 case CS7: return JDATABITS_7;
2794 case CS8: return JDATABITS_8;
2795 default: return(-1);
2796 }
2797 }
2798 /*----------------------------------------------------------
2799 RXTXPort.nativeStaticGetParity
2800
2801 accept: filename
2802 perform: find the parity
2803 return: return the parity
2804 exceptions:
2805 comments: simple test for preopened ports
2806 ----------------------------------------------------------*/
2807 JNIEXPORT jint JNICALL RXTXPort(nativeStaticGetParity)( JNIEnv *env, jobject jobj, jstring jstr )
2808 {
2809 const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
2810 int fd = find_preopened_ports( filename );
2811 struct termios ttyset;
2812 (*env)->ReleaseStringUTFChars( env, jstr, filename );
2813
2814 ENTER( "RXTXPort:nativeStaticGetParity" );
2815 if( !fd )
2816 {
2817 /* Exception? FIXME */
2818 return -1;
2819 }
2820 if( tcgetattr( fd, &ttyset ) < 0 )
2821 {
2822 report( "nativeStaticGetParity: Cannot Get Serial Port Settings\n" );
2823 return(-1);
2824 }
2825 #ifdef CMSPAR
2826 switch( ttyset.c_cflag&(PARENB|PARODD|CMSPAR ) ) {
2827 #else
2828 switch( ttyset.c_cflag&(PARENB|PARODD) ) {
2829 #endif /* CMSPAR */
2830 case 0: return JPARITY_NONE;
2831 case PARENB: return JPARITY_EVEN;
2832 case PARENB | PARODD: return JPARITY_ODD;
2833 #ifdef CMSPAR
2834 case PARENB | PARODD | CMSPAR: return JPARITY_MARK;
2835 case PARENB | CMSPAR: return JPARITY_SPACE;
2836 #endif /* CMSPAR */
2837 default: return(-1);
2838 }
2839 }
2840 /*----------------------------------------------------------
2841 RXTXPort.nativeStaticGetStopBits
2842
2843 accept: filename
2844 perform: find the stop bits
2845 return: return the stop bits
2846 exceptions:
2847 comments: simple test for preopened ports
2848 ----------------------------------------------------------*/
2849 JNIEXPORT jint JNICALL RXTXPort(nativeStaticGetStopBits)( JNIEnv *env, jobject jobj, jstring jstr )
2850 {
2851 const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
2852 int fd = find_preopened_ports( filename );
2853 struct termios ttyset;
2854 (*env)->ReleaseStringUTFChars( env, jstr, filename );
2855
2856 ENTER( "RXTXPort:nativeStaticGetStopBits" );
2857 if( !fd )
2858 {
2859 /* Exception? FIXME */
2860 return -1;
2861 }
2862 if( tcgetattr( fd, &ttyset ) < 0 )
2863 {
2864 report( "nativeStaticGetStopBits: Cannot Get Serial Port Settings\n" );
2865 return(-1);
2866 }
2867 switch( ttyset.c_cflag&(CSTOPB) ) {
2868 case 0:
2869 return STOPBITS_1;
2870 case CSTOPB:
2871 if( ttyset.c_cflag & CS5 ) {
2872 return STOPBITS_1_5;
2873 }
2874 else {
2875 return STOPBITS_2;
2876 }
2877 default:
2878 return -1;
2879 }
2880 }
2881
2882 /*----------------------------------------------------------
2883 RXTXPort.nativeGetParityErrorChar
2884
2885 accept: -
2886 perform: check the ParityErrorChar
2887 return: The ParityErrorChar as an jbyte.
2888 exceptions: UnsupportedCommOperationException if not implemented
2889 comments: It appears the Parity char is usually \0. The windows
2890 API allows for this to be changed. I cant find may
2891 examples of this being done. Maybe for a reason.
2892
2893 Use a direct call to the termios file until we find a
2894 solution.
2895 ----------------------------------------------------------*/
2896 JNIEXPORT jbyte JNICALL RXTXPort(nativeGetParityErrorChar)( JNIEnv *env,
2897 jobject jobj )
2898 {
2899 unsigned int result = 0;
2900
2901 ENTER( "nativeGetParityErrorChar" );
2902 #ifdef WIN32
2903 result = ( jbyte ) termiosGetParityErrorChar(
2904 get_java_var(env, jobj, "fd", "I" ) );
2905 #else
2906 /*
2907 arg! I cant find a way to change it from \0 in Linux. I think
2908 the frame and parity error characters are hardcoded.
2909 */
2910 result = ( jint ) '\0';
2911
2912 #endif /* WIN32 */
2913 LEAVE( "nativeGetParityErrorChar" );
2914 return( ( jbyte ) result );
2915 }
2916
2917 /*----------------------------------------------------------
2918 RXTXPort.nativeGetEndOfInputChar
2919
2920 accept: -
2921 perform: check the EndOf InputChar
2922 return: the EndOfInputChar as an jbyte. -1 on error
2923 exceptions: UnsupportedCommOperationException if not implemented
2924 comments:
2925 ----------------------------------------------------------*/
2926 JNIEXPORT jbyte JNICALL RXTXPort(nativeGetEndOfInputChar)( JNIEnv *env,
2927 jobject jobj )
2928 {
2929 int fd = get_java_var( env, jobj,"fd","I" );
2930 struct termios ttyset;
2931
2932 ENTER( "nativeGetEndOfInputChar" );
2933 if( tcgetattr( fd, &ttyset ) < 0 ) goto fail;
2934 LEAVE( "nativeGetEndOfInputChar" );
2935 return( (jbyte) ttyset.c_cc[VEOF] );
2936 fail:
2937 LEAVE( "nativeGetEndOfInputChar" );
2938 report( "nativeGetEndOfInputChar failed\n" );
2939 return( ( jbyte ) -1 );
2940 }
2941
2942 /*----------------------------------------------------------
2943 RXTXPort.nativeSetParityErrorChar
2944
2945 accept: the ParityArrorCharacter as an int.
2946 perform: Set the ParityErrorChar
2947 return: JNI_TRUE on success
2948 exceptions: UnsupportedCommOperationException if not implemented
2949 comments: It appears the Parity char is usually \0. The windows
2950 API allows for this to be changed. I cant find may
2951 examples of this being done. Maybe for a reason.
2952
2953 Use a direct call to the termios file until we find a
2954 solution.
2955 ----------------------------------------------------------*/
2956 JNIEXPORT jboolean JNICALL RXTXPort(nativeSetParityErrorChar)( JNIEnv *env,
2957 jobject jobj, jbyte value )
2958 {
2959
2960 #ifdef WIN32
2961 int fd = get_java_var( env, jobj,"fd","I" );
2962 ENTER( "nativeSetParityErrorChar" );
2963 termiosSetParityError( fd, ( char ) value );
2964 LEAVE( "nativeSetParityErrorChar" );
2965 return( JNI_TRUE );
2966 #else
2967 ENTER( "nativeSetParityErrorChar" );
2968 /*
2969 arg! I cant find a way to change it from \0 in Linux. I think
2970 the frame and parity error characters are hardcoded.
2971 */
2972
2973 throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
2974 "Not implemented... yet",
2975 strerror( errno ) );
2976 LEAVE( "nativeSetParityErrorChar" );
2977 return( JNI_FALSE );
2978 #endif /* WIN32 */
2979 }
2980
2981 /*----------------------------------------------------------
2982 RXTXPort.nativeSetEndOfInputChar
2983
2984 accept: The EndOfInputChar as an int
2985 perform: set the EndOfInputChar
2986 return: JNI_TRUE on success
2987 exceptions: UnsupportedCommOperationException if not implemented
2988 comments: This may cause troubles on Windows.
2989 Lets give it a shot and see what happens.
2990
2991 See termios.c for the windows bits.
2992
2993 EofChar = val;
2994 fBinary = false; winapi docs say always use true. ?
2995 ----------------------------------------------------------*/
2996 JNIEXPORT jboolean JNICALL RXTXPort(nativeSetEndOfInputChar)( JNIEnv *env,
2997 jobject jobj, jbyte value )
2998 {
2999 int fd = get_java_var( env, jobj,"fd","I" );
3000 struct termios ttyset;
3001
3002 ENTER( "nativeSetEndOfInputChar" );
3003 if( tcgetattr( fd, &ttyset ) < 0 ) goto fail;
3004 ttyset.c_cc[VEOF] = ( char ) value;
3005 if( tcsetattr( fd, TCSANOW, &ttyset ) < 0 ) goto fail;
3006 LEAVE( "nativeSetEndOfInputChar" );
3007 return( JNI_TRUE );
3008 fail:
3009 throw_java_exception( env, IO_EXCEPTION, "nativeSetEndOfInputChar",
3010 strerror( errno ) );
3011 report( "nativeSetEndOfInputChar failed\n" );
3012 LEAVE( "nativeSetEndOfInputChar" );
3013 return( JNI_FALSE );
3014 }
3015
3016 #ifndef WIN32
3017 long
3018 GetTickCount()
3019 {
3020 /* return milliseconds */
3021 struct timeval now;
3022
3023 gettimeofday(&now, NULL);
3024 report_verbose("gettimeofday\n");
3025
3026 #ifdef __QNX__
3027 return now.tv_sec * 1000 + now.tv_usec / 1000;
3028 #else
3029 return (now.tv_sec * 1000) + ceil(now.tv_usec / 1000);
3030 #endif /* __QNX__ */
3031 }
3032
3033 #endif /* !WIN32 */
3034
3035 /*----------------------------------------------------------
3036 read_byte_array
3037
3038 accept: int fd file descriptor to read from
3039 unsigned char *buffer buffer to read data into
3040 int length number of bytes to read
3041 int timeout milliseconds to wait before returning
3042 perform: read bytes from the port into a buffer
3043 return: status of read
3044 -1 fail (IOException)
3045 0 timeout
3046 >0 number of bytes read
3047 comments: According to the Communications API spec, a receive threshold
3048 of 1 is the same as having the threshold disabled.
3049
3050 The nuts and bolts are documented in
3051 NativeEnableReceiveTimeoutThreshold()
3052 ----------------------------------------------------------*/
3053
3054 int read_byte_array( JNIEnv *env,
3055 jobject *jobj,
3056 int fd,
3057 unsigned char *buffer,
3058 int length,
3059 int timeout )
3060 {
3061 int ret, left, bytes = 0;
3062 long timeLeft, now = 0, start = 0;
3063 /* char msg[80]; */
3064 struct timeval tv, *tvP;
3065 fd_set rset;
3066 /* TRENT */
3067 int flag, count = 0;
3068 struct event_info_struct *eis = ( struct event_info_struct * )
3069 get_java_var( env, *jobj,"eis","J" );
3070
3071 report_time_start();
3072 flag = eis->eventflags[SPE_DATA_AVAILABLE];
3073 eis->eventflags[SPE_DATA_AVAILABLE] = 0;
3074 /*
3075 ENTER( "read_byte_array" );
3076 sprintf(msg, "read_byte_array requests %i\n", length);
3077 report( msg );
3078 */
3079 left = length;
3080 if (timeout >= 0)
3081 start = GetTickCount();
3082 while( bytes < length && count++ < 20 ) /* && !is_interrupted( eis ) )*/
3083 {
3084 if (timeout >= 0) {
3085 now = GetTickCount();
3086 if ( now-start >= timeout )
3087 {
3088 eis->eventflags[SPE_DATA_AVAILABLE] = flag;
3089 return bytes;
3090 }
3091 }
3092
3093 FD_ZERO(&rset);
3094 FD_SET(fd, &rset);
3095
3096 if (timeout >= 0){
3097 timeLeft = timeout - (now - start);
3098 tv.tv_sec = timeLeft / 1000;
3099 tv.tv_usec = 1000 * ( timeLeft % 1000 );
3100 tvP = &tv;
3101 }
3102 else{
3103 tvP = NULL;
3104 }
3105 /* FIXME HERE Trent */
3106 #ifndef WIN32
3107 do {
3108 ret = SELECT( fd + 1, &rset, NULL, NULL, tvP );
3109 } while (ret < 0 && errno==EINTR);
3110 #else
3111 ret = 1;
3112 #endif /* WIN32 */
3113 if (ret == -1){
3114 report( "read_byte_array: select returned -1\n" );
3115 LEAVE( "read_byte_array" );
3116 eis->eventflags[SPE_DATA_AVAILABLE] = flag;
3117 return -1;
3118 }
3119 else if (ret > 0)
3120 {
3121 if ((ret = READ( fd, buffer + bytes, left )) < 0 ){
3122 if (errno != EINTR && errno != EAGAIN){
3123 report( "read_byte_array: read returned -1\n" );
3124 LEAVE( "read_byte_array" );
3125 eis->eventflags[SPE_DATA_AVAILABLE] = flag;
3126 return -1;
3127 }
3128 eis->eventflags[SPE_DATA_AVAILABLE] = flag;
3129 return -1;
3130 }
3131 else if ( ret ) {
3132 bytes += ret;
3133 left -= ret;
3134 }
3135 /*
3136 The only thing that is bugging me with the new
3137 version is the CPU usage when reading on the serial port. I
3138 looked at it today and find a quick fix. It doesn't seems to
3139 affect the performance for our apps (I mean in a negative way,
3140 cause the CPU is back to normal, near 0-5%). All I did is add
3141 a usleep in the reading function.
3142
3143 Nicolas <[email protected]>
3144 */
3145 else {
3146 /* usleep(10); */
3147 usleep(1000);
3148 }
3149 }
3150 }
3151
3152 /*
3153 if( count > 19 )
3154 {
3155 throw_java_exception( env, IO_EXCEPTION, "read_byte_array",
3156 "No data available" );
3157 }
3158
3159 sprintf(msg, "read_byte_array returns %i\n", bytes);
3160 report( msg );
3161 LEAVE( "read_byte_array" );
3162 report_time_end();
3163 */
3164 eis->eventflags[SPE_DATA_AVAILABLE] = flag;
3165 return bytes;
3166 }
3167
3168 #ifdef asdf
3169 int read_byte_array( JNIEnv *env,
3170 jobject *jobj,
3171 int fd,
3172 unsigned char *buffer,
3173 int length,
3174 int timeout )
3175 {
3176 int ret, left, bytes = 0;
3177 long now, start = 0;
3178 char msg[80];
3179
3180 report_time_start();
3181 ENTER( "read_byte_array" );
3182 sprintf(msg, "read_byte_array requests %i\n", length);
3183 report( msg );
3184 left = length;
3185 if (timeout >= 0)
3186 start = GetTickCount();
3187 while( bytes < length )
3188 {
3189 if (timeout >= 0) {
3190 now = GetTickCount();
3191 if (now-start >= timeout)
3192 return bytes;
3193 }
3194 RETRY: if ((ret = READ( fd, buffer + bytes, left )) < 0 )
3195 {
3196 if (errno == EINTR)
3197 goto RETRY;
3198 report( "read_byte_array: read returned -1\n" );
3199 LEAVE( "read_byte_array" );
3200 return -1;
3201 }
3202 bytes += ret;
3203 left -= ret;
3204 }
3205 sprintf(msg, "read_byte_array returns %i\n", bytes);
3206 report( msg );
3207 LEAVE( "read_byte_array" );
3208 report_time_end();
3209 return bytes;
3210 }
3211
3212
3213 int read_byte_array( JNIEnv *env,
3214 jobject *jobj,
3215 int fd,
3216 unsigned char *buffer,
3217 int length,
3218 int timeout )
3219 {
3220 int ret, left, bytes = 0;
3221 /* int count = 0; */
3222 fd_set rfds;
3223 struct timeval sleep;
3224 struct event_info_struct *eis = find_eis( fd );
3225
3226 #ifndef WIN32
3227 struct timeval *psleep=&sleep;
3228 #endif /* WIN32 */
3229
3230 ENTER( "read_byte_array" );
3231 left = length;
3232 FD_ZERO( &rfds );
3233 FD_SET( fd, &rfds );
3234 if( timeout != 0 )
3235 {
3236 sleep.tv_sec = timeout / 1000;
3237 sleep.tv_usec = 1000 * ( timeout % 1000 );
3238 }
3239 while( bytes < length )
3240 {
3241 /* FIXME: In Linux, select updates the timeout automatically, so
3242 other OSes will need to update it manually if they want to have
3243 the same behavior. For those OSes, timeouts will occur after no
3244 data AT ALL is received for the timeout duration. No big deal. */
3245 #ifndef WIN32
3246 do {
3247 if( timeout == 0 ) psleep = NULL;
3248 ret=SELECT( fd + 1, &rfds, NULL, NULL, psleep );
3249 } while (ret < 0 && errno==EINTR);
3250 #else
3251 /*
3252 the select() needs some work before the above will
3253 work on win32. The select code cannot be accessed
3254 from both the Monitor Thread and the Reading Thread.
3255
3256 */
3257 ret = RXTXPort(nativeavailable)( env, *jobj );
3258 #endif /* WIN32 */
3259 if( ret == 0 )
3260 {
3261 report( "read_byte_array: select returned 0\n" );
3262 LEAVE( "read_byte_array" );
3263 break;
3264 }
3265 if( ret < 0 )
3266 {
3267 report( "read_byte_array: select returned -1\n" );
3268 LEAVE( "read_byte_array" );
3269 return -1;
3270 }
3271 ret = READ( fd, buffer + bytes, left );
3272 if( ret == 0 )
3273 {
3274 report( "read_byte_array: read returned 0 bytes\n" );
3275 LEAVE( "read_byte_array" );
3276 break;
3277 }
3278 else if( ret < 0 )
3279 {
3280 report( "read_byte_array: read returned -1\n" );
3281 LEAVE( "read_byte_array" );
3282 return -1;
3283 }
3284 bytes += ret;
3285 left -= ret;
3286 }
3287 LEAVE( "read_byte_array" );
3288 return bytes;
3289 }
3290 #endif /* asdf */
3291
3292 /*----------------------------------------------------------
3293 NativeEnableReceiveTimeoutThreshold
3294 accept: int threshold, int vtime,int buffer
3295 perform: Set c_cc->VMIN to threshold and c_cc=>VTIME to vtime
3296 return: void
3297 exceptions: IOException
3298 comments: This is actually all handled in read with select in
3299 canonical input mode.
3300 ----------------------------------------------------------*/
3301 JNIEXPORT void JNICALL RXTXPort(NativeEnableReceiveTimeoutThreshold)(
3302 JNIEnv *env, jobject jobj, jint vtime, jint threshold, jint buffer)
3303 {
3304 int fd = get_java_var( env, jobj,"fd","I" );
3305 struct termios ttyset;
3306 int timeout;
3307
3308 if (vtime < 0){
3309 timeout = 0;
3310 }
3311 else if (vtime == 0){
3312 timeout = 1;
3313 }
3314 else{
3315 timeout = vtime;
3316 }
3317
3318 ENTER( "RXTXPort:NativeEnableRecieveTimeoutThreshold" );
3319 if( tcgetattr( fd, &ttyset ) < 0 ) goto fail;
3320 ttyset.c_cc[ VMIN ] = threshold;
3321 ttyset.c_cc[ VTIME ] = timeout/100;
3322 if( tcsetattr( fd, TCSANOW, &ttyset ) < 0 ) goto fail;
3323
3324 LEAVE( "RXTXPort:NativeEnableRecieveTimeoutThreshold" );
3325 return;
3326 fail:
3327 LEAVE( "RXTXPort:NativeEnableRecieveTimeoutThreshold" );
3328 throw_java_exception( env, IO_EXCEPTION, "TimeoutThreshold",
3329 strerror( errno ) );
3330 return;
3331 }
3332
3333 /*----------------------------------------------------------
3334 RXTXPort.readByte
3335
3336 accept: none
3337 perform: Read a single byte from the port. Block unless an exeption
3338 is thrown, or end of stream.
3339 return: The byte read
3340 exceptions: IOException
3341 comments:
3342
3343 On Fri, 30 Aug 2002, Bill Smith wrote:
3344
3345 I agree, the documentation isn't the best. No surprises there.
3346
3347 I did do a test using the sun/win32 comm driver with read() and retrieve
3348 timeout enabled. It blocked until the timeout expired, then returned a -1.
3349 This seems to jive with the way I'm reading it which is the javax.comm
3350 comments regarding read (in the CommPort.getInputStream stuff)
3351 extends/overrides
3352 the documentation for java.io.InputStream.
3353
3354 This is the same behavior that the Windriver driver for vxworks exhibits.
3355
3356 On Fri, 30 Aug 2002, Bill Smith wrote:
3357
3358 > Hi Trent,
3359 >
3360 > I have a couple of questions/comments.
3361 >
3362 > 1) I noticed in the thread last night and in the code changes this morning that you
3363 > now have readByte() (which is called from the input stream read(), to block
3364 > forever. I pulled the following info from the javax.comm doc for the CommPort class in
3365 > getInputStream().
3366 >
3367 > The way I interpret that is that read() just like read(byte[]), and read(byte[], int, int),
3368 > show only block indefinitely if timeout is disabled. The sun implementation for win32 (as
3369 > well as the one we have for vxworks) returns a -1 when it times out.
3370 >
3371
3372 Doing what Sun does is going to the least hassle. The documentation was a
3373 little unclear to me. I assume this is the CommPort.getInputStream
3374 comment that you mention
3375
3376 The read behaviour of the input stream returned by getInputStream
3377 depends on combination of the threshold and timeout values. The
3378 possible behaviours are described in the table below: ...
3379
3380 But InputStream is where read(byte) is documented
3381 http://java.sun.com/j2se/1.3/docs/api/java/io/InputStream.html#read()
3382
3383 Reads the next byte of data from the input stream. The value byte
3384 is returned as an int in the range 0 to 255. If no byte is
3385 available because the end of the stream has been reached, the value
3386 -1 is returned. This method blocks until input data is
3387 available, the end of the stream is detected, or an exception is
3388 thrown
3389
3390 If you are sure commapi is doing a timeout and returning -1, I can change
3391 it back and document the issue.
3392
3393 Because I often grep my own mailbox for details, I'm going to add
3394 these two comments also:
3395
3396 public int read(byte[] b)
3397 )
3398 http://java.sun.com/j2se/1.3/docs/api/java/io/InputStream.html#read(byte[])
3399
3400 Reads some number of bytes from the input stream and stores them
3401 into the buffer array b. The number of bytes actually read is
3402 returned as an integer. This method blocks until input data is
3403 available, end of file is detected, or an exception is thrown.
3404
3405 If b is null, a NullPointerException is thrown. If the length of b
3406 is zero, then no bytes are read and 0 is returned; otherwise,
3407 there is an attempt to read at least one byte. If no byte is
3408 available because the stream is at end of file, the value -1 is
3409 returned; otherwise, at least one byte is read and stored into b.
3410
3411 So read(byte[] b) is documented as blocking for the first byte.
3412
3413 public int read(byte[] b,int off,int len)
3414 http://java.sun.com/j2se/1.3/docs/api/java/io/InputStream.html#read(byte[],
3415 int, int)
3416
3417 Reads up to len bytes of data from the input stream into an array of
3418 bytes. An attempt is made to read as many as len bytes, but a
3419 smaller number may be read, possibly zero. The number of bytes
3420 actually read is returned as an integer.
3421
3422 Which makes sense with the timeout documentation.
3423
3424 <snip>threshold comment I'll look at that next. I thought those changes
3425 where in the ifdefed code. I'll take a second look and reply.
3426
3427 >
3428 > Thoughts? Comments?
3429 >
3430 > Bill
3431 >
3432 > ----------------------
3433 >
3434 > public abstract InputStream getInputStream() throws IOException
3435 >
3436 >
3437 > Returns an input stream. This is the only way to receive data from the
3438 communications
3439 > port. If the port is unidirectional and doesn't support receiving data, then
3440 > getInputStream returns null.
3441 >
3442 > The read behaviour of the input stream returned by getInputStream depends on
3443 > combination of the threshold and timeout values. The possible behaviours are
3444 > described in the table below:
3445 >
3446 >
3447 > Threshold Timeout Read Buffer Read Behaviour
3448 > State Value State Value Size
3449 >
3450 -----------------------------------------------------------------------------------
3451 > disabled - disabled - n bytes block until any data is available
3452 >
3453 > enabled m bytes disabled - n bytes block until min(m,n) bytes are available
3454 >
3455 > disabled - enabled x ms n bytes block for x ms or
3456 until any data is available
3457 >
3458 > enabled m bytes enabled x ms n bytes block for x ms or
3459 until min(m,n) bytes are available
3460 >
3461 > Returns: InputStream object that can be used to read from the port
3462 >
3463 > Throws: IOException if an I/O error occurred
3464
3465
3466 ----------------------------------------------------------*/
3467 JNIEXPORT jint JNICALL RXTXPort(readByte)( JNIEnv *env,
3468 jobject jobj )
3469 {
3470 int bytes;
3471 unsigned char buffer[ 1 ];
3472 int fd = get_java_var( env, jobj,"fd","I" );
3473 int timeout = get_java_var( env, jobj, "timeout", "I" );
3474 /* char msg[80]; */
3475
3476 /*
3477 ENTER( "RXTXPort:readByte" );
3478 report_time_start( );
3479 */
3480 bytes = read_byte_array( env, &jobj, fd, buffer, 1, timeout );
3481 if( bytes < 0 ) {
3482 LEAVE( "RXTXPort:readByte" );
3483 throw_java_exception( env, IO_EXCEPTION, "readByte",
3484 strerror( errno ) );
3485 return -1;
3486 }
3487 /*
3488 LEAVE( "RXTXPort:readByte" );
3489 sprintf( msg, "readByte return(%i)\n", bytes ? buffer[ 0 ] : -1 );
3490 report( msg );
3491 report_time_end( );
3492 */
3493 return (bytes ? (jint)buffer[ 0 ] : -1);
3494 }
3495
3496 /*----------------------------------------------------------
3497 RXTXPort.readArray
3498
3499 accept: offset (offset to start storing data in the jbarray) and
3500 Length (bytes to read)
3501 perform: read bytes from the port into a byte array
3502 return: bytes read on success
3503 0 on read timeout
3504 exceptions: IOException
3505 comments: throws ArrayIndexOutOfBoundsException if asked to
3506 read more than SSIZE_MAX bytes
3507 ----------------------------------------------------------*/
3508 JNIEXPORT jint JNICALL RXTXPort(readArray)( JNIEnv *env,
3509 jobject jobj, jbyteArray jbarray, jint offset, jint length )
3510 {
3511 int bytes;
3512 jbyte *body;
3513 /* char msg[80]; */
3514 int fd = get_java_var( env, jobj, "fd", "I" );
3515 int timeout = get_java_var( env, jobj, "timeout", "I" );
3516
3517 /*
3518 ENTER( "readArray" );
3519 report_time_start( );
3520 */
3521 if( (size_t) length > SSIZE_MAX || (size_t) length < 0 ) {
3522 report( "RXTXPort:readArray length > SSIZE_MAX" );
3523 LEAVE( "RXTXPort:readArray" );
3524 throw_java_exception( env, ARRAY_INDEX_OUT_OF_BOUNDS,
3525 "readArray", "Invalid length" );
3526 return -1;
3527 }
3528 body = (*env)->GetByteArrayElements( env, jbarray, 0 );
3529 bytes = read_byte_array( env, &jobj, fd, (unsigned char *)(body+offset), length, timeout );/* dima */
3530 (*env)->ReleaseByteArrayElements( env, jbarray, body, 0 );
3531 if( bytes < 0 ) {
3532 report( "RXTXPort:readArray bytes < 0" );
3533 LEAVE( "RXTXPort:readArray" );
3534 throw_java_exception( env, IO_EXCEPTION, "readArray",
3535 strerror( errno ) );
3536 return -1;
3537 }
3538 /*
3539 sprintf( msg, "RXTXPort:readArray: %i %i\n", (int) length, bytes);
3540 report( msg );
3541 report_time_end( );
3542 LEAVE( "RXTXPort:readArray" );
3543 */
3544 return (bytes);
3545 }
3546
3547 /*----------------------------------------------------------
3548 RXTXPort.nativeClearCommInput
3549
3550 accept: none
3551 perform: try to clear the input.
3552 return: true on success, false on error
3553 exceptions: none
3554 comments: This is an extension to commapi.
3555 ----------------------------------------------------------*/
3556 JNIEXPORT jboolean JNICALL RXTXPort(nativeClearCommInput)( JNIEnv *env,
3557 jobject jobj )
3558 {
3559 int fd = get_java_var( env, jobj, "fd", "I" );
3560 if ( tcflush( fd, TCIFLUSH ) )
3561 return( JNI_FALSE );
3562 return( JNI_TRUE );
3563 }
3564 /*----------------------------------------------------------
3565 RXTXPort.readTerminatedArray
3566
3567 accept: offset (offset to start storing data in the jbarray) and
3568 Length (bytes to read). Terminator - 2 bytes that we
3569 dont read past
3570 perform: read bytes from the port into a byte array
3571 return: bytes read on success
3572 0 on read timeout
3573 exceptions: IOException
3574 comments: throws ArrayIndexOutOfBoundsException if asked to
3575 read more than SSIZE_MAX bytes
3576 timeout is not properly handled
3577
3578 This is an extension to commapi.
3579 ----------------------------------------------------------*/
3580 JNIEXPORT jint JNICALL RXTXPort(readTerminatedArray)( JNIEnv *env,
3581 jobject jobj, jbyteArray jbarray, jint offset, jint length,
3582 jbyteArray jterminator )
3583 {
3584 int bytes, total = 0;
3585 jbyte *body, *terminator;
3586 /* char msg[80]; */
3587 int fd = get_java_var( env, jobj, "fd", "I" );
3588 int timeout = get_java_var( env, jobj, "timeout", "I" );
3589
3590 /*
3591 ENTER( "readArray" );
3592 report_time_start( );
3593 */
3594 if( (size_t) length > SSIZE_MAX || (size_t) length < 0 ) {
3595 report( "RXTXPort:readArray length > SSIZE_MAX" );
3596 LEAVE( "RXTXPort:readArray" );
3597 throw_java_exception( env, ARRAY_INDEX_OUT_OF_BOUNDS,
3598 "readArray", "Invalid length" );
3599 return -1;
3600 }
3601 body = (*env)->GetByteArrayElements( env, jbarray, 0 );
3602 terminator = (*env)->GetByteArrayElements( env, jterminator, 0 );
3603 do
3604 {
3605 bytes = read_byte_array( env, &jobj, fd, (unsigned char *)(body+offset + total ), 1 , timeout );/* dima */
3606 total += bytes;
3607 if( bytes < 0 ) {
3608 report( "RXTXPort:readArray bytes < 0" );
3609 LEAVE( "RXTXPort:readArray" );
3610 throw_java_exception( env, IO_EXCEPTION, "readArray",
3611 strerror( errno ) );
3612 return -1;
3613 }
3614 if ( total > 1 && terminator[1] == body[total -1] &&
3615 terminator[ 0 ] == body[ total -2 ]
3616 )
3617 {
3618 report("Got terminator!\n" );
3619 break;
3620 }
3621
3622 } while ( bytes > 0 && total < length );
3623 (*env)->ReleaseByteArrayElements( env, jbarray, body, 0 );
3624 /*
3625 sprintf( msg, "RXTXPort:readArray: %i %i\n", (int) length, bytes);
3626 report( msg );
3627 report_time_end( );
3628 LEAVE( "RXTXPort:readArray" );
3629 */
3630 return (bytes);
3631 }
3632
3633 /*----------------------------------------------------------
3634 RXTXPort.nativeavailable
3635
3636 accept: none
3637 perform: find out the number of bytes available for reading
3638 return: available bytes
3639 -1 on error
3640 exceptions: none
3641 ----------------------------------------------------------*/
3642 JNIEXPORT jint JNICALL RXTXPort(nativeavailable)( JNIEnv *env,
3643 jobject jobj )
3644 {
3645 int fd = get_java_var( env, jobj,"fd","I" );
3646 int result;
3647 /*
3648 char message[80];
3649
3650
3651 ENTER( "RXTXPort:nativeavailable" );
3652
3653 On SCO OpenServer FIONREAD always fails for serial devices,
3654 so try ioctl FIORDCHK instead; will only tell us whether
3655 bytes are available, not how many, but better than nothing.
3656
3657 This turns out to be true on Solaris also. taj.
3658 */
3659 #ifdef FIORDCHK /* __unixware__ __sun__ probably others */
3660 result = ioctl(fd, FIORDCHK, 0);
3661 #else
3662 if( ioctl( fd, FIONREAD, &result ) < 0 )
3663 {
3664 goto fail;
3665 }
3666 #endif /* FIORDCHK */
3667 if (result == -1) {
3668 goto fail;
3669 }
3670 /*
3671 sprintf(message, " nativeavailable: FIORDCHK result %d, \
3672 errno %d\n", result , result == -1 ? errno : 0);
3673 report_verbose( message );
3674 if( result )
3675 {
3676 sprintf(message, " nativeavailable: FIORDCHK result %d, \
3677 errno %d\n", result , result == -1 ? errno : 0);
3678 report( message );
3679 }
3680 LEAVE( "RXTXPort:nativeavailable" );
3681 */
3682 return (jint)result;
3683 fail:
3684 report("RXTXPort:nativeavailable: ioctl() failed\n");
3685 /*
3686 LEAVE( "RXTXPort:nativeavailable" );
3687 */
3688 throw_java_exception( env, IO_EXCEPTION, "nativeavailable",
3689 strerror( errno ) );
3690 return (jint)result;
3691 }
3692
3693 /*----------------------------------------------------------
3694 RXTXPort.setflowcontrol
3695
3696 accept: flowmode
3697 FLOWCONTROL_NONE none
3698 FLOWCONTROL_RTSCTS_IN hardware flow control
3699 FLOWCONTROL_RTSCTS_OUT ""
3700 FLOWCONTROL_XONXOFF_IN input software flow control
3701 FLOWCONTROL_XONXOFF_OUT output software flow control
3702 perform: set flow control to flowmode
3703 return: none
3704 exceptions: UnsupportedCommOperationException
3705 comments: there is no differentiation between input and output hardware
3706 flow control
3707 ----------------------------------------------------------*/
3708 JNIEXPORT void JNICALL RXTXPort(setflowcontrol)( JNIEnv *env,
3709 jobject jobj, jint flowmode )
3710 {
3711 struct termios ttyset;
3712 int fd = get_java_var( env, jobj,"fd","I" );
3713
3714 ENTER( "RXTXPort:setflowcontrol" );
3715 if( tcgetattr( fd, &ttyset ) ) goto fail;
3716
3717 if ( flowmode & ( FLOWCONTROL_RTSCTS_IN | FLOWCONTROL_RTSCTS_OUT ) )
3718 {
3719 ttyset.c_cflag |= HARDWARE_FLOW_CONTROL;
3720 }
3721 else ttyset.c_cflag &= ~HARDWARE_FLOW_CONTROL;
3722
3723 ttyset.c_iflag &= ~IXANY;
3724
3725 if ( flowmode & FLOWCONTROL_XONXOFF_IN )
3726 {
3727 ttyset.c_iflag |= IXOFF;
3728 }
3729 else ttyset.c_iflag &= ~IXOFF;
3730
3731 if ( flowmode & FLOWCONTROL_XONXOFF_OUT )
3732 {
3733
3734 ttyset.c_iflag |= IXON;
3735 }
3736 else ttyset.c_iflag &= ~IXON;
3737 /* TRENT */
3738 if( tcsetattr( fd, TCSANOW, &ttyset ) ) goto fail;
3739 LEAVE( "RXTXPort:setflowcontrol" );
3740 return;
3741 fail:
3742 LEAVE( "RXTXPort:setflowcontrol" );
3743 throw_java_exception( env, UNSUPPORTED_COMM_OPERATION, "",
3744 "flow control type not supported" );
3745 return;
3746 }
3747
3748 /*----------------------------------------------------------
3749 unlock_monitor_thread
3750
3751 accept: event_info_struct
3752 perform: unlock the monitor thread so event notification can start.
3753 return: none
3754 exceptions: none
3755 comments: Events can be missed otherwise.
3756 ----------------------------------------------------------*/
3757
3758 void unlock_monitor_thread( struct event_info_struct *eis )
3759 {
3760 JNIEnv *env = eis->env;
3761 jobject jobj = *(eis->jobj);
3762
3763 jfieldID jfid = (*env)->GetFieldID( env, (*env)->GetObjectClass( env, jobj ), "MonitorThreadLock", "Z" );
3764 (*env)->SetBooleanField( env, jobj, jfid, (jboolean) 0 );
3765 }
3766
3767 /*----------------------------------------------------------
3768 check_line_status_register
3769
3770 accept: event_info_struct
3771 perform: check for changes on the LSR
3772 return: 0 on success
3773 exceptions: none
3774 comments: not supported on all devices/drivers.
3775 ----------------------------------------------------------*/
3776 int check_line_status_register( struct event_info_struct *eis )
3777 {
3778 #ifdef TIOCSERGETLSR
3779 struct stat fstatbuf;
3780
3781 if( ! eis->eventflags[SPE_OUTPUT_BUFFER_EMPTY] )
3782 {
3783 /* This occurs constantly so remove for now
3784 * report( "check_line_status_registe OUPUT_BUFFER_EMPTY not set\n" );
3785 */
3786 return 0;
3787 }
3788 if ( fstat( eis->fd, &fstatbuf ) )
3789 {
3790 report( "check_line_status_register: fstat\n" );
3791 return( 1 );
3792 }
3793 if( ioctl( eis->fd, TIOCSERGETLSR, &eis->change ) )
3794 {
3795 report( "check_line_status_register: TIOCSERGETLSR\n is nonnull\n" );
3796 return( 1 );
3797 }
3798 else if( eis && eis->change )
3799 {
3800 report_verbose( "check_line_status_register: sending OUTPUT_BUFFER_EMPTY\n" );
3801 send_event( eis, SPE_OUTPUT_BUFFER_EMPTY, 1 );
3802 }
3803 #else
3804 /*
3805 printf("test %i\n", eis->output_buffer_empty_flag );
3806 */
3807 if( eis && eis->output_buffer_empty_flag == 1 &&
3808 eis->eventflags[SPE_OUTPUT_BUFFER_EMPTY] )
3809 {
3810 report_verbose("check_line_status_register: sending SPE_OUTPUT_BUFFER_EMPTY\n");
3811 send_event( eis, SPE_OUTPUT_BUFFER_EMPTY, 1 );
3812 /*
3813 send_event( eis, SPE_DATA_AVAILABLE, 1 );
3814 */
3815 eis->output_buffer_empty_flag = 0;
3816 }
3817 #endif /* TIOCSERGETLSR */
3818 return( 0 );
3819 }
3820
3821 /*----------------------------------------------------------
3822 has_line_status_register_access
3823
3824 accept: fd of interest
3825 perform: check for access to the LSR
3826 return: 0 if not available
3827 exceptions: none
3828 comments: not supported on all devices/drivers.
3829 JK00: work around for multiport cards without TIOCSERGETLSR
3830 Cyclades is one of those :-(
3831 ----------------------------------------------------------*/
3832 int has_line_status_register_access( int fd )
3833 {
3834 #if defined(TIOCSERGETLSR)
3835 int change;
3836
3837 if( !ioctl( fd, TIOCSERGETLSR, &change ) ) {
3838 return(1);
3839 }
3840 #endif /* TIOCSERGETLSR */
3841 report( "has_line_status_register_acess: Port does not support TIOCSERGETLSR\n" );
3842 return( 0 );
3843 }
3844
3845 /*----------------------------------------------------------
3846 check_cgi_count
3847
3848 accept: fd of interest
3849 perform: check for access to TIOCGICOUNT
3850 return: 0 if not available
3851 exceptions: none
3852 comments: not supported on all devices/drivers.
3853 * wait for RNG, DSR, CD or CTS but not DataAvailable
3854 * The drawback here is it never times out so if someone
3855 * reads there will be no chance to try again.
3856 * This may make sense if the program does not want to
3857 * be notified of data available or errors.
3858 * ret=ioctl(fd,TIOCMIWAIT);
3859 ----------------------------------------------------------*/
3860 void check_cgi_count( struct event_info_struct *eis )
3861 {
3862 #if defined(TIOCGICOUNT)
3863
3864 /* JK00: only use it if supported by this port */
3865
3866 struct serial_icounter_struct sis;
3867 memcpy( &sis, &eis->osis, sizeof( struct serial_icounter_struct ) );
3868
3869 if( ioctl( eis->fd, TIOCGICOUNT, &sis ) )
3870 {
3871 report( "check_cgi_count: TIOCGICOUNT\n is not 0\n" );
3872 return;
3873 }
3874 while( eis && sis.frame != eis->osis.frame ) {
3875 send_event( eis, SPE_FE, 1);
3876 eis->osis.frame++;
3877 }
3878 while( eis && sis.overrun != eis->osis.overrun ) {
3879 send_event( eis, SPE_OE, 1);
3880 eis->osis.overrun++;
3881 }
3882 while( eis && sis.parity != eis->osis.parity ) {
3883 send_event( eis, SPE_PE, 1);
3884 eis->osis.parity++;
3885 }
3886 while( eis && sis.brk != eis->osis.brk ) {
3887 send_event( eis, SPE_BI, 1);
3888 eis->osis.brk++;
3889 }
3890 if( eis )
3891 memcpy( &eis->osis, &sis, sizeof( struct serial_icounter_struct ) );
3892 #endif /* TIOCGICOUNT */
3893 }
3894
3895 /*----------------------------------------------------------
3896 port_has_changed_fionread
3897
3898 accept: fd of interest
3899 perform: check if FIONREAD has changed
3900 return: 0 if no data available
3901 exceptions: none
3902 comments:
3903 ----------------------------------------------------------*/
3904 int port_has_changed_fionread( struct event_info_struct *eis )
3905 {
3906 int change, rc;
3907 char message[80];
3908
3909 rc = ioctl( eis->fd, FIONREAD, &change );
3910 sprintf( message, "port_has_changed_fionread: change is %i ret is %i\n", change, eis->ret );
3911 #if defined(__unixware__) || defined(__sun__)
3912 /*
3913 On SCO OpenServer FIONREAD always fails for serial devices,
3914 so rely upon select() result to know whether data available.
3915
3916 This is true for Solaris, also. taj.
3917 */
3918 if( (rc != -1 && change) || (rc == -1 && eis->ret > 0) )
3919 return( 1 );
3920 #else
3921 sprintf( message, "port_has_changed_fionread: change is %i\n", change );
3922 report_verbose( message );
3923 if( change )
3924 return( 1 );
3925 #endif /* __unixware__ || __sun__ */
3926 return( 0 );
3927 }
3928
3929 /*----------------------------------------------------------
3930 check_tiocmget_changes
3931
3932 accept: event_info_struct
3933 perform: use TIOCMGET to report events
3934 return: none
3935 exceptions: none
3936 comments: not supported on all devices/drivers.
3937 ----------------------------------------------------------*/
3938 void check_tiocmget_changes( struct event_info_struct * eis )
3939 {
3940 unsigned int mflags = 0;
3941 int change;
3942
3943 /* DORITO */
3944 if( !eis ) return;
3945 change = eis->change;
3946
3947 report_verbose("entering check_tiocmget_changes\n");
3948 if( ioctl( eis->fd, TIOCMGET, &mflags ) )
3949 {
3950 report( "=======================================\n");
3951 report( "check_tiocmget_changes: ioctl(TIOCMGET)\n" );
3952 return;
3953 }
3954
3955 change = (mflags&TIOCM_CTS) - (eis->omflags&TIOCM_CTS);
3956 if( eis && change ) send_event( eis, SPE_CTS, change );
3957
3958 change = (mflags&TIOCM_DSR) - (eis->omflags&TIOCM_DSR);
3959 if( eis && change )
3960 {
3961 report( "sending DSR ===========================\n");
3962 send_event( eis, SPE_DSR, change );
3963 }
3964
3965 change = (mflags&TIOCM_RNG) - (eis->omflags&TIOCM_RNG);
3966 if( eis && change ) send_event( eis, SPE_RI, change );
3967
3968 change = (mflags&TIOCM_CD) - (eis->omflags&TIOCM_CD);
3969 if( eis && change ) send_event( eis, SPE_CD, change );
3970
3971 if( eis )
3972 eis->omflags = mflags;
3973 report_verbose("leaving check_tiocmget_changes\n");
3974 }
3975
3976 /*----------------------------------------------------------
3977 system_wait
3978
3979 accept:
3980 perform:
3981 return:
3982 exceptions: none
3983 comments:
3984 ----------------------------------------------------------*/
3985 void system_wait()
3986 {
3987 #if defined (__sun__ )
3988 struct timespec retspec, tspec;
3989 retspec.tv_sec = 0;
3990 retspec.tv_nsec = 100000000;
3991 do {
3992 tspec = retspec;
3993 nanosleep( &tspec, &retspec );
3994 } while( tspec.tv_nsec != 0 );
3995 /* Trent
3996 */
3997 #else
3998 #ifdef TRENT_IS_HERE_DEBUGGING_THREADS
3999 /* On NT4 The following was observed in a intense test:
4000 50000 95% 179 sec
4001 200000 95% 193 sec
4002 1000000 95% 203 sec some callback failures sometimes.
4003 2000000 0-95% callback failures.
4004 */
4005 #endif /* TRENT_IS_HERE_DEBUGGING_THREADS */
4006 #endif /* __sun__ */
4007 }
4008
4009 /*----------------------------------------------------------
4010 driver_has_tiocgicount
4011
4012 accept: fd of interest
4013 perform: check for access to TIOCGICOUNT
4014 return: 0 if not available
4015 exceptions: none
4016 comments: not supported on all devices/drivers.
4017 Some multiport serial cards do not implement TIOCGICOUNT ...
4018 So use the 'dumb' mode to enable using them after all! JK00
4019 ----------------------------------------------------------*/
4020 int driver_has_tiocgicount( struct event_info_struct * eis )
4021 {
4022 #if defined(TIOCGICOUNT)
4023
4024 /* Some multiport serial cards do not implement TIOCGICOUNT ... */
4025 /* So use the 'dumb' mode to enable using them after all! JK00 */
4026
4027 if( ioctl( eis->fd, TIOCGICOUNT, &eis->osis ) < 0 ) {
4028 report_verbose( " driver_has_tiocgicount: Port does not support TIOCGICOUNT events\n" );
4029 return(0);
4030 }
4031 else
4032 return(1);
4033 #endif /* TIOCGICOUNT */
4034 return(0);
4035
4036 }
4037
4038 /*----------------------------------------------------------
4039 report_serial_events
4040
4041 accept: event_info_struct
4042 perform: send events if they occured
4043 return: 0 if not available
4044 exceptions: none
4045 comments: not supported on all devices/drivers.
4046 ----------------------------------------------------------*/
4047 void report_serial_events( struct event_info_struct *eis )
4048 {
4049 /* JK00: work around for Multi IO cards without TIOCSERGETLSR */
4050 /* if( eis->has_tiocsergetlsr ) we have a fix for output empty */
4051 if( check_line_status_register( eis ) )
4052 return;
4053
4054 if ( eis && eis->has_tiocgicount )
4055 check_cgi_count( eis );
4056 #ifndef WIN32 /* something is wrong here */
4057 #endif /* WIN32 */
4058
4059 check_tiocmget_changes( eis );
4060 if( eis && port_has_changed_fionread( eis ) )
4061 {
4062 if(!eis->eventflags[SPE_DATA_AVAILABLE] )
4063 {
4064 report_verbose("report_serial_events: ignoring DATA_AVAILABLE\n");
4065 /*
4066 report(".");
4067 */
4068 usleep(20000);
4069 #if !defined(__sun__)
4070 /* FIXME: No time to test on all OS's for production */
4071 usleep(20000);
4072 #endif /* !__sun__ */
4073 return;
4074 }
4075 report("report_serial_events: sending DATA_AVAILABLE\n");
4076 if(!send_event( eis, SPE_DATA_AVAILABLE, 1 ))
4077 {
4078 /* select wont block */
4079 /* FIXME: No time to test on all OS's for production */
4080 /* REMOVE goes around usleep */
4081 #if !defined(__sun__)
4082 #endif /* !__sun__ */
4083 }
4084 usleep(20000);
4085 }
4086 }
4087
4088 /*----------------------------------------------------------
4089 initialise_event_info_struct
4090
4091 accept: event_info_struct for this thread.
4092 perform: initialise or reset the event_info_struct
4093 return: 1 on success
4094 exceptions: none
4095 comments:
4096 ----------------------------------------------------------*/
4097 int initialise_event_info_struct( struct event_info_struct *eis )
4098 {
4099 int i;
4100 jobject jobj = *eis->jobj;
4101 JNIEnv *env = eis->env;
4102 struct event_info_struct *index = master_index;
4103
4104 if ( eis->initialised == 1 )
4105 goto end;
4106
4107 #ifdef TIOCGICOUNT
4108 memset(&eis->osis,0,sizeof(eis->osis));
4109 #endif /* TIOCGICOUNT */
4110
4111 if( index )
4112 {
4113 while( index->next )
4114 {
4115 index = index->next;
4116 }
4117 index->next = eis;
4118 eis->prev = index;
4119 eis->next = NULL;
4120 }
4121 else
4122 {
4123 master_index = eis;
4124 master_index->next = NULL;
4125 master_index->prev = NULL;
4126 }
4127
4128 for( i = 0; i < 11; i++ ) eis->eventflags[i] = 0;
4129 #if !defined(TIOCSERGETLSR) && !defined(WIN32)
4130 eis->output_buffer_empty_flag = 0;
4131 eis->writing = 0;
4132 #endif /* TIOCSERGETLSR */
4133 eis->eventloop_interrupted = 0;
4134 eis->closing = 0;
4135
4136 eis->fd = get_java_var( env, jobj, "fd", "I" );
4137 eis->has_tiocsergetlsr = has_line_status_register_access( eis->fd );
4138 eis->has_tiocgicount = driver_has_tiocgicount( eis );
4139
4140 if( ioctl( eis->fd, TIOCMGET, &eis->omflags) < 0 ) {
4141 report( "initialise_event_info_struct: Port does not support events\n" );
4142 }
4143
4144 eis->send_event = (*env)->GetMethodID( env, eis->jclazz, "sendEvent",
4145 "(IZ)Z" );
4146 if(eis->send_event == NULL)
4147 goto fail;
4148 end:
4149 FD_ZERO( &eis->rfds );
4150 FD_SET( eis->fd, &eis->rfds );
4151 eis->tv_sleep.tv_sec = 0;
4152 eis->tv_sleep.tv_usec = 1000;
4153 eis->initialised = 1;
4154 return( 1 );
4155 fail:
4156 report_error("initialise_event_info_struct: initialise failed!\n");
4157 finalize_event_info_struct( eis );
4158 return( 0 );
4159 }
4160
4161 /*----------------------------------------------------------
4162 finalize_event_info_struct
4163
4164 accept: event_info_struct for this thread.
4165 perform: free resources
4166 return: none
4167 exceptions: none
4168 comments:
4169 ----------------------------------------------------------*/
4170 void finalize_event_info_struct( struct event_info_struct *eis )
4171 {
4172 if( eis->jclazz)
4173 {
4174 (*eis->env)->DeleteLocalRef( eis->env, eis->jclazz );
4175 }
4176 if( eis->next && eis->prev )
4177 {
4178 eis->prev->next = eis->next;
4179 eis->next->prev = eis->prev;
4180 }
4181 else if( eis->next )
4182 {
4183 eis->next->prev = NULL;
4184 master_index = eis->next;
4185 }
4186 else if( eis->prev )
4187 eis->prev->next = NULL;
4188 else master_index = NULL;
4189 }
4190
4191 /*----------------------------------------------------------
4192 RXTXPort.eventLoop
4193
4194 accept: none
4195 perform: periodically check for SerialPortEvents
4196 return: none
4197 exceptions: none
4198 comments: please keep this function clean.
4199 ----------------------------------------------------------*/
4200 JNIEXPORT void JNICALL RXTXPort(eventLoop)( JNIEnv *env, jobject jobj )
4201 {
4202 #ifdef WIN32
4203 int i = 0;
4204 #endif /* WIN32 */
4205 struct event_info_struct eis;
4206 eis.jclazz = (*env)->GetObjectClass( env, jobj );
4207 eis.env = env;
4208 eis.jobj = &jobj;
4209 eis.initialised = 0;
4210
4211 ENTER( "eventLoop\n" );
4212 if ( !initialise_event_info_struct( &eis ) ) goto end;
4213 if ( !init_threads( &eis ) ) goto end;
4214 unlock_monitor_thread( &eis );
4215 do{
4216 report_time_eventLoop( );
4217 do {
4218 /* nothing goes between this call and select */
4219 if( eis.closing )
4220 {
4221 report("eventLoop: got interrupt\n");
4222 finalize_threads( &eis );
4223 finalize_event_info_struct( &eis );
4224 LEAVE("eventLoop");
4225 return;
4226 }
4227 #ifndef WIN32
4228 /* report( "." ); */
4229 do {
4230 eis.ret = SELECT( eis.fd + 1, &eis.rfds, NULL, NULL,
4231 &eis.tv_sleep );
4232 } while (eis.ret < 0 && errno==EINTR);
4233 #else
4234 /*
4235 termios.c:serial_select is instable for some
4236 reason
4237
4238 polling is not blowing up.
4239 */
4240 /*
4241 usleep(5000);
4242 */
4243 eis.ret=1;
4244 while( i++ < 5 )
4245 {
4246 if(eis.eventflags[SPE_DATA_AVAILABLE] )
4247 {
4248 if( port_has_changed_fionread( &eis ) )
4249 {
4250 send_event( &eis, SPE_DATA_AVAILABLE, 1 );
4251 }
4252 }
4253 usleep(1000);
4254 }
4255 i = 0;
4256 #endif /* WIN32 */
4257 } while ( eis.ret < 0 && errno == EINTR );
4258 if( eis.ret >= 0 )
4259 {
4260 report_serial_events( &eis );
4261 }
4262 initialise_event_info_struct( &eis );
4263 } while( 1 );
4264 end:
4265 LEAVE( "eventLoop: Bailing!\n" );
4266 }
4267
4268 /*----------------------------------------------------------
4269 RXTXVersion.nativeGetVersion
4270
4271 accept: none
4272 perform: return the current version
4273 return: version
4274 exceptions: none
4275 comments: This is used to avoid mixing versions of the .jar and
4276 native library.
4277 First introduced in rxtx-1.5-9
4278 Moved from RXTXCommDriver to RXTXVersion in rxtx-2.1-7
4279
4280 ----------------------------------------------------------*/
4281 JNIEXPORT jstring JNICALL RXTXVersion(nativeGetVersion) (JNIEnv *env,
4282 jclass jclazz )
4283 {
4284 return (*env)->NewStringUTF( env, "RXTX-2.2" );
4285 }
4286
4287 /*----------------------------------------------------------
4288 RXTXCommDriver.testRead
4289
4290 accept: tty_name The device to be tested
4291 perform: test if the device can be read from
4292 return: JNI_TRUE if the device can be read from
4293 exceptions: none
4294 comments: From Wayne Roberts [email protected]
4295 check tcget/setattr returns.
4296 support for non serial ports Trent
4297 ----------------------------------------------------------*/
4298
4299 JNIEXPORT jboolean JNICALL RXTXCommDriver(testRead)(
4300 JNIEnv *env,
4301 jobject jobj,
4302 jstring tty_name,
4303 jint port_type
4304 )
4305 {
4306 struct termios ttyset;
4307 char c;
4308 #ifdef TRENT_IS_HERE_DEBUGGING_ENUMERATION
4309 char message[80];
4310 #endif /* TRENT_IS_HERE_DEBUGGING_ENUMERATION */
4311 int fd;
4312 const char *name = (*env)->GetStringUTFChars(env, tty_name, 0);
4313 int ret = JNI_TRUE;
4314 int pid = -1;
4315 /* We opened the file in this thread, use this pid to unlock */
4316 #ifndef WIN32
4317 pid = getpid();
4318 #else
4319 char full_windows_name[80];
4320 #endif /* WIN32 */
4321
4322 ENTER( "RXTXPort:testRead" );
4323 #ifdef TRENT_IS_HERE_DEBUGGING_ENUMERATION
4324 /* vmware lies about which ports are there causing irq conflicts */
4325 /* this is for testing only */
4326 if( !strcmp( name, "COM1" ) || !strcmp( name, "COM2") )
4327 {
4328 printf("%s is good\n",name);
4329 sprintf( message, "testRead: %s is good!\n", name );
4330 report( message );
4331 (*env)->ReleaseStringUTFChars( env, tty_name, name );
4332 return( JNI_TRUE );
4333 }
4334 (*env)->ReleaseStringUTFChars( env, tty_name, name );
4335 return( JNI_FALSE );
4336 #endif /* TRENT_IS_HERE_DEBUGGING_ENUMERATION */
4337 #ifdef WIN32
4338 strcpy( full_windows_name, DEVICEDIR );
4339 strcat( full_windows_name, name );
4340 ret = serial_test((char *) full_windows_name );
4341 (*env)->ReleaseStringUTFChars( env, tty_name, name );
4342 return(ret);
4343 #endif /* WIN32 */
4344
4345 /*
4346 LOCK is one of three functions defined in SerialImp.h
4347
4348 uucp_lock Solaris
4349 fhs_lock Linux
4350 system_does_not_lock Win32
4351 */
4352
4353 if ( LOCK( name, pid ) )
4354 {
4355 (*env)->ReleaseStringUTFChars(env, tty_name, name);
4356 LEAVE( "RXTXPort:testRead no lock" );
4357 return JNI_FALSE;
4358 }
4359
4360 /*
4361 CLOCAL eliminates open blocking on modem status lines
4362 -- changed to O_NONBLOCK
4363 */
4364 do {
4365 fd=OPEN ( name, O_RDWR | O_NOCTTY | O_NONBLOCK );
4366 } while ( fd < 0 && errno==EINTR );
4367
4368 if( fd < 0 )
4369 {
4370 report_verbose( "testRead() open \"" );
4371 report_verbose( name );
4372 report_verbose( "\" failed: " );
4373 report_verbose( strerror(errno) );
4374 report_verbose( "\n" );
4375 ret = JNI_FALSE;
4376 goto END;
4377 }
4378
4379 if ( port_type == PORT_SERIAL )
4380 {
4381 int saved_flags;
4382 struct termios saved_termios;
4383
4384 if (tcgetattr(fd, &ttyset) < 0) {
4385 ret = JNI_FALSE;
4386 goto END;
4387 }
4388
4389 /* save, restore later */
4390 if ( ( saved_flags = fcntl(fd, F_GETFL ) ) < 0 )
4391 {
4392 report( "testRead() fcntl(F_GETFL) failed\n" );
4393 ret = JNI_FALSE;
4394 goto END;
4395 }
4396
4397 memcpy( &saved_termios, &ttyset, sizeof( struct termios ) );
4398
4399 if ( fcntl( fd, F_SETFL, O_NONBLOCK ) < 0 )
4400 {
4401 report( "testRead() fcntl(F_SETFL) failed\n" );
4402 ret = JNI_FALSE;
4403 goto END;
4404 }
4405
4406 cfmakeraw(&ttyset);
4407 ttyset.c_cc[VMIN] = ttyset.c_cc[VTIME] = 0;
4408
4409 if ( tcsetattr( fd, TCSANOW, &ttyset) < 0 )
4410 {
4411 report( "testRead() tcsetattr failed\n" );
4412 ret = JNI_FALSE;
4413 tcsetattr( fd, TCSANOW, &saved_termios );
4414 goto END;
4415 }
4416
4417 /*
4418
4419 The following may mess up if both EAGAIN and EWOULDBLOCK
4420 are defined but only EWOULDBLOCK is used
4421
4422 Linux:
4423
4424 man 2 open
4425 O_NONBLOCK or O_NDELAY
4426 When possible, the file is opened in non-blocking
4427 mode. Neither the open nor any subsequent opera�
4428 tions on the file descriptor which is returned will
4429 cause the calling process to wait. For the han�
4430 dling of FIFOs (named pipes), see also fifo(4).
4431 This mode need not have any effect on files other
4432 than FIFOs.
4433
4434 man 2 read
4435 EAGAIN
4436 Non-blocking I/O has been selected using O_NONBLOCK
4437 and no data was immediately available for reading.
4438
4439
4440 /usr/include/asm/error.h:
4441 #define EAGAIN 11 / Try again /
4442 #define EWOULDBLOCK EAGAIN / Operation would block /
4443
4444 looks like the kernel is using EAGAIN
4445
4446 -- should be OK
4447
4448 Solaris:
4449
4450 man 2 open
4451 EAGAIN The path argument names the slave side of a
4452 pseudo-terminal device that is locked.
4453
4454 man 2 read
4455 If O_NONBLOCK is set, read() returns -1 and sets errno
4456 to EAGAIN.
4457
4458 -- should be OK.
4459
4460 HP-UX
4461
4462 both are defined but EAGAIN is used.
4463
4464 -- should be OK.
4465
4466 Win32
4467
4468 neither errno is currently set. Comment added to termios.c
4469 serial_open().
4470
4471 -- should be OK
4472
4473 Steven's book. Advanced programming in the Unix Environment pg 364
4474
4475 "A common use for nonblocking I/O is for dealing with a terminal device
4476 for a network connection and these devices are normally used by one process
4477 at a time. This means that the change in the BSD semantics normally does 't
4478 effect us. The different error return, EWOULDBLOCK, instead of POSIX.1
4479 EAGAIN, continues to be a portability difference that we must deal with."
4480
4481 */
4482
4483 if ( READ( fd, &c, 1 ) < 0 )
4484 {
4485 #ifdef EAGAIN
4486 if ( errno != EAGAIN ) {
4487 report( "testRead() read failed\n" );
4488 ret = JNI_FALSE;
4489 }
4490 #else
4491 #ifdef EWOULDBLOCK
4492 if ( errno != EWOULDBLOCK )
4493 {
4494 report( "testRead() read failed\n" );
4495 ret = JNI_FALSE;
4496 }
4497 #else
4498 ret = JNI_FALSE;
4499 #endif /* EWOULDBLOCK */
4500 #endif /* EAGAIN */
4501 }
4502
4503 /* dont walk over unlocked open devices */
4504 tcsetattr( fd, TCSANOW, &saved_termios );
4505 fcntl( fd, F_SETFL, saved_flags );
4506 }
4507
4508 /*
4509 UNLOCK is one of three functions defined in SerialImp.h
4510
4511 uucp_unlock Solaris
4512 fhs_unlock Linux
4513 system_does_not_unlock Win32
4514 */
4515
4516 END:
4517 UNLOCK(name, pid );
4518 (*env)->ReleaseStringUTFChars( env, tty_name, name );
4519 CLOSE( fd );
4520 LEAVE( "RXTXPort:testRead" );
4521 return ret;
4522 }
4523
4524 #if defined(__APPLE__)
4525 /*----------------------------------------------------------
4526 createSerialIterator()
4527 accept:
4528 perform:
4529 return:
4530 exceptions:
4531 comments:
4532 Code courtesy of Eric Welch at Keyspan, except for the bugs
4533 which are courtesy of Joseph Goldstone ([email protected])
4534 ----------------------------------------------------------*/
4535
4536 kern_return_t
4537 createSerialIterator(io_iterator_t *serialIterator)
4538 {
4539 kern_return_t kernResult;
4540 mach_port_t masterPort;
4541 CFMutableDictionaryRef classesToMatch;
4542 if ((kernResult=IOMasterPort( (int) NULL, &masterPort ) ) != KERN_SUCCESS)
4543 {
4544 printf( "IOMasterPort returned %d\n", kernResult);
4545 return kernResult;
4546 }
4547 if ((classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue)) == NULL)
4548 {
4549 printf( "IOServiceMatching returned NULL\n" );
4550 return kernResult;
4551 }
4552 CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
4553 kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch, serialIterator);
4554 if (kernResult != KERN_SUCCESS)
4555 {
4556 printf( "IOServiceGetMatchingServices returned %d\n", kernResult);
4557 }
4558 return kernResult;
4559 }
4560
4561 /*----------------------------------------------------------
4562 getRegistryString()
4563
4564 accept:
4565 perform:
4566 return:
4567 exceptions:
4568 comments:
4569 Code courtesy of Eric Welch at Keyspan, except for the bugs
4570 which are courtesy of Joseph Goldstone ([email protected])
4571 ----------------------------------------------------------*/
4572 char *
4573 getRegistryString(io_object_t sObj, char *propName)
4574 {
4575 static char resultStr[256];
4576 CFTypeRef nameCFstring;
4577 resultStr[0] = 0;
4578 nameCFstring = IORegistryEntryCreateCFProperty(sObj,
4579 CFStringCreateWithCString(kCFAllocatorDefault, propName, kCFStringEncodingASCII),
4580 kCFAllocatorDefault, 0);
4581 if (nameCFstring)
4582 {
4583 CFStringGetCString(nameCFstring, resultStr, sizeof(resultStr), kCFStringEncodingASCII);
4584 CFRelease(nameCFstring);
4585 }
4586 return resultStr;
4587 }
4588
4589 /*----------------------------------------------------------
4590 registerKnownSerialPorts()
4591 accept:
4592 perform:
4593 return:
4594 exceptions:
4595 comments:
4596 ----------------------------------------------------------*/
4597 int
4598 registerKnownSerialPorts(JNIEnv *env, jobject jobj, jint portType) /* dima */
4599 {
4600 io_iterator_t theSerialIterator;
4601 io_object_t theObject;
4602 int numPorts = 0;/* dima it should initiated */
4603
4604 if (( createSerialIterator( &theSerialIterator ) != KERN_SUCCESS) ||
4605 ( ! IOIteratorIsValid( theSerialIterator)))
4606 {
4607 /* This also happens when no drivers are installed */
4608 report( "createSerialIterator failed\n" );
4609 return(0);
4610 } else {
4611 jclass cls; /* dima */
4612 jmethodID mid; /* dima */
4613 cls = (*env)->FindClass(env,"gnu/io/CommPortIdentifier" ); /* dima */
4614 if (cls == 0) { /* dima */
4615 report( "can't find class of gnu/io/CommPortIdentifier\n" ); /* dima */
4616 return numPorts; /* dima */
4617 } /* dima */
4618 mid = (*env)->GetStaticMethodID(env, cls, "addPortName", "(Ljava/lang/String;ILgnu/io/CommDriver;)V" ); /* dima */
4619
4620 if (mid == 0) {
4621 printf( "getMethodID of CommDriver.addPortName failed\n" );
4622 } else {
4623 while (theObject = IOIteratorNext(theSerialIterator))
4624 {
4625 /* begin dima */
4626 jstring tempJstring;
4627 tempJstring = (*env)->NewStringUTF(env,getRegistryString(theObject, kIODialinDeviceKey));
4628 (*env)->CallStaticVoidMethod(env, cls, mid,tempJstring,portType,jobj);/* dima */
4629 (*env)->DeleteLocalRef(env,tempJstring);
4630 numPorts++;
4631
4632 tempJstring = (*env)->NewStringUTF(env,getRegistryString(theObject, kIOCalloutDeviceKey));
4633 (*env)->CallStaticVoidMethod(env, cls, mid,tempJstring,portType,jobj);/* dima */
4634 (*env)->DeleteLocalRef(env,tempJstring);
4635 numPorts++;
4636 /* end dima */
4637 }
4638 }
4639 }
4640 return numPorts;
4641 }
4642 #endif /* __APPLE__ */
4643
4644 /*----------------------------------------------------------
4645 registerKnownPorts
4646
4647 accept: the type of port
4648 perform: register any ports of the desired type a priori known to this OS
4649 return: JNI_TRUE if any such ports were registered otherwise JNI_FALSE
4650 exceptions: none
4651 comments:
4652 ----------------------------------------------------------*/
4653 JNIEXPORT jboolean JNICALL RXTXCommDriver(registerKnownPorts)(JNIEnv *env,
4654 jobject jobj, jint portType)
4655 {
4656 enum {PORT_TYPE_SERIAL = 1,
4657 PORT_TYPE_PARALLEL,
4658 PORT_TYPE_I2C,
4659 PORT_TYPE_RS485,
4660 PORT_TYPE_RAW};
4661 jboolean result = JNI_FALSE;
4662 char message[80];
4663
4664 switch(portType) {
4665 case PORT_TYPE_SERIAL:
4666 #if defined(__APPLE__)
4667 if (registerKnownSerialPorts(env, jobj,
4668 PORT_TYPE_SERIAL) > 0) {/* dima */
4669 result = JNI_TRUE;
4670 }
4671 #endif
4672 break;
4673 case PORT_TYPE_PARALLEL: break;
4674 case PORT_TYPE_I2C: break;
4675 case PORT_TYPE_RS485: break;
4676 case PORT_TYPE_RAW: break;
4677 default:
4678 sprintf( message, "unknown portType %d handed to \
4679 native RXTXCommDriver.registerKnownPorts() \
4680 method.\n",
4681 (int) portType
4682 );
4683 report( message );
4684 }
4685 return result;
4686 }
4687
4688 /*----------------------------------------------------------
4689 isPortPrefixValid
4690
4691 accept: a port prefix
4692 perform: see if the port prefix matches a port that is valid on this OS.
4693 return: JNI_TRUE if it exists otherwise JNI_FALSE
4694 exceptions: none
4695 comments:
4696 ----------------------------------------------------------*/
4697 JNIEXPORT jboolean JNICALL RXTXCommDriver(isPortPrefixValid)(JNIEnv *env,
4698 jobject jobj, jstring tty_name)
4699 {
4700 jboolean result;
4701 static struct stat mystat;
4702 char teststring[256];
4703 int fd,i;
4704 const char *name = (*env)->GetStringUTFChars(env, tty_name, 0);
4705
4706 ENTER( "RXTXCommDriver:isPortPrefixValid" );
4707 for(i=0;i<64;i++){
4708 #if defined(__sun__)
4709 /* Solaris uses /dev/cua/a instead of /dev/cua0 */
4710 if( i > 25 ) break;
4711 sprintf(teststring,"%s%s%c",DEVICEDIR, name, i + 97 );
4712 fprintf(stderr, "testing: %s\n", teststring);
4713 #else
4714 #if defined(_GNU_SOURCE)
4715 snprintf(teststring, 256, "%s%s%i",DEVICEDIR,name, i);
4716 #else
4717 sprintf(teststring,"%s%s%i",DEVICEDIR,name, i);
4718 #endif /* _GNU_SOURCE */
4719 stat(teststring,&mystat);
4720 #endif /* __sun__ */
4721 /* XXX the following hoses freebsd when it tries to open the port later on */
4722 #ifndef __FreeBSD_kernel__
4723 if(S_ISCHR(mystat.st_mode)){
4724 fd=OPEN(teststring,O_RDONLY|O_NONBLOCK);
4725 if (fd>0){
4726 CLOSE(fd);
4727 result=JNI_TRUE;
4728 break;
4729 }
4730 else
4731 result=JNI_FALSE;
4732 }
4733 else
4734 result=JNI_FALSE;
4735 #else
4736 result=JNI_TRUE;
4737 #endif /* __FreeBSD __ */
4738 }
4739 #if defined(_GNU_SOURCE)
4740 snprintf(teststring, 256, "%s%s",DEVICEDIR,name);
4741 #else
4742 sprintf(teststring,"%s%s",DEVICEDIR,name);
4743 #endif /* _GNU_SOURCE */
4744 stat(teststring,&mystat);
4745 if(S_ISCHR(mystat.st_mode)){
4746 fd=OPEN(teststring,O_RDONLY|O_NONBLOCK);
4747 if (fd>0){
4748 CLOSE(fd);
4749 result=JNI_TRUE;
4750 }
4751 }
4752 (*env)->ReleaseStringUTFChars(env, tty_name, name);
4753 LEAVE( "RXTXCommDriver:isPortPrefixValid" );
4754 return(result);
4755 }
4756
4757 /*----------------------------------------------------------
4758 getDeviceDirectory
4759
4760 accept:
4761 perform:
4762 return: the directory containing the device files
4763 exceptions:
4764 comments: use this to avoid hard coded "/dev/"
4765 values are in SerialImp.h
4766 ----------------------------------------------------------*/
4767
4768 JNIEXPORT jstring JNICALL RXTXCommDriver(getDeviceDirectory)(JNIEnv *env,
4769 jobject jobj)
4770 {
4771 ENTER( "RXTXCommDriver:getDeviceDirectory" );
4772 return (*env)->NewStringUTF(env, DEVICEDIR);
4773 LEAVE( "RXTXCommDriver:getDeviceDirectory" );
4774 }
4775
4776 /*----------------------------------------------------------
4777 setInputBufferSize
4778
4779 accept:
4780 perform:
4781 return: none
4782 exceptions: none
4783 comments: see fopen/fclose/fwrite/fread man pages.
4784 ----------------------------------------------------------*/
4785 JNIEXPORT void JNICALL RXTXPort(setInputBufferSize)(JNIEnv *env,
4786 jobject jobj, jint size )
4787 {
4788 report( "setInputBufferSize is not implemented\n" );
4789 }
4790
4791 /*----------------------------------------------------------
4792 getIputBufferSize
4793
4794 accept:
4795 perform:
4796 return: none
4797 exceptions: none
4798 comments: see fopen/fclose/fwrite/fread man pages.
4799 ----------------------------------------------------------*/
4800 JNIEXPORT jint JNICALL RXTXPort(getInputBufferSize)(JNIEnv *env,
4801 jobject jobj)
4802 {
4803 report( "getInputBufferSize is not implemented\n" );
4804 return(1);
4805 }
4806
4807 /*----------------------------------------------------------
4808 setOutputBufferSize
4809
4810 accept:
4811 perform:
4812 return: none
4813 exceptions: none
4814 comments: see fopen/fclose/fwrite/fread man pages.
4815 ----------------------------------------------------------*/
4816 JNIEXPORT void JNICALL RXTXPort(setOutputBufferSize)(JNIEnv *env,
4817 jobject jobj, jint size )
4818 {
4819 report( "setOutputBufferSize is not implemented\n" );
4820 }
4821
4822 /*----------------------------------------------------------
4823 getOutputBufferSize
4824
4825 accept:
4826 perform:
4827 return: none
4828 exceptions: none
4829 comments: see fopen/fclose/fwrite/fread man pages.
4830 ----------------------------------------------------------*/
4831 JNIEXPORT jint JNICALL RXTXPort(getOutputBufferSize)(JNIEnv *env,
4832 jobject jobj)
4833 {
4834 report( "getOutputBufferSize is not implemented\n" );
4835 return(1);
4836 }
4837
4838 /*----------------------------------------------------------
4839 interruptEventLoop
4840
4841 accept: nothing
4842 perform: increment eventloop_interrupted
4843 return: nothing
4844 exceptions: none
4845 comments: all eventloops in this PID will check if their thread
4846 is interrupted. When all the interrupted threads exit
4847 they will decrement the var leaving it 0.
4848 the remaining threads will continue.
4849 ----------------------------------------------------------*/
4850 JNIEXPORT void JNICALL RXTXPort(interruptEventLoop)(JNIEnv *env,
4851 jobject jobj)
4852 {
4853 struct event_info_struct *index = master_index;
4854 int fd = get_java_var( env, jobj, "fd", "I" );
4855 int searching = 1;
4856
4857
4858 while( searching )
4859 {
4860 index = master_index;
4861 if( index )
4862 {
4863 while( index->fd != fd &&
4864 index->next ) index = index->next;
4865 if ( index->fd == fd ) searching = 0;
4866 }
4867 else
4868 report("x");
4869 if( searching )
4870 {
4871 report("@");
4872 usleep(1000);
4873 }
4874 }
4875 index->eventloop_interrupted = 1;
4876 /*
4877 Many OS's need a thread running to determine if output buffer is
4878 empty. For Linux and Win32 it is not needed. So closing is used to
4879 shut down the thread in the write order on OS's that don't have
4880 kernel support for output buffer empty.
4881
4882 In rxtx TIOCSERGETLSR is defined for win32 and Linux
4883 */
4884 #ifdef TIOCSERGETLSR
4885 index->closing=1;
4886 #endif /* TIOCSERGETLSR */
4887 #ifdef WIN32
4888 termios_interrupt_event_loop( index->fd, 1 );
4889 #endif /* WIN32 */
4890 #if !defined(TIOCSERGETLSR) && !defined(WIN32)
4891 /* make sure that the drainloop unblocks from tcdrain */
4892 pthread_kill(index->drain_tid, SIGABRT);
4893 /* TODO use wait/join/SIGCHLD/?? instead of sleep? */
4894 usleep(50 * 1000);
4895 /*
4896 Under normal conditions, SIGABRT will unblock tcdrain. However
4897 a non-responding USB device combined with an unclean driver
4898 may still block. This is very ugly because it may block the call
4899 to close indefinetly.
4900 */
4901 if (index->closing != 1) {
4902 /* good bye tcdrain, and thanks for all the fish */
4903 report("interruptEventLoop: canceling blocked drain thread\n");
4904 pthread_cancel(index->drain_tid);
4905 index->closing = 1;
4906 }
4907 #endif
4908 report("interruptEventLoop: interrupted\n");
4909 }
4910
4911 /*----------------------------------------------------------
4912 is_interrupted
4913
4914 accept: event_info_struct
4915 perform: see if the port is being closed.
4916 return: a positive value if the port is being closed.
4917 exceptions: none
4918 comments:
4919 ----------------------------------------------------------*/
4920 jboolean is_interrupted( struct event_info_struct *eis )
4921 {
4922 int result;
4923 JNIEnv *env = eis->env;
4924
4925 ENTER( "is_interrupted" );
4926 (*env)->ExceptionClear(env);
4927 result = (*env)->CallBooleanMethod( env, *eis->jobj,
4928 eis->checkMonitorThread );
4929 #ifdef DEBUG
4930 if((*env)->ExceptionOccurred(env)) {
4931 report ( "is_interrupted: an error occured calling sendEvent()\n" );
4932 (*env)->ExceptionDescribe(env);
4933 (*env)->ExceptionClear(env);
4934 }
4935 #endif /* DEBUG */
4936 LEAVE( "RXTXCommDriver:is_interrupted" );
4937 return(result);
4938 }
4939
4940 /*----------------------------------------------------------
4941 nativeSetEventFlag
4942
4943 accept: fd for finding the struct, event to flag, flag.
4944 perform: toggle the flag
4945 return: none
4946 exceptions: none
4947 comments: all the logic used to be done in Java but its too noisy
4948 ----------------------------------------------------------*/
4949 JNIEXPORT void JNICALL RXTXPort(nativeSetEventFlag)( JNIEnv *env,
4950 jobject jobj,
4951 jint fd,
4952 jint event,
4953 jboolean flag )
4954 {
4955 struct event_info_struct *index = master_index;
4956
4957 if( !index )
4958 {
4959 report_error("nativeSetEventFlag !index\n");
4960 return;
4961 }
4962 while( index->fd != fd && index->next )
4963 {
4964 index = index->next;
4965 }
4966 if( index->fd != fd )
4967 {
4968 report_error("nativeSetEventFlag !fd\n");
4969 return;
4970 }
4971 index->eventflags[event] = (int) flag;
4972 #ifdef WIN32
4973 termios_setflags( fd, index->eventflags );
4974 #endif /* win32 */
4975
4976 }
4977
4978 /*----------------------------------------------------------
4979 send_event
4980
4981 accept: event_info_structure, event type and true/false
4982 perform: if state is > 0 send a JNI_TRUE event otherwise send JNI_FALSE
4983 return: a positive value if the port is being closed.
4984 exceptions: none
4985 comments:
4986 ----------------------------------------------------------*/
4987 int send_event( struct event_info_struct *eis, jint type, int flag )
4988 {
4989 int result;
4990 JNIEnv *env;
4991 if( eis ) env = eis->env;
4992 else return(-1);
4993
4994 ENTER( "send_event" );
4995 if( !eis || eis->eventloop_interrupted > 1 )
4996 {
4997 report("event loop interrupted\n");
4998 return JNI_TRUE;
4999 }
5000 report_verbose("send_event: !eventloop_interupted\n");
5001 if(eis->jclazz == NULL) return JNI_TRUE;
5002 report_verbose("send_event: jclazz\n");
5003
5004 (*env)->ExceptionClear(env);
5005
5006 report_verbose("send_event: calling\n");
5007 result = (*env)->CallBooleanMethod( env, *eis->jobj, eis->send_event,
5008 type, flag > 0 ? JNI_TRUE : JNI_FALSE );
5009 report_verbose("send_event: called\n");
5010
5011 #ifdef asdf
5012 if(!eis || (*eis->env)->ExceptionOccurred(eis->env)) {
5013 report ( "send_event: an error occured calling sendEvent()\n" );
5014 (*eis->env)->ExceptionDescribe(eis->env);
5015 (*eis->env)->ExceptionClear(eis->env);
5016 }
5017 #endif /* asdf */
5018 /* report("e"); */
5019 LEAVE( "send_event" );
5020 return(result);
5021 }
5022
5023 /*----------------------------------------------------------
5024 get_java_var
5025
5026 accept: env (keyhole to java)
5027 jobj (java RXTXPort object)
5028 return: the fd field from the java object
5029 exceptions: none
5030 comments:
5031 ----------------------------------------------------------*/
5032 size_t get_java_var( JNIEnv *env, jobject jobj, char *id, char *type )
5033 {
5034 int result = 0;
5035 jclass jclazz = (*env)->GetObjectClass( env, jobj );
5036 jfieldID jfd = (*env)->GetFieldID( env, jclazz, id, type );
5037
5038 /*
5039 ENTER( "get_java_var" );
5040 */
5041 if( !jfd ) {
5042 (*env)->ExceptionDescribe( env );
5043 (*env)->ExceptionClear( env );
5044 (*env)->DeleteLocalRef( env, jclazz );
5045 LEAVE( "get_java_var" );
5046 return result;
5047 }
5048 result = (int)( (*env)->GetIntField( env, jobj, jfd ) );
5049 /* ct7 & gel * Added DeleteLocalRef */
5050 (*env)->DeleteLocalRef( env, jclazz );
5051 if(!strncmp( "fd",id,2) && result == 0)
5052 report_error( "get_java_var: invalid file descriptor\n" );
5053 /*
5054 LEAVE( "get_java_var" );
5055 */
5056 return result;
5057 }
5058
5059 /*----------------------------------------------------------
5060 throw_java_exception
5061
5062 accept: env (keyhole to java)
5063 *exc (exception class name)
5064 *foo (function name)
5065 *msg (error message)
5066 perform: Throw a new java exception
5067 return: none
5068 exceptions: haha!
5069 comments:
5070 ----------------------------------------------------------*/
5071 void throw_java_exception( JNIEnv *env, char *exc, char *foo, char *msg )
5072 {
5073 char buf[ 60 ];
5074 jclass clazz = (*env)->FindClass( env, exc );
5075 ENTER( "throw_java_exception" );
5076 if( !clazz ) {
5077 (*env)->ExceptionDescribe( env );
5078 (*env)->ExceptionClear( env );
5079 LEAVE( "throw_java_exception" );
5080 return;
5081 }
5082 #if defined(_GNU_SOURCE)
5083 snprintf( buf, 60, "%s in %s", msg, foo );
5084 #else
5085 sprintf( buf,"%s in %s", msg, foo );
5086 #endif /* _GNU_SOURCE */
5087 (*env)->ThrowNew( env, clazz, buf );
5088 /* ct7 * Added DeleteLocalRef */
5089 (*env)->DeleteLocalRef( env, clazz );
5090 LEAVE( "throw_java_exception" );
5091 }
5092
5093 /*----------------------------------------------------------
5094 report_warning
5095
5096 accept: string to send to report as an message
5097 perform: send the string to stderr or however it needs to be reported.
5098 return: none
5099 exceptions: none
5100 comments:
5101 ----------------------------------------------------------*/
5102 void report_warning(const char *msg)
5103 {
5104 #ifndef DEBUG_MW
5105 fprintf(stderr, "%s", msg);
5106 #else
5107 mexWarnMsgTxt( (const char *) msg );
5108 #endif /* DEBUG_MW */
5109 }
5110
5111 /*----------------------------------------------------------
5112 report_verbose
5113
5114 accept: string to send to report as an verbose message
5115 perform: send the string to stderr or however it needs to be reported.
5116 return: none
5117 exceptions: none
5118 comments:
5119 ----------------------------------------------------------*/
5120 void report_verbose(const char *msg)
5121 {
5122 #ifdef DEBUG_VERBOSE
5123 #ifdef DEBUG_MW
5124 mexErrMsgTxt( msg );
5125 #else
5126 fprintf(stderr, "%s", msg);
5127 #endif /* DEBUG_MW */
5128 #endif /* DEBUG_VERBOSE */
5129 }
5130 /*----------------------------------------------------------
5131 report_error
5132
5133 accept: string to send to report as an error
5134 perform: send the string to stderr or however it needs to be reported.
5135 return: none
5136 exceptions: none
5137 comments:
5138 ----------------------------------------------------------*/
5139 void report_error(const char *msg)
5140 {
5141 #ifndef DEBUG_MW
5142 fprintf(stderr, "%s", msg);
5143 #else
5144 mexWarnMsgTxt( msg );
5145 #endif /* DEBUG_MW */
5146 }
5147
5148 /*----------------------------------------------------------
5149 report
5150
5151 accept: string to send to stderr
5152 perform: if DEBUG is defined send the string to stderr.
5153 return: none
5154 exceptions: none
5155 comments:
5156 ----------------------------------------------------------*/
5157 void report(const char *msg)
5158 {
5159 #ifdef DEBUG
5160 # ifndef DEBUG_MW
5161 fprintf(stderr, "%s", msg);
5162 # else
5163 mexPrintf( msg );
5164 # endif /* DEBUG_MW */
5165 #endif /* DEBUG */
5166 }
5167
5168 #ifndef WIN32
5169 #ifdef LFS
5170 /*----------------------------------------------------------
5171 lfs_lock
5172
5173 accept: The name of the device to try to lock
5174 perform: Create a lock file if there is not one already using a
5175 lock file server.
5176 return: 1 on failure 0 on success
5177 exceptions: none
5178 comments:
5179
5180 ----------------------------------------------------------*/
5181 int lfs_lock( const char *filename, int pid )
5182 {
5183 int s;
5184 int ret;
5185 int size = 1024;
5186 char *buffer = malloc(size);
5187 struct sockaddr_in addr;
5188
5189 if ( !( s = socket( AF_INET, SOCK_STREAM, 0 ) ) > 0 )
5190 return 1;
5191 addr.sin_family = AF_INET;
5192 addr.sin_port = htons( 50001 );
5193 addr.sin_addr.s_addr = inet_addr( "127.0.0.1" );
5194
5195 if ( !connect( s, ( struct sockaddr * ) &addr, sizeof( addr ) ) == 0 )
5196 return 1;
5197 ret=recv( s, buffer, size, 0 );
5198 sprintf( buffer, "lock %s %i\n", filename, pid );
5199 /* printf( "%s", buffer ); */
5200 send( s, buffer, strlen(buffer), 0 );
5201 ret=recv( s, buffer, size, 0 );
5202 if ( ret > 0 )
5203 {
5204 buffer[ret] = '\0';
5205 /* printf( "Message recieved: %s", buffer ); */
5206 }
5207 send( s, "quit\n", strlen( "quit\n" ), 0 );
5208 close(s);
5209 /* printf("%s\n", buffer); */
5210 if( buffer[0] == '2' ) return 0;
5211 return 1;
5212 }
5213
5214 /*----------------------------------------------------------
5215 lfs_unlock
5216
5217 accept: The name of the device to try to unlock
5218 perform: Remove a lock file if there is one using a
5219 lock file server.
5220 return: 1 on failure 0 on success
5221 exceptions: none
5222 comments:
5223
5224 ----------------------------------------------------------*/
5225 int lfs_unlock( const char *filename, int pid )
5226 {
5227 int s;
5228 int ret;
5229 int size = 1024;
5230 char *buffer = malloc(size);
5231 struct sockaddr_in addr;
5232
5233 if ( !( s = socket( AF_INET, SOCK_STREAM, 0 ) ) > 0 )
5234 return 1;
5235 addr.sin_family = AF_INET;
5236 addr.sin_port = htons( 50001 );
5237 addr.sin_addr.s_addr = inet_addr( "127.0.0.1" );
5238
5239 if ( !connect( s, ( struct sockaddr * ) &addr, sizeof( addr ) ) == 0 )
5240 return 1;
5241 sprintf( buffer, "unlock %s %i\n", filename, pid );
5242 /* printf( "%s", buffer ); */
5243 send( s, buffer, strlen(buffer), 0 );
5244 ret = recv( s, buffer, size, 0 );
5245 if ( ret > 0 )
5246 {
5247 buffer[ret] = '\0';
5248 /* printf( "Message recieved: %s", buffer ); */
5249 }
5250 send( s, "quit\n", strlen( "quit\n" ), 0 );
5251 close(s);
5252 if( buffer[0] == '2' ) return 0;
5253 return 1;
5254 }
5255 #endif /* LFS */
5256
5257 /*----------------------------------------------------------
5258 lib_lock_dev_unlock
5259
5260 accept: The name of the device to try to unlock
5261 perform: Remove a lock file if there is one using a
5262 lock file server.
5263 return: 1 on failure 0 on success
5264 exceptions: none
5265 comments: This is for use with liblockdev which comes with Linux
5266 distros. I suspect it will be problematic with embeded
5267 Linux. taj
5268
5269 ----------------------------------------------------------*/
5270 #ifdef LIBLOCKDEV
5271 int lib_lock_dev_unlock( const char *filename, int pid )
5272 {
5273 if( dev_unlock( filename, pid ) )
5274 {
5275 report("fhs_unlock: Unable to remove LockFile\n");
5276 return(1);
5277 }
5278 return(0);
5279 }
5280 #endif /* LIBLOCKDEV */
5281
5282 /*----------------------------------------------------------
5283 lib_lock_dev_lock
5284
5285 accept: The name of the device to try to lock
5286 termios struct
5287 perform: Create a lock file if there is not one already.
5288 return: 1 on failure 0 on success
5289 exceptions: none
5290 comments: This is for use with liblockdev which comes with Linux
5291 distros. I suspect it will be problematic with embeded
5292 Linux. taj
5293
5294 One could load the library here rather than link it and
5295 always try to use this.
5296
5297 ----------------------------------------------------------*/
5298 #ifdef LIBLOCKDEV
5299 int lib_lock_dev_lock( const char *filename, int pid )
5300 {
5301 char message[80];
5302 printf("LOCKING %s\n", filename);
5303 if ( dev_testlock( filename ) )
5304 {
5305 report( "fhs_lock() lockstatus fail\n" );
5306 return 1;
5307 }
5308 if ( dev_lock( filename ) )
5309 {
5310 snprintf( message, 79,
5311 "RXTX fhs_lock() Error: creating lock file for: %s: %s\n",
5312 filename, strerror(errno) );
5313 report_error( message );
5314 return 1;
5315 }
5316 return( 0 );
5317 }
5318 #endif /* LIBLOCKDEV */
5319
5320 /*----------------------------------------------------------
5321 fhs_lock
5322
5323 accept: The name of the device to try to lock
5324 termios struct
5325 perform: Create a lock file if there is not one already.
5326 return: 1 on failure 0 on success
5327 exceptions: none
5328 comments: This is for linux and freebsd only currently. I see SVR4 does
5329 this differently and there are other proposed changes to the
5330 Filesystem Hierachy Standard
5331
5332 more reading:
5333
5334 ----------------------------------------------------------*/
5335 int fhs_lock( const char *filename, int pid )
5336 {
5337 /*
5338 * There is a zoo of lockdir possibilities
5339 * Its possible to check for stale processes with most of them.
5340 * for now we will just check for the lockfile on most
5341 * Problem lockfiles will be dealt with. Some may not even be in use.
5342 *
5343 */
5344 int fd,j;
5345 char lockinfo[12], message[80];
5346 char file[80], *p;
5347
5348 j = strlen( filename );
5349 p = ( char * ) filename + j;
5350 /* FIXME need to handle subdirectories /dev/cua/...
5351 SCO Unix use lowercase all the time
5352 taj
5353 */
5354 while( *( p - 1 ) != '/' && j-- != 1 )
5355 {
5356 #if defined ( __unixware__ )
5357 *p = tolower( *p );
5358 #endif /* __unixware__ */
5359 p--;
5360 }
5361 sprintf( file, "%s/LCK..%s", LOCKDIR, p );
5362 if ( check_lock_status( filename ) )
5363 {
5364 report( "fhs_lock() lockstatus fail\n" );
5365 return 1;
5366 }
5367 fd = open( file, O_CREAT | O_WRONLY | O_EXCL, 0444 );
5368 if( fd < 0 )
5369 {
5370 snprintf( message, 79,
5371 "RXTX fhs_lock() Error: creating lock file: %s: %s\n",
5372 file, strerror(errno) );
5373 report_error( message );
5374 return 1;
5375 }
5376 sprintf( lockinfo, "%10d\n",(int) getpid() );
5377 sprintf( message, "fhs_lock: creating lockfile: %s\n", lockinfo );
5378 report( message );
5379 write( fd, lockinfo, 11 );
5380 close( fd );
5381 return 0;
5382 }
5383
5384 /*----------------------------------------------------------
5385 uucp_lock
5386
5387 accept: char * filename. Device to be locked
5388 perform: Try to get a uucp_lock
5389 return: int 0 on success
5390 exceptions: none
5391 comments:
5392 The File System Hierarchy Standard
5393 http://www.pathname.com/fhs/
5394
5395 UUCP Lock Files
5396 http://docs.freebsd.org/info/uucp/uucp.info.UUCP_Lock_Files.html
5397
5398 FSSTND
5399 ftp://tsx-11.mit.edu/pub/linux/docs/linux-standards/fsstnd/
5400
5401 Proposed Changes to the File System Hierarchy Standard
5402 ftp://scicom.alphacdc.com/pub/linux/devlock-0.X.tgz
5403
5404 "UNIX Network Programming", W. Richard Stevens,
5405 Prentice-Hall, 1990, pages 96-101.
5406
5407 There is much to do here.
5408
5409 1) UUCP style locks (done)
5410 /var/spool/uucp
5411 2) SVR4 locks
5412 /var/spool/locks
5413 3) FSSTND locks (done)
5414 /var/lock
5415 4) handle stale locks (done except kermit locks)
5416 5) handle minicom lockfile contents (FSSTND?)
5417 " 16929 minicom root\n" (done)
5418 6) there are other Lock conventions that use Major and Minor
5419 numbers...
5420 7) Stevens recommends LCK..<pid>
5421
5422 most are caught above. If they turn out to be problematic
5423 rather than an exercise, we will handle them.
5424
5425 ----------------------------------------------------------*/
5426 int uucp_lock( const char *filename, int pid )
5427 {
5428 char lockfilename[80], lockinfo[12], message[80];
5429 char name[80];
5430 int fd;
5431 struct stat buf;
5432
5433 sprintf( message, "uucp_lock( %s );\n", filename );
5434 report( message );
5435
5436 if ( check_lock_status( filename ) )
5437 {
5438 report( "RXTX uucp check_lock_status true\n" );
5439 return 1;
5440 }
5441 if ( stat( LOCKDIR, &buf ) != 0 )
5442 {
5443 report( "RXTX uucp_lock() could not find lock directory.\n" );
5444 return 1;
5445 }
5446 if ( stat( filename, &buf ) != 0 )
5447 {
5448 report( "RXTX uucp_lock() could not find device.\n" );
5449 sprintf( message, "uucp_lock: device was %s\n", name );
5450 report( message );
5451 return 1;
5452 }
5453 sprintf( lockfilename, "%s/LK.%03d.%03d.%03d",
5454 LOCKDIR,
5455 (int) major( buf.st_dev ),
5456 (int) major( buf.st_rdev ),
5457 (int) minor( buf.st_rdev )
5458 );
5459 sprintf( lockinfo, "%10d\n", (int) getpid() );
5460 if ( stat( lockfilename, &buf ) == 0 )
5461 {
5462 sprintf( message, "RXTX uucp_lock() %s is there\n",
5463 lockfilename );
5464 report( message );
5465 report_error( message );
5466 return 1;
5467 }
5468 fd = open( lockfilename, O_CREAT | O_WRONLY | O_EXCL, 0444 );
5469 if( fd < 0 )
5470 {
5471 sprintf( message,
5472 "RXTX uucp_lock() Error: creating lock file: %s\n",
5473 lockfilename );
5474 report_error( message );
5475 return 1;
5476 }
5477 write( fd, lockinfo,11 );
5478 close( fd );
5479 return 0;
5480 }
5481
5482 /*----------------------------------------------------------
5483 check_lock_status
5484
5485 accept: the lock name in question
5486 perform: Make sure everything is sane
5487 return: 0 on success
5488 exceptions: none
5489 comments:
5490 ----------------------------------------------------------*/
5491 int check_lock_status( const char *filename )
5492 {
5493 struct stat buf;
5494 /* First, can we find the directory? */
5495
5496 if ( stat( LOCKDIR, &buf ) != 0 )
5497 {
5498 report( "check_lock_status: could not find lock directory.\n" );
5499 return 1;
5500 }
5501
5502 /* OK. Are we able to write to it? If not lets bail */
5503
5504 if ( check_group_uucp() )
5505 {
5506 report_error( "check_lock_status: No permission to create lock file.\nplease see: How can I use Lock Files with rxtx? in INSTALL\n" );
5507 return(1);
5508 }
5509
5510 /* is the device alread locked */
5511
5512 if ( is_device_locked( filename ) )
5513 {
5514 report( "check_lock_status: device is locked by another application\n" );
5515 return 1;
5516 }
5517 return 0;
5518
5519 }
5520
5521 /*----------------------------------------------------------
5522 fhs_unlock
5523
5524 accept: The name of the device to unlock
5525 perform: delete the lock file
5526 return: none
5527 exceptions: none
5528 comments: This is for linux only currently. I see SVR4 does this
5529 differently and there are other proposed changes to the
5530 Filesystem Hierachy Standard
5531 ----------------------------------------------------------*/
5532 void fhs_unlock( const char *filename, int openpid )
5533 {
5534 char file[80],*p;
5535 int i;
5536
5537 i = strlen( filename );
5538 p = ( char * ) filename + i;
5539 /* FIXME need to handle subdirectories /dev/cua/... */
5540 while( *( p - 1 ) != '/' && i-- != 1 ) p--;
5541 sprintf( file, "%s/LCK..%s", LOCKDIR, p );
5542
5543 if( !check_lock_pid( file, openpid ) )
5544 {
5545 unlink(file);
5546 report("fhs_unlock: Removing LockFile\n");
5547 }
5548 else
5549 {
5550 report("fhs_unlock: Unable to remove LockFile\n");
5551 }
5552 }
5553
5554 /*----------------------------------------------------------
5555 uucp_unlock
5556
5557 accept: char *filename the device that is locked
5558 perform: remove the uucp lockfile if it exists
5559 return: none
5560 exceptions: none
5561 comments: http://docs.freebsd.org/info/uucp/uucp.info.UUCP_Lock_Files.html
5562 ----------------------------------------------------------*/
5563 void uucp_unlock( const char *filename, int openpid )
5564 {
5565 struct stat buf;
5566 char file[80], message[80];
5567 /* FIXME */
5568
5569 sprintf( message, "uucp_unlock( %s );\n", filename );
5570 report( message );
5571
5572 if ( stat( filename, &buf ) != 0 )
5573 {
5574 /* hmm the file is not there? */
5575 report( "uucp_unlock() no such device\n" );
5576 return;
5577 }
5578 sprintf( file, LOCKDIR"/LK.%03d.%03d.%03d",
5579 (int) major( buf.st_dev ),
5580 (int) major( buf.st_rdev ),
5581 (int) minor( buf.st_rdev )
5582 );
5583 if ( stat( file, &buf ) != 0 )
5584 {
5585 /* hmm the file is not there? */
5586 report( "uucp_unlock no such lockfile\n" );
5587 return;
5588 }
5589 if( !check_lock_pid( file, openpid ) )
5590 {
5591 sprintf( message, "uucp_unlock: unlinking %s\n", file );
5592 report( message );
5593 unlink(file);
5594 }
5595 else
5596 {
5597 sprintf( message, "uucp_unlock: unlinking failed %s\n", file );
5598 report( message );
5599 }
5600 }
5601
5602 /*----------------------------------------------------------
5603 check_lock_pid
5604
5605 accept: the name of the lockfile
5606 perform: make sure the lock file is ours.
5607 return: 0 on success
5608 exceptions: none
5609 comments:
5610 ----------------------------------------------------------*/
5611 int check_lock_pid( const char *file, int openpid )
5612 {
5613 int fd, lockpid;
5614 char pid_buffer[12];
5615 char message[80];
5616
5617 fd=open( file, O_RDONLY );
5618 if ( fd < 0 )
5619 {
5620 return( 1 );
5621 }
5622 if ( read( fd, pid_buffer, 11 ) < 0 )
5623 {
5624 close( fd );
5625 return( 1 );
5626 }
5627 close( fd );
5628 pid_buffer[11] = '\0';
5629 lockpid = atol( pid_buffer );
5630 /* Native threads JVM's have multiple pids */
5631 if ( lockpid != getpid() && lockpid != getppid() && lockpid != openpid )
5632 {
5633 sprintf(message, "check_lock_pid: lock = %s pid = %i gpid=%i openpid=%i\n",
5634 pid_buffer, (int) getpid(), (int) getppid(), openpid );
5635 report( message );
5636 return( 1 );
5637 }
5638 return( 0 );
5639 }
5640
5641 /*----------------------------------------------------------
5642 check_group_uucp
5643
5644 accept: none
5645 perform: check if the user is root or in group uucp
5646 return: 0 on success
5647 exceptions: none
5648 comments:
5649 This checks if the effective user is in group uucp so we can
5650 create lock files. If not we give them a warning and bail.
5651 If its root we just skip the test.
5652
5653 if someone really wants to override this they can use the USER_LOCK_DIRECTORY --not recommended.
5654
5655 In a recent change RedHat 7.2 decided to use group lock.
5656 In order to get around this we just check the group id
5657 of the lock directory.
5658
5659 * Modified to support Debian *
5660
5661 The problem was that checking the ownership of the lock file
5662 dir is not enough, in the sense that even if the current user
5663 is not in the group of the lock directory if the lock
5664 directory has 777 permissions the lock file can be anyway
5665 created. My solution is simply to try to create a tmp file
5666 there and if it works then we can go on. Here is my code that
5667 I tried and seems to work.
5668
5669 Villa Valerio <[email protected]>
5670 ----------------------------------------------------------*/
5671 int check_group_uucp()
5672 {
5673 #ifndef USER_LOCK_DIRECTORY
5674 FILE *testLockFile ;
5675 char testLockFileDirName[] = LOCKDIR;
5676 char testLockFileName[] = "tmpXXXXXX";
5677 char *testLockAbsFileName;
5678
5679 testLockAbsFileName = calloc(strlen(testLockFileDirName)
5680 + strlen(testLockFileName) + 2, sizeof(char));
5681 if ( NULL == testLockAbsFileName )
5682 {
5683 report_error("check_group_uucp(): Insufficient memory");
5684 return 1;
5685 }
5686 strcat(testLockAbsFileName, testLockFileDirName);
5687 strcat(testLockAbsFileName, "/");
5688 strcat(testLockAbsFileName, testLockFileName);
5689 if ( NULL == mktemp(testLockAbsFileName) )
5690 {
5691 free(testLockAbsFileName);
5692 report_error("check_group_uucp(): mktemp malformed string - \
5693 should not happen");
5694
5695 return 1;
5696 }
5697 testLockFile = fopen (testLockAbsFileName, "w+");
5698 if (NULL == testLockFile)
5699 {
5700 report_error("check_group_uucp(): error testing lock file "
5701 "creation Error details:");
5702 report_error(strerror(errno));
5703 free(testLockAbsFileName);
5704 return 1;
5705 }
5706
5707 fclose (testLockFile);
5708 unlink (testLockAbsFileName);
5709 free(testLockAbsFileName);
5710
5711 #endif /* USER_LOCK_DIRECTORY */
5712 return 0;
5713
5714 #ifdef USE_OLD_CHECK_GROUP_UUCP
5715 int check_group_uucp()
5716 {
5717 #ifndef USER_LOCK_DIRECTORY
5718 int group_count;
5719 struct passwd *user = getpwuid( geteuid() );
5720 struct stat buf;
5721 char msg[80];
5722 gid_t list[ NGROUPS_MAX ];
5723
5724 if( stat( LOCKDIR, &buf) )
5725 {
5726 sprintf( msg, "check_group_uucp: Can not find Lock Directory: %s\n", LOCKDIR );
5727 report_error( msg );
5728 return( 1 );
5729 }
5730 group_count = getgroups( NGROUPS_MAX, list );
5731 list[ group_count ] = geteuid();
5732
5733 /* JJO changes start */
5734 if( user == NULL )
5735 {
5736 report_error( "Not able to get user groups.\n" );
5737 return 1;
5738 } else
5739 /* JJO changes stop */
5740
5741
5742 if( user->pw_gid )
5743 {
5744 while( group_count >= 0 && buf.st_gid != list[ group_count ] )
5745 {
5746 group_count--;
5747 }
5748 if( buf.st_gid == list[ group_count ] )
5749 return 0;
5750 sprintf( msg, "%i %i\n", buf.st_gid, list[ group_count ] );
5751 report_error( msg );
5752 report_error( UUCP_ERROR );
5753 return 1;
5754 }
5755 return 0;
5756 /*
5757 if( strcmp( user->pw_name, "root" ) )
5758 {
5759 while( *g->gr_mem )
5760 {
5761 if( !strcmp( *g->gr_mem, user->pw_name ) )
5762 {
5763 break;
5764 }
5765 (void) *g->gr_mem++;
5766 }
5767 if( !*g->gr_mem )
5768 {
5769 report( UUCP_ERROR );
5770 return 1;
5771 }
5772 }
5773 */
5774 #endif /* USER_LOCK_DIRECTORY */
5775 return 0;
5776 #endif /* USE_OLD_CHECK_GROUP_UUCP */
5777 }
5778
5779 /*----------------------------------------------------------
5780 The following should be able to follow symbolic links. I think the stat
5781 method used below will work on more systems. This was found while looking
5782 for information.
5783
5784 * realpath() doesn't exist on all of the systems my code has to run
5785 on (HP-UX 9.x, specifically)
5786 ----------------------------------------------------------
5787 int different_from_LOCKDIR(const char* ld)
5788 {
5789 char real_ld[MAXPATHLEN];
5790 char real_LOCKDIR[MAXPATHLEN];
5791 if (strncmp(ld, LOCKDIR, strlen(ld)) == 0)
5792 return 0;
5793 if (realpath(ld, real_ld) == NULL)
5794 return 1;
5795 if (realpath(LOCKDIR, real_LOCKDIR) == NULL)
5796 return 1;
5797 if (strncmp(real_ld, real_LOCKDIR, strlen(real_ld)) == 0)
5798 return 0;
5799 else
5800 return 1;
5801 }
5802 */
5803
5804 /*----------------------------------------------------------
5805 is_device_locked
5806
5807 accept: char * filename. The device in question including the path.
5808 perform: see if one of the many possible lock files is aready there
5809 if there is a stale lock, remove it.
5810 return: 1 if the device is locked or somethings wrong.
5811 0 if its possible to create our own lock file.
5812 exceptions: none
5813 comments: check if the device is already locked
5814 ----------------------------------------------------------*/
5815 int is_device_locked( const char *port_filename )
5816 {
5817 const char *lockdirs[] = { "/etc/locks", "/usr/spool/kermit",
5818 "/usr/spool/locks", "/usr/spool/uucp", "/usr/spool/uucp/",
5819 "/usr/spool/uucp/LCK", "/var/lock", "/var/lock/modem",
5820 "/var/spool/lock", "/var/spool/locks", "/var/spool/uucp",
5821 LOCKDIR, NULL
5822 };
5823 const char *lockprefixes[] = { "LCK..", "lk..", "LK.", NULL };
5824 char *p, *file, pid_buffer[20], *message;
5825 int i = 0, j, k, fd , pid;
5826 struct stat buf, buf2, lockbuf;
5827
5828 j = strlen( port_filename );
5829 p = ( char * ) port_filename+j;
5830 while( *( p-1 ) != '/' && j-- !=1 ) p--;
5831
5832 stat(LOCKDIR, &lockbuf);
5833
5834 while( lockdirs[i] )
5835 {
5836 /*
5837 Look for lockfiles in all known places other than the
5838 defined lock directory for this system
5839 report any unexpected lockfiles.
5840
5841 Is the suspect lockdir there?
5842 if it is there is it not the expected lock dir?
5843 */
5844 if( !stat( lockdirs[i], &buf2 ) &&
5845 buf2.st_ino != lockbuf.st_ino &&
5846 strncmp( lockdirs[i], LOCKDIR, strlen( lockdirs[i] ) ) )
5847 {
5848 j = strlen( port_filename );
5849 p = ( char * ) port_filename + j;
5850 /*
5851 SCO Unix use lowercase all the time
5852 taj
5853 */
5854 while( *( p - 1 ) != '/' && j-- != 1 )
5855 {
5856 #if defined ( __unixware__ )
5857 *p = tolower( *p );
5858 #endif /* __unixware__ */
5859 p--;
5860 }
5861 k=0;
5862 while ( lockprefixes[k] )
5863 {
5864 /* FHS style */
5865 asprintf( &file, "%s/%s%s", lockdirs[i],
5866 lockprefixes[k], p );
5867 if( stat( file, &buf ) == 0 )
5868 {
5869 asprintf( &message, UNEXPECTED_LOCK_FILE,
5870 file );
5871 report_warning( message );
5872 free( message );
5873 free( file );
5874 return 1;
5875 }
5876 free( file );
5877
5878 /* UUCP style */
5879 stat(port_filename , &buf );
5880 asprintf( &file, "%s/%s%03d.%03d.%03d",
5881 lockdirs[i],
5882 lockprefixes[k],
5883 (int) major( buf.st_dev ),
5884 (int) major( buf.st_rdev ),
5885 (int) minor( buf.st_rdev )
5886 );
5887 if( stat( file, &buf ) == 0 )
5888 {
5889 asprintf( &message, UNEXPECTED_LOCK_FILE,
5890 file );
5891 report_warning( message );
5892 free( message );
5893 free( file );
5894 return 1;
5895 }
5896 free( file );
5897 k++;
5898 }
5899 }
5900 i++;
5901 }
5902
5903 /*
5904 OK. We think there are no unexpect lock files for this device
5905 Lets see if there any stale lock files that need to be
5906 removed.
5907 */
5908
5909 #ifdef FHS
5910 /* FHS standard locks */
5911 i = strlen( port_filename );
5912 p = ( char * ) port_filename + i;
5913 while( *(p-1) != '/' && i-- != 1)
5914 {
5915 #if defined ( __unixware__ )
5916 *p = tolower( *p );
5917 #endif /* __unixware__ */
5918 p--;
5919 }
5920 asprintf( &file, "%s/%s%s", LOCKDIR, LOCKFILEPREFIX, p );
5921 #else
5922 /* UUCP standard locks */
5923 if ( stat( port_filename, &buf ) != 0 )
5924 {
5925 report( "RXTX is_device_locked() could not find device.\n" );
5926 return 1;
5927 }
5928 asprintf( &file, "%s/LK.%03d.%03d.%03d",
5929 LOCKDIR,
5930 (int) major( buf.st_dev ),
5931 (int) major( buf.st_rdev ),
5932 (int) minor( buf.st_rdev )
5933 );
5934
5935 #endif /* FHS */
5936
5937 if( stat( file, &buf ) == 0 )
5938 {
5939
5940 /* check if its a stale lock */
5941 fd=open( file, O_RDONLY );
5942 read( fd, pid_buffer, 11 );
5943 /* FIXME null terminiate pid_buffer? need to check in Solaris */
5944 close( fd );
5945 sscanf( pid_buffer, "%d", &pid );
5946
5947 if( kill( (pid_t) pid, 0 ) && errno==ESRCH )
5948 {
5949 asprintf( &message,
5950 "RXTX Warning: Removing stale lock file. %s\n",
5951 file );
5952 report_warning( message );
5953 free( message );
5954 if( unlink( file ) != 0 )
5955 {
5956 asprintf( &message, "RXTX Error: Unable to \
5957 remove stale lock file: %s\n",
5958 file
5959 );
5960 report_warning( message );
5961 free( message );
5962 free( file );
5963 return 1;
5964 }
5965 }
5966 }
5967 free(file);
5968 return 0;
5969 }
5970 #endif /* WIN32 */
5971
5972 /*----------------------------------------------------------
5973 system_does_not_lock
5974
5975 accept: the filename the system thinks should be locked.
5976 perform: avoid trying to create lock files on systems that dont use them
5977 return: 0 for success ;)
5978 exceptions: none
5979 comments: OS's like Win32 may not have lock files.
5980 ----------------------------------------------------------*/
5981 int system_does_not_lock( const char * filename, int pid )
5982 {
5983 return 0;
5984 }
5985
5986 /*----------------------------------------------------------
5987 system_does_not_unlock
5988
5989 accept: the filename the system thinks should be locked.
5990 perform: avoid trying to create lock files on systems that dont use them
5991 return: none
5992 exceptions: none
5993 comments: OS's like Win32 may not have lock files.
5994 ----------------------------------------------------------*/
5995 void system_does_not_unlock( const char * filename, int openpid )
5996 {
5997 return;
5998 }
5999
6000 /*----------------------------------------------------------
6001 dump_termios
6002
6003 accept: string to indicate where this was called.
6004 termios struct
6005 perform: print the termios struct to stderr.
6006 return: none
6007 exceptions: none
6008 comments: used to debug the termios struct.
6009 ----------------------------------------------------------*/
6010 void dump_termios(char *foo,struct termios *ttyset)
6011 {
6012 #ifdef DEBUG
6013 int i;
6014
6015 fprintf(stderr, "%s c_iflag=%#x\n", foo, ttyset->c_iflag);
6016 fprintf(stderr, "%s c_lflag=%#x\n", foo, ttyset->c_lflag);
6017 fprintf(stderr, "%s c_oflag=%#x\n", foo, ttyset->c_oflag);
6018 fprintf(stderr, "%s c_cflag=%#x\n", foo, ttyset->c_cflag);
6019 fprintf(stderr, "%s c_cc[]: ", foo);
6020 for(i=0; i<NCCS; i++)
6021 {
6022 fprintf(stderr,"%d=%x ", i, ttyset->c_cc[i]);
6023 }
6024 fprintf(stderr,"\n" );
6025 #endif /* DEBUG */
6026 }
6027
6028 /*----------------------------------------------------------
6029 get_java_environment
6030
6031 accept: pointer to the virtual machine
6032 flag to know if we are attached
6033 return: pointer to the Java Environment
6034 exceptions: none
6035 comments: see JNI_OnLoad. For getting the JNIEnv in the thread
6036 used to monitor for output buffer empty.
6037 ----------------------------------------------------------*/
6038 JNIEnv *get_java_environment(JavaVM *java_vm, jboolean *was_attached){
6039 void **env = NULL;
6040 jint err_get_env;
6041 if(java_vm == NULL) return (JNIEnv *) *env;
6042 *was_attached = JNI_FALSE;
6043
6044 err_get_env = (*java_vm)->GetEnv(
6045 java_vm,
6046 env,
6047 JNI_VERSION_1_2
6048 );
6049 if(err_get_env == JNI_ERR) return NULL;
6050 if(err_get_env == JNI_EDETACHED){
6051 (*java_vm)->AttachCurrentThread(
6052 java_vm,
6053 env,
6054 (void **) NULL
6055 );
6056 if(*env != NULL) *was_attached = JNI_TRUE;
6057 }else if(err_get_env != JNI_OK) return (JNIEnv *) NULL;
6058 return (JNIEnv *) *env;
6059 }
6060
6061 /*----------------------------------------------------------
6062 JNI_OnLoad
6063
6064 accept: JavaVM pointer to the Vertial Machine
6065 void * reserved ???
6066 return: jint JNI version used.
6067 exceptions: none
6068 comments: http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-14.html
6069 http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html
6070 grab the Java VM pointer when the library loads for later use
6071 in the drain thread. Also lets Java know we are using the
6072 1.4 API so we can get pointers later.
6073 ----------------------------------------------------------*/
6074 JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *java_vm, void *reserved)
6075 {
6076 javaVM = java_vm;
6077 report_verbose("JNI_OnLoad called.\n");
6078 return JNI_VERSION_1_2; /* JNI API used */
6079 }
6080
6081 /*----------------------------------------------------------
6082 JNI_OnUnload
6083
6084 accept: JavaVM pointer to the Vertial Machine
6085 void * reserved ???
6086 return: none
6087 exceptions: none
6088 comments: http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-14.html
6089 http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html
6090 final library cleanup here.
6091 ----------------------------------------------------------*/
6092 JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
6093 {
6094 /* never called it appears */
6095 printf("Experimental: JNI_OnUnload called.\n");
6096 }
6097
6098 #ifdef asdf
6099 /*----------------------------------------------------------
6100 printj
6101
6102 accept: like vwprintf()
6103 return: number of jchars written or -1
6104 exceptions: none
6105 comments: prints data using System.out.print()
6106 ----------------------------------------------------------*/
6107 int printj(JNIEnv *env, wchar_t *fmt, ...)
6108 {
6109 wchar_t buf[1024];
6110 int retval;
6111 jstring jsBuf;
6112 jclass clsSystem, clsOut;
6113 jfieldID jfid;
6114 jobject objOut;
6115 jmethodID midPrint;
6116
6117 va_list ap;
6118 va_start(ap, fmt);
6119 retval = _vsnwprintf(buf, 1024, fmt, ap);
6120 va_end(ap);
6121 buf[1023] = '\0';
6122
6123 if((clsSystem = env->FindClass("java/lang/System")) == NULL)
6124 {
6125 IF_DEBUG
6126 (
6127 env->ExceptionDescribe();
6128 )
6129 env->ExceptionClear();
6130 return -1;
6131 }
6132
6133 if( ( jfid = env->GetStaticFieldID(clsSystem,
6134 "out", "Ljava/io/PrintStream;" ) ) == NULL )
6135 {
6136 IF_DEBUG
6137 (
6138 env->ExceptionDescribe();
6139 )
6140 env->ExceptionClear();
6141 env->DeleteLocalRef(clsSystem);
6142 return -1;
6143 }
6144
6145 objOut = env->GetStaticObjectField(clsSystem, jfid);
6146 clsOut = env->GetObjectClass(objOut);
6147
6148 if( ( midPrint = env->GetMethodID(clsOut, "print",
6149 "(Ljava/lang/String;)V" ) ) == NULL )
6150 {
6151 IF_DEBUG
6152 (
6153 env->ExceptionDescribe();
6154 )
6155 env->ExceptionClear();
6156 env->DeleteLocalRef(clsOut);
6157 env->DeleteLocalRef(clsSystem);
6158 return -1;
6159 }
6160
6161 jsBuf = env->NewString(buf, wcslen(buf));
6162
6163 env->CallVoidMethod(objOut, midPrint, jsBuf);
6164
6165 env->DeleteLocalRef(jsBuf);
6166 env->DeleteLocalRef(clsOut);
6167 env->DeleteLocalRef(clsSystem);
6168
6169 return retval;
6170 }
6171 /*
6172 jclass cls = ( *env )->FindClass( env, "System.Thread" );
6173 jmethodID mid = ( *env )->GetStaticMethodID( env, cls, "Sleep", "(I)V" );
6174 (*env)->CallStaticVoidMethod(env, cls, mid, 1);
6175 */
6176 #endif /* asdf */
6177