Debian Codegraph @

src/ParallelImp.c

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 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-2007 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 /*
59 fear he who enter here. It appears that things have changed. An attempt
60 has been made to put things the way the should be.
61
62 It compiles and ParallelBlackBox runs. No further guarantees.
63
64 Well... One.. it will print "Hello World!" on an epson DX 10 printer.
65 you know.. the 10 character per second daisy wheel printer ;)
66
67 - Trent Jarvi
68 */
69
70 #if defined(__MWERKS__)/* dima */
71 #include "LPRPort.h"
72 #else /* dima */
73 #ifndef WIN32
74 # include "config.h"
75 #endif
76 /* work around for libc5 */
77 /*#include <typedefs_md.h>*/
78 #include "gnu_io_LPRPort.h"
79 #endif /* dima */
80 #include <time.h>
81 #include <stdio.h>
82 #include <string.h>
83 #ifndef WIN32
84 # include <unistd.h>
85 # include <sys/ioctl.h>
86 # include <sys/errno.h>
87 # include <sys/param.h>
88 #else
89 # include <errno.h>
90 # include "win32termios.h"
91 #endif
92 #include <sys/types.h>
93 #include <sys/stat.h>
94 #include <stdlib.h>
95
96 #ifdef HAVE_TERMIOS_H
97 # include <termios.h>
98 #endif
99 #ifdef HAVE_SYS_FCNTL_H
100 # include <sys/fcntl.h>
101 #endif
102 #ifdef HAVE_SYS_FILE_H
103 # include <sys/file.h>
104 #endif
105 #ifdef HAVE_SYS_SIGNAL_H
106 # include <sys/signal.h>
107 #endif
108 #ifdef HAVE_SYS_TIME_H
109 # include <sys/time.h>
110 #endif /* HAVE_SYS_TIME_H */
111 #if defined(__linux__)
112 # include <linux/lp.h>
113 #endif
114 #if defined(__FreeBSD__)
115 /* # include <machine/lpt.h> ? is this changed or wrong */
116 # include <dev/ppbus/lpt.h>
117 #endif
118 #ifdef __unixware__
119 # include <sys/filio.h>
120 #endif
121
122 extern int errno;
123
124 #include "ParallelImp.h"
125
126 #define LPRPort(foo) Java_gnu_io_LPRPort_ ## foo
127 /* #define DEBUG */
128
129 /*----------------------------------------------------------
130 LPRPort.getOutputBufferFree
131 accept: none
132 perform:
133 return: number of bytes available in buffer.
134 exceptions: none
135 comments: have not seen how to do this in the kernel yet.
136 ----------------------------------------------------------*/
137 JNIEXPORT jint JNICALL LPRPort(getOutputBufferFree)(JNIEnv *env,
138 jclass jclazz)
139 {
140 printf("getOutputBufferFree is not implemented yet\n");
141
142 return(0);
143
144 }
145 /*----------------------------------------------------------
146 LPRPort.setLPRMode
147 accept: mode
148 perform: set the Printer communication mode
149 LPT_MODE_ANY: pick the best possible mode
150 LPT_MODE_SPP: compatibility mode/unidirectional
151 LPT_MODE_PS2: byte mode/bidirectional
152 LPT_MODE_EPP: extended parallel port
153 LPT_MODE_ECP: enhanced capabilities port
154 LPT_MODE_NIBBLE: Nibble Mode. Bi-directional. HP Bi-tronics.
155 4 bits at a time.
156 return: none
157 exceptions: UnsupportedCommOperationException
158 comments:
159 ----------------------------------------------------------*/
160 JNIEXPORT jboolean JNICALL LPRPort(setLPRMode)(JNIEnv *env,
161 jclass jclazz, jint mode)
162 {
163 switch(mode)
164 {
165 case LPT_MODE_ANY:
166 break;
167 case LPT_MODE_SPP:
168 case LPT_MODE_PS2:
169 case LPT_MODE_EPP:
170 case LPT_MODE_ECP:
171 case LPT_MODE_NIBBLE:
172 default:
173 throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
174 "nativeSetSerialPortParams",
175 "setLPRMode was unable to proced the requested \
176 mode"
177 );
178 }
179 return(JNI_TRUE);
180 }
181
182 #if defined (WIN32)
183
184 #define CTL_CODE( DeviceType, Function, Method, Access ) (((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
185
186 #define FILE_DEVICE_PARALLEL_PORT 0x00000016
187 #define METHOD_BUFFERED 0
188 #define FILE_ANY_ACCESS 0
189
190 #define IOCTL_PAR_QUERY_INFORMATION CTL_CODE(FILE_DEVICE_PARALLEL_PORT,1,METHOD_BUFFERED,FILE_ANY_ACCESS)
191
192 #define PARALLEL_INIT 0x1
193 #define PARALLEL_AUTOFEED 0x2
194 #define PARALLEL_PAPER_EMPTY 0x4
195 #define PARALLEL_OFF_LINE 0x8
196 #define PARALLEL_POWER_OFF 0x10
197 #define PARALLEL_NOT_CONNECTED 0x20
198 #define PARALLEL_BUSY 0x40
199 #define PARALLEL_SELECTED 0x80
200
201 int getWin32ParallelStatusFlags(int fd){
202 int status = 0;
203 DWORD count;
204 if(!DeviceIoControl( (HANDLE)fd, IOCTL_PAR_QUERY_INFORMATION, NULL,0, &status, sizeof(status), &count, 0) && count == 1){
205 YACK();
206 return 0;
207 }
208 #ifdef DEBUG
209 printf("getWin32ParallelStatusFlags: %d\n", status );
210 #endif
211 return status;
212 }
213
214 jboolean getWin32ParallelStatus(int fd, int flag){
215 return( (getWin32ParallelStatusFlags(fd) & flag) ? JNI_TRUE : JNI_FALSE);
216 }
217 #endif
218
219 /*----------------------------------------------------------
220 LPRPort.isPaperOut
221 accept: none
222 perform: check if printer reports paper is out
223 return: Paper Out: JNI_TRUE Not Paper Out: JNI_FALSE
224 exceptions: none
225 comments: LP_NOPA unchanged out-of-paper input, active high
226 ----------------------------------------------------------*/
227 JNIEXPORT jboolean JNICALL LPRPort(isPaperOut)(JNIEnv *env,
228 jobject jobj)
229 {
230
231 int fd = get_java_var( env, jobj,"fd","I" );
232 #if defined (__linux__)
233 int status;
234 ioctl(fd, LPGETSTATUS,&status);
235 return( status & LP_NOPA ? JNI_TRUE : JNI_FALSE );
236 #elif defined (WIN32)
237 return getWin32ParallelStatus( fd, PARALLEL_PAPER_EMPTY);
238 #else
239 /* FIXME?? */
240 printf("ParallelImp.c LPGETSTATUS not defined\n");
241 return(JNI_TRUE);
242 #endif
243 }
244 /*----------------------------------------------------------
245 LPRPort.isPrinterBusy
246 accept: none
247 perform: Check to see if the printer is printing.
248 return: JNI_TRUE if the printer is Busy, JNI_FALSE if its idle
249 exceptions: none
250 comments: LP_BUSY inverted busy input, active high
251 ----------------------------------------------------------*/
252 JNIEXPORT jboolean JNICALL LPRPort(isPrinterBusy)(JNIEnv *env,
253 jobject jobj)
254 {
255 int fd = get_java_var( env, jobj,"fd","I" );
256 int status;
257 #if defined (__linux__)
258 ioctl(fd, LPGETSTATUS, &status);
259 #elif defined (WIN32)
260 return getWin32ParallelStatus( fd, PARALLEL_BUSY);
261 #else
262 /* FIXME?? */
263 printf("ParallelImp.c LPGETSTATUS not defined\n");
264 #endif
265 #if defined(__linux__)
266 return( status & LP_BUSY ? JNI_TRUE : JNI_FALSE );
267 #endif
268 #if defined(__FreeBSD__)
269 return( status & EBUSY ? JNI_TRUE : JNI_FALSE );
270 #endif
271 return(JNI_FALSE);
272 }
273 /*----------------------------------------------------------
274 LPRPort.isPrinterError
275 accept: none
276 perform: check for printer error
277 return: JNI_TRUE if there is an printer error otherwise JNI_FALSE
278 exceptions: none
279 comments: LP_ERR unchanged error input, active low
280 ----------------------------------------------------------*/
281 JNIEXPORT jboolean JNICALL LPRPort(isPrinterError)(JNIEnv *env,
282 jobject jobj)
283 {
284 int fd = get_java_var( env, jobj,"fd","I" );
285 #if defined (__linux__)
286 int status;
287 ioctl(fd, LPGETSTATUS, &status);
288 return( status & LP_ERR ? JNI_TRUE : JNI_FALSE );
289 #elif defined (WIN32)
290 return getWin32ParallelStatus( fd, PARALLEL_PAPER_EMPTY |
291 PARALLEL_OFF_LINE |
292 PARALLEL_POWER_OFF |
293 PARALLEL_NOT_CONNECTED |
294 PARALLEL_BUSY);
295 #else
296 /* FIXME?? */
297 printf("ParallelImp.c LPGETSTATUS not defined\n");
298 return(JNI_FALSE);
299 #endif
300 }
301 /*----------------------------------------------------------
302 LPRPort.isPrinterSelected
303 accept: none
304 perform: check if printer is selected
305 return: JNI_TRUE if printer is selected other wise JNI_FALSE
306 exceptions: none
307 comments: LP_SELEC unchanged selected input, active high
308 ----------------------------------------------------------*/
309 JNIEXPORT jboolean JNICALL LPRPort(isPrinterSelected)(JNIEnv *env,
310 jobject jobj)
311 {
312 int fd = get_java_var( env, jobj,"fd","I" );
313 #if defined (__linux__)
314 int status;
315 ioctl(fd, LPGETSTATUS, &status);
316 return( status & LP_SELEC ? JNI_TRUE : JNI_FALSE );
317 #elif defined (WIN32)
318 return getWin32ParallelStatus( fd, PARALLEL_SELECTED);
319 #else
320 /* FIXME?? */
321 printf("ParallelImp.c LPGETSTATUS not defined\n");
322 return(JNI_FALSE);
323 #endif
324 }
325 /*----------------------------------------------------------
326 LPRPort.isPrinterTimedOut
327 accept: none
328 perform: Not really sure see isPaperOut
329 return: JNI_FALSE if the printer does not return out of paper other
330 wise JNI_TRUE.
331 exceptions: none
332 comments: Is this documented right in the javadocs?
333 not sure this is correct FIXME
334 ----------------------------------------------------------*/
335 JNIEXPORT jboolean JNICALL LPRPort(isPrinterTimedOut)(JNIEnv *env,
336 jobject jobj)
337 {
338 #if defined(__linux__)
339 int fd = get_java_var( env, jobj,"fd","I" );
340 int status;
341 ioctl(fd, LPGETSTATUS, &status);
342 return( status & LP_BUSY ? JNI_TRUE : JNI_FALSE );
343 #endif
344 #if defined(__FreeBSD__)
345 printf("ParallelImp.c LPGETSTATUS not defined\n");
346 /*
347 return( status & EBUSY ? JNI_TRUE : JNI_FALSE );
348 */
349 #endif
350 return( JNI_FALSE );
351 }
352
353
354 /*----------------------------------------------------------
355 LPRPort.Initialize
356
357 accept: none
358 perform: Initialize the native library
359 return: none
360 comments: lots of reading to do here. FIXME
361 ----------------------------------------------------------*/
362 JNIEXPORT void JNICALL LPRPort(Initialize)( JNIEnv *env,
363 jclass jclazz )
364 {
365 /* This bit of code checks to see if there is a signal handler installed
366 for SIGIO, and installs SIG_IGN if there is not. This is necessary
367 for the native threads jdk, but we don't want to do it with green
368 threads, because it slows things down. Go figure. */
369 #if !defined(WIN32)
370 struct sigaction handler;
371 sigaction( SIGIO, NULL, &handler );
372 if( !handler.sa_handler ) signal( SIGIO, SIG_IGN );
373 #endif /* !WIN32 */
374 }
375
376
377 /*----------------------------------------------------------
378 LPRPort.open
379
380 accept: The device to open. ie "/dev/lp0"
381 perform: open the device and return the filedescriptor
382 return: fd
383 exceptions: PortInUseException
384 comments: Very often people complain about not being able to get past
385 this function and it turns out to be permissions on the
386 device file or bios has the device disabled.
387 FIXME Lock Files?
388 ----------------------------------------------------------*/
389 JNIEXPORT jint JNICALL LPRPort(open)( JNIEnv *env, jobject jobj,
390 jstring jstr )
391 {
392 /*struct termios ttyset;*/
393 const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
394 #ifdef WIN32
395 int fd = (int)CreateFile( filename, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0 );
396 #else
397 int fd = open( filename, O_RDWR | O_NONBLOCK );
398 #endif
399 (*env)->ReleaseStringUTFChars( env, jstr, NULL );
400 if( fd < 0 ) goto fail;
401 return (jint)fd;
402
403 fail:
404 throw_java_exception_system_msg( env, PORT_IN_USE_EXCEPTION, "open" );
405 return -1;
406 }
407
408
409 /*----------------------------------------------------------
410 LPRPort.nativeClose
411
412 accept: none
413 perform: get the fd from the java end and close it
414 return: none
415 exceptions: none
416 ----------------------------------------------------------*/
417 JNIEXPORT void JNICALL LPRPort(nativeClose)( JNIEnv *env,
418 jobject jobj )
419 {
420 int fd = get_java_var( env, jobj,"fd","I" );
421
422 #ifdef WIN32
423 CloseHandle( (HANDLE)fd );
424 #else
425 close( fd );
426 #endif
427 return;
428 }
429
430 /*----------------------------------------------------------
431 LPRPort.writeByte
432
433 accept: byte to write (passed as int)
434 perform: write a single byte to the port
435 return: none
436 exceptions: IOException
437 ----------------------------------------------------------*/
438 JNIEXPORT void JNICALL LPRPort(writeByte)( JNIEnv *env,
439 jobject jobj, jint ji )
440 {
441 unsigned char byte = (unsigned char)ji;
442 int fd = get_java_var( env, jobj,"fd","I" );
443
444 #ifdef WIN32
445 DWORD countWritten; /* Fixme, should be a loop until all is written */
446 if( WriteFile( (HANDLE)fd, &byte, sizeof( unsigned char ), &countWritten, NULL ) < 0 ) return;
447 #else
448 if( write( fd, &byte, sizeof( unsigned char ) ) >= 0 ) return;
449 #endif
450 throw_java_exception_system_msg( env, IO_EXCEPTION, "writeByte" );
451 }
452
453
454 /*----------------------------------------------------------
455 LPRPort.writeArray
456
457 accept: jbarray: bytes used for writing
458 offset: offset in array to start writing
459 count: Number of bytes to write
460 perform: write length bytes of jbarray
461 return: none
462 exceptions: IOException
463 ----------------------------------------------------------*/
464 JNIEXPORT void JNICALL LPRPort(writeArray)( JNIEnv *env,
465 jobject jobj, jbyteArray jbarray, jint offset, jint count )
466 {
467 #ifdef WIN32
468 DWORD countWritten; /* Fixme, should be a loop until all is written */
469 COMMTIMEOUTS timeouts;
470 int errorCount = 0;
471 #endif
472 int fd = get_java_var( env, jobj,"fd","I" );
473 jbyte *body = (*env)->GetByteArrayElements( env, jbarray, 0 );
474 unsigned char *bytes = (unsigned char *)malloc( count );
475 int i;
476 for( i = 0; i < count; i++ ) bytes[ i ] = body[ i + offset ];
477 (*env)->ReleaseByteArrayElements( env, jbarray, body, 0 );
478 #ifdef WIN32
479 /*
480 we set a timeout because all calls are sequentiell (also with asynchron)
481 this means that the default timeout of unlimited
482 blocks all calls (also close and status request) if the device is down
483 */
484 GetCommTimeouts( (HANDLE)fd, &timeouts );
485 timeouts.WriteTotalTimeoutMultiplier = 0;
486 timeouts.WriteTotalTimeoutConstant = 2000; /* 2000 is the min value for the default Windows NT and Windows 2000 driver */
487 SetCommTimeouts( (HANDLE)fd, &timeouts );
488 while( count > 0 ){
489 if(!WriteFile( (HANDLE)fd, bytes, count, &countWritten, NULL ) && countWritten == 0){
490 /*
491 this are 20 * 2 seconds, in this time a printer (or other parallel device)
492 should solv all problems like buffer full, etc
493 */
494 if(errorCount++ < 20){
495 Sleep( 20 ); /* make a small pause to execute all other requests in all other threads */
496 continue;
497 }
498 throw_java_exception_system_msg( env, IO_EXCEPTION, "writeArray" );
499 break;
500 }
501 errorCount = 0;
502 bytes += countWritten;
503 count -= countWritten;
504 }
505 #else
506 if( write( fd, bytes, count ) < 0 )
507 throw_java_exception_system_msg( env, IO_EXCEPTION, "writeArray" );
508 #endif
509 free( bytes );
510 }
511
512
513 /*----------------------------------------------------------
514 read_byte_array
515
516 accept: int fd file descriptor to read from
517 unsigned char *buffer buffer to read data into
518 int length number of bytes to read
519 int threshold receive threshold
520 int timeout milliseconds to wait before returning
521 perform: read bytes from the port into a buffer
522 return: status of read
523 -1 fail (IOException)
524 0 timeout
525 >0 number of bytes read
526 comments: According to the Communications API spec, a receive threshold
527 of 1 is the same as having the threshold disabled.
528 ----------------------------------------------------------*/
529 int read_byte_array( int fd, unsigned char *buffer, int length, int threshold,
530 int timeout )
531 {
532 int ret, left, bytes = 0;
533 fd_set rfds;
534 struct timeval sleep;
535
536 FD_ZERO( &rfds );
537 FD_SET( fd, &rfds );
538 sleep.tv_sec = timeout / 1000;
539 sleep.tv_usec = 1000 * ( timeout % 1000 );
540 left = length;
541
542 while( bytes < length && bytes < threshold )
543 {
544 if( timeout > 0 )
545 {
546 /* FIXME: In Linux, select updates the timeout automatically, so
547 other OSes will need to update it manually if they want to have
548 the same behavior. For those OSes, timeouts will occur after no
549 data AT ALL is received for the timeout duration. No big deal. */
550 do {
551 ret=select( fd + 1, &rfds, NULL, NULL, &sleep );
552 } while(ret < 0 && errno ==EINTR);
553 if( ret == 0 ) break;
554 if( ret < 0 ) return -1;
555 }
556 #if defined(WIN32)
557 if(!ReadFile( (HANDLE)fd, buffer + bytes, left, (DWORD *)&ret, NULL )){
558 YACK();
559 ret = -1;
560 }
561 #else
562 ret = read( fd, buffer + bytes, left );
563 #endif
564 if( ret == 0 ) break;
565 if( ret < 0 ) return -1;
566 bytes += ret;
567 left -= ret;
568 }
569 return bytes;
570 }
571
572
573 /*----------------------------------------------------------
574 LPRPort.readByte
575
576 accept: none
577 perform: Read a single byte from the port
578 return: The byte read
579 exceptions: IOException
580 ----------------------------------------------------------*/
581 JNIEXPORT jint JNICALL LPRPort(readByte)( JNIEnv *env,
582 jobject jobj )
583 {
584 int bytes, fd, timeout;
585 unsigned char buffer[ 1 ];
586
587 fd = get_java_var( env, jobj,"fd","I" );
588 timeout = get_java_var( env, jobj, "timeout","I");
589
590 bytes = read_byte_array( fd, buffer, 1, 1, timeout );
591 if( bytes < 0 )
592 {
593 throw_java_exception_system_msg( env, IO_EXCEPTION, "readByte" );
594
595 return -1;
596 }
597 return (bytes ? (jint)buffer[ 0 ] : -1);
598 }
599
600
601 /*----------------------------------------------------------
602 LPRPort.readArray
603
604 accept: offset (bytes to skip) and Length (bytes to read)
605 perform: read bytes from the port into a byte array
606 return: bytes read on success
607 0 on read timeout
608 exceptions: IOException
609 comments: throws IOException if asked to read > SSIZE_MAX
610 ----------------------------------------------------------*/
611 JNIEXPORT jint JNICALL LPRPort(readArray)( JNIEnv *env,
612 jobject jobj, jbyteArray jbarray, jint offset, jint length )
613 {
614 int bytes, i, fd, threshold, timeout;
615 jbyte *body;
616 unsigned char *buffer;
617 fd = get_java_var( env, jobj,"fd","I" );
618 threshold = get_java_var( env, jobj,"threshold","I" );
619 timeout = get_java_var( env, jobj,"threshold","I" );
620
621 if( (size_t) length < 1 || (size_t) length > SSIZE_MAX )
622 {
623 throw_java_exception( env, IO_EXCEPTION, "readArray",
624 "Invalid length" );
625 return -1;
626 }
627
628 buffer = (unsigned char *)malloc( sizeof( unsigned char ) * length );
629 if( buffer == 0 )
630 {
631 throw_java_exception( env, IO_EXCEPTION, "readArray",
632 "Unable to allocate buffer" );
633
634 return -1;
635 }
636
637 bytes = read_byte_array( fd, buffer, length, threshold, timeout );
638 if( bytes < 0 )
639 {
640 free( buffer );
641 throw_java_exception_system_msg( env, IO_EXCEPTION, "readArray" );
642
643 return -1;
644 }
645
646 body = (*env)->GetByteArrayElements( env, jbarray, 0 );
647 for( i = 0; i < bytes; i++ ) body[ i + offset ] = buffer[ i ];
648 (*env)->ReleaseByteArrayElements( env, jbarray, body, 0 );
649 free( buffer );
650 return (bytes ? bytes : -1);
651 }
652
653
654 /*----------------------------------------------------------
655 LPRPort.nativeavailable
656
657 accept: none
658 perform: find out the number of bytes available for reading
659 return: available bytes
660 -1 on error
661 exceptions: none
662 ----------------------------------------------------------*/
663 JNIEXPORT jint JNICALL LPRPort(nativeavailable)( JNIEnv *env,
664 jobject jobj )
665 {
666 int fd = get_java_var( env, jobj,"fd","I" );
667 int result;
668 /*
669 char message[80];
670
671 ENTER( "LPRPort:nativeavailable" );
672 */
673 /*
674 On SCO OpenServer FIONREAD always fails for serial devices,
675 so try ioctl FIORDCHK instead; will only tell us whether
676 bytes are available, not how many, but better than nothing.
677
678 This turns out to be true on Solaris also. taj.
679 */
680 #ifdef FIORDCHK /* __unixware__ __sun__ probably others */
681 result = ioctl(fd, FIORDCHK, 0);
682 #else
683 if( ioctl( fd, FIONREAD, &result ) < 0 )
684 {
685 goto fail;
686 }
687 #endif /* FIORDCHK */
688 if (result == -1) {
689 goto fail;
690 }
691 if( result )
692 {
693 /* sprintf(message, " nativeavailable: FIORDCHK result %d, \
694 errno %d\n", result , result == -1 ? errno : 0);
695 report( message );
696 */
697 }
698 /*
699 LEAVE( "LPRPort:nativeavailable" );
700 */
701 return (jint)result;
702 fail:
703 /*
704 report("LPRPort:nativeavailable: ioctl() failed\n");
705 LEAVE( "LPRPort:nativeavailable" );
706 */
707 throw_java_exception_system_msg( env, IO_EXCEPTION, "nativeavailable" );
708 return (jint)result;
709 }
710
711
712 /*----------------------------------------------------------
713 LPRPort.setHWFC
714
715 accept: state (JNI_FALSE 0, JNI_TRUE 1)
716 perform: set hardware flow control to state
717 return: none
718 exceptions: IOException
719 ----------------------------------------------------------*/
720 JNIEXPORT void JNICALL LPRPort(setHWFC)( JNIEnv *env,
721 jobject jobj, jboolean state )
722 {
723 /* int fd = get_java_var( env, jobj,"fd","I" ); */
724 return;
725 }
726
727 /*----------------------------------------------------------
728 LPRPort.eventLoop
729
730 accept: none
731 perform: periodically check for ParallelPortEvents
732 return: none
733 exceptions: none
734 comments: lots of work needed here. Yes its a mess.
735 struct lp_stats
736 {
737 unsigned long chars;
738 unsigned long sleeps;
739 unsigned int maxrun;
740 unsigned int maxwait;
741 unsigned int meanwait;
742 unsigned int mdev;
743 };
744
745 ----------------------------------------------------------*/
746 JNIEXPORT void JNICALL LPRPort(eventLoop)( JNIEnv *env,
747 jobject jobj )
748 {
749 int fd, ret;
750 unsigned int pflags = 0;
751 fd_set rfds;
752 struct timeval sleep;
753 jboolean interrupted = 0;
754
755 fd = get_java_var( env, jobj,"fd","I" );
756
757 interrupted = is_interrupted(env, jobj);
758
759 FD_ZERO( &rfds );
760 while( !interrupted )
761 {
762 FD_SET( fd, &rfds );
763 /* Check every 1 second, or on receive data */
764 sleep.tv_sec = 1;
765 sleep.tv_usec = 0;
766 do {
767 ret = select( fd + 1, &rfds, NULL, NULL, &sleep );
768 }
769 while (ret < 0 && errno == EINTR);
770 if( ret < 0 ) break;
771 interrupted = is_interrupted(env, jobj);
772 if(interrupted) {
773 return;
774 }
775
776 #if defined(LPGETSTATUS)
777 ioctl( fd, LPGETSTATUS, &pflags );
778 #elif defined(WIN32)
779 pflags = getWin32ParallelStatusFlags(fd);
780 #else
781 /* FIXME?? */
782 printf("ParallelImp.c LPGETSTATUS is undefined!\n");
783 #endif
784
785 /*
786 PAR_EV_BUFFER:
787 PAR_EV_ERROR:
788 */
789
790 #if defined(PARALLEL_BUSY)
791 if (pflags & PARALLEL_BUSY)
792 send_event( env, jobj, PAR_EV_ERROR, JNI_TRUE );
793 #elif defined(LP_BUSY)
794 if (pflags&LP_BUSY) /* inverted input, active high */
795 send_event( env, jobj, PAR_EV_ERROR, JNI_TRUE );
796 #elif defined(EBUSY)
797 if (pflags&EBUSY) /* inverted input, active high */
798 send_event( env, jobj, PAR_EV_ERROR, JNI_TRUE );
799 #endif /* EBUSY LP_BUSY */
800 /* FIXME this has moved into the ifdef __kernel__? Need to get the
801 posix documentation on this.
802 if (pflags&LP_ACK)
803 send_event( env, jobj, PAR_EV_ERROR, JNI_TRUE );
804 */
805
806
807 #if defined (__linux__)
808 /* unchanged input, active low */
809 if (pflags&LP_NOPA) /* unchanged input, active high */
810 send_event( env, jobj, PAR_EV_ERROR, 1 );
811 if (pflags&LP_SELEC) /* unchanged input, active high */
812 send_event( env, jobj, PAR_EV_ERROR, 1 );
813 if (pflags&LP_ERR) /* unchanged input, active low */
814 send_event( env, jobj, PAR_EV_ERROR, 1 );
815 #else
816 /* FIXME?? */
817 printf("ParallelImp.c LPGETSTATUS is undefined!\n");
818 #endif
819 usleep(1000);
820 }
821 return;
822 }
823
824 JNIEXPORT void JNICALL LPRPort(setInputBufferSize)(JNIEnv *env,
825 jobject jobj, jint size )
826 {
827 #ifdef DEBUG
828 printf("setInputBufferSize is not implemented\n");
829 #endif
830 }
831 JNIEXPORT jint JNICALL LPRPort(getInputBufferSize)(JNIEnv *env,
832 jobject jobj)
833 {
834 #ifdef DEBUG
835 printf("getInputBufferSize is not implemented\n");
836 #endif
837 return(1);
838 }
839 JNIEXPORT void JNICALL LPRPort(setOutputBufferSize)(JNIEnv *env,
840 jobject jobj, jint size )
841 {
842 #ifdef DEBUG
843 printf("setOutputBufferSize is not implemented\n");
844 #endif
845 }
846 JNIEXPORT jint JNICALL LPRPort(getOutputBufferSize)(JNIEnv *env,
847 jobject jobj)
848 {
849 #ifdef DEBUG
850 printf("getOutputBufferSize is not implemented\n");
851 #endif
852 return(1);
853 }
854
855 /*----------------------------------------------------------
856 throw_java_exception
857
858 accept: env (keyhole to java)
859 *exc (exception class name)
860 *foo (function name)
861 *msg (error message)
862 perform: Throw a new java exception
863 return: none
864 exceptions: haha!
865 comments:
866 ----------------------------------------------------------*/
867 void throw_java_exception( JNIEnv *env, char *exc, char *foo, char *msg )
868 {
869 #define MSG_SIZE 128
870 char buf[ 128 ];
871 jclass clazz = (*env)->FindClass( env, exc );
872 if( !clazz )
873 {
874 (*env)->ExceptionDescribe( env );
875 (*env)->ExceptionClear( env );
876 return;
877 }
878 /* reduce the message size if it to large for the message buffer */
879 if(MSG_SIZE < (strlen( msg ) + strlen(foo) + 5)){
880 msg[ MSG_SIZE - strlen(foo) - 5] = 0;
881 }
882 #if defined(_GNU_SOURCE)
883 snprintf( buf, 60, "%s in %s", msg, foo );
884 #else
885 sprintf( buf,"%s in %s", msg, foo );
886 #endif /* _GNU_SOURCE */
887 (*env)->ThrowNew( env, clazz, buf );
888 /* ct7 * Added DeleteLocalRef */
889 (*env)->DeleteLocalRef( env, clazz );
890 }
891
892 void throw_java_exception_system_msg( JNIEnv *env, char *exc, char *foo )
893 {
894 #ifdef WIN32
895 char *allocTextBuf;
896 FormatMessage (
897 FORMAT_MESSAGE_ALLOCATE_BUFFER |
898 FORMAT_MESSAGE_FROM_SYSTEM,
899 NULL,
900 GetLastError(),
901 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
902 (LPSTR)&allocTextBuf,
903 16,
904 NULL );
905 throw_java_exception( env, exc, foo, allocTextBuf );
906 LocalFree(allocTextBuf);
907 #else
908 throw_java_exception( env, exc, foo, strerror( errno ) );
909 #endif
910 }
911 /*----------------------------------------------------------
912 report_error
913
914 accept: string to send to report as an error
915 perform: send the string to stderr or however it needs to be reported.
916 return: none
917 exceptions: none
918 comments:
919 ----------------------------------------------------------*/
920 void report_error(char *msg)
921 {
922 #ifndef DEBUG_MW
923 fprintf(stderr, msg);
924 #else
925 mexWarnMsgTxt( msg );
926 #endif /* DEBUG_MW */
927 }
928
929 /*----------------------------------------------------------
930 report
931
932 accept: string to send to stderr
933 perform: if DEBUG is defined send the string to stderr.
934 return: none
935 exceptions: none
936 comments:
937 ----------------------------------------------------------*/
938 void report(char *msg)
939 {
940 #ifdef DEBUG
941 fprintf(stderr, msg);
942 #endif /* DEBUG */
943 }
944
945 /*----------------------------------------------------------
946 is_interrupted
947
948 accept:
949 perform: see if the port is being closed.
950 return: a positive value if the port is being closed.
951 exceptions: none
952 comments:
953 ----------------------------------------------------------*/
954 jboolean is_interrupted(JNIEnv *env, jobject jobj)
955 {
956 jmethodID foo;
957 jclass jclazz;
958 int result;
959
960 (*env)->ExceptionClear(env);
961
962 jclazz = (*env)->GetObjectClass( env, jobj );
963 if(jclazz == NULL) return JNI_TRUE;
964
965 foo = (*env)->GetMethodID( env, jclazz, "checkMonitorThread", "()Z");
966 if(foo == NULL) return JNI_TRUE;
967
968 result = (*env)->CallBooleanMethod( env, jobj, foo );
969
970 #ifdef DEBUG
971 if((*env)->ExceptionOccurred(env)) {
972 report ("an error occured calling sendEvent()\n");
973 (*env)->ExceptionDescribe(env);
974 (*env)->ExceptionClear(env);
975 }
976 #endif /* DEBUG */
977 (*env)->DeleteLocalRef( env, jclazz );
978
979 return(result);
980 }
981 /*----------------------------------------------------------
982 send_event
983
984 accept: The event type and the event state
985 perform: if state is > 0 send a JNI_TRUE event otherwise send JNI_FALSE
986 return: a positive value if the port is being closed.
987 exceptions: none
988 comments:
989 ----------------------------------------------------------*/
990 int send_event(JNIEnv *env, jobject jobj, jint type, int flag)
991 {
992 int result;
993 jmethodID foo;
994 jclass jclazz = (*env)->GetObjectClass( env, jobj );
995
996 if(jclazz == NULL) return JNI_TRUE;
997 foo = (*env)->GetMethodID( env, jclazz, "sendEvent", "(IZ)Z" );
998
999 (*env)->ExceptionClear(env);
1000
1001 result = (*env)->CallBooleanMethod( env, jobj, foo, type,
1002 flag > 0 ? JNI_TRUE : JNI_FALSE );
1003
1004 #ifdef DEBUG
1005 if((*env)->ExceptionOccurred(env)) {
1006 report ("an error occured calling sendEvent()\n");
1007 (*env)->ExceptionDescribe(env);
1008 (*env)->ExceptionClear(env);
1009 }
1010 #endif /* DEBUG */
1011 (*env)->DeleteLocalRef( env, jclazz );
1012 return(result);
1013 }
1014 /*----------------------------------------------------------
1015 get_java_var
1016
1017 accept: env (keyhole to java)
1018 jobj (java RXTXPort object)
1019
1020 return: the fd field from the java object
1021 exceptions: none
1022 comments:
1023 ----------------------------------------------------------*/
1024 int get_java_var( JNIEnv *env, jobject jobj, char *id, char *type )
1025 {
1026 int result = 0;
1027 jclass jclazz = (*env)->GetObjectClass( env, jobj );
1028 jfieldID jfd = (*env)->GetFieldID( env, jclazz, id, type );
1029 if( !jfd )
1030 {
1031 (*env)->ExceptionDescribe( env );
1032 (*env)->ExceptionClear( env );
1033 return result;
1034 }
1035 result = (int)( (*env)->GetIntField( env, jobj, jfd ) );
1036 /* ct7 & gel * Added DeleteLocalRef */
1037 (*env)->DeleteLocalRef( env, jclazz );
1038 return result;
1039 }