Skip to content

Instantly share code, notes, and snippets.

@chendo
Last active January 11, 2022 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chendo/c4b8a28a244bd33d17778f61dfb189be to your computer and use it in GitHub Desktop.
Save chendo/c4b8a28a244bd33d17778f61dfb189be to your computer and use it in GitHub Desktop.
Pulls energy usage from a Rainforest Automation RAVEn USB stick and publishes into a MQTT server to be consumed by Home Assistant
# License: Public domain
# Depends on https://github.com/nonspecialist/pyraven being installed and accessible at `raven`
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'mqtt'
end
require 'json'
require 'time'
ENV['PYTHONUNBUFFERED'] = 'true'
begin
IO.popen('raven') do |io|
puts "Process started, connecting to MQTT server..."
MQTT::Client.connect('mqtt://user:pass@host') do |c|
puts "Connected to MQTT server."
while line = io.gets do
begin
data = JSON.parse(line)
if demand = data['raw_demand']
puts "#{Time.now.iso8601}\t Demand: #{demand}W"
c.publish('energy/meter', demand)
end
rescue StandardError => ex
$stderr.puts("Error publishing: #{ex}")
end
end
end
end
rescue StandardError => ex
$stderr.puts("Error: #{ex}")
$stderr.puts(ex.backtrace.join("\n"))
$stderr.puts("Restarting...")
sleep 2
retry
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment