diff options
author | Yorhel <git@yorhel.nl> | 2012-02-17 17:27:06 +0100 |
---|---|---|
committer | Yorhel <git@yorhel.nl> | 2012-02-17 17:27:06 +0100 |
commit | 3f4299423b40499a785268bd90c116c2cbb4fa7c (patch) | |
tree | d8ea122a8636c8caa6e73d0a76974cac3daa7ad5 | |
parent | 62307659346c05b2da3dcbd4b122d11d571929b2 (diff) |
perl: Add JSON serialization module + send register messages on connect
-rw-r--r-- | perl/Tanja.pm | 45 |
1 files changed, 43 insertions, 2 deletions
diff --git a/perl/Tanja.pm b/perl/Tanja.pm index 680ef83..0d1915a 100644 --- a/perl/Tanja.pm +++ b/perl/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 |