phone-moniter
[tpope-extra.git] / perl / phone-monitor
1 #!/usr/bin/perl
2 # Author: Tim Pope
3
4 # Watches my modem on ttyS4 for new calls and reports the caller id.
5 # Requires a $HOME/bin/phone-call to handle them.
6
7 use strict;
8 use Device::Modem;
9 my $number;
10 #my %status;
11 my %values;
12
13 my $modem = new Device::Modem( port => '/dev/ttyS4', baudrate => '38400', log => 'file,/dev/null');
14
15 $SIG{INT}  = 'death';
16 $SIG{TERM} = 'death';
17 $SIG{QUIT} = 'death';
18
19 sub initialize {
20     my $modem=shift;
21     $modem->connect() || return 0;
22     $modem->atsend( 'AT#CID=1' . Device::Modem::CR );
23     $modem->answer();
24     return 1;
25 }
26
27 daemonize() if (shift eq "-d");
28
29 initialize($modem) || die "Could not initialize modem: $!";
30
31 while(1) {
32         sleep 1;
33         %values = wait_for_ring();
34         #%values=("NMBR" => "2102130787", "NAME" => "WIRELESS CALLER");
35         if($values{"NMBR"}) {
36             print $values{"NMBR"}. " " .$values{"NAME"}, "\n";
37             ring($values{"NMBR"}.' "'.$values{"NAME"}.'"');
38         } elsif (!%values) {last;}
39 }
40 $modem->disconnect();
41
42 sub wait_for_ring {
43     local $_;
44     #eval {
45         #local $SIG{ALRM} = sub { die "alarm\n" };
46         #alarm 15;
47         $_ = $modem->answer("NMBR = [0-9A-Z]*[^0-9A-Z]");
48         #alarm 0
49         #};
50     #if($@) {
51         #die unless $@ eq "alarm\n";
52         #return undef;
53     #} else {
54         #my $CR = Device::Modem::CR;
55         my %values = ("success" => 1);
56         #print ("$_\n"); # if ($_);
57         foreach (split /\r\n/) {
58             if(m/^(.*) = (.*)$/) {
59                 $values{$1} = $2;
60             }
61         }
62         return %values;
63     #}
64 }
65
66 sub ring {
67     system($ENV{"HOME"} . "/bin/phone-call " . $_[0]);
68 }
69
70 sub daemonize {
71     chdir "/";
72     my $pid=fork();
73     if($pid) {
74         exit(0)
75     }
76     elsif(defined($pid))
77     {
78         close STDIN;
79         close STDOUT;
80         open(STDOUT,">/tmp/.phone.log") or die "$!";
81         close STDERR;
82     }
83     else { exit(1); }
84 }
85
86 sub death {
87     $modem->disconnect() if($modem);
88     unlink "/tmp/.phone.log";
89     exit(0);
90 }