App-EventStreamr

 view release on metacpan or  search on metacpan

lib/App/EventStreamr/Roles/ConfigAPI.pm  view on Meta::CPAN

package App::EventStreamr::Roles::ConfigAPI;

use v5.010;
use strict;
use warnings;
use Config::JSON;
use JSON;
use Method::Signatures 20140224; # libmethod-signatures-perl
use HTTP::Tiny '0.053'; # libhttp-tiny-perl
use Proc::ProcessTable; # libproc-processtable-perl

use Moo::Role; # libmoo-perl

# ABSTRACT: A config api

our $VERSION = '0.5'; # VERSION: Generated by DZP::OurPkg:Version


requires 'write_config','localconfig','config_path','macaddress','devices';

has 'controller_config' => ( is => 'ro', lazy => 1, builder => 1 );
has 'controller'        => ( is => 'rw', lazy => 1, builder => 1 );
has 'remote_config'     => ( is => 'rw', lazy => 1, builder => 1 );
has 'http'              => ( is => 'rw', lazy => 1, builder => 1, handles => [ qw( post get ) ] );
has 'api_url'           => ( is => 'ro', default => sub { "http://127.0.0.1:3000/internal/settings" } );


method _build_http() {
  return HTTP::Tiny->new(timeout => 15);
}

method _build_controller_config() {
  return $self->config_path."/controller.json";
}

method _build_controller() {
  if ( -e $self->controller_config ) {
    return Config::JSON->new($self->controller_config)->config->{controller};
  } else {
    return 0;
  }
}

method _build_remote_config() {
  # We're designed to operate without a controller.
  return 0 if (! $self->controller);
  
  $self->info("Registering with controller ".$self->controller."/api/station/".$self->macaddress);
  my $response = $self->http->post($self->controller."/api/station/".$self->macaddress);

  # Controller responds with created 201, post our config.
  # This occurs when our identifier isn't registered in the
  # Frontend.
  if ($response->{status} == 201) {
    # Status Post Data
    my $json = to_json($self->_post_data());
    $self->debug($json);
     
    my %post_data = (
          content => $json,
          headers => {
            'station-mgr' => 1,
            'Content-Type' => 'application/json',
          } 
    );
  
    $response = $self->http->post($self->controller."/api/station", \%post_data);
  }



( run in 1.140 second using v1.01-cache-2.11-cpan-39bf76dae61 )