huey 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ .bundle
3
+
4
+ .autotest
5
+ .DS_Store
6
+ .loadpath
7
+ .project
8
+ .yardoc/
9
+ .bundle/
10
+ .idea/
11
+
12
+ coverage/
13
+ doc/
14
+ pkg/
15
+ tmp/
16
+
17
+ */.DS_Store
data/Gemfile ADDED
@@ -0,0 +1,5 @@
1
+ source "http://rubygems.org"
2
+ gemspec
3
+
4
+ gem 'rake'
5
+ gem 'color-tools'
data/Gemfile.lock ADDED
@@ -0,0 +1,39 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ huey (0.1.0)
5
+ eventmachine (>= 1.0.0)
6
+ httparty (>= 0.9.0)
7
+
8
+ GEM
9
+ remote: http://rubygems.org/
10
+ specs:
11
+ addressable (2.3.2)
12
+ color-tools (1.3.0)
13
+ crack (0.3.1)
14
+ eventmachine (1.0.0)
15
+ httparty (0.9.0)
16
+ multi_json (~> 1.0)
17
+ multi_xml
18
+ metaclass (0.0.1)
19
+ mocha (0.13.1)
20
+ metaclass (~> 0.0.1)
21
+ multi_json (1.5.0)
22
+ multi_xml (0.5.1)
23
+ rake (0.9.5)
24
+ webmock (1.9.0)
25
+ addressable (>= 2.2.7)
26
+ crack (>= 0.1.7)
27
+ yard (0.8.3)
28
+
29
+ PLATFORMS
30
+ ruby
31
+
32
+ DEPENDENCIES
33
+ bundler
34
+ color-tools
35
+ huey!
36
+ mocha (>= 0.13.1)
37
+ rake
38
+ webmock (>= 1.9.0)
39
+ yard (>= 0.8.3)
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2012 Josh Symonds
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.markdown ADDED
@@ -0,0 +1,99 @@
1
+ # Huey
2
+
3
+ Easy control of your Phillips Hue lights, in an attractive Gem format!
4
+
5
+ ## Installation
6
+
7
+ Installing Huey is pretty simple. First include the Gem in your Gemfile:
8
+
9
+ ```ruby
10
+ gem 'huey', git: 'git://github.com/Veraticus/huey.git'
11
+ ```
12
+
13
+ (It's not in RubyGems yet because I'm not totally sure it's actually stable enough for release.)
14
+
15
+ You shouldn't need to initialize anything to make Huey work correctly, but if you want to specify some configuration options go nuts:
16
+
17
+ ```ruby
18
+ Huey.configure do |config|
19
+ # For discovering the Hue hub, usually you won't have to change this
20
+ config.ssdp_ip = '239.255.255.250'
21
+
22
+ # Also for discovering the Hue hub
23
+ config.ssdp_port = 1900
24
+
25
+ # If you get constant errors about not being able to find the Hue hub and you're sure it's connected, increase this
26
+ config.ssdp_ttl = 1
27
+
28
+ # Change this if you don't like the included uuid
29
+ config.uuid = '0123456789abdcef0123456789abcdef'
30
+ end
31
+ ```
32
+
33
+ ## Usage
34
+
35
+ The first time you issue any Huey command, you're likely to see something like this:
36
+
37
+ ```ruby
38
+ Huey::Errors::PressLinkButton: 'Press the link button and try your request again'
39
+ ```
40
+
41
+ Just like the message says, go press the link button on your Hue hub, and then reissue the request. It should work the second time. Then you can get to the exciting stuff:
42
+
43
+ ```ruby
44
+ Huey::Bulb.all # Returns an array of your bulbs
45
+
46
+ bulb = Huey::Bulb.find(1) # Finds the bulb with the ID of 1
47
+ bulb = Huey::Bulb.find('Living Room') # Finds the bulb with the name 'Living Room'
48
+
49
+ bulb.alert! # Flashes the bulb in question once and immediately, useful for checking connectivity
50
+
51
+ bulb.bri = 100 # Let's dim the bulb a little bit
52
+ bulb.ct = 500 # And make it a little more orange
53
+
54
+ bulb.save # Apply all the changes you've made
55
+
56
+ bulb.update(bri: 100, ct: 500) # Set and save in one step
57
+
58
+ bulb.rgb = '#8FF1F5' # Everyone loves aqua
59
+
60
+ bulb.commit # Alias for save
61
+ ```
62
+
63
+ Changes to the bulb only take effect when you call `save` on it. If you prefer, `save` is aliased as `commit`.
64
+
65
+ For your reference, the attributes on bulb you can change are:
66
+ - **name**: Any string. The bulb's name.
67
+ - **on**: `true` or `false`. Set and commit to activate or deactive the bulb.
68
+ - **bri**: The bulb's brightness, between `0` and `254`. 0 is not off!
69
+ - **hue**: For hue/saturation mode. Between `0` and `65535`. Multiply the hue degree by 182 to get this.
70
+ - **sat**: For hue/saturation mode. Between `0` and `254`.
71
+ - **xy**: For CIE 1931 mode. An array of two floats, like: [0.44, 0.4051]
72
+ - **ct**: For color temperature mode. Expressed in [mireds](http://en.wikipedia.org/wiki/Mired), an integer between `154` and `500`.
73
+ - **transitiontime**: An integer. Tenths of a second, so `10` is 1 second, and `100` is 10 seconds. Use `0` for instantaneous transitions.
74
+
75
+ I used [http://rsmck.co.uk/hue](http://rsmck.co.uk/hue) as the source for all this stuff.
76
+
77
+ I've added in some convenience attributes as well:
78
+
79
+ - **rgb**: An HTML hex value. Will automatically convert to hue/saturation.
80
+
81
+ ## Attribution
82
+
83
+ The structure of the configuration files and the modules are taken from [Mongoid](https://github.com/mongoid/mongoid), which had some really great ideas.
84
+
85
+ The SSDP discovery driver is lifted whole cloth from turboladen's [UPNP](https://github.com/turboladen/upnp). I would have used it as a Gem dependency, but unfortunately, it's not released as a Gem, so I just took it. The code is his, though, not mine.
86
+
87
+ ## Quasi-Legal Mumbo-Jumbo
88
+
89
+ I am not affiliated with Phillips or the Phillips Hue in any way. I just think it's neat. While this Gem works for me, if it causes your lights to catastrophically fail it's not my fault. (Though I think the chances of this happening are pretty unlikely, you never know.)
90
+
91
+ ## Copyright
92
+
93
+ Copyright (c) 2012 Josh Symonds.
94
+
95
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
96
+
97
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
98
+
99
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,13 @@
1
+ require 'rake/testtask'
2
+ require "bundler/gem_tasks"
3
+ require 'yard'
4
+
5
+ YARD::Rake::YardocTask.new
6
+
7
+ Rake::TestTask.new do |t|
8
+ t.libs << 'test'
9
+ t.pattern = 'test/**/*_test.rb'
10
+ end
11
+
12
+ desc "Run tests"
13
+ task :default => :test
data/huey.gemspec ADDED
@@ -0,0 +1,28 @@
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path("../lib", __FILE__)
3
+ require "huey/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "huey"
7
+ s.version = Huey::VERSION
8
+ s.author = "Veraticus"
9
+ s.email = "josh@joshsymonds.com"
10
+ s.homepage = "https://github.com/Veraticus/huey"
11
+ s.summary = "Quick and simple discovery and control of Phillips Hue lightbulbs"
12
+ s.description = %q{Everything you could want for making Phillips Hue lightbulbs obey your every command.}
13
+
14
+ s.files = `git ls-files`.split("\n")
15
+ s.test_files = `git ls-files -- {spec,features}/*`.split("\n")
16
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
17
+ s.extra_rdoc_files = %w(LICENSE README.markdown)
18
+ s.require_paths = ["lib"]
19
+ s.required_ruby_version = Gem::Requirement.new(">=1.9.1")
20
+
21
+ s.add_dependency('eventmachine', '>=1.0.0')
22
+ s.add_dependency('httparty', '>=0.9.0')
23
+
24
+ s.add_development_dependency('bundler', '>=0')
25
+ s.add_development_dependency('yard', '>=0.8.3')
26
+ s.add_development_dependency('mocha', '>=0.13.1')
27
+ s.add_development_dependency('webmock', '>=1.9.0')
28
+ end
data/lib/huey/bulb.rb ADDED
@@ -0,0 +1,106 @@
1
+ # encoding: utf-8
2
+
3
+ module Huey
4
+
5
+ # An actual object for a bulb.
6
+ class Bulb
7
+ Attributes = [:on, :bri, :hue, :sat, :xy, :ct, :name, :transitiontime, :colormode]
8
+ attr_reader :id
9
+
10
+ def self.all
11
+ @all ||= Huey::Request.get['lights'].collect do |id, hash|
12
+ Bulb.new(id, hash)
13
+ end
14
+ end
15
+
16
+ def self.find(id)
17
+ self.all.find {|b| b.id == id || b.name == id}
18
+ end
19
+
20
+ def initialize(id, hash)
21
+ @id = id.to_i
22
+ @changes = {}
23
+ @name = hash['name']
24
+
25
+ (Huey::Bulb::Attributes - [:name]).each do |attribute|
26
+ instance_variable_set("@#{attribute}".to_sym, hash['state'][attribute.to_s])
27
+ end
28
+ end
29
+
30
+ Huey::Bulb::Attributes.each do |attribute|
31
+ define_method(attribute) do
32
+ instance_variable_get("@#{attribute}".to_sym)
33
+ end
34
+
35
+ define_method("#{attribute}=".to_sym) do |new_value|
36
+ return true if self.send(attribute) == new_value
37
+
38
+ @changes[attribute] = new_value
39
+ instance_variable_set("@#{attribute}".to_sym, new_value)
40
+ end unless attribute == :colormode
41
+ end
42
+
43
+ def save
44
+ Huey::Request.put("lights/#{self.id}/state", body: MultiJson.dump(@changes))
45
+ @changes = {}
46
+ true
47
+ end
48
+ alias :commit :save
49
+
50
+ def update(hash)
51
+ hash.each { |k, v| self.send("#{k}=".to_sym, v) }
52
+
53
+ save
54
+ end
55
+
56
+ def rgb
57
+ Color::HSL.new(self.hue.to_f / 182.04, self.sat.to_f / 255.0 * 100.0, self.bri.to_f / 255.0 * 100.0).to_rgb.html
58
+ end
59
+
60
+ def rgb=(hex)
61
+ color = Color::RGB.from_html(hex)
62
+
63
+ # Manual calcuation is necessary here because of an error in the Color library
64
+ r = color.r
65
+ g = color.g
66
+ b = color.b
67
+ max = [r, g, b].max
68
+ min = [r, g, b].min
69
+ delta = max - min
70
+ v = max * 100
71
+
72
+ if (max != 0.0)
73
+ s = delta / max *100
74
+ else
75
+ s = 0.0
76
+ end
77
+
78
+ if (s == 0.0)
79
+ h = 0.0
80
+ else
81
+ if (r == max)
82
+ h = (g - b) / delta
83
+ elsif (g == max)
84
+ h = 2 + (b - r) / delta
85
+ elsif (b == max)
86
+ h = 4 + (r - g) / delta
87
+ end
88
+
89
+ h *= 60.0
90
+
91
+ if (h < 0)
92
+ h += 360.0
93
+ end
94
+ end
95
+
96
+ self.hue = (h * 182.04).round
97
+ self.sat = (s / 100.0 * 255.0).round
98
+ self.bri = (v / 100.0 * 255.0).round
99
+ end
100
+
101
+ def alert!
102
+ Huey::Request.put("lights/#{self.id}/state", body: MultiJson.dump({alert: 'select'}))
103
+ end
104
+
105
+ end
106
+ end
@@ -0,0 +1,79 @@
1
+ # encoding: utf-8
2
+ # Shamelessly stolen from Mongoid! And Dynamoid...
3
+ module Huey #:nodoc
4
+ module Config
5
+
6
+ # Encapsulates logic for setting options.
7
+ module Options
8
+
9
+ # Get the defaults or initialize a new empty hash.
10
+ #
11
+ # @example Get the defaults.
12
+ # options.defaults
13
+ #
14
+ # @return [ Hash ] The default options.
15
+ #
16
+ # @since 0.0.1
17
+ def defaults
18
+ @defaults ||= {}
19
+ end
20
+
21
+ # Define a configuration option with a default.
22
+ #
23
+ # @example Define the option.
24
+ # Options.option(:persist_in_safe_mode, :default => false)
25
+ #
26
+ # @param [ Symbol ] name The name of the configuration option.
27
+ # @param [ Hash ] options Extras for the option.
28
+ #
29
+ # @option options [ Object ] :default The default value.
30
+ #
31
+ # @since 0.0.1
32
+ def option(name, options = {})
33
+ defaults[name] = settings[name] = options[:default]
34
+
35
+ class_eval <<-RUBY
36
+ def #{name}
37
+ settings[#{name.inspect}]
38
+ end
39
+
40
+ def #{name}=(value)
41
+ settings[#{name.inspect}] = value
42
+ end
43
+
44
+ def #{name}?
45
+ #{name}
46
+ end
47
+
48
+ def reset_#{name}
49
+ settings[#{name.inspect}] = defaults[#{name.inspect}]
50
+ end
51
+ RUBY
52
+ end
53
+
54
+ # Reset the configuration options to the defaults.
55
+ #
56
+ # @example Reset the configuration options.
57
+ # config.reset
58
+ #
59
+ # @return [ Hash ] The defaults.
60
+ #
61
+ # @since 0.0.1
62
+ def reset
63
+ settings.replace(defaults)
64
+ end
65
+
66
+ # Get the settings or initialize a new empty hash.
67
+ #
68
+ # @example Get the settings.
69
+ # options.settings
70
+ #
71
+ # @return [ Hash ] The setting options.
72
+ #
73
+ # @since 0.0.1
74
+ def settings
75
+ @settings ||= {}
76
+ end
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,44 @@
1
+ # encoding: utf-8
2
+ require "huey/config/options"
3
+
4
+ module Huey #:nodoc
5
+
6
+ # Contains all the basic configuration information required for huey.
7
+ module Config
8
+ extend self
9
+ extend Options
10
+
11
+ # All the default options.
12
+ option :ssdp_ip, default: '239.255.255.250'
13
+ option :ssdp_port, default: 1900
14
+ option :ssdp_ttl, default: 1
15
+ option :uuid, default: '0123456789abdcef0123456789abcdef'
16
+
17
+ # The default logger for Huey: either the Rails logger or just stdout.
18
+ #
19
+ # @since 0.0.1
20
+ def default_logger
21
+ defined?(Rails) && Rails.respond_to?(:logger) ? Rails.logger : ::Logger.new($stdout)
22
+ end
23
+
24
+ # Returns the assigned logger instance.
25
+ #
26
+ # @since 0.0.1
27
+ def logger
28
+ @logger ||= default_logger
29
+ end
30
+
31
+ # If you want to, set the logger manually to any output you'd like. Or pass false or nil to disable logging entirely.
32
+ #
33
+ # @since 0.0.1
34
+ def logger=(logger)
35
+ case logger
36
+ when false, nil then @logger = nil
37
+ when true then @logger = default_logger
38
+ else
39
+ @logger = logger if logger.respond_to?(:info)
40
+ end
41
+ end
42
+
43
+ end
44
+ end
@@ -0,0 +1,20 @@
1
+ # encoding: utf-8
2
+
3
+ module Huey
4
+
5
+ # All the error specific to Huey.
6
+ module Errors
7
+
8
+ # Generic error class.
9
+ class Error < StandardError; end
10
+
11
+ # CouldNotFindHub is raised when no IP address can be found for Hue.
12
+ class CouldNotFindHue < Error; end
13
+
14
+ # PressLinkButton is raised if the link button hasn't been pressed yet.
15
+ class PressLinkButton < Error; end
16
+
17
+ # HueResponseError is raised if we receive an odd response from the Hue.
18
+ class HueResponseError < Error; end
19
+ end
20
+ end
@@ -0,0 +1,43 @@
1
+ # encoding: utf-8
2
+
3
+ module Huey
4
+
5
+ # Wraps requests to the actual Hue itself
6
+ class Request
7
+ class << self
8
+
9
+ [:get, :post, :put, :delete].each do |method|
10
+ define_method(method) do |url = '', options = {}|
11
+ response = HTTParty.send(method, "http://#{Huey::SSDP.hue_ip}/api/#{Huey::Config.uuid}/#{url}", options).parsed_response
12
+
13
+ if self.error?(response, 1)
14
+ self.register
15
+ return self.send(method, url, options)
16
+ end
17
+
18
+ response
19
+ end
20
+ end
21
+
22
+ def register
23
+ response = HTTParty.post("http://#{Huey::SSDP.hue_ip}/api", body: MultiJson.dump({username: Huey::Config.uuid, devicetype: 'Huey'})).parsed_response
24
+
25
+ raise Huey::Errors::PressLinkButton, 'Press the link button and try your request again' if self.error?(response, 101)
26
+
27
+ response
28
+ end
29
+
30
+ def error?(response, type)
31
+ if response.is_a?(Array) && response.first && response.first['error']
32
+ if response.first['error']['type'] == type
33
+ true
34
+ else
35
+ raise Huey::Errors::HueResponseError, response
36
+ end
37
+ end
38
+ end
39
+
40
+ end
41
+
42
+ end
43
+ end
@@ -0,0 +1,61 @@
1
+ # encoding: utf-8
2
+
3
+ # This code is shamelessly cribbed from the yet-unreleased upnp gem:
4
+ # https://github.com/turboladen/upnp
5
+ # I would take it more reasonably (as its own gem) but it isn't released yet, so I just stole the parts I needed.
6
+ #
7
+ # (That's also my excuse for why this has no testing.)
8
+
9
+ module Huey
10
+ module SSDP
11
+ class Searcher < EventMachine::Connection
12
+ attr_reader :discovery_responses
13
+
14
+ def initialize
15
+ @discovery_responses = EM::Channel.new
16
+ end
17
+
18
+ def post_init
19
+ if send_datagram(m_search, Huey::Config.ssdp_ip, Huey::Config.ssdp_port) > 0
20
+ Huey.logger.debug "Sent datagram search:\n#{m_search}"
21
+ end
22
+ end
23
+
24
+ def parse(data)
25
+ new_data = {}
26
+
27
+ data.each_line do |line|
28
+ if match = line.match(/(\S+):(.*)/)
29
+ key = match[1].gsub('-', '_').downcase.to_sym
30
+ value = match[2]
31
+ new_data[key] = value.strip
32
+ end
33
+ end
34
+
35
+ new_data
36
+ end
37
+
38
+ def receive_data(response)
39
+ parsed_response = parse(response)
40
+
41
+ Huey.logger.debug "Received response: #{parsed_response}"
42
+ return if parsed_response.has_key? :nts
43
+ return if parsed_response[:man] && parsed_response[:man] =~ /ssdp:discover/
44
+
45
+ @discovery_responses << parsed_response
46
+ end
47
+
48
+ def m_search
49
+ <<-MSEARCH
50
+ M-SEARCH * HTTP/1.1\r
51
+ HOST: #{Huey::Config.ssdp_ip}:#{Huey::Config.ssdp_port}\r
52
+ MAN: "ssdp:discover"\r
53
+ MX: #{Huey::Config.ssdp_ttl}\r
54
+ ST: urn:schemas-upnp-org:device:Basic:1\r
55
+ \r
56
+ MSEARCH
57
+ end
58
+
59
+ end
60
+ end
61
+ end
data/lib/huey/ssdp.rb ADDED
@@ -0,0 +1,39 @@
1
+ # encoding: utf-8
2
+
3
+ # This code is shamelessly cribbed from the yet-unreleased upnp gem:
4
+ # https://github.com/turboladen/upnp
5
+ # I would take it more reasonably (as its own gem) but it isn't released yet, so I just stole the parts I needed.
6
+
7
+ require 'huey/ssdp/searcher'
8
+
9
+ module Huey
10
+ module SSDP
11
+ def self.hue_ip
12
+ return @hue_ip if @hue_ip
13
+
14
+ multicast_searcher = proc do
15
+ EM.open_datagram_socket('0.0.0.0', 0, Huey::SSDP::Searcher)
16
+ end
17
+
18
+ response = nil
19
+
20
+ EM.run do
21
+ ms = multicast_searcher.call
22
+
23
+ ms.discovery_responses.subscribe do |notification|
24
+ response = notification
25
+ EM.stop
26
+ end
27
+
28
+ EM.add_timer(Huey::Config.ssdp_ttl) { EM.stop }
29
+ trap('INT') { EM.stop }
30
+ trap('TERM') { EM.stop }
31
+ trap('HUP') { EM.stop }
32
+ end
33
+
34
+ raise Huey::Errors::CouldNotFindHue, 'No IP address found for the Hue hub' unless response
35
+
36
+ @hue_ip = response[:location].match(/http:\/\/(.*?):(.*?)\//)[1]
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,3 @@
1
+ module Huey
2
+ VERSION = "0.1.0"
3
+ end
data/lib/huey.rb ADDED
@@ -0,0 +1,27 @@
1
+ require 'ipaddr'
2
+ require 'socket'
3
+ require 'eventmachine'
4
+ require 'logger'
5
+ require 'httparty'
6
+ require 'color'
7
+
8
+ require 'huey/version'
9
+
10
+ require 'huey/config'
11
+ require 'huey/errors'
12
+ require 'huey/ssdp'
13
+ require 'huey/request'
14
+ require 'huey/bulb'
15
+
16
+ module Huey
17
+ extend self
18
+
19
+ def configure
20
+ block_given? ? yield(Huey::Config) : Huey::Config
21
+ end
22
+ alias :config :configure
23
+
24
+ def logger
25
+ Huey::Config.logger
26
+ end
27
+ end
@@ -0,0 +1,25 @@
1
+ require 'test/unit'
2
+ require 'webmock/test_unit'
3
+ require "mocha/setup"
4
+ require 'huey'
5
+
6
+
7
+ class Test::Unit::TestCase
8
+ def setup
9
+ super
10
+ # Prevent real connections to the hub
11
+ # EM.stubs(:open_datagram_socket).returns(fake_searcher)
12
+ end
13
+
14
+ def set_hue_ip(ip)
15
+ Huey::SSDP.instance_variable_set(:@hue_ip, ip)
16
+ end
17
+
18
+ def fake_searcher
19
+ searcher = mock()
20
+ responses = mock()
21
+ responses.stubs(:subscribe).yields({:cache_control=>"max-age=100", :ext=>"", :location=>"http://192.168.0.1:80/description.xml", :server=>"FreeRTOS/6.0.5, UPnP/1.0, IpBridge/0.1", :st=>"upnp:rootdevice", :usn=>"uuid:2f402f80-da50-11e1-9b23-0017880931a2::upnp:rootdevice"}).returns(true)
22
+ searcher.stubs(:discovery_responses).returns(responses)
23
+ searcher
24
+ end
25
+ end
@@ -0,0 +1,87 @@
1
+ require 'test_helper'
2
+
3
+ class BulbTest < Test::Unit::TestCase
4
+
5
+ def setup
6
+ super
7
+ @bulb = init_bulb
8
+ end
9
+
10
+ def test_initializes_bulb_from_hash
11
+ assert_equal @bulb.name, "Living Room"
12
+ assert_equal @bulb.id, 1
13
+ assert_equal @bulb.hue, 54418
14
+ end
15
+
16
+ def test_initializes_all_bulbs
17
+ Huey::Request.expects(:get).once.returns('lights' => light_response.merge(light_response('2', 'Bedroom')))
18
+
19
+ assert Huey::Bulb.all
20
+ assert_equal Huey::Bulb.all.first.id, 1
21
+ assert_equal Huey::Bulb.all.last.id, 2
22
+ end
23
+
24
+ def test_send_alert_to_bulb
25
+ Huey::Request.expects(:put).with("lights/1/state", body: MultiJson.dump({alert: 'select'})).once.returns(true)
26
+
27
+ @bulb.alert!
28
+ end
29
+
30
+ def test_bulb_get_attributes
31
+ Huey::Bulb::Attributes.each do |attr|
32
+ assert @bulb.respond_to?(attr), "#{attr} is not set"
33
+ assert @bulb.instance_variable_defined?("@#{attr}".to_sym), "#{attr} has no instance variable"
34
+ end
35
+ end
36
+
37
+ def test_bulb_set_attributes
38
+ assert @bulb.instance_variable_defined?(:@changes), "@changes has no instance variable"
39
+
40
+ Huey::Bulb::Attributes.each do |attr|
41
+ assert @bulb.respond_to?("#{attr}="), "#{attr} is not set" unless attr == :colormode
42
+ end
43
+ end
44
+
45
+ def test_send_changes_on_save
46
+ Huey::Request.expects(:put).with("lights/1/state", body: MultiJson.dump({on: true, bri: 100})).once.returns(true)
47
+
48
+ @bulb.on = true
49
+ @bulb.bri = 100
50
+ assert @bulb.save
51
+ end
52
+
53
+ def test_only_different_changes_on_save
54
+ Huey::Request.expects(:put).with("lights/1/state", body: MultiJson.dump({bri: 100})).once.returns(true)
55
+
56
+ @bulb.on = false
57
+ @bulb.bri = 100
58
+ assert @bulb.save
59
+ end
60
+
61
+ def test_update_attributes_simultaneously
62
+ Huey::Request.expects(:put).with("lights/1/state", body: MultiJson.dump({on: true, bri: 100})).once.returns(true)
63
+
64
+ assert @bulb.update(on: true, bri: 100)
65
+ end
66
+
67
+ def test_get_html_color
68
+ assert_equal '#cb30ce', @bulb.rgb
69
+ end
70
+
71
+ def test_set_html_color
72
+ @bulb.rgb = '#8FF1F5'
73
+
74
+ assert_equal 33196, @bulb.hue
75
+ assert_equal 106, @bulb.sat
76
+ assert_equal 245, @bulb.bri
77
+ end
78
+
79
+ def light_response(id = "1", name = "Living Room")
80
+ {id => {"state"=>{"on"=>false, "bri"=>127, "hue"=>54418, "sat"=>158, "xy"=>[0.509, 0.4149], "ct"=>459, "alert"=>"none", "effect"=>"none", "colormode"=>"hue", "reachable"=>true}, "type"=>"Extended color light", "name"=>name, "modelid"=>"LCT001", "swversion"=>"65003148", "pointsymbol"=>{"1"=>"none", "2"=>"none", "3"=>"none", "4"=>"none", "5"=>"none", "6"=>"none", "7"=>"none", "8"=>"none"}}}
81
+ end
82
+
83
+ def init_bulb
84
+ Huey::Bulb.new(light_response.keys.first, light_response.values.last)
85
+ end
86
+
87
+ end
@@ -0,0 +1,41 @@
1
+ require 'test_helper'
2
+
3
+ class RequestTest < Test::Unit::TestCase
4
+
5
+ def setup
6
+ super
7
+ set_hue_ip('0.0.0.0')
8
+ end
9
+
10
+ [:get, :post, :put, :delete].each do |m|
11
+ define_method("test_basic_#{m}") do
12
+ stub_request(:any, "http://0.0.0.0/api/0123456789abdcef0123456789abcdef/")
13
+
14
+ Huey::Request.send(m)
15
+
16
+ assert_requested m, "0.0.0.0/api/0123456789abdcef0123456789abcdef/"
17
+ end
18
+ end
19
+
20
+ def test_attempt_authentication_upon_failure
21
+ stub_request(:get, "http://0.0.0.0/api/0123456789abdcef0123456789abcdef/").to_return(body: MultiJson.dump([{"error"=>{"type"=>1, "address"=>"/", "description"=>"unauthorized user"}}]), headers: {"Content-Type" => 'application/json'})
22
+ stub_request(:post, "http://0.0.0.0/api").with(body: MultiJson.dump({username: '0123456789abdcef0123456789abcdef', devicetype: 'Huey'})).to_return(body: MultiJson.dump([{"error"=>{"type"=>101, "address"=>"", "description"=>"link button not pressed"}}]), headers: {"Content-Type" => 'application/json'})
23
+
24
+ assert_raises Huey::Errors::PressLinkButton do
25
+ Huey::Request.get
26
+ end
27
+
28
+ assert_requested :get, "http://0.0.0.0/api/0123456789abdcef0123456789abcdef/"
29
+ assert_requested :post, "http://0.0.0.0/api"
30
+ end
31
+
32
+ def test_raises_unexpected_errors
33
+ stub_request(:get, "http://0.0.0.0/api/0123456789abdcef0123456789abcdef/").to_return(body: MultiJson.dump([{"error"=>{"type"=>404, "address"=>"/", "description"=>"bad error!"}}]), headers: {"Content-Type" => 'application/json'})
34
+
35
+ assert_raises Huey::Errors::HueResponseError do
36
+ Huey::Request.get
37
+ end
38
+
39
+ assert_requested :get, "http://0.0.0.0/api/0123456789abdcef0123456789abcdef/"
40
+ end
41
+ end
@@ -0,0 +1,29 @@
1
+ require 'test_helper'
2
+
3
+ class SSDPTest < Test::Unit::TestCase
4
+
5
+ def setup
6
+ super
7
+ set_hue_ip(nil)
8
+ end
9
+
10
+ def test_raises_error_with_no_ip
11
+ searcher = mock()
12
+ responses = mock()
13
+ responses.stubs(:subscribe).returns(true)
14
+ searcher.stubs(:discovery_responses).returns(responses)
15
+
16
+ EM.expects(:open_datagram_socket).once.returns(searcher)
17
+
18
+ assert_raises Huey::Errors::CouldNotFindHue do
19
+ Huey::SSDP.hue_ip
20
+ end
21
+ end
22
+
23
+ def test_finds_ip_correctly
24
+ EM.expects(:open_datagram_socket).once.returns(fake_searcher)
25
+
26
+ assert Huey::SSDP.hue_ip == '192.168.0.1'
27
+ end
28
+
29
+ end
metadata ADDED
@@ -0,0 +1,167 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: huey
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Veraticus
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-12-20 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: eventmachine
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: 1.0.0
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ! '>='
28
+ - !ruby/object:Gem::Version
29
+ version: 1.0.0
30
+ - !ruby/object:Gem::Dependency
31
+ name: httparty
32
+ requirement: !ruby/object:Gem::Requirement
33
+ none: false
34
+ requirements:
35
+ - - ! '>='
36
+ - !ruby/object:Gem::Version
37
+ version: 0.9.0
38
+ type: :runtime
39
+ prerelease: false
40
+ version_requirements: !ruby/object:Gem::Requirement
41
+ none: false
42
+ requirements:
43
+ - - ! '>='
44
+ - !ruby/object:Gem::Version
45
+ version: 0.9.0
46
+ - !ruby/object:Gem::Dependency
47
+ name: bundler
48
+ requirement: !ruby/object:Gem::Requirement
49
+ none: false
50
+ requirements:
51
+ - - ! '>='
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ type: :development
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ none: false
58
+ requirements:
59
+ - - ! '>='
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ - !ruby/object:Gem::Dependency
63
+ name: yard
64
+ requirement: !ruby/object:Gem::Requirement
65
+ none: false
66
+ requirements:
67
+ - - ! '>='
68
+ - !ruby/object:Gem::Version
69
+ version: 0.8.3
70
+ type: :development
71
+ prerelease: false
72
+ version_requirements: !ruby/object:Gem::Requirement
73
+ none: false
74
+ requirements:
75
+ - - ! '>='
76
+ - !ruby/object:Gem::Version
77
+ version: 0.8.3
78
+ - !ruby/object:Gem::Dependency
79
+ name: mocha
80
+ requirement: !ruby/object:Gem::Requirement
81
+ none: false
82
+ requirements:
83
+ - - ! '>='
84
+ - !ruby/object:Gem::Version
85
+ version: 0.13.1
86
+ type: :development
87
+ prerelease: false
88
+ version_requirements: !ruby/object:Gem::Requirement
89
+ none: false
90
+ requirements:
91
+ - - ! '>='
92
+ - !ruby/object:Gem::Version
93
+ version: 0.13.1
94
+ - !ruby/object:Gem::Dependency
95
+ name: webmock
96
+ requirement: !ruby/object:Gem::Requirement
97
+ none: false
98
+ requirements:
99
+ - - ! '>='
100
+ - !ruby/object:Gem::Version
101
+ version: 1.9.0
102
+ type: :development
103
+ prerelease: false
104
+ version_requirements: !ruby/object:Gem::Requirement
105
+ none: false
106
+ requirements:
107
+ - - ! '>='
108
+ - !ruby/object:Gem::Version
109
+ version: 1.9.0
110
+ description: Everything you could want for making Phillips Hue lightbulbs obey your
111
+ every command.
112
+ email: josh@joshsymonds.com
113
+ executables: []
114
+ extensions: []
115
+ extra_rdoc_files:
116
+ - LICENSE
117
+ - README.markdown
118
+ files:
119
+ - .gitignore
120
+ - Gemfile
121
+ - Gemfile.lock
122
+ - LICENSE
123
+ - README.markdown
124
+ - Rakefile
125
+ - huey.gemspec
126
+ - lib/huey.rb
127
+ - lib/huey/bulb.rb
128
+ - lib/huey/config.rb
129
+ - lib/huey/config/options.rb
130
+ - lib/huey/errors.rb
131
+ - lib/huey/request.rb
132
+ - lib/huey/ssdp.rb
133
+ - lib/huey/ssdp/searcher.rb
134
+ - lib/huey/version.rb
135
+ - test/test_helper.rb
136
+ - test/unit/bulb_test.rb
137
+ - test/unit/request_test.rb
138
+ - test/unit/ssdp_test.rb
139
+ homepage: https://github.com/Veraticus/huey
140
+ licenses: []
141
+ post_install_message:
142
+ rdoc_options: []
143
+ require_paths:
144
+ - lib
145
+ required_ruby_version: !ruby/object:Gem::Requirement
146
+ none: false
147
+ requirements:
148
+ - - ! '>='
149
+ - !ruby/object:Gem::Version
150
+ version: 1.9.1
151
+ required_rubygems_version: !ruby/object:Gem::Requirement
152
+ none: false
153
+ requirements:
154
+ - - ! '>='
155
+ - !ruby/object:Gem::Version
156
+ version: '0'
157
+ segments:
158
+ - 0
159
+ hash: -1646308313904845457
160
+ requirements: []
161
+ rubyforge_project:
162
+ rubygems_version: 1.8.24
163
+ signing_key:
164
+ specification_version: 3
165
+ summary: Quick and simple discovery and control of Phillips Hue lightbulbs
166
+ test_files: []
167
+ has_rdoc: