summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorYorhel <git@yorhel.nl>2012-02-17 17:27:06 +0100
committerYorhel <git@yorhel.nl>2012-02-17 17:27:06 +0100
commit17fde575fd77113ef93ed65df57391585ed3b6c3 (patch)
tree3ca40661b3a6fbfdc56288037e6e307cccce8eb7
parentd58dccc8615a5ed4017c9d7612fbdb365aa4c0ea (diff)
Add JSON serialization module + send register messages on connect
-rw-r--r--Tanja.pm45
1 files changed, 43 insertions, 2 deletions
diff --git a/Tanja.pm b/Tanja.pm
index 680ef83..0d1915a 100644
--- a/Tanja.pm
+++ b/Tanja.pm
@@ -1,3 +1,6 @@
+# TODO: Split into multiple files? (Or at least don't load AnyEvent::Handle and
+# JSON::XS when they aren't needed.)
+
package Tanja;
use strict;
@@ -33,7 +36,7 @@ use warnings;
sub new {
return bless({
lastid => 1,
- pat => {},
+ pat => {}, # Note: Also used directly by Tanja::Link
}, shift);
}
@@ -228,11 +231,49 @@ sub _handshake {
# Reply with our handshake if we hadn't sent it yet.
!$s->{init} && $s->{hdl}->push_write("ver,1.0 ser,json\012");
- # TODO: handshake is complete at this point, start regular message exchange.
+ # Handshake complete, send out initial register messages
+ $s->{hdl}->push_write('Tanja::Link::JSON' => register => $_+0, $s->{serv}{pat}{$_}[0]) for (keys %{$s->{serv}{pat}});
+
+ # TODO: start regular message exchange.
});
}
+sub close {
+ $_[0]->{hdl}->push_shutdown;
+}
+
+
+# JSON serialization format
+package Tanja::Link::JSON;
+
+use strict;
+use warnings;
+use JSON::XS;
+
+my @num_to_cmd = ('', qw|register unregister tuple response close|);
+my %cmd_to_num = map +($num_to_cmd[$_], $_), keys @num_to_cmd;
+
+
+sub anyevent_read_type {
+ my $cb = $_[1];
+ sub {
+ $_[0]{rbuf} =~ s/^([^\012]*)\012// or return;
+ my $d = eval { decode_json $1; };
+ return $cb->($_[0], undef) || 1 if !$d || ref($d) ne 'ARRAY';
+ my $num = shift @$d;
+ return $cb->($_[0], undef) || 1 if !$num || $num !~ /^\d+$/ || $num > @num_to_cmd;
+ $cb->($_[0], $num_to_cmd[$num], @$d);
+ 1
+ }
+}
+
+sub anyevent_write_type {
+ my(undef, $cmd, @args) = @_;
+ encode_json([$cmd_to_num{$cmd}, @args])."\n";
+}
+
+
1;
# vim:noet:sw=4:ts=4