Documentation
¶
Overview ¶
Package govee provides a Go client for the Govee OpenAPI.
The Govee OpenAPI uses a capability-based model: each device reports the capabilities it supports (on/off, brightness, color, scenes, etc.) along with valid parameter ranges and options. All control commands go through a single endpoint using a {type, instance, value} triple.
Getting started ¶
client := govee.New("your-api-key")
devices, err := client.GetDevices(ctx)
err = client.TurnOn(ctx, devices[0].SKU, devices[0].DeviceID)
Scenes ¶
Static scenes are included in the device capabilities from GetDevices. Dynamic scenes (which can be numerous) must be fetched separately:
scenes, err := client.GetScenes(ctx, sku, deviceID) err = client.SetLightScene(ctx, sku, deviceID, scenes[0].Value)
Events ¶
To receive real-time device events (sensor readings, alerts), use EventClient:
ec := govee.NewEventClient("your-api-key", func(event govee.DeviceEvent) {
fmt.Printf("event from %s: %v\n", event.SKU, event.Capabilities)
})
err := ec.Connect(ctx)
defer ec.Close()
Index ¶
- Constants
- type APIError
- type Capability
- type CapabilityCommand
- type CapabilityState
- type Client
- func (c *Client) ControlDevice(ctx context.Context, sku, deviceID string, cmd CapabilityCommand) error
- func (c *Client) GetDIYScenes(ctx context.Context, sku, deviceID string) ([]DIYSceneOption, error)
- func (c *Client) GetDeviceState(ctx context.Context, sku, deviceID string) (*DeviceStateResponse, error)
- func (c *Client) GetDevices(ctx context.Context) ([]Device, error)
- func (c *Client) GetScenes(ctx context.Context, sku, deviceID string) ([]SceneOption, error)
- func (c *Client) SetBrightness(ctx context.Context, sku, deviceID string, percent int) error
- func (c *Client) SetColor(ctx context.Context, sku, deviceID string, r, g, b int) error
- func (c *Client) SetColorTemp(ctx context.Context, sku, deviceID string, kelvin int) error
- func (c *Client) SetDIYScene(ctx context.Context, sku, deviceID string, value int) error
- func (c *Client) SetLightScene(ctx context.Context, sku, deviceID string, value interface{}) error
- func (c *Client) SetMode(ctx context.Context, sku, deviceID, instance string, value int) error
- func (c *Client) SetMusicMode(ctx context.Context, sku, deviceID string, mode MusicModeValue) error
- func (c *Client) SetSegmentBrightness(ctx context.Context, sku, deviceID string, segments []int, brightness int) error
- func (c *Client) SetSegmentColor(ctx context.Context, sku, deviceID string, segments []int, rgb int) error
- func (c *Client) SetSnapshot(ctx context.Context, sku, deviceID string, value int) error
- func (c *Client) SetTemperature(ctx context.Context, sku, deviceID string, temp TemperatureValue) error
- func (c *Client) SetToggle(ctx context.Context, sku, deviceID, instance string, on bool) error
- func (c *Client) SetWorkMode(ctx context.Context, sku, deviceID string, mode WorkModeValue) error
- func (c *Client) TurnOff(ctx context.Context, sku, deviceID string) error
- func (c *Client) TurnOn(ctx context.Context, sku, deviceID string) error
- type DIYSceneOption
- type Device
- type DeviceEvent
- type DeviceStateResponse
- func (r *DeviceStateResponse) Brightness() (percent int, found bool)
- func (r *DeviceStateResponse) ColorRGB() (red, green, blue int, found bool)
- func (r *DeviceStateResponse) ColorTemp() (kelvin int, found bool)
- func (r *DeviceStateResponse) FindState(capType, instance string) *Capability
- func (r *DeviceStateResponse) IsOnline() bool
- func (r *DeviceStateResponse) PowerState() (on bool, found bool)
- type EnumOption
- type EnumParameters
- type EventCapability
- type EventClient
- type EventHandler
- type EventOption
- type LightSceneValue
- type MusicModeValue
- type Option
- type SceneOption
- type TemperatureValue
- type WorkModeValue
Examples ¶
Constants ¶
const ( DeviceLight = "devices.types.light" DeviceAirPurifier = "devices.types.air_purifier" DeviceThermometer = "devices.types.thermometer" DeviceSocket = "devices.types.socket" DeviceSensor = "devices.types.sensor" DeviceHeater = "devices.types.heater" DeviceHumidifier = "devices.types.humidifier" DeviceDehumidifier = "devices.types.dehumidifier" DeviceIceMaker = "devices.types.ice_maker" DeviceAromaDiffuser = "devices.types.aroma_diffuser" DeviceBox = "devices.types.box" )
Device type constants.
const ( CapabilityOnOff = "devices.capabilities.on_off" CapabilityToggle = "devices.capabilities.toggle" CapabilityRange = "devices.capabilities.range" CapabilityMode = "devices.capabilities.mode" CapabilityColorSetting = "devices.capabilities.color_setting" CapabilitySegmentColorSetting = "devices.capabilities.segment_color_setting" CapabilityMusicSetting = "devices.capabilities.music_setting" CapabilityDynamicScene = "devices.capabilities.dynamic_scene" CapabilityWorkMode = "devices.capabilities.work_mode" CapabilityTemperatureSetting = "devices.capabilities.temperature_setting" CapabilityOnline = "devices.capabilities.online" CapabilityProperty = "devices.capabilities.property" CapabilityEvent = "devices.capabilities.event" )
Capability type constants.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Capability ¶ added in v0.0.3
type Capability struct {
Type string `json:"type"`
Instance string `json:"instance"`
Parameters json.RawMessage `json:"parameters,omitempty"`
State *CapabilityState `json:"state,omitempty"`
AlarmType int `json:"alarmType,omitempty"`
EventState json.RawMessage `json:"eventState,omitempty"`
}
Capability represents a single device capability with its parameter schema and optional current state (populated by GetDeviceState).
type CapabilityCommand ¶ added in v0.0.3
type CapabilityCommand struct {
Type string `json:"type"`
Instance string `json:"instance"`
Value interface{} `json:"value"`
}
CapabilityCommand is a capability control command sent to a device via ControlDevice.
type CapabilityState ¶ added in v0.0.3
type CapabilityState struct {
Value json.RawMessage `json:"value"`
}
CapabilityState holds the current value of a capability, as returned by GetDeviceState.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a Govee API client. Create one with New().
func (*Client) ControlDevice ¶ added in v0.0.3
func (c *Client) ControlDevice(ctx context.Context, sku, deviceID string, cmd CapabilityCommand) error
ControlDevice sends a raw capability command to a device identified by (sku, deviceID). This is the generic form; prefer the typed helpers for common operations.
func (*Client) GetDIYScenes ¶ added in v0.0.3
GetDIYScenes returns the user-created DIY scenes available for a device. Activate a scene with SetDIYScene using the integer Value from each DIYSceneOption.
func (*Client) GetDeviceState ¶
func (c *Client) GetDeviceState(ctx context.Context, sku, deviceID string) (*DeviceStateResponse, error)
GetDeviceState queries the current state of a device. Each capability in the returned DeviceStateResponse has a State field containing its current value.
func (*Client) GetDevices ¶
GetDevices returns all devices associated with the API key along with their capabilities. Use the returned Device values to discover what each device supports and to build control commands.
Example ¶
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
govee "github.com/DTCurrie/govee-go"
)
func main() {
// Normally you would use govee.New("your-api-key").
// Here we use a test server so the example is self-contained.
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
devices := []govee.Device{
{
SKU: "H6008",
DeviceID: "AA:BB:CC:DD",
DeviceName: "Bedroom Light",
Type: govee.DeviceLight,
Capabilities: []govee.Capability{
{Type: govee.CapabilityOnOff, Instance: "powerSwitch"},
{Type: govee.CapabilityRange, Instance: "brightness"},
},
},
}
type envelope struct {
Code int `json:"code"`
Message string `json:"message"`
Data []govee.Device `json:"data"`
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(envelope{Code: 200, Message: "success", Data: devices})
}))
defer srv.Close()
client := govee.New("my-api-key", govee.WithBaseURL(srv.URL))
devices, err := client.GetDevices(context.Background())
if err != nil {
fmt.Println("error:", err)
return
}
for _, d := range devices {
fmt.Printf("%s (%s)\n", d.DeviceName, d.SKU)
}
}
Output: Bedroom Light (H6008)
func (*Client) GetScenes ¶ added in v0.0.3
GetScenes returns the dynamic light scenes available for a device. These scenes have compound LightSceneValue values (id + paramId) and are separate from the static scenes embedded in device capabilities returned by GetDevices.
func (*Client) SetBrightness ¶
SetBrightness sets the device brightness. percent must be in the range [1, 100].
Example ¶
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
govee "github.com/DTCurrie/govee-go"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
type envelope struct {
RequestID string `json:"requestId"`
Code int `json:"code"`
Msg string `json:"msg"`
Payload interface{} `json:"payload"`
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(envelope{Code: 200, Msg: "success", Payload: struct{}{}})
}))
defer srv.Close()
client := govee.New("my-api-key", govee.WithBaseURL(srv.URL))
err := client.SetBrightness(context.Background(), "H6008", "AA:BB:CC:DD", 80)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("brightness set")
}
Output: brightness set
func (*Client) SetColor ¶
SetColor sets the device color. Each of r, g, b must be in the range [0, 255].
func (*Client) SetColorTemp ¶
SetColorTemp sets the device color temperature in Kelvin. kelvin must be greater than 0.
func (*Client) SetDIYScene ¶ added in v0.0.3
SetDIYScene activates a user-created DIY scene. value is the scene ID obtained from GetDIYScenes.
func (*Client) SetLightScene ¶ added in v0.0.3
SetLightScene activates a built-in light scene. value should be a LightSceneValue obtained from GetScenes for devices with compound scene values, or a plain int for devices whose scene options use simple integer IDs.
Example ¶
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
govee "github.com/DTCurrie/govee-go"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
type envelope struct {
RequestID string `json:"requestId"`
Code int `json:"code"`
Msg string `json:"msg"`
Payload interface{} `json:"payload"`
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(envelope{Code: 200, Msg: "success", Payload: struct{}{}})
}))
defer srv.Close()
client := govee.New("my-api-key", govee.WithBaseURL(srv.URL))
// Obtain scene values from GetScenes, then activate with SetLightScene.
scene := govee.LightSceneValue{ID: 2, ParamID: 0}
err := client.SetLightScene(context.Background(), "H6008", "AA:BB:CC:DD", scene)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("scene activated")
}
Output: scene activated
func (*Client) SetMode ¶ added in v0.0.3
SetMode sets a mode-type capability. instance identifies which mode to set (e.g. "nightlightScene", "presetScene"). value is the mode ID.
func (*Client) SetMusicMode ¶ added in v0.0.3
SetMusicMode activates a music visualization mode.
func (*Client) SetSegmentBrightness ¶ added in v0.0.3
func (c *Client) SetSegmentBrightness(ctx context.Context, sku, deviceID string, segments []int, brightness int) error
SetSegmentBrightness sets the brightness of specific light strip segments. segments is a slice of zero-based segment indices. brightness must be in [0, 100].
func (*Client) SetSegmentColor ¶ added in v0.0.3
func (c *Client) SetSegmentColor(ctx context.Context, sku, deviceID string, segments []int, rgb int) error
SetSegmentColor sets the color of specific light strip segments. segments is a slice of zero-based segment indices. rgb is a packed color integer (r<<16|g<<8|b).
func (*Client) SetSnapshot ¶ added in v0.0.3
SetSnapshot activates a saved snapshot by its integer ID.
func (*Client) SetTemperature ¶ added in v0.0.3
func (c *Client) SetTemperature(ctx context.Context, sku, deviceID string, temp TemperatureValue) error
SetTemperature sets the target temperature of a heater, thermostat, or kettle.
func (*Client) SetToggle ¶ added in v0.0.3
SetToggle enables or disables a named toggle feature such as "gradientToggle" or "nightlightToggle".
func (*Client) SetWorkMode ¶ added in v0.0.3
SetWorkMode sets the working mode of an appliance such as a humidifier or air purifier.
func (*Client) TurnOn ¶
TurnOn powers the device on.
Example ¶
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
govee "github.com/DTCurrie/govee-go"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
type envelope struct {
RequestID string `json:"requestId"`
Code int `json:"code"`
Msg string `json:"msg"`
Payload interface{} `json:"payload"`
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(envelope{Code: 200, Msg: "success", Payload: struct{}{}})
}))
defer srv.Close()
client := govee.New("my-api-key", govee.WithBaseURL(srv.URL))
err := client.TurnOn(context.Background(), "H6008", "AA:BB:CC:DD")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("turned on")
}
Output: turned on
type DIYSceneOption ¶ added in v0.0.3
DIYSceneOption is a user-created DIY scene available for a device. Activate it with SetDIYScene using the integer Value.
type Device ¶
type Device struct {
SKU string `json:"sku"`
DeviceID string `json:"device"`
DeviceName string `json:"deviceName,omitempty"`
Type string `json:"type,omitempty"`
Capabilities []Capability `json:"capabilities"`
}
Device represents a Govee device and its capabilities as returned by GetDevices.
func (Device) FindCapability ¶ added in v0.0.3
func (d Device) FindCapability(capType, instance string) *Capability
FindCapability returns the first capability matching the given type and instance, or nil if the device does not have that capability.
func (Device) HasCapability ¶ added in v0.0.3
HasCapability reports whether the device advertises the given capability type and instance.
type DeviceEvent ¶ added in v0.0.3
type DeviceEvent struct {
SKU string `json:"sku"`
DeviceID string `json:"device"`
DeviceName string `json:"deviceName"`
Capabilities []EventCapability `json:"capabilities"`
}
DeviceEvent is a device state notification received from the Govee MQTT broker.
type DeviceStateResponse ¶ added in v0.0.3
type DeviceStateResponse struct {
SKU string `json:"sku"`
DeviceID string `json:"device"`
Capabilities []Capability `json:"capabilities"`
}
DeviceStateResponse holds the current state of a device expressed as a list of capabilities, each carrying their current value in the State field.
func (*DeviceStateResponse) Brightness ¶ added in v0.0.3
func (r *DeviceStateResponse) Brightness() (percent int, found bool)
Brightness returns the current brightness percentage and whether the capability was present in the response.
func (*DeviceStateResponse) ColorRGB ¶ added in v0.0.3
func (r *DeviceStateResponse) ColorRGB() (red, green, blue int, found bool)
ColorRGB returns the current color as separate R, G, B components decoded from the packed integer (r<<16|g<<8|b), plus whether the capability was present.
func (*DeviceStateResponse) ColorTemp ¶ added in v0.0.3
func (r *DeviceStateResponse) ColorTemp() (kelvin int, found bool)
ColorTemp returns the current color temperature in Kelvin and whether the capability was present in the response.
func (*DeviceStateResponse) FindState ¶ added in v0.0.3
func (r *DeviceStateResponse) FindState(capType, instance string) *Capability
FindState returns the capability with the given type and instance, or nil if not found.
func (*DeviceStateResponse) IsOnline ¶ added in v0.0.3
func (r *DeviceStateResponse) IsOnline() bool
IsOnline reports whether the device is currently online.
func (*DeviceStateResponse) PowerState ¶ added in v0.0.3
func (r *DeviceStateResponse) PowerState() (on bool, found bool)
PowerState returns the power state (true = on, false = off) and whether the capability was present in the response.
type EnumOption ¶ added in v0.0.3
type EnumOption struct {
Name string `json:"name"`
Value json.RawMessage `json:"value"`
}
EnumOption is a single named option within an ENUM capability parameter.
type EnumParameters ¶ added in v0.0.3
type EnumParameters struct {
DataType string `json:"dataType"`
Options []EnumOption `json:"options"`
}
EnumParameters describes the valid values for an ENUM-typed capability parameter.
type EventCapability ¶ added in v0.0.3
type EventCapability struct {
Type string `json:"type"`
Instance string `json:"instance"`
State json.RawMessage `json:"state"`
}
EventCapability is a single capability state update delivered inside a DeviceEvent.
type EventClient ¶ added in v0.0.3
type EventClient struct {
// contains filtered or unexported fields
}
EventClient subscribes to real-time device events from the Govee MQTT broker. Create one with NewEventClient, then call Connect to begin receiving events.
func NewEventClient ¶ added in v0.0.3
func NewEventClient(apiKey string, handler EventHandler, opts ...EventOption) *EventClient
NewEventClient creates a new EventClient that delivers events to handler.
Example ¶
package main
import (
"fmt"
govee "github.com/DTCurrie/govee-go"
)
func main() {
handler := func(event govee.DeviceEvent) {
fmt.Printf("event from %s: %d capability updates\n", event.SKU, len(event.Capabilities))
}
ec := govee.NewEventClient("my-api-key", handler,
govee.WithMQTTBroker("mqtt://localhost:1883"),
)
// ec.Connect(ctx) would establish the MQTT connection.
_ = ec
}
Output:
func (*EventClient) Close ¶ added in v0.0.3
func (e *EventClient) Close() error
Close disconnects the MQTT client and stops event delivery.
type EventHandler ¶ added in v0.0.3
type EventHandler func(event DeviceEvent)
EventHandler is a callback invoked for each DeviceEvent received over MQTT.
type EventOption ¶ added in v0.0.3
type EventOption func(*EventClient)
EventOption is a functional option for configuring an EventClient.
func WithMQTTBroker ¶ added in v0.0.3
func WithMQTTBroker(url string) EventOption
WithMQTTBroker overrides the MQTT broker URL used by an EventClient. The default is mqtts://mqtt.openapi.govee.com:8883.
type LightSceneValue ¶ added in v0.0.3
LightSceneValue identifies a dynamic built-in light scene by its API-assigned ID and parameter ID. Obtain these values from GetScenes and pass to SetLightScene.
type MusicModeValue ¶ added in v0.0.3
type MusicModeValue struct {
MusicMode int `json:"musicMode"`
Sensitivity int `json:"sensitivity"`
AutoColor *int `json:"autoColor,omitempty"`
RGB *int `json:"rgb,omitempty"`
}
MusicModeValue configures a music visualization mode.
type Option ¶
type Option func(*Client)
Option is a functional option for configuring a Client.
func WithBaseURL ¶
WithBaseURL overrides the default API base URL. Useful for testing.
func WithHTTPClient ¶
WithHTTPClient replaces the default *http.Client. Useful for custom transports or timeouts.
type SceneOption ¶ added in v0.0.3
type SceneOption struct {
Name string `json:"name"`
Value LightSceneValue `json:"value"`
}
SceneOption is a named dynamic light scene available for a device. The Value contains the id and paramId required to activate it via SetLightScene.
type TemperatureValue ¶ added in v0.0.3
type TemperatureValue struct {
Temperature int `json:"temperature"`
Unit string `json:"unit,omitempty"`
AutoStop *int `json:"autoStop,omitempty"`
}
TemperatureValue sets the target temperature for heaters, thermostats, and similar devices.
type WorkModeValue ¶ added in v0.0.3
WorkModeValue sets the active working mode and its associated sub-value for appliances.