Skip to content

Instantly share code, notes, and snippets.

@iGEL
Last active August 29, 2015 13:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iGEL/9110526 to your computer and use it in GitHub Desktop.
Save iGEL/9110526 to your computer and use it in GitHub Desktop.
Build light
#!/usr/bin/env ruby
require 'net/http'
require 'json'
require 'uri'
class Light
GREEN_ID = 4762304
RED_ID = 4762303
def initialize(working_time: -> { true })
@working_time = working_time
end
def turn_green_or_off
working_time? ? turn_green : turn_off
end
def turn_green
set_light(green: :on, red: :off)
@light = :green
end
def turn_red
set_light(green: :off, red: :on)
@light = :red
end
def turn_off
set_light(green: :off, red: :off)
@light = :off
end
private
attr_reader :light
def set_light(green: :off, red: :off)
# pilight sends the signal 10 times per default to make sure it's received.
# But sending 10 times the green and then 10 times the red signal causes a
# big delay between the lights, so we changed pilight in
# /etc/pilight/settings.json to send it only once and we send both signals
# 10 times ourself.
10.times do
pilight_switch(GREEN_ID, green == :on ? 't' : 'f')
pilight_switch(RED_ID, red == :on ? 't' : 'f')
end
end
def pilight_switch(id, command)
system("sudo pilight-send -p kaku_switch -i #{id} -u 0 -#{command}")
end
# Let's save energy
def working_time?
@working_time.call
end
end
class Jenkins
def initialize(uri)
@uri = uri
end
def all_green?
job_statuses.all? { |(_, status)| status == 'blue' }
end
def request_was_success?
@success
end
def fetch_status
@job_statuses = filter(normalize(fetch))
end
private
attr_reader :uri, :job_statuses
def fetch
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |connection|
request = Net::HTTP::Get.new(uri.path)
request.basic_auth(uri.user, uri.password) if uri.user
response = connection.request(request)
@success = response.is_a?(Net::HTTPSuccess)
JSON.load(response.body)['jobs']
end
rescue StandardError => e
$stderr.puts "#{e.class}: #{e.message}"
@success = false
[]
end
def normalize(data)
data.each_with_object({}) do |data, out|
out[data['name']] = data['color'].split('_').first
end
end
def filter(jobs)
jobs.select { |name, status| name.start_with?('wimdu') && status != 'disabled' }
end
end
light = Light.new(working_time: -> {
now = Time.now
!now.sunday? && !now.saturday? && now.hour >= 8 && now.hour < 20
})
begin
jenkins = Jenkins.new(URI.parse(ENV['BUILD_URI']))
rescue URI::InvalidURIError
$stderr.puts "Invalid or unset BUILD_URI envvar"
exit(false)
end
at_exit do
light.turn_off
exit
end
loop do
jenkins.fetch_status
case
when !jenkins.request_was_success?
light.turn_off
when jenkins.all_green?
light.turn_green_or_off
else
light.turn_red
end
sleep 5 if jenkins.request_was_success?
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment