Exobrain/Bus.pm

filter: Statementstmt 75.0% 6 / 8 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 81.8% 9 / 11 CC 1 SCAR 0.9
CC
1
Cov
75%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Exobrain/Agent.pm ↑ Summary Exobrain/Message.pm »
1 package Exobrain::Bus;
2 10 ▶use v5.10.0;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 10 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 0 ▶use ZMQ;
Subroutine BEGIN: called CC=1 SCAR=2.6
6 use ZMQ::Constants qw(ZMQ_SUB ZMQ_PUB ZMQ_SUBSCRIBE ZMQ_RCVMORE);
7  
8 use Method::Signatures;
9  
10 use Exobrain::Router;
11 use Exobrain::Message::Raw;
12  
13 # ABSTRACT: Connection to the Exobrain bus
14 our $VERSION = '1.08'; # VERSION
15  
16  
17 my $context = ZMQ::Context->new; # Context is always shared.
18 my $endpoint = 'tcp://localhost:3568/'; # TODO: From config file?
19 my $router = Exobrain::Router->new;
20  
21 has context => ( is => 'ro', default => sub { $context } );
22 has router => ( is => 'ro', default => sub { $router } );
23 has type => ( is => 'ro', ); # TODO: Type
24 has subscribe => ( is => 'rw', isa => 'Str', default => '' );
25 has _socket => ( is => 'rw' );
26 has exobrain => ( is => 'ro', isa => 'Exobrain' );
27  
28 sub BUILD {
29 my ($self) = @_;
30  
31 my $type = $self->type;
32  
33 if ($type eq 'SUB') {
34 my $socket = $context->socket(ZMQ_SUB);
35 $socket->connect($self->router->subscriber);
36 $socket->setsockopt(ZMQ_SUBSCRIBE, $self->subscribe);
37 $self->_socket($socket);
38 }
39 elsif ($type eq 'PUB') {
40 my $socket = $context->socket(ZMQ_PUB);
41 $socket->connect($self->router->publisher);
42 $self->_socket($socket);
43 }
44 else {
45 die "Internal error: Can't make a $type socket.";
46 }
47  
48 return;
49 }
50  
51 method get() {
52 my $message = Exobrain::Message::Raw->new( [
53 map { $_->data } $self->_socket->recv_multipart
54 ] );
55  
56 # If I have an exobrain object, attach that to the message.
57 if ($self->exobrain) {
58 $message->exobrain($self->exobrain);
59 }
60  
61 return $message;
62 }
63  
64 # TODO: This should be retired. Messages come with their own
65 # send functionality.
66 method send($msg) {
67 $self->_socket->send($msg);
68 }
69  
70 method send_msg(%opts) {
71 my $msg = Exobrain::Message::Raw->new( %opts );
72  
73 return $msg->send_msg( $self->_socket );
74 }
75  
76  
77 1;
78  
79 __END__
« Exobrain/Agent.pm ↑ Summary Exobrain/Message.pm »