use Win32; require 5.003; use Win32::SerialPort qw( :STAT 0.13 );
$PortObj = new Win32::SerialPort ($PortName) || die "Can't open $PortName: $^E\n";
$PortObj = start Win32::SerialPort ($Configuration_File_Name) || die "Can't start $Configuration_File_Name: $^E\n";
$PortObj->alias("MODEM1");
# before using start $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";
# 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.5); $PortObj->debug(0);
# 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
# specials for test suite only @necessary_param = Win32::SerialPort->set_test_mode_active(1); $PortObj->lookclear("loopback to next 'input' method");
($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 major messages like "Framing Error" $PortObj->user_msg(1); # prints minor 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"; }
$PortObj->close; ## passed to CommPort; undef $PortObj preferred
$PortObj->are_match("pattern", "\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 = ""; until ("" ne $gotit) { $gotit = $PortObj->lookfor; # poll until data ready die "Aborted without match\n" unless (defined $gotit); sleep 1; # polling sample time }
printf "gotit = %s\n", $gotit; # input before the match my ($match, $after) = $PortObj->lastlook; # match and input after printf "lastlook-match = %s -after = %s\n", $match, $after;
$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(1); # echo every character $PortObj->stty_echoe(1); # echo erase character with bsdel string $PortObj->stty_echok(1); # echo \n after kill character $PortObj->stty_echonl(0); # echo \n $PortObj->stty_echoke(1); # echo clear string after kill character $PortObj->stty_echoctl(0); # echo "^Char" for control chars $PortObj->stty_istrip(0); # strip input to 7-bits $PortObj->stty_icrnl(1); # 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_isig(0); # enable quit and intr characters $PortObj->stty_icanon(1); # enable erase and kill characters
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
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
# no demand for this one yet - may never exist $PortObj = dosmode Win32::SerialPort ($MS_Dos_Mode_String) || die "Can't complete dosmode open: $^E\n";
$PortObj->ignore_null(No); $PortObj->ignore_no_dsr(No); $PortObj->abort_on_error("no"); $PortObj->subst_pe_char("no");
$PortObj->accept_xoff(F); # hold during output $PortObj->accept_dsr(F); $PortObj->accept_cts(F); $PortObj->send_xoff(N); $PortObj->tx_on_xoff(Y);
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.
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.
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:
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 and restart can use to reestablish a functional setup.
$PortObj = new Win32::SerialPort ($PortName) || die "Can't open $PortName: $^E\n";
$PortObj->user_msg(ON); $PortObj->databits(8); $PortObj->baudrate(9600); $PortObj->parity("none"); $PortObj->stopbits(1.5); $PortObj->handshake("rts"); $PortObj->buffers(4096, 4096);
$PortObj->write_settings || undef $PortObj;
$PortObj->save($Configuration_File_Name);
$PortObj->baudrate(300);
undef $PortObj; # closes port AND frees memory in 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;
A possible third constructor, dosmode, is a further simplification. The parameters are specified as in the MS-DOS 6.x "MODE" command
. Unspecified parameters would be set to plausible ``DOS like'' defaults.
Once created, all of the parameter settings would be available.
$PortObj3 = dosmode Win32::SerialPort ($MS_Dos_Mode_String) || die "Can't complete dosmode open: $^E\n";
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:
(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. The null list
(undef)
will be returned for failed calls in list context (e.g. for an invalid or
unexpected argument).
LONGsize SHORTsize nocarp Yes_true OS_Error
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
Version 0.13 adds the primative functions required to implement this feature. There is not a unified stty method yet. But 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. 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 ixon crtscts handshake from port ixoff xon_limit, xoff_limit 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 onlcr stty_onlcr on
stty (local) SerialPort Default Value ---------------- ------------------ ------------- raw read, write, input none cooked lookfor none echo stty_echo on echoe stty_echoe on echok stty_echok on echonl stty_echonl off echoke stty_echoke on echoctl stty_echoctl off
isig stty_isig off
icanon stty_icanon on 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) stop xoff_char from port ("\cS" typ) The following stty functions have no equivalent in SerialPort: -------------------------------------------------------------- -a -v [-]cread [-]hupcl [-]hup [-]ignbrk [-]brkint [-]ignpar [-]opost [-]tostop susp 0 50 134 200 exta extb
The stty function list is taken from the documentation for IO::Stty by Austin Schutz.
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 before 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 lookfor method is designed to be sampled periodically (polled). Any characters
after the match pattern are saved for a subsequent
lookfor. The actual match and the characters after it (if any) may also be viewed
using the lastlook method. The default are_match list is
("\n")
which matches complete lines.
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.
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, $after
return values are available if someone needs to create an ``expect''
subroutine for porting a script.
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 (default) $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 (default)
The default specifies a device which sends ``\r'' at the end of a line and requires ``\r\n'' to terminate incoming lines. Many ``dumb terminals'' act this way.
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 (default) $PortObj->stty_echoe; # echo erase with bsdel string (default) $PortObj->stty_echok; # echo \n after kill character (default) $PortObj->stty_echonl; # echo \n $PortObj->stty_echoke; # echo clear string after kill (default) $PortObj->stty_echoctl; # 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
e.g. the following is WRONG!!____print $PortObj "some text";
An important note about Win32 filenames. The reserved device names such as
can NOT be used as filenames. Hence
"COM2.cfg" would not be usable for $Configuration_File_Name.
COM1, AUX, LPT1, CON, PRN
Thanks to Ken White for testing on NT.
The lookfor and stty_xxx mechanisms should be considered experimental. The 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).
There have been several changes to the configuration file. You should rewrite any existing files.
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)
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.
__Please send comments and bug reports to wcbirthisel@alum.mit.edu.
Tye McQueen, tye@metronet.com, http://www.metronet.com/~tye/.
Win32API::File when available
Win32::API - Aldo Calpini's ``Magic'', http://www.divinf.it/dada/perl/
Perltoot.xxx - Tom (Christiansen)'s Object-Oriented Tutorial
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.