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;
83 return $sip2->{sock} if exists $sip2->{sock} && $sip2->{sock}->connected;
85 if ( my $server = $sip2->{server} ) {
86 my $sock = $sip2->{sock} = IO::Socket::INET->new( $server ) || die "can't connect to $server: $!";
87 warn "SIP2 server ", $sock->peerhost, ":", $sock->peerport, "\n";
90 if ( sip2_message("9300CN$sip2->{user}|CO$sip2->{password}|")->{fixed} !~ m/^941/ ) {
91 die "SIP2 login failed";
102 my $sock = sip2_socket || die "no sip2 socket";
106 $send .= "\r" unless $send =~ m/\r$/;
107 $send .= "\n" unless $send =~ m/\n$/;
111 warn "SIP2 >>>> ",dump($send), "\n";
115 my $expect = substr($send,0,2) | 0x01;
118 warn "SIP2 <<<< ",dump($in), "\n";
125 warn "empty read from SIP server, retry: $retry\n";
127 close( $sip2->{sock} );
134 die "expected $expect" unless substr($in,0,2) != $expect;
137 if ( $in =~ s/^([0-9\s]+)// ) {
140 foreach ( split(/\|/, $in ) ) {
141 my ( $f, $v ) = ( $1, $2 ) if m/([A-Z]{2})(.+)/;
142 $hash->{$f} = decode('utf-8',$v);
145 warn "# sip2 hash response ",dump($hash);
152 use Biblio::RFID::RFID501;
153 use Biblio::RFID::Reader;
154 my $rfid = Biblio::RFID::Reader->new( shift @ARGV );
155 $rfid->debug( $debug );
160 $index_html = <DATA>;
161 $index_html =~ s{http://koha.example.com:8080}{$koha_url}sg;
168 my $server = IO::Socket::INET->new(
170 LocalAddr => $listen,
175 die "can't setup server: $!" unless $server;
177 $server_url = 'http://' . $listen;
178 print "Server $0 ready at $server_url\n";
180 while (my $client = $server->accept()) {
182 eval { # don't die inside here!
184 $client->autoflush(1);
185 my $request = <$client>;
187 warn "WEB << $request\n" if $debug;
190 if ($request =~ m{^GET (/.*) HTTP/1.[01]}) {
193 if ( $method =~ s{\?(.+)}{} ) {
194 foreach my $p ( split(/[&;]/, $1) ) {
195 my ($n,$v) = split(/=/, $p, 2);
198 warn "WEB << param: ",dump( $param ) if $debug;
202 if ( $path eq '/' ) {
203 print $client "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n$index_html";
204 } elsif ( $path =~ m{^/(examples/.+)} ) {
205 $path = $1; # FIXME prefix with dir for installation
207 warn "static $path $size bytes\n";
208 my $content_type = 'text/plain';
209 $content_type = 'application/javascript' if $path =~ /\.js$/;
210 $content_type = 'text/html' if $path =~ /\.html$/;
211 print $client "HTTP/1.0 200 OK\r\nContent-Type: $content_type\r\nContent-Length: $size\r\n\r\n";
214 open(my $fh, '<', $path) || die "can't open $path: $!";
220 } elsif ( $method =~ m{/scan(/only/(.+))?} ) {
222 my @tags = $rfid->tags( reader => sub {
224 return 1 unless $only;
225 if ( ref($reader) =~ m/$only/i ) {
230 my $json = { time => time() };
231 foreach my $tag ( @tags ) {
232 my $hash = $rfid->to_hash( $tag );
234 $hash->{reader} = $rfid->from_reader( $tag );
235 if ( $hash->{tag_type} eq 'SmartX' ) {
236 my $borrower = rfid_borrower $hash;
237 if ( exists $borrower->{error} ) {
238 warn "ERROR ", dump($borrower);
240 $hash->{borrower} = $borrower->{borrower};
241 $hash->{content} = $borrower->{borrower}->{cardnumber}; # compatibile with 3M tags
244 $hash->{security} = uc unpack 'H*', $rfid->afi( $tag );
246 push @{ $json->{tags} }, $hash;
248 warn "#### ", encode_json($json);
249 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
250 $param->{callback}, "(", encode_json($json), ")\r\n";
251 } elsif ( $method =~ m{/program} ) {
253 my $status = 501; # Not implementd
255 foreach my $p ( keys %$param ) {
256 next unless $p =~ m/^(E[0-9A-F]{15})$/;
258 my $content = Biblio::RFID::RFID501->from_hash({ content => $param->{$p} });
259 $content = Biblio::RFID::RFID501->blank if $param->{$p} eq 'blank';
262 warn "PROGRAM $tag $content\n";
263 $rfid->write_blocks( $tag => $content );
264 $rfid->write_afi( $tag => chr( $param->{$p} =~ /^130/ ? $afi->{secure} : $afi->{unsecure} ) );
267 print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
269 } elsif ( $method =~ m{/secure(.js)} ) {
273 my $status = 501; # Not implementd
275 foreach my $p ( keys %$param ) {
276 next unless $p =~ m/^(E[0-9A-F]{15})$/;
278 my $data = $param->{$p};
281 warn "SECURE $tag $data\n";
282 $rfid->write_afi( $tag => chr(hex($data)) );
286 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
287 $param->{callback}, "({ ok: 1 })\r\n";
289 print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
292 } elsif ( $method =~ m{/sip2/(\w+)/(.+)} ) {
293 my ( $method, $args ) = ( $1, $2 );
294 warn "SIP2: $method [$args]";
296 my $ts = strftime('%Y%m%d %H%M%S', localtime());
297 my $loc = $sip2->{loc} || die "missing sip->{loc}";
298 my $password = $sip2->{password} || die "missing sip->{password}";
302 if ( $method eq 'patron_info' ) {
304 $hash = sip2_message("63000${ts} AO$loc|AA$patron|AC$password|");
306 } elsif ( $method eq 'checkout' ) {
307 my ($patron,$barcode,$sid) = split(/\//, $args, 3);
308 $hash = sip2_message("11YN${ts} AO$loc|AA$patron|AB$barcode|AC$password|BON|BIN|");
309 if ( substr( $hash->{fixed}, 2, 1 ) == 1 ) {
310 $rfid->write_afi( $sid => chr( $afi->{unsecure} ) );
313 } elsif ( $method eq 'checkin' ) {
314 my ($patron,$barcode,$sid) = split(/\//, $args, 3);
315 $hash = sip2_message("09N${ts}${ts}AP|AO${loc}|AB$barcode|AC|BIN|");
316 if ( substr( $hash->{fixed}, 2, 1 ) == 1 ) {
317 $rfid->write_afi( $sid => chr( $afi->{secure} ) );
320 print $client "HTTP/1.0 501 $method not implemented\r\n\r\n";
321 warn "ERROR 501 $request\n";
325 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
326 encode_json( $hash );
329 } elsif ( $method =~ m{/beep/(.*)} ) {
330 my $error = uri_unescape($1);
331 system "beep -f 800 -r 2 -l 100";
332 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n{ beep: '$error' }\n";
333 print "BEEP $error\n";
335 print $client "HTTP/1.0 404 Unkown method\r\n\r\n";
336 warn "ERROR 404 $request\n";
339 print $client "HTTP/1.0 500 No method\r\n\r\n";
340 warn "ERROR 500 $request\n";
346 print $client "HTTP/1.0 500 Error\r\n\r\nContent-Type: text/plain\r\n$@";
358 foreach ( split(/\n/, `ip addr` ) ) {
359 if ( /^\d:\s(\w+):\s/ ) {
361 } elsif ( /^\s+inet\s((\d+)\.(\d+)\.(\d+)\.(\d+))\/(\d+)/ ) {
362 $ip->{ $ip->{_last} } = $1;
364 #warn "# SKIP [$_]\n";
370 my $ua = LWP::UserAgent->new;
371 my $url = URI->new( $rfid_url . '/register.pl');
373 local_ip => $ip->{eth0} || $ip->{ (keys %$ip)[0] },
375 warn "GET ",$url->as_string;
376 my $response = $ua->get($url);
377 if ( $response->is_success ) {
378 warn "# ", $response->decoded_content;
379 my $json = decode_json $response->decoded_content;
380 warn "REGISTER: ",dump($json);
383 warn "ERROR ", $response->status_line;
387 rfid_register if $rfid_url;
393 <title>RFID JSONP</title>
394 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
395 <style type="text/css">
408 label[for=pull-reader] {
416 <script type="text/javascript">
419 if(!window.console) {
420 window.console = new function() {
421 this.info = function(str) {};
422 this.debug = function(str) {};
427 function got_visible_tags(data,textStatus) {
428 var html = 'No tags in range';
430 html = '<ul class="tags">';
431 $.each(data.tags, function(i,tag) {
432 console.debug( i, tag );
433 html += '<li><tt class="' + tag.security + '">' + tag.sid;
434 var content = tag.content || tag.borrower.cardnumber;
437 html += ' <a href="http://koha.example.com:8080/cgi-bin/koha/';
438 if ( tag.type == 1 ) { // book
439 html += 'catalogue/search.pl?q=';
441 html += 'members/member.pl?member=';
443 html += content + '" title="lookup in Koha" target="koha-lookup">' + content + '</a>';
446 html += '<form method=get action=program style="display:inline">'
447 + '<input type=hidden name='+tag.sid+' value="blank">'
448 + '<input type=submit value="Blank" onclick="return confirm(\'Blank tag '+tag.sid+'\')">'
454 html += ' <form method=get action=program style="display:inline">'
455 + '<!-- <input type=checkbox name=secure value='+tag.sid+' title="secure tag"> -->'
456 + '<input type=text name='+tag.sid+' size=12>'
457 + '<input type=submit value="Program">'
465 var arrows = Array( 8592, 8598, 8593, 8599, 8594, 8600, 8595, 8601 );
467 html = '<div class=status>'
469 + ' &#' + arrows[ data.time % arrows.length ] + ';'
473 $('#tags').html( html );
474 window.setTimeout(function(){
476 },200); // re-scan every 200ms
479 function scan_tags() {
480 console.info('scan_tags');
481 if ( $('input#pull-reader').attr('checked') )
482 $.getJSON("/scan?callback=?", got_visible_tags);
485 $(document).ready(function() {
486 $('input#pull-reader').click( function() {
489 $('input#pull-reader').attr('checked', true); // force check on load
491 $('div#tags').click( function() {
492 $('input#pull-reader').attr('checked', false);
501 <h1>RFID tags in range</h1>
503 <label for=pull-reader>
504 <input id=pull-reader type=checkbox checked=1>
509 RFID reader not found or driver program not started.