package govee
import govee "github.com/DTCurrie/govee-go"
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 New(apiKey string, opts ...Option) *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.
Types
type APIError
type APIError struct { Code int Message string }
APIError represents an error response from the Govee API.
func (*APIError) Error
func (e *APIError) Error() string
type Capability
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
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
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 New
func New(apiKey string, opts ...Option) *Client
New creates a new Govee API client authenticated with the given API key.
func (*Client) ControlDevice
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
func (c *Client) GetDIYScenes(ctx context.Context, sku, deviceID string) ([]DIYSceneOption, error)
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
func (c *Client) GetDevices(ctx context.Context) ([]Device, error)
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.
Output: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)
}
}
Bedroom Light (H6008)
func (*Client) GetScenes
func (c *Client) GetScenes(ctx context.Context, sku, deviceID string) ([]SceneOption, error)
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
func (c *Client) SetBrightness(ctx context.Context, sku, deviceID string, percent int) error
SetBrightness sets the device brightness. percent must be in the range [1, 100].
Output: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")
}
brightness set
func (*Client) SetColor
func (c *Client) SetColor(ctx context.Context, sku, deviceID string, r, g, b int) error
SetColor sets the device color. Each of r, g, b must be in the range [0, 255].
func (*Client) SetColorTemp
func (c *Client) SetColorTemp(ctx context.Context, sku, deviceID string, kelvin int) error
SetColorTemp sets the device color temperature in Kelvin. kelvin must be greater than 0.
func (*Client) SetDIYScene
func (c *Client) SetDIYScene(ctx context.Context, sku, deviceID string, value int) error
SetDIYScene activates a user-created DIY scene. value is the scene ID obtained from GetDIYScenes.
func (*Client) SetLightScene
func (c *Client) SetLightScene(ctx context.Context, sku, deviceID string, value interface{}) error
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.
Output: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")
}
scene activated
func (*Client) SetMode
func (c *Client) SetMode(ctx context.Context, sku, deviceID, instance string, value int) error
SetMode sets a mode-type capability. instance identifies which mode to set (e.g. "nightlightScene", "presetScene"). value is the mode ID.
func (*Client) SetMusicMode
func (c *Client) SetMusicMode(ctx context.Context, sku, deviceID string, mode MusicModeValue) error
SetMusicMode activates a music visualization mode.
func (*Client) SetSegmentBrightness
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
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
func (c *Client) SetSnapshot(ctx context.Context, sku, deviceID string, value int) error
SetSnapshot activates a saved snapshot by its integer ID.
func (*Client) SetTemperature
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
func (c *Client) SetToggle(ctx context.Context, sku, deviceID, instance string, on bool) error
SetToggle enables or disables a named toggle feature such as "gradientToggle" or "nightlightToggle".
func (*Client) SetWorkMode
func (c *Client) SetWorkMode(ctx context.Context, sku, deviceID string, mode WorkModeValue) error
SetWorkMode sets the working mode of an appliance such as a humidifier or air purifier.
func (*Client) TurnOff
func (c *Client) TurnOff(ctx context.Context, sku, deviceID string) error
TurnOff powers the device off.
func (*Client) TurnOn
func (c *Client) TurnOn(ctx context.Context, sku, deviceID string) error
TurnOn powers the device on.
Output: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")
}
turned on
type DIYSceneOption
type DIYSceneOption struct { Name string `json:"name"` Value int `json:"value"` }
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
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
func (d Device) HasCapability(capType, instance string) bool
HasCapability reports whether the device advertises the given capability type and instance.
type DeviceEvent
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
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
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
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
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
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
func (r *DeviceStateResponse) IsOnline() bool
IsOnline reports whether the device is currently online.
func (*DeviceStateResponse) PowerState
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
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
type EnumParameters struct { DataType string `json:"dataType"` Options []EnumOption `json:"options"` }
EnumParameters describes the valid values for an ENUM-typed capability parameter.
type EventCapability
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
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
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
}
func (*EventClient) Close
func (e *EventClient) Close() error
Close disconnects the MQTT client and stops event delivery.
func (*EventClient) Connect
func (e *EventClient) Connect(ctx context.Context) error
Connect establishes the MQTT connection and starts delivering events to the handler. It blocks until the initial connection is established or ctx is cancelled.
type EventHandler
type EventHandler func(event DeviceEvent)
EventHandler is a callback invoked for each DeviceEvent received over MQTT.
type EventOption
type EventOption func(*EventClient)
EventOption is a functional option for configuring an EventClient.
func WithMQTTBroker
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
type LightSceneValue struct { ID int `json:"id"` ParamID int `json:"paramId"` }
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
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
func WithBaseURL(url string) Option
WithBaseURL overrides the default API base URL. Useful for testing.
func WithHTTPClient
func WithHTTPClient(hc *http.Client) Option
WithHTTPClient replaces the default *http.Client. Useful for custom transports or timeouts.
type SceneOption
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
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
type WorkModeValue struct { WorkMode int `json:"workMode"` ModeValue int `json:"modeValue"` }
WorkModeValue sets the active working mode and its associated sub-value for appliances.