require 'mqtt'
require 'json'

# Subscribe example
MQTT::Client.connect('cerbo.lan') do |client|
  # client.subscribe('#') bare # is the topic for everything
  client.subscribe('N/48e7da85e05d/battery/279/Soc')

  thread = Thread.new do
    loop do
      puts 'sending keep alive'
      client.publish('R/48e7da85e05d/keepalive', 'ping')
      sleep 15
    end
  end

  client.get do |topic,message|
    soc = JSON.parse(message).dig('value').round(2)
    puts "Battery is currently at #{soc} %"
  end
end