NAME
Win32API::CommPort - Raw Win32 system API calls for serial communications.
SYNOPSIS
use Win32;
require 5.003;
use Win32API::CommPort qw( :STAT 0.10 );
## when available ## use Win32API::File 0.05 qw( :ALL );
Constructors
$PortObj = new Win32API::CommPort ($PortName)
|| die "Can't open $PortName: $^E\n";
@required = qw( BAUD DATA STOP );
$faults = $PortObj->initialize(@required);
if ($faults) { die "Required parameters not set before initialize\n"; }
Configuration Utility Methods
set_no_messages; # test suite use
nocarp || carp "Something fishy";
$a = SHORTsize;
$a = LONGsize;
$answer = Yes_true("choice");
OS_Error unless ($API_Call_OK);
$PortObj->init_done || die "Not done";
$PortObj->fetch_DCB || die "Not done";
$PortObj->update_DCB || die "Not done";
Capability Methods (read only)
# true/false capabilities
$a = $PortObj->can_baud; # else fixed
$a = $PortObj->can_databits;
$a = $PortObj->can_stopbits;
$a = $PortObj->can_dtrdsr;
$a = $PortObj->can_handshake;
$a = $PortObj->can_parity_check;
$a = $PortObj->can_parity_config;
$a = $PortObj->can_parity_enable;
$a = $PortObj->can_rlsd; # receive line signal detect (carrier)
$a = $PortObj->can_rlsd_config;
$a = $PortObj->can_16bitmode;
$a = $PortObj->is_rs232;
$a = $PortObj->is_modem;
$a = $PortObj->can_rtscts;
$a = $PortObj->can_xonxoff;
$a = $PortObj->can_xon_char;
$a = $PortObj->can_spec_char;
$a = $PortObj->can_interval_timeout;
$a = $PortObj->can_total_timeout;
# list output capabilities
($rmax, $wmax) = $PortObj->buffer_max;
($rbuf, $wbuf) = $PortObj->are_buffers; # current
@choices = $PortObj->are_baudrate; # legal values
@choices = $PortObj->are_handshake;
@choices = $PortObj->are_parity;
@choices = $PortObj->are_databits;
@choices = $PortObj->are_stopbits;
Configuration Methods
# most methods can be called two ways:
$PortObj->is_handshake("xoff"); # set parameter
$flowcontrol = $PortObj->is_handshake; # current value (scalar)
# similar
$PortObj->is_baudrate(9600);
$PortObj->is_parity("odd");
$PortObj->is_databits(8);
$PortObj->is_stopbits(1.5);
$PortObj->debug_comm(0);
$PortObj->is_xon_limit(100); # bytes left in buffer
$PortObj->is_xoff_limit(100); # space left in buffer
$PortObj->is_xon_char(0x11);
$PortObj->is_xoff_char(0x13);
$PortObj->is_eof_char(0x0);
$PortObj->is_event_char(0x0);
$PortObj->is_error_char(0); # for parity errors
$rbuf = $PortObj->is_read_buf; # read_only except internal use
$wbuf = $PortObj->is_write_buf;
$PortObj->is_buffers(4096, 4096); # read, write
# returns current in list context
$PortObj->is_read_interval(100); # max time between read char (millisec)
$PortObj->is_read_char_time(5); # avg time between read char
$PortObj->is_read_const_time(100); # total = (avg * bytes) + const
$PortObj->is_write_char_time(5);
$PortObj->is_write_const_time(100);
$PortObj->is_binary(T); # just say Yes (Win 3.x option)
$PortObj->is_parity_enable(F); # faults during input
Operating Methods
($BlockingFlags, $InBytes, $OutBytes, $LatchErrorFlags) = $PortObj->is_status
|| warn "could not get port status\n";
$ClearedErrorFlags = $PortObj->reset_error;
# The API resets errors when reading status, $LatchErrorFlags
# is all $ErrorFlags since they were last explicitly cleared
if ($BlockingFlags) { warn "Port is blocked"; }
if ($BlockingFlags & BM_fCtsHold) { warn "Waiting for CTS"; }
if ($LatchErrorFlags & CE_FRAME) { warn "Framing Error"; }
Additional useful constants may be exported eventually.
$count_in = $PortObj->read_bg($InBytes);
($done, $count_in, $string_in) = $PortObj->read_done(1);
# background read with wait until done
$count_out = $PortObj->write_bg($output_string); # background write
($done, $count_out) = $PortObj->write_done(0);
$PortObj->suspend_tx; # output from write buffer
$PortObj->resume_tx;
$PortObj->xmit_imm_char(0x03); # bypass buffer (and suspend)
$PortObj->dtr_active(T); # direct to hardware
$PortObj->rts_active(Yes); # returns status of API call
$PortObj->break_active(N); # NOT state of bit
$PortObj->xoff_active; # simulate received xoff
$PortObj->xon_active; # simulate received xon
$PortObj->purge_all;
$PortObj->purge_rx;
$PortObj->purge_tx;
$ModemStatus = $PortObj->is_modemlines;
if ($ModemStatus & $PortObj->MS_RLSD_ON) { print "carrier detected"; }
$PortObj->close; ## undef $PortObj preferred
DESCRIPTION
This provides fairly low-level access to the Win32 System API calls 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.
Beyond raw access to the API calls and related constants, this module will eventually handle smart buffer allocation and translation of return codes.
Initialization
The constructor is new with a PortName (as the Registry knows it) specified. This will do a CreateFile, get the available options and capabilities via the Win32 API, and create the object. 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 should all checked for validity by the method calls that set them. The initialize method takes a list of required parameters and confirms they have been set. For others, it will attempt to deduce defaults from the hardware or from other parameters. The initialize method returns the number of faults (zero if the port is setup ok). The update_DCB method writes a new Device Control Block to complete the startup and allow the port to be used. Ports are opened for binary transfers. A separate binmode
is not needed. The USER must release the object if initialize or update_DCB does not succeed.
The fault checking in initialize consists in verifying an _N_$item internal variable exists for each $item in the input list. The _N_$item is created for each parameter that is set either directly or by default. A derived class must create the _N_$items for any varibles it adds to the base class if it wants initialize to check them. Win32API::Comm supports the following:
$item _N_$item setting method
------ --------- --------------
BAUD "_N_BAUD" is_baudrate
BINARY "_N_BINARY" is_binary
DATA "_N_DATA" is_databits
EOFCHAR "_N_EOFCHAR" is_eof_char
ERRCHAR "_N_ERRCHAR" is_error_char
EVTCHAR "_N_EVTCHAR" is_event_char
HSHAKE "_N_HSHAKE" is_handshake
PARITY "_N_PARITY" is_parity
PARITY_EN "_N_PARITY_EN" is_parity_enable
RCONST "_N_RCONST" is_read_const_time
READBUF "_N_READBUF" is_read_buf
RINT "_N_RINT" is_read_interval
RTOT "_N_RTOT" is_read_char_time
STOP "_N_STOP" is_stopbits
WCONST "_N_WCONST" is_write_const_time
WRITEBUF "_N_WRITEBUF" is_write_buf
WTOT "_N_WTOT" is_write_char_time
XOFFCHAR "_N_XOFFCHAR" is_xoff_char
XOFFLIM "_N_XOFFLIM" is_xoff_limit
XONCHAR "_N_XONCHAR" is_xon_char
XONLIM "_N_XONLIM" is_xon_limit
Some individual parameters (eg. baudrate) can be changed after the initialization is completed. These will automatically update the Device Control Block as required. The init_done method indicates when initialize has completed successfully.
$PortObj = new Win32API::CommPort ($PortName)
|| die "Can't open $PortName: $^E\n";
if $PortObj->can_databits { $PortObj->is_databits(8) };
$PortObj->is_baudrate(9600);
$PortObj->is_parity("none");
$PortObj->is_stopbits(1.5);
$PortObj->is_handshake("rts");
$PortObj->is_buffers(4096, 4096);
$PortObj->dtr_active(T);
@required = qw( BAUD DATA STOP PARITY );
$PortObj->initialize(@required) || undef $PortObj;
$PortObj->dtr_active(f);
$PortObj->is_baudrate(300);
$PortObj->close;
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 Win32API::CommPort ("COM2");
$P2 = new Win32API::CommPort ("\\\\.\\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.
Configuration and Capability Methods
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 two 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. After init_done, the port will be updated immediately if allowed. Otherwise, the value will be applied when update_DCB 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 init_done. 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".
Exports
Nothing is exported by default. Nothing is currently exported. The following tags can be used to have large sets of symbols exported:
- :PARAM
-
Utility subroutines and constants for parameter setting and test:
LONGsize SHORTsize nocarp Yes_true OS_Error
- :STAT
-
Serial communications status constants. 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
- :RAW
-
The constants and objects for low-level API calls. These are likely to change with testing. Some may be inherited from Win32API::File when that becomes available.
$result=$ClearCommError->Call($handle, $Error_BitMask_p, $CommStatus); $result=$ClearCommBreak->Call($handle); $result=$SetCommBreak->Call($handle); $result=$GetCommModemStatus->Call($handle, $ModemStatus); $result=$GetCommProperties->Call($handle, $CommProperties); $result=$GetCommState->Call($handle, $DCB_Buffer); $result=$SetCommState->Call($handle, $DCB_Buffer); $result=$SetupComm->Call($handle, $in_buf_size, $out_buf_size); $result=$ReadFile->Call($handle, $buffer, $wanted, $got, $template); $result=$WriteFile->Call($handle, $buffer, $size, $count, $template); $error=$GetLocalError->Call(); $result=$GetCommTimeouts->Call($handle, $CommTimeOuts); $result=$SetCommTimeouts->Call($handle, $CommTimeOuts); $result=$EscapeCommFunction->Call($handle, $Func_ID); $result=$GetCommConfig->Call($handle, $CommConfig, $Size); $result=$SetCommConfig->Call($handle, $CommConfig, $Size); $result=$PurgeComm->Call($handle, $flags); $result=$GetCommMask->Call($handle, $Event_Bitmask); $result=$SetCommMask->Call($handle, $Event_Bitmask); $hEvent=$CreateEvent->Call($security, $reset_req, $initial, $name); $handle=$CreateFile->Call($file, $access, $share, $security, $creation, $flags, $template); $result=$CloseHandle->Call($handle); $result=$ResetEvent->Call($hEvent); $result=$TransmitCommChar->Call($handle, $char); $result=$WaitCommEvent->Call($handle, $Event_Bitmask, $lpOverlapped); $result=$GetOverlappedResult->Call($handle, $lpOverlapped, $count, $bool);
Flags used by $PurgeComm:
PURGE_TXABORT PURGE_RXABORT PURGE_TXCLEAR PURGE_RXCLEAR
Function IDs used by $EscapeCommFunction:
SETXOFF SETXON SETRTS CLRRTS SETDTR CLRDTR SETBREAK CLRBREAK
Events used by $WaitCommEvent:
EV_RXCHAR EV_RXFLAG EV_TXEMPTY EV_CTS EV_DSR EV_RLSD EV_BREAK EV_ERR EV_RING EV_PERR EV_RX80FULL EV_EVENT1 EV_EVENT2
Errors specific to $GetOverlappedResult:
ERROR_IO_INCOMPLETE ERROR_IO_PENDING
- :COMMPROP
-
The constants for the $CommProperties structure returned by $GetCommProperties. Included mostly for completeness.
BAUD_USER BAUD_075 BAUD_110 BAUD_134_5 BAUD_150 BAUD_300 BAUD_600 BAUD_1200 BAUD_1800 BAUD_2400 BAUD_4800 BAUD_7200 BAUD_9600 BAUD_14400 BAUD_19200 BAUD_38400 BAUD_56K BAUD_57600 BAUD_115200 BAUD_128K PST_FAX PST_LAT PST_MODEM PST_PARALLELPORT PST_RS232 PST_RS422 PST_X25 PST_NETWORK_BRIDGE PST_RS423 PST_RS449 PST_SCANNER PST_TCPIP_TELNET PST_UNSPECIFIED PCF_INTTIMEOUTS PCF_PARITY_CHECK PCF_16BITMODE PCF_DTRDSR PCF_SPECIALCHARS PCF_RLSD PCF_RTSCTS PCF_SETXCHAR PCF_TOTALTIMEOUTS PCF_XONXOFF SP_BAUD SP_DATABITS SP_HANDSHAKING SP_PARITY SP_RLSD SP_STOPBITS SP_SERIALCOMM SP_PARITY_CHECK DATABITS_5 DATABITS_6 DATABITS_7 DATABITS_8 DATABITS_16 DATABITS_16X STOPBITS_10 STOPBITS_15 STOPBITS_20 PARITY_SPACE PARITY_NONE PARITY_ODD PARITY_EVEN PARITY_MARK COMMPROP_INITIALIZED
- :DCB
-
The constants for the Device Control Block returned by $GetCommState and updated by $SetCommState. Again, included mostly for completeness. But there are some combinations of "FM_f" settings which are not currrently supported by high-level commands. If you need one of those, please report the lack as a bug.
CBR_110 CBR_300 CBR_600 CBR_1200 CBR_2400 CBR_4800 CBR_9600 CBR_14400 CBR_19200 CBR_38400 CBR_56000 CBR_57600 CBR_115200 CBR_128000 CBR_256000 DTR_CONTROL_DISABLE DTR_CONTROL_ENABLE DTR_CONTROL_HANDSHAKE RTS_CONTROL_DISABLE RTS_CONTROL_ENABLE RTS_CONTROL_HANDSHAKE RTS_CONTROL_TOGGLE EVENPARITY MARKPARITY NOPARITY ODDPARITY SPACEPARITY ONESTOPBIT ONE5STOPBITS TWOSTOPBITS FM_fBinary FM_fParity FM_fOutxCtsFlow FM_fOutxDsrFlow FM_fDtrControl FM_fDsrSensitivity FM_fTXContinueOnXoff FM_fOutX FM_fInX FM_fErrorChar FM_fNull FM_fRtsControl FM_fAbortOnError FM_fDummy2
- :ALL
-
All of the above. Except for the test suite, there is not really a good reason to do this.
NOTES
The object returned by new 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";
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.
This module uses Win32API extensively. The raw API calls are very unforgiving. You will certainly want to start perl with the -w switch. If you can, use strict as well. Try to ferret out all the syntax and usage problems BEFORE issuing the API calls (many of which modify tuning constants in hardware device drivers....not where you want to look for bugs).
Thanks to Ken White for testing on NT.
KNOWN LIMITATIONS
The current version of the module has been designed for testing using the ActiveState and Core (GS 5.004_02) ports of perl for Win32 without requiring a compiler or using XS. In every case, compatibility has been selected over performance. 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.
- Tutorial
-
With all the options, this module needs a good tutorial. It doesn't have one yet. The demo programs with Win32::SerialPort provide a starting point for common functions.
- Buffers
-
The size of the Win32 buffers are selectable with is_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.
- Modems
-
Lots of modem-specific options are not supported. The same is true of TAPI, MAPI. Of course, 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$$.
- Asynchronous (Background) I/O
-
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).
- Timeouts
-
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 is_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 = is_read_const_time + (is_read_char_time * bytes_to_read)
Write_total = is_write_const_time + (is_write_char_time * bytes_to_write)
BUGS
ActiveState ports of Perl for Win32 before build 500 do not support the tools for building extensions and so will not support later versions of this extension.
There is no parameter checking on the "raw" API calls. You probably should be familiar with using the calls in "C" before doing much experimenting.
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.
AUTHORS
Bill Birthisel, wcbirthisel@alum.mit.edu, http://members.aol.com/Bbirthisel/.
Tye McQueen, tye@metronet.com, http://www.metronet.com/~tye/.
SEE ALSO
Wi32::SerialPort - High-level user interface/front-end for 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
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.
DISCLAIMER
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.
1 POD Error
The following errors were encountered while parsing the POD:
- Around line 2278:
You can't have =items (as at line 2288) unless the first thing after the =over is an =item