fix connection end .END/.DONE
[safeq] / terminal-server.pl
index 4b964ed..992768e 100755 (executable)
@@ -1,10 +1,12 @@
 #!/usr/bin/perl
 use warnings;
 use strict;
+use autodie;
 
 use Data::Dump qw(dump);
 
 use IO::Socket::INET;
+use Time::HiRes;
 
 $| = 1;
 
@@ -25,6 +27,9 @@ my $prices = {
        DUPLEX => -0.05,
 };
 
+
+my $next_nop_t = time() + 5;
+
 while(1) {
        our $client_socket = $socket->accept();
 
@@ -35,11 +40,34 @@ while(1) {
        }
 
        sub client_line {
-               my $line = <$client_socket>;
+               #my $line = <$client_socket>;
+
+               my $line;
+               my $timeout = $next_nop_t - time();
+               if ( $timeout > 0 ) {
+                       eval {
+                               local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
+                               alarm $timeout;
+                               warn "# NOP alarm $timeout";
+                               $line = <$client_socket>;
+                               alarm 0;
+                       };
+                       if ($@) {
+                               # timed out
+                               client_send ".NOP";
+                               $line = <$client_socket>;
+                       }
+               } else {
+                       $line = <$client_socket>;
+               }
+
                if ( defined $line ) {
                        $line =~ s/[\r\n]+$//;
                        warn "<< $line\n";
+               } else {
+                       warn "<< [NULL] connected: ",dump($client_socket), $client_socket->connected;
                }
+
                return $line;
        }
 
@@ -109,22 +137,18 @@ while(1) {
                } elsif ( $line =~ m/^\.NOP/ ) {
                        # XXX it's important to sleep, before sending response or
                        # interface on terminal device will be unresponsive
-                       sleep 1;
-                       client_send  ".NOP";
+                       $next_nop_t = time() + 5; # NOP every 5s?
                } elsif ( $line =~ m/^\.END/ ) {
                        client_send  ".DONE BLK WAIT";
-                       client_send  ".NOP";
-                       my $nop = client_line;
-                       client_send ".DONE $total_pages ".credit($total_charged);
-                       warn "expected NOP got: $nop" unless $nop =~ m/NOP/;
-                       my $null = client_line;
                        $client_socket->close;
-               } else {
+               } elsif (defined $line) {
                        warn "UNKNOWN: ",dump($line);
                        print "Response>";
                        my $r = <STDIN>;
                        chomp $r;
                        client_send $r;
+               } else {
+                       warn "NULL line, connected ", $client_socket->connected;
                }
        }
        warn "# return to accept";