Last Updated: February 25, 2016
·
903
· bunkerbewohner

Simple Ruby script to control LIFX light bulbs

The following little Ruby script can be used to control your LIFX (lifx.co) light bulbs.
I added the script to my ~/bin folder so I can control the lights from my Linux terminal. Fun times!

Requirements:
- Ruby 2.0+
- "lifx" gem (https://github.com/LIFX/lifx-gem)

The Code (https://gist.github.com/Bunkerbewohner/9845832):


#!/usr/bin/env ruby
require 'lifx'

if ARGV.length > 0
    # see if a specific lamp is addressed 
    label = /^on|off|0x[0-9a-f]{6}$/.match(ARGV[0]) ? nil : ARGV[0]

    # discover lamps and wait for label data to be available
    client = LIFX::Client.lan
    client.discover!
    sleep(0.3)

    # select either the specified light or all lights if none was specified
    light = label ? client.lights.with_label(label) : client.lights

    # transition duration in seconds
    duration = [4, ARGV[-1].to_i].max

    # value is either first or second argument, depending whether a label was provided
    value = label ? ARGV[1] : ARGV[0]

    if value == 'on'        
        light.turn_on!
        sleep(0.2)      
        light.set_color(LIFX::Color.rgb(255,255,255), duration: duration)
    elsif value == 'off' and light.on?
        light.set_color(LIFX::Color.rgb(0, 0, 0), duration: duration)
        sleep(duration)
        light.turn_off!
    elsif value[0,2] == '0x'
        r = value[2,2].hex
        g = value[4,2].hex
        b = value[6,2].hex

        if light.off?
            light.turn_on!
            sleep(0.2)
        end

        color = LIFX::Color.rgb(r, g, b)        
        light.set_color(color, duration: duration)      
    end

    # make sure all commands are send before the program exits
    client.flush
else
    print("usage: light [label] on|off|0xRRGGBB [duration=4]

examples:
  light on            -> turns all lights on
  light \"Kitchen\" off -> turns Kitchen light off
  light 0xff0000      -> turns all lights red
  light Bedroom on 30 -> turns up the light in the Bedroom over 30 seconds\n")
end