From 9a494fc233ff3fc74b1a30a672a10e49b44de549 Mon Sep 17 00:00:00 2001 From: Collin Guarino Date: Fri, 12 Feb 2016 17:44:52 -0500 Subject: Added Light.Blink and made SetLightState get the new light state after a change. --- light.go | 40 +++++++++++++++++++++++++++++++++++++++- light_test.go | 9 ++++++--- 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/light.go b/light.go index 413d9bc..252a84a 100644 --- a/light.go +++ b/light.go @@ -13,6 +13,7 @@ import ( "encoding/json" "strings" "errors" + "time" ) // Light struct defines attributes of a light. @@ -82,10 +83,38 @@ func (self *Light) On() error { // Light.Toggle will toggle the light source on and off func (self *Light) Toggle() error { if self.State.On { + fmt.Println("toggling off") return self.Off() } else { + fmt.Println("toggling on") return self.On() } + return nil +} + +// Light.Blink will turn the light off and on repeatedly for a given seconds +// interval and return the light back to its off or on state afterwards. +// Note: time will vary based on connection speed and algorithm speed. +func (self *Light) Blink(seconds int) error { + originalState := self.State.On + + // Toggle the light on and off + for i := 0; i <= seconds; i++ { + err := self.Toggle() + if err != nil { + return err + } + time.Sleep(time.Second) + } + + // Return the light to its original on or off state + if self.State.On != originalState { + err := self.Toggle() + if err != nil { + return err + } + } + return nil } // Light.ColorLoop will set the light state to 'colorloop' if `active` @@ -103,7 +132,16 @@ func (self *Light) ColorLoop(activate bool) error { func SetLightState(light *Light, newState LightState) error { uri := fmt.Sprintf("/api/%s/lights/%d/state", light.Bridge.Username, light.Index) _, _, err := light.Bridge.Put(uri, newState) - return err + if err != nil { + return err + } + + // Get the new light state and update the current Light struct + *light, err = GetLight(light.Bridge, light.Name) + if err != nil { + return err + } + return nil } // GetAllLights retreives the state of all lights that the bridge is aware of. diff --git a/light_test.go b/light_test.go index 98c2030..0ecfeaa 100644 --- a/light_test.go +++ b/light_test.go @@ -10,7 +10,7 @@ package hue import ( "testing" "fmt" - "time" + //"time" ) func TestGetAllLights(t *testing.T) { @@ -27,7 +27,7 @@ func TestSetLightState(t *testing.T) { fmt.Println("\nTESTING LIGHT STATE:\n\n") bridge := NewBridge("192.168.1.128", "319b36233bd2328f3e40731b23479207") lights, _ := GetAllLights(bridge) - selectedLight := lights[0] + selectedLight := lights[5] selectedLight.On() time.Sleep(time.Second) @@ -35,7 +35,10 @@ func TestSetLightState(t *testing.T) { time.Sleep(time.Second) selectedLight.Toggle() time.Sleep(time.Second) + selectedLight.ColorLoop(false) - selectedLight.SetName("Ceiling Fan Outer") + selectedLight.SetName(selectedLight.Name) + + selectedLight.Blink(3) } -- cgit v1.2.3