Device-Modem-1.59/0000755000175000017500000000000013671620771013264 5ustar cosimocosimoDevice-Modem-1.59/Changes0000644000175000017500000002031113671620266014553 0ustar cosimocosimoRevision history for Perl extension Device::Modem. 1.59 Mon Jun 15 08:17:54 CEST 2020 - Merged pull request #6 from ghciv6/fix_multi_instance_log fixed log handling with multi instances and typo in close(). Thanks to @ghciv6 ! 1.58 - Updated test suite a bit. - Added the tests to the manifest. - Got rid of indirect object syntax. - Moved test.pl to the actual test suite. - Updated $VERSION declarations according to: http://www.dagolden.com/index.php/369/version-numbers-should-be-boring/ - Added some extra tests (xt/author, xt/release). - Fixed some spelling. 1.57 Sun Jan 26 11:36:11 CET 2014 - Added a "handshake" option to the connect() method. Allowed values are "xoff", "rts" or "none" (default). Thanks to Ezio Bonsi for suggesting the idea. 1.56 Thu Sep 29 13:43:31 CEST 2011 - [RT#71330] Unbroken the MANIFEST file. 1.55 was non functional. Thanks to Vita Cizek for reporting. 1.55 [BROKEN RELEASE. AVOID] Fri Sep 23 22:01:31 CEST 2011 - Performance improvements by Ed Wildgoose, long time user. Thanks Ed! Windows users, please test this release! 1.54 Sun May 29 20:53:23 AEST 2011 - Removed uninitialized warning on $obj->{'CONNECTED'}. Fixes RT #68504. 1.53 Thu Apr 01 13:49:00 CET 2010 - ***CHANGED*** default log file position from /var/log/modem.log to /tmp/modem.log. Too many failed tests and user reports made me reconsider my poor default choice. - Added voice dialing. Just dialing though. You can't perform real voice calls through Device::Modem (yet :) Thanks to Marek Jaros. - Added ';' (voice dialing) and 'p' (pause) as valid values for dial() number. 1.52 Sun Mar 28 15:50:00 CET 2010 - Added automatic port reconnection in the port() method. This should improve connection reliability and reduce risk of "Can't call method XXXXXX on undefined value YYYYYY" errors. 1.51 Sun Jul 5 09:46:08 CEST 2009 - Fixed documentation for answer() method, timeout was declared to be in seconds instead of milliseconds. Thanks to Mikko Puisto for reporting. 1.50 Tue Sep 30 22:59:00 CEST 2008 - Fixed use of wrong 'error' loglevel for SysLog plugin 1.49 Sat May 31 22:38:00 CEST 2008 - Changed default wait cycles and timeout to be more reliable with slow devices after several user reports. - Fixed man page for Xmodem.pm module. Incorporated fix from the debian package. 1.48 Sun Jun 24 09:30:16 CEST 2007 - atsend() method made more reliable with longer commands (ex. longer sms messages). Thanks to Ben Knight for his bug report and patch. 1.47 Thu Apr 20 22:16:17 CET 2006 - Sensible speedup in the command/response cycle. Thanks to Ed Wildgoose for his contribution. 1.46 1.45 Tue Nov 15 23:29:40 CET 2005 - Fixed dial() now it does not wait for timeout in presence of a valid remote response (NO CARRIER, BUSY, ...) - Fine tuned answer read cycle times - Added constant $Device::Modem::WAITCMD for wait time before issuing commands (atsend) - Added patch to make Xmodem work from Aaron Mitti . - Now dial() accepts also '#' sign in numbers (thanks to Pierre Hilson). 1.44 Sat Apr 30 23:29:03 CET 2005 - (again) now cygwin and darwin platforms should be detected correctly. (thanks to Rob Johnson for reporting) - added a preliminary version of Device::Modem::UsRobotics module, that allows to access voice/fax messages stored on your UsRobotics message modem. Read the (incomplete) docs for more details. 1.42 Sun Sep 19 21:12:10 CET 2004 - little fix for correct MacOSX os detection and SerialPort inclusion (thanks to Lidie Steve for reporting) 1.39 1.38 1.37 Wed Aug 18 09:21:50 CET 2004 - parse_answer() now in scalar context (string) returns *all* modem answer instead of removing the last string (OK/ERROR/...) - documented new example scripts: caller-id.pl and xmodem.pl 1.36 1.35 1.34 Sun Feb 22 18:12:54 CET 2004 - fixed CPAN bug #5131 (https://rt.cpan.org/Ticket/Display.html?id=5131) - closed CPAN bug #5134 (https://rt.cpan.org/Ticket/Display.html?id=5134) - dial() now should return correctly after a successful connect, without unnecessarily waiting for timeout - updated changes file missing in 1.35 1.33 1.32 1.31 Fri Jan 23 01:14:01 CET 2004 - Improved reliability in answer() method (sempre lui!), that was more unstable due to recent changes. - Documented _answer() internal function to get the raw modem reponse instead of response string stripped of all cr/lf chars. 1.29 1.30 Sat Nov 8 18:23:02 CET 2003 - improved answer() method speed. Now it runs sensibly faster, but needs explicit timeout parameter if you want to wait for answers (dialing a remote modem, for example) - implemented a basic xmodem file transfer. *DON'T KNOW IF IT WORKS* - documentation now stays only in docs/ folder, separate from main module - now there is a way to get the raw modem answers (internal _answer() method) 1.25 1.26 1.27 1.28 Sun May 18 17:19:23 CET 2003 - dial() now works as expected, returning the `CONNECT' or `BUSY' or whatever message without hanging for minutes; - answer() routine now is definitely more reliable than before: now everytime the buffer receives input from modem, it does not restart counting the timeout. Removed also the possibility of infinite loop if modem always receives garbage chars (like on a RAW PPP link); - Added full documentation for every method; - Added a FAQ document in new "docs/" folder; - new(): added possibility to pass a custom log object as `log' property; - fixed log levels for File and Syslog plugins. Implemented correct log level masking also for Syslog. 1.23 Wed Dec 4 00:34:52 CET 2002 - little documentation adjustments in main Modem.pm class; - removed use of `warnings.pm' - now File log class opens the log file once and writes on already opened file handle, until final close(). - Thanks to Joerg Neuberger for spotting out a problem with older perls (5.005_xx) and `use warnings' 1.19 1.20 Thu Sep 12 00:19:11 CEST 2002 1.22 Thu Sep 26 00:16:49 CEST 2002 - improved command/response cycle with proper handling of timeout and idle/data cycles. Now it is more reliable also with fairly big serial messages (removed this from TODO list). - removed warnings on undefined answer strings. 1.17 1.18 Tue Sep 3 21:57:11 CEST 2002 - removed some warnings and error in regexp pattern, slight changes in documentation 1.16 Mon Jun 17 21:58:22 CEST 2002 - added S_register() method to read/write S-registers; - store_number() to store an address-book number (cannot retrieve yet); - restore_factory_settings() now accepts a number of profile (default=0); - dial() now dials also address book numbers (only if supplied number is composed of 1 digit: the address book position, from 0 to 9). - status() method added, which looks up CTS, DSR, RLSD and RING signals; 1.15 Tue Jun 04 23:20:12 CEST 2002 - modified makefile/test procedure to pass automated cpan tests 1.14 Mon Jun 03 21:53:05 CEST 2002 - added is_active() method to test if modem ... (guess :-) - tested, now seems to work, dial() method - fixed a *bad* bug in modem answer parsing routine - better timing and less waits in AT commands - moved "PRE-ALPHA" to "ALPHA" :-) 1.10 Wed Apr 10 00:11:35 CEST 2002 - modified docs, license details - fixed wrong hangup() call 1.08 Wed Apr 3 23:31:58 CEST 2002 - fixed logging classes auto-load mechanism - added parse_answer() function, to easily retrieve informational responses - added TO-DO list to pod 1.07 Wed Apr 3 22:05:00 CEST 2002 - renamed `serial' parameter as `port', syncing with existent docs - removed some warnings on parameters passing 1.05 Sat Mar 30 16:19:40 CET 2002 - added and documented dial() and repeat(), still to be tested! 1.04 Mon Mar 25 07:37:20 CET 2002 - cleaned up docs and some of source code 0.01 Tue Feb 26 22:15:22 CET 2002 - original version; created by h2xs 1.20 with options -A -X -n Device::Modem -v 0.01 Device-Modem-1.59/t/0000755000175000017500000000000013671620770013526 5ustar cosimocosimoDevice-Modem-1.59/t/02-coms.t0000644000175000017500000000735313671620724015102 0ustar cosimocosimo#!perl use strict; use warnings; use Device::Modem; use Test::More; my $port = $ENV{'DEV_MODEM_PORT'}; my $baud = $ENV{'DEV_MODEM_BAUD'} || 19200; my $is_windows = ($^O eq 'MSWin32')? 1: 0; my $is_root = ($< + $> == 0)? 1: 0; if (!$is_windows && !$is_root) { plan skip_all => 'These tests require root access on non-Windows devices'; exit; } unless( $port && $baud ) { plan skip_all => 'Environment variables: DEV_MODEM_PORT and DEV_MODEM_BAUD are necessary'; exit; } $Device::Modem::port = $port; $Device::Modem::baudrate = $baud; if ($Device::Modem::port eq 'NONE' || !$Device::Modem::port) { diag(< 'No modem found'; exit(); } plan tests => 25; diag "Your serial port is `$Device::Modem::port' (environment configured)"; diag "Link baud rate is `$Device::Modem::baudrate' (environment configured)"; my $modem = Device::Modem->new(port => $port, log => 'file,test.log', loglevel => 'info'); isa_ok($modem, 'Device::Modem', 'new: new object instance'); my $res; my $error = do { local $@; eval { $res = $modem->connect( baudrate => $baud ) if $modem; }; $@; }; is($error, undef, 'connect: no errors'); ok($res, 'connect: successfully connected to serial port $port'); SKIP: { skip "No modem connection", 9 unless $res; # Try with AT escape code my $ans = $modem->attention(); is($ans, '', 'attention: correctly got empty response'); # Send empty AT command ok($modem->atsend('AT'.Device::Modem::CR), 'atsend: sent ATdevice'); $ans = $modem->answer(); like($ans, qr/OK/, 'answer: contains OK'); # This must generate an error! ok($modem->atsend('AT@x@@!$#'.Device::Modem::CR), 'atsend: invalid ATdevice'); $ans = $modem->answer(); like($ans, qr/ERROR/, 'answer: contains proper ERROR response'); ok($modem->atsend('AT'.Device::Modem::CR), 'atsend: sent ATdevice after error'); $ans = $modem->answer(); like($ans, qr/OK/, 'answer: contains OK'); ok($modem->atsend('ATZ'.Device::Modem::CR), 'atsend: ATZ reset command'); $ans = $modem->answer(); like($ans, qr/OK/, 'answer: contains OK'); } SKIP: { skip "No modem connection", 3 unless $res; ok($modem->echo(1), 'echo: on'); ok($modem->echo(0), 'echo: off'); ok($modem->offhook(), 'offhook: ok'); } SKIP: { skip "No modem connection", 2 unless $res; my $res = $modem->hangup(); like($res, qr/OK/, 'hangup: got OK response'); ok($modem->is_active(), 'is_active: still OK'); } SKIP: { skip "No modem connection", 5 unless $res; my $reg = 1; my $v1 = $modem->S_register($reg); is(defined($v1), 'S_register: got a value'); my $v2 = $modem->S_register($reg, 72); is($v2, 72, 'S_register: set value to 72'); my $v3 = $modem->S_register($reg); is($v3, 72, 'S_registor: got value 72'); my $v4 = $modem->S_register($reg, $v1); is($v4, $v1, 'S_register: set value to $v1'); my $v5 = $modem->S_register($reg); is($v5, $v1, 'S_register: got value $v1'); } SKIP: { skip "No modem connection", 3 unless $res; ok($modem->atsend('ATI4'.Device::Modem::CR), 'atsend: ATI4'); my $ans = $modem->answer(); unlike($ans, qr/ERROR/, 'answer: does not contain ERROR'); my %status = $modem->status(); ok(keys %status, 'Status: returned keys'); for my $key (keys %status) { my $stat = $status{$key} ? 'on' : 'off'; diag("$key signal is $stat\n"); } } Device-Modem-1.59/t/01-load.t0000644000175000017500000000072213671617660015055 0ustar cosimocosimo#!perl use strict; use warnings; use Test::More tests => 6; BEGIN { use_ok('Device::Modem') or BAIL_OUT("Can't use module"); use_ok('Device::Modem::UsRobotics') or BAIL_OUT("Can't use module"); use_ok('Device::Modem::Protocol::Xmodem') or BAIL_OUT("Can't use module"); use_ok('Device::Modem::Log::File') or BAIL_OUT("Can't use module"); use_ok('Device::Modem::Log::Syslog') or BAIL_OUT("Can't use module"); } can_ok('Device::Modem', qw(new)); Device-Modem-1.59/t/00-report-prereqs.t0000644000175000017500000001271413671617660017133 0ustar cosimocosimo#!perl use strict; use warnings; # This test was generated by Dist::Zilla::Plugin::Test::ReportPrereqs 0.025 use Test::More tests => 1; use ExtUtils::MakeMaker; use File::Spec; # from $version::LAX my $lax_version_re = qr/(?: undef | (?: (?:[0-9]+) (?: \. | (?:\.[0-9]+) (?:_[0-9]+)? )? | (?:\.[0-9]+) (?:_[0-9]+)? ) | (?: v (?:[0-9]+) (?: (?:\.[0-9]+)+ (?:_[0-9]+)? )? | (?:[0-9]+)? (?:\.[0-9]+){2,} (?:_[0-9]+)? ) )/x; # hide optional CPAN::Meta modules from prereq scanner # and check if they are available my $cpan_meta = "CPAN::Meta"; my $cpan_meta_pre = "CPAN::Meta::Prereqs"; my $HAS_CPAN_META = eval "require $cpan_meta; $cpan_meta->VERSION('2.120900')" && eval "require $cpan_meta_pre"; ## no critic # Verify requirements? my $DO_VERIFY_PREREQS = 1; sub _max { my $max = shift; $max = ( $_ > $max ) ? $_ : $max for @_; return $max; } sub _merge_prereqs { my ($collector, $prereqs) = @_; # CPAN::Meta::Prereqs object if (ref $collector eq $cpan_meta_pre) { return $collector->with_merged_prereqs( CPAN::Meta::Prereqs->new( $prereqs ) ); } # Raw hashrefs for my $phase ( keys %$prereqs ) { for my $type ( keys %{ $prereqs->{$phase} } ) { for my $module ( keys %{ $prereqs->{$phase}{$type} } ) { $collector->{$phase}{$type}{$module} = $prereqs->{$phase}{$type}{$module}; } } } return $collector; } my @include = qw( ); my @exclude = qw( ); # Add static prereqs to the included modules list my $static_prereqs = do 't/00-report-prereqs.dd'; # Merge all prereqs (either with ::Prereqs or a hashref) my $full_prereqs = _merge_prereqs( ( $HAS_CPAN_META ? $cpan_meta_pre->new : {} ), $static_prereqs ); # Add dynamic prereqs to the included modules list (if we can) my ($source) = grep { -f } 'MYMETA.json', 'MYMETA.yml'; if ( $source && $HAS_CPAN_META && (my $meta = eval { CPAN::Meta->load_file($source) } ) ) { $full_prereqs = _merge_prereqs($full_prereqs, $meta->prereqs); } else { $source = 'static metadata'; } my @full_reports; my @dep_errors; my $req_hash = $HAS_CPAN_META ? $full_prereqs->as_string_hash : $full_prereqs; # Add static includes into a fake section for my $mod (@include) { $req_hash->{other}{modules}{$mod} = 0; } for my $phase ( qw(configure build test runtime develop other) ) { next unless $req_hash->{$phase}; next if ($phase eq 'develop' and not $ENV{AUTHOR_TESTING}); for my $type ( qw(requires recommends suggests conflicts modules) ) { next unless $req_hash->{$phase}{$type}; my $title = ucfirst($phase).' '.ucfirst($type); my @reports = [qw/Module Want Have/]; for my $mod ( sort keys %{ $req_hash->{$phase}{$type} } ) { next if $mod eq 'perl'; next if grep { $_ eq $mod } @exclude; my $file = $mod; $file =~ s{::}{/}g; $file .= ".pm"; my ($prefix) = grep { -e File::Spec->catfile($_, $file) } @INC; my $want = $req_hash->{$phase}{$type}{$mod}; $want = "undef" unless defined $want; $want = "any" if !$want && $want == 0; my $req_string = $want eq 'any' ? 'any version required' : "version '$want' required"; if ($prefix) { my $have = MM->parse_version( File::Spec->catfile($prefix, $file) ); $have = "undef" unless defined $have; push @reports, [$mod, $want, $have]; if ( $DO_VERIFY_PREREQS && $HAS_CPAN_META && $type eq 'requires' ) { if ( $have !~ /\A$lax_version_re\z/ ) { push @dep_errors, "$mod version '$have' cannot be parsed ($req_string)"; } elsif ( ! $full_prereqs->requirements_for( $phase, $type )->accepts_module( $mod => $have ) ) { push @dep_errors, "$mod version '$have' is not in required range '$want'"; } } } else { push @reports, [$mod, $want, "missing"]; if ( $DO_VERIFY_PREREQS && $type eq 'requires' ) { push @dep_errors, "$mod is not installed ($req_string)"; } } } if ( @reports ) { push @full_reports, "=== $title ===\n\n"; my $ml = _max( map { length $_->[0] } @reports ); my $wl = _max( map { length $_->[1] } @reports ); my $hl = _max( map { length $_->[2] } @reports ); if ($type eq 'modules') { splice @reports, 1, 0, ["-" x $ml, "", "-" x $hl]; push @full_reports, map { sprintf(" %*s %*s\n", -$ml, $_->[0], $hl, $_->[2]) } @reports; } else { splice @reports, 1, 0, ["-" x $ml, "-" x $wl, "-" x $hl]; push @full_reports, map { sprintf(" %*s %*s %*s\n", -$ml, $_->[0], $wl, $_->[1], $hl, $_->[2]) } @reports; } push @full_reports, "\n"; } } } if ( @full_reports ) { diag "\nVersions for all modules listed in $source (including optional ones):\n\n", @full_reports; } if ( @dep_errors ) { diag join("\n", "\n*** WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING ***\n", "The following REQUIRED prerequisites were not satisfied:\n", @dep_errors, "\n" ); } pass; # vim: ts=4 sts=4 sw=4 et: Device-Modem-1.59/t/00-report-prereqs.dd0000644000175000017500000000507713671617660017263 0ustar cosimocosimodo { my $x = { 'configure' => { 'requires' => { 'ExtUtils::MakeMaker' => '0' } }, 'develop' => { 'requires' => { 'File::Spec' => '0', 'IO::Handle' => '0', 'IPC::Open3' => '0', 'Pod::Coverage::TrustPod' => '0', 'Test::CPAN::Changes' => '0.4', 'Test::CheckManifest' => '1.29', 'Test::Kwalitee' => '1.22', 'Test::More' => '0.88', 'Test::Pod' => '1.41', 'Test::Pod::Coverage' => '1.08', 'Test::Pod::Spelling::CommonMistakes' => '1.000', 'Test::Spelling' => '0.12', 'Test::Version' => '1', 'warnings' => '0' } }, 'runtime' => { 'requires' => { 'Carp' => '0', 'Exporter' => '0', 'File::Basename' => '0', 'File::Path' => '0', 'IO::Handle' => '0', 'Sys::Syslog' => '0', 'base' => '0', 'constant' => '0', 'perl' => '5.006', 'overload' => '0', 'strict' => '0', } }, 'test' => { 'recommends' => { 'CPAN::Meta' => '2.120900' }, 'requires' => { 'ExtUtils::MakeMaker' => '0', 'File::Spec' => '0', 'Test::More' => '0', } } }; if ($^O eq 'MSWin32') { $x->{runtime}->{requires}->{'Win32::SerialPort'} = 0; } else { $x->{runtime}->{requires}->{'Device::SerialPort'} = 0; } $x; } Device-Modem-1.59/README0000644000175000017500000000251313671620213014134 0ustar cosimocosimo======================================================================= Device::Modem - a Perl class to interface generic modems (AT-compliant) Copyright (C) 2002-2020 Cosimo Streppone, cosimo@cpan.org ======================================================================= This is a perl extension to talk to AT compliant devices via serial port. It should be enough platform independent as you need. For more details, look at the "docs/" folder where you will find a minimal FAQ ("docs/FAQ.pod"), and the full documentation for this extension ("docs/Modem.pod"). Please contact me for any problems you may encounter using this beast. Have fun! Prerequisites ------------- + working perl installation >= 5.006 + Device::SerialPort >= 0.19 (Win32::SerialPort in on Windows platform) + a modem or AT-compliant device if you want to use it for some real work Installation ------------ This module installs like all other good old perl modules: $ perl Makefile.PL $ make $ make test $ make install Licensing terms --------------- This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Use this software at your own risk without *ANY* warranty! Advertising :-) --------------- Check out also Device::Gsm module from the same author to work with GSM devices connected via serial port. Device-Modem-1.59/examples/0000755000175000017500000000000013671620770015101 5ustar cosimocosimoDevice-Modem-1.59/examples/caller-id.pl0000644000175000017500000000260413671617660017300 0ustar cosimocosimo#!/usr/bin/perl # # Demo of "Caller id" feature: detect who is calling us! # Thanks to Marcelo Fernandez (mfernandez@lq.com.ar) # # $Id: caller-id.pl,v 1.1 2004-08-18 07:29:10 cosimo Exp $ # use Device::Modem; # Init modem my $port = '/dev/ttyS0'; my $baud = 9600; my $modem = Device::Modem->new( port => $port ); die "Can't connect to port $port!\n" unless $modem->connect( baudrate => $baud ); print "Connected to $port.\n\n"; # Init ATs #$modem->atsend('AT S7=45 S0=0 L1 V1 X4 &c1 E1 Q0'.Device::Modem::CR); # 'Stolen' from minicom :P # Set modem in autoanswer mode (to receive incoming calls) # Doesn't work (it says "NO CARRIER") if I uncomment it # $modem->atsend('ATA'.Device::Modem::CR); # Enable Caller ID info $modem->atsend('AT#CID=1'.Device::Modem::CR); # Poll state of modem my $received_call = 0; my $number = ''; print "Waiting for call...\n"; while( ! $received_call ) { # Listen for data coming from modem my $cid_info = $modem->answer(undef, 3); # 3 seconds timeout print "$cid_info\n" if ($cid_info); # If something received, take a look at it if( $cid_info =~ /NMBR\s*=\s*([\d\s]+)/ ) { # Ok, received! Number is in $1 var $number = $1; $received_call++; print "\nNumber $number IS CALLING!!\n"; } elsif( $cid_info ) { # Received something else, we must investigate } else { # No data received. No call arrived. } # Repeat until done } $modem->disconnect(); Device-Modem-1.59/examples/active.pl0000644000175000017500000000266713671617660016730 0ustar cosimocosimo# $Id: active.pl,v 1.4 2005-04-30 21:45:47 cosimo Exp $ # # This script tries to test if modem is active (on and enabled) # If modem is not active, tries to reset it. # # As I know, this script works to the extent as it: # # 1) Fails if modem is turned off # 2) Succeeds if modem is turned on # # It's not a big thing, I know ... :-( # use Device::Modem; my %config; my $port; if( open CACHED_CONFIG, '< ../.config' ) { while( ) { my @t = split /[\s\t]+/; $config{ $t[0] } = $t[1]; } close CACHED_CONFIG; } if( $config{'tty'} ) { print "Your serial port is `$config{'tty'}' (cached)\n"; $port = $config{'tty'}; } else { $config{'tty'} = $Device::Modem::DEFAULT_PORT; print "What is your serial port? [$config{'tty'}] "; chomp( $port = ); $port ||= $config{'tty'}; if( open( CONFIG, '>../.config' ) ) { print CONFIG "tty\t$port\n"; close CONFIG; } } # ----------------------------------------------------- # BEGIN OF TESTS # ----------------------------------------------------- my $modem = Device::Modem->new( port => $port ); if( $modem->connect( baudrate => $config{'baud'} || 19200 ) ) { print "ok 2\n"; } else { print "not ok 2\n"; die "cannot connect to $port serial port!: $!"; } print '- testing if modem is turned on and available', "\n"; my $lOk = 0; if( $lOk = $modem->is_active() ) { print "Ok, modem is active\n"; } else { print "NO! Modem is turned off, or not functioning...\n"; } Device-Modem-1.59/examples/dial.pl0000644000175000017500000000237013671617660016355 0ustar cosimocosimo# $Id: dial.pl,v 1.3 2005-04-30 21:45:47 cosimo Exp $ # # This script tries to dial a number taken from STDIN # or as first argument. # # Example: # perl dial.pl 012,3456789 # # 03/06/2002 Cosimo # use Device::Modem; my %config; my $port; if( open CACHED_CONFIG, '< ../.config' ) { while( ) { my @t = split /[\s\t]+/; $config{ $t[0] } = $t[1]; } close CACHED_CONFIG; } if( $config{'tty'} ) { print "Your serial port is `$config{'tty'}' (cached)\n"; $port ||= $config{'tty'}; } else { $config{'tty'} = $Device::Modem::DEFAULT_PORT; print "What is your serial port? [$config{'tty'}] "; chomp( $port = ); $port ||= $config{'tty'}; if( open( CONFIG, '>../.config' ) ) { print CONFIG "tty\t$port\n"; close CONFIG; } } my $modem = Device::Modem->new( port => $port ); if( $modem->connect( baudrate => $config{'baud'} || 19200 ) ) { print "ok connected.\n"; } else { die "cannot connect to $port serial port!: $!"; } my $number = $ARGV[0]; while( ! $number ) { print "\nInsert the number to dial: \n"; $number = ; chomp $number; $number =~ s/\D//g; } print '- trying to dial [', $number, ']', "\n"; if( $lOk = $modem->dial($number,30) ) { print "Ok, number dialed\n"; } else { print "No luck!\n"; } Device-Modem-1.59/examples/xmodem.pl0000644000175000017500000000065713671617660016743 0ustar cosimocosimo#!/usr/bin/perl use Device::Modem; use Device::Modem::Protocol::Xmodem; my $port = $ARGV[0] || '/dev/pts/1'; my $mdm = Device::Modem->new( port => $port ); $mdm->connect( baudrate => 9600 ) or die "Can't connect to port $port"; print "Ok, connected. Press a key to begin transfer..."; ; my $recv = Xmodem::Receiver->new( modem => $mdm ); die "Receiver object undef!" if ! $recv; $recv->run() or die "Cannot receive!"; Device-Modem-1.59/examples/shell.pl0000644000175000017500000000200013671617660016541 0ustar cosimocosimo#!/usr/bin/perl # # Simple test program that executes a modem `shell' # to monitor AT command results. # # ****************************************** # If it does not work, try with baud = 9600 # # $Id: shell.pl,v 1.6 2005-04-30 21:45:47 cosimo Exp $ use strict; use Device::Modem; if( $> && $< ) { print "\n*** REMEMBER to run this program as root if you cannot connect on serial port!\n"; sleep 3; } print "Your serial port? [/dev/ttyS0]\n"; my $port = ; chomp $port; $port ||= '/dev/ttyS0'; print "Your baud rate? [19200]\n"; my $baud = ; chomp $baud; $baud ||= 19200; my $modem = Device::Modem->new( port => $port ); my $stop; die "Could not connect to $port!\n" unless $modem->connect( baudrate => $baud ); print "Connected to $port.\n\n"; while( not $stop ) { print "insert AT command (`stop' to quit)\n"; print "> "; my $AT = ; chomp $AT; if( $AT eq 'stop' ) { $stop = 1; } else { $modem->atsend( $AT . "\r\n" ); print $modem->answer(), "\n"; } } print "Done.\n"; Device-Modem-1.59/xt/0000755000175000017500000000000013671620770013716 5ustar cosimocosimoDevice-Modem-1.59/xt/author/0000755000175000017500000000000013671620770015220 5ustar cosimocosimoDevice-Modem-1.59/xt/author/addressbook.t0000644000175000017500000000147413671617660017717 0ustar cosimocosimo#!perl use strict; use Device::Modem; use Test::More; my $port = $ENV{'DEV_MODEM_PORT'}; my $baud = $ENV{'DEV_MODEM_BAUD'}; unless( $port && $baud ) { plan skip_all => 'Environment variables: DEV_MODEM_PORT and DEV_MODEM_BAUD are necessary'; exit; } plan tests => 5; my $modem = Device::Modem->new( port => $port ); isa_ok($modem, 'Device::Modem', 'new: new object instance'); my $connected; my $error = do { local $@; eval { $connected = $modem->connect( baudrate => $baud ) if $modem; }; $@; }; is($error, undef, 'connect: no errors'); ok($connected, 'connect: successfully connected'); SKIP: { skip "Couldn't connect for some reason", 2 unless $connected; ok($modem->store_number(0, '10880432090000'), 'store_number: Number stored'); ok($modem->store_number(1, '0432,649062'), 'store_number: Number stored'); } Device-Modem-1.59/xt/author/pod-spell.t0000644000175000017500000000071113671617660017307 0ustar cosimocosimo#!perl use strict; use warnings; use Test::More; # generated by Dist::Zilla::Plugin::Test::PodSpelling 2.007002 use Test::Spelling 0.12; use Pod::Wordlist; set_spell_cmd('aspell list'); add_stopwords(); all_pod_files_spelling_ok( qw( bin lib ) ); __DATA__ CPAN github stopwords wordlist Cosimo Streppone Bla DSR Xmodem XModem ZModem xmodem spiegata AutoScan CTS Drolez GSM Ludovic Mitti PPP Qui RLSD TkUsr USR cani checksum da decrescent favourite Device-Modem-1.59/xt/author/offhook.t0000644000175000017500000000202013671617660017036 0ustar cosimocosimo#!perl use strict; use Device::Modem; use Test::More; my %config; parse_config(); my $port = $config{tty} || $ENV{DEV_MODEM_PORT} || $Device::Modem::DEFAULT_PORT; unless( $port ) { plan skip_all => 'Environment variables: DEV_MODEM_PORT and DEV_MODEM_BAUD are necessary'; exit; } diag("Testing against port $port. Set env DEV_MODEM_PORT to change"); plan tests => 4; my $modem = Device::Modem->new( port => $port ); isa_ok($modem, 'Device::Modem', 'new: new object instance'); my $connected; my $error = do { local $@; eval { $connected = $modem->connect() if $modem; }; $@; }; is($error, undef, 'connect: no errors'); ok($connected, 'connect: successfully connected'); SKIP: { skip "Not connected.", 1 unless $connected; diag('testing offhook function...'); $modem->attention(); ok($modem->offhook(), 'offhook: properly set'); } sub parse_config { open my $fh, '<', '../.config' or return undef; while (my $line = <$fh>) { chomp $line; my @t = split ' ', $line, 2; $config{ $t[0] } = $t[1]; } return undef; } Device-Modem-1.59/xt/author/registers.t0000644000175000017500000000231113671617660017415 0ustar cosimocosimo# Before `make install' is performed this script should be runnable with # `make test'. After `make install' it should work as `perl test.pl' ######################### We start with some black magic to print on failure. # Change 1..1 below to 1..last_test_to_print . # (It may become useful if the test is moved to ./t subdirectory.) BEGIN { $| = 1; print "1..3\n"; } END {print "not ok 1\n" unless $loaded;} use lib '..'; use Device::Modem; $loaded = 1; print "ok 1\n"; ######################### End of black magic. $|++; my $port = $ENV{'DEV_MODEM_PORT'}; my $baud = $ENV{'DEV_MODEM_BAUD'}; unless( $port && $baud ) { print "skip 1\nskip 2\nskip 3\n"; exit; } my $modem = Device::Modem->new( port => $port ); if( $modem->connect( baudrate => $baud ) ) { print "ok 2\n"; } else { print "not ok 2\n"; die "cannot connect to $port serial port!: $!"; } print 'testing S-registers functions...', "\n"; my $v1 = $modem->S_register(1); my $v2 = $modem->S_register(1, 72); my $v3 = $modem->S_register(1); my $v4 = $modem->S_register(1, $v1); my $v5 = $modem->S_register(1); if( $v1 eq $v5 && $v1 == $v5 && $v2 == 72 && $v3 == 72 && $v4 eq $v1 && $v4 == $v1 ) { print "ok 3\n"; } else { print "not ok 3\n"; } Device-Modem-1.59/xt/author/pod-syntax.t0000644000175000017500000000025213671617660017516 0ustar cosimocosimo#!perl # This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests. use strict; use warnings; use Test::More; use Test::Pod 1.41; all_pod_files_ok(); Device-Modem-1.59/xt/author/status.t0000644000175000017500000000153513671617660016740 0ustar cosimocosimo#!perl use strict; use warnings; use Device::Modem; use Test::More; my $port = $ENV{'DEV_MODEM_PORT'} || ''; my $baud = $ENV{'DEV_MODEM_BAUD'} || ''; unless( $port && $baud ) { plan skip_all => 'Environment variables: DEV_MODEM_PORT and DEV_MODEM_BAUD are necessary'; exit; } plan tests => 4; my $modem = Device::Modem->new( port => $port ); isa_ok($modem, 'Device::Modem', 'new: new object instance'); my $res; my $error = do { local $@; eval { $res = $modem->connect( baudrate => $baud ) if $modem; }; $@; }; is($error, undef, 'connect: no errors'); ok($res, 'connect: successfully connected'); SKIP: { skip "Couldn't connect for some reason", 1 unless $res; my %status = $modem->status(); ok(keys %status, 'Status: returned keys'); for my $key (keys %status) { my $stat = $status{$key} ? 'on' : 'off'; diag("$key signal is $stat\n"); } } Device-Modem-1.59/xt/author/usrobotics.t0000644000175000017500000000141013671617660017601 0ustar cosimocosimo#!perl # UsRobotics module test # # $Id: usrobotics.t,v 1.2 2006-04-20 20:19:22 cosimo Exp $ use strict; use Test::More; plan tests => 6; use_ok('Device::Modem::UsRobotics'); my $modem = Device::Modem::UsRobotics->new( port => '/dev/ttyS0', log => 'file,./usrobotics.log', loglevel=>'info' ); ok($modem, 'UsRobotics object ok'); $modem->connect(baudrate=>19200) or die "Can't connect"; ok($modem, 'connected'); $modem->attention(); # Test MCC usr extension my $ans = $modem->mcc_get(); diag('mcc: ', $ans, "\n"); ok(defined $ans && $ans ne '' && $ans =~ /[\d\,]+/, 'mcc command'); # Test msr extension $ans = $modem->msg_status(); diag('msr: ', $ans, "\n"); ok($ans =~ /\d+,\d+,\d+,\d+/, 'message status ok'); ok($modem->disconnect(), 'disconnected'); Device-Modem-1.59/xt/author/00-compile.t0000644000175000017500000000246213671617660017262 0ustar cosimocosimo#!perl use 5.006; use strict; use warnings; # this test was generated with Dist::Zilla::Plugin::Test::Compile 2.054 use Test::More; plan tests => 6; my @module_files = ( 'Device/Modem.pm', 'Device/Modem/UsRobotics.pm', 'Device/Modem/Log/File.pm', 'Device/Modem/Log/Syslog.pm', 'Device/Modem/Protocol/Xmodem.pm', ); # no fake home requested my $inc_switch = -d 'blib' ? '-Mblib' : '-Ilib'; use File::Spec; use IPC::Open3; use IO::Handle; open my $stdin, '<', File::Spec->devnull or die "can't open devnull: $!"; my @warnings; for my $lib (@module_files) { # see L my $stderr = IO::Handle->new; my $pid = open3($stdin, '>&STDERR', $stderr, $^X, $inc_switch, '-e', "require q[$lib]"); binmode $stderr, ':crlf' if $^O eq 'MSWin32'; my @_warnings = <$stderr>; waitpid($pid, 0); is($?, 0, "$lib loaded ok"); shift @_warnings if @_warnings and $_warnings[0] =~ /^Using .*\bblib/ and not eval { require blib; blib->VERSION('1.01') }; if (@_warnings) { warn @_warnings; push @warnings, @_warnings; } } is(scalar(@warnings), 0, 'no warnings found') or diag 'got warnings: ', ( Test::More->can('explain') ? Test::More::explain(\@warnings) : join("\n", '', @warnings) ); Device-Modem-1.59/xt/author/echo.t0000644000175000017500000000306613671617660016334 0ustar cosimocosimo#!perl use strict; use Device::Modem; use Test::More; my %config; parse_config(); my $port = $config{tty} || $ENV{DEV_MODEM_PORT} || $Device::Modem::DEFAULT_PORT; unless( $port ) { plan skip_all => 'Environment variables: DEV_MODEM_PORT and DEV_MODEM_BAUD are necessary'; exit; } diag("Testing against port $port. Set env DEV_MODEM_PORT to change"); plan tests => 10; my $modem = Device::Modem->new( port => $port ); isa_ok($modem, 'Device::Modem', 'new: new object instance'); my $connected; my $error = do { local $@; eval { $connected = $modem->connect() if $modem; }; $@; }; is($error, undef, 'connect: no errors'); ok($connected, 'connect: successfully connected'); SKIP: { skip "Not connected.", 7 unless $connected; my $echo = $modem->echo(1); ok($echo, "echo: echo turned on"); ECHO: { skip "No Echo", 3 unless $echo; diag("Sending AT@@@ string..."); ok($modem->atsend('AT@@@'.Device::Modem::CR), 'atsend: AT@@@ sent'); my $ans = $modem->answer(); like($ans, qr/AT@@@/, 'answer: contains AT@@@'); like($ans, qr/ERROR/, 'answer: contains ERROR'); } $echo = $modem->echo(0); ok($echo, "echo: echo turned off"); ECHO: { skip "Couldn't turn off echo", 2 unless $echo; diag("Sending AT@@@ string"); ok($modem->atsend('AT@@@'.Device::Modem::CR), 'atsend: AT@@@ sent'); my $ans = $modem->answer(); like($ans, qr/ERROR/, 'answer: contains ERROR'); } } sub parse_config { open my $fh, '<', '../.config' or return undef; while (my $line = <$fh>) { chomp $line; my @t = split ' ', $line, 2; $config{ $t[0] } = $t[1]; } return undef; } Device-Modem-1.59/xt/author/test-version.t0000644000175000017500000000063613671617660020060 0ustar cosimocosimouse strict; use warnings; use Test::More; # generated by Dist::Zilla::Plugin::Test::Version 1.09 use Test::Version; my @imports = qw( version_all_ok ); my $params = { is_strict => 0, has_version => 1, multiple => 0, }; push @imports, $params if version->parse( $Test::Version::VERSION ) >= version->parse('1.002'); Test::Version->import(@imports); version_all_ok; done_testing; Device-Modem-1.59/xt/author/pod-coverage.t0000644000175000017500000000171313671617660017766 0ustar cosimocosimo#!perl # This file was automatically generated by Dist::Zilla::Plugin::Test::Pod::Coverage::Configurable. use Test::Pod::Coverage 1.08; use Test::More 0.88; BEGIN { if ( $] <= 5.008008 ) { plan skip_all => 'These tests require Pod::Coverage::TrustPod, which only works with Perl 5.8.9+'; } } use Pod::Coverage::TrustPod; my %skip = map { $_ => 1 } qw( ); my @modules; for my $module ( all_modules() ) { next if $skip{$module}; push @modules, $module; } plan skip_all => 'All the modules we found were excluded from POD coverage test.' unless @modules; plan tests => scalar @modules; my %trustme = (); my @also_private; for my $module ( sort @modules ) { pod_coverage_ok( $module, { coverage_class => 'Pod::Coverage::TrustPod', also_private => \@also_private, trustme => $trustme{$module} || [], }, "pod coverage for $module" ); } done_testing(); Device-Modem-1.59/xt/release/0000755000175000017500000000000013671620770015336 5ustar cosimocosimoDevice-Modem-1.59/xt/release/changes_has_content.t0000644000175000017500000000205613671617660021527 0ustar cosimocosimo#!perl use Test::More tests => 2; use Device::Modem (); note 'Checking Changes'; my $changes_file = 'Changes'; my $newver = $Device::Modem::VERSION; my $trial_token = '-TRIAL'; SKIP: { ok(-e $changes_file, "$changes_file file exists") or skip 'Changes is missing', 1; ok(_get_changes($newver), "$changes_file has content for $newver"); } done_testing; # _get_changes copied and adapted from Dist::Zilla::Plugin::Git::Commit # by Jerome Quelin sub _get_changes { my $newver = shift; # parse changelog to find commit message open(my $fh, '<', $changes_file) or die "cannot open $changes_file: $!"; my $changelog = join('', <$fh>); close $fh; my @content = grep { /^$newver(?:$trial_token)?(?:\s+|$)/ ... /^\S/ } # from newver to un-indented split /\n/, $changelog; shift @content; # drop the version line # drop unindented last line and trailing blank lines pop @content while ( @content && $content[-1] =~ /^(?:\S|\s*$)/ ); # return number of non-blank lines return scalar @content; } Device-Modem-1.59/xt/release/kwalitee.t0000644000175000017500000000030413671617660017331 0ustar cosimocosimo#!perl # this test was generated with Dist::Zilla::Plugin::Test::Kwalitee 2.12 use strict; use warnings; use Test::More 0.88; use Test::Kwalitee 1.21 'kwalitee_ok'; kwalitee_ok(); done_testing; Device-Modem-1.59/META.json0000664000175000017500000000342513671620771014713 0ustar cosimocosimo{ "abstract" : "Perl extension to talk to modem devices connected via serial port", "author" : [ "Cosimo Streppone " ], "dynamic_config" : 1, "generated_by" : "ExtUtils::MakeMaker version 7.24, CPAN::Meta::Converter version 2.150010", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Device-Modem", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "Carp" : "0", "Device::SerialPort" : "0", "Exporter" : "0", "File::Basename" : "0", "File::Path" : "0", "IO::Handle" : "0", "Sys::Syslog" : "0", "base" : "0", "constant" : "0", "overload" : "0", "perl" : "5.006", "strict" : "0" } }, "test" : { "requires" : { "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "Test::More" : "0", "warnings" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "mailto" : "bug-device-modem@rt.cpan.org" }, "license" : [ "http://dev.perl.org/licenses/" ], "repository" : { "type" : "git", "url" : "git://github.com/cosimo/perl5-device-modem.git" } }, "version" : "1.59", "x_serialization_backend" : "JSON::PP version 2.27400_02" } Device-Modem-1.59/META.yml0000664000175000017500000000166313671620770014544 0ustar cosimocosimo--- abstract: 'Perl extension to talk to modem devices connected via serial port' author: - 'Cosimo Streppone ' build_requires: ExtUtils::MakeMaker: '0' File::Spec: '0' Test::More: '0' warnings: '0' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 1 generated_by: 'ExtUtils::MakeMaker version 7.24, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Device-Modem no_index: directory: - t - inc requires: Carp: '0' Device::SerialPort: '0' Exporter: '0' File::Basename: '0' File::Path: '0' IO::Handle: '0' Sys::Syslog: '0' base: '0' constant: '0' overload: '0' perl: '5.006' strict: '0' resources: license: http://dev.perl.org/licenses/ repository: git://github.com/cosimo/perl5-device-modem.git version: '1.59' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Device-Modem-1.59/MANIFEST0000644000175000017500000000144313671620771014417 0ustar cosimocosimoChanges examples/active.pl examples/caller-id.pl examples/dial.pl examples/shell.pl examples/xmodem.pl lib/Device/Modem.pm lib/Device/Modem/FAQ.pod lib/Device/Modem/Log/File.pm lib/Device/Modem/Log/Syslog.pm lib/Device/Modem/Protocol/Xmodem.pm lib/Device/Modem/UsRobotics.pm Makefile.PL MANIFEST META.yml Module meta-data (added by MakeMaker) README t/00-report-prereqs.dd t/00-report-prereqs.t t/01-load.t t/02-coms.t xt/author/00-compile.t xt/author/addressbook.t xt/author/echo.t xt/author/offhook.t xt/author/pod-coverage.t xt/author/pod-spell.t xt/author/pod-syntax.t xt/author/registers.t xt/author/status.t xt/author/test-version.t xt/author/usrobotics.t xt/release/changes_has_content.t xt/release/kwalitee.t META.json Module JSON meta-data (added by MakeMaker) Device-Modem-1.59/lib/0000755000175000017500000000000013671620770014031 5ustar cosimocosimoDevice-Modem-1.59/lib/Device/0000755000175000017500000000000013671620770015230 5ustar cosimocosimoDevice-Modem-1.59/lib/Device/Modem/0000755000175000017500000000000013671620770016271 5ustar cosimocosimoDevice-Modem-1.59/lib/Device/Modem/Protocol/0000755000175000017500000000000013671620770020072 5ustar cosimocosimoDevice-Modem-1.59/lib/Device/Modem/Protocol/Xmodem.pm0000644000175000017500000003615413671617660021676 0ustar cosimocosimo# Device::Modem::Protocol::Xmodem - Xmodem file transfer protocol for Device::Modem class # # Initial revision: 1 Oct 2003 # # Copyright (C) 2003-2005 Cosimo Streppone, cosimo@cpan.org # # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # # Additionally, this is ALPHA software, still needs extensive # testing and support for generic AT commads, so use it at your own risk, # and without ANY warranty! Have fun. # # This Xmodem protocol version is indeed very alpha code, # probably does not work at all, so stay tuned... # # $Id$ package Xmodem::Constants; # Define constants used in xmodem blocks sub nul () { 0x00 } # ^@ sub soh () { 0x01 } # ^A sub stx () { 0x02 } # ^B sub eot () { 0x04 } # ^D sub ack () { 0x06 } # ^E sub nak () { 0x15 } # ^U sub can () { 0x18 } # ^X sub C () { 0x43 } sub ctrl_z () { 0x1A } # ^Z sub CHECKSUM () { 1 } sub CRC16 () { 2 } sub CRC32 () { 3 } sub XMODEM () { 0x01 } sub XMODEM_1K () { 0x02 } sub XMODEM_CRC () { 0x03 } #sub YMODEM () { 0x04 } #sub ZMODEM () { 0x05 } package Xmodem::Block; use overload q[""] => \&to_string; # Create a new block object sub new { my($proto, $num, $data, $length) = @_; my $class = ref $proto || $proto; # Define block type (128 or 1k chars) if not specified $length ||= ( length $data > 128 ? 1024 : 128 ); # Define structure of a Xmodem transfer block object my $self = { number => defined $num ? $num : 0, 'length'=> $length, data => defined $data ? substr($data, 0, $length) : "", # Blocks are limited to 128 or 1024 chars }; bless $self, $class; } # Calculate checksum of current block data sub checksum { my $self = $_[0]; my $sum = 0; foreach my $c ( $self->data() ) { $sum += ord $c; $sum %= 256; } return $sum % 256; } # Calculate CRC 16 bit on block data sub crc16 { my $self = $_[0]; return unpack('%C16*' => $self->data()) % 65536; } # Calculate CRC 32 bit on block data sub crc32 { my $self = $_[0]; return unpack('%C32' => $self->data()); } # Return data one char at a time sub data { my $self = $_[0]; return wantarray ? split(//, $self->{data}) : substr($self->{data}, 0, $self->{'length'}) } sub number { my $self = $_[0]; return $self->{number}; } # Calculate checksum/crc for the current block and stringify block for transfer sub to_string { my $self = $_[0]; my $block_num = $self->number(); # Assemble block to be transferred my $xfer = pack( 'cccA'.$self->{'length'}.'c', $self->{'length'} == 128 ? Xmodem::Constants::soh # Start Of Header (block size = 128) : Xmodem::Constants::stx, # Start Of Text (block size = 1024) $block_num, # Block number $block_num ^ 0xFF, # 2's complement of block number scalar $self->data, # Data chars $self->checksum() # Final checksum (or crc16 or crc32) # TODO crc16, crc32 ? ); return $xfer; } # # verify( type, value ) # ex.: verify( 'checksum', 0x7F ) # ex.: verify( 'crc16', 0x8328 ) # sub verify { my($self, $type, $value) = @_; # Detect type of value to be checked # TODO use new constants $type = 'checksum' unless defined $type; if( $type eq 'checksum' ) { $good_value = $self->checksum(); } elsif( $type eq 'crc16' ) { $good_value = $self->crc16(); } elsif( $type eq 'crc32' ) { $good_value = $self->crc32(); } else { $good_value = $self->checksum(); } print 'value:', $value, 'goodvalue:', $good_value; return $good_value == $value; } # ---------------------------------------------------------------- package Xmodem::Buffer; sub new { my($proto, $num, $data) = @_; my $class = ref $proto || $proto; # Define structure of a Xmodem transfer buffer my $self = []; bless($self); return $self; } # Push, pop, operations on buffer sub push { my $self = $_[0]; my $block = $_[1]; push @$self, $block; } sub pop { my $self = $_[0]; pop @$self } # Get last block on buffer (to retransmit / re-receive) sub last { my $self = $_[0]; return $self->[ $#$self ]; } sub blocks { return @{$_[0]}; } # # Replace n-block with given block object # sub replace { my $self = $_[0]; my $num = $_[1]; my $block = $_[2]; $self->[$num] = $block; } sub dump { my $self = $_[0]; my $output; # Join all blocks into string for (my $pos = 0; $pos < scalar($self->blocks()); $pos++) { $output .= $self->[$pos]->data(); } # Clean out any end of file markers (^Z) in data $output =~ s/\x1A*$//; return $output; } # ---------------------------------------------------------------- package Xmodem::Receiver; # Define default timeouts for CRC handshaking stage and checksum normal procedure sub TIMEOUT_CRC () { 3 }; sub TIMEOUT_CHECKSUM () { 10 }; our $TIMEOUT = TIMEOUT_CRC; our $DEBUG = 1; sub abort_transfer { my $self = $_[0]; # Send a cancel char to abort transfer _log('aborting transfer'); $self->modem->atsend( chr(Xmodem::Constants::can) ); $self->modem->port->write_drain() unless $self->modem->ostype() eq 'windoze'; $self->{aborted} = 1; return 1; } # # TODO protocol management # sub new { my $proto = shift; my %opt = @_; my $class = ref $proto || $proto; # Create `modem' object if does not exist _log('opt{modem} = ', $opt{modem}); if( ! exists $opt{modem} ) { require Device::Modem; $opt{modem} = Device::Modem->new(); } my $self = { _modem => $opt{modem}, _filename => $opt{filename} || 'received.dat', current_block => 0, timeouts => 0, }; bless $self, $class; } # Get `modem' Device::SerialPort member sub modem { $_[0]->{_modem}; } # # Try to receive a block. If receive is correct, push a new block on buffer # sub receive_message { my $self = $_[0]; my $message_type; my $message_number = 0; my $message_complement = 0; my $message_data; my $message_checksum; # Receive answer #my $received = $self->modem->answer( undef, 1000 ); #my $received = $self->modem->answer( "/.{132}/", 1000 ); # Had problems dropping bytes from block messages that caused the checksum # to be missing on rare occasions. ($count_in, $received) = $self->modem->port->read(132); _log('[receive_message][', $count_in, '] received [', unpack('H*',$received), '] data'); # Get Message Type $message_type = ord(substr($received, 0, 1)); # If this is a block extract data from message if( $message_type eq Xmodem::Constants::soh ) { # Check block number and its 2's complement ($message_number, $message_complement) = ( ord(substr($received,1,1)), ord(substr($received,2,1)) ); # Extract data string from message $message_data = substr($received,3,128); # Extract checksum from message $message_checksum = ord(substr($received, 131, 1)); } my %message = ( type => $message_type, # Message Type number => $message_number, # Message Sequence Number complement => $message_complement, # Message Number's Complement data => $message_data, # Message Data String checksum => $message_checksum, # Message Data Checksum ); return %message; } sub run { my $self = $_[0]; my $modem = $self->{_modem}; my $file = $_[1] || $self->{_filename}; my $protocol = $_[2] || Xmodem::Constants::XMODEM; _log('[run] checking modem[', $modem, '] or file[', $file, '] members'); return 0 unless $modem and $file; # Initialize transfer $self->{current_block} = 0; $self->{timeouts} = 0; # Initialize a receiving buffer _log('[run] creating new receive buffer'); my $buffer = Xmodem::Buffer->new(); # Stage 1: handshaking for xmodem standard version _log('[run] sending first timeout'); $self->send_timeout(); my $file_complete = 0; $self->{current_block} = Xmodem::Block->new(0); # Open output file return undef unless open OUTFILE, '>'.$file; # Main receive cycle (subsequent timeout cycles) do { # Try to receive a message my %message = $self->receive_message(); if ( $message{type} eq Xmodem::Constants::nul ) { # Nothing received yet, do nothing _log('[run] ', $message{type}); } elsif ( $message{type} eq Xmodem::Constants::eot ) { # If last block transmitted mark complete and close file _log('[run] ', $message{type}); # Acknoledge we received $self->send_ack(); $file_complete = 1; # Write buffer data to file print(OUTFILE $buffer->dump()); close OUTFILE; } elsif ( $message{type} eq Xmodem::Constants::soh ) { # If message header, check integrity and build block _log('[run] ', $message{type}); my $message_status = 1; # Check block number if ( (255 - $message{complement}) != $message{number} ) { _log('[run] bad block number: ', $message{number}, ' != (255 - ', $message{complement}, ')' ); $message_status = 0; } # Check block numbers for out of sequence blocks if ( $message{number} < $self->{current_block}->number() || $message{number} > ($self->{current_block}->number() + 1) ) { _log('[run] bad block sequence'); $self->abort_transfer(); } # Instance a new "block" object from message data received my $new_block = Xmodem::Block->new( $message{number}, $message{data} ); # Check block against checksum if (!( defined $new_block && $new_block->verify( 'checksum', $message{checksum}) )) { _log('[run] bad block checksum'); $message_status = 0; } # This message block was good, update current_block and push onto buffer if ($message_status) { _log('[run] received block ', $new_block->number()); # Update current block to the one received $self->{current_block} = $new_block; # Push block onto buffer $buffer->push($self->{current_block}); # Acknoledge we successfully received block $self->send_ack(); } else { # Send nak since did not receive block successfully _log('[run] message_status = 0, sending '); $self->send_nak(); } } else { _log('[run] neither types found, sending timingout'); $self->send_timeout(); } } until $file_complete or $self->timeouts() >= 10; } sub send_ack { my $self = $_[0]; _log('sending ack'); $self->modem->atsend( chr(Xmodem::Constants::ack) ); $self->modem->port->write_drain(); $self->{timeouts} = 0; return 1; } sub send_nak { my $self = $_[0]; _log('sending timeout (', $self->{timeouts}, ')'); $self->modem->atsend( chr(Xmodem::Constants::nak) ); my $received = $self->modem->answer( undef, TIMEOUT_CHECKSUM ); _log('[nak_dump] received [', unpack('H*',$received), '] data'); $self->modem->port->write_drain(); $self->{timeouts}++; return 1; } sub send_timeout { my $self = $_[0]; _log('sending timeout (', $self->{timeouts}, ')'); $self->modem->atsend( chr(Xmodem::Constants::nak) ); $self->modem->port->write_drain(); $self->{timeouts}++; return 1; } sub timeouts { my $self = $_[0]; $self->{timeouts}; } sub _log { print STDERR @_, "\n" if $DEBUG } 1; =head1 NAME Device::Modem::Protocol::Xmodem =head1 Xmodem::Block Class that represents a single Xmodem data block. =head2 Synopsis my $b = Xmodem::Block->new( 1, 'My Data......' ); if( defined $b ) { # Ok, block instanced, verify its checksum if( $b->verify( 'checksum', ) ) { ... } else { ... } } else { # No block } # Calculate checksum, crc16, 32, ... $crc16 = $b->crc16(); $crc32 = $b->crc32(); $chksm = $b->checksum(); =head1 Xmodem::Buffer Class that implements an Xmodem receive buffer of data blocks. Every block of data is represented by a C object. Blocks can be Bed and Bped from the buffer. You can retrieve the B block, or the list of B from buffer. =head2 Synopsis my $buf = Xmodem::Buffer->new(); my $b1 = Xmodem::Block->new(1, 'Data...'); $buf->push($b1); my $b2 = Xmodem::Block->new(2, 'More data...'); $buf->push($b2); my $last_block = $buf->last(); print 'now I have ', scalar($buf->blocks()), ' in the buffer'; # TODO document replace() function ??? =head1 Xmodem::Constants Package that contains all useful Xmodem protocol constants used in handshaking and data blocks encoding procedures =head2 Synopsis Xmodem::Constants::soh ........... 'start of header' Xmodem::Constants::eot ........... 'end of trasmission' Xmodem::Constants::ack ........... 'acknowlegded' Xmodem::Constants::nak ........... 'not acknowledged' Xmodem::Constants::can ........... 'cancel' Xmodem::Constants::C ........... `C' ASCII char Xmodem::Constants::XMODEM ........ basic xmodem protocol Xmodem::Constants::XMODEM_1K ..... xmodem protocol with 1k blocks Xmodem::Constants::XMODEM_CRC .... xmodem protocol with CRC checks Xmodem::Constants::CHECKSUM ...... type of block checksum Xmodem::Constants::CRC16 ......... type of block crc16 Xmodem::Constants::CRC32 ......... type of block crc32 =head1 Xmodem::Receiver Control class to initiate and complete a C file transfer in receive mode =head2 Synopsis my $recv = Xmodem::Receiver->new( modem => {Device::Modem object}, filename => 'name of file', XXX protocol => 'xmodem' | 'xmodem-crc', | 'xmodem-1k' ); $recv->run(); =head2 Object methods =over 4 =item abort_transfer() Sends a B char (C), that signals to sender that transfer is aborted. This is issued if we receive a bad block number, which usually means we got a bad line. =item modem() Returns the underlying L object. =item receive_message() Retrieves message from modem and if a block is detected it breaks it into appropriate parts. =item run() Starts a new transfer until file receive is complete. The only parameter accepted is the (optional) local filename to be written. =item send_ack() Sends an acknowledge (C) char, to signal that we received and stored a correct block Resets count of timeouts and returns the C object of the data block received. =item send_timeout() Sends a B (C) char, to signal that we received a bad block header (either a bad start char or a bad block number), or a bad data checksum. Increments count of timeouts and at ten timeouts, aborts transfer. =back =head2 See also =over 4 =item - L =back Device-Modem-1.59/lib/Device/Modem/Log/0000755000175000017500000000000013671620770017012 5ustar cosimocosimoDevice-Modem-1.59/lib/Device/Modem/Log/File.pm0000644000175000017500000001033013671617660020230 0ustar cosimocosimo# Device::Modem::Log::File - Text files logging plugin for Device::Modem class # # Copyright (C) 2002-2004 Cosimo Streppone, cosimo@cpan.org # # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # # Additionally, this is ALPHA software, still needs extensive # testing and support for generic AT commads, so use it at your own risk, # and without ANY warranty! Have fun. # # $Id$ # package Device::Modem::Log::File; our $VERSION = '2.11'; $VERSION = eval $VERSION; use strict; use File::Path (); use File::Basename (); use IO::Handle; # Define log levels like syslog service our %levels = ( debug => 7, info => 6, notice => 5, warning => 4, err => 3, error => 3, crit => 2, alert => 1, emerg => 0 ); sub new { my( $class, $package, $filename ) = @_; # Get a decent default if no file available $filename ||= default_filename(); my %obj = ( file => $filename, loglevel => 'info' ); my $self = bless \%obj, 'Device::Modem::Log::File'; # Open file at the start and save reference my $LOGFILE = new IO::Handle; if( open( $LOGFILE, '>>'.$self->{'file'} ) ) { $self->{'fh'} = $LOGFILE; # Unbuffer writes to logfile my $oldfh = select $self->{'fh'}; $| = 1; select $oldfh; } else { warn('Could not open '.$self->{'file'}.' to start logging'); } return $self; } # Provide a suitable filename default sub default_filename () { my $dir = '/tmp'; # If this is windows, use the temp/tmp dirs if (exists $ENV{'TEMP'} || exists $ENV{'TMP'}) { $dir = $ENV{'TEMP'} || $ENV{'TMP'}; } return "$dir/modem.log"; } sub filename { my $self = shift(); $self->{'file'} ||= $self->default_filename(); if( ! -d File::Basename::dirname($self->{'file'}) ) { File::Path::mkpath( File::Basename::dirname($self->{'file'}), 0, 0755 ); } return $self->{'file'}; } sub loglevel { my($self, $newlevel) = @_; if( defined $newlevel ) { $newlevel = lc $newlevel; if( ! exists $levels{$newlevel} ) { $newlevel = 'warning'; } $self->{'loglevel'} = $newlevel; } else { return $self->{'loglevel'}; } } sub write($$) { my($self, $level, @msg) = @_; # If log level mask allows it, log given message #warn('message level='.$level.' ('.$levels{$level}.') loglevel='.$self->{loglevel}.' ('.$levels{$self->{loglevel}}.')'); if( $levels{$level} <= $levels{$self->{'loglevel'}} ) { if( my $fh = $self->fh() ) { map { tr/\r\n/^M/s } @msg; print $fh join("\t", scalar localtime, $0, $level, @msg), "\n"; } else { warn('cannot log '.$level.' '.join("\t",@msg).' to file: '.$! ); } } } sub fh { my $self = shift; return $self->{'fh'}; } # Closes log file opened in new() sub close { my $self = shift; my $fh = $self->{'fh'}; close $fh; undef $self->{'fh'}; } 1; __END__ =head1 NAME Device::Modem::Log::File - Text files logging plugin for Device::Modem class =head1 SYNOPSIS use Device::Modem; my $box = Device::Modem->new( log => 'file', ... ); my $box = Device::Modem->new( log => 'file,name=/tmp/mymodem.log', ... ); ... =head1 DESCRIPTION This is meant for an example log class to be hooked to C to provide one's favourite logging mechanism. You just have to implement your own C, C and C methods. Default text file is C. On Windows platforms, this goes into C<%TEMP%/modem.log> or C<%TMP%/modem.log>, whichever is defined. By default, if the folder of the log file does not exist, it is created. This class is loaded automatically by C class when an object is instantiated, and it is the B logging mechanism for C class. Normally, you should B need to use this class directly, because there are many other zillions of modules that do logging better than this. Also, it should be pondered whether to replace C and mates with those better classes in a somewhat distant future. =head2 REQUIRES Device::Modem =head2 EXPORTS None =head1 AUTHOR Cosimo Streppone, cosimo@cpan.org =head1 COPYRIGHT (C) 2002 Cosimo Streppone, This library is free software; you can only redistribute it and/or modify it under the same terms as Perl itself. =head1 SEE ALSO L L =cut Device-Modem-1.59/lib/Device/Modem/Log/Syslog.pm0000644000175000017500000000461313671617660020640 0ustar cosimocosimo# Device::Modem::Log::Syslog - Syslog logging plugin for Device::Modem class # # Copyright (C) 2002-2004 Cosimo Streppone, cosimo@cpan.org # # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # # Additionally, this is ALPHA software, still needs extensive # testing and support for generic AT commads, so use it at your own risk, # and without ANY warranty! Have fun. # # $Id$ package Device::Modem::Log::Syslog; our $VERSION = '2.11'; $VERSION = eval $VERSION; use strict; use Sys::Syslog (); sub new { my($class, $package) = @_; Sys::Syslog::setlogsock('unix'); Sys::Syslog::openlog($package, 'cons,pid', 'user'); my $loglevel = 'info'; bless \$loglevel, 'Device::Modem::Log::Syslog'; } { # Define log levels like syslog service my %levels = ( debug => 7, info => 6, notice => 5, warning => 4, err => 3, crit => 2, alert => 1, emerg => 0 ); sub loglevel { my($self, $newlevel) = @_; if( defined $newlevel ) { $newlevel = lc $newlevel; if( $newlevel eq 'verbose' ) { $newlevel = 'info'; } if( ! exists $levels{$newlevel} ) { $newlevel = 'notice'; } $$self = $newlevel; # Set new logmask my $logmask = 0xFF; #(1 << ($levels{$newlevel} + 1)) - 1; Sys::Syslog::setlogmask( $logmask ); } else { return $$self; } } sub write($$) { my($self, $level, @msg) = @_; Sys::Syslog::syslog( $level, @msg ); return 1; } } sub close { my $self = shift(); Sys::Syslog::closelog(); } 1; __END__ =head1 NAME Device::Modem::Log::Syslog - Syslog logging plugin for Device::Modem class =head1 SYNOPSIS use Device::Modem; my $box = Device::Modem->( log => 'syslog', ... ); ... =head1 DESCRIPTION Example log class for B that logs all modem activity, commands, ... to B It is loaded automatically at B startup, only if you specify C value to C parameter. If you don't have B additional module installed, you will not be able to use this logging plugin, and you should better leave the default logging (to text file). =head2 REQUIRES C =head2 EXPORTS None =head1 AUTHOR Cosimo Streppone, cosimo@cpan.org =head1 COPYRIGHT (C) 2002 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. =head1 SEE ALSO C C =cut Device-Modem-1.59/lib/Device/Modem/FAQ.pod0000644000175000017500000001503613671617660017415 0ustar cosimocosimo=head1 Device::Modem::FAQ This is a Frequently Asked Questions list about C perl extension. =head2 What is C? C is a L extension written in pure perl that allows to communicate with modems, or generically with C devices connected to your computer via a B. =head2 Who is the author of this work? Cosimo Streppone (L), an Italian guy, who works and enjoys writing perl programs and objects. If you want to know more, go to http://www.streppone.it/cosimo/work/perl/ =head2 BTW, what is L? If you are asking that, probably you are in the wrong place. L is a wonderful programming language, that cuts development times, helps developer keep mental health, good life-style, doesn't pollute developer's mind, allows complete freedom of style, and (from perl manual), I. Some starting points: =over 4 =item * L - Reference site for Perl programmers =item * L - Perl Mongers home =item * L - Comprehensive Perl Archive Network =item * L - Higher Perl souls =item * L - Large Perl community =back =head2 What is an C? It is a set of standard commands, also called C, in which (almost) all commands begin with C prefix and they allow to control a modem, router, whatever device. Also cellular phones work with a subset of standard C commands. =head2 What is a modem? What the heck are you doing here? http://www.google.com/search?q=Tech+glossary+modem =head2 What are the requisites of C? You must have: =over 4 =item * A working computer with a standard RS-232 serial port =item * An AT-compliant device (a modem will do perfectly here :-) =item * A working Perl installation =item * C module installed if you are on some unix platform. C module installed if you are on Win32 platform. =back =head2 Is it multi-platform? C works close to the serial port communication layer, which varies on many platforms. It relies on C and C modules for all low-level communication layer. It tries to build a platform independent layer above these two low-level modules, so developers don't need to distinguish among different platforms. It's been reported to work on C, C, C, C, C, C, C and C. =head2 Can I use it for my commercial application? Yes, it is allowed by its license, that is the same as Perl language. If you are using it in a commercial package, or plan to do so, please inform the author (Cosimo Streppone, L). Thank you. =head2 Why the [insert_you_preferred_feature_here] does not work? This is an open-source software developed in my little home spare time and for my personal interest and amusement. This module has a test suite, but it is not very extensive, so it is possible that some feature X does not work, or it is not implemented yet or I cannot test it. If you are in this situation, please contact L and provide the following information: =over 4 =item * Your operating system version and architecture. Complete output of C command is good for this. =item * Your perl version. Again C. =item * Your C, C and (if you are using it) C version. In case of doubt, send the output of: perl -MDevice::Modem -le 'print Device::Modem->VERSION' =back Thank you. =head2 Do XModem transfers work? This is definitely reported to be working by several users, who also contributed patches and tested the feature. Otherwise, just look at Aaron Mitti's Device::SerialPort::Xmodem CPAN module. =head2 XModem sucks. What about ZModem? It might seem that XModem and ZModem should be well over dead at this point. But, looks like several old/new devices still support them. So, B support has been contributed by a user, and will be added to the main release Soon(tm). =head2 Why I keep getting "can't open device: /dev/xxxxx at .../Modem.pm line 468" errors ? First of all, be sure to use B. Probably you don't have the correct permissions to access your modem device (usually /dev/modem, or /dev/ttyS0 on unix and COM1/COM2/... on windows). Or you are trying to use the examples that come with Device::Modem distribution with an older version (Device::Modem <= 1.33). In this case, you should upgrade to Device::Modem 1.52+. =head2 Why I get the error "Can't call method "purge_all" on an undefined value at .../Modem.pm line 545" ? Again, B. If you get this error, it means that the communication port could not be opened. Most probably you don't have permissions to access your serial port, or you have used a wrong device name (check your device entry in C folder). Since version 1.52, C will try to automatically reconnect if your port connection shuts down, or the C, or C underlying object is deleted or invalidated. You should really upgrade to Device::Modem 1.52+. =head2 Can I make voice calls with this modem? B. What you can do, is voice call B. After the dialing though, you have to speak. Your computer can not do that, unless you have a PBX board, at least not with Device::Modem. =head2 This module is pretty slow. What can I do? Make sure you are using that latest version. From version 1.30, the main "send-command" / "wait-answer" cycle has been sensibly improved for speed, though you now have to specify a timeout if you want the module to wait an answer if modem is not ready. Probably this is the better compromise... =head2 Can I make a [insert_your_preferred_number_here] euro donation to you for this fantastic module? Oh, yes! Please feel free to contact L to decide details about this... :-) =for html Or, if you have nothing wrong with that, go to my Amazon wishlist. =for pod Or, if you have nothing wrong with that, go to my amazon wishlist (C). =head2 I think you are a ?#!x$*z!#(!* and your software sucks Uh. Please contact me, so I can improve my software design, ideas and coding, but only if you explain the reasons of your criticism. Thank you. Device-Modem-1.59/lib/Device/Modem/UsRobotics.pm0000644000175000017500000004421713671617660020737 0ustar cosimocosimo# Device::Modem::UsRobotics - control USR modems self mode # # Copyright (C) 2004-2005 Cosimo Streppone, cosimo@cpan.org # # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # # Additionally, this is ALPHA software, still needs extensive # testing and support for generic AT commads, so use it at your own risk, # and without ANY warranty! Have fun. # # Portions of this code are adapted from TkUsr tcl program # published with the GPL by Ludovic Drolez (ldrolez@free.fr). # Here is his copyright and license statements: # # TkUsr v0.80 # # Copyright (C) 1998-2003 Ludovic Drolez (ldrolez@free.fr) # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # # $Id$ package Device::Modem::UsRobotics; our $VERSION = '1.58'; $VERSION = eval $VERSION; use strict; use base 'Device::Modem'; use constant DLE => chr(0x10); use constant SUB => chr(0x1A); use constant ETX => chr(0x03); our %CACHE; sub dump_memory { my($self, $memtype) = @_; $memtype = 2 unless defined $memtype; my $cmd = ''; if( $memtype == 2 || $memtype eq 'messages' ) { $cmd = 'MTM'; } $cmd = 'AT+' . $cmd . Device::Modem::CR; $self->atsend($cmd); $self->wait(500); my $data = $self->answer(); $self->log->write('info', 'dumped messages memory (length: '.length($data).')'); return($data); } #sub dump_page #{ # my($self, $page) = @_; # $self->atsend( sprintf('AT+MTP=%d'.Device::Modem::CR, 0 + $page) ); # $self->wait(500); # my $data = $self->answer(); # $self->log->write('info', 'dumped memory page '.$page.' (length: '.length($data).')'); # return($data); #} sub get_mem_page($) { my($self, $page) = @_; # # get a memory page and cache it for fast retrieving # return $CACHE{$page} if exists $CACHE{$page}; # Download a page #set device(binary) 1 #fconfigure $device(dev) -translation binary # Get the page $self->atsend( sprintf('AT+MTP=%d'.Device::Modem::CR, 0 + $page) ); $self->wait(100); # Wait for data my $data = $self->answer(); #set device(buffer) "" # cache the page $CACHE{$page} = $data; ## cancel binary mode #fconfigure $device(dev) -translation auto #set device(binary) 0 return $data; } sub mcc_get { my $self = $_[0]; $self->atsend('AT+MCC?'.Device::Modem::CR); my @time; my($ok, @data) = $self->parse_answer(); if( index($ok, 'OK') >= 0 ) { @time = split ',', $data[0]; $self->log->write('info', sprintf('MCC: %d days, %02d hrs, %02d mins, %02d secs after last clock reset', @time) ); return wantarray ? @time : join(',',@time); } else { $self->log->write('warning', 'MCC: failed to get clock value'); return undef; } } # # Takes days,hrs,mins values and obtains a real time value # sub mcc_merge { my($self, $d, $h, $m) = @_; $_ += 0 for $d, $h, $m ; if( $d == $h && $h == $m && $m == 255 ) { $self->log->write('warning', 'invalid time 255,255,255'); return(time()); } my $mcc_last = $self->mcc_last_saved(); $mcc_last += 86400 * $d + 3600 * $h + 60 * $m; $self->log->write('info', "$d days, $h hours, $m mins is real time ".localtime($mcc_last)); return($mcc_last); } sub mcc_last_saved { my $self = $_[0]; my $dir = $self->_createSettingsDir(); my $mcc_basetime = undef; if( ! -d $dir ) { return undef; } elsif( open SETTINGS, "$dir/mcc_timer" ) { chomp($mcc_basetime = ); } $self->log->write('info', 'last mcc timer saved at '.localtime($mcc_basetime)); return($mcc_basetime); } sub mcc_reset { my $self = $_[0]; $self->atsend('AT+MCC'.Device::Modem::CR); my($ok, $ans) = $self->parse_answer(); $self->log->write('info', 'internal timer reset to 00 days, 00 hrs, 00 mins'); if( index($ok, 'OK') >= 0 ) { # Create settings dir my $dir = $self->_createSettingsDir(); if( -d $dir ) { if( open SETTINGS, "> $dir/mcc_timer" ) { print SETTINGS time(), "\n"; $ok = close SETTINGS; } } else { $self->log->write('warning', 'Failed writing mcc timer settings in ['.$dir.']'); } } } sub msg_status { my($self, $index) = @_; $self->atsend('AT+MSR=0'.Device::Modem::CR); my($ok, @data) = $self->parse_answer(); if( index($ok,'OK') >= 0 ) { $self->log->write('info', 'MSR: '.join('/ ', @data)); return wantarray ? @data : join("\n", @data); } else { $self->log->write('warning', 'MSR: Error in querying status'); return undef; } } sub clear_memory { my($self, $memtype) = @_; $memtype = 2 unless defined $memtype; my $cmd = ''; if( $memtype == 0 || $memtype eq 'all' ) { $cmd = 'MEA'; } elsif( $memtype == 1 || $memtype eq 'user' ) { $cmd = 'MEU'; } elsif( $memtype == 2 || $memtype eq 'messages' ) { $cmd = 'MEM'; } $cmd = 'AT+' . $cmd . Device::Modem::CR; $self->atsend($cmd); $self->wait(500); $self->log->write('info', 'cleared memory type '.$memtype); return(1); } sub fax_id_string { my $self = shift; my $result = ''; if( @_ ) { $self->atsend( sprintf('AT+MFI="%s"',$_[0]) . Device::Modem::CR ); $self->wait(100); my($ok, $ans) = $self->parse_answer(); $self->log->write('info', 'New Fax ID string set to ['.$_[0].']'); $result = $ok; } else { # Retrieve current fax id string $self->atsend('AT+MFI?' . Device::Modem::CR); $self->wait(100); my($ok, $ans) = $self->parse_answer(); $self->log->write('info', 'Fax ID string is ['.$ans.']'); # Remove double quotes chars if present $ans = substr($ans, 1, -1) if $ans =~ /^".*"$/; $result = $ans; } $self->log->write('debug', 'fax_id_string answer is ['.$result.']'); return($result); } sub messages_info { my $me = $_[0]; $me->atsend('AT+MSR=0'.Device::Modem::CR); $me->wait(100); my $info_string = $me->answer(); my @keys = qw( memory_size memory_used stored_voice_msg unreleased_voice_msg stored_fax_msg unreleased_fax_msg ); my %data; my $n = 0; for( split ',', $info_string, 6 ) { $data{$keys[$n++]} = 0 + $_; } $me->log->write('info', "Memory size is $data{memory_size} Mb. Used $data{memory_used}%"); $me->log->write('info', "Voice messages: $data{unreleased_voice_msg}/$data{stored_voice_msg} unread"); $me->log->write('info', "Fax messages: $data{unreleased_fax_msg}/$data{stored_fax_msg} unread"); return %data; } sub message_dump { my($me, $msg) = @_; my %info = $me->message_info($msg); if( exists $info{index} && $info{index} > 0 ) { $me->log->write('info', sprintf('message %d starts at page %d address %x%x', $msg, $info{page}, $info{addresshigh}, $info{addresslow})); my $mem_page = $me->get_mem_page($info{page}); my $offset = $info{addresshigh} << 8 + $info{addresslow}; $me->log->write('info', sprintf('offset in page %d is %d (%x)', $info{page}, $offset, $offset)); $mem_page = substr($mem_page, $offset); $me->message_scan_page($mem_page); } return undef; } sub message_scan_page($\$) { my($me, $page) = @_; my $block_len = 32768; my $header_len = 32; my $pos = 0; my $len = length($page); while( $pos <= $len ) { # Read next message # XXX #my $chksum = substr($page, $pos, 2); #$pos += 2; my $chksum = 0; my $block = substr($page, $pos, $block_len); $pos += $block_len; # Check checksum my $calc_chksum = 0; for( 0 .. length($block) ) { $calc_chksum += ord(substr($block,$_,1)); $calc_chksum &= 0xFF; } my $header = substr($block, 0, $header_len); print "Calculated checksum = ", $calc_chksum, "\n"; print "Declared checksum = ", hex($chksum), "\n"; my @msg = unpack('CCCCCCCCA20CSCS', $header); my @fld = qw(index type info attrs recvstat days hours minutes sender p_page p_addr n_page n_addr); my %msg = map { $_ => shift(@msg) } @fld; foreach( @fld ) { print "MESSAGGIO $_ = [", $msg{$_}, "]\n"; } print "-" x 60, "\n"; } } sub message_info { my($me, $msg) = @_; unless( $msg > 0 && $msg < 255 ) { $me->log->write('warning', 'message_info(): message index must be 0 < x < 255'); return undef; } # Send message info command $me->atsend("AT+MSR=$msg".Device::Modem::CR); $me->wait(100); my $info_string = $me->answer(); my @keys = qw( index type information attributes status day hour minute callerid page addresshigh addresslow checksum ); my %data; my $n = 0; for( split(',', $info_string, scalar @keys) ) { $data{$keys[$n]} = $_; $me->log->write('info', 'Message '.$keys[$n].': '.$data{$keys[$n]}); $n++; } return %data; } sub _createSettingsDir { my $self = $_[0]; my $ok = 1; require File::Path; my $dir = $self->_settingsDir(); if( ! -d $dir ) { $ok = File::Path::mkpath( $dir, 0, 0700 ); } return($ok ? $dir : undef); } sub _settingsDir { "$ENV{HOME}/.usrmodem" } # # retrieve and save a message in GSM format # sub extract_voice_message($) { my($self, $number) = @_; my $addr; my $d; my $data; my $end; my $header; my $startpage; # Check if this message is really a voice message (type==2) my %msg = $self->message_info($number); return undef unless %msg; return undef if $msg{type} != 2; # set startpage $stat($number.page) $startpage = $msg{page}; # Download the 1st page #set d [GetMemPage $startpage] $d = $self->get_mem_page($startpage); #set addr [expr $stat($number.hi)*256 + $stat($number.lo) + 2] $addr = 2 + $msg{addresslow} + ($msg{addresshigh} << 8); #set header [string range $d $addr [expr $addr+34]] #set data [string range $d [expr $addr+34] end] $header = substr $d, $addr, 34; #$addr + 34; $data = substr $d, $addr + 34; #warn('header ['.$header.']'.(length($header))); # Extract the data from the header #binary scan $header cccccccca20cScS h_idx h_type h_info h_attr h_stat h_day h_hour h_min h_faxid h_ppage h_paddr h_npage h_naddr my @hdr = unpack('cccccccca20cncn', $header); my %hdr = map { $_ => shift @hdr } qw(idx type info attr stat day hour min faxid ppage paddr npage naddr); undef @hdr; # set h_naddr [expr ($h_naddr + 0x10000) % 0x10000] # set h_paddr [expr ($h_paddr + 0x10000) % 0x10000] #$hdr{naddr} = ($hdr{naddr} + 0x10000) % 0x10000; #$hdr{paddr} = ($hdr{paddr} + 0x10000) % 0x10000; $hdr{naddr} &= 0xFFFF; #($hdr{naddr} + 0x10000) % 0x10000; $hdr{paddr} &= 0xFFFF; #($hdr{paddr} + 0x10000) % 0x10000; #for (sort keys %hdr) #{ # warn("header $_ {$hdr{$_}}"); #} # One or more pages ? if($startpage == $hdr{npage}) { # Only one page $data = substr $data, 0, $hdr{naddr}; #warn('1page datalen:'.(length($data))); } else { # Get the following pages $startpage++; while( $startpage <= $hdr{npage} ) { #set d [GetMemPage $startpage] $d = $self->get_mem_page($startpage); # Remove the checksum if( $hdr{npage} == $startpage ) { # set end [expr $h_naddr - 1] $end = $hdr{naddr} - 1; } else { #set end end #$end = $end; } # append data [string range $d 2 $end] if( $end ) { $data .= substr $d, 2, 2 + $end; } else { $data .= substr $d, 2; } #warn('datalen:'.length($data)); #incr startpage $startpage++; } } # Unstuff data, $num should always be 1 # set pages(0) "" my @pages = (); # set num [ByteUnstuff $data pages] my $num = $self->_byte_unstuff($data, \@pages); # Gsm messages have always 1 page #warn('length of final msg = '.length($pages[1])); return $pages[1]; } sub _byte_stuff($) { my($self, $data) = @_; # # Escape DLE (0x10) codes from data: # DLE DLE <= DLE # DLE SUB(0x1A) <= DLE DLE # DLE ETX(0x03) = end of page # # I: data: data to decode # R: escaped data # # set out "" my $out = ''; while (1) { # set id [string first "\x10" $data] my $id = index($data, chr(0x10)); # if {$id == -1} break last if $id == -1; #append out [string range $data 0 [expr $id - 1]] $out .= substr($data, 0, $id - 1); #set nextchar [string index $data [expr $id+1]] my $nextchar = substr($data, $id + 1, 1); #set data [string range $data [expr $id+2] end] $data = substr($data, $id + 2); #switch $nextchar { # "\x10" { append out \x10\x1A } # default { append out \x10\x10$nextchar } #} if( $nextchar eq chr(0x10) ) { $out .= chr(0x10) . chr(0x1A); } else { $out .= chr(0x10) . chr(0x10) . $nextchar; } } # add end of data #append out $data\x10\x03 $out .= $data . chr(0x10) . chr(0x03); return $out; } sub _byte_unstuff(@) { #proc {ByteUnstuff} {data array} { # # Unescape DLE (0x10) codes from data: # DLE DLE => DLE # DLE SUB(0x1A) => DLE DLE # DLE ETX(0x03) = end of page, the data is put in another hash # # I: data: data to decode # O: array: contains one or more pages of data (array(1), array(2)...) # R: number of pages # my($self, $data, $r_pages) = @_; $r_pages ||= []; my $numpage = 1; my $out = ''; my $id; while (1) { # set id [string first "\x10" $data] $id = index($data, DLE); last if $id == -1; #append out [string range $data 0 [expr $id - 1]] $out .= substr($data, 0, $id); #set nextchar [string index $data [expr $id+1]] my $nextchar = substr($data, $id + 1, 1); #set data [string range $data [expr $id+2] end] $data = substr($data, $id + 2); #switch $nextchar { #"\x10" { append out \x10 } #"\x1A" { append out \x10\x10 } #"\x03" { set adata($numpage) $out # set out "" # incr numpage # # end of page #} #default { append out \x10$nextchar } #} if( $nextchar eq DLE ) { $out .= DLE; } elsif( $nextchar eq SUB ) { $out .= DLE . DLE; } elsif( $nextchar eq ETX ) { $r_pages->[$numpage++] = $out; $out = ''; } else { $out .= DLE . $nextchar; } } # Manage last page $r_pages->[$numpage] = $out . $data; return $numpage; } 1; =head1 NAME Device::Modem::UsRobotics - USR modems extensions to control self-mode =head1 SYNOPSIS use Device::Modem::UsRobotics; my $modem = Device::Modem::UsRobotics->new( port => '/dev/ttyS1' ); $modem->connect( baudrate => 9600 ); my %info = $modem->messages_info(); print "There are $info{unreleased_voice_msg} unread voice messages on $info{stored_voice_msg} total\n"; print "There are $info{unreleased_fax_msg} unread fax messages on $info{stored_fax_msg} total\n"; # Get details about message n. X my %msg = $modem->message_info(1); index type information attributes status day hour minute callerid page addresshigh addresslow checksum print 'This is a ', ($msg{type} == 2 ? 'voice' : 'fax'), 'message', "\n"; print 'It came from no. ', $msg{callerid}, "\n"; # ... # Now clear all messages $modem->clear_memory(); =head1 WARNING This module is not documented yet, and it is a rough work in progress. Until now, it correctly reads voice/fax messages information, but when saving voice messages to disk, sometimes they are incorrectly decoded. So, if you need a working program, check out the good old TkUsr by Ludovic Drolez, unless you want to help develop Device::Modem::UsRobotics. =head1 DOCS TO BE COMPLETED FROM NOW..... Yes, I'm a bad boy :-) =head1 DESCRIPTION Bla Bla Bla... =head1 METHODS =head2 clear_memory() Used to permanently clear the memory space of the modem. There are separate memory spaces, one for voice/fax messages and one for user settings. Examples: $modem->clear_memory('user'); # or $modem->clear_memory(1) $modem->clear_memory('messages'); # or $modem->clear_memory(2) To clear both, you can use: $modem->clear_memory('all'); # or $modem->clear_memory(0); Parameters: =over 4 =item C<$memtype> String or integer that selects the type of memory to be cleared, where C<0> is for C, C<1> is for C memory, C<2> is for C memory. =back =head1 SUPPORT Please feel free to contact me at my e-mail address L for any information, to resolve problems you can encounter with this module or for any kind of commercial support you may need. =head1 AUTHOR Cosimo Streppone, L =head1 COPYRIGHT (C) 2004-2005 Cosimo Streppone, L This library is free software; you can only redistribute it and/or modify it under the same terms as Perl itself. =head1 SEE ALSO Device::Modem, perl =cut # vim: set ts=4 sw=4 tw=0 nowrap nu Device-Modem-1.59/lib/Device/Modem.pm0000755000175000017500000012447113671620022016631 0ustar cosimocosimo# Device::Modem - a Perl class to interface generic modems (AT-compliant) # Copyright (C) 2002-2020 Cosimo Streppone, cosimo@cpan.org # # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # Perl licensing terms for details. package Device::Modem; our $VERSION = '1.59'; $VERSION = eval $VERSION; BEGIN { if( index($^O, 'Win') >= 0 ) { # MSWin32 (and not darwin, cygwin, ...) require Win32::SerialPort; Win32::SerialPort->import; # Import line status constants from Win32::SerialPort module *Device::Modem::MS_CTS_ON = *Win32::SerialPort::MS_CTS_ON; *Device::Modem::MS_DSR_ON = *Win32::SerialPort::MS_DSR_ON; *Device::Modem::MS_RING_ON = *Win32::SerialPort::MS_RING_ON; *Device::Modem::MS_RLSD_ON = *Win32::SerialPort::MS_RLSD_ON; } else { require Device::SerialPort; Device::SerialPort->import; # Import line status constants from Device::SerialPort module *Device::Modem::MS_CTS_ON = *Device::SerialPort::MS_CTS_ON; *Device::Modem::MS_DSR_ON = *Device::SerialPort::MS_DSR_ON; *Device::Modem::MS_RING_ON = *Device::SerialPort::MS_RING_ON; *Device::Modem::MS_RLSD_ON = *Device::SerialPort::MS_RLSD_ON; } } use strict; use Carp (); # Constants definition use constant CTRL_Z => chr(26); use constant CR => "\r"; # Connection defaults $Device::Modem::DEFAULT_PORT = index($^O, 'Win') >= 0 ? 'COM1' : '/dev/modem'; $Device::Modem::DEFAULT_INIT_STRING = 'S7=45 S0=0 L1 V1 X4 &c1 E1 Q0'; $Device::Modem::BAUDRATE = 19200; $Device::Modem::DATABITS = 8; $Device::Modem::STOPBITS = 1; $Device::Modem::HANDSHAKE= 'none'; $Device::Modem::PARITY = 'none'; $Device::Modem::TIMEOUT = 500; # milliseconds $Device::Modem::READCHARS= 130; $Device::Modem::WAITCMD = 200; # milliseconds # Setup text and numerical response codes @Device::Modem::RESPONSE = ( 'OK', undef, 'RING', 'NO CARRIER', 'ERROR', undef, 'NO DIALTONE', 'BUSY' ); $Device::Modem::STD_RESPONSE = qr/^(OK|ERROR|COMMAND NOT SUPPORT)$/m; #%Device::Modem::RESPONSE = ( # 'OK' => 'Command executed without errors', # 'RING' => 'Detected phone ring', # 'NO CARRIER' => 'Link not established or disconnected', # 'ERROR' => 'Invalid command or command line too long', # 'NO DIALTONE' => 'No dial tone, dialing not possible or wrong mode', # 'BUSY' => 'Remote terminal busy' #); # object constructor (prepare only object) sub new { my($proto,%aOpt) = @_; # Get reference to object # Options of object my $class = ref($proto) || $proto; # Get reference to class $aOpt{'ostype'} = $^O; # Store OSTYPE in object $aOpt{'ostype'} = 'windoze' if index( $aOpt{'ostype'}, 'Win' ) >= 0; # Initialize flags array $aOpt{'flags'} = {}; # Start as not connected $aOpt{'CONNECTED'} = 0; $aOpt{'port'} ||= $Device::Modem::DEFAULT_PORT; # Instance log object $aOpt{'log'} ||= 'file'; # Force logging to file if this is windoze and user requested syslog mechanism $aOpt{'log'} = 'file' if( $aOpt{'ostype'} eq 'windoze' && $aOpt{'log'} =~ /syslog/i ); $aOpt{'loglevel'} ||= 'warning'; if( ! ref $aOpt{'log'} ) { my($method, @options) = split ',', delete $aOpt{'log'}; my $logclass = 'Device/Modem/Log/'.ucfirst(lc $method).'.pm'; my $package = 'Device::Modem::Log::'.ucfirst lc $method; eval { require $logclass; }; unless($@) { $aOpt{'_log'} = $package->new( $class, @options ); } else { print STDERR "Failed to require Log package: $@\n"; } } else { # User passed an already instanced log object $aOpt{'_log'} = $aOpt{'log'}; } if( ref $aOpt{'_log'} && $aOpt{'_log'}->can('loglevel') ) { $aOpt{'_log'}->loglevel($aOpt{'loglevel'}); } bless \%aOpt, $class; # Instance $class object } sub attention { my $self = shift; $self->log->write('info', 'sending attention sequence...'); # Send attention sequence $self->atsend('+++'); # Wait for response $self->answer(); } sub dial { my($self, $number, $timeout, $mode) = @_; my $ok = 0; # Default timeout in seconds $timeout ||= 30; # Default is data calls if (! defined $mode) { $mode = 'DATA'; } # Numbers with ';' mean voice calls elsif ($mode =~ m{VOICE}i || $number =~ m{;}) { $mode = 'VOICE'; } # Invalid input, or explicit 'DATA' call else { $mode = 'DATA'; } # Check if we have already dialed some number... if ($self->flag('CARRIER')) { $self->log->write( 'warning', 'line is already connected, ignoring dial()' ); return; } # Check if no number supplied if (! defined $number) { # # XXX Here we could enable ATDL command (dial last number) # $self->log->write( 'warning', 'cannot dial without a number!' ); return; } # Remove all non number chars plus some others allowed # Thanks to Pierre Hilson for the `#' (UMTS) # and to Marek Jaros for the `;' (voice calls) $number =~ s{[^0-9,\(\)\*\-#;\sp]}{}g; my $suffix = ''; if ($mode eq 'VOICE') { $self->log->write('info', 'trying to make a voice call'); $suffix = ';'; } # Dial number and wait for response if( length $number == 1 ) { $self->log->write('info', 'dialing address book number ['.$number.']' ); $self->atsend( 'ATDS' . $number . $suffix . CR ); } else { $self->log->write('info', 'dialing number ['.$number.']' ); $self->atsend( 'ATDT' . $number . $suffix . CR ); } # XXX Check response times here (timeout!) my $ans = $self->answer( qr/[A-Z]/, $timeout * 1000 ); if( (index($ans,'CONNECT') > -1) || (index($ans,'RING') > -1) ) { $ok = 1; } # Turn on/off `CARRIER' flag $self->flag('CARRIER', $ok); $self->log->write('info', 'dialing result = '.$ok); return wantarray ? ($ok, $ans) : $ok; } # Enable/disable local echo of commands (enabling echo can cause everything else to fail, I think) sub echo { my($self, $lEnable) = @_; $self->log->write( 'info', ( $lEnable ? 'enabling' : 'disabling' ) . ' echo' ); $self->atsend( ($lEnable ? 'ATE1' : 'ATE0') . CR ); $self->answer($Device::Modem::STD_RESPONSE); } # Terminate current call (XXX not tested) sub hangup { my $self = shift; $self->log->write('info', 'hanging up...'); $self->atsend( 'ATH0' . CR ); my $ok = $self->answer($Device::Modem::STD_RESPONSE); unless ($ok) { $self->attention(); $self->atsend( 'ATH0' . CR ); $self->answer($Device::Modem::STD_RESPONSE, 5000); } $self->_reset_flags(); } # Checks if modem is enabled (for now, it works ok for modem OFF/ON case) sub is_active { my $self = shift; my $lOk; $self->log->write('info', 'testing modem activity on port ' . ($self->options->{'port'} || '') ); # Modem is active if already connected to a line if( $self->flag('CARRIER') ) { $self->log->write('info', 'carrier is '.$self->flag('CARRIER').', modem is connected, it should be active'); $lOk = 1; } else { # XXX Old mode to test modem ... # Try sending an echo enable|disable command #$self->attention(); #$self->verbose(0); #$lOk = $self->verbose(1); # If DSR signal is on, modem is active my %sig = $self->status(); $lOk = $sig{DSR}; undef %sig; # If we have no success, try to reset if( ! $lOk ) { $self->log->write('warning', 'modem not responding... trying to reset'); $lOk = $self->reset(); } } $self->log->write('info', 'modem reset result = '.$lOk); return $lOk; } # Take modem off hook, prepare to dial sub offhook { my $self = shift; $self->log->write('info', 'taking off hook'); $self->atsend( 'ATH1' . CR ); $self->flag('OFFHOOK', 1); return 1; } # Get/Set S* registers value: S_register( number [, new_value] ) # returns undef on failure ( zero is a good value ) sub S_register { my $self = shift; my $register = shift; my $value = 0; return unless $register; my $ok; # If `new_value' supplied, we want to update value of this register if( @_ ) { my $new_value = shift; $new_value =~ s|\D||g; $self->log->write('info', 'storing value ['.$new_value.'] into register S'.$register); $self->atsend( sprintf( 'AT S%02d=%d' . CR, $register, $new_value ) ); $value = ( index( $self->answer(), 'OK' ) != -1 ) ? $new_value : undef; } else { $self->atsend( sprintf( 'AT S%d?' . CR, $register ) ); ($ok, $value) = $self->parse_answer(); if( index($ok, 'OK') != -1 ) { $self->log->write('info', 'value of S'.$register.' register seems to be ['.$value.']'); } else { $value = undef; $self->log->write('err', 'error reading value of S'.$register.' register'); } } # Return updated value of register $self->log->write('info', 'S'.$register.' = '.$value); return $value; } # Repeat the last commands (this comes gratis with `A/' at-command) sub repeat { my $self = shift; $self->log->write('info', 'repeating last command' ); $self->atsend( 'A/' . CR ); $self->answer(); } # Complete modem reset sub reset { my $self = shift; $self->log->write('warning', 'resetting modem on '.$self->{'port'} ); $self->hangup(); my $result = $self->send_init_string(); $self->_reset_flags(); return $result; } # Return an hash with the status of main modem signals sub status { my $self = shift; $self->log->write('info', 'getting modem line status on '.$self->{'port'}); # This also relies on Device::SerialPort my $status = $self->port->modemlines(); # See top of module for these constants, exported by (Win32|Device)::SerialPort my %signal = ( CTS => $status & Device::Modem::MS_CTS_ON, DSR => $status & Device::Modem::MS_DSR_ON, RING => $status & Device::Modem::MS_RING_ON, RLSD => $status & Device::Modem::MS_RLSD_ON ); $self->log->write('info', 'modem on '.$self->{'port'}.' status is ['.$status.']'); $self->log->write('info', "CTS=$signal{CTS} DSR=$signal{DSR} RING=$signal{RING} RLSD=$signal{RLSD}"); return %signal; } # Of little use here, but nice to have it # restore_factory_settings( profile ) # profile can be 0 or 1 sub restore_factory_settings { my $self = shift; my $profile = shift; $profile = 0 unless defined $profile; $self->log->write('warning', 'restoring factory settings '.$profile.' on '.$self->{'port'} ); $self->atsend( 'AT&F'.$profile . CR); $self->answer($Device::Modem::STD_RESPONSE); } # Store telephone number in modem's internal address book, to dial later # store_number( position, number ) sub store_number { my( $self, $position, $number ) = @_; my $ok = 0; # Check parameters unless( defined($position) && $number ) { $self->log->write('warning', 'store_number() called with wrong parameters'); return $ok; } $self->log->write('info', 'storing number ['.$number.'] into memory ['.$position.']'); # Remove all non-numerical chars from position and number $position =~ s/\D//g; $number =~ s/[^0-9,]//g; $self->atsend( sprintf( 'AT &Z%d=%s' . CR, $position, $number ) ); if( index( $self->answer(), 'OK' ) != -1 ) { $self->log->write('info', 'stored number ['.$number.'] into memory ['.$position.']'); $ok = 1; } else { $self->log->write('warning', 'error storing number ['.$number.'] into memory ['.$position.']'); $ok = 0; } return $ok; } # Enable/disable verbose response messages against numerical response messages # XXX I need to manage also numerical values... sub verbose { my($self, $lEnable) = @_; $self->log->write( 'info', ( $lEnable ? 'enabling' : 'disabling' ) . ' verbose messages' ); $self->atsend( ($lEnable ? 'ATQ0V1' : 'ATQ0V0') . CR ); $self->answer($Device::Modem::STD_RESPONSE); } sub wait { my( $self, $msec ) = @_; $self->log->write('debug', 'waiting for '.$msec.' msecs'); # Perhaps Time::HiRes here is not so useful, since I tested `select()' system call also on Windows select( undef, undef, undef, $msec / 1000 ); return 1; } # Set a named flag. Flags are now: OFFHOOK, CARRIER sub flag { my $self = shift; my $cFlag = uc shift; $self->{'_flags'}->{$cFlag} = shift() if @_; $self->{'_flags'}->{$cFlag}; } # reset internal flags that tell the status of modem (XXX to be extended) sub _reset_flags { my $self = shift(); map { $self->flag($_, 0) } 'OFFHOOK', 'CARRIER'; } # initialize modem with some basic commands (XXX &C0) # send_init_string( [my_init_string] ) # my_init_string goes without 'AT' prefix sub send_init_string { my($self, $cInit) = @_; $cInit = $self->options->{'init_string'} unless defined $cInit; # If no Init string then do nothing! if ($cInit) { $self->attention(); $self->atsend('AT '.$cInit. CR ); return $self->answer($Device::Modem::STD_RESPONSE); } } # returns log object reference or nothing if it is not defined sub log { my $me = shift; if( ref $me->{'_log'} ) { return $me->{'_log'}; } else { return {}; } } # instances (Device|Win32)::SerialPort object and initializes communications sub connect { my $me = shift(); my %aOpt = (); if( @_ ) { %aOpt = @_; } my $lOk = 0; # Set default values if missing $aOpt{'baudrate'} ||= $Device::Modem::BAUDRATE; $aOpt{'databits'} ||= $Device::Modem::DATABITS; $aOpt{'parity'} ||= $Device::Modem::PARITY; $aOpt{'stopbits'} ||= $Device::Modem::STOPBITS; $aOpt{'handshake'}||= $Device::Modem::HANDSHAKE; $aOpt{'max_reset_iter'} ||= 0; # Store communication options in object $me->{'_comm_options'} = \%aOpt; # Connect on serial (use different mod for win32) if( $me->ostype eq 'windoze' ) { $me->port( Win32::SerialPort->new($me->{'port'}) ); } else { $me->port( Device::SerialPort->new($me->{'port'}) ); } # Check connection unless( ref $me->port ) { $me->log->write( 'err', '*FAILED* connect on '.$me->{'port'} ); return $lOk; } # Set communication options my $oPort = $me->port; $oPort -> baudrate ( $me->options->{'baudrate'} ); $oPort -> databits ( $me->options->{'databits'} ); $oPort -> stopbits ( $me->options->{'stopbits'} ); $oPort -> parity ( $me->options->{'parity'} ); $oPort -> handshake( $me->options->{'handshake'} ); # Non configurable options $oPort -> buffers ( 10000, 10000 ); $oPort -> read_const_time ( 20 ); # was 500 $oPort -> read_char_time ( 0 ); # read_interval() seems to be unsupported on Device::SerialPort, # while allowed on Win32::SerialPort... if( $oPort->can('read_interval') ) { $oPort->read_interval( 20 ); } $oPort -> are_match ( 'OK' ); $oPort -> lookclear; unless ( $oPort -> write_settings ) { $me->log->write('err', '*FAILED* write_settings on '.$me->{'port'} ); return $lOk; } $oPort -> purge_all; # Get the modems attention # Send multiple reset commands looking for a sensible response. # A small number of modems need time to settle down and start responding to the serial port my $iter = 0; my $ok = 0; my $blank = 0; while ( ($iter < $aOpt{'max_reset_iter'}) && ($ok < 2) && ($blank < 3) ) { $me->atsend('AT E0'. CR ); my $rslt = $me->answer($Device::Modem::STD_RESPONSE, 1500); # print "Res: $rslt \r\n"; $iter+=1; if ($rslt && $rslt =~ /^OK/) { $ok+=1; } else { $ok=0; } if (!$rslt) { $blank++; } else { $blank=0; } } if ($aOpt{'max_reset_iter'}) { $me->log->write('debug', "DEBUG CONNECT: $iter : $ok : $blank\n"); # DEBUG } $me-> log -> write('info', 'sending init string...' ); # Set default initialization string if none supplied my $init_string = defined $me->options->{'init_string'} ? $me->options->{'init_string'} : $Device::Modem::DEFAULT_INIT_STRING; my $init_response = $me->send_init_string($init_string) || ''; $me-> log -> write('debug', "init response: $init_response\n"); # DEBUG $me-> _reset_flags(); # Disable local echo $me-> echo(0); $me-> log -> write('info', 'Ok connected' ); $me-> {'CONNECTED'} = 1; } # $^O is stored into object sub ostype { my $self = shift; $self->{'ostype'}; } # returns Device::SerialPort reference to hash options sub options { my $self = shift(); @_ ? $self->{'_comm_options'} = shift() : $self->{'_comm_options'}; } # returns Device::SerialPort object handle sub port { my $self = shift; if (@_) { return ($self->{'_comm_object'} = shift); } my $port_obj = $self->{'_comm_object'}; # Maybe the port was disconnected? if (defined $self->{'CONNECTED'} && $self->{'CONNECTED'} == 1 && # We were connected (! defined $port_obj || ! $port_obj)) { # Now we aren't anymore # Avoid recursion on ourselves $self->{'CONNECTED'} = 0; # Try to reconnect if possible my $connect_options = $self->options; # No connect options probably because we didn't ever connect if (! $connect_options) { Carp::croak("Not connected"); } $self->connect(%{ $connect_options }); $port_obj = $self->{'_comm_object'}; } # Still not connected? bail out if (! defined $port_obj || ! $port_obj) { Carp::croak("Not connected"); } return $port_obj; } # disconnect serial port sub disconnect { my $me = shift; $me->port->close(); $me->log->write('info', 'Disconnected from '.$me->{'port'} ); } # Send AT command to device on serial port (command must include CR for now) sub atsend { my( $me, $msg ) = @_; my $cnt = 0; # Write message on port $me->port->purge_all(); $cnt = $me->port->write($msg); my $lbuf=length($msg); my $ret; while ($cnt < $lbuf) { $ret = $me->port->write(substr($msg, $cnt)); $me->write_drain(); last unless defined $ret; $cnt += $ret; } $me->log->write('debug', 'atsend: wrote '.$cnt.'/'.length($msg).' chars'); # If wrote all chars of `msg', we are successful return $cnt == length $msg; } # Call write_drain() if platform allows to (no call for Win32) sub write_drain { my $me = shift; # No write_drain() call for win32 systems return if $me->ostype eq 'windoze'; # No write_drain() if no port object available my $port = $me->port; return unless $port; return $port->write_drain(); } # answer() takes strings from the device until a pattern # is encountered or a timeout happens. sub _answer { my $me = shift; my($expect, $timeout) = @_; $expect = $Device::Modem::STD_RESPONSE if (! defined($expect)); $timeout = $Device::Modem::TIMEOUT if (! defined($timeout)); # If we expect something, we must first match against serial input my $done = (defined $expect and $expect ne ''); $me->log->write('debug', 'answer: expecting ['.($expect||'').']'.($timeout ? ' or '.($timeout/1000).' seconds timeout' : '' ) ); # Main read cycle my $cycles = 0; my $idle_cycles = 0; my $answer; my $start_time = time(); my $end_time = 0; # If timeout was defined, check max time (timeout is in milliseconds) $me->log->write('debug', 'answer: timeout value is '.($timeout||'undef')); if( defined $timeout && $timeout > 0 ) { $end_time = $start_time + ($timeout / 1000); $end_time++ if $end_time == $start_time; $me->log->write( debug => 'answer: end time set to '.$end_time ); } do { my ($what, $howmany); $what = $me->port->read(1) . $me->port->input; $howmany = length($what); # Timeout count incremented only on empty readings if( defined $what && $howmany > 0 ) { # Add received chars to answer string $answer .= $what; # Check if buffer matches "expect string" if( defined $expect ) { my $copy = $answer; $copy =~ s/\r(\n)?/\n/g; # Convert line endings from "\r" or "\r\n" to "\n" $done = ( defined $copy && $copy =~ $expect ) ? 1 : 0; $me->log->write( debug => 'answer: matched expect: '.$expect ) if ($done); } # Check if we reached max time for timeout (only if end_time is defined) } elsif( $end_time > 0 ) { $done = (time >= $end_time) ? 1 : 0; # Read last chars in read queue if( $done ) { $me->log->write('info', 'reached timeout max wait without response'); } # Else we have done } else { $done = 1; } $me->log->write('debug', 'done='.$done.' end='.$end_time.' now='.time().' start='.$start_time ); } while (not $done); $me->log->write('info', 'answer: read ['.($answer||'').']' ); # Flush receive and trasmit buffers $me->port->purge_all; return $answer; } sub answer { my $me = shift(); my $answer = $me->_answer(@_); # Trim result of beginning and ending CR+LF (XXX) if( defined $answer ) { $answer =~ s/^[\r\n]+//; $answer =~ s/[\r\n]+$//; } $me->log->write('info', 'answer: `'.($answer||'').'\'' ); return $answer; } # parse_answer() cleans out answer() result as response code + # useful information (useful in informative commands, for example # Gsm command AT+CGMI) sub parse_answer { my $me = shift; my $buff = $me->answer( @_ ); # Separate response code from information if( defined $buff && $buff ne '' ) { my @buff = split /[\r\n]+/o, $buff; # Remove all empty lines before/after response shift @buff while $buff[0] =~ /^[\r\n]+/o; pop @buff while $buff[-1] =~ /^[\r\n]+/o; # Extract responde code $buff = join( CR, @buff ); my $code = pop @buff; return wantarray ? ($code, @buff) : $buff; } else { return ''; } } 1; =head1 NAME Device::Modem - Perl extension to talk to modem devices connected via serial port =head1 WARNING This is B software, so use it at your own risk, and without B warranty! Have fun. =head1 SYNOPSIS 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(); =head1 DESCRIPTION C class implements basic B device abstraction. It can be inherited by sub classes (as C), which are based on serial connections. =head2 Things C can do =over 4 =item * connect to a modem on your serial port =item * test if the modem is alive and working =item * dial a number and connect to a remote modem =item * work with registers and settings of the modem =item * issue standard or arbitrary C commands, getting results from modem =back =head2 Things C can't do yet =over 4 =item * Transfer a file to a remote modem =item * Control a terminal-like (or a PPP) connection. This should really not be very hard to do anyway. =item * Many others... =back =head2 Things it will never be able to do =over 4 =item * Coffee :-) =back =head2 Examples In the `examples' directory, there are some scripts that should work without big problems, that you can take as (yea) examples: =over 4 =item `examples/active.pl' Tests if modem is alive =item `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. =item `examples/dial.pl' Dials a phone number and display result of call =item `examples/shell.pl' (Very) poor man's minicom/hyperterminal utility =item `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! =back =head1 METHODS =head2 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 C<$answer> that is the string received from modem stripped of all B and B chars B at the beginning and at the end of the string. No in-between B 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: =over 4 =item * C<$expect> - Can be a regexp compiled with C or a simple substring. Input coming from the modem is matched against this parameter. If input matches, result is returned. =item * C<$timeout> - Expressed in milliseconds. After that time, answer returns result also if nothing has been received. Example: C<10000>. Default: C<$Device::Modem::TIMEOUT>, currently 500 ms. =back =head2 atsend() Sends a raw C 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 C<$msg>, that is the raw AT command to be sent to modem expressed as string. You must include the C prefix and final B and/or B manually. There is the special constant C that can be used to include such a char sequence into the at command. Returns C<$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); =head2 attention() This command sends an B sequence to modem. This allows modem to pass in B and accept B commands. Example: $ok = $modem->attention() =head2 connect() Connects C object to the specified serial port. There are options (the same options that C has) to control the parameters associated to serial link. Example: $ok = $modem->connect( [%options] ) List of allowed options follows: =over 4 =item C Controls the speed of serial communications. The default is B<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 C object. =item C This tells how many bits your data word is composed of. Default (and most common setting) is C<8>. This parameter is handled directly by C object. =item C Sets the handshake (or flow control) method for the serial port. By default it is C, but can be either C (hardware flow control) or C (software flow control). These flow control modes may or may not work depending on your modem device or software. =item C Custom initialization string can be supplied instead of the built-in one, that is the following: C, that is taken shamelessly from C utility, I think. =item C Controls how parity bit is generated and checked. Can be B, B or B. Default is B. This parameter is handled directly by C object. =item C Tells how many bits are used to identify the end of a data word. Default (and most common usage) is C<1>. This parameter is handled directly by C object. =back =head2 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 B 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 C<;> 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 C. Examples: # Simple usage. Timeout and mode are optional. $ok = $mode->dial('123456789'); # List context: allows 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 B, returns only success of connection. If modem answer contains the C string, C returns successful state, otherwise a false value is returned. If called in B, returns the same C<$ok> flag, but also the exact modem answer to the dial operation in the C<$answer> scalar. C<$answer> typically can contain strings like: =over 4 =item C =item C =item C =back and so on ... all standard modem answers to a dial command. Parameters are: =over 4 =item C<$number> B, this is the phone number to dial. If C<$number> is only 1 digit, it is interpreted as: B>. So if your code is: $modem->dial( 2, 10 ); This means: dial number in the modem internal address book (see C for a way to read/write address book) in position number B<2> and wait for a timeout of B<10> seconds. =item C<$timeout> B, default is B<30 seconds>. Timeout expressed in seconds to wait for the remote device to answer. Please do not expect an B wait for the number of seconds you specified. =item C<$mode> B, default is C, as string. Allows to specify the type of call. Can be either: =over 4 =item C (default) To perform a B. =item C To perform a B, if your device supports it. No attempt to verify whether your device can do that will be made. =back =back =head2 disconnect() Disconnects C object from serial port. This method calls underlying C of C object. Example: $modem->disconnect(); =head2 echo() Enables or disables local echo of commands. This is managed automatically by C object. Normally you should not need to worry about this. Usage: $ok = $modem->echo( $enable ) =head2 hangup() Does what it is supposed to do. Hang up the phone thus terminating any active call. Usage: $ok = $modem->hangup(); =head2 is_active() Can be used to check if there is a modem attached to your computer. If modem is alive and responding (on serial link, not to a remote call), C returns true (1), otherwise returns false (0). Test of modem activity is done through DSR (Data Set Ready) signal. If this signal is in off state, modem is probably turned off, or not working. From my tests I've found that DSR stays in "on" state after more or less one second I turn off my modem, so know you know that. Example: if( $modem->is_active() ) { # Ok! } else { # Modem turned off? } =head2 log() Simple accessor to log object instanced at object creation time. Used internally. If you want to know the gory details, see C objects. You can also see the B for how to log something without knowing all the gory details. Hint: $modem->log->write('warning', 'ok, my log message here'); =head2 new() C constructor. This takes several options. A basic example: my $modem = Device::Modem->new( port => '/dev/ttyS0' ); if under Linux or some kind of unix machine, or my $modem = Device::Modem->new( port => 'COM1' ); if you are using a Win32 machine. This builds the C object with all the default parameters. This should be fairly usable if you want to connect to a real modem. Note that I'm testing it with a B<3Com US Robotics 56K Message> modem at B<19200> baud and works ok. List of allowed options: =over 4 =item * C - serial port to connect to. On Unix, can be also a convenient link as F (the default value). For Win32, C can be used. =item * C - this specifies the method and eventually the filename for logging. Logging process with C is controlled by B, stored under F folder. At present, there are two main plugins: C and C. C does not work with Win32 machines. When using C plug-in, all log information will be written to a default filename if you don't specify one yourself. The default is F<%WINBOOTDIR%\temp\modem.log> on Win32 and F on Unix. Also there is the possibility to pass a B, if this object provides the following C call: $log_object->write( $loglevel, $logmessage ) You can simply pass this object (already instanced) as the C 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() ); =item * C - default logging level. One of (order of decrescent verbosity): C, C, C, C, C, C, C, C, C. =back =head2 offhook() Takes the modem "off hook", ready to dial. Normally you don't need to use this. Also C goes automatically off hook before dialing. =head2 parse_answer() This method works like C, it accepts the same parameters, but it does not return the raw modem answer. Instead, it returns the answer string stripped of all B/B characters at the beginning B at the end. C is meant as an easy way of extracting result code (C, C, ...) and information strings that can be sent by modem in response to specific commands. Example: > AT xSHOW_MODELx US Robotics 56K Message OK > In this example, C is the result and C is the informational message. In fact, another difference with C is in the return value(s). Here are some examples: $modem->atsend( '?my_at_command?' ); $answer = $modem->parse_answer(); where C<$answer> is the complete response string, or: ($result, @lines) = $modem->parse_answer(); where C<$result> is the C or C final message and C<@lines> is the array of information messages (one or more lines). For the I example, C<$result> would hold "C" and C<@lines> would consist of only 1 line with the string "C". =head2 port() Used internally. Accesses the C underlying object. If you need to experiment or do low-level serial calls, you may want to access 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, C will automatically try to reconnect if it detects a bogus underlying port object. It will reconnect with the same options used when Cing the first time. If no connection has taken place yet, then B will be attempted. =head2 repeat() Repeats the last C command issued. Usage: $ok = $modem->repeat() =head2 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 C commands. =head2 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, that can be different depending on your modem manufacturer. Usage: $ok = $modem->restore_factory_settings( [$profile] ) If no C<$profile> is supplied, C<0> is assumed as default value. Check on your modem hardware manual for the meaning of these B. =head2 S_register() Gets or sets an B value. These are some internal modem registers that hold important information that controls all modem behaviour. If you don't know what you are doing, don't use this method. Usage: $value = $modem->S_register( $reg_number [, $new_value] ); C<$reg_number> ranges from 0 to 99 (sure?). If no C<$new_value> is supplied, return value is the current register value. If a C<$new_value> is supplied (you want to set the register value), return value is the new value or C if there was an error setting the new value. Examples: # Get value of S7 register $modem->S_register(7); # Set value of S0 register to 0 $modem->S_register(0, 0); =head2 send_init_string() Sends the initialization string to the connected modem. Usage: $ok = $modem->send_init_string( [$init_string] ); If you specified an C as an option to C object constructor, that is taken by default to initialize the modem. Else you can specify C<$init_string> parameter to use your own custom initialization string. Be careful! =head2 status() Returns status of main modem signals as managed by C (or C) objects. The signals reported are: =over 4 =item CTS Clear to send =item DSR Data set ready =item RING Active if modem is ringing =item RLSD ??? Released line ??? =back Return value of C call is a hash, where each key is a signal name and each value is > 0 if signal is active, 0 otherwise. Usage: ... my %sig = $modem->status(); for ('CTS','DSR','RING','RLSD') { print "Signal $_ is ", ($sig{$_} > 0 ? 'on' : 'off'), "\n"; } =head2 store_number() Store telephone number in modem internal address book, to be dialed later (see C method). Usage: $ok = $modem->store_number( $position, $number ) where C<$position> is the address book memory slot to store phone number (usually from 0 to 9), and C<$number> is the number to be stored in the slot. Return value is true if operation was successful, false otherwise. =head2 verbose() Enables or disables verbose messages. This is managed automatically by C object. Normally you should not need to worry about this. Usage: $ok = $modem->verbose( $enable ) =head2 wait() Waits (yea) for a given amount of time (in milliseconds). Usage: $modem->wait( [$msecs] ) Wait is implemented via C