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/;
22 use POSIX qw(strftime);
26 my $listen = '127.0.0.1:9000';
29 my $koha_url = $ENV{KOHA_URL};
31 # internal URL so we can find local address of machine and vmware NAT
32 my $rfid_url = $ENV{RFID_URL};
34 server => $ENV{SIP2_SERVER}, # '10.60.0.11:6002' must be IP!
35 user => $ENV{SIP2_USER},
36 password => $ENV{SIP2_PASSWORD},
37 loc => $ENV{SIP2_LOC},
48 'listen=s', => \$listen,
49 'reader=s', => \$reader,
52 die "need KOHA_URL, eg. http://ffzg.koha-dev.rot13.org:8080" unless $koha_url;
58 if ( my $json = $rfid_sid_cache->{ $hash->{sid} } ) {
61 my $ua = LWP::UserAgent->new;
62 my $url = URI->new( $koha_url . '/cgi-bin/koha/ffzg/rfid/borrower.pl');
64 RFID_SID => $hash->{sid}
66 , JMBAG => $hash->{JMBAG}
68 warn "GET ",$url->as_string;
69 my $response = $ua->get($url);
70 if ( $response->is_success ) {
71 my $json = decode_json $response->decoded_content;
72 $rfid_sid_cache->{ $hash->{sid} } = $json;
75 warn "ERROR ", $response->status_line;
83 my $sock = $sip2->{sock} || die "no sip2 socket";
87 $send .= "\r" unless $send =~ m/\r$/;
88 warn "SIP2 >>>> ",dump($send), "\n";
92 my $expect = substr($send,0,2) | 0x01;
96 warn "SIP2 <<<< ",dump($in), "\n";
98 die "expected $expect" unless substr($in,0,2) != $expect;
103 if ( $in =~ s/^([0-9\s]+)// ) {
106 foreach ( split(/\|/, $in ) ) {
107 my ( $f, $v ) = ( $1, $2 ) if m/([A-Z]{2})(.+)/;
108 $hash->{$f} = decode('utf-8',$v);
111 warn "# sip2 hash response ",dump($hash);
116 if ( my $server = $sip2->{server} ) {
117 my $sock = $sip2->{sock} = IO::Socket::INET->new( $server ) || die "can't connect to $server: $!";
118 warn "SIP2 server ", $sock->peerhost, ":", $sock->peerport, "\n";
121 if ( sip2_message("9300CN$sip2->{user}|CO$sip2->{password}|")->{fixed} !~ m/^941/ ) {
122 die "SIP2 login failed";
128 use Biblio::RFID::RFID501;
129 use Biblio::RFID::Reader;
130 my $rfid = Biblio::RFID::Reader->new( shift @ARGV );
131 $rfid->debug( $debug );
136 $index_html = <DATA>;
137 $index_html =~ s{http://koha.example.com:8080}{$koha_url}sg;
144 my $server = IO::Socket::INET->new(
146 LocalAddr => $listen,
151 die "can't setup server: $!" unless $server;
153 $server_url = 'http://' . $listen;
154 print "Server $0 ready at $server_url\n";
156 while (my $client = $server->accept()) {
158 eval { # don't die inside here!
160 $client->autoflush(1);
161 my $request = <$client>;
163 warn "WEB << $request\n" if $debug;
166 if ($request =~ m{^GET (/.*) HTTP/1.[01]}) {
169 if ( $method =~ s{\?(.+)}{} ) {
170 foreach my $p ( split(/[&;]/, $1) ) {
171 my ($n,$v) = split(/=/, $p, 2);
174 warn "WEB << param: ",dump( $param ) if $debug;
178 if ( $path eq '/' ) {
179 print $client "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n$index_html";
180 } elsif ( $path =~ m{^/(examples/.+)} ) {
181 $path = $1; # FIXME prefix with dir for installation
183 warn "static $path $size bytes\n";
184 my $content_type = 'text/plain';
185 $content_type = 'application/javascript' if $path =~ /\.js$/;
186 $content_type = 'text/html' if $path =~ /\.html$/;
187 print $client "HTTP/1.0 200 OK\r\nContent-Type: $content_type\r\nContent-Length: $size\r\n\r\n";
190 open(my $fh, '<', $path) || die "can't open $path: $!";
196 } elsif ( $method =~ m{/scan(/only/(.+))?} ) {
198 my @tags = $rfid->tags( reader => sub {
200 return 1 unless $only;
201 if ( ref $reader =~ m/\Q$only\E/i ) {
206 my $json = { time => time() };
207 foreach my $tag ( @tags ) {
208 my $hash = $rfid->to_hash( $tag );
210 $hash->{reader} = $rfid->from_reader( $tag );
211 if ( $hash->{tag_type} eq 'SmartX' ) {
212 my $borrower = rfid_borrower $hash;
213 if ( exists $borrower->{error} ) {
214 warn "ERROR ", dump($borrower);
216 $hash->{borrower} = $borrower->{borrower};
217 $hash->{content} = $borrower->{borrower}->{cardnumber}; # compatibile with 3M tags
220 $hash->{security} = uc unpack 'H*', $rfid->afi( $tag );
222 push @{ $json->{tags} }, $hash;
224 warn "#### ", encode_json($json);
225 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
226 $param->{callback}, "(", encode_json($json), ")\r\n";
227 } elsif ( $method =~ m{/program} ) {
229 my $status = 501; # Not implementd
231 foreach my $p ( keys %$param ) {
232 next unless $p =~ m/^(E[0-9A-F]{15})$/;
234 my $content = Biblio::RFID::RFID501->from_hash({ content => $param->{$p} });
235 $content = Biblio::RFID::RFID501->blank if $param->{$p} eq 'blank';
238 warn "PROGRAM $tag $content\n";
239 $rfid->write_blocks( $tag => $content );
240 $rfid->write_afi( $tag => chr( $param->{$p} =~ /^130/ ? $afi->{secure} : $afi->{unsecure} ) );
243 print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
245 } elsif ( $method =~ m{/secure(.js)} ) {
249 my $status = 501; # Not implementd
251 foreach my $p ( keys %$param ) {
252 next unless $p =~ m/^(E[0-9A-F]{15})$/;
254 my $data = $param->{$p};
257 warn "SECURE $tag $data\n";
258 $rfid->write_afi( $tag => chr(hex($data)) );
262 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
263 $param->{callback}, "({ ok: 1 })\r\n";
265 print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
268 } elsif ( $method =~ m{/sip2/(\w+)/(.+)} ) {
269 my ( $method, $args ) = ( $1, $2 );
270 warn "SIP2: $method [$args]";
272 my $ts = strftime('%Y%m%d %H%M%S', localtime());
273 my $loc = $sip2->{loc} || die "missing sip->{loc}";
274 my $password = $sip2->{password} || die "missing sip->{password}";
278 if ( $method eq 'patron_info' ) {
280 $hash = sip2_message("63000${ts} AO$loc|AA$patron|AC$password|");
282 } elsif ( $method eq 'checkout' ) {
283 my ($patron,$barcode,$sid) = split(/\//, $args, 3);
284 $hash = sip2_message("11YN${ts} AO$loc|AA$patron|AB$barcode|AC$password|BON|BIN|");
285 if ( substr( $hash->{fixed}, 2, 1 ) == 1 ) {
286 $rfid->write_afi( $sid => chr( $afi->{unsecure} ) );
289 } elsif ( $method eq 'checkin' ) {
290 my ($patron,$barcode,$sid) = split(/\//, $args, 3);
291 $hash = sip2_message("09N${ts}${ts}AP|AO${loc}|AB$barcode|AC|BIN|");
292 if ( substr( $hash->{fixed}, 2, 1 ) == 1 ) {
293 $rfid->write_afi( $sid => chr( $afi->{secure} ) );
296 print $client "HTTP/1.0 500 $method not implemented\r\n\r\n";
300 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
301 encode_json( $hash );
305 print $client "HTTP/1.0 404 Unkown method\r\n\r\n";
308 print $client "HTTP/1.0 500 No method\r\n\r\n";
314 print $client "HTTP/1.0 500 Error\r\n\r\nContent-Type: text/plain\r\n$@";
326 foreach ( split(/\n/, `ip addr` ) ) {
327 if ( /^\d:\s(\w+):\s/ ) {
329 } elsif ( /^\s+inet\s((\d+)\.(\d+)\.(\d+)\.(\d+))\/(\d+)/ ) {
330 $ip->{ $ip->{_last} } = $1;
332 #warn "# SKIP [$_]\n";
338 my $ua = LWP::UserAgent->new;
339 my $url = URI->new( $rfid_url . '/register.pl');
341 local_ip => $ip->{eth0} || $ip->{ (keys %$ip)[0] },
343 warn "GET ",$url->as_string;
344 my $response = $ua->get($url);
345 if ( $response->is_success ) {
346 warn "# ", $response->decoded_content;
347 my $json = decode_json $response->decoded_content;
348 warn "REGISTER: ",dump($json);
351 warn "ERROR ", $response->status_line;
355 rfid_register if $rfid_url;
361 <title>RFID JSONP</title>
362 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
363 <style type="text/css">
376 label[for=pull-reader] {
384 <script type="text/javascript">
387 if(!window.console) {
388 window.console = new function() {
389 this.info = function(str) {};
390 this.debug = function(str) {};
395 function got_visible_tags(data,textStatus) {
396 var html = 'No tags in range';
398 html = '<ul class="tags">';
399 $.each(data.tags, function(i,tag) {
400 console.debug( i, tag );
401 html += '<li><tt class="' + tag.security + '">' + tag.sid;
402 var content = tag.content || tag.borrower.cardnumber;
405 html += ' <a href="http://koha.example.com:8080/cgi-bin/koha/';
406 if ( tag.type == 1 ) { // book
407 html += 'catalogue/search.pl?q=';
409 html += 'members/member.pl?member=';
411 html += content + '" title="lookup in Koha" target="koha-lookup">' + content + '</a>';
414 html += '<form method=get action=program style="display:inline">'
415 + '<input type=hidden name='+tag.sid+' value="blank">'
416 + '<input type=submit value="Blank" onclick="return confirm(\'Blank tag '+tag.sid+'\')">'
422 html += ' <form method=get action=program style="display:inline">'
423 + '<!-- <input type=checkbox name=secure value='+tag.sid+' title="secure tag"> -->'
424 + '<input type=text name='+tag.sid+' size=12>'
425 + '<input type=submit value="Program">'
433 var arrows = Array( 8592, 8598, 8593, 8599, 8594, 8600, 8595, 8601 );
435 html = '<div class=status>'
437 + ' &#' + arrows[ data.time % arrows.length ] + ';'
441 $('#tags').html( html );
442 window.setTimeout(function(){
444 },200); // re-scan every 200ms
447 function scan_tags() {
448 console.info('scan_tags');
449 if ( $('input#pull-reader').attr('checked') )
450 $.getJSON("/scan?callback=?", got_visible_tags);
453 $(document).ready(function() {
454 $('input#pull-reader').click( function() {
457 $('input#pull-reader').attr('checked', true); // force check on load
459 $('div#tags').click( function() {
460 $('input#pull-reader').attr('checked', false);
469 <h1>RFID tags in range</h1>
471 <label for=pull-reader>
472 <input id=pull-reader type=checkbox checked=1>
477 RFID reader not found or driver program not started.