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

NAME

6       Device::SerialPort - Linux/POSIX emulation of Win32::SerialPort
7       functions.
8

SYNOPSIS

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

DESCRIPTION

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

PINOUT

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

NOTES

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

EXAMPLE

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

PORTING

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

KNOWN LIMITATIONS

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

BUGS

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

Win32::SerialPort & Win32API::CommPort

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

AUTHORS

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

SEE ALSO

925       Win32API::CommPort
926
927       Win32::SerialPort
928
929       perltoot - Tom Christiansen's Object-Oriented Tutorial
930
932        Copyright (C) 1999, Bill Birthisel. All rights reserved.
933        Copyright (C) 2000-2007, Kees Cook.  All rights reserved.
934
935       This module is free software; you can redistribute it and/or modify it
936       under the same terms as Perl itself.
937

POD ERRORS

939       Hey! The above document had some coding errors, which are explained
940       below:
941
942       Around line 2647:
943           You can't have =items (as at line 2653) unless the first thing
944           after the =over is an =item
945
946       Around line 2737:
947           You can't have =items (as at line 2747) unless the first thing
948           after the =over is an =item
949
950
951
952perl v5.30.0                      2019-07-26                     SerialPort(3)
Impressum