Win32API::CommPort - Raw Win32 system API calls for serial communications. |
Win32API::CommPort - Raw Win32 system API calls for serial communications.
use Win32; ## not required under all circumstances require 5.006; use Win32API::CommPort qw( :PARAM :STAT 0.20 );
## when available ## use Win32API::File 0.07 qw( :ALL );
$PortObj = new Win32API::CommPort ($PortName, $quiet) || die "Can't open $PortName: $^E\n"; # $quiet is optional
@required = qw( BAUD DATA STOP ); $faults = $PortObj->initialize(@required); if ($faults) { die "Required parameters not set before initialize\n"; }
set_no_messages(1); # test suite use
# exported by :PARAM nocarp || carp "Something fishy"; $a = SHORTsize; # 0xffff $a = LONGsize; # 0xffffffff $answer = yes_true("choice"); # 1 or 0 OS_Error unless ($API_Call_OK); # prints error
$PortObj->init_done || die "Not done";
$PortObj->fetch_DCB || die "Not done"; $PortObj->update_DCB || die "Not done";
$milliseconds = $PortObj->get_tick_count;
# 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->can_ioctl; # false, unix only $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;
# 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); $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; $size = $PortObj->internal_buffer;
$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
($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->xoff_active; # simulate received xoff $PortObj->xon_active; # simulate received xon
$PortObj->purge_all; $PortObj->purge_rx; $PortObj->purge_tx;
# controlling outputs from the port $PortObj->dtr_active(T); # sends outputs direct to hardware $PortObj->rts_active(Yes); # returns status of API call $PortObj->break_active(N); # NOT state of bit
$PortObj->pulse_break_on($milliseconds); # off version is implausible $PortObj->pulse_rts_on($milliseconds); $PortObj->pulse_rts_off($milliseconds); $PortObj->pulse_dtr_on($milliseconds); $PortObj->pulse_dtr_off($milliseconds); # sets_bit, delays, resets_bit, delays
$ModemStatus = $PortObj->is_modemlines; if ($ModemStatus & $PortObj->MS_RLSD_ON) { print "carrier detected"; }
$PortObj->close || die; # "undef $PortObj" preferred unless reopening port # "close" should precede "undef" if both used
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.
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.
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.
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::CommPort 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, $quiet) || die "Can't open $PortName: $^E\n"; # $quiet is optional
if $PortObj->can_databits { $PortObj->is_databits(8) }; $PortObj->is_baudrate(9600); $PortObj->is_parity("none"); $PortObj->is_stopbits(1); $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 || die; # "undef $PortObj" preferred unless reopening port # "close" should precede "undef" if both used
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.
Version 0.16 adds pulse methods for the RTS, BREAK, and DTR bits. The pulse methods assume the bit is in the opposite state when the method is called. They set the requested state, delay the specified number of milliseconds, set the opposite state, and again delay the specified time. These methods are designed to support devices, such as the X10 ``FireCracker'' control and some modems, which require pulses on these lines to signal specific events or data.
$PortObj->pulse_break_on($milliseconds); $PortObj->pulse_rts_on($milliseconds); $PortObj->pulse_rts_off($milliseconds); $PortObj->pulse_dtr_on($milliseconds); $PortObj->pulse_dtr_off($milliseconds);
Version 0.16 also adds experimental support for the rest of the option bits available through the Device Control Block. They have not been extensively tested and these settings are NOT saved in the configuration file by Win32::SerialPort. Please let me know if one does not work as advertised. [Win32 API bit designation]
$PortObj->ignore_null(0); # discard \000 bytes on input [fNull]
$PortObj->ignore_no_dsr(0); # discard input bytes unless DSR # [fDsrSensitivity]
$PortObj->subst_pe_char(0); # replace parity errors with B<is_error_char> # when B<is_parity_enable> [fErrorChar]
$PortObj->abort_on_error(0); # cancel read/write [fAbortOnError]
# next one set by $PortObj->is_handshake("dtr"); $PortObj->output_dsr(0); # use DSR handshake on output [fOutxDsrFlow]
# next one set by $PortObj->is_handshake("rts"); $PortObj->output_cts(0); # use CTS handshake on output [fOutxCtsFlow]
# next two set by $PortObj->is_handshake("xoff"); $PortObj->input_xoff(0); # use Xon/Xoff handshake on input [fInX] $PortObj->output_xoff(0); # use Xon/Xoff handshake on output [fOutX]
$PortObj->tx_on_xoff(0); # continue output even after input xoff sent # [fTXContinueOnXoff]
The get_tick_count method is a wrapper around the Win32::GetTickCount() function. It matches a corresponding method in Device::SerialPort which does not have access to the Win32:: namespace. It still returns time in milliseconds - but can be used in cross-platform scripts.
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:
Setting is_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 = is_read_const_time + (is_read_char_time * bytes_to_read)
Write_Total = is_write_const_time + (is_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 Win32::SerialPort tied FileHandles because the tie methods can make multiple internal API calls. The Read_Interval mechanism is suitable for a read_bg 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.
Nothing is exported by default. The following tags can be used to have large sets of symbols exported:
LONGsize SHORTsize nocarp yes_true OS_Error internal_buffer
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
$result=ClearCommError($handle, $Error_BitMask_p, $CommStatus); $result=ClearCommBreak($handle); $result=SetCommBreak($handle); $result=GetCommModemStatus($handle, $ModemStatus); $result=GetCommProperties($handle, $CommProperties); $result=GetCommState($handle, $DCB_Buffer); $result=SetCommState($handle, $DCB_Buffer); $result=SetupComm($handle, $in_buf_size, $out_buf_size); $result=ReadFile($handle, $buffer, $wanted, $got, $template); $result=WriteFile($handle, $buffer, $size, $count, $template);
$result=GetCommTimeouts($handle, $CommTimeOuts); $result=SetCommTimeouts($handle, $CommTimeOuts); $result=EscapeCommFunction($handle, $Func_ID); $result=GetCommConfig($handle, $CommConfig, $Size); $result=SetCommConfig($handle, $CommConfig, $Size); $result=PurgeComm($handle, $flags);
$result=GetCommMask($handle, $Event_Bitmask); $result=SetCommMask($handle, $Event_Bitmask); $hEvent=CreateEvent($security, $reset_req, $initial, $name); $handle=CreateFile($file, $access, $share, $security, $creation, $flags, $template); $result=CloseHandle($handle); $result=ResetEvent($hEvent); $result=TransmitCommChar($handle, $char); $result=WaitCommEvent($handle, $Event_Bitmask, $lpOverlapped); $result=GetOverlappedResult($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
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
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
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";
Win32::SerialPort supports accessing ports via Tied Filehandles.
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 Win32::API 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.
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-509 and GS 5.004_02. It has only been tested on Intel hardware.
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. In particular, the automated install and test scripts in this distribution work differently with ActiveState builds 3xx.
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 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.
A few NT systems seem to set can_parity_enable true, but do not actually support setting is_parity_enable. This may be a characteristic of certain third-party serial drivers. Or a Microsoft bug. I have been able to reproduce it on my system, but not identify a specific cause.
__Please send comments and bug reports to wcbirthisel@alum.mit.edu.
Bill Birthisel, wcbirthisel@alum.mit.edu, http://members.aol.com/Bbirthisel/.
Tye McQueen contributed but no longer supports these modules.
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 (C) 2010, 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.
Most of the code in this module has been stable since version 0.12. Version 0.20 adds explicit support for COM10++ and USB - although the functionality existed before. Perl ports before 5.6.0 are no longer supported for test or install. The modules themselves work with 5.003. 1 April 2010.
Win32API::CommPort - Raw Win32 system API calls for serial communications. |