From f18585ea7bc206d931f850d7df1fb96125e2a232 Mon Sep 17 00:00:00 2001 From: Collin Guarino Date: Fri, 12 Feb 2016 17:53:20 -0500 Subject: Major speed improvement for getting light state. --- light.go | 47 ++++++++++++++++++++++++++++------------------- light_test.go | 2 +- 2 files changed, 29 insertions(+), 20 deletions(-) diff --git a/light.go b/light.go index 252a84a..7847df1 100644 --- a/light.go +++ b/light.go @@ -150,32 +150,41 @@ func GetAllLights(bridge *Bridge) ([]Light, error) { // and parse their values. Supports 100 lights. var lights []Light for index := 1; index < 101; index++ { - - // Send an http GET and inspect the response - uri := fmt.Sprintf("/api/%s/lights/%d", bridge.Username, index) - body, _, err := bridge.Get(uri) + light, err := GetLightByIndex(bridge, index) if err != nil { - return lights, err - } - if strings.Contains(string(body), "not available") { - // Handle end of searchable lights - //fmt.Printf("\n\n%d lights found.\n\n", index) break } - - // Parse and load the response into the light array - data := Light{} - err = json.Unmarshal(body, &data) - if err != nil { - trace("", err) - } - data.Index = index - data.Bridge = bridge - lights = append(lights, data) + lights = append(lights, light) } return lights, nil } +// GetLightByIndex will return a light struct containing data on +// a light given its index stored on the bridge. This is used for +// quickly updating an individual light. +func GetLightByIndex(bridge *Bridge, index int) (Light, error) { + + // Send an http GET and inspect the response + uri := fmt.Sprintf("/api/%s/lights/%d", bridge.Username, index) + body, _, err := bridge.Get(uri) + if err != nil { + return Light{}, err + } + if strings.Contains(string(body), "not available") { + return Light{}, errors.New("Index Error") + } + + // Parse and load the response into the light array + light := Light{} + err = json.Unmarshal(body, &light) + if err != nil { + trace("", err) + } + light.Index = index + light.Bridge = bridge + return light, nil +} + // GetLight will return a light struct containing data on a given name. func GetLight(bridge *Bridge, name string) (Light, error) { lights, _ := GetAllLights(bridge) diff --git a/light_test.go b/light_test.go index 0ecfeaa..9073a06 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) { -- cgit v1.2.3