Device::Modem(3pm)

๐Ÿ“ฆ
version 1.59 ยท 3 versions
, in debian bookworm, debian trixie, ubuntu jammy, ubuntu noble, ubuntu resolute

๐Ÿ’– Device::Modem ๐Ÿ’–

okay so this is the manual for Device::Modem, a Perl extension to talk to modem devices connected via serial port ๐Ÿ’…โœจ


๐ŸŒธ NAME ๐ŸŒธ

Device::Modem โ€” Perl extension to talk to modem devices connected via serial port ๐Ÿ’–


โš ๏ธ WARNING โš ๏ธ

bestie, this is BETA software! use it at your own risk, and without ANY warranty! have fun ๐Ÿ’…

โœจ SYNOPSIS โœจ

okay so here's the whole vibe in code, bestie:

use Device::Modem;

my $modem = Device::Modem->new( port => '/dev/ttyS1' );

if( $modem->connect( baudrate => 9600 ) ) {
    print "connected!\n";
} else {
    print "sorry, no connection with serial port!\n";
}

$modem->attention();          # send `attention' sequence (+++)

($ok, $answer) = $modem->dial('02270469012');  # dial phone number
$ok = $modem->dial(3);        # 1-digit parameter = dial number stored in memory 3

$modem->echo(1);              # enable local echo (0 to disable)

$modem->offhook();            # Take off hook (ready to dial)
$modem->hangup();             # returns modem answer

$modem->is_active();          # Tests whether modem device is active or not
                              # So far it works for modem OFF/ modem ON condition

$modem->reset();              # hangup + attention + restore setting 0 (Z0)

$modem->restore_factory_settings();  # Handle with care!
$modem->restore_factory_settings(1); # Same with preset profile 1 (can be 0 or 1)

$modem->send_init_string();   # Send initialization string
                              # Now this is fixed to 'AT H0 Z S7=45 S0=0 Q0 V1 E0 &C0 X4'

# Get/Set value of S1 register
my $S1 = $modem->S_register(1);
my $S1 = $modem->S_register(1, 55); # Don't do that if you definitely don't know!

# Get status of managed signals (CTS, DSR, RLSD, RING)
my %signal = $modem->status();
if( $signal{DSR} ) { print "Data Set Ready signal active!\n"; }

# Stores this number in modem memory number 3
$modem->store_number(3, '01005552817');

$modem->repeat();             # Repeat last command

$modem->verbose(1);           # Normal text responses (0=numeric codes)

# Some raw AT commands
$modem->atsend( 'ATH0' );
print $modem->answer();

$modem->atsend( 'ATDT01234567' . Device::Modem::CR );
print $modem->answer();

๐ŸŒธ DESCRIPTION ๐ŸŒธ

Device::Modem class implements basic AT (Hayes) compliant device abstraction. It can be inherited by sub classes (as Device::Gsm), which are based on serial connections.


๐Ÿ’– Things Device::Modem can do ๐Ÿ’–

  • connect to a modem on your serial port
  • test if the modem is alive and working
  • dial a number and connect to a remote modem
  • work with registers and settings of the modem
  • issue standard or arbitrary "AT" commands, getting results from modem

๐Ÿ˜ญ Things Device::Modem can't do yet ๐Ÿ˜ญ

  • Transfer a file to a remote modem
  • Control a terminal-like (or a PPP) connection. This should really not be very hard to do anyway.
  • Many others...

๐Ÿ’€ Things it will never be able to do ๐Ÿ’€

  • Coffee :-)

๐Ÿ“‚ Examples ๐Ÿ“‚

In the examples directory, there are some scripts that should work without big problems, that you can take as (yea) examples:

  • examples/active.pl โ€” Tests if modem is alive
  • examples/caller-id.pl โ€” Waits for an incoming call and displays date, time and phone number of the caller. Normally this is available everywhere, but you should check your local phone line and settings.
  • examples/dial.pl โ€” Dials a phone number and display result of call
  • examples/shell.pl โ€” (Very) poor man's minicom/hyperterminal utility
  • examples/xmodem.pl โ€” First attempt at a test script to receive a file via xmodem protocol. Please be warned that this thing does not have a chance to work. It's only a (very low priority) work in progress...

If you want to help out, be welcome!


โœจ METHODS โœจ

๐ŸŒŸ answer() ๐ŸŒŸ

One of the most used methods, waits for an answer from the device. It waits until $timeout (seconds) is reached (but don't rely on this time to be very correct) or until an expected string is encountered. Example:

$answer = $modem->answer( [$expect [, $timeout]] )

Returns $answer that is the string received from modem stripped of all Carriage Return and Line Feed chars only at the beginning and at the end of the string. No in-between CR+LF are stripped.

Note that if you need the raw answer from the modem, you can use the _answer() (note that underscore char before answer) method, which does not strip anything from the response, so you get the real modem answer string.

Parameters:

  • $expect โ€” Can be a regexp compiled with qr or a simple substring. Input coming from the modem is matched against this parameter. If input matches, result is returned.
  • $timeout โ€” Expressed in milliseconds. After that time, answer returns result also if nothing has been received. Example: 10000. Default: $Device::Modem::TIMEOUT, currently 500 ms.

๐ŸŒŸ atsend() ๐ŸŒŸ

Sends a raw "AT" command to the device connected. Note that this method is most used internally, but can be also used to send your own custom commands. Example:

$ok = $modem->atsend( $msg )

The only parameter is $msg, that is the raw AT command to be sent to modem expressed as string. You must include the "AT" prefix and final Carriage Return and/or Line Feed manually. There is the special constant "CR" that can be used to include such a char sequence into the at command.

Returns $ok flag that is true if all characters are sent successfully, false otherwise.

Example:

# Enable verbose messages
$modem->atsend( 'AT V1' . Device::Modem::CR );

# The same as:
$modem->verbose(1);

๐ŸŒŸ attention() ๐ŸŒŸ

This command sends an attention sequence to modem. This allows modem to pass in command state and accept AT commands. Example:

$ok = $modem->attention()

๐ŸŒŸ connect() ๐ŸŒŸ

Connects Device::Modem object to the specified serial port. There are options (the same options that Device::SerialPort has) to control the parameters associated to serial link. Example:

$ok = $modem->connect( [%options] )

List of allowed options follows:

  • baudrate โ€” Controls the speed of serial communications. The default is 19200 baud, that should be supported by all modern modems. However, here you can supply a custom value. Common speed values: 300, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200. This parameter is handled directly by Device::SerialPort object.
  • databits โ€” This tells how many bits your data word is composed of. Default (and most common setting) is 8. This parameter is handled directly by Device::SerialPort object.
  • handshake โ€” Sets the handshake (or flow control) method for the serial port. By default it is none, but can be either rts (hardware flow control) or xoff (software flow control). These flow control modes may or may not work depending on your modem device or software.
  • init_string โ€” Custom initialization string can be supplied instead of the built-in one, that is the following: H0 Z S7=45 S0=0 Q0 V1 E0 &C0 X4, that is taken shamelessly from minicom utility, I think.
  • parity โ€” Controls how parity bit is generated and checked. Can be even, odd or none. Default is none. This parameter is handled directly by Device::SerialPort object.
  • stopbits โ€” Tells how many bits are used to identify the end of a data word. Default (and most common usage) is 1. This parameter is handled directly by Device::SerialPort object.

๐ŸŒŸ dial() ๐ŸŒŸ

Dials a telephone number. Can perform both voice and data calls.

Usage:

$ok = $modem->dial($number);
$ok = $modem->dial($number, $timeout);
$ok = $modem->dial($number, $timeout, $mode);

Takes the modem off hook, dials the specified number and returns modem answer.

Regarding voice calls, you will not be able to send your voice through. You probably have to connect an analog microphone, and just speak. Or use a GSM phone. For voice calls, a simple ; is appended to the number to be dialed.

If the number to dial is 1 digit only, extracts the number from the address book, provided your device has one. See store_number().

Examples:

# Simple usage. Timeout and mode are optional.
$ok = $mode->dial('123456789');

# List context: allows one to get at exact modem answer
# like `CONNECT 19200/...', `BUSY', `NO CARRIER', ...
# Also, 30 seconds timeout
($ok, $answer) = $modem->dial('123456789', 30);

If called in scalar context, returns only success of connection. If modem answer contains the CONNECT string, dial() returns successful state, otherwise a false value is returned.

If called in list context, returns the same $ok flag, but also the exact modem answer to the dial operation in the $answer scalar. $answer typically can contain strings like:

"CONNECT 19200"
"NO CARRIER"
"BUSY"

and so on ... all standard modem answers to a dial command.

Parameters are:

  • $number โ€” mandatory, this is the phone number to dial. If $number is only 1 digit, it is interpreted as: dial number in my address book position $number.

So if your code is:

$modem->dial( 2, 10 );

This means: dial number in the modem internal address book (see store_number for a way to read/write address book) in position number 2 and wait for a timeout of 10 seconds.

  • $timeout โ€” optional, default is 30 seconds.

Timeout expressed in seconds to wait for the remote device to answer. Please do not expect an exact wait for the number of seconds you specified.

  • $mode โ€” optional, default is DATA, as string. Allows one to specify the type of call. Can be either:
    • DATA (default) โ€” To perform a data call.
    • VOICE โ€” To perform a voice call, if your device supports it. No attempt to verify whether your device can do that will be made.

๐ŸŒŸ disconnect() ๐ŸŒŸ

Disconnects Device::Modem object from serial port. This method calls underlying disconnect() of Device::SerialPort object. Example:

$modem->disconnect();

๐ŸŒŸ echo() ๐ŸŒŸ

Enables or disables local echo of commands. This is managed automatically by Device::Modem object. Normally you should not need to worry about this. Usage:

$ok = $modem->echo( $enable )

๐ŸŒŸ hangup() ๐ŸŒŸ

Does what it is supposed to do. Hang up the phone thus terminating any active call. Usage:

$ok = $modem->hangup();

๐ŸŒธ is_active()

Bestie, this one's your vibe check on the hardware ๐Ÿซถ. It tells you if there's actually a modem attached to your computer. If the modem is alive and responding (over the serial link, not to some remote call), is_active() hands you true (1). Otherwise you get false (0).

The activity test happens through the DSR (Data Set Ready) signal. If that signal is in the off state, your modem is probably turned off, or just not working. And from the author's own tests: DSR stays "on" for roughly one second after the modem gets turned off. So now you know that. ๐Ÿ’…

Example:

if( $modem->is_active() ) {
        # Ok!
} else {
        # Modem turned off?
}

๐Ÿ““ log()

A simple little accessor to the log object that got instanced back at object creation time. Used internally. If you're the kind of girl who wants the gory details, go look at the Device::Modem::Log::* objects. You can also peek at the examples to see how to log something without knowing all the gory details.

Hint:

$modem->log->write('warning', 'ok, my log message here');

โœจ new()

The Device::Modem constructor, the main character of this whole situation ๐Ÿ‘‘. It takes several options. A basic example:

my $modem = Device::Modem->new( port => '/dev/ttyS0' );

if you're on Linux or some kind of unix machine, or

my $modem = Device::Modem->new( port => 'COM1' );

if you're on a Win32 machine.

This builds the Device::Modem object with all the default parameters, and honestly it should be fairly usable if you just wanna connect to a real modem. For the record, the author tested it with a 3Com US Robotics 56K Message modem at 19200 baud and it works ok. ๐Ÿ”ฅ

List of allowed options, no gatekeeping:

  • port โ€” the serial port to connect to. On Unix, this can also be a convenient link like /dev/modem (that's the default value). For Win32, COM1,2,3,4 can be used.
  • log โ€” this specifies the method and eventually the filename for logging. The logging process in Device::Modem is controlled by log plugins, stored under the Device/Modem/Log/ folder. At present there are two main plugins: Syslog and File. Heads up: Syslog does not work with Win32 machines. When you use the File plug-in, all log info gets written to a default filename if you don't specify one yourself โ€” the default is /var/log/modem/modem.log.

Also! There's the possibility to pass a custom log object, if that object provides the following write() call:

$log_object->write( $loglevel, $logmessage )

You can simply pass this object (already instanced) as the log property.

Examples:

# For Win32, default is to log in "%WINBOOTDIR%/temp/modem.log" file
my $modem = Device::Modem->new( port => 'COM1' );

# Unix, custom logfile
my $modem = Device::Modem->new( port => '/dev/ttyS0', log => 'file,/home/neo/matrix.log' )

# With custom log object
my $modem = Device::modem->new( port => '/dev/ttyS0', log => My::LogObj->new() );
  • loglevel โ€” the default logging level. One of (in order of decrescent verbosity): debug, verbose, notice, info, warning, err, crit, alert, emerg.

๐Ÿ“ž offhook()

Takes the modem off hook, ready to dial. Normally you don't need to use this yourself, bestie โ€” dial() goes automatically off hook before dialing anyway. Iconic behaviour, honestly. ๐ŸŽ€


๐Ÿ” parse_answer()

This method works like answer(), and it accepts the same parameters, but it does not return the raw modem answer. Instead, it returns the answer string stripped of all CR/LF characters at the beginning and at the end. Clean girl aesthetic โœจ.

parse_answer() is meant as an easy way of extracting the result code (OK, ERROR, ...) and information strings that a modem can send back in response to specific commands. Example:

> AT xSHOW_MODELx<CR>
US Robotics 56K Message
OK
>

In this example, OK is the result and US Robotics 56K Message is the informational message.

In fact, another difference from answer() is in the return value(s). Here are some examples:

$modem->atsend( '?my_at_command?' );
$answer = $modem->parse_answer();

where $answer is the complete response string, or:

($result, @lines) = $modem->parse_answer();

where $result is the OK or ERROR final message and @lines is the array of information messages (one or more lines). For the model example, $result would hold "OK" and @lines would consist of only 1 line with the string "US Robotics 56K Message".


๐Ÿ”Œ port()

Used internally. It accesses the Device::SerialPort underlying object. If you need to experiment or do low-level serial calls, you may want to get at this. Please report any usage of this kind, because probably (?) it is possible to include it in a higher level method. ๐Ÿ‘€

As of 1.52, port() will automatically try to reconnect if it detects a bogus underlying port object. It will reconnect with the same options used when connect()ing the first time.

If no connection has taken place yet, then no attempt to automatically reconnect will be attempted. Simple as that.


๐Ÿ” repeat()

Repeats the last AT command issued. Usage:

$ok = $modem->repeat()

โ™ป๏ธ reset()

Tries in any possible way to reset the modem to the starting state โ€” hanging up all active calls, resending the initialization string, and preparing to receive AT commands. A full glow-up back to factory-fresh energy. ๐Ÿ’…


๐Ÿญ restore_factory_settings()

Restores the modem default factory settings. There are normally two main "profiles", two different memories for all modem settings, so you can load profile 0 and profile 1, which can be different depending on your modem manufacturer.

Usage:

$ok = $modem->restore_factory_settings( [$profile] )

If no $profile is supplied, 0 is assumed as the default value.

Check your modem hardware manual for the meaning of these profiles, bestie โ€” don't guess. ๐Ÿ“–


๐Ÿงฎ S_register()

Gets or sets an S register value. These are some internal modem registers that hold important information controlling all modem behaviour. If you don't know what you're doing, don't use this method. Fr fr. โš ๏ธ

Usage:

$value = $modem->S_register( $reg_number [, $new_value] );

$reg_number ranges from 0 to 99 (sure?). If no $new_value is supplied, the return value is the current register value. If a $new_value is supplied (meaning you want to set the register value), the return value is the new value, or undef if there was an error setting the new value.

There's literally a little leftover note in the source that says <!-- Qui &egrave; spiegata da cani --> ๐Ÿ’€ no comment.

Examples:

# Get value of S7 register
$modem->S_register(7);

# Set value of S0 register to 0
$modem->S_register(0, 0);

๐Ÿ“จ send_init_string()

Sends the initialization string to the connected modem. Usage:

$ok = $modem->send_init_string( [$init_string] );

If you specified an init_string as an option to the new() object constructor, that one is taken by default to initialize the modem. Otherwise you can specify the $init_string parameter to use your own custom initialization string. Be careful! ๐Ÿซฃ


๐Ÿ“Š status()

Returns the status of the main modem signals as managed by Device::SerialPort (or Win32::SerialPort) objects. The signals reported are:

  • CTS โ€” Clear to send
  • DSR โ€” Data set ready
  • RING โ€” Active if modem is ringing
  • RLSD โ€” ??? Released line ???

The return value of a status() call is a hash, where each key is a signal name and each value is > 0 if the signal is active, and 0 otherwise. Usage:

...
my %sig = $modem->status();
for ('CTS','DSR','RING','RLSD') {
        print "Signal $_ is ", ($sig{$_} > 0 ? 'on' : 'off'), "\n";
}

๐Ÿ“‡ store_number()

Stores a telephone number in the modem's internal address book, to be dialed later (see the dial() method). Usage:

$ok = $modem->store_number( $position, $number )

where $position is the address book memory slot to store the phone number in (usually from 0 to 9), and $number is the number to be stored in that slot. The return value is true if the operation was successful, false otherwise. โœจ


๐Ÿ—ฃ๏ธ verbose()

Enables or disables verbose messages. This is managed automatically by the Device::Modem object, so normally you shouldn't need to worry about it. Usage:

$ok = $modem->verbose( $enable )

โณ wait()

Waits (yea) for a given amount of time, in milliseconds. Usage:

$modem->wait( [$msecs] )

Wait is implemented via the select system call. Don't know if this is really a problem on some platforms. ๐Ÿคท


๐Ÿšฐ write_drain()

Only a simple wrapper around the Device::SerialPort::write_drain method. Disabled for the Win32 platform, which doesn't have that. ๐Ÿšซ


๐Ÿ“ฆ REQUIRES

Device::SerialPort (Win32::SerialPort for Win32 machines)


๐ŸŽ EXPORT

None


๐Ÿงš TO-DO

  • AutoScan โ€” an AT command script with all interesting commands is run when autoscan is invoked, creating a profile of the current device, with a list of supported commands, and a database of brand/model-specific commands.
  • Serial speed auto-detect โ€” right now, if you connect to a different baud rate than that of your modem, you'll probably get no response at all. It would be nice if Device::Modem could auto-detect the speed so it correctly connects at your modem's rate.
  • File transfers โ€” it would be nice to implement [xyz]modem-like transfers between two Device::Modem objects connected with two modems.

๐Ÿ’ฌ FAQ

There is a minimal FAQ document for this module online at http://www.streppone.it/cosimo/work/perl/CPAN/Device-Modem/FAQ.html


๐Ÿซถ SUPPORT

Please feel free to contact me at my e-mail address cosimo@cpan.org for any information, to resolve problems you can encounter with this module, or for any kind of commercial support you may need.


๐Ÿ‘‘ AUTHOR

Cosimo Streppone, cosimo@cpan.org


(C) 2002-2014 Cosimo Streppone, cosimo@cpan.org

This library is free software; you can only redistribute it and/or modify it under the same terms as Perl itself.


๐ŸŒˆ SEE ALSO

Device::SerialPort, Win32::SerialPort, Device::Gsm, perl


And that's a wrap, bestie!! ๐ŸŽ€๐Ÿ’– This whole page was written for perl v5.30.3, dated 2020-06-20, and it's Device::Modem(3pm) โ€” go forth and dial something iconic. Periodt. โœจ

๐Ÿ“ฆ where this page comes from