1SerialPort(3)         User Contributed Perl Documentation        SerialPort(3)
2
3
4

NAME

6       Device::SerialPort - Linux/POSIX emulation of Win32::SerialPort func‐
7       tions.
8

SYNOPSIS

10         use Device::SerialPort qw( :PARAM :STAT 0.07 );
11
12       Constructors
13
14         # $lockfile is optional
15         $PortObj = new Device::SerialPort ($PortName, $quiet, $lockfile)
16              ⎪⎪ die "Can't open $PortName: $!\n";
17
18         $PortObj = start Device::SerialPort ($Configuration_File_Name)
19              ⎪⎪ die "Can't start $Configuration_File_Name: $!\n";
20
21         $PortObj = tie (*FH, 'Device::SerialPort', $Configuration_File_Name)
22              ⎪⎪ die "Can't tie using $Configuration_File_Name: $!\n";
23
24       Configuration Utility Methods
25
26         $PortObj->alias("MODEM1");
27
28         $PortObj->save($Configuration_File_Name)
29              ⎪⎪ warn "Can't save $Configuration_File_Name: $!\n";
30
31         # currently optional after new, POSIX version expected to succeed
32         $PortObj->write_settings;
33
34         # rereads file to either return open port to a known state
35         # or switch to a different configuration on the same port
36         $PortObj->restart($Configuration_File_Name)
37              ⎪⎪ warn "Can't reread $Configuration_File_Name: $!\n";
38
39         # "app. variables" saved in $Configuration_File, not used internally
40         $PortObj->devicetype('none');     # CM11, CM17, 'weeder', 'modem'
41         $PortObj->hostname('localhost');  # for socket-based implementations
42         $PortObj->hostaddr(0);            # false unless specified
43         $PortObj->datatype('raw');        # in case an application needs_to_know
44         $PortObj->cfg_param_1('none');    # null string '' hard to save/restore
45         $PortObj->cfg_param_2('none');    # 3 spares should be enough for now
46         $PortObj->cfg_param_3('none');    # one may end up as a log file path
47
48         # test suite use only
49         @necessary_param = Device::SerialPort->set_test_mode_active(1);
50
51         # exported by :PARAM
52         nocarp ⎪⎪ carp "Something fishy";
53         $a = SHORTsize;                       # 0xffff
54         $a = LONGsize;                        # 0xffffffff
55         $answer = yes_true("choice");         # 1 or 0
56         OS_Error unless ($API_Call_OK);       # prints error
57
58       Configuration Parameter Methods
59
60         # most methods can be called two ways:
61         $PortObj->handshake("xoff");           # set parameter
62         $flowcontrol = $PortObj->handshake;    # current value (scalar)
63
64         # The only "list context" method calls from Win32::SerialPort
65         # currently supported are those for baudrate, parity, databits,
66         # stopbits, and handshake (which only accept specific input values).
67         @handshake_opts = $PortObj->handshake; # permitted choices (list)
68
69         # similar
70         $PortObj->baudrate(9600);
71         $PortObj->parity("odd");
72         $PortObj->databits(8);
73         $PortObj->stopbits(1);        # POSIX does not support 1.5 stopbits
74
75         # these are essentially dummies in POSIX implementation
76         # the calls exist to support compatibility
77         $PortObj->buffers(4096, 4096);        # returns (4096, 4096)
78         @max_values = $PortObj->buffer_max;   # returns (4096, 4096)
79         $PortObj->reset_error;                # returns 0
80
81         # true/false parameters (return scalar context only)
82         # parameters exist, but message processing not yet fully implemented
83         $PortObj->user_msg(ON);       # built-in instead of warn/die above
84         $PortObj->error_msg(ON);      # translate error bitmasks and carp
85
86         $PortObj->parity_enable(F);   # faults during input
87         $PortObj->debug(0);
88
89         # true/false capabilities (read only)
90         # most are just constants in the POSIX case
91         $PortObj->can_baud;                   # 1
92         $PortObj->can_databits;               # 1
93         $PortObj->can_stopbits;               # 1
94         $PortObj->can_dtrdsr;                 # 1
95         $PortObj->can_handshake;              # 1
96         $PortObj->can_parity_check;           # 1
97         $PortObj->can_parity_config;          # 1
98         $PortObj->can_parity_enable;          # 1
99         $PortObj->can_rlsd;                   # 0 currently
100         $PortObj->can_16bitmode;              # 0 Win32-specific
101         $PortObj->is_rs232;                   # 1
102         $PortObj->is_modem;                   # 0 Win32-specific
103         $PortObj->can_rtscts;                 # 1
104         $PortObj->can_xonxoff;                # 1
105         $PortObj->can_xon_char;               # 1 use stty
106         $PortObj->can_spec_char;              # 0 use stty
107         $PortObj->can_interval_timeout;       # 0 currently
108         $PortObj->can_total_timeout;          # 1 currently
109         $PortObj->can_ioctl;                  # automatically detected by eval
110         $PortObj->can_status;                 # automatically detected by eval
111         $PortObj->can_write_done;             # automatically detected by eval
112         $PortObj->can_modemlines;     # automatically detected by eval
113         $PortObj->can_wait_modemlines;# automatically detected by eval
114         $PortObj->can_intr_count;             # automatically detected by eval
115
116       Operating Methods
117
118         ($count_in, $string_in) = $PortObj->read($InBytes);
119         warn "read unsuccessful\n" unless ($count_in == $InBytes);
120
121         $count_out = $PortObj->write($output_string);
122         warn "write failed\n"         unless ($count_out);
123         warn "write incomplete\n"     if ( $count_out != length($output_string) );
124
125         if ($string_in = $PortObj->input) { PortObj->write($string_in); }
126            # simple echo with no control character processing
127
128         if ($PortObj->can_wait_modemlines) {
129           $rc = $PortObj->wait_modemlines( MS_RLSD_ON );
130           if (!$rc) { print "carrier detect changed\n"; }
131         }
132
133         if ($PortObj->can_modemlines) {
134           $ModemStatus = $PortObj->modemlines;
135           if ($ModemStatus & $PortObj->MS_RLSD_ON) { print "carrier detected\n"; }
136         }
137
138         if ($PortObj->can_intr_count) {
139           $count = $PortObj->intr_count();
140           print "got $count interrupts\n";
141         }
142
143         ($BlockingFlags, $InBytes, $OutBytes, $ErrorFlags) = $PortObj->status;
144             # same format for compatibility. Only $InBytes and $OutBytes are
145             # currently returned (on linux). Others are 0.
146             # Check return value of "can_status" to see if this call is valid.
147
148         ($done, $count_out) = $PortObj->write_done(0);
149            # POSIX defaults to background write. Currently $count_out always 0.
150            # $done set when hardware finished transmitting and shared line can
151            # be released for other use. Ioctl may not work on all OSs.
152            # Check return value of "can_write_done" to see if this call is valid.
153
154         $PortObj->write_drain;  # POSIX alternative to Win32 write_done(1)
155                                 # set when software is finished transmitting
156         $PortObj->purge_all;
157         $PortObj->purge_rx;
158         $PortObj->purge_tx;
159
160             # controlling outputs from the port
161         $PortObj->dtr_active(T);              # sends outputs direct to hardware
162         $PortObj->rts_active(Yes);            # return status of ioctl call
163                                               # return undef on failure
164
165         $PortObj->pulse_break_on($milliseconds); # off version is implausible
166         $PortObj->pulse_rts_on($milliseconds);
167         $PortObj->pulse_rts_off($milliseconds);
168         $PortObj->pulse_dtr_on($milliseconds);
169         $PortObj->pulse_dtr_off($milliseconds);
170             # sets_bit, delays, resets_bit, delays
171             # returns undef if unsuccessful or ioctls not implemented
172
173         $PortObj->read_const_time(100);       # const time for read (milliseconds)
174         $PortObj->read_char_time(5);          # avg time between read char
175
176         $milliseconds = $PortObj->get_tick_count;
177
178       Methods used with Tied FileHandles
179
180         $PortObj = tie (*FH, 'Device::SerialPort', $Configuration_File_Name)
181              ⎪⎪ die "Can't tie: $!\n";             ## TIEHANDLE ##
182
183         print FH "text";                           ## PRINT     ##
184         $char = getc FH;                           ## GETC      ##
185         syswrite FH, $out, length($out), 0;        ## WRITE     ##
186         $line = <FH>;                              ## READLINE  ##
187         @lines = <FH>;                             ## READLINE  ##
188         printf FH "received: %s", $line;           ## PRINTF    ##
189         read (FH, $in, 5, 0) or die "$!";          ## READ      ##
190         sysread (FH, $in, 5, 0) or die "$!";       ## READ      ##
191         close FH ⎪⎪ warn "close failed";           ## CLOSE     ##
192         undef $PortObj;
193         untie *FH;                                 ## DESTROY   ##
194
195         $PortObj->linesize(10);                    # with READLINE
196         $PortObj->lastline("_GOT_ME_");            # with READLINE, list only
197
198             ## with PRINT and PRINTF, return previous value of separator
199         $old_ors = $PortObj->output_record_separator("RECORD");
200         $old_ofs = $PortObj->output_field_separator("COMMA");
201
202       Destructors
203
204         $PortObj->close ⎪⎪ warn "close failed";
205             # release port to OS - needed to reopen
206             # close will not usually DESTROY the object
207             # also called as: close FH ⎪⎪ warn "close failed";
208
209         undef $PortObj;
210             # preferred unless reopen expected since it triggers DESTROY
211             # calls $PortObj->close but does not confirm success
212             # MUST precede untie - do all three IN THIS SEQUENCE before re-tie.
213
214         untie *FH;
215
216       Methods for I/O Processing
217
218         $PortObj->are_match("text", "\n");    # possible end strings
219         $PortObj->lookclear;                  # empty buffers
220         $PortObj->write("Feed Me:");          # initial prompt
221         $PortObj->is_prompt("More Food:");    # not implemented
222
223         my $gotit = "";
224         until ("" ne $gotit) {
225             $gotit = $PortObj->lookfor;       # poll until data ready
226             die "Aborted without match\n" unless (defined $gotit);
227             sleep 1;                          # polling sample time
228         }
229
230         printf "gotit = %s\n", $gotit;                # input BEFORE the match
231         my ($match, $after, $pattern, $instead) = $PortObj->lastlook;
232             # input that MATCHED, input AFTER the match, PATTERN that matched
233             # input received INSTEAD when timeout without match
234         printf "lastlook-match = %s  -after = %s  -pattern = %s\n",
235                                  $match,      $after,        $pattern;
236
237         $gotit = $PortObj->lookfor($count);   # block until $count chars received
238
239         $PortObj->are_match("-re", "pattern", "text");
240             # possible match strings: "pattern" is a regular expression,
241             #                         "text" is a literal string
242

