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