use Win32; require 5.003; use Win32API::CommPort qw( :STAT 0.10 );
## when available ## use Win32API::File 0.05 qw( :ALL );
$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"; }
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";
# 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;
# 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
($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
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.
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.
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:
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
$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
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
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
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.
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)
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.
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.