aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--bridge.go446
-rw-r--r--bridge_test.go28
-rw-r--r--group.go60
-rw-r--r--group_test.go18
-rw-r--r--light.go337
-rw-r--r--light_test.go92
-rw-r--r--scene.go102
-rw-r--r--scene_test.go32
-rw-r--r--schedule.go94
-rw-r--r--schedule_test.go16
10 files changed, 610 insertions, 615 deletions
diff --git a/bridge.go b/bridge.go
index d9c0c5c..8b7df9f 100644
--- a/bridge.go
+++ b/bridge.go
@@ -3,7 +3,7 @@
* GoHue library for Philips Hue
* Copyright (C) 2016 Collin Guarino (Collinux) collin.guarino@gmail.com
* License: GPL version 2 or higher http://www.gnu.org/licenses/gpl.html
-*/
+ */
// All things start with the bridge. You will find many Bridge.Func() items
// to use once a bridge has been created and identified.
// See the getting started guide on the Philips hue website:
@@ -12,163 +12,160 @@
package hue
import (
- "log"
- "encoding/xml"
- "encoding/json"
- "net/http"
- "io/ioutil"
- "runtime"
- "fmt"
- "strings"
- "bytes"
- "io"
- "errors"
- "strconv"
+ "bytes"
+ "encoding/json"
+ "encoding/xml"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "runtime"
+ "strconv"
+ "strings"
)
// Bridge struct defines hardware that is used to communicate with the lights.
type Bridge struct {
- IPAddress string
- Username string
- Info BridgeInfo
+ IPAddress string
+ Username string
+ Info BridgeInfo
}
// BridgeInfo struct is the format for parsing xml from a bridge.
type BridgeInfo struct {
- XMLName xml.Name `xml:"root"`
- Device struct {
- XMLName xml.Name `xml:"device"`
- DeviceType string `xml:"deviceType"`
- FriendlyName string `xml:"friendlyName"`
- Manufacturer string `xml:"manufacturer"`
- ManufacturerURL string `xml:"manufacturerURL"`
- ModelDescription string `xml:"modelDescription"`
- ModelName string `xml:"modelName"`
- ModelNumber string `xml:"modelNumber"`
- ModelURL string `xml:"modelURL"`
- SerialNumber string `xml:"serialNumber"`
- UDN string `xml:"UDN"`
- } `xml:"device"`
+ XMLName xml.Name `xml:"root"`
+ Device struct {
+ XMLName xml.Name `xml:"device"`
+ DeviceType string `xml:"deviceType"`
+ FriendlyName string `xml:"friendlyName"`
+ Manufacturer string `xml:"manufacturer"`
+ ManufacturerURL string `xml:"manufacturerURL"`
+ ModelDescription string `xml:"modelDescription"`
+ ModelName string `xml:"modelName"`
+ ModelNumber string `xml:"modelNumber"`
+ ModelURL string `xml:"modelURL"`
+ SerialNumber string `xml:"serialNumber"`
+ UDN string `xml:"UDN"`
+ } `xml:"device"`
}
// bridge.Get sends an http GET to the bridge
func (bridge *Bridge) Get(path string) ([]byte, io.Reader, error) {
- uri := fmt.Sprintf("http://" + bridge.IPAddress + path)
- resp, err := http.Get(uri)
- if err != nil {
- err = errors.New("Error: Unable to access bridge. ")
- log.Println(err)
- return []byte{}, nil, err
- }
- return HandleResponse(resp)
+ uri := fmt.Sprintf("http://" + bridge.IPAddress + path)
+ resp, err := http.Get(uri)
+ if err != nil {
+ err = errors.New("Error: Unable to access bridge. ")
+ log.Println(err)
+ return []byte{}, nil, err
+ }
+ return HandleResponse(resp)
}
// Bridge.Put sends an http PUT to the bridge with
// a body formatted with parameters (in a generic interface)
func (bridge *Bridge) Put(path string, params interface{}) ([]byte, io.Reader, error) {
- uri := fmt.Sprintf("http://" + bridge.IPAddress + path)
- client := &http.Client{}
+ uri := fmt.Sprintf("http://" + bridge.IPAddress + path)
+ client := &http.Client{}
- data, err := json.Marshal(params)
- if err != nil {
- err = errors.New("Error: Unable marshal PUT request interface.")
- log.Println(err)
- return []byte{}, nil, err
- }
- //fmt.Println("\n\nPARAMS: ", params)
- //log.Println("\nSending PUT body: ", string(data))
+ data, err := json.Marshal(params)
+ if err != nil {
+ err = errors.New("Error: Unable marshal PUT request interface.")
+ log.Println(err)
+ return []byte{}, nil, err
+ }
+ //fmt.Println("\n\nPARAMS: ", params)
+ //log.Println("\nSending PUT body: ", string(data))
request, err := http.NewRequest("PUT", uri, bytes.NewReader(data))
- resp, err := client.Do(request)
- if err != nil {
- err = errors.New("Error: Unable to access bridge.")
- log.Println(err)
- return []byte{}, nil, err
- }
- return HandleResponse(resp)
+ resp, err := client.Do(request)
+ if err != nil {
+ err = errors.New("Error: Unable to access bridge.")
+ log.Println(err)
+ return []byte{}, nil, err
+ }
+ return HandleResponse(resp)
}
// bridge.Post sends an http POST to the bridge with
// a body formatted with parameters (in a generic interface)
func (bridge *Bridge) Post(path string, params interface{}) ([]byte, io.Reader, error) {
- // Add the params to the request
- request, err := json.Marshal(params)
- if err != nil {
- err = errors.New("Error: Unable to marshal request from bridge http POST")
- log.Println(err)
- return []byte{}, nil, err
- }
+ // Add the params to the request
+ request, err := json.Marshal(params)
+ if err != nil {
+ err = errors.New("Error: Unable to marshal request from bridge http POST")
+ log.Println(err)
+ return []byte{}, nil, err
+ }
- // Send the request and handle the response
- uri := fmt.Sprintf("http://" + bridge.IPAddress + path)
- resp, err := http.Post(uri, "text/json", bytes.NewReader(request))
- if err != nil {
- err = errors.New("Error: Unable to access bridge.")
- log.Println(err)
- return []byte{}, nil, err
- }
- return HandleResponse(resp)
+ // Send the request and handle the response
+ uri := fmt.Sprintf("http://" + bridge.IPAddress + path)
+ resp, err := http.Post(uri, "text/json", bytes.NewReader(request))
+ if err != nil {
+ err = errors.New("Error: Unable to access bridge.")
+ log.Println(err)
+ return []byte{}, nil, err
+ }
+ return HandleResponse(resp)
}
// Bridge.Delete sends an http DELETE to the bridge
func (bridge *Bridge) Delete(path string) error {
- uri := fmt.Sprintf("http://" + bridge.IPAddress + path)
- client := &http.Client{}
- req, err := http.NewRequest("DELETE", uri, nil)
- resp, err := client.Do(req)
- if err != nil {
- err = errors.New("Error: Unable to access bridge.")
- log.Println(err)
- return err
- }
- _, _, err = HandleResponse(resp)
- return err
+ uri := fmt.Sprintf("http://" + bridge.IPAddress + path)
+ client := &http.Client{}
+ req, err := http.NewRequest("DELETE", uri, nil)
+ resp, err := client.Do(req)
+ if err != nil {
+ err = errors.New("Error: Unable to access bridge.")
+ log.Println(err)
+ return err
+ }
+ _, _, err = HandleResponse(resp)
+ return err
}
// HandleResponse manages the http.Response content from a
// bridge Get/Put/Post/Delete by checking it for errors
// and invalid return types.
func HandleResponse(resp *http.Response) ([]byte, io.Reader, error) {
- body, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- trace("Error parsing bridge description xml.", nil)
- return []byte{}, nil, err
- }
- reader := bytes.NewReader(body)
- if strings.Contains(string(body), "\"error\"") {
- errString := string(body)
- errNum := errString[strings.Index(errString, "type\":")+6 :
- strings.Index(errString, ",\"address")]
- errDesc := errString[strings.Index(errString, "description\":\"")+14 :
- strings.Index(errString, "\"}}")]
- errOut := fmt.Sprintf("Error type %s: %s.", errNum, errDesc)
- err = errors.New(errOut)
- log.Println(err)
- return []byte{}, nil, err
- }
- return body, reader, nil
+ body, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ trace("Error parsing bridge description xml.", nil)
+ return []byte{}, nil, err
+ }
+ reader := bytes.NewReader(body)
+ if strings.Contains(string(body), "\"error\"") {
+ errString := string(body)
+ errNum := errString[strings.Index(errString, "type\":")+6 : strings.Index(errString, ",\"address")]
+ errDesc := errString[strings.Index(errString, "description\":\"")+14 : strings.Index(errString, "\"}}")]
+ errOut := fmt.Sprintf("Error type %s: %s.", errNum, errDesc)
+ err = errors.New(errOut)
+ log.Println(err)
+ return []byte{}, nil, err
+ }
+ 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("Error: 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
+ bridge := Bridge{IPAddress: "www.meethue.com"}
+ body, _, err := bridge.Get("/api/nupnp")
+ if err != nil {
+ err = errors.New("Error: 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.
@@ -176,16 +173,16 @@ func FindBridge() (Bridge, error) {
// to call `NewBridge` and `Login` or `CreateUser` to access any
// lights, scenes, groups, etc.
func NewBridge(ip string) (*Bridge, error) {
- bridge := Bridge {
- IPAddress: ip,
- }
- // Test the connection by attempting to get the bridge info.
- err := bridge.GetInfo()
- if err != nil {
- log.Fatal("Error: Unable to access bridge. ", err)
- return &Bridge{}, err
- }
- return &bridge, nil
+ bridge := Bridge{
+ IPAddress: ip,
+ }
+ // Test the connection by attempting to get the bridge info.
+ err := bridge.GetInfo()
+ if err != nil {
+ log.Fatal("Error: Unable to access bridge. ", err)
+ return &Bridge{}, err
+ }
+ return &bridge, nil
}
// GetBridgeInfo retreives the description.xml file from the bridge.
@@ -193,32 +190,32 @@ func NewBridge(ip string) (*Bridge, error) {
// 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 {
- return err
- }
- data := BridgeInfo{}
- err = xml.NewDecoder(reader).Decode(&data)
- if err != nil {
- err = errors.New("Error: Unable to decode XML response from bridge. ")
- log.Fatal(err)
- return err
- }
- bridge.Info = data
- return nil
+ _, reader, err := bridge.Get("/description.xml")
+ if err != nil {
+ return err
+ }
+ data := BridgeInfo{}
+ err = xml.NewDecoder(reader).Decode(&data)
+ if err != nil {
+ err = errors.New("Error: Unable to decode XML response from bridge. ")
+ log.Fatal(err)
+ return err
+ }
+ bridge.Info = data
+ return nil
}
// Bridge.Login verifies that the username token has bridge access
// and only assigns the bridge its Username value if verification is successful.
func (bridge *Bridge) Login(username string) error {
- uri := fmt.Sprintf("/api/%s", username)
- _, _, err := bridge.Get(uri)
- if err != nil {
- log.Fatal(err)
- return err
- }
- bridge.Username = username
- return nil
+ uri := fmt.Sprintf("/api/%s", username)
+ _, _, err := bridge.Get(uri)
+ if err != nil {
+ log.Fatal(err)
+ return err
+ }
+ bridge.Username = username
+ return nil
}
// Bridge.CreateUser adds a new user token on the whitelist.
@@ -227,110 +224,109 @@ func (bridge *Bridge) Login(username string) error {
// like the argument provided in this function.
// This was done by Philips Hue for security reasons.
func (bridge *Bridge) CreateUser(deviceType string) (string, error) {
- params := map[string]string{"devicetype": deviceType}
- body, _, err := bridge.Post("/api", params)
- if err != nil {
- log.Fatal("Error: Failed to create user. ", err)
- return "", err
- }
- content := string(body)
- username := content[strings.LastIndex(content, ":\"")+2 :
- strings.LastIndex(content, "\"")]
- userOut := fmt.Sprintf(
- "Created user token '%s'. Use Bridge.Login with this token from now on.",
- username)
- log.Println(userOut)
- bridge.Username = username
- return username, nil
+ params := map[string]string{"devicetype": deviceType}
+ body, _, err := bridge.Post("/api", params)
+ if err != nil {
+ log.Fatal("Error: Failed to create user. ", err)
+ return "", err
+ }
+ content := string(body)
+ username := content[strings.LastIndex(content, ":\"")+2 : strings.LastIndex(content, "\"")]
+ userOut := fmt.Sprintf(
+ "Created user token '%s'. Use Bridge.Login with this token from now on.",
+ username)
+ log.Println(userOut)
+ bridge.Username = username
+ return username, nil
}
// Bridge.DeleteUser deletes a user given its USER KEY, not the string name.
// See http://www.developers.meethue.com/documentation/configuration-api
// for description on `username` deprecation in place of the devicetype key.
func (bridge *Bridge) DeleteUser(username string) error {
- uri := fmt.Sprintf("/api/%s/config/whitelist/%s", bridge.Username, username)
- err := bridge.Delete(uri)
- if err != nil {
- return err
- }
- return nil
+ uri := fmt.Sprintf("/api/%s/config/whitelist/%s", bridge.Username, username)
+ err := bridge.Delete(uri)
+ if err != nil {
+ return err
+ }
+ return nil
}
// GetAllLights retreives the state of all lights that the bridge is aware of.
func (bridge *Bridge) GetAllLights() ([]Light, error) {
- uri := fmt.Sprintf("/api/%s/lights", bridge.Username)
- body, _, err := bridge.Get(uri)
- if err != nil {
- return []Light{}, err
- }
+ uri := fmt.Sprintf("/api/%s/lights", bridge.Username)
+ body, _, err := bridge.Get(uri)
+ if err != nil {
+ return []Light{}, err
+ }
- // An index is at the top of every Light in the array
- lightMap := map[string]Light{}
- err = json.Unmarshal(body, &lightMap)
- if err != nil {
- return []Light{}, errors.New("Unable to marshal GetAllLights response. ")
- }
+ // An index is at the top of every Light in the array
+ lightMap := map[string]Light{}
+ err = json.Unmarshal(body, &lightMap)
+ if err != nil {
+ return []Light{}, errors.New("Unable to marshal GetAllLights response. ")
+ }
- // Parse the index, add the light to the list, and return the array
- lights := []Light{}
- for index, light := range lightMap {
- light.Index, err = strconv.Atoi(index)
- if err != nil {
- return []Light{}, errors.New("Unable to convert light index to integer. ")
- }
- light.Bridge = bridge
- lights = append(lights, light)
- }
- return lights, nil
+ // Parse the index, add the light to the list, and return the array
+ lights := []Light{}
+ for index, light := range lightMap {
+ light.Index, err = strconv.Atoi(index)
+ if err != nil {
+ return []Light{}, errors.New("Unable to convert light index to integer. ")
+ }
+ light.Bridge = bridge
+ lights = append(lights, light)
+ }
+ return lights, nil
}
// GetLightByIndex returns 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 (bridge *Bridge) GetLightByIndex(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("Error: Light selection index out of bounds. ")
- }
+ // 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("Error: Light selection index out of bounds. ")
+ }
- // Parse and load the response into the light array
- light := Light{}
- err = json.Unmarshal(body, &light)
- if err != nil {
- return Light{}, errors.New("Error: Unable to unmarshal light data. ")
- }
- light.Index = index
- light.Bridge = bridge
- return light, nil
+ // Parse and load the response into the light array
+ light := Light{}
+ err = json.Unmarshal(body, &light)
+ if err != nil {
+ return Light{}, errors.New("Error: Unable to unmarshal light data. ")
+ }
+ light.Index = index
+ light.Bridge = bridge
+ return light, nil
}
// GetLight returns a light struct containing data on a given name.
func (bridge *Bridge) GetLightByName(name string) (Light, error) {
- lights, _ := bridge.GetAllLights()
- for _, light := range lights {
- if light.Name == name {
- return light, nil
- }
- }
- errOut := fmt.Sprintf("Error: Light name '%s' not found. ", name)
- return Light{}, errors.New(errOut)
+ lights, _ := bridge.GetAllLights()
+ for _, light := range lights {
+ if light.Name == name {
+ return light, nil
+ }
+ }
+ errOut := fmt.Sprintf("Error: Light name '%s' not found. ", name)
+ return Light{}, errors.New(errOut)
}
// Log the date, time, file location, line number, and function.
// Message can be "" or Err can be nil (not both)
func trace(message string, err error) {
- pc := make([]uintptr, 10)
- runtime.Callers(2, pc)
- f := runtime.FuncForPC(pc[0])
- file, line := f.FileLine(pc[0])
- if err != nil {
- log.Printf("%s:%d %s: %s\n", file, line, f.Name(), err)
- } else {
- log.Printf("%s:%d %s: %s\n", file, line, f.Name(), message)
- }
+ pc := make([]uintptr, 10)
+ runtime.Callers(2, pc)
+ f := runtime.FuncForPC(pc[0])
+ file, line := f.FileLine(pc[0])
+ if err != nil {
+ log.Printf("%s:%d %s: %s\n", file, line, f.Name(), err)
+ } else {
+ log.Printf("%s:%d %s: %s\n", file, line, f.Name(), message)
+ }
}
diff --git a/bridge_test.go b/bridge_test.go
index b98d63e..cc312fe 100644
--- a/bridge_test.go
+++ b/bridge_test.go
@@ -3,32 +3,32 @@
* GoHue library for Philips Hue
* Copyright (C) 2016 Collin Guarino (Collinux) collin.guarino@gmail.com
* License: GPL version 2 or higher http://www.gnu.org/licenses/gpl.html
-*/
+ */
package hue
import (
- "testing"
- "fmt"
+ "fmt"
+ "testing"
)
func TestCreateUser(t *testing.T) {
- bridge, _ := NewBridge("192.168.1.128")
- username, _ := bridge.CreateUser("test")
- bridge.Login(username)
- //bridge.DeleteUser(bridge.Username)
+ bridge, _ := NewBridge("192.168.1.128")
+ username, _ := bridge.CreateUser("test")
+ bridge.Login(username)
+ //bridge.DeleteUser(bridge.Username)
}
func TestFindBridge(t *testing.T) {
- bridge, _ := FindBridge()
- fmt.Println(bridge.IPAddress)
+ bridge, _ := FindBridge()
+ fmt.Println(bridge.IPAddress)
}
func TestBridgeLogin(t *testing.T) {
- bridge, err := FindBridge()
- if err != nil {
- fmt.Println("Error on TestBridgeLogin")
- }
- bridge.Login("427de8bd6d49f149c8398e4fc08f")
+ bridge, err := FindBridge()
+ if err != nil {
+ fmt.Println("Error on TestBridgeLogin")
+ }
+ bridge.Login("427de8bd6d49f149c8398e4fc08f")
}
diff --git a/group.go b/group.go
index f10ab96..4a36346 100644
--- a/group.go
+++ b/group.go
@@ -3,51 +3,51 @@
* GoHue library for Philips Hue
* Copyright (C) 2016 Collin Guarino (Collinux) collin.guarino@gmail.com
* License: GPL version 2 or higher http://www.gnu.org/licenses/gpl.html
-*/
+ */
// http://www.developers.meethue.com/documentation/groups-api
package hue
import (
- "fmt"
- "encoding/json"
+ "encoding/json"
+ "fmt"
)
// Group struct defines the attributes for a group of lights.
type Group struct {
- Action struct {
- Alert string `json:"alert"`
- Bri int `json:"bri"`
- Colormode string `json:"colormode"`
- Ct int `json:"ct"`
- Effect string `json:"effect"`
- Hue int `json:"hue"`
- On bool `json:"on"`
- Sat int `json:"sat"`
- XY []float64 `json:"xy"`
- } `json:"action"`
- Lights []string `json:"lights"`
- Name string `json:"name"`
- Type string `json:"type"`
+ Action struct {
+ Alert string `json:"alert"`
+ Bri int `json:"bri"`
+ Colormode string `json:"colormode"`
+ Ct int `json:"ct"`
+ Effect string `json:"effect"`
+ Hue int `json:"hue"`
+ On bool `json:"on"`
+ Sat int `json:"sat"`
+ XY []float64 `json:"xy"`
+ } `json:"action"`
+ Lights []string `json:"lights"`
+ Name string `json:"name"`
+ Type string `json:"type"`
}
// Bridge.GetGroups gets the attributes for each group of lights.
// TODO: NOT TESTED, NOT FULLY IMPLEMENTED
func (bridge *Bridge) GetGroups() ([]Group, error) {
- uri := fmt.Sprintf("/api/%s/groups", bridge.Username)
- body, _, err := bridge.Get(uri)
- if err != nil {
- return []Group{}, err
- }
+ uri := fmt.Sprintf("/api/%s/groups", bridge.Username)
+ body, _, err := bridge.Get(uri)
+ if err != nil {
+ return []Group{}, err
+ }
- //fmt.Println("GROUP GET: ", string(body))
+ //fmt.Println("GROUP GET: ", string(body))
- groups := map[string]Group{}
- err = json.Unmarshal(body, &groups)
- if err != nil {
- return []Group{}, err
- }
- //fmt.Println("GROUPS: ", groups)
+ groups := map[string]Group{}
+ err = json.Unmarshal(body, &groups)
+ if err != nil {
+ return []Group{}, err
+ }
+ //fmt.Println("GROUPS: ", groups)
- return []Group{}, nil
+ return []Group{}, nil
}
diff --git a/group_test.go b/group_test.go
index ea13d64..58b74bc 100644
--- a/group_test.go
+++ b/group_test.go
@@ -3,20 +3,20 @@
* GoHue library for Philips Hue
* Copyright (C) 2016 Collin Guarino (Collinux) collin.guarino@gmail.com
* License: GPL version 2 or higher http://www.gnu.org/licenses/gpl.html
-*/
+ */
package hue
import (
- "testing"
- "fmt"
+ "fmt"
+ "testing"
)
func TestGetGroups(t *testing.T) {
- bridge, _ := NewBridge("192.168.1.128")
- bridge.Login("427de8bd6d49f149c8398e4fc08f")
- groups, _ := bridge.GetGroups()
- for group := range groups {
- fmt.Println(groups[group])
- }
+ bridge, _ := NewBridge("192.168.1.128")
+ bridge.Login("427de8bd6d49f149c8398e4fc08f")
+ groups, _ := bridge.GetGroups()
+ for group := range groups {
+ fmt.Println(groups[group])
+ }
}
diff --git a/light.go b/light.go
index f6674de..0dd38db 100644
--- a/light.go
+++ b/light.go
@@ -3,103 +3,103 @@
* GoHue library for Philips Hue
* Copyright (C) 2016 Collin Guarino (Collinux) collin.guarino@gmail.com
* License: GPL version 2 or higher http://www.gnu.org/licenses/gpl.html
-*/
+ */
// http://www.developers.meethue.com/documentation/lights-api
package hue
import (
- "fmt"
- "time"
- "errors"
- "log"
+ "errors"
+ "fmt"
+ "log"
+ "time"
)
// Light struct defines attributes of a light.
type Light struct {
- State struct {
- On bool `json:"on"` // On or Off state of the light ("true" or "false")
- Bri uint8 `json:"bri"` // Brightness value 1-254
- Hue int `json:"hue"` // Hue value 1-65535
- Saturation int `json:"sat"` // Saturation value 0-254
- Effect string `json:"effect"` // "None" or "Colorloop"
- XY [2]float32 `json:"xy"` // Coordinates of color in CIE color space
- CT int `json:"ct"` // Mired Color Temperature (google it)
- Alert string `json:"alert"` // "selected" or "none"
- ColorMode string `json:"colormode"` // HS or XY mode for choosing color
- Reachable bool `json:"reachable"`
- } `json:"state"`
- Type string `json:"type"`
- Name string `json:"name"`
- ModelID string `json:"modelid"`
- ManufacturerName string `json:"manufacturername"`
- UniqueID string `json:"uniqueid"`
- SWVersion string `json:"swversion"`
- Index int // Set by index of light array response
- Bridge *Bridge // Set by the bridge when the light is found
+ State struct {
+ On bool `json:"on"` // On or Off state of the light ("true" or "false")
+ Bri uint8 `json:"bri"` // Brightness value 1-254
+ Hue int `json:"hue"` // Hue value 1-65535
+ Saturation int `json:"sat"` // Saturation value 0-254
+ Effect string `json:"effect"` // "None" or "Colorloop"
+ XY [2]float32 `json:"xy"` // Coordinates of color in CIE color space
+ CT int `json:"ct"` // Mired Color Temperature (google it)
+ Alert string `json:"alert"` // "selected" or "none"
+ ColorMode string `json:"colormode"` // HS or XY mode for choosing color
+ Reachable bool `json:"reachable"`
+ } `json:"state"`
+ Type string `json:"type"`
+ Name string `json:"name"`
+ ModelID string `json:"modelid"`
+ ManufacturerName string `json:"manufacturername"`
+ UniqueID string `json:"uniqueid"`
+ SWVersion string `json:"swversion"`
+ Index int // Set by index of light array response
+ Bridge *Bridge // Set by the bridge when the light is found
}
// LightState used in Light.SetState to amend light attributes.
type LightState struct {
- On bool `json:"on"`
- Bri uint8 `json:"bri,omitempty"`
- Hue uint16 `json:"hue,omitempty"`
- Sat uint8 `json:"sat,omitempty"`
- XY *[2]float32 `json:"xy,omitempty"`
- CT uint16 `json:"ct,omitempty"`
- Effect string `json:"effect,omitempty"`
- Alert string `json:"alert,omitempty"`
- TransitionTime string `json:"transitiontime,omitempty"`
- SaturationIncrement int16 `json:"sat_inc,omitempty"`
- HueIncrement int32 `json:"hue_inc,omitempty"`
- BrightnessIncrement int16 `json:"bri_inc,omitempty"`
- CTIncrement int32 `json:"ct_inc,omitempty"`
- XYIncrement *[2]float32 `json:"xy_inc,omitempty"`
- Name string `json:"name,omitempty"`
+ On bool `json:"on"`
+ Bri uint8 `json:"bri,omitempty"`
+ Hue uint16 `json:"hue,omitempty"`
+ Sat uint8 `json:"sat,omitempty"`
+ XY *[2]float32 `json:"xy,omitempty"`
+ CT uint16 `json:"ct,omitempty"`
+ Effect string `json:"effect,omitempty"`
+ Alert string `json:"alert,omitempty"`
+ TransitionTime string `json:"transitiontime,omitempty"`
+ SaturationIncrement int16 `json:"sat_inc,omitempty"`
+ HueIncrement int32 `json:"hue_inc,omitempty"`
+ BrightnessIncrement int16 `json:"bri_inc,omitempty"`
+ CTIncrement int32 `json:"ct_inc,omitempty"`
+ XYIncrement *[2]float32 `json:"xy_inc,omitempty"`
+ Name string `json:"name,omitempty"`
}
// Light.SetName assigns a new name in the light's
// attributes as recognized by the bridge.
func (light *Light) SetName(name string) error {
- uri := fmt.Sprintf("/api/%s/lights/%d", light.Bridge.Username, light.Index)
- body := make(map[string]string)
- body["name"] = name
- _, _, err := light.Bridge.Put(uri, body)
- if err != nil {
- return err
- }
- return nil
+ uri := fmt.Sprintf("/api/%s/lights/%d", light.Bridge.Username, light.Index)
+ body := make(map[string]string)
+ body["name"] = name
+ _, _, err := light.Bridge.Put(uri, body)
+ if err != nil {
+ return err
+ }
+ return nil
}
// Light.Off turns the light source off
func (light *Light) Off() error {
- return light.SetState(LightState{On: false})
+ return light.SetState(LightState{On: false})
}
// Light.Off turns the light source on
func (light *Light) On() error {
- return light.SetState(LightState{On: true})
+ return light.SetState(LightState{On: true})
}
// Light.Toggle switches the light source on and off
func (light *Light) Toggle() error {
- if light.State.On {
- return light.Off()
- } else {
- return light.On()
- }
- return nil
+ if light.State.On {
+ return light.Off()
+ } else {
+ return light.On()
+ }
+ return nil
}
// Light.Delete removes the light from the
// list of lights available on the bridge.
func (light *Light) Delete() error {
- uri := fmt.Sprintf("/api/%s/lights/%d", light.Bridge.Username, light.Index)
- err := light.Bridge.Delete(uri)
- if err != nil {
- return err
- }
- return nil
+ uri := fmt.Sprintf("/api/%s/lights/%d", light.Bridge.Username, light.Index)
+ err := light.Bridge.Delete(uri)
+ if err != nil {
+ return err
+ }
+ return nil
}
// Light.Blink increases and decrease the brightness
@@ -107,133 +107,132 @@ func (light *Light) Delete() error {
// light back to its off or on state afterwards.
// Note: time will vary based on connection speed and algorithm speed.
func (light *Light) Blink(seconds int) error {
- originalPosition := light.State.On
- originalBrightness := light.State.Bri
- blinkMax := 75 // Percent brightness
- blinkMin := 25 // Percent brightness
+ originalPosition := light.State.On
+ originalBrightness := light.State.Bri
+ blinkMax := 75 // Percent brightness
+ blinkMin := 25 // Percent brightness
- // Start with near maximum brightness and toggle between that and
- // a lesser brightness to create a blinking effect.
- for i := 0; i <= seconds*2; i++ {
- if i == 0 {
- err := light.SetBrightness(blinkMax)
- if err != nil {
- return err
- }
- } else if i % 2 == 0 {
- err := light.SetBrightness(blinkMax)
- if err != nil {
- return err
- }
- } else {
- err := light.SetBrightness(blinkMin)
- if err != nil {
- return err
- }
- }
- time.Sleep(time.Second/2)
- }
+ // Start with near maximum brightness and toggle between that and
+ // a lesser brightness to create a blinking effect.
+ for i := 0; i <= seconds*2; i++ {
+ if i == 0 {
+ err := light.SetBrightness(blinkMax)
+ if err != nil {
+ return err
+ }
+ } else if i%2 == 0 {
+ err := light.SetBrightness(blinkMax)
+ if err != nil {
+ return err
+ }
+ } else {
+ err := light.SetBrightness(blinkMin)
+ if err != nil {
+ return err
+ }
+ }
+ time.Sleep(time.Second / 2)
+ }
- // Return the light to its original on or off state and brightness
- if light.State.Bri != originalBrightness || light.State.On != originalPosition {
- light.SetState(LightState{On: originalPosition, Bri: originalBrightness})
- }
- return nil
+ // Return the light to its original on or off state and brightness
+ if light.State.Bri != originalBrightness || light.State.On != originalPosition {
+ light.SetState(LightState{On: originalPosition, Bri: originalBrightness})
+ }
+ return nil
}
// Light.ColorLoop sets the light state to 'colorloop' if `active`
// is true or it sets the light state to "none" if `activate` is false.
func (light *Light) ColorLoop(activate bool) error {
- var state = "none"
- if activate {
- state = "colorloop"
- }
- return light.SetState(LightState{On: true, Effect: state})
+ var state = "none"
+ if activate {
+ state = "colorloop"
+ }
+ return light.SetState(LightState{On: true, Effect: state})
}
// XY positions on the HSL color spectrum used in `Light.SetColor`
// https://en.wikipedia.org/wiki/HSL_and_HSV
var (
- RED = &[2]float32{0.6915, 0.3083}
- YELLOW = &[2]float32{0.4023, 0.4725}
- ORANGE = &[2]float32{0.4693, 0.4007}
- GREEN = &[2]float32{0.1700, 0.7000}
- CYAN = &[2]float32{0.1610, 0.3549}
- BLUE = &[2]float32{0.1530, 0.0480}
- PURPLE = &[2]float32{0.2363, 0.1154}
- PINK = &[2]float32{0.3645, 0.1500}
- WHITE = &[2]float32{0.3227, 0.3290}
+ RED = &[2]float32{0.6915, 0.3083}
+ YELLOW = &[2]float32{0.4023, 0.4725}
+ ORANGE = &[2]float32{0.4693, 0.4007}
+ GREEN = &[2]float32{0.1700, 0.7000}
+ CYAN = &[2]float32{0.1610, 0.3549}
+ BLUE = &[2]float32{0.1530, 0.0480}
+ PURPLE = &[2]float32{0.2363, 0.1154}
+ PINK = &[2]float32{0.3645, 0.1500}
+ WHITE = &[2]float32{0.3227, 0.3290}
)
// Light.SetColor requires a selection from the above light
// color variable section and sets the light to that XY HSL color
func (light *Light) SetColor(color *[2]float32) error {
- lightState := LightState{On: true, XY: color}
- err := light.SetState(lightState)
- if err != nil {
- return err
- }
- return nil
+ lightState := LightState{On: true, XY: color}
+ err := light.SetState(lightState)
+ if err != nil {
+ return err
+ }
+ return nil
}
// Light.Dim lowers the brightness by a percent.
// Note the required value is an integer, for example "20" is converted to 20%.
func (light *Light) Dim(percent int) error {
- if percent > 0 && percent <= 100 {
- originalBri := light.State.Bri
- decreaseBri := float32(originalBri)*float32((float32(percent)/100.0))
- newBri := uint8(originalBri-uint8(decreaseBri))
- if newBri < 0 {
- newBri = 0
- log.Println("Light.Dim state set under 0%, setting brightness to 0. ")
- }
- lightState := LightState{On: true, Bri: newBri}
- err := light.SetState(lightState)
- if err != nil {
- return err
- }
- return nil
- } else {
- return errors.New("Light.Dim percentage given is not between 1 and 100. ")
- }
+ if percent > 0 && percent <= 100 {
+ originalBri := light.State.Bri
+ decreaseBri := float32(originalBri) * float32((float32(percent) / 100.0))
+ newBri := uint8(originalBri - uint8(decreaseBri))
+ if newBri < 0 {
+ newBri = 0
+ log.Println("Light.Dim state set under 0%, setting brightness to 0. ")
+ }
+ lightState := LightState{On: true, Bri: newBri}
+ err := light.SetState(lightState)
+ if err != nil {
+ return err
+ }
+ return nil
+ } else {
+ return errors.New("Light.Dim percentage given is not between 1 and 100. ")
+ }
}
// Light.SetBrightness sets the brightness to a percentage of the maximum
// maximum brightness as an integer (`LightStruct.Bri between 1 and 254 inclusive`)
func (light *Light) SetBrightness(percent int) error {
- if percent > 0 && percent <= 100 {
- brightness := uint8(float32(percent)*2.54) // 100=254x --> 2.54
- lightState := LightState{On: true, Bri: brightness}
- err := light.SetState(lightState)
- if err != nil {
- return err
- }
- return nil
- } else {
- return errors.New("Light.SetBrightness percentage is not between 1 and 100. ")
- }
+ if percent > 0 && percent <= 100 {
+ brightness := uint8(float32(percent) * 2.54) // 100=254x --> 2.54
+ lightState := LightState{On: true, Bri: brightness}
+ err := light.SetState(lightState)
+ if err != nil {
+ return err
+ }
+ return nil
+ } else {
+ return errors.New("Light.SetBrightness percentage is not between 1 and 100. ")
+ }
}
-
// Light.Brighten will increase LightStruct.Bri by a given percent (integer)
func (light *Light) Brighten(percent int) error {
- if percent > 0 && percent <= 100 {
- originalBri := light.State.Bri
- increaseBri := float32(originalBri)*float32((float32(percent)/100.0))
- newBri := uint8(originalBri+uint8(increaseBri))
- if newBri > 254 { // LightState.Bri must be between 1 and 254 inclusive
- newBri = 254
- log.Println("Light.Brighten state set over 100%, setting brightness to 100%. ")
- }
- lightState := LightState{On: true, Bri: newBri}
- err := light.SetState(lightState)
- if err != nil {
- return err
- }
- return nil
- } else {
- return errors.New("Light.Brighten percentage is not between 1 and 100. ")
- }
+ if percent > 0 && percent <= 100 {
+ originalBri := light.State.Bri
+ increaseBri := float32(originalBri) * float32((float32(percent) / 100.0))
+ newBri := uint8(originalBri + uint8(increaseBri))
+ if newBri > 254 { // LightState.Bri must be between 1 and 254 inclusive
+ newBri = 254
+ log.Println("Light.Brighten state set over 100%, setting brightness to 100%. ")
+ }
+ lightState := LightState{On: true, Bri: newBri}
+ err := light.SetState(lightState)
+ if err != nil {
+ return err
+ }
+ return nil
+ } else {
+ return errors.New("Light.Brighten percentage is not between 1 and 100. ")
+ }
}
// Light.SetState modifyies light attributes. See `LightState` struct for attributes.
@@ -242,16 +241,16 @@ func (light *Light) Brighten(percent int) error {
// Sat must be between 0 and 254 (inclusive)
// See http://www.developers.meethue.com/documentation/lights-api for more info
func (light *Light) SetState(newState LightState) error {
- uri := fmt.Sprintf("/api/%s/lights/%d/state", light.Bridge.Username, light.Index)
- _, _, err := light.Bridge.Put(uri, newState)
- if err != nil {
- return err
- }
+ uri := fmt.Sprintf("/api/%s/lights/%d/state", light.Bridge.Username, light.Index)
+ _, _, err := light.Bridge.Put(uri, newState)
+ if err != nil {
+ return err
+ }
- // Get the new light state and update the current Light struct
- *light, err = light.Bridge.GetLightByIndex(light.Index)
- if err != nil {
- return err
- }
- return nil
+ // Get the new light state and update the current Light struct
+ *light, err = light.Bridge.GetLightByIndex(light.Index)
+ if err != nil {
+ return err
+ }
+ return nil
}
diff --git a/light_test.go b/light_test.go
index 9e944c1..51f761f 100644
--- a/light_test.go
+++ b/light_test.go
@@ -3,57 +3,57 @@
* GoHue library for Philips Hue
* Copyright (C) 2016 Collin Guarino (Collinux) collin.guarino@gmail.com
* License: GPL version 2 or higher http://www.gnu.org/licenses/gpl.html
-*/
+ */
package hue
import (
- "testing"
- //"fmt"
- "time"
+ "testing"
+ //"fmt"
+ "time"
)
func TestSetLightState(t *testing.T) {
- bridge, _ := NewBridge("192.168.1.128")
- bridge.Login("427de8bd6d49f149c8398e4fc08f")
- nameTest, _ := bridge.GetLightByName("Desk Light") // Also tests GetAllLights
- _ = nameTest
- selectedLight, _ := bridge.GetLightByIndex(7)
-
- selectedLight.On()
- selectedLight.SetBrightness(100)
- time.Sleep(time.Second)
- selectedLight.Off()
- time.Sleep(time.Second)
- selectedLight.Toggle()
- time.Sleep(time.Second)
-
- selectedLight.ColorLoop(false)
-
- selectedLight.SetName(selectedLight.Name)
-
- selectedLight.Blink(3)
-
- selectedLight.Dim(20)
- selectedLight.Brighten(20)
-
- // selectedLight.SetColor(RED)
- // time.Sleep(time.Second)
- // selectedLight.SetColor(YELLOW)
- // time.Sleep(time.Second)
- // selectedLight.SetColor(ORANGE)
- // time.Sleep(time.Second)
- // selectedLight.SetColor(GREEN)
- // time.Sleep(time.Second)
- // selectedLight.SetColor(CYAN)
- // time.Sleep(time.Second)
- // selectedLight.SetColor(BLUE)
- // time.Sleep(time.Second)
- // selectedLight.SetColor(PURPLE)
- // time.Sleep(time.Second)
- // selectedLight.SetColor(PINK)
- // time.Sleep(time.Second)
- // selectedLight.SetColor(WHITE)
-
- // _ := selectedLight.Delete()
+ bridge, _ := NewBridge("192.168.1.128")
+ bridge.Login("427de8bd6d49f149c8398e4fc08f")
+ nameTest, _ := bridge.GetLightByName("Desk Light") // Also tests GetAllLights
+ _ = nameTest
+ selectedLight, _ := bridge.GetLightByIndex(7)
+
+ selectedLight.On()
+ selectedLight.SetBrightness(100)
+ time.Sleep(time.Second)
+ selectedLight.Off()
+ time.Sleep(time.Second)
+ selectedLight.Toggle()
+ time.Sleep(time.Second)
+
+ selectedLight.ColorLoop(false)
+
+ selectedLight.SetName(selectedLight.Name)
+
+ selectedLight.Blink(3)
+
+ selectedLight.Dim(20)
+ selectedLight.Brighten(20)
+
+ // selectedLight.SetColor(RED)
+ // time.Sleep(time.Second)
+ // selectedLight.SetColor(YELLOW)
+ // time.Sleep(time.Second)
+ // selectedLight.SetColor(ORANGE)
+ // time.Sleep(time.Second)
+ // selectedLight.SetColor(GREEN)
+ // time.Sleep(time.Second)
+ // selectedLight.SetColor(CYAN)
+ // time.Sleep(time.Second)
+ // selectedLight.SetColor(BLUE)
+ // time.Sleep(time.Second)
+ // selectedLight.SetColor(PURPLE)
+ // time.Sleep(time.Second)
+ // selectedLight.SetColor(PINK)
+ // time.Sleep(time.Second)
+ // selectedLight.SetColor(WHITE)
+
+ // _ := selectedLight.Delete()
}
diff --git a/scene.go b/scene.go
index 8c55d23..687ca1c 100644
--- a/scene.go
+++ b/scene.go
@@ -3,82 +3,82 @@
* GoHue library for Philips Hue
* Copyright (C) 2016 Collin Guarino (Collinux) collin.guarino@gmail.com
* License: GPL version 2 or higher http://www.gnu.org/licenses/gpl.html
-*/
+ */
// http://www.developers.meethue.com/documentation/scenes-api
package hue
import (
- "fmt"
- "encoding/json"
+ "encoding/json"
+ "fmt"
)
// Scene struct defines attributes for Scene items
type Scene struct {
- Appdata *struct {
- Data string `json:"data,omitempty"`
- Version int `json:"version,omitempty"`
- } `json:"appdata,omitempty"`
- Lastupdated string `json:"lastupdated,omitempty"`
- Lights []string `json:"lights,omitempty"`
- Locked bool `json:"locked,omitempty"`
- Name string `json:"name,omitempty"`
- Owner string `json:"owner,omitempty"`
- Picture string `json:"picture,omitempty"`
- Recycle bool `json:"recycle,omitempty"`
- Version int `json:"version,omitempty"`
- ID string `json:",omitempty"`
+ Appdata *struct {
+ Data string `json:"data,omitempty"`
+ Version int `json:"version,omitempty"`
+ } `json:"appdata,omitempty"`
+ Lastupdated string `json:"lastupdated,omitempty"`
+ Lights []string `json:"lights,omitempty"`
+ Locked bool `json:"locked,omitempty"`
+ Name string `json:"name,omitempty"`
+ Owner string `json:"owner,omitempty"`
+ Picture string `json:"picture,omitempty"`
+ Recycle bool `json:"recycle,omitempty"`
+ Version int `json:"version,omitempty"`
+ ID string `json:",omitempty"`
}
// Bridge.GetScenes gets the attributes for all scenes.
func (bridge *Bridge) GetAllScenes() ([]Scene, error) {
- uri := fmt.Sprintf("/api/%s/scenes", bridge.Username)
- body, _, err := bridge.Get(uri)
- if err != nil {
- return []Scene{}, err
- }
+ uri := fmt.Sprintf("/api/%s/scenes", bridge.Username)
+ body, _, err := bridge.Get(uri)
+ if err != nil {
+ return []Scene{}, err
+ }
- scenes := map[string]Scene{}
- err = json.Unmarshal(body, &scenes)
- if err != nil {
- return []Scene{}, err
- }
- scenesList := []Scene{}
- for key, value := range scenes {
- scene := Scene{}
- scene = value
- scene.ID = key
- scenesList = append(scenesList, scene)
- }
- return scenesList, nil
+ scenes := map[string]Scene{}
+ err = json.Unmarshal(body, &scenes)
+ if err != nil {
+ return []Scene{}, err
+ }
+ scenesList := []Scene{}
+ for key, value := range scenes {
+ scene := Scene{}
+ scene = value
+ scene.ID = key
+ scenesList = append(scenesList, scene)
+ }
+ return scenesList, nil
}
// Bridge.GetScene gets the attributes for an individual scene.
// This is used to optimize time when updating the state of the scene.
// Note: The ID is not an index, it's a unique key generated for each scene.
func (bridge *Bridge) GetScene(id string) (Scene, error) {
- uri := fmt.Sprintf("/api/%s/scenes/%s", bridge.Username, id)
- body, _, err := bridge.Get(uri)
- if err != nil {
- return Scene{}, err
- }
+ uri := fmt.Sprintf("/api/%s/scenes/%s", bridge.Username, id)
+ body, _, err := bridge.Get(uri)
+ if err != nil {
+ return Scene{}, err
+ }
- scene := Scene{}
- err = json.Unmarshal(body, &scene)
- if err != nil {
- return Scene{}, err
- }
- return scene, nil
+ scene := Scene{}
+ err = json.Unmarshal(body, &scene)
+ if err != nil {
+ return Scene{}, err
+ }
+ return scene, nil
}
// Bridge.CreateScene posts a new scene configuration to the bridge.
func (bridge *Bridge) CreateScene(scene Scene) error {
- uri := fmt.Sprintf("/api/%s/scenes/", bridge.Username)
- _, _, err := bridge.Post(uri, scene)
- if err != nil {
- return err
- }
- return nil
+ uri := fmt.Sprintf("/api/%s/scenes/", bridge.Username)
+ _, _, err := bridge.Post(uri, scene)
+ if err != nil {
+ return err
+ }
+ return nil
}
// Bridge.ModifySceneState amends light states for lights
diff --git a/scene_test.go b/scene_test.go
index 945825b..1eff2ac 100644
--- a/scene_test.go
+++ b/scene_test.go
@@ -3,31 +3,31 @@
* GoHue library for Philips Hue
* Copyright (C) 2016 Collin Guarino (Collinux) collin.guarino@gmail.com
* License: GPL version 2 or higher http://www.gnu.org/licenses/gpl.html
-*/
+ */
package hue
import (
- "testing"
- //"fmt"
+ "testing"
+ //"fmt"
)
func TestGetAllScenes(t *testing.T) {
- bridge, _ := NewBridge("192.168.1.128")
- bridge.Login("427de8bd6d49f149c8398e4fc08f")
- scenes, _ := bridge.GetAllScenes()
- // for scene := range scenes {
- // fmt.Println("SCENE: ", scenes[scene])
- // }
+ bridge, _ := NewBridge("192.168.1.128")
+ bridge.Login("427de8bd6d49f149c8398e4fc08f")
+ scenes, _ := bridge.GetAllScenes()
+ // for scene := range scenes {
+ // fmt.Println("SCENE: ", scenes[scene])
+ // }
- individual, _ := bridge.GetScene(scenes[0].ID)
- _ = individual
- //fmt.Println("Individual scene: ", individual)
+ individual, _ := bridge.GetScene(scenes[0].ID)
+ _ = individual
+ //fmt.Println("Individual scene: ", individual)
}
func TestCreateScene(t *testing.T) {
- bridge, _ := NewBridge("192.168.1.128")
- bridge.Login("427de8bd6d49f149c8398e4fc08f")
- scene := Scene{Lights: []string{"1", "2"}}
- _ = bridge.CreateScene(scene)
+ bridge, _ := NewBridge("192.168.1.128")
+ bridge.Login("427de8bd6d49f149c8398e4fc08f")
+ scene := Scene{Lights: []string{"1", "2"}}
+ _ = bridge.CreateScene(scene)
}
diff --git a/schedule.go b/schedule.go
index a251d3c..50755ef 100644
--- a/schedule.go
+++ b/schedule.go
@@ -3,88 +3,88 @@
* GoHue library for Philips Hue
* Copyright (C) 2016 Collin Guarino (Collinux) collin.guarino@gmail.com
* License: GPL version 2 or higher http://www.gnu.org/licenses/gpl.html
-*/
+ */
// http://www.developers.meethue.com/documentation/schedules-api-0
package hue
import (
- "fmt"
- "encoding/json"
+ "encoding/json"
+ "fmt"
)
// Schedule struct defines attributes of Alarms and Timers
type Schedule struct {
- Name string `json:"name"`
- Description string `json:"description"`
- Command struct {
- Address string `json:"address"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ Command struct {
+ Address string `json:"address"`
Body struct {
- Scene string `json:"scene"`
+ Scene string `json:"scene"`
} `json:"body"`
- Method string `json:"method"`
+ Method string `json:"method"`
} `json:"command"`
- Localtime string `json:"localtime"`
- Time string `json:"time"`
- Created string `json:"created"`
- Status string `json:"status"`
- Autodelete bool `json:"autodelete"`
- ID string
+ Localtime string `json:"localtime"`
+ Time string `json:"time"`
+ Created string `json:"created"`
+ Status string `json:"status"`
+ Autodelete bool `json:"autodelete"`
+ ID string
}
// Bridge.GetAllSchedules gets Alarms and Timers in a Schedule struct.
func (bridge *Bridge) GetAllSchedules() ([]Schedule, error) {
- uri := fmt.Sprintf("/api/%s/schedules", bridge.Username)
- body, _, err := bridge.Get(uri)
- if err != nil {
- return []Schedule{}, err
- }
+ uri := fmt.Sprintf("/api/%s/schedules", bridge.Username)
+ body, _, err := bridge.Get(uri)
+ if err != nil {
+ return []Schedule{}, err
+ }
- // Each index key is the topmost element of the json array.
- // Unmarshal the array, loop through each index key, and add it to the list
- schedules := map[string]Schedule{}
- err = json.Unmarshal(body, &schedules)
+ // Each index key is the topmost element of the json array.
+ // Unmarshal the array, loop through each index key, and add it to the list
+ schedules := map[string]Schedule{}
+ err = json.Unmarshal(body, &schedules)
if err != nil {
return []Schedule{}, err
}
- scheduleList := []Schedule{}
- for key, value := range schedules {
- schedule := Schedule{}
- schedule = value
- schedule.ID = key
- scheduleList = append(scheduleList, schedule)
- }
- return scheduleList, nil
+ scheduleList := []Schedule{}
+ for key, value := range schedules {
+ schedule := Schedule{}
+ schedule = value
+ schedule.ID = key
+ scheduleList = append(scheduleList, schedule)
+ }
+ return scheduleList, nil
}
// Bridge.GetSchedule gets the attributes for an individual schedule.
// This is used to optimize time when updating the state of a schedule item.
// Note: The ID is not an index, it's a unique key generated for each schedule.
func (bridge *Bridge) GetSchedule(id string) (Schedule, error) {
- uri := fmt.Sprintf("/api/%s/schedules/%s", bridge.Username, id)
- body, _, err := bridge.Get(uri)
- if err != nil {
- return Schedule{}, err
- }
+ uri := fmt.Sprintf("/api/%s/schedules/%s", bridge.Username, id)
+ body, _, err := bridge.Get(uri)
+ if err != nil {
+ return Schedule{}, err
+ }
- schedule := Schedule{}
- err = json.Unmarshal(body, &schedule)
+ schedule := Schedule{}
+ err = json.Unmarshal(body, &schedule)
if err != nil {
return Schedule{}, err
}
- return schedule, nil
+ return schedule, nil
}
// TODO: NOT TESTED, NOT FULLY IMPLEMENTED
func (bridge *Bridge) CreateSchedule(schedule Schedule) error {
- uri := fmt.Sprintf("/api/%s/schedules", bridge.Username)
- body, _, err := bridge.Post(uri, schedule)
- if err != nil {
- return err
- }
+ uri := fmt.Sprintf("/api/%s/schedules", bridge.Username)
+ body, _, err := bridge.Post(uri, schedule)
+ if err != nil {
+ return err
+ }
- fmt.Println("CREATE SCHEDULE BODY: ", string(body))
- return nil
+ fmt.Println("CREATE SCHEDULE BODY: ", string(body))
+ return nil
}
// func (schedule *Schedule) Disable() {
diff --git a/schedule_test.go b/schedule_test.go
index 3a4cc59..0039c6b 100644
--- a/schedule_test.go
+++ b/schedule_test.go
@@ -3,24 +3,24 @@
* GoHue library for Philips Hue
* Copyright (C) 2016 Collin Guarino (Collinux) collin.guarino@gmail.com
* License: GPL version 2 or higher http://www.gnu.org/licenses/gpl.html
-*/
+ */
package hue
import (
- "testing"
+ "testing"
)
func TestGetAllSchedules(t *testing.T) {
- bridge, _ := NewBridge("192.168.1.128")
- bridge.Login("427de8bd6d49f149c8398e4fc08f")
- _, _ = bridge.GetAllSchedules()
+ bridge, _ := NewBridge("192.168.1.128")
+ bridge.Login("427de8bd6d49f149c8398e4fc08f")
+ _, _ = bridge.GetAllSchedules()
}
func TestGetSchedule(t *testing.T) {
- bridge, _ := NewBridge("192.168.1.128")
- bridge.Login("427de8bd6d49f149c8398e4fc08f")
- _, _ = bridge.GetSchedule("4673980164949558")
+ bridge, _ := NewBridge("192.168.1.128")
+ bridge.Login("427de8bd6d49f149c8398e4fc08f")
+ _, _ = bridge.GetSchedule("4673980164949558")
}
// func TestCreateSchedule(t *testing.T) {