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