#!/usr/bin/env ruby
# frozen_string_literal: true

require 'rexml/document'
require 'net/http'
require 'pvoutput/client'
require 'yaml'
require 'ipaddress'

yaml_file = 'saj_collector.yaml'

# Load the configuration from the yaml file
sajcollector_config = YAML.load_file(yaml_file)

# Create a pvoutput with the configured system_id and api_key which both
# can be obtained from the pvoutput website
pvoutput = PVOutput::Client.new(sajcollector_config[:system_id], sajcollector_config[:api_key])

unless IPAddress.valid?(sajcollector_config[:saj])
  raise("[#{sajcollector_config[:saj]}] is not a valid IP address, please correct your #{yaml_file} file")
end

# Get the current realtime data from the SAJ device
c = Net::HTTP.get(sajcollector_config[:saj], '/real_time_data.xml')

options = {
  temperature:      0, # Temperature in celcius
  energy_generated: 0, # Energy generation in watt hours
  power_generated:  0, # Power generation in watts
  voltage:          0, # Voltage in volts
  amperage:         0, # Amperage
  power_today:      0,
  power_all_time:   0,
  runtime_today:    0,
  runtime_all_time: 0
}

# Let REXML parse the XML site
doc = REXML::Document.new c

# Get the temperature
doc.elements.each('real_time_data/temp') do |e|
  options[:temperature] = e.text
end

# e-today is in kWh where pvoutput is Wh
doc.elements.each('real_time_data/e-today') do |e|
  options[:energy_generated] = e.text.to_f * 1000
end

# Get the power generated
doc.elements.each('real_time_data/p-ac') do |e|
  options[:power_generated] = e.text
end

# Get the current amperage
doc.elements.each('real_time_data/i-grid') do |e|
  options[:amperage] = e.text
end

# Get the voltage for a 1 phase inverter
doc.elements.each('real_time_data/v-grid') do |e|
  options[:voltage] = e.text
end
# Get the voltage for a 3 phase inverter
doc.elements.each('real_time_data/Vac_l1') do |e|
  options[:voltage] = e.text
end
doc.elements.each('real_time_data/e-today') do |e|
  options[:power_today] = e.text
end
doc.elements.each('real_time_data/e-total') do |e|
  options[:power_all_time] = e.text
end
doc.elements.each('real_time_data/t-today') do |e|
  options[:runtime_today] = e.text
end
doc.elements.each('real_time_data/t-total') do |e|
  options[:runtime_all_time] = e.text
end

puts '-------------------------'
puts
puts "Time: #{Time.now}"
puts
puts 'Realtime:'
puts "  Temp: #{options[:temperature]} C"
puts "  V: #{options[:voltage]} V"
puts "  I: #{options[:amperage]} A"
puts "  P: #{options[:power_generated]} W"
puts
puts 'Total:'
puts "  Power (today): #{options[:power_today]} kWH"
puts "  Power (all time): #{options[:power_all_time]} kWH"
puts "  Run Time: #{options[:runtime_today]} Hours"
puts "  Run Time: #{options[:runtime_all_time]} Hours"

pvoutput.add_status(
  energy_generated: options[:energy_generated],
  power_generated:  options[:power_generated],
  temperature:      options[:temperature],
  voltage:          options[:voltage]
)