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