package onewire;

use strict;
use warnings;

use OWNet;
use Collectd qw/:plugin :types :log/;

my @sensors = (
  {
    'instance'  => 'sensor1',
    'id'        => '10.267621010800',
    'type'      => 'temperature',
    'owname'    => 'temperature',
  },
  { 
    'instance'  => 'sensor2',
    'id'        => '10.A74021010800',
    'type'      => 'temperature',
    'owname'    => 'temperature',
  },
); 

my $plugin_name = 'onewire';

plugin_register(TYPE_READ, $plugin_name, 'ow_read');
plugin_register(TYPE_WRITE, $plugin_name, 'ow_write');

sub ow_read {
  my $vl = {};

  foreach (@sensors) {
    my $value = OWNet::read('localhost:4304', '/uncached/' . $_->{'id'} . '/' . $_->{'owname'});
    $vl->{'values'} = [$value] if defined $value;
    $vl->{'plugin'} = $plugin_name;
    $vl->{'type_instance'} = $_->{'instance'};
    plugin_dispatch_values($_->{'type'}, $vl);
  }
  return 1;
}

sub ow_write {
  my $type = shift;
  my $ds   = shift;
  my $vl   = shift;

  if (scalar (@$ds) != scalar (@{$vl->{'values'}})) {
    plugin_log (LOG_WARNING, "DS number does not match values length");
    return;
  }

  for (my $i = 0; $i < scalar (@$ds); ++$i) {
    # do the magic to output the data
    print "$vl->{'host'}: $vl->{'plugin'}: ";
    if (defined $vl->{'plugin_instance'}) {
      print "$vl->{'plugin_instance'}: ";
    }

    print "$type: ";
    if (defined $vl->{'type_instance'}) {
      print "$vl->{'type_instance'}: ";
    }
    print "$vl->{'values'}->[$i]\n";
  }
  return 1;
}

# workaround if collectd segfaults
END{}

1;