DESCRIPTION

244       This module provides an object-based user interface essentially identi‐
245       cal to the one provided by the Win32::SerialPort module.
246
247       Initialization
248
249       The primary constructor is new with either a PortName, or a Configure‐
250       tion File specified.  With a PortName, this will open the port and cre‐
251       ate the object. The port is not yet ready for read/write access. First,
252       the desired parameter settings must be established. Since these are
253       tuning constants for an underlying hardware driver in the Operating
254       System, they are all checked for validity by the methods that set them.
255       The write_settings method updates the port (and will return True under
256       POSIX). Ports are opened for binary transfers. A separate "binmode" is
257       not needed.
258
259         $PortObj = new Device::SerialPort ($PortName, $quiet, $lockfile)
260              ⎪⎪ die "Can't open $PortName: $!\n";
261
262       The $quiet parameter is ignored and is only there for compatibility
263       with Win32::SerialPort.  The $lockfile parameter is optional.  It will
264       attempt to create a file (containing just the current process id) at
265       the location specified. This file will be automatically deleted when
266       the $PortObj is no longer used (by DESTROY). You would usually request
267       $lockfile with $quiet true to disable messages while attempting to
268       obtain exclusive ownership of the port via the lock. Lockfiles are
269       experimental in Version 0.07. They are intended for use with other
270       applications. No attempt is made to resolve port aliases (/dev/modem ==
271       /dev/ttySx) or to deal with login processes such as getty and uugetty.
272
273       Using a Configuration File with new or by using second constructor,
274       start, scripts can be simplified if they need a constant setup. It exe‐
275       cutes all the steps from new to write_settings based on a previously
276       saved configuration. This constructor will return "undef" on a bad con‐
277       figuration file or failure of a validity check. The returned object is
278       ready for access. This is new and experimental for Version 0.055.
279
280         $PortObj2 = start Device::SerialPort ($Configuration_File_Name)
281              ⎪⎪ die;
282
283       The third constructor, tie, will combine the start with Perl's support
284       for tied FileHandles (see perltie). Device::SerialPort will implement
285       the complete set of methods: TIEHANDLE, PRINT, PRINTF, WRITE, READ,
286       GETC, READLINE, CLOSE, and DESTROY. Tied FileHandle support is new with
287       Version 0.04 and the READ and READLINE methods were added in Version
288       0.06. In "scalar context", READLINE sets stty_icanon to do character
289       processing and calls lookfor. It restores stty_icanon after the read.
290       In "list context", READLINE does Canonical (line) reads if stty_icanon
291       is set or calls streamline if it is not. (stty_icanon is not altered).
292       The streamline choice allows duplicating the operation of Win32::Seri‐
293       alPort for cross-platform scripts.
294
295       The implementation attempts to mimic STDIN/STDOUT behaviour as closely
296       as possible: calls block until done and data strings that exceed inter‐
297       nal buffers are divided transparently into multiple calls. In Version
298       0.06, the output separators $, and "$\" are also applied to PRINT if
299       set.  The output_record_separator and output_field_separator methods
300       can set Port-FileHandle-Specific versions of $, and "$\" if desired.
301       Since PRINTF is treated internally as a single record PRINT, "$\" will
302       be applied.  Output separators are not applied to WRITE (called as
303       "syswrite FH, $scalar, $length, [$offset]").  The input_record_separa‐
304       tor $/ is not explicitly supported - but an identical function can be
305       obtained with a suitable are_match setting.
306
307         $PortObj2 = tie (*FH, 'Device::SerialPort', $Configuration_File_Name)
308              ⎪⎪ die;
309
310       The tied FileHandle methods may be combined with the Device::SerialPort
311       methods for read, input, and write as well as other methods. The typi‐
312       cal restrictions against mixing print with syswrite do not apply. Since
313       both (tied) read and sysread call the same "$ob->READ" method, and
314       since a separate "$ob->read" method has existed for some time in
315       Device::SerialPort, you should always use sysread with the tied inter‐
316       face (when it is implemented).
317
318               Certain parameters SHOULD be set before executing write_set‐
319               tings.  Others will attempt to deduce defaults from the hard‐
320               ware or from other parameters. The Required parameters are:
321
322       baudrate
323               Any legal value.
324
325       parity  One of the following: "none", "odd", "even".
326
327               By default, incoming parity is not checked.  This mimics the
328               behavior of most terminal programs (like "minicom").  If you
329               need parity checking enabled, please use the "stty_inpck" and
330               "stty_istrip" functions.
331
332       databits
333               An integer from 5 to 8.
334
335       stopbits
336               Legal values are 1 and 2.
337
338       handshake
339               One of the following: "none", "rts", "xoff".
340
341       Some individual parameters (eg. baudrate) can be changed after the ini‐
342       tialization is completed. These will be validated and will update the
343       serial driver as required. The save method will write the current
344       parameters to a file that start, tie, and restart can use to reestab‐
345       lish a functional setup.
346
347         $PortObj = new Win32::SerialPort ($PortName, $quiet)
348              ⎪⎪ die "Can't open $PortName: $^E\n";    # $quiet is optional
349
350         $PortObj->user_msg(ON);
351         $PortObj->databits(8);
352         $PortObj->baudrate(9600);
353         $PortObj->parity("none");
354         $PortObj->stopbits(1);
355         $PortObj->handshake("rts");
356
357         $PortObj->write_settings ⎪⎪ undef $PortObj;
358
359         $PortObj->save($Configuration_File_Name);
360         $PortObj->baudrate(300);
361         $PortObj->restart($Configuration_File_Name);  # back to 9600 baud
362
363         $PortObj->close ⎪⎪ die "failed to close";
364         undef $PortObj;                               # frees memory back to perl
365
366       Configuration Utility Methods
367
368       Use alias to convert the name used by "built-in" messages.
369
370         $PortObj->alias("MODEM1");
371
372       Starting in Version 0.07, a number of Application Variables are saved
373       in $Configuration_File. These parameters are not used internally. But
374       methods allow setting and reading them. The intent is to facilitate the
375       use of separate configuration scripts to create the files. Then an
376       application can use start as the Constructor and not bother with com‐
377       mand line processing or managing its own small configuration file.  The
378       default values and number of parameters is subject to change.
379
380         $PortObj->devicetype('none');
381         $PortObj->hostname('localhost');  # for socket-based implementations
382         $PortObj->hostaddr(0);            # a "false" value
383         $PortObj->datatype('raw');        # 'record' is another possibility
384         $PortObj->cfg_param_1('none');
385         $PortObj->cfg_param_2('none');    # 3 spares should be enough for now
386         $PortObj->cfg_param_3('none');
387
388       Configuration and Capability Methods
389
390       The Win32 Serial Comm API provides extensive information concerning the
391       capabilities and options available for a specific port (and instance).
392       This module will return suitable responses to facilitate porting code
393       from that environment.
394
395       The get_tick_count method is a clone of the Win32::GetTickCount() func‐
396       tion. It matches a corresponding method in Win32::CommPort.  It returns
397       time in milliseconds - but can be used in cross-platform scripts.
398
399               Binary selections will accept as true any of the following:
400               "("YES", "Y", "ON", "TRUE", "T", "1", 1)" (upper/lower/mixed
401               case) Anything else is false.
402
403               There are a large number of possible configuration and option
404               parameters.  To facilitate checking option validity in scripts,
405               most configuration methods can be used in two different ways:
406
407       method called with an argument
408               The parameter is set to the argument, if valid. An invalid
409               argument returns false (undef) and the parameter is unchanged.
410               The function will also carp if $user_msg is true. The port will
411               be updated immediately if allowed (an automatic write_settings
412               is called).
413
414       method called with no argument in scalar context
415               The current value is returned. If the value is not initialized
416               either directly or by default, return "undef" which will parse
417               to false.  For binary selections (true/false), return the cur‐
418               rent value. All current values from "multivalue" selections
419               will parse to true.
420
421       method called with no argument in list context
422               Methods which only accept a limited number of specific input
423               values return a list consisting of all acceptable choices. The
424               null list "(undef)" will be returned for failed calls in list
425               context (e.g. for an invalid or unexpected argument). Only the
426               baudrate, parity, databits, stopbits, and handshake methods
427               currently support this feature.
428
429       Operating Methods
430
431       Version 0.04 adds pulse methods for the RTS, BREAK, and DTR bits. The
432       pulse methods assume the bit is in the opposite state when the method
433       is called. They set the requested state, delay the specified number of
434       milliseconds, set the opposite state, and again delay the specified
435       time.  These methods are designed to support devices, such as the X10
436       "FireCracker" control and some modems, which require pulses on these
437       lines to signal specific events or data. Timing for the active part of
438       pulse_break_on is handled by POSIX::tcsendbreak(0), which sends a
439       250-500 millisecond BREAK pulse. It is NOT guaranteed to block until
440       done.
441
442         $PortObj->pulse_break_on($milliseconds);
443         $PortObj->pulse_rts_on($milliseconds);
444         $PortObj->pulse_rts_off($milliseconds);
445         $PortObj->pulse_dtr_on($milliseconds);
446         $PortObj->pulse_dtr_off($milliseconds);
447
448       In Version 0.05, these calls and the rts_active and dtr_active calls
449       verify the parameters and any required ioctl constants, and return
450       "undef" unless the call succeeds. You can use the can_ioctl method to
451       see if the required constants are available. On Version 0.04, the mod‐
452       ule would not load unless asm/termios.ph was found at startup.
453
454       Stty Shortcuts
455
456       Version 0.06 adds primitive methods to modify port parameters that
457       would otherwise require a "system("stty...");" command. These act much
458       like the identically-named methods in Win32::SerialPort. However, they
459       are initialized from "current stty settings" when the port is opened
460       rather than from defaults. And like stty settings, they are passed to
461       the serial driver and apply to all operations rather than only to I/O
462       processed via the lookfor method or the tied FileHandle methods.  Each
463       returns the current setting for the parameter. There are no "global" or
464       "combination" parameters - you still need "system("stty...")" for that.
465
466       The methods which handle CHAR parameters set and return values as
467       "ord(CHAR)".  This corresponds to the settings in the POSIX termios
468       cc_field array. You are unlikely to actually want to modify most of
469       these. They reflect the special characters which can be set by stty.
470
471         $PortObj->is_xon_char($num_char);     # VSTART (stty start=.)
472         $PortObj->is_xoff_char($num_char);    # VSTOP
473         $PortObj->is_stty_intr($num_char);    # VINTR
474         $PortObj->is_stty_quit($num_char);    # VQUIT
475         $PortObj->is_stty_eof($num_char);     # VEOF
476         $PortObj->is_stty_eol($num_char);     # VEOL
477         $PortObj->is_stty_erase($num_char);   # VERASE
478         $PortObj->is_stty_kill($num_char);    # VKILL
479         $PortObj->is_stty_susp($num_char);    # VSUSP
480
481       Binary settings supported by POSIX will return 0 or 1. Several parame‐
482       ters settable by stty do not yet have shortcut methods. Contact me if
483       you need one that is not supported. These are the common choices. Try
484       "man stty" if you are not sure what they do.
485
486         $PortObj->stty_echo;
487         $PortObj->stty_echoe;
488         $PortObj->stty_echok;
489         $PortObj->stty_echonl;
490         $PortObj->stty_ignbrk;
491         $PortObj->stty_istrip;
492         $PortObj->stty_inpck;
493         $PortObj->stty_parmrk;
494         $PortObj->stty_ignpar;
495         $PortObj->stty_icrnl;
496         $PortObj->stty_igncr;
497         $PortObj->stty_inlcr;
498         $PortObj->stty_opost;
499         $PortObj->stty_isig;
500         $PortObj->stty_icanon;
501
502       The following methods require successfully loading ioctl constants.
503       They will return "undef" if the needed constants are not found. But the
504       method calls may still be used without syntax errors or warnings even
505       in that case.
506
507         $PortObj->stty_ocrlf;
508         $PortObj->stty_onlcr;
509         $PortObj->stty_echoke;
510         $PortObj->stty_echoctl;
511
512       Lookfor and I/O Processing
513
514       Some communications programs have a different need - to collect (or
515       discard) input until a specific pattern is detected. For lines, the
516       pattern is a line-termination. But there are also requirements to
517       search for other strings in the input such as "username:" and "pass‐
518       word:". The lookfor method provides a consistant mechanism for solving
519       this problem.  It searches input character-by-character looking for a
520       match to any of the elements of an array set using the are_match
521       method. It returns the entire input up to the match pattern if a match
522       is found. If no match is found, it returns "" unless an input error or
523       abort is detected (which returns undef).
524
525       Unlike Win32::SerialPort, lookfor does not handle backspace, echo, and
526       other character processing. It expects the serial driver to handle
527       those and to be controlled via stty. For interacting with humans, you
528       will probably want stty_icanon(1) during lookfor to obtain familiar
529       command-line response. The actual match and the characters after it (if
530       any) may also be viewed using the lastlook method. It also adopts the
531       convention from Expect.pm that match strings are literal text (tested
532       using index) unless preceeded in the are_match list by a "-re", entry.
533       The default are_match list is "("\n")", which matches complete lines.
534
535          my ($match, $after, $pattern, $instead) = $PortObj->lastlook;
536            # input that MATCHED, input AFTER the match, PATTERN that matched
537            # input received INSTEAD when timeout without match ("" if match)
538
539          $PortObj->are_match("text1", "-re", "pattern", "text2");
540            # possible match strings: "pattern" is a regular expression,
541            #                         "text1" and "text2" are literal strings
542
543       Everything in lookfor is still experimental. Please let me know if you
544       use it (or can't use it), so I can confirm bug fixes don't break your
545       code.  For literal strings, $match and $pattern should be identical.
546       The $instead value returns the internal buffer tested by the match
547       logic.  A successful match or a lookclear resets it to "" - so it is
548       only useful for error handling such as timeout processing or reporting
549       unexpected responses.
550
551       The lookfor method is designed to be sampled periodically (polled). Any
552       characters after the match pattern are saved for a subsequent lookfor.
553       Internally, lookfor is implemented using the nonblocking input method
554       when called with no parameter. If called with a count, lookfor calls
555       "$PortObj->read(count)" which blocks until the read is Complete or a
556       Timeout occurs. The blocking alternative should not be used unless a
557       fault time has been defined using read_interval, read_const_time, and
558       read_char_time. It exists mostly to support the tied FileHandle func‐
559       tions sysread, getc, and <FH>. When stty_icanon is active, even the
560       non-blocking calls will not return data until the line is complete.
561
562       The internal buffers used by lookfor may be purged by the lookclear
563       method (which also clears the last match). For testing, lookclear can
564       accept a string which is "looped back" to the next input. This feature
565       is enabled only when set_test_mode_active(1). Normally, lookclear will
566       return "undef" if given parameters. It still purges the buffers and
567       last_match in that case (but nothing is "looped back"). You will want
568       stty_echo(0) when exercising loopback.
569
570       The matchclear method is designed to handle the "special case" where
571       the match string is the first character(s) received by lookfor. In this
572       case, "$lookfor_return == """, lookfor does not provide a clear indica‐
573       tion that a match was found. The matchclear returns the same $match
574       that would be returned by lastlook and resets it to "" without reset‐
575       ting any of the other buffers. Since the lookfor already searched
576       through the match, matchclear is used to both detect and step-over
577       "blank" lines.
578
579       The character-by-character processing used by lookfor is fine for
580       interactive activities and tasks which expect short responses. But it
581       has too much "overhead" to handle fast data streams.There is also a
582       streamline method which is a fast, line-oriented alternative with just
583       pattern searching. Since streamline uses the same internal buffers, the
584       lookclear, lastlook, are_match, and matchclear methods act the same in
585       both cases. In fact, calls to streamline and lookfor can be interleaved
586       if desired (e.g. an interactive task that starts an upload and returns
587       to interactive activity when it is complete).
588
589       There are two additional methods for supporting "list context" input:
590       lastline sets an "end_of_file" Regular Expression, and linesize permits
591       changing the "packet size" in the blocking read operation to allow tun‐
592       ing performance to data characteristics. These two only apply during
593       READLINE. The default for linesize is 1. There is no default for the
594       lastline method.
595
596       The Regular Expressions set by are_match and lastline will be pre-com‐
597       piled using the qr// construct on Perl 5.005 and higher.  This doubled
598       lookfor and streamline speed in my tests with Regular Expressions - but
599       actual improvements depend on both patterns and input data.
600
601       The functionality of lookfor includes a limited subset of the capabili‐
602       ties found in Austin Schutz's Expect.pm for Unix (and Tcl's expect
603       which it resembles). The "$before, $match, $pattern, and $after" return
604       values are available if someone needs to create an "expect" subroutine
605       for porting a script. When using multiple patterns, there is one impor‐
606       tant functional difference: Expect.pm looks at each pattern in turn and
607       returns the first match found; lookfor and streamline test all patterns
608       and return the one found earliest in the input if more than one
609       matches.
610
611       Exports
612
613       Nothing is exported by default. The following tags can be used to have
614       large sets of symbols exported:
615
616       :PARAM
617           Utility subroutines and constants for parameter setting and test:
618
619                   LONGsize        SHORTsize       nocarp          yes_true
620                   OS_Error
621
622       :STAT
623           The Constants named BM_* and CE_* are omitted. But the modem status
624           (MS_*) Constants are defined for possible use with modemlines and
625           wait_modemlines. They are assigned to corresponding functions, but
626           the bit position will be different from that on Win32.
627
628           Which incoming bits are active:
629
630                   MS_CTS_ON    - Clear to send
631               MS_DSR_ON    - Data set ready
632               MS_RING_ON   - Ring indicator
633               MS_RLSD_ON   - Carrier detected
634               MS_RTS_ON    - Request to send (might not exist on Win32)
635               MS_DTR_ON    - Data terminal ready (might not exist on Win32)
636
637           If you want to write more POSIX-looking code, you can use the con‐
638           stants seen there, instead of the Win32 versions:
639
640               TIOCM_CTS, TIOCM_DSR, TIOCM_RI, TIOCM_CD, TIOCM_RTS, and TIOCM_DTR
641
642           Offsets into the array returned by status:
643
644                   ST_BLOCK        ST_INPUT        ST_OUTPUT       ST_ERROR
645
646       :ALL
647           All of the above. Except for the test suite, there is not really a
648           good reason to do this.
649

