From 2b398315af634497a6e7afd0e927e47212cac88d Mon Sep 17 00:00:00 2001 From: Collin Guarino Date: Sat, 27 Feb 2016 00:04:52 -0500 Subject: Implemented FindBridge, added unit tests, and documentation. --- bridge.go | 27 ++++++++++++++++++++++++++- bridge_test.go | 6 ++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/bridge.go b/bridge.go index cd0f30d..217bf7c 100644 --- a/bridge.go +++ b/bridge.go @@ -148,6 +148,28 @@ func HandleResponse(resp *http.Response) ([]byte, io.Reader, error) { return body, reader, nil } +// FindBridge will visit www.meethue.com/api/nupnp to see if a bridge +// is available on the local network. This feature currently only supports one +// bridge on the network. +func FindBridge() (Bridge, error) { + bridge := Bridge { IPAddress: "www.meethue.com" } + body, _, err := bridge.Get("/api/nupnp") + if err != nil { + err = errors.New("Unable to locate bridge.") + log.Fatal(err) + return Bridge{}, err + } + content := string(body) + ip := content[strings.LastIndex(content, ":\"")+2 : + strings.LastIndex(content, "\"}]")] + bridge.IPAddress = ip + err = bridge.GetInfo() + if err != nil { + return Bridge{}, err + } + return bridge, nil +} + // NewBridge defines hardware that is compatible with Hue. // The function is the core of all functionality, it's necessary // to call `NewBridge` and `Login` or `CreateUser` to access any @@ -166,6 +188,9 @@ func NewBridge(ip string) (*Bridge, error) { } // GetBridgeInfo retreives the description.xml file from the bridge. +// This is used as a check to see if the bridge is accessible +// and any error will be fatal as the bridge is required for nearly +// all functions. func (bridge *Bridge) GetInfo() error { _, reader, err := bridge.Get("/description.xml") if err != nil { @@ -175,7 +200,7 @@ func (bridge *Bridge) GetInfo() error { err = xml.NewDecoder(reader).Decode(&data) if err != nil { err = errors.New("Error: Unable to decode XML response from bridge. ") - log.Println(err) + log.Fatal(err) return err } bridge.Info = data diff --git a/bridge_test.go b/bridge_test.go index 65c2c4a..3fcaa81 100644 --- a/bridge_test.go +++ b/bridge_test.go @@ -9,6 +9,7 @@ package hue import ( "testing" + "fmt" ) func TestCreateUser(t *testing.T) { @@ -16,3 +17,8 @@ func TestCreateUser(t *testing.T) { bridge.CreateUser("test") //bridge.DeleteUser(bridge.Username) } + +func TestFindBridge(t *testing.T) { + bridge, _ := FindBridge() + fmt.Println(bridge.IPAddress) +} -- cgit v1.2.3