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;
97 warn "SIP2 <<<< ",dump($in), "\n";
99 die "expected $expect" unless substr($in,0,2) != $expect;
104 if ( $in =~ s/^([0-9\s]+)// ) {
107 foreach ( split(/\|/, $in ) ) {
108 my ( $f, $v ) = ( $1, $2 ) if m/([A-Z]{2})(.+)/;
109 $hash->{$f} = decode('utf-8',$v);
112 warn "# sip2 hash response ",dump($hash);
117 if ( my $server = $sip2->{server} ) {
118 my $sock = $sip2->{sock} = IO::Socket::INET->new( $server ) || die "can't connect to $server: $!";
119 warn "SIP2 server ", $sock->peerhost, ":", $sock->peerport, "\n";
122 if ( sip2_message("9300CN$sip2->{user}|CO$sip2->{password}|")->{fixed} !~ m/^941/ ) {
123 die "SIP2 login failed";
129 use Biblio::RFID::RFID501;
130 use Biblio::RFID::Reader;
131 my $rfid = Biblio::RFID::Reader->new( shift @ARGV );
132 $rfid->debug( $debug );
137 $index_html = <DATA>;
138 $index_html =~ s{http://koha.example.com:8080}{$koha_url}sg;
145 my $server = IO::Socket::INET->new(
147 LocalAddr => $listen,
152 die "can't setup server: $!" unless $server;
154 $server_url = 'http://' . $listen;
155 print "Server $0 ready at $server_url\n";
157 while (my $client = $server->accept()) {
159 eval { # don't die inside here!
161 $client->autoflush(1);
162 my $request = <$client>;
164 warn "WEB << $request\n" if $debug;
167 if ($request =~ m{^GET (/.*) HTTP/1.[01]}) {
170 if ( $method =~ s{\?(.+)}{} ) {
171 foreach my $p ( split(/[&;]/, $1) ) {
172 my ($n,$v) = split(/=/, $p, 2);
175 warn "WEB << param: ",dump( $param ) if $debug;
179 if ( $path eq '/' ) {
180 print $client "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n$index_html";
181 } elsif ( $path =~ m{^/(examples/.+)} ) {
182 $path = $1; # FIXME prefix with dir for installation
184 warn "static $path $size bytes\n";
185 my $content_type = 'text/plain';
186 $content_type = 'application/javascript' if $path =~ /\.js$/;
187 $content_type = 'text/html' if $path =~ /\.html$/;
188 print $client "HTTP/1.0 200 OK\r\nContent-Type: $content_type\r\nContent-Length: $size\r\n\r\n";
191 open(my $fh, '<', $path) || die "can't open $path: $!";
197 } elsif ( $method =~ m{/scan(/only/(.+))?} ) {
199 my @tags = $rfid->tags( reader => sub {
201 return 1 unless $only;
202 if ( ref($reader) =~ m/$only/i ) {
207 my $json = { time => time() };
208 foreach my $tag ( @tags ) {
209 my $hash = $rfid->to_hash( $tag );
211 $hash->{reader} = $rfid->from_reader( $tag );
212 if ( $hash->{tag_type} eq 'SmartX' ) {
213 my $borrower = rfid_borrower $hash;
214 if ( exists $borrower->{error} ) {
215 warn "ERROR ", dump($borrower);
217 $hash->{borrower} = $borrower->{borrower};
218 $hash->{content} = $borrower->{borrower}->{cardnumber}; # compatibile with 3M tags
221 $hash->{security} = uc unpack 'H*', $rfid->afi( $tag );
223 push @{ $json->{tags} }, $hash;
225 warn "#### ", encode_json($json);
226 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
227 $param->{callback}, "(", encode_json($json), ")\r\n";
228 } elsif ( $method =~ m{/program} ) {
230 my $status = 501; # Not implementd
232 foreach my $p ( keys %$param ) {
233 next unless $p =~ m/^(E[0-9A-F]{15})$/;
235 my $content = Biblio::RFID::RFID501->from_hash({ content => $param->{$p} });
236 $content = Biblio::RFID::RFID501->blank if $param->{$p} eq 'blank';
239 warn "PROGRAM $tag $content\n";
240 $rfid->write_blocks( $tag => $content );
241 $rfid->write_afi( $tag => chr( $param->{$p} =~ /^130/ ? $afi->{secure} : $afi->{unsecure} ) );
244 print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
246 } elsif ( $method =~ m{/secure(.js)} ) {
250 my $status = 501; # Not implementd
252 foreach my $p ( keys %$param ) {
253 next unless $p =~ m/^(E[0-9A-F]{15})$/;
255 my $data = $param->{$p};
258 warn "SECURE $tag $data\n";
259 $rfid->write_afi( $tag => chr(hex($data)) );
263 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
264 $param->{callback}, "({ ok: 1 })\r\n";
266 print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
269 } elsif ( $method =~ m{/sip2/(\w+)/(.+)} ) {
270 my ( $method, $args ) = ( $1, $2 );
271 warn "SIP2: $method [$args]";
273 my $ts = strftime('%Y%m%d %H%M%S', localtime());
274 my $loc = $sip2->{loc} || die "missing sip->{loc}";
275 my $password = $sip2->{password} || die "missing sip->{password}";
279 if ( $method eq 'patron_info' ) {
281 $hash = sip2_message("63000${ts} AO$loc|AA$patron|AC$password|");
283 } elsif ( $method eq 'checkout' ) {
284 my ($patron,$barcode,$sid) = split(/\//, $args, 3);
285 $hash = sip2_message("11YN${ts} AO$loc|AA$patron|AB$barcode|AC$password|BON|BIN|");
286 if ( substr( $hash->{fixed}, 2, 1 ) == 1 ) {
287 $rfid->write_afi( $sid => chr( $afi->{unsecure} ) );
290 } elsif ( $method eq 'checkin' ) {
291 my ($patron,$barcode,$sid) = split(/\//, $args, 3);
292 $hash = sip2_message("09N${ts}${ts}AP|AO${loc}|AB$barcode|AC|BIN|");
293 if ( substr( $hash->{fixed}, 2, 1 ) == 1 ) {
294 $rfid->write_afi( $sid => chr( $afi->{secure} ) );
297 print $client "HTTP/1.0 501 $method not implemented\r\n\r\n";
298 warn "ERROR 501 $request\n";
302 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
303 encode_json( $hash );
306 } elsif ( $method =~ m{/beep/(.*)} ) {
307 my $error = uri_unescape($1);
308 system "beep -f 800 -r 2 -l 100";
309 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n{ beep: '$error' }\n";
310 print "BEEP $error\n";
312 print $client "HTTP/1.0 404 Unkown method\r\n\r\n";
313 warn "ERROR 404 $request\n";
316 print $client "HTTP/1.0 500 No method\r\n\r\n";
317 warn "ERROR 500 $request\n";
323 print $client "HTTP/1.0 500 Error\r\n\r\nContent-Type: text/plain\r\n$@";
335 foreach ( split(/\n/, `ip addr` ) ) {
336 if ( /^\d:\s(\w+):\s/ ) {
338 } elsif ( /^\s+inet\s((\d+)\.(\d+)\.(\d+)\.(\d+))\/(\d+)/ ) {
339 $ip->{ $ip->{_last} } = $1;
341 #warn "# SKIP [$_]\n";
347 my $ua = LWP::UserAgent->new;
348 my $url = URI->new( $rfid_url . '/register.pl');
350 local_ip => $ip->{eth0} || $ip->{ (keys %$ip)[0] },
352 warn "GET ",$url->as_string;
353 my $response = $ua->get($url);
354 if ( $response->is_success ) {
355 warn "# ", $response->decoded_content;
356 my $json = decode_json $response->decoded_content;
357 warn "REGISTER: ",dump($json);
360 warn "ERROR ", $response->status_line;
364 rfid_register if $rfid_url;
370 <title>RFID JSONP</title>
371 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
372 <style type="text/css">
385 label[for=pull-reader] {
393 <script type="text/javascript">
396 if(!window.console) {
397 window.console = new function() {
398 this.info = function(str) {};
399 this.debug = function(str) {};
404 function got_visible_tags(data,textStatus) {
405 var html = 'No tags in range';
407 html = '<ul class="tags">';
408 $.each(data.tags, function(i,tag) {
409 console.debug( i, tag );
410 html += '<li><tt class="' + tag.security + '">' + tag.sid;
411 var content = tag.content || tag.borrower.cardnumber;
414 html += ' <a href="http://koha.example.com:8080/cgi-bin/koha/';
415 if ( tag.type == 1 ) { // book
416 html += 'catalogue/search.pl?q=';
418 html += 'members/member.pl?member=';
420 html += content + '" title="lookup in Koha" target="koha-lookup">' + content + '</a>';
423 html += '<form method=get action=program style="display:inline">'
424 + '<input type=hidden name='+tag.sid+' value="blank">'
425 + '<input type=submit value="Blank" onclick="return confirm(\'Blank tag '+tag.sid+'\')">'
431 html += ' <form method=get action=program style="display:inline">'
432 + '<!-- <input type=checkbox name=secure value='+tag.sid+' title="secure tag"> -->'
433 + '<input type=text name='+tag.sid+' size=12>'
434 + '<input type=submit value="Program">'
442 var arrows = Array( 8592, 8598, 8593, 8599, 8594, 8600, 8595, 8601 );
444 html = '<div class=status>'
446 + ' &#' + arrows[ data.time % arrows.length ] + ';'
450 $('#tags').html( html );
451 window.setTimeout(function(){
453 },200); // re-scan every 200ms
456 function scan_tags() {
457 console.info('scan_tags');
458 if ( $('input#pull-reader').attr('checked') )
459 $.getJSON("/scan?callback=?", got_visible_tags);
462 $(document).ready(function() {
463 $('input#pull-reader').click( function() {
466 $('input#pull-reader').attr('checked', true); // force check on load
468 $('div#tags').click( function() {
469 $('input#pull-reader').attr('checked', false);
478 <h1>RFID tags in range</h1>
480 <label for=pull-reader>
481 <input id=pull-reader type=checkbox checked=1>
486 RFID reader not found or driver program not started.