- NAME
- SYNOPSIS
  - Constructors
  - Configuration Utility Methods
  - Configuration Parameter Methods
  - Operating Methods
  - Methods used with Tied FileHandles
  - Destructors
  - Methods for I/O Processing
  - Capability Methods inherited from Win32API::CommPort
  - Operating Methods inherited from Win32API::CommPort
- DESCRIPTION
  - Initialization
  - Configuration and Capability Methods
  - Exports
  - Stty Emulation
  - Lookfor and I/O Processing
- NOTES
- KNOWN LIMITATIONS
- BUGS
- AUTHORS
- SEE ALSO
- COPYRIGHT
  - COMPATIBILITY

# NAME

Win32::SerialPort - User interface to Win32 Serial API calls

# SYNOPSIS

      require 5.003;
      use Win32::SerialPort qw( :STAT 0.19 );

## Constructors

      $PortObj = new Win32::SerialPort ($PortName, $quiet)
           || die "Can't open $PortName: $^E\n";    # $quiet is optional

      $PortObj = start Win32::SerialPort ($Configuration_File_Name)
           || die "Can't start $Configuration_File_Name: $^E\n";

      $PortObj = tie (*FH, 'Win32::SerialPort', $Configuration_File_Name)
           || die "Can't tie using $Configuration_File_Name: $^E\n";

## Configuration Utility Methods

      $PortObj->alias("MODEM1");

         # before using start, restart, or tie
      $PortObj->save($Configuration_File_Name)
           || warn "Can't save $Configuration_File_Name: $^E\n";

         # after new, must check for failure
      $PortObj->write_settings || undef $PortObj;
      print "Can't change Device_Control_Block: $^E\n" unless ($PortObj);

         # rereads file to either return open port to a known state
         # or switch to a different configuration on the same port
      $PortObj->restart($Configuration_File_Name)
           || warn "Can't reread $Configuration_File_Name: $^E\n";

         # "app. variables" saved in $Configuration_File, not used internally
      $PortObj->devicetype('none');     # CM11, CM17, 'weeder', 'modem'
      $PortObj->hostname('localhost');  # for socket-based implementations
      $PortObj->hostaddr(0);            # false unless specified
      $PortObj->datatype('raw');        # in case an application needs_to_know
      $PortObj->cfg_param_1('none');    # null string '' hard to save/restore
      $PortObj->cfg_param_2('none');    # 3 spares should be enough for now
      $PortObj->cfg_param_3('none');    # one may end up as a log file path

         # specials for test suite only
      @necessary_param = Win32::SerialPort->set_test_mode_active(1);
      $PortObj->lookclear("loopback to next 'input' method");

## Configuration Parameter Methods

         # most methods can be called three ways:
      $PortObj->handshake("xoff");           # set parameter
      $flowcontrol = $PortObj->handshake;    # current value (scalar)
      @handshake_opts = $PortObj->handshake; # permitted choices (list)

         # similar
      $PortObj->baudrate(9600);
      $PortObj->parity("odd");
      $PortObj->databits(8);
      $PortObj->stopbits(1);

         # range parameters return (minimum, maximum) in list context
      $PortObj->xon_limit(100);      # bytes left in buffer
      $PortObj->xoff_limit(100);     # space left in buffer
      $PortObj->xon_char(0x11);
      $PortObj->xoff_char(0x13);
      $PortObj->eof_char(0x0);
      $PortObj->event_char(0x0);
      $PortObj->error_char(0);       # for parity errors

      $PortObj->buffers(4096, 4096);  # read, write
            # returns current in list context

      $PortObj->read_interval(100);    # max time between read char (milliseconds)
      $PortObj->read_char_time(5);     # avg time between read char
      $PortObj->read_const_time(100);  # total = (avg * bytes) + const
      $PortObj->write_char_time(5);
      $PortObj->write_const_time(100);

         # true/false parameters (return scalar context only)

      $PortObj->binary(T);          # just say Yes (Win 3.x option)
      $PortObj->parity_enable(F);   # faults during input
      $PortObj->debug(0);

## Operating Methods

      ($BlockingFlags, $InBytes, $OutBytes, $LatchErrorFlags) = $PortObj->status
            || warn "could not get port status\n";

      if ($BlockingFlags) { warn "Port is blocked"; }
      if ($BlockingFlags & BM_fCtsHold) { warn "Waiting for CTS"; }
      if ($LatchErrorFlags & CE_FRAME) { warn "Framing Error"; }
            # The API resets errors when reading status, $LatchErrorFlags
            # is all $ErrorFlags seen since the last reset_error

Additional useful constants may be exported eventually. If the only fault action desired is a message, status provides Built-In BitMask processing:

      $PortObj->error_msg(1);  # prints hardware messages like "Framing Error"
      $PortObj->user_msg(1);   # prints function messages like "Waiting for CTS"

      ($count_in, $string_in) = $PortObj->read($InBytes);
      warn "read unsuccessful\n" unless ($count_in == $InBytes);

      $count_out = $PortObj->write($output_string);
      warn "write failed\n"         unless ($count_out);
      warn "write incomplete\n"     if ( $count_out != length($output_string) );

      if ($string_in = $PortObj->input) { PortObj->write($string_in); }
         # simple echo with no control character processing

      $PortObj->transmit_char(0x03);        # bypass buffer (and suspend)

      $ModemStatus = $PortObj->modemlines;
      if ($ModemStatus & $PortObj->MS_RLSD_ON) { print "carrier detected"; }

## Methods used with Tied FileHandles

      $PortObj = tie (*FH, 'Win32::SerialPort', $Configuration_File_Name)
           || die "Can't tie: $^E\n";            ## TIEHANDLE ##

      print FH "text";                           ## PRINT     ##
      $char = getc FH;                           ## GETC      ##
      syswrite FH, $out, length($out), 0;        ## WRITE     ##
      $line = <FH>;                              ## READLINE  ##
      @lines = <FH>;                             ## READLINE  ##
      printf FH "received: %s", $line;           ## PRINTF    ##
      read (FH, $in, 5, 0) or die "$^E";         ## READ      ##
      sysread (FH, $in, 5, 0) or die "$^E";      ## READ      ##
      close FH || warn "close failed";           ## CLOSE     ##
      undef $PortObj;
      untie *FH;                                 ## DESTROY   ##

      $PortObj->linesize(10);               # with READLINE
      $PortObj->lastline("_GOT_ME_");       # with READLINE, list only

      $old_ors = $PortObj->output_record_separator("RECORD");       # with PRINT
      $old_ofs = $PortObj->output_field_separator("COMMA");         # with PRINT

## Destructors

      $PortObj->close || warn "close failed";
          # passed to CommPort to release port to OS - needed to reopen
          # close will not usually DESTROY the object
          # also called as: close FH || warn "close failed";

      undef $PortObj;
          # preferred unless reopen expected since it triggers DESTROY
          # calls $PortObj->close but does not confirm success
          # MUST precede untie - do all three IN THIS SEQUENCE before re-tie.

      untie *FH;

## Methods for I/O Processing

      $PortObj->are_match("text", "\n");    # possible end strings
      $PortObj->lookclear;                  # empty buffers
      $PortObj->write("Feed Me:");          # initial prompt
      $PortObj->is_prompt("More Food:");    # new prompt after "kill" char

      my $gotit = "";
      my $match1 = "";
      until ("" ne $gotit) {
          $gotit = $PortObj->lookfor;       # poll until data ready
          die "Aborted without match\n" unless (defined $gotit);
          last if ($gotit);
          $match1 = $PortObj->matchclear;   # match is first thing received
          last if ($match1);
          sleep 1;                          # polling sample time
      }

      printf "gotit = %s\n", $gotit;                # input BEFORE the match
      my ($match, $after, $pattern, $instead) = $PortObj->lastlook;
          # input that MATCHED, input AFTER the match, PATTERN that matched
          # input received INSTEAD when timeout without match

      if ($match1) {
          $match = $match1;
      }
      printf "lastlook-match = %s  -after = %s  -pattern = %s\n",
                               $match,      $after,        $pattern;

      $gotit = $PortObj->lookfor($count);   # block until $count chars received

      $PortObj->are_match("-re", "pattern", "text");
          # possible match strings: "pattern" is a regular expression,
          #                         "text" is a literal string

      $gotit = $PortObj->streamline;        # poll until data ready
      $gotit = $PortObj->streamline($count);# block until $count chars received
          # fast alternatives to lookfor with no character processing

      $PortObj->stty_intr("\cC");   # char to abort lookfor method
      $PortObj->stty_quit("\cD");   # char to abort perl
      $PortObj->stty_eof("\cZ");    # end_of_file char
      $PortObj->stty_eol("\cJ");    # end_of_line char
      $PortObj->stty_erase("\cH");  # delete one character from buffer (backspace)
      $PortObj->stty_kill("\cU");   # clear line buffer

      $PortObj->is_stty_intr(3);    # ord(char) to abort lookfor method
      $qc = $PortObj->is_stty_quit; # ($qc == 4) for "\cD"
      $PortObj->is_stty_eof(26);
      $PortObj->is_stty_eol(10);
      $PortObj->is_stty_erase(8);
      $PortObj->is_stty_kill(21);

      my $air = " "x76;
      $PortObj->stty_clear("\r$air\r");     # written after kill character
      $PortObj->is_stty_clear;              # internal version for config file
      $PortObj->stty_bsdel("\cH \cH");      # written after erase character

      $PortObj->stty_echo(0);       # echo every character
      $PortObj->stty_echoe(1);      # if echo erase character with bsdel string
      $PortObj->stty_echok(1);      # if echo \n after kill character
      $PortObj->stty_echonl(0);     # if echo \n
      $PortObj->stty_echoke(1);     # if echo clear string after kill character
      $PortObj->stty_echoctl(0);    # if echo "^Char" for control chars
      $PortObj->stty_istrip(0);     # strip input to 7-bits
      $PortObj->stty_icrnl(0);      # map \r to \n on input
      $PortObj->stty_ocrnl(0);      # map \r to \n on output
      $PortObj->stty_igncr(0);      # ignore \r on input
      $PortObj->stty_inlcr(0);      # map \n to \r on input
      $PortObj->stty_onlcr(1);      # map \n to \r\n on output
      $PortObj->stty_opost(0);      # enable output mapping
      $PortObj->stty_isig(0);       # enable quit and intr characters
      $PortObj->stty_icanon(0);     # enable erase and kill characters

      $PortObj->stty("-icanon");    # disable eof, erase and kill char, Unix-style
      @stty_all = $PortObj->stty(); # get all the parameters, Perl-style

## Capability Methods inherited from Win32API::CommPort

These return scalar context only.

      can_baud            can_databits           can_stopbits
      can_dtrdsr          can_handshake          can_parity_check
      can_parity_config   can_parity_enable      can_rlsd
      can_16bitmode       is_rs232               is_modem
      can_rtscts          can_xonxoff            can_xon_char
      can_spec_char       can_interval_timeout   can_total_timeout
      buffer_max          can_rlsd_config

## Operating Methods inherited from Win32API::CommPort

      write_bg            write_done             read_bg
      read_done           reset_error            suspend_tx
      resume_tx           dtr_active             rts_active
      break_active        xoff_active            xon_active
      purge_all           purge_rx               purge_tx
      pulse_rts_on        pulse_rts_off          pulse_dtr_on
      pulse_dtr_off       ignore_null            ignore_no_dsr
      subst_pe_char       abort_on_error         output_xoff
      output_dsr          output_cts             tx_on_xoff
      input_xoff          get_tick_count

# DESCRIPTION

This module uses Win32API::CommPort for raw access to the API calls and related constants. It provides an object-based user interface to allow higher-level use of common API call sequences for dealing with serial ports.

Uses features of the Win32 API to implement non-blocking I/O, serial parameter setting, event-loop operation, and enhanced error handling.

To pass in `NULL` as the pointer to an optional buffer, pass in `$null=0`. This is expected to change to an empty list reference, `[]`, when Perl supports that form in this usage.

## Initialization

The primary constructor is new with a PortName (as the Registry knows it) specified. This will create an object, and get the available options and capabilities via the Win32 API. The object is a superset of a Win32API::CommPort object, and supports all of its methods. The port is not yet ready for read/write access. First, the desired parameter settings must be established. Since these are tuning constants for an underlying hardware driver in the Operating System, they are all checked for validity by the methods that set them. The write_settings method writes a new Device Control Block to the driver. The write_settings method will return true if the port is ready for access or `undef` on failure. Ports are opened for binary transfers. A separate `binmode` is not needed. The USER must release the object if write_settings does not succeed.

Version 0.15 adds an optional `$quiet` parameter to new. Failure to open a port prints a error message to STDOUT by default. Since only one application at a time can ``own'' the port, one source of failure was ``port in use''. There was previously no way to check this without getting a ``fail message''. Setting `$quiet` disables this built-in message. It also returns 0 instead of `undef` if the port is unavailable (still FALSE, used for testing this condition - other faults may still return `undef`). Use of `$quiet` only applies to new.

Certain parameters MUST be set before executing write_settings. Others will attempt to deduce defaults from the hardware or from other parameters. The Required parameters are:

baudrate
  Any legal value.

parity
  One of the following: ``none'', ``odd'', ``even'', ``mark'', ``space''. If you select anything except ``none'', you will need to set parity_enable.

databits
  An integer from 5 to 8.

stopbits
  Legal values are 1, 1.5, and 2. But 1.5 only works with 5 databits, 2 does not work with 5 databits, and other combinations may not work on all hardware if parity is also used.

The handshake setting is recommended but no longer required. Select one of the following: ``none'', ``rts'', ``xoff'', ``dtr''.

Some individual parameters (eg. baudrate) can be changed after the initialization is completed. These will be validated and will update the Device Control Block as required. The save method will write the current parameters to a file that start, tie, and restart can use to reestablish a functional setup.

      $PortObj = new Win32::SerialPort ($PortName, $quiet)
           || die "Can't open $PortName: $^E\n";    # $quiet is optional

      $PortObj->user_msg(ON);
      $PortObj->databits(8);
      $PortObj->baudrate(9600);
      $PortObj->parity("none");
      $PortObj->stopbits(1);
      $PortObj->handshake("rts");
      $PortObj->buffers(4096, 4096);

      $PortObj->write_settings || undef $PortObj;

      $PortObj->save($Configuration_File_Name);

      $PortObj->baudrate(300);
      $PortObj->restart($Configuration_File_Name);  # back to 9600 baud

      $PortObj->close || die "failed to close";
      undef $PortObj;                               # frees memory back to perl

The PortName maps to both the Registry Device Name and the Properties associated with that device. A single Physical port can be accessed using two or more Device Names. But the options and setup data will differ significantly in the two cases. A typical example is a Modem on port ``COM2''. Both of these PortNames open the same Physical hardware:

      $P1 = new Win32::SerialPort ("COM2");

      $P2 = new Win32::SerialPort ("\\\\.\\Nanohertz Modem model K-9");

`$P1` is a ``generic'' serial port. `$P2` includes all of `$P1` plus a variety of modem-specific added options and features. The ``raw'' API calls return different size configuration structures in the two cases. Win32 uses the ``\\.\'' prefix to identify ``named'' devices. Since both names use the same Physical hardware, they can not both be used at the same time. The OS will complain. Consider this A Good Thing. Use alias to convert the name used by ``built-in'' messages.

      $P2->alias("FIDO");

The second constructor, start is intended to simplify scripts which need a constant setup. It executes all the steps from new to write_settings based on a previously saved configuration. This constructor will return `undef` on a bad configuration file or failure of a validity check. The returned object is ready for access.

      $PortObj2 = start Win32::SerialPort ($Configuration_File_Name)
           || die;

The third constructor, tie, combines the start with Perl's support for tied FileHandles (see perltie). Win32::SerialPort implements the complete set of methods: TIEHANDLE, PRINT, PRINTF, WRITE, READ, GETC, READLINE, CLOSE, and DESTROY. Tied FileHandle support was new with Version 0.14.

      $PortObj2 = tie (*FH, 'Win32::SerialPort', $Configuration_File_Name)
           || die;

The implementation attempts to mimic STDIN/STDOUT behaviour as closely as possible: calls block until done, data strings that exceed internal buffers are divided transparently into multiple calls, and stty_onlcr and stty_ocrnl are applied to output data (WRITE, PRINT, PRINTF) when stty_opost is true. In Version 0.17, the output separators `$,` and `$\` are also applied to PRINT if set. Since PRINTF is treated internally as a single record PRINT, `$\` will be applied. Output separators are not applied to WRITE (called as `syswrite FH, $scalar, $length, [$offset]`).

The output_record_separator and output_field_separator methods can set Port-FileHandle-Specific versions of `$,` and `$\` if desired. The input_record_separator `$/` is not explicitly supported - but an identical function can be obtained with a suitable are_match setting. Record separators are experimental in Version 0.17. They are not saved in the configuration_file.

The tied FileHandle methods may be combined with the Win32::SerialPort methods for read, input, and write as well as other methods. The typical restrictions against mixing print with syswrite do not apply. Since both (tied) read and sysread call the same `$ob->READ` method, and since a separate `$ob->read` method has existed for some time in Win32::SerialPort, you should always use sysread with the tied interface. Beginning in Version 0.17, sysread checks the input against stty_icrnl, stty_inlcr, and stty_igncr. With stty_igncr active, the sysread returns the count of all characters received including and `\r` characters subsequently deleted.

Because all the tied methods block, they should ALWAYS be used with timeout settings and are not suitable for background operations and polled loops. The sysread method may return fewer characters than requested when a timeout occurs. The method call is still considered successful. If a sysread times out after receiving some characters, the actual elapsed time may be as much as twice the programmed limit. If no bytes are received, the normal timing applies.

## Configuration and Capability Methods

Starting in Version 0.18, a number of Application Variables are saved in $Configuration_File. These parameters are not used internally. But methods allow setting and reading them. The intent is to facilitate the use of separate configuration scripts to create the files. Then an application can use start as the Constructor and not bother with command line processing or managing its own small configuration file. The default values and number of parameters is subject to change.

      $PortObj->devicetype('none');
      $PortObj->hostname('localhost');  # for socket-based implementations
      $PortObj->hostaddr(0);            # a "false" value
      $PortObj->datatype('raw');        # 'record' is another possibility
      $PortObj->cfg_param_1('none');
      $PortObj->cfg_param_2('none');    # 3 spares should be enough for now
      $PortObj->cfg_param_3('none');

The Win32 Serial Comm API provides extensive information concerning the capabilities and options available for a specific port (and instance). ``Modem'' ports have different capabilties than ``RS-232'' ports - even if they share the same Hardware. Many traditional modem actions are handled via TAPI. ``Fax'' ports have another set of options - and are accessed via MAPI. Yet many of the same low-level API commands and data structures are ``common'' to each type (``Modem'' is implemented as an ``RS-232'' superset). In addition, Win95 supports a variety of legacy hardware (e.g fixed 134.5 baud) while WinNT has hooks for ISDN, 16-data-bit paths, and 256Kbaud.

Binary selections will accept as true any of the following: `("YES", "Y", "ON", "TRUE", "T", "1", 1)` (upper/lower/mixed case) Anything else is false.

There are a large number of possible configuration and option parameters. To facilitate checking option validity in scripts, most configuration methods can be used in three different ways:

method called with an argument
  The parameter is set to the argument, if valid. An invalid argument returns false (undef) and the parameter is unchanged. The function will also carp if $user_msg is true. After write_settings, the port will be updated immediately if allowed. Otherwise, the value will be applied when write_settings is called.

method called with no argument in scalar context
  The current value is returned. If the value is not initialized either directly or by default, return ``undef'' which will parse to false. For binary selections (true/false), return the current value. All current values from ``multivalue'' selections will parse to true. Current values may differ from requested values until write_settings. There is no way to see requests which have not yet been applied. Setting the same parameter again overwrites the first request. Test the return value of the setting method to check ``success''.

method called with no argument in list context
  Return a list consisting of all acceptable choices for parameters with discrete choices. Return a list `(minimum, maximum)` for parameters which can be set to a range of values. Binary selections have no need to call this way - but will get `(0,1)` if they do. Beginning in Version 0.16, Binary selections inherited from Win32API::CommPort may not return anything useful in list context. The null list `(undef)` will be returned for failed calls in list context (e.g. for an invalid or unexpected argument).

Asynchronous (Background) I/O
  The module handles Polling (do if Ready), Synchronous (block until Ready), and Asynchronous Modes (begin and test if Ready) with the timeout choices provided by the API. No effort has yet been made to interact with Windows events. But background I/O has been used successfully with the Perl Tk modules and callbacks from the event loop.

Timeouts
  The API provides two timing models. The first applies only to reading and essentially determines Read Not Ready by checking the time between consecutive characters. The ReadFile operation returns if that time exceeds the value set by read_interval. It does this by timestamping each character. It appears that at least one character must by received in every read call to the API to initialize the mechanism. The timer is then reset by each succeeding character. If no characters are received, the read will block indefinitely.

  Setting read_interval to `0xffffffff` will do a non-blocking read. The ReadFile returns immediately whether or not any characters are actually read. This replicates the behavior of the API.

  The other model defines the total time allowed to complete the operation. A fixed overhead time is added to the product of bytes and per_byte_time. A wide variety of timeout options can be defined by selecting the three parameters: fixed, each, and size.

  Read_Total = read_const_time + (read_char_time * bytes_to_read)

  Write_Total = write_const_time + (write_char_time * bytes_to_write)

  When reading a known number of characters, the Read_Total mechanism is recommended. This mechanism MUST be used with tied FileHandles because the tie methods can make multiple internal API calls in response to a single sysread or READLINE. The Read_Interval mechanism is suitable for a read method that expects a response of variable or unknown size. You should then also set a long Read_Total timeout as a ``backup'' in case no bytes are received.

## Exports

Nothing is exported by default. Nothing is currently exported. Optional tags from Win32API::CommPort are passed through.

:PARAM
  Utility subroutines and constants for parameter setting and test:

              LONGsize        SHORTsize       nocarp          yes_true
              OS_Error        internal_buffer

:STAT
  Serial communications constants from Win32API::CommPort. Included are the constants for ascertaining why a transmission is blocked:

              BM_fCtsHold     BM_fDsrHold     BM_fRlsdHold    BM_fXoffHold
              BM_fXoffSent    BM_fEof         BM_fTxim        BM_AllBits

  Which incoming bits are active:

              MS_CTS_ON       MS_DSR_ON       MS_RING_ON      MS_RLSD_ON

  What hardware errors have been detected:

              CE_RXOVER       CE_OVERRUN      CE_RXPARITY     CE_FRAME
              CE_BREAK        CE_TXFULL       CE_MODE

  Offsets into the array returned by status:

              ST_BLOCK        ST_INPUT        ST_OUTPUT       ST_ERROR

## Stty Emulation

Nothing wrong with dreaming! A subset of stty options is available through a stty method. The purpose is support of existing serial devices which have embedded knowledge of Unix communication line and login practices. It is also needed by Tom Christiansen's Perl Power Tools project. This is new and experimental in Version 0.15. The stty method returns an array of ``traditional stty values'' when called with no arguments. With arguments, it sets the corresponding parameters.

      $ok = $PortObj->stty("-icanon");      # equivalent to stty_icanon(0)
      @stty_all = $PortObj->stty();         # get all the parameters, Perl-style
      $ok = $PortObj->stty("cs7",19200);    # multiple parameters
      $ok = $PortObj->stty(@stty_save);     # many parameters

The distribution includes a demo script, stty.plx, which gives details of usage. Not all Unix parameters are currently supported. But the array will contain all those which can be set. The order in `@stty_all` will match the following pattern:

      baud,                 # numeric, always first
      "intr", character,    # the parameters which set special characters
      "name", character, ...
      "stop", character,    # "stop" will always be the last "pair"
      "parameter",          # the on/off settings
      "-parameter", ...

Version 0.13 added the primitive functions required to implement this feature. A number of methods named stty_xxx do what an experienced stty user would expect. Unlike stty on Unix, the stty_xxx operations apply only to I/O processed via the lookfor method or the tied FileHandle methods. The read, input, read_done, write methods all treat data as ``raw''.

            The following stty functions have related SerialPort functions:
            ---------------------------------------------------------------
            stty (control)          SerialPort              Default Value
            ----------------        ------------------      -------------
            parenb inpck            parity_enable           from port

            parodd                  parity                  from port

            cs5 cs6 cs7 cs8         databits                from port

            cstopb                  stopbits                from port

            clocal crtscts          handshake               from port
            ixon ixoff              handshake               from port

            time                    read_const_time         from port

            110 300 600 1200 2400   baudrate                from port
            4800 9600 19200 38400   baudrate

            75 134.5 150 1800       fixed baud only - not selectable

            g, "stty < /dev/x"      start, save             none

            sane                    restart                 none

            stty (input)            SerialPort              Default Value
            ----------------        ------------------      -------------
            istrip                  stty_istrip             off

            igncr                   stty_igncr              off

            inlcr                   stty_inlcr              off

            icrnl                   stty_icrnl              on

            parmrk                  error_char              from port (off typ)

            stty (output)           SerialPort              Default Value
            ----------------        ------------------      -------------
            ocrnl                   stty_ocrnl              off if opost

            onlcr                   stty_onlcr              on if opost

            opost                   stty_opost              off

            stty (local)            SerialPort              Default Value
            ----------------        ------------------      -------------
            raw                     read, write, input      none

            cooked                  lookfor                 none

            echo                    stty_echo               off

            echoe                   stty_echoe              on if echo

            echok                   stty_echok              on if echo

            echonl                  stty_echonl             off

            echoke                  stty_echoke             on if echo

            echoctl                 stty_echoctl            off

            isig                    stty_isig               off

            icanon                  stty_icanon             off

            stty (char)             SerialPort              Default Value
            ----------------        ------------------      -------------
            intr                    stty_intr               "\cC"
                                    is_stty_intr            3

            quit                    stty_quit               "\cD"
                                    is_stty_quit            4

            erase                   stty_erase              "\cH"
                                    is_stty_erase           8

            (erase echo)            stty_bsdel              "\cH \cH"

            kill                    stty_kill               "\cU"
                                    is_stty_kill            21

            (kill echo)             stty_clear              "\r {76}\r"
                                    is_stty_clear           "-@{76}-"

            eof                     stty_eof                "\cZ"
                                    is_stty_eof             26

            eol                     stty_eol                "\cJ"
                                    is_stty_eol             10

            start                   xon_char                from port ("\cQ" typ)
                                    is_xon_char             17

            stop                    xoff_char               from port ("\cS" typ)
                                    is_xoff_char            19

            The following stty functions have no equivalent in SerialPort:
            --------------------------------------------------------------
            [-]hup          [-]ignbrk       [-]brkint       [-]ignpar
            [-]tostop       susp            0               50
            134             200             exta            extb
            [-]cread        [-]hupcl

The stty function list is taken from the documentation for IO::Stty by Austin Schutz.

## Lookfor and I/O Processing

Many of the stty_xxx methods support features which are necessary for line-oriented input (such as command-line handling). These include methods which select control-keys to delete characters (stty_erase) and lines (stty_kill), define input boundaries (stty_eol, stty_eof), and abort processing (stty_intr, stty_quit). These keys also have is_stty_xxx methods which convert the key-codes to numeric equivalents which can be saved in the configuration file.

Some communications programs have a different but related need - to collect (or discard) input until a specific pattern is detected. For lines, the pattern is a line-termination. But there are also requirements to search for other strings in the input such as ``username:'' and ``password:''. The lookfor method provides a consistant mechanism for solving this problem. It searches input character-by-character looking for a match to any of the elements of an array set using the are_match method. It returns the entire input up to the match pattern if a match is found. If no match is found, it returns ``'' unless an input error or abort is detected (which returns undef).

The actual match and the characters after it (if any) may also be viewed using the lastlook method. In Version 0.13, the match test included a `s/$pattern//s` test which worked fine for literal text but returned the Regular Expression that matched when `$pattern` contained any Perl metacharacters. That was probably a bug - although no one reported it.

In Version 0.14, lastlook returns both the input and the pattern from the match test. It also adopts the convention from Expect.pm that match strings are literal text (tested using index) unless preceeded in the are_match list by a "-re", entry. The default are_match list is `("\n")`, which matches complete lines.

       my ($match, $after, $pattern, $instead) = $PortObj->lastlook;
         # input that MATCHED, input AFTER the match, PATTERN that matched
         # input received INSTEAD when timeout without match ("" if match)

       $PortObj->are_match("text1", "-re", "pattern", "text2");
         # possible match strings: "pattern" is a regular expression,
         #                         "text1" and "text2" are literal strings

The Regular Expression handling in lookfor is still experimental. Please let me know if you use it (or can't use it), so I can confirm bug fixes don't break your code. For literal strings, `$match` and `$pattern` should be identical. The `$instead` value returns the internal buffer tested by the match logic. A successful match or a lookclear resets it to ``'' - so it is only useful for error handling such as timeout processing or reporting unexpected responses.

The lookfor method is designed to be sampled periodically (polled). Any characters after the match pattern are saved for a subsequent lookfor. Internally, lookfor is implemented using the nonblocking input method when called with no parameter. If called with a count, lookfor calls `$PortObj->read(count)` which blocks until the read is Complete or a Timeout occurs. The blocking alternative should not be used unless a fault time has been defined using read_interval, read_const_time, and read_char_time. It exists mostly to support the tied FileHandle functions sysread, getc, and <FH>.

The internal buffers used by lookfor may be purged by the lookclear method (which also clears the last match). For testing, lookclear can accept a string which is ``looped back'' to the next input. This feature is enabled only when `set_test_mode_active(1)`. Normally, lookclear will return `undef` if given parameters. It still purges the buffers and last_match in that case (but nothing is ``looped back''). You will want stty_echo(0) when exercising loopback.

Version 0.15 adds a matchclear method. It is designed to handle the ``special case'' where the match string is the first `character(s)` received by lookfor. In this case, `$lookfor_return == ""`, lookfor does not provide a clear indication that a match was found. The matchclear returns the same `$match` that would be returned by lastlook and resets it to ``'' without resetting any of the other buffers. Since the lookfor already searched through the match, matchclear is used to both detect and step-over ``blank'' lines.

The character-by-character processing used by lookfor to support the stty emulation is fine for interactive activities and tasks which expect short responses. But it has too much ``overhead'' to handle fast data streams. Version 0.15 adds a streamline method which is a fast, line-oriented alternative with no echo support or input handling except for pattern searching. Exact benchmarks will vary with input data and patterns, but my tests indicate streamline is 10-20 times faster then lookfor when uploading files averaging 25-50 characters per line. Since streamline uses the same internal buffers, the lookclear, lastlook, are_match, and matchclear methods act the same in both cases. In fact, calls to streamline and lookfor can be interleaved if desired (e.g. an interactive task that starts an upload and returns to interactive activity when it is complete).

Beginning in Version 0.15, the READLINE method supports ``list context''. A tied FileHandle can slurp in a whole file with an ``@lines = <FH>`` construct. In ''scalar context``, READLINE calls lookfor. But it calls streamline in ``list context''. Both contexts also call matchclear to detect ``empty'' lines and reset_error to detect hardware problems. The existance of a hardware fault is reported with `$^E`, although the specific fault is only reported when error_msg is true.

There are two additional methods for supporting ``list context'' input: lastline sets an ``end_of_file'' Regular Expression, and linesize permits changing the ``packet size'' in the blocking read operation to allow tuning performance to data characteristics. These two only apply during READLINE. The default for linesize is 1. There is no default for the lastline method.

In Version 0.15, Regular Expressions set by are_match and lastline will be pre-compiled using the qr// construct on Perl 5.005 and higher. This doubled lookfor and streamline speed in my tests with Regular Expressions - but actual improvements depend on both patterns and input data.

The functionality of lookfor includes a limited subset of the capabilities found in Austin Schutz's Expect.pm for Unix (and Tcl's expect which it resembles). The `$before, $match, $pattern, and $after` return values are available if someone needs to create an ``expect'' subroutine for porting a script. When using multiple patterns, there is one important functional difference: Expect.pm looks at each pattern in turn and returns the first match found; lookfor and streamline test all patterns and return the one found earliest in the input if more than one matches.

Because lookfor can be used to manage a command-line environment much like a Unix serial login, a number of ``stty-like'' methods are included to handle the issues raised by serial logins. One issue is dissimilar line terminations. This is addressed by the following methods:

      $PortObj->stty_icrnl;         # map \r to \n on input
      $PortObj->stty_igncr;         # ignore \r on input
      $PortObj->stty_inlcr;         # map \n to \r on input
      $PortObj->stty_ocrnl;         # map \r to \n on output
      $PortObj->stty_onlcr;         # map \n to \r\n on output
      $PortObj->stty_opost;         # enable output mapping

The default specifies a raw device with no input or output processing. In Version 0.14, the default was a device which sends ``\r'' at the end of a line, requires ``\r\n'' to terminate incoming lines, and expects the ``host'' to echo every keystroke. Many ``dumb terminals'' act this way and the defaults were similar to Unix defaults. But some users found this ackward and confusing.

Sometimes, you want perl to echo input characters back to the serial device (and other times you don't want that).

      $PortObj->stty_echo;          # echo every character
      $PortObj->stty_echoe;         # if echo erase with bsdel string (default)
      $PortObj->stty_echok;         # if echo \n after kill character (default)
      $PortObj->stty_echonl;        # echo \n even if stty_echo(0)
      $PortObj->stty_echoke;        # if echo clear string after kill (default)
      $PortObj->stty_echoctl;       # if echo "^Char" for control chars

      $PortObj->stty_istrip;        # strip input to 7-bits

      my $air = " "x76;             # overwrite entire line with spaces
      $PortObj->stty_clear("\r$air\r");     # written after kill character
      $PortObj->is_prompt("PROMPT:");       # need to write after kill
      $PortObj->stty_bsdel("\cH \cH");      # written after erase character

      # internal method that permits clear string with \r in config file
      my $plus32 = "@"x76;          # overwrite line with spaces (ord += 32)
      $PortObj->is_stty_clear("-$plus32-"); # equivalent to stty_clear

# NOTES

The object returned by new or start is NOT a FileHandle. You will be disappointed if you try to use it as one. If you need a FileHandle, you must use tie as the constructor.

e.g. the following is WRONG!!____`print $PortObj "some text";`

You need something like this (Perl 5.005):

            # construct
        $tie_ob = tie(*FOO,'Win32::SerialPort', $cfgfile)
                     or die "Can't start $cfgfile\n";

        print FOO "enter char: "; # destination is FileHandle, not Object
        my $in = getc FOO;
        syswrite FOO, "$in\n", 2, 0;
        print FOO "enter line: ";
        $in = <FOO>;
        printf FOO "received: %s\n", $in;
        print FOO "enter 5 char: ";
        sysread (FOO, $in, 5, 0) or die;
        printf FOO "received: %s\n", $in;

            # destruct
        close FOO || print "close failed\n";
        undef $tie_ob;      # Don't forget this one!!
        untie *FOO;

Always include the `undef $tie_ob` before the untie. See the Gotcha description in perltie.

The Perl 5.004 implementation of tied FileHandles is missing close and syswrite. The Perl 5.003 version is essentially unusable. If you need these functions, consider Perl 5.005 seriously.

An important note about Win32 filenames. The reserved device names such as ``

     COM1, AUX, LPT1, CON, PRN

can NOT be used as filenames. Hence "COM2.cfg" would not be usable for $Configuration_File_Name.

Thanks to Ken White for testing on NT.

There is a linux clone of this module implemented using POSIX.pm. It also runs on AIX and Solaris, and will probably run on other POSIX systems as well. It does not currently support the complete set of methods - although portability of user programs is excellent for the calls it does support. It is available from CPAN as Device::SerialPort.

# KNOWN LIMITATIONS

Since everything is (sometimes convoluted but still pure) Perl, you can fix flaws and change limits if required. But please file a bug report if you do. This module has been tested with each of the binary perl versions for which Win32::API is supported: AS builds 315, 316, 500-509 and GS 5.004_02. It has only been tested on Intel hardware.

Although the lookfor, stty_xxx, and Tied FileHandle mechanisms are considered stable, they have only been tested on a small subset of possible applications. While ``\r'' characters may be included in the clear string using is_stty_clear internally, ``\n'' characters may NOT be included in multi-character strings if you plan to save the strings in a configuration file (which uses ``\n'' as an internal terminator).

Tutorial
  With all the options, this module needs a good tutorial. It doesn't have a complete one yet. A "How to get started" tutorial appeared The Perl Journal #13 (March 1999). Examples from the article are available from http://tpj.com and from http://members.aol.com/Bbirthisel. The demo programs in the distribution are a good starting point for additional examples.

Buffers
  The size of the Win32 buffers are selectable with buffers. But each read method currently uses a fixed internal buffer of 4096 bytes. This can be changed in the Win32API::CommPort source and read with internal_buffer. The XS version will support dynamic buffer sizing. Large operations are automatically converted to multiple smaller ones by the tied FileHandle methods.

Modems
  Lots of modem-specific options are not supported. The same is true of TAPI, MAPI. API Wizards are welcome to contribute.

API Options
  Lots of options are just ``passed through from the API''. Some probably shouldn't be used together. The module validates the obvious choices when possible. For something really fancy, you may need additional API documentation. Available from Micro$oft Pre$$.

# BUGS

On Win32, a port must close before it can be reopened again by the same process. If a physical port can be accessed using more than one name (see above), all names are treated as one. The perl script can also be run multiple times within a single batch file or shell script. The Makefile.PL spawns subshells with backticks to run the test suite on Perl 5.003 - ugly, but it works.

On NT, a read_done or write_done returns False if a background operation is aborted by a purge. Win95 returns True.

EXTENDED_OS_ERROR ($^E) is not supported by the binary ports before 5.005. It ``sort-of-tracks'' $! in 5.003 and 5.004, but YMMV.

A few NT systems seem to set can_parity_enable true, but do not actually support setting parity_enable. This may be a characteristic of certain third-party serial drivers.

__Please send comments and bug reports to wcbirthisel@alum.mit.edu.

# AUTHORS

Bill Birthisel, wcbirthisel@alum.mit.edu, http://members.aol.com/Bbirthisel/.

Tye McQueen, tye@metronet.com, http://www.metronet.com/~tye/.

# SEE ALSO

Win32API::CommPort - the low-level API calls which support this module

Win32API::File when available

Win32::API - Aldo Calpini's ``Magic'', http://www.divinf.it/dada/perl/

Perltoot.xxx - Tom (Christiansen)'s Object-Oriented Tutorial

Expect.pm - Austin Schutz's adaptation of TCL's ``expect'' for Unix Perls

# COPYRIGHT

Copyright (C) 1999, Bill Birthisel. All rights reserved.

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

## COMPATIBILITY

Most of the code in this module has been stable since version 0.12. Except for items indicated as Experimental, I do not expect functional changes which are not fully backwards compatible. However, Version 0.16 removes the ``dummy (0, 1) list'' which was returned by many binary methods in case they were called in list context. I do not know of any use outside the test suite for that feature.

Version 0.12 added an Install.PL script to put modules into the documented Namespaces. The script uses MakeMaker tools not available in ActiveState 3xx builds. Users of those builds will need to install differently (see README). Programs in the test suite are modified for the current version. Additions to the configurtion files generated by save prevent those created by Version 0.18 from being used by earlier Versions. 4 November 1999.