PINOUT

651       Here is a handy pinout map, showing each line and signal on a standard
652       DB9 connector:
653
654       1 DCD   Data Carrier Detect
655
656       2 RD    Receive Data
657
658       3 TD    Transmit Data
659
660       4 DTR   Data Terminal Ready
661
662       5 SG    Signal Ground
663
664       6 DSR   Data Set Ready
665
666       7 RTS   Request to Send
667
668       8 CTS   Clear to Send
669
670       9 RI    Ring Indicator
671

NOTES

673       The object returned by new is NOT a Filehandle. You will be disap‐
674       pointed if you try to use it as one.
675
676       e.g. the following is WRONG!!
677
678        print $PortObj "some text";
679
680       This module uses POSIX termios extensively. Raw API calls are very
681       unforgiving. You will certainly want to start perl with the -w switch.
682       If you can, use strict as well. Try to ferret out all the syntax and
683       usage problems BEFORE issuing the API calls (many of which modify tun‐
684       ing constants in hardware device drivers....not where you want to look
685       for bugs).
686
687       With all the options, this module needs a good tutorial. It doesn't
688       have one yet.
689

EXAMPLE

691       It is recommended to always use "read(255)" due to some unexpected
692       behavior with the termios under some operating systems (Linux and
693       Solaris at least).  To deal with this, a routine is usually needed to
694       read from the serial port until you have what you want.  This is a
695       quick example of how to do that:
696
697        my $port=Device::SerialPort->new("/dev/ttyS0");
698
699        my $STALL_DEFAULT=10; # how many seconds to wait for new input
700
701        my $timeout=$STALL_DEFAULT;
702
703        $port->read_char_time(0);     # don't wait for each character
704        $port->read_const_time(1000); # 1 second per unfulfilled "read" call
705
706        my $chars=0;
707        my $buffer="";
708        while ($timeout>0) {
709               my ($count,$saw)=$port->read(255); # will read _up to_ 255 chars
710               if ($count > 0) {
711                       $chars+=$count;
712                       $buffer.=$saw;
713
714                       # Check here to see if what we want is in the $buffer
715                       # say "last" if we find it
716               }
717               else {
718                       $timeout--;
719               }
720        }
721
722        if ($timeout==0) {
723               die "Waited $STALL_DEFAULT seconds and never saw what I wanted\n";
724        }
725

