fix overwrite of variables on multiple responses
[snmp-json.git] / printer-callbacks.pl
index 832d554..1b722a4 100755 (executable)
@@ -5,6 +5,27 @@ use strict;
 use Net::SNMP;
 use Data::Dump qw(dump);
 
+my $dir = 'public/json/monitor/printers/';
+$dir = "/tmp/printers-" unless -d $dir;
+
+use JSON;
+sub save_json {
+       my ( $ip, $json ) = @_;
+       my $path = $dir . $ip;
+       open(my $fh, '>', $path) || die "$path: $!";
+       print $fh encode_json $json;
+       close($fh);
+       warn "# $path ", -s $path, " bytes\n";
+}
+
+sub iso_datetime {
+       my ($ss,$mm,$hh,$d,$m,$y) = localtime(time);
+       return sprintf "%04d-%02d-%02dT%02d:%02d:%02d", $y+1900, $m, $d, $hh, $mm, $ss;
+}
+
+my $log_path = join('.', $dir . (split(/T/,iso_datetime,2))[0], 'json');
+open(my $log, '>>', $log_path) || die "$log_path: $!";
+
 my $community = 'public';
 my @printers = qw(
 10.60.0.20
@@ -21,7 +42,7 @@ my %vars = qw[
 info                           iso.3.6.1.2.1.1.1.0
 hostname                       iso.3.6.1.2.1.43.5.1.1.16.1
 serial                         iso.3.6.1.2.1.43.5.1.1.17.1
-pages                          iso.3.6.1.2.1.43.10.2.1.4.1
+pages                          iso.3.6.1.2.1.43.10.2.1.4.1.1
 @message                       iso.3.6.1.2.1.43.18.1.1.8
 @consumable.name       iso.3.6.1.2.1.43.11.1.1.6.1
 @consumable.max                iso.3.6.1.2.1.43.11.1.1.8.1
@@ -49,7 +70,8 @@ sub columns_cb {
 
        warn "# $ip var_bind_list ", dump( $session->var_bind_list );
        my $results = $session->var_bind_list;
-       $response->{$ip} = { ip => $ip, utime => time() };
+       $response->{$ip}->{ip} ||= $ip;
+       $response->{$ip}->{utime} ||= time();
        # oid_lex_sort would be wonderfull to use here, but it doesn't work
        foreach my $r_oid ( sort {
                        my ($af,$bf) = ($a,$b);
@@ -62,7 +84,6 @@ sub columns_cb {
                        substr($r_oid,0,length($_)) eq $_
                } keys %$oid2name)[0] || die "no name for $r_oid in ",dump($oid2name);
                my $name = $oid2name->{$oid};
-warn "++ $oid $name $var\n";
                if ( $name =~ m{^\@} ) {
                        my $no_prefix = $name;
                        $no_prefix =~ s{^\@}{};
@@ -128,4 +149,10 @@ foreach my $ip ( keys %$response ) {
        }
 
        print "$ip ",dump($status);
+       save_json $ip => $response->{$ip};
+       print $log encode_json($response->{$ip}),"\n";
 }
+
+close($log);
+warn "# log $log_path ", -s $log_path, " bytes\n";
+