call read_afi only if it exists
[Biblio-RFID.git] / scripts / RFID-JSONP-server.pl
1 #!/usr/bin/perl
2
3 =head1 RFID-JSONP-server
4
5 This is simpliest possible JSONP server which provides local web interface to RFID readers
6
7 Usage:
8
9   ./scripts/RFID-JSONP-server.pl
10
11 =cut
12
13 use strict;
14 use warnings;
15
16 use Data::Dump qw/dump/;
17
18 use JSON::XS;
19 use IO::Socket::INET;
20
21 my $debug = 1;
22 my $listen = '127.0.0.1:9000';
23 my $reader;
24
25 use Getopt::Long;
26
27 GetOptions(
28         'debug!'    => \$debug,
29         'listen=s', => \$listen,
30         'reader=s', => \$reader,
31 ) || die $!;
32
33 use lib 'lib';
34 use RFID::Biblio::RFID501;
35 use RFID::Biblio::Readers;
36 my $rfid = (RFID::Biblio::Readers->available( $reader ))[0]; # FIXME
37 warn "using $rfid reader\n";
38
39 my $index_html;
40 {
41         local $/ = undef;
42         $index_html = <DATA>;
43 }
44
45 my $server_url;
46
47 sub http_server {
48
49         my $server = IO::Socket::INET->new(
50                 Proto     => 'tcp',
51                 LocalAddr => $listen,
52                 Listen    => SOMAXCONN,
53                 Reuse     => 1
54         );
55                                                                   
56         die "can't setup server: $!" unless $server;
57
58         $server_url = 'http://' . $listen;
59         print "Server $0 ready at $server_url\n";
60
61         while (my $client = $server->accept()) {
62                 $client->autoflush(1);
63                 my $request = <$client>;
64
65                 warn "WEB << $request\n" if $debug;
66                 my $path;
67
68                 if ($request =~ m{^GET (/.*) HTTP/1.[01]}) {
69                         my $method = $1;
70                         my $param;
71                         if ( $method =~ s{\?(.+)}{} ) {
72                                 foreach my $p ( split(/[&;]/, $1) ) {
73                                         my ($n,$v) = split(/=/, $p, 2);
74                                         $param->{$n} = $v;
75                                 }
76                                 warn "WEB << param: ",dump( $param ) if $debug;
77                         }
78                         $path = $method;
79
80                         if ( $path eq '/' ) {
81                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n$index_html";
82                         } elsif ( $path =~ m{^/(examples/.+)} ) {
83                                 $path = $1; # FIXME prefix with dir for installation
84                                 my $size = -s $path;
85                                 warn "static $path $size bytes\n";
86                                 my $content_type = 'text/plain';
87                                 $content_type = 'application/javascript' if $path =~ /\.js/;
88                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: $content_type\r\nContent-Length: $size\r\n\r\n";
89                                 {
90                                         local $/ = undef;
91                                         open(my $fh, '<', $path) || die "can't open $path: $!";
92                                         while(<$fh>) {
93                                                 print $client $_;
94                                         }
95                                         close($fh);
96                                 }
97                         } elsif ( $method =~ m{/scan} ) {
98                                 my $tags = $rfid->scan;
99                                 my $json = { time => time() };
100                                 foreach my $tag ( keys %$tags ) {
101                                         my $hash = RFID::Biblio::RFID501->to_hash( $tags->{$tag} );
102                                         $hash->{sid}  = $tag;
103                                         $hash->{security} = uc unpack 'H*', $rfid->read_afi( $tag )
104                                                 if $rfid->can('read_afi');
105                                         push @{ $json->{tags} }, $hash;
106                                 };
107                                 warn "#### ", encode_json($json);
108                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
109                                         $param->{callback}, "(", encode_json($json), ")\r\n";
110                         } elsif ( $method =~ m{/program} ) {
111
112                                 my $status = 501; # Not implementd
113
114                                 foreach my $p ( keys %$param ) {
115                                         next unless $p =~ m/^(E[0-9A-F]{15})$/;
116                                         my $tag = $1;
117                                         my $content = RFID::Biblio::RFID501->from_hash({ content => $param->{$p} });
118                                         $content    = RFID::Biblio::RFID501->blank if $param->{$p} eq 'blank';
119                                         $status = 302;
120
121                                         warn "PROGRAM $tag $content\n";
122                                         $rfid->write_blocks( $tag => $content );
123                                         $rfid->write_afi(    $tag => chr( $param->{$p} =~ /^130/ ? 0xDA : 0xD7 ) );
124                                 }
125
126                                 print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
127
128                         } elsif ( $method =~ m{/secure(.js)} ) {
129
130                                 my $json = $1;
131
132                                 my $status = 501; # Not implementd
133
134                                 foreach my $p ( keys %$param ) {
135                                         next unless $p =~ m/^(E[0-9A-F]{15})$/;
136                                         my $tag = $1;
137                                         my $data = $param->{$p};
138                                         $status = 302;
139
140                                         warn "SECURE $tag $data\n";
141                                         $rfid->write_afi( $tag => hex($data) );
142                                 }
143
144                                 if ( $json ) {
145                                         print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
146                                                 $param->{callback}, "({ ok: 1 })\r\n";
147                                 } else {
148                                         print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
149                                 }
150
151                         } else {
152                                 print $client "HTTP/1.0 404 Unkown method\r\n\r\n";
153                         }
154                 } else {
155                         print $client "HTTP/1.0 500 No method\r\n\r\n";
156                 }
157                 close $client;
158         }
159
160         die "server died";
161 }
162
163 http_server;
164
165 __DATA__
166 <html>
167 <head>
168 <title>RFID JSONP</title>
169 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
170 <style type="text/css">
171 .status {
172         background: #ff8;
173 }
174
175 .da {
176         background: #fcc;
177 }
178
179 .d7 {
180         background: #cfc;
181 }
182
183 label[for=pull-reader] {
184         position: absolute;
185         top: 1em;
186         right: 1em;
187         background: #eee;
188 }
189
190 </style>
191 <script type="text/javascript">
192
193 // mock console
194 if(!window.console) {
195         window.console = new function() {
196                 this.info = function(str) {};
197                 this.debug = function(str) {};
198         };
199 }
200
201
202 function got_visible_tags(data,textStatus) {
203         var html = 'No tags in range';
204         if ( data.tags ) {
205                 html = '<ul class="tags">';
206                 $.each(data.tags, function(i,tag) {
207                         console.debug( i, tag );
208                         html += '<li><tt class=' + tag.security + '>' + tag.sid;
209                         if ( tag.content ) {
210                                 html += ' <a href="https://koha-dev.rot13.org:8443/cgi-bin/koha/members/member.pl?member=' + tag.content + '" title="lookup in Koha" target="koha-lookup">' + tag.content + '</a>';
211                                 html += '</tt>';
212                                 html += '<form method=get action=program style="display:inline">'
213                                         + '<input type=hidden name='+tag.sid+' value="blank">'
214                                         + '<input type=submit value="Blank" onclick="return confirm(\'Blank tag '+tag.sid+'\')">'
215                                         + '</form>'
216                                 ;
217                         } else {
218                                 html += '</tt>';
219                                 html += ' <form method=get action=program style="display:inline">'
220                                         + '<!-- <input type=checkbox name=secure value='+tag.sid+' title="secure tag"> -->'
221                                         + '<input type=text name='+tag.sid+' size=12>'
222                                         + '<input type=submit value="Program">'
223                                         + '</form>'
224                                 ;
225                         }
226                 });
227                 html += '</ul>';
228         }
229
230         var arrows = Array( 8592, 8598, 8593, 8599, 8594, 8600, 8595, 8601 );
231
232         html = '<div class=status>'
233                 + textStatus
234                 + ' &#' + arrows[ data.time % arrows.length ] + ';'
235                 + '</div>'
236                 + html
237                 ;
238         $('#tags').html( html );
239         window.setTimeout(function(){
240                 scan_tags();
241         },200); // re-scan every 200ms
242 };
243
244 function scan_tags() {
245         console.info('scan_tags');
246         if ( $('input#pull-reader').attr('checked') )
247                 $.getJSON("/scan?callback=?", got_visible_tags);
248 }
249
250 $(document).ready(function() {
251                 $('input#pull-reader').click( function() {
252                         scan_tags();
253                 });
254                 $('input#pull-reader').attr('checked', true); // force check on load
255
256                 $('div#tags').click( function() {
257                         $('input#pull-reader').attr('checked', false);
258                 } );
259
260                 scan_tags();
261 });
262 </script>
263 </head>
264 <body>
265
266 <h1>RFID tags in range</h1>
267
268 <label for=pull-reader>
269 <input id=pull-reader type=checkbox checked=1>
270 active
271 </label>
272
273 <div id="tags">
274 RFID reader not found or driver program not started.
275 </div>
276
277 </body>
278 </html>