PORTING

727       For a serial port to work under Unix, you need the ability to do sev‐
728       eral types of operations.  With POSIX, these operations are implemented
729       with a set of "tc*" functions.  However, not all Unix systems follow
730       this correctly.  In those cases, the functions change, but the vari‐
731       ables used as parameters generally turn out to be the same.
732
733       Get/Set RTS
734           This is only available through the bit-set(TIOCM‐
735           BIS)/bit-clear(TIOCMBIC) ioctl function using the RTS
736           value(TIOCM_RTS).
737
738            ioctl($handle,$on ? $TIOCMBIS : $TIOCMBIC, $TIOCM_RTS);
739
740       Get/Set DTR
741           This is available through the bit-set(TIOCMBIS)/bit-clear(TIOCMBIC)
742           ioctl function using the DTR value(TIOCM_DTR)
743
744            ioctl($handle,$on ? $TIOCMBIS : $TIOCMBIC, $TIOCM_DTR);
745
746           or available through the DTRSET/DTRCLEAR ioctl functions, if they
747           exist.
748
749            ioctl($handle,$on ? $TIOCSDTR : $TIOCCDTR, 0);
750
751       Get modem lines
752           To read Clear To Send (CTS), Data Set Ready (DSR), Ring Indicator
753           (RING), and Carrier Detect (CD/RLSD), the TIOCMGET ioctl function
754           must be used.
755
756            ioctl($handle, $TIOCMGET, $status);
757
758           To decode the individual modem lines, some bits have multiple pos‐
759           sible constants:
760
761           Clear To Send (CTS)
762               TIOCM_CTS
763
764           Data Set Ready (DSR)
765               TIOCM_DSR
766
767           Ring Indicator (RING)
768               TIOCM_RNG TIOCM_RI
769
770           Carrier Detect (CD/RLSD)
771               TIOCM_CAR TIOCM_CD
772
773       Get Buffer Status
774           To get information about the state of the serial port input and
775           output buffers, the TIOCINQ and TIOCOUTQ ioctl functions must be
776           used.  I'm not totally sure what is returned by these functions
777           across all Unix systems.  Under Linux, it is the integer number of
778           characters in the buffer.
779
780            ioctl($handle,$in ? $TIOCINQ : $TIOCOUTQ, $count);
781            $count = unpack('i',$count);
782
783       Get Line Status
784           To get information about the state of the serial transmission line
785           (to see if a write has made its way totally out of the serial port
786           buffer), the TIOCSERGETLSR ioctl function must be used.  Addition‐
787           ally, the "Get Buffer Status" methods must be functioning, as well
788           as having the first bit of the result set (Linux is TIOCSER_TEMT,
789           others unknown, but we've been using TIOCM_LE even though that
790           should be returned from the TIOCMGET ioctl).
791
792            ioctl($handle,$TIOCSERGETLSR, $status);
793            $done = (unpack('i', $status) & $TIOCSER_TEMT);
794
795       Set Flow Control
796           Some Unix systems require special TCGETX/TCSETX ioctls functions
797           and the CTSXON/RTSXOFF constants to turn on and off CTS/RTS "hard"
798           flow control instead of just using the normal POSIX tcsetattr
799           calls.
800
801            ioctl($handle, $TCGETX, $flags);
802            @bytes = unpack('SSSS',$flags);
803            $bytes[0] = $on ? ($CTSXON ⎪ $RTSXOFF) : 0;
804            $flags = pack('SSSS',@bytes);
805            ioctl($handle, $TCSETX, $flags);
806

