| 1 | package ZMQ::Declare::Application; | ||
| 2 | { | ||
| 3 | $ZMQ::Declare::Application::VERSION = '0.03'; | ||
| 4 | } | ||
| 5 | use 5.008001; | ||
| 6 | use Moose; | ||
| 7 | |||
| 8 | use Carp (); | ||
| 9 | use ZeroMQ qw(:all); | ||
| 10 | |||
| 11 | use ZMQ::Declare; | ||
| 12 | use ZMQ::Declare::ZDCF; | ||
| 13 | |||
| 14 | has 'name' => ( | ||
| 15 | is => 'ro', | ||
| 16 | isa => 'Str', | ||
| 17 | required => 1, | ||
| 18 | ); | ||
| 19 | |||
| 20 | has 'spec' => ( | ||
| 21 | is => 'ro', | ||
| 22 | isa => 'ZMQ::Declare::ZDCF', | ||
| 23 | required => 1, | ||
| 24 | ); | ||
| 25 | |||
| 26 | has '_app_tree_ref' => ( | ||
| 27 | is => 'rw', | ||
| 28 | isa => 'HashRef', | ||
| 29 | weak_ref => 1, | ||
| 30 | builder => "_fetch_app_tree_ref", | ||
| 31 | lazy => 1, | ||
| 32 | ); | ||
| 33 | sub _fetch_app_tree_ref { | ||
| 34 | my $self = shift; | ||
| 35 | return $self->spec->tree->{apps}{ $self->name }; | ||
| 36 | } | ||
| 37 | |||
| 38 | has '_runtime_context' => ( | ||
| 39 | is => 'rw', | ||
| 40 | isa => 'ZeroMQ::Context', | ||
| 41 | weak_ref => 1, | ||
| 42 | ); | ||
| 43 | |||
| 44 | sub device { | ||
| 45 | my ($self, $name) = @_; | ||
| 46 | |||
| 47 | # For convenience: default to using application name for device if none provided | ||
| 48 | $name = $self->name if not defined $name; | ||
| 49 | |||
| 50 | my $app_spec = $self->_app_tree_ref; | ||
| 51 | my $dev_spec = $app_spec->{devices}{$name}; | ||
| 52 | if (not defined $dev_spec) { | ||
| 53 | Carp::croak("Unknown device name '$name' in application '" . $self->name . "'"); | ||
| 54 | } | ||
| 55 | |||
| 56 | my $typename = $dev_spec->{type}; | ||
| 57 | $typename = '' if not defined $typename; | ||
| 58 | |||
| 59 | return ZMQ::Declare::Device->new( | ||
| 60 | name => $name, | ||
| 61 | application => $self, | ||
| 62 | typename => $typename, | ||
| 63 | ); | ||
| 64 | } | ||
| 65 | |||
| 66 | sub device_names { | ||
| 67 | my $self = shift; | ||
| 68 | my $ref = $self->_app_tree_ref; | ||
| 69 | return keys %{ $ref->{devices} }; | ||
| 70 | } | ||
| 71 | |||
| 72 | # runtime context | ||
| 73 | sub get_context { | ||
| 74 | my ($self) = @_; | ||
| 75 | my $cxt = $self->_runtime_context; | ||
| 76 | return $cxt if defined $cxt; | ||
| 77 | |||
| 78 | my $app_tree = $self->_app_tree_ref; | ||
| 79 | my $context_struct = $app_tree->{context}; | ||
| 80 | my $iothreads = defined $context_struct ? $context_struct->{iothreads} : 1; | ||
| 81 | $cxt = ZeroMQ::Context->new($iothreads); | ||
| 82 | $self->_runtime_context($cxt); | ||
| 83 | |||
| 84 | return $cxt; | ||
| 85 | } | ||
| 86 | |||
| 87 | |||
| 88 | |||
| 89 | no Moose; | ||
| 90 | __PACKAGE__->meta->make_immutable; | ||
| 91 | |||
| 92 | __END__ |