5 RFID-JSONP-server - simpliest possible JSONP server which provides local web interface to RFID readers
9 ./scripts/RFID-JSONP-server.pl [--debug] [--listen=127.0.0.1:9000] [--reader=filter]
16 use Data::Dump qw/dump/;
23 use POSIX qw(strftime);
27 my $listen = '127.0.0.1:9000';
30 my $koha_url = $ENV{KOHA_URL};
32 # internal URL so we can find local address of machine and vmware NAT
33 my $rfid_url = $ENV{RFID_URL};
35 server => $ENV{SIP2_SERVER}, # '10.60.0.11:6002' must be IP!
36 user => $ENV{SIP2_USER},
37 password => $ENV{SIP2_PASSWORD},
38 loc => $ENV{SIP2_LOC},
49 'listen=s', => \$listen,
50 'reader=s', => \$reader,
53 die "need KOHA_URL, eg. http://ffzg.koha-dev.rot13.org:8080" unless $koha_url;
59 if ( my $json = $rfid_sid_cache->{ $hash->{sid} } ) {
62 my $ua = LWP::UserAgent->new;
63 my $url = URI->new( $koha_url . '/cgi-bin/koha/ffzg/rfid/borrower.pl');
65 RFID_SID => $hash->{sid}
67 , JMBAG => $hash->{JMBAG}
69 warn "GET ",$url->as_string;
70 my $response = $ua->get($url);
71 if ( $response->is_success ) {
72 my $json = decode_json $response->decoded_content;
73 $rfid_sid_cache->{ $hash->{sid} } = $json;
76 warn "ERROR ", $response->status_line;
84 my $sock = $sip2->{sock} || die "no sip2 socket";
88 $send .= "\r" unless $send =~ m/\r$/;
89 warn "SIP2 >>>> ",dump($send), "\n";
93 my $expect = substr($send,0,2) | 0x01;
98 warn "SIP2 <<<< ",dump($in), "\n";
100 die "empty read from SIP server" unless length $in > 1;
102 die "expected $expect" unless substr($in,0,2) != $expect;
105 if ( $in =~ s/^([0-9\s]+)// ) {
108 foreach ( split(/\|/, $in ) ) {
109 my ( $f, $v ) = ( $1, $2 ) if m/([A-Z]{2})(.+)/;
110 $hash->{$f} = decode('utf-8',$v);
113 warn "# sip2 hash response ",dump($hash);
118 if ( my $server = $sip2->{server} ) {
119 my $sock = $sip2->{sock} = IO::Socket::INET->new( $server ) || die "can't connect to $server: $!";
120 warn "SIP2 server ", $sock->peerhost, ":", $sock->peerport, "\n";
123 if ( sip2_message("9300CN$sip2->{user}|CO$sip2->{password}|")->{fixed} !~ m/^941/ ) {
124 die "SIP2 login failed";
130 use Biblio::RFID::RFID501;
131 use Biblio::RFID::Reader;
132 my $rfid = Biblio::RFID::Reader->new( shift @ARGV );
133 $rfid->debug( $debug );
138 $index_html = <DATA>;
139 $index_html =~ s{http://koha.example.com:8080}{$koha_url}sg;
146 my $server = IO::Socket::INET->new(
148 LocalAddr => $listen,
153 die "can't setup server: $!" unless $server;
155 $server_url = 'http://' . $listen;
156 print "Server $0 ready at $server_url\n";
158 while (my $client = $server->accept()) {
160 eval { # don't die inside here!
162 $client->autoflush(1);
163 my $request = <$client>;
165 warn "WEB << $request\n" if $debug;
168 if ($request =~ m{^GET (/.*) HTTP/1.[01]}) {
171 if ( $method =~ s{\?(.+)}{} ) {
172 foreach my $p ( split(/[&;]/, $1) ) {
173 my ($n,$v) = split(/=/, $p, 2);
176 warn "WEB << param: ",dump( $param ) if $debug;
180 if ( $path eq '/' ) {
181 print $client "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n$index_html";
182 } elsif ( $path =~ m{^/(examples/.+)} ) {
183 $path = $1; # FIXME prefix with dir for installation
185 warn "static $path $size bytes\n";
186 my $content_type = 'text/plain';
187 $content_type = 'application/javascript' if $path =~ /\.js$/;
188 $content_type = 'text/html' if $path =~ /\.html$/;
189 print $client "HTTP/1.0 200 OK\r\nContent-Type: $content_type\r\nContent-Length: $size\r\n\r\n";
192 open(my $fh, '<', $path) || die "can't open $path: $!";
198 } elsif ( $method =~ m{/scan(/only/(.+))?} ) {
200 my @tags = $rfid->tags( reader => sub {
202 return 1 unless $only;
203 if ( ref($reader) =~ m/$only/i ) {
208 my $json = { time => time() };
209 foreach my $tag ( @tags ) {
210 my $hash = $rfid->to_hash( $tag );
212 $hash->{reader} = $rfid->from_reader( $tag );
213 if ( $hash->{tag_type} eq 'SmartX' ) {
214 my $borrower = rfid_borrower $hash;
215 if ( exists $borrower->{error} ) {
216 warn "ERROR ", dump($borrower);
218 $hash->{borrower} = $borrower->{borrower};
219 $hash->{content} = $borrower->{borrower}->{cardnumber}; # compatibile with 3M tags
222 $hash->{security} = uc unpack 'H*', $rfid->afi( $tag );
224 push @{ $json->{tags} }, $hash;
226 warn "#### ", encode_json($json);
227 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
228 $param->{callback}, "(", encode_json($json), ")\r\n";
229 } elsif ( $method =~ m{/program} ) {
231 my $status = 501; # Not implementd
233 foreach my $p ( keys %$param ) {
234 next unless $p =~ m/^(E[0-9A-F]{15})$/;
236 my $content = Biblio::RFID::RFID501->from_hash({ content => $param->{$p} });
237 $content = Biblio::RFID::RFID501->blank if $param->{$p} eq 'blank';
240 warn "PROGRAM $tag $content\n";
241 $rfid->write_blocks( $tag => $content );
242 $rfid->write_afi( $tag => chr( $param->{$p} =~ /^130/ ? $afi->{secure} : $afi->{unsecure} ) );
245 print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
247 } elsif ( $method =~ m{/secure(.js)} ) {
251 my $status = 501; # Not implementd
253 foreach my $p ( keys %$param ) {
254 next unless $p =~ m/^(E[0-9A-F]{15})$/;
256 my $data = $param->{$p};
259 warn "SECURE $tag $data\n";
260 $rfid->write_afi( $tag => chr(hex($data)) );
264 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
265 $param->{callback}, "({ ok: 1 })\r\n";
267 print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
270 } elsif ( $method =~ m{/sip2/(\w+)/(.+)} ) {
271 my ( $method, $args ) = ( $1, $2 );
272 warn "SIP2: $method [$args]";
274 my $ts = strftime('%Y%m%d %H%M%S', localtime());
275 my $loc = $sip2->{loc} || die "missing sip->{loc}";
276 my $password = $sip2->{password} || die "missing sip->{password}";
280 if ( $method eq 'patron_info' ) {
282 $hash = sip2_message("63000${ts} AO$loc|AA$patron|AC$password|");
284 } elsif ( $method eq 'checkout' ) {
285 my ($patron,$barcode,$sid) = split(/\//, $args, 3);
286 $hash = sip2_message("11YN${ts} AO$loc|AA$patron|AB$barcode|AC$password|BON|BIN|");
287 if ( substr( $hash->{fixed}, 2, 1 ) == 1 ) {
288 $rfid->write_afi( $sid => chr( $afi->{unsecure} ) );
291 } elsif ( $method eq 'checkin' ) {
292 my ($patron,$barcode,$sid) = split(/\//, $args, 3);
293 $hash = sip2_message("09N${ts}${ts}AP|AO${loc}|AB$barcode|AC|BIN|");
294 if ( substr( $hash->{fixed}, 2, 1 ) == 1 ) {
295 $rfid->write_afi( $sid => chr( $afi->{secure} ) );
298 print $client "HTTP/1.0 501 $method not implemented\r\n\r\n";
299 warn "ERROR 501 $request\n";
303 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
304 encode_json( $hash );
307 } elsif ( $method =~ m{/beep/(.*)} ) {
308 my $error = uri_unescape($1);
309 system "beep -f 800 -r 2 -l 100";
310 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n{ beep: '$error' }\n";
311 print "BEEP $error\n";
313 print $client "HTTP/1.0 404 Unkown method\r\n\r\n";
314 warn "ERROR 404 $request\n";
317 print $client "HTTP/1.0 500 No method\r\n\r\n";
318 warn "ERROR 500 $request\n";
324 print $client "HTTP/1.0 500 Error\r\n\r\nContent-Type: text/plain\r\n$@";
336 foreach ( split(/\n/, `ip addr` ) ) {
337 if ( /^\d:\s(\w+):\s/ ) {
339 } elsif ( /^\s+inet\s((\d+)\.(\d+)\.(\d+)\.(\d+))\/(\d+)/ ) {
340 $ip->{ $ip->{_last} } = $1;
342 #warn "# SKIP [$_]\n";
348 my $ua = LWP::UserAgent->new;
349 my $url = URI->new( $rfid_url . '/register.pl');
351 local_ip => $ip->{eth0} || $ip->{ (keys %$ip)[0] },
353 warn "GET ",$url->as_string;
354 my $response = $ua->get($url);
355 if ( $response->is_success ) {
356 warn "# ", $response->decoded_content;
357 my $json = decode_json $response->decoded_content;
358 warn "REGISTER: ",dump($json);
361 warn "ERROR ", $response->status_line;
365 rfid_register if $rfid_url;
371 <title>RFID JSONP</title>
372 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
373 <style type="text/css">
386 label[for=pull-reader] {
394 <script type="text/javascript">
397 if(!window.console) {
398 window.console = new function() {
399 this.info = function(str) {};
400 this.debug = function(str) {};
405 function got_visible_tags(data,textStatus) {
406 var html = 'No tags in range';
408 html = '<ul class="tags">';
409 $.each(data.tags, function(i,tag) {
410 console.debug( i, tag );
411 html += '<li><tt class="' + tag.security + '">' + tag.sid;
412 var content = tag.content || tag.borrower.cardnumber;
415 html += ' <a href="http://koha.example.com:8080/cgi-bin/koha/';
416 if ( tag.type == 1 ) { // book
417 html += 'catalogue/search.pl?q=';
419 html += 'members/member.pl?member=';
421 html += content + '" title="lookup in Koha" target="koha-lookup">' + content + '</a>';
424 html += '<form method=get action=program style="display:inline">'
425 + '<input type=hidden name='+tag.sid+' value="blank">'
426 + '<input type=submit value="Blank" onclick="return confirm(\'Blank tag '+tag.sid+'\')">'
432 html += ' <form method=get action=program style="display:inline">'
433 + '<!-- <input type=checkbox name=secure value='+tag.sid+' title="secure tag"> -->'
434 + '<input type=text name='+tag.sid+' size=12>'
435 + '<input type=submit value="Program">'
443 var arrows = Array( 8592, 8598, 8593, 8599, 8594, 8600, 8595, 8601 );
445 html = '<div class=status>'
447 + ' &#' + arrows[ data.time % arrows.length ] + ';'
451 $('#tags').html( html );
452 window.setTimeout(function(){
454 },200); // re-scan every 200ms
457 function scan_tags() {
458 console.info('scan_tags');
459 if ( $('input#pull-reader').attr('checked') )
460 $.getJSON("/scan?callback=?", got_visible_tags);
463 $(document).ready(function() {
464 $('input#pull-reader').click( function() {
467 $('input#pull-reader').attr('checked', true); // force check on load
469 $('div#tags').click( function() {
470 $('input#pull-reader').attr('checked', false);
479 <h1>RFID tags in range</h1>
481 <label for=pull-reader>
482 <input id=pull-reader type=checkbox checked=1>
487 RFID reader not found or driver program not started.