KNOWN LIMITATIONS

808       The current version of the module has been tested with Perl 5.003 and
809       above. It was initially ported from Win32 and was designed to be used
810       without requiring a compiler or using XS. Since everything is (some‐
811       times convoluted but still pure) Perl, you can fix flaws and change
812       limits if required. But please file a bug report if you do.
813
814       The read method, and tied methods which call it, currently can use a
815       fixed timeout which approximates behavior of the Win32::SerialPort
816       read_const_time and read_char_time methods. It is used internally by
817       select. If the timeout is set to zero, the read call will return imme‐
818       diately. A read larger than 255 bytes will be split internally into
819       255-byte POSIX calls due to limitations of select and VMIN.  The time‐
820       out is reset for each 255-byte segment. Hence, for large reads, use a
821       read_const_time suitable for a 255-byte read. All of this is expeimen‐
822       tal in Version 0.055.
823
824         $PortObj->read_const_time(500);       # 500 milliseconds = 0.5 seconds
825         $PortObj->read_char_time(5);          # avg time between read char
826
827       The timing model defines the total time allowed to complete the opera‐
828       tion.  A fixed overhead time is added to the product of bytes and
829       per_byte_time.
830
831       Read_Total = read_const_time + (read_char_time * bytes_to_read)
832
833       Write timeouts and read_interval timeouts are not currently supported.
834
835       On some machines, reads larger than 4,096 bytes may be truncated at
836       4,096, regardless of the read size or read timing settings used. In
837       this case, try turning on or increasing the inter-character delay on
838       your serial device. Also try setting the read size to
839
840         $PortObj->read(1) or $PortObj->read(255)
841
842       and performing multiple reads until the transfer is completed.
843

BUGS

845       See the limitations about lockfiles. Experiment if you like.
846
847       With all the currently unimplemented features, we don't need any more.
848       But there probably are some.
849
850       Please send comments and bug reports to kees@outflux.net.
851

Win32::SerialPort & Win32API::CommPort

853       Win32::SerialPort Functions Not Currently Supported
854
855         $LatchErrorFlags = $PortObj->reset_error;
856
857         $PortObj->read_interval(100);         # max time between read char
858         $PortObj->write_char_time(5);
859         $PortObj->write_const_time(100);
860
861       Functions Handled in a POSIX system by "stty"
862
863               xon_limit       xoff_limit      xon_char        xoff_char
864               eof_char        event_char      error_char      stty_intr
865               stty_quit       stty_eof        stty_eol        stty_erase
866               stty_kill       stty_clear      is_stty_clear   stty_bsdel
867               stty_echoke     stty_echoctl    stty_ocrnl      stty_onlcr
868
869       Win32::SerialPort Functions Not Ported to POSIX
870
871               transmit_char
872
873       Win32API::CommPort Functions Not Ported to POSIX
874
875               init_done       fetch_DCB       update_DCB      initialize
876               are_buffers     are_baudrate    are_handshake   are_parity
877               are_databits    are_stopbits    is_handshake    xmit_imm_char
878               is_baudrate     is_parity       is_databits     is_write_char_time
879               debug_comm      is_xon_limit    is_xoff_limit   is_read_const_time
880               suspend_tx      is_eof_char     is_event_char   is_read_char_time
881               is_read_buf     is_write_buf    is_buffers      is_read_interval
882               is_error_char   resume_tx       is_stopbits     is_write_const_time
883               is_binary       is_status       write_bg        is_parity_enable
884               is_modemlines   read_bg         read_done       break_active
885               xoff_active     is_read_buf     is_write_buf    xon_active
886
887       "raw" Win32 API Calls and Constants
888
889       A large number of Win32-specific elements have been omitted. Most of
890       these are only available in Win32::SerialPort and Win32API::CommPort as
891       optional Exports. The list includes the following:
892
893       :RAW
894           The API Wrapper Methods and Constants used only to support them
895           including PURGE_*, SET*, CLR*, EV_*, and ERROR_IO*
896
897       :COMMPROP
898           The Constants used for Feature and Properties Detection including
899           BAUD_*, PST_*, PCF_*, SP_*, DATABITS_*, STOPBITS_*, PARITY_*, and
900           COMMPROP_INITIALIZED
901
902       :DCB
903           The constants for the Win32 Device Control Block including CBR_*,
904           DTR_*, RTS_*, *PARITY, *STOPBIT*, and FM_*
905
906       Compatibility
907
908       This code implements the functions required to support the MisterHouse
909       Home Automation software by Bruce Winter. It does not attempt to sup‐
910       port functions from Win32::SerialPort such as stty_emulation that
911       already have POSIX implementations or to replicate Win32 idosyncracies.
912       However, the supported functions are intended to clone the equivalent
913       functions in Win32::SerialPort and Win32API::CommPort. Any discrepan‐
914       cies or omissions should be considered bugs and reported to the main‐
915       tainer.
916

AUTHORS

918        Based on Win32::SerialPort.pm, Version 0.8, by Bill Birthisel
919        Ported to linux/POSIX by Joe Doss for MisterHouse
920        Ported to Solaris/POSIX by Kees Cook for Sendpage
921        Ported to BSD/POSIX by Kees Cook
922        Ported to Perl XS by Kees Cook
923
924        Currently maintained by:
925        Kees Cook, kees@outflux.net, http://outflux.net/
926

SEE ALSO

928       Win32API::CommPort
929
930       Win32::SerialPort
931
932       perltoot - Tom Christiansen's Object-Oriented Tutorial
933
935        Copyright (C) 1999, Bill Birthisel. All rights reserved.
936        Copyright (C) 2000-2004, Kees Cook.  All rights reserved.
937
938       This module is free software; you can redistribute it and/or modify it
939       under the same terms as Perl itself.
940
941
942
943perl v5.8.8                       2004-11-09                     SerialPort(3)
Impressum