Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 107 lines (93 sloc) 2.83 KB
#!/usr/bin/env ruby
# rubocop:disable GlobalVars,MixinUsage,RescueStandardError
require "bundler/setup"
require "json"
require "net/http"
require "ostruct"
require "yaml"
require "pi_piper"
include PiPiper
def play_sound(config)
return unless config.enabled
system config.command
end
def klingelblink(config)
return unless config.enabled
url = URI(config.url)
Net::HTTP.post_form(url, {})
end
def save_snapshot(config)
return unless config.enabled
url = URI(config.url)
response =
if config.request_method == "POST"
Net::HTTP.post_form(url, {}).body
else
Net::HTTP.get(url)
end
JSON.parse(response)["url"]
end
def update_status_screen(config, snapshot_url = nil)
return unless config.enabled
url = URI(config.url)
url.path = "/api/force/#{config.screen}"
url.query = URI.encode_www_form(snapshot_url: snapshot_url) if snapshot_url
Net::HTTP.get(url)
end
def post_to_campfire(config, snapshot_url = nil)
return unless config.enabled
time = Time.now.strftime(config.time_format)
message =
if snapshot_url
"<summary>#{config.messages.snapshot_available % {time: time}}</summary><details><a href='#{snapshot_url}' target='_blank'><img src='#{snapshot_url}'></a></details>"
else
config.messages.no_snapshot_available % {time: time}
end
Net::HTTP.post_form(URI(config.url), content: message)
end
def convert_members_to_ostruct(hash)
hash.each_pair do |key, value|
value = convert_members_to_ostruct(value) if value.is_a?(Hash)
hash[key] = OpenStruct.new(value) if value.is_a?(Hash) || value.nil?
end
hash
end
def run
Thread.new do
begin
yield
rescue => ex
puts "ERROR: #{ex.message} (#{ex.backtrace[0]})"
end
end
end
begin
$config = YAML.load_file(File.realpath("config.yml", File.dirname(__FILE__)))
rescue
puts "Could not load config file! Aborting."
raise
end
$config = OpenStruct.new(convert_members_to_ostruct($config))
if $0 == __FILE__
# If the script terminated ungracefully, the gpio port may still “exported”, which
# causes an error when trying to use it with pi_piper. So we try to unexport it
# first.
begin
File.write "/sys/class/gpio/unexport", $config.gpio_pin
rescue Errno::EINVAL # rubocop:disable HandleExceptions
# EINVAL is raised if the port could not be unexported. This probably means it
# wasn’t exported in the first place, so we can safely ignore this.
end
after pin: $config.gpio_pin, goes: $config.trigger_on_going do
run{ play_sound($config.sound) }
run{ klingelblink($config.klingelblink) }
run{
snapshot_url = save_snapshot($config.snapshot)
run{ update_status_screen($config.status_screen, snapshot_url) }
run{ post_to_campfire($config.campfire, snapshot_url) }
}
sleep 0.5
end
PiPiper.wait
end
# rubocop:enable GlobalVars,MixinUsage,RescueStandardError