hue

package module
v0.0.0-...-5684411 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 9, 2019 License: GPL-2.0 Imports: 13 Imported by: 11

README

GoHue

Package hue interfaces Philips Hue devices to control lights, scenes, schedules, and groups.

GoDoc Go Report Card Build Status

See GoHue in action!

Have a cool project you made using GoHue? Add yours here in a pull request!

HueBeat by Mobilpadde - Light up a room in sync with your heartbeat.

BitHue by ytcracker - Light color according to profit gain/loss in bitcoin price

Installation

go get github.com/collinux/gohue

Usage

package main

import (
    "github.com/collinux/gohue"
)

func main() {
    // It is recommended that you save the username from bridge.CreateUser
    // so you don't have to press the link button every time and re-auth.
    // When CreateUser is called it will print the generated user token.
    bridgesOnNetwork, _ := hue.FindBridges()
    bridge := bridgesOnNetwork[0]
    username, _ := bridge.CreateUser("someusernamehere")
    bridge.Login(username)

    lights, _ := bridge.GetAllLights()
    for _, light := range lights {
        light.SetBrightness(100)
        light.ColorLoop(true)
    }

    nightstandLight, _ := bridge.GetLightByName("Nightstand")
    nightstandLight.Blink(5)
    nightstandLight.SetName("Bedroom Lamp")

    lights[0].SetColor(hue.RED)
    lights[1].SetColor(hue.BLUE)
    lights[2].SetColor(hue.GREEN)

    for _, light := range lights {
        light.Off()
    }
}

Testing & Validation

  1. Set the environment variable "HUE_USER_TOKEN" (example: export HUE_USER_TOKEN="sby7xirR87dUpnfzp1yGRVBeP0Zoxo3LH1krNxSi")
  2. Run go test *_test.go
  3. Wait for all covered tests to be executed (Estimated 15 seconds - may vary depending on network latency).

Features

Lights
  • Get all lights
  • Get light by name
  • Get light by index on bridge
  • Get lights attributes and state
  • Set lights attributes (rename)
  • Set light state (color, effects, brightness, etc)
  • Delete light
  • Turn On, Off, Toggle
  • Blink
  • Colorloop On/Off
Bridge
  • Create user
  • Delete user
  • Get configuration
  • Modify configuration
  • Get full state (datastore)
  • Search for bridges
  • Search for new lights
  • Get all timezones
Schedules
  • Get all schedules
  • Get schedule by ID
  • Get schedule attributes
  • Create schedules
  • Set schedule attributes
  • Delete schedule
Scenes
  • Get all scenes
  • Get scene by ID
  • Create scene
  • Modify scene
  • Recall scene
  • Delete scene
Groups
  • Get all groups
  • Create group
  • Get group attributes
  • Set group attributes
  • Set group state
  • Delete Group
Sensors
  • Get all sensors
  • Create sensor
  • Find new sensors
  • Get new sensors
  • Get sensor
  • Update sensor
  • Delete sensor
  • Change sensor configuration
Rules
  • Get all rules
  • Get rule
  • Create rule
  • Update rule
  • Delete rule

API Documentation

This repository is featured on the Philips Hue® developer site and was not developed by "Philips Lighting Holding B.V"... for official Hue® documentation check out the Philips Hue® website. This codebase comes with no guaranetees. Use at your own risk.

License

GoHue - Third party golang library for Philips Hue® gateway interface. Copyright (C) 2016 Collinux GPL version 2 or higher http://www.gnu.org/licenses/gpl.html

Contributing

Pull requests happily accepted on GitHub

Documentation

Index

Constants

This section is empty.

Variables

View Source
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}
)

XY positions on the HSL color spectrum used in `Light.SetColor` https://en.wikipedia.org/wiki/HSL_and_HSV

Functions

func HandleResponse

func HandleResponse(resp *http.Response) ([]byte, io.Reader, error)

HandleResponse manages the http.Response content from a bridge Get/Put/Post/Delete by checking it for errors and invalid return types.

Types

type Action

type Action struct {
	Alert     string    `json:"alert,omitempty"`
	Bri       int       `json:"bri,omitempty"`
	Colormode string    `json:"colormode,omitempty"`
	Ct        int       `json:"ct,omitempty"`
	Effect    string    `json:"effect,omitempty"`
	Hue       *int      `json:"hue,omitempty"`
	On        *bool     `json:"on,omitempty"`
	Sat       *int      `json:"sat,omitempty"`
	XY        []float64 `json:"xy,omitempty"`
	Scene     string    `json:"scene,omitempty"`
}

Action struct defines the state of a group

type Bridge

type Bridge struct {
	IPAddress string `json:"internalipaddress"`
	Username  string // Token from Bridge.CreateUser
	Info      BridgeInfo
}

Bridge struct defines hardware that is used to communicate with the lights.

func FindBridges

func FindBridges() ([]Bridge, error)

FindBridges will visit www.meethue.com/api/nupnp to see a list of bridges on the local network.

func NewBridge

func NewBridge(ip string) (*Bridge, error)

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 lights, scenes, groups, etc.

func (*Bridge) CreateScene

func (bridge *Bridge) CreateScene(scene Scene) error

CreateScene posts a new scene configuration to the bridge.

func (*Bridge) CreateSchedule

func (bridge *Bridge) CreateSchedule(schedule Schedule) error

CreateSchedule TODO: NOT TESTED, NOT FULLY IMPLEMENTED

func (*Bridge) CreateUser

func (bridge *Bridge) CreateUser(deviceType string) (string, error)

CreateUser adds a new user token on the whitelist. and returns this value as a string.

The 'Bridge.Login` function **must be run** with the user token as an argument. No functions can be called until a valid user token is assigned as the bridge's `Username` value.

You cannot set a plaintext username, it must be a generated user token. This was done by Philips Hue for security purposes.

func (*Bridge) Delete

func (bridge *Bridge) Delete(path string) error

Delete sends an http DELETE to the bridge

func (*Bridge) DeleteUser

func (bridge *Bridge) DeleteUser(username string) error

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) FindNewLights

func (bridge *Bridge) FindNewLights() error

FindNewLights makes the bridge search the zigbee spectrum for lights in the area and will add them to the list of lights available. If successful these new lights can be used by `Bridge.GetAllLights`

Notes from Philips Hue API documentation: The bridge will search for 1 minute and will add a maximum of 15 new lights. To add further lights, the command needs to be sent again after the search has completed. If a search is already active, it will be aborted and a new search will start. http://www.developers.meethue.com/documentation/lights-api#13_search_for_new_lights

func (*Bridge) Get

func (bridge *Bridge) Get(path string) ([]byte, io.Reader, error)

Get sends an http GET to the bridge

func (*Bridge) GetAllLights

func (bridge *Bridge) GetAllLights() ([]Light, error)

GetAllLights retrieves the state of all lights that the bridge is aware of.

func (*Bridge) GetAllScenes

func (bridge *Bridge) GetAllScenes() ([]Scene, error)

GetAllScenes gets the attributes for all scenes.

func (*Bridge) GetAllSchedules

func (bridge *Bridge) GetAllSchedules() ([]Schedule, error)

GetAllSchedules gets Alarms and Timers in a Schedule struct.

func (*Bridge) GetAllSensors

func (bridge *Bridge) GetAllSensors() ([]Sensor, error)

GetAllSensors retrieves the state of all sensors that the bridge is aware of.

func (*Bridge) GetGroups

func (bridge *Bridge) GetGroups() ([]Group, error)

GetGroups gets the attributes for each group of lights. TODO: NOT TESTED, NOT FULLY IMPLEMENTED

func (*Bridge) GetInfo

func (bridge *Bridge) GetInfo() error

GetInfo 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) GetLightByIndex

func (bridge *Bridge) GetLightByIndex(index int) (Light, error)

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) GetLightByName

func (bridge *Bridge) GetLightByName(name string) (Light, error)

GetLightByName returns a light struct containing data on a given name.

func (*Bridge) GetScene

func (bridge *Bridge) GetScene(id string) (Scene, error)

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) GetSceneByName

func (bridge *Bridge) GetSceneByName(name string) (Scene, error)

GetSceneByName gets the attributes for the scene identified by a name

func (*Bridge) GetSchedule

func (bridge *Bridge) GetSchedule(id string) (Schedule, error)

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) GetSensorByIndex

func (bridge *Bridge) GetSensorByIndex(index int) (Sensor, error)

GetSensorByIndex returns a sensor struct containing data on a sensor given its index stored on the bridge.

func (*Bridge) Login

func (bridge *Bridge) Login(username string) error

Login verifies that the username token has bridge access and only assigns the bridge its Username value if verification is successful.

func (*Bridge) Post

func (bridge *Bridge) Post(path string, params interface{}) ([]byte, io.Reader, error)

Post sends an http POST to the bridge with a body formatted with parameters (in a generic interface). If `params` is nil then it will send an empty body with the post request.

func (*Bridge) Put

func (bridge *Bridge) Put(path string, params interface{}) ([]byte, io.Reader, error)

Put sends an http PUT to the bridge with a body formatted with parameters (in a generic interface)

func (*Bridge) RecallScene

func (bridge *Bridge) RecallScene(id string) error

RecallScene recalls a scene

func (*Bridge) RecallSceneByName

func (bridge *Bridge) RecallSceneByName(name string) error

RecallSceneByName recalls a scene

func (*Bridge) SetGroupState

func (bridge *Bridge) SetGroupState(group int, action *Action) error

SetGroupState sends an action to group

type BridgeInfo

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"`
}

BridgeInfo struct is the format for parsing xml from a bridge.

type Group

type Group struct {
	Action Action   `json:"action"`
	Lights []string `json:"lights"`
	Name   string   `json:"name"`
	Type   string   `json:"type"`
}

Group struct defines the attributes for a group of lights.

type 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        uint16     `json:"hue"`       // Hue value 1-65535
		Saturation uint8      `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
}

Light struct defines attributes of a light.

func (light *Light) Blink(seconds int) error

Blink increases and decrease the brightness 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 (*Light) Brighten

func (light *Light) Brighten(percent int) error

Brighten will increase LightStruct.Bri by a given percent (integer)

func (*Light) ColorLoop

func (light *Light) ColorLoop(activate bool) error

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) Delete

func (light *Light) Delete() error

Delete removes the light from the list of lights available on the bridge.

func (*Light) Dim

func (light *Light) Dim(percent int) error

Dim lowers the brightness by a percent. Note the required value is an integer, for example "20" is converted to 20%.

func (*Light) Off

func (light *Light) Off() error

Off turns the light source off

func (*Light) On

func (light *Light) On() error

On turns the light source on

func (*Light) SetBrightness

func (light *Light) SetBrightness(percent int) error

SetBrightness sets the brightness to a percentage of the maximum maximum brightness as an integer (`LightStruct.Bri between 1 and 254 inclusive`)

func (*Light) SetColor

func (light *Light) SetColor(color *[2]float32) error

SetColor requires a selection from the above light color variable section and sets the light to that XY HSL color

func (*Light) SetColorHS

func (light *Light) SetColorHS(color uint16) error

SetColorHS requires a selection from the above light color variable section and sets the light to the Hue value

func (*Light) SetColorXY

func (light *Light) SetColorXY(color *[2]float32)

SetColorXY requires a selection from the above light color variable section and sets the light to that XY HSL color aliased for clarity

func (*Light) SetName

func (light *Light) SetName(name string) error

SetName assigns a new name in the light's attributes as recognized by the bridge.

func (*Light) SetState

func (light *Light) SetState(newState LightState) error

SetState modifyies light attributes. See `LightState` struct for attributes. Brightness must be between 1 and 254 (inclusive) Hue must be between 0 and 65535 (inclusive) Sat must be between 0 and 254 (inclusive) See http://www.developers.meethue.com/documentation/lights-api for more info

func (*Light) Toggle

func (light *Light) Toggle() error

Toggle switches the light source on and off

type LightState

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"`
}

LightState used in Light.SetState to amend light attributes.

type Scene

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"`
}

Scene struct defines attributes for Scene items

type Schedule

type Schedule struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Command     struct {
		Address string `json:"address"`
		Body    struct {
			Scene string `json:"scene"`
		} `json:"body"`
		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
}

Schedule struct defines attributes of Alarms and Timers

type Sensor

type Sensor struct {
	State struct {
		Daylight    bool       `json:"daylight"`    // True if day & false if night
		LastUpdated UpdateTime `json:"lastupdated"` // Time of last update
		ButtonEvent uint16     `json:"buttonevent"` // ID of button event
	} `json:"state"`

	Config struct {
		On        bool  `json:"on"`        // Turns the sensor on/off. When off, state changes of the sensor are not reflected in the sensor resource.
		Reachable bool  `json:"reachable"` // Indicates whether communication with devices is possible
		Battery   uint8 `json:"battery"`   // The current battery state in percent, only for battery powered devices
	} `json:"config"`

	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 sensor array response
	Bridge           *Bridge // Set by the bridge when the sensor is found
}

Sensor struct defines attributes of a sensor.

func (*Sensor) Refresh

func (s *Sensor) Refresh() error

/ Refresh sensor attributes

type UpdateTime

type UpdateTime struct {
	*time.Time
}

special time type for unmarshal of lastupdated

func (*UpdateTime) UnmarshalJSON

func (u *UpdateTime) UnmarshalJSON(b []byte) error

implement Unmarshal interface required for "none" as lastupdated in unused sensor

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL