Win32::SerialPort - User interface to Win32 Serial API calls
use Win32; require 5.003; use Win32::SerialPort qw( :STAT 0.10 );
$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 # test suite only @necessary_param = SerialPort->set_test_mode_active;
($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
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
$PortObj = dosmode Win32::SerialPort ($MS_Dos_Mode_String) || die "Can't complete dosmode open: $^E\n"; ($complete, $count_in, $string_in) = $PortObj->readline($prompt); $PortObj->readline_end("\012"); $PortObj->echo(OFF); # input from a terminal (readline) # a number of others to provide "stty-like" settings $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);
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.
NULL
$null=0
[]
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.
undef
binmode
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.
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 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.
MS-DOS 6.x "MODE" command
$PortObj3 = dosmode Win32::SerialPort ($MS_Dos_Mode_String) || die "Can't complete dosmode open: $^E\n";
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.
("YES", "Y", "ON", "TRUE", "T", "1", 1)
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 $error_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. The null list (undef) will be returned for failed calls in list context (e.g. for an invalid or unexpected argument).
(minimum, maximum)
(0,1)
(undef)
Nothing is exported by default. Nothing is currently exported. Optional tags from Win32API::CommPort are passed through.
Utility subroutines and constants for parameter setting and test:
LONGsize SHORTsize nocarp Yes_true OS_Error
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
Nothing wrong with dreaming! At some point in the future, a limited subset of stty options may be available through a stty method. The purpose would be support of existing serial devices which have embedded knowledge of Unix communication line and login practices.
Until that time, the following table shows correspondance between stty and SerialPort functions:
The following stty functions have equivalents in SerialPort: ------------------------------------------------------------ stty functions related SerialPort functions -------------------- ---------------------------- parenb -parenb parity_enable parodd -parodd parity cs5 cs6 cs7 cs8 databits cstopb -cstopb stopbits clocal -clocal ixon -ixon handshake ixoff -ixoff xon_limit, xoff_limit parmrk -parmrk error_char sane restart start xon_char stop xoff_char time read_const_time 110 300 600 1200 2400 baudrate 4800 9600 19200 38400 baudrate 75 134.5 150 1800 fixed baud only - not selectable -g, "stty < /dev/x" start, save raw read, write -icanon input The following stty functions will have equivalents in SerialPort after readline (canonical processing) is implemented: ---------------------------------------------------------------- stty functions related SerialPort functions -------------------- ---------------------------- intr intr_char eof eof_char eol readline_end cooked icanon readline noflsh -noflsh purge_all, purge_rx, purge_tx Equivalents for the following stty functions are expected but have not yet been defined in SerialPort: ------------------------------------------------------------- [-]istrip [-]inlcr [-]igncr [-]icrnl [-]isig [-]echo [-]echoe [-]crterase [-]echok [-]echonl ek [-]pass8 dec erase kill min The following stty functions have no equivalent in SerialPort: -------------------------------------------------------------- -a -v [-]cread [-]hupcl [-]hup [-]ignbrk [-]brkint [-]ignpar [-]inpck [-]opost [-]tostop susp quit 0 50 134 200 exta extb
The stty function list is taken from the documentation for IO::Stty by Austin Schutz.
The object returned by new or start is NOT a Filehandle. You will be disappointed if you try to use it as one.
e.g. the following is WRONG!!____print $PortObj "some text";
print $PortObj "some text";
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.
COM1, AUX, LPT1, CON, PRN
Thanks to Ken White for testing on NT.
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, and 500 and GS 5.004_02. It has only been tested on Intel hardware.
With all the options, this module needs a good tutorial. It doesn't have one yet. The demo programs are a good starting point.
The size of the Win32 buffers are selectable with buffers. But each read method currently uses a fixed internal buffer of 4096 bytes. There are other fixed internal buffers as well. The XS version will support dynamic buffer sizing.
Lots of modem-specific options are not supported. The same is true of TAPI, MAPI. Of course, API Wizards are welcome to contribute.
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$$.
This version now 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 TK events (or Windows events).
The API provides two timing models. The first applies only to read 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 to initialize the mechanism.
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 Win32, a port which has been closed cannot 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. Exiting and rerunning the script is ok. The perl script can also be run multiple times within a singe batch file or shell script.
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.
Bill Birthisel, wcbirthisel@alum.mit.edu, http://members.aol.com/Bbirthisel/.
Tye McQueen, tye@metronet.com, http://www.metronet.com/~tye/.
Win32API::Comm - 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
Copyright (C) 1998, 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.
This is still Beta code and may be subject to functional changes which are not fully backwards compatible. This module is NOT ready for production use. Consider the lack of an Install program to be a feature and run in a "standalone" directory. 29 Aug 1998.
2 POD Errors
The following errors were encountered while parsing the POD:
You can't have =items (as at line 873) unless the first thing after the =over is an =item
You can't have =items (as at line 982) unless the first thing after the =over is an =item
To install SerialPort, copy and paste the appropriate command in to your terminal.
cpanm
cpanm SerialPort
CPAN shell
perl -MCPAN -e shell install SerialPort
For more information on module installation, please visit the detailed CPAN module installation guide.