govee

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 14 Imported by: 0

README

Govee

A complete, strongly typed Go client for the Govee Developer Platform OpenAPI and the Govee LAN control protocol.

The library covers the full device catalogue the official APIs support — lights, air purifiers, thermometers, sockets, sensors, heaters, humidifiers, dehumidifiers, ice makers, aroma diffusers, fans, kettles and more — with typed commands, capability discovery, client-side validation, rate limiting and automatic retries, so applications can manage Govee devices programmatically with no app in the loop.

import "github.com/Sh4wnK/Govee"

c := govee.NewClient(os.Getenv("GOVEE_API_KEY"))

devices, err := c.Devices(ctx)          // what do I have, and what can it do?
light := devices[0]

if light.Supports(govee.CapOnOff, govee.InstancePowerSwitch) {
    c.SetPower(ctx, light.SKU, light.ID, true)
}
if r, ok := light.Range(govee.CapRange, govee.InstanceBrightness); ok {
    // r.Min..r.Max — validated before the request is sent
    c.SetBrightness(ctx, light.SKU, light.ID, int(r.Max/2))
}
c.SetColorRGB(ctx, light.SKU, light.ID, govee.Color{R: 255, G: 128, B: 0})
c.SetColorTemperature(ctx, light.SKU, light.ID, 6500)

For LAN-only control (no API key, same network):

import "github.com/Sh4wnK/Govee/lan"

devices, _ := lan.Scan(ctx)      // UDP multicast discovery
for _, d := range devices {
    c := lan.NewClient(d.IP)
    c.Turn(ctx, true)
    c.Color(ctx, 255, 0, 0)
    status, _ := c.DevStatus(ctx)
}

Why this library

  • One codebase for the whole ecosystem. Every capability the OpenAPI documents is typed: on_off, toggle, range, mode, color_setting, segment_color_setting, dynamic_scene, music_setting, work_mode, temperature_setting, plus the read-only online, property and event capabilities.
  • No app required. The full device/state/control/scenes surface is exposed through a small, documented API — see cmd/govee for a ready-made CLI and examples/ for programs.
  • Made for sustained use. Client-side token-bucket rate limiting honors Govee's published limits (12 req/s account, 2 req/s per device for control), transient failures (HTTP 429/5xx) are retried with exponential backoff, jitter, and Retry-After support, and the connection-reusing http.Client keeps keep-alive connections hot. The soak test fires 600 concurrent calls through a fault-injecting server and asserts zero failures — reproduce it with:
    go test -run TestSoak500Calls -v
    

Architecture

cmd/govee/          CLI (devices, state, power, brightness, color, scenes, lan scan)
examples/           runnable example programs (basic, lanctl)
lan/                LAN control: multicast discovery + per-device commands
testdata/           JSON fixtures captured from the official API docs
├── client.go       transport, retries/backoff, token bucket plumbing
├── api.go          endpoint methods: Devices, State, Control, ListScenes, ...
├── types.go        typed helpers (SetPower, SetBrightness, SetScene, ...)
├── commands.go     capability command constructors + validation
├── device.go       Device/Capability model with discovery helpers
├── errors.go       APIError + sentinel errors (errors.Is/As friendly)
└── ratelimit.go    concurrency-safe token bucket

Flow of a control call:

SetPower(ctx, sku, id, on)
  -> Control(ctx, sku, id, OnCommand(on))
    -> ValidateCommand against device capabilities (when known)   [client.go-side]
    -> per-device token bucket (2 req/s, burst 6)
    -> account token bucket (12 req/s, burst 80)
    -> POST /router/api/v1/device/control  (+ requestId envelope)
    -> on 429/5xx/network error: exponential backoff + jitter, Retry-After honored
Design decisions
  • Strongly typed requests. No map[string]interface{} anywhere on the send path; capability values are typed structs (CapabilityCommand, WorkModeCommand, SegmentColorCommand, ...). Because Value is any, the wire format still matches the API exactly.
  • Capabilities drive validation. Device carries the parameters the API advertises (GET /router/api/v1/user/devices), and ValidateCommand rejects out-of-range brightness, unknown scenes, and missing struct fields before anything hits the network — which is what keeps the error rate low under sustained use.
  • Two rate-limiting layers. Govee enforces both account-level (12 req/s) and per-device (2 req/s) control limits. Client enforces the account bucket; Client.Device(sku, id, dev) returns a per-device handle with its own bucket, so two devices controlled from one client each get their full headroom.
  • Honest errors. APIError carries HTTP status, API code, message, requestId and endpoint, and supports errors.Is(err, govee.ErrRateLimited).
  • No external dependencies. The library uses only the Go standard library.

Quickstart

  1. Get an API key: Govee Home app → Settings → Apply for API key (https://developer.govee.com/reference/apply-you-govee-api-key).
  2. Add a device to your Govee account (the app and the API share the account's devices).
  3. Build the CLI or use the library:
export GOVEE_API_KEY=...

go run ./cmd/govee devices
go run ./cmd/govee state H6601 9D:FA:85:EB:D3:00:8B:FF
go run ./cmd/govee power H6601 9D:FA:85:EB:D3:00:8B:FF on
go run ./cmd/govee brightness H6601 9D:FA:85:EB:D3:00:8B:FF 50
go run ./cmd/govee color H6601 9D:FA:85:EB:D3:00:8B:FF 255,128,0
go run ./cmd/govee scenes H618E 8C:2E:9C:04:A0:03:82:D1
go run ./cmd/govee lan scan

Configuration

The Client is configured with functional options:

Option Default Purpose
WithHTTPClient(c *http.Client) keep-alive client Custom transport; used by tests and proxies
WithBaseURL(url) https://openapi.api.govee.com Govee test environment / local testing
WithTimeout(d) 30s Per-request HTTP timeout
WithRateLimit(allow, window) 720/min (12/s) Account-level token bucket
WithNoRateLimit() — Opt out (you own the limits)
WithRetryPolicy(maxAttempts, baseDelay) 5, 200ms Retry budget for 429/5xx

The CLI reads the API key from GOVEE_API_KEY (see .env.example); the test environment can be selected with GOVEE_BASE_URL.

Client API

Devices & discovery
Method Description
Devices(ctx) ([]Device, error) All account devices + advertised capabilities
(Device).Supports(type, instance) bool Capability discovery
(Device).Range(type, instance) (ValueRange, bool) min/max/precision of a range capability
(Device).Options(type, instance) ([]CapabilityOption, bool) enum choices (scenes, modes, ...)
ValidateCommand(dev, cmd) error Client-side validation against advertised parameters
Control

All methods take ctx, sku, deviceID and return error:

Method Capability
SetPower(ctx, sku, id, on) / SetColorRGB / SetBrightness contract API
SetColorTemperature(kelvin) color_setting / colorTemperatureK
SetSegmentColor(segments, color) / SetSegmentBrightness segment_color_setting
SetScene(name) / SetSceneID(id) dynamic_scene / lightScene
SetWorkMode(workMode, modeValue) work_mode
SetTargetTemperature(temp, unit, autoStop) temperature_setting
Toggle(instance, on) / SetMode(instance, value) toggle / mode
SetHumidity(percent) range / humidity
SetMusicMode(on) music_setting
Control(ctx, sku, id, CapabilityCommand) any capability, fully typed
State queries
Method Description
State(ctx, sku, id) (*State, error) Full state; State.Bool/Number/String(instance) accessors
ListScenes(ctx, sku, id) ([]Scene, error) Dynamic scenes (/device/scenes)
ListDIYScenes(ctx, sku, id) ([]Scene, error) DIY scenes (/device/diy-scenes)
Errors

*govee.APIError carries Status, Code, Message, RequestID, Endpoint and RetryAfter; sentinels ErrRateLimited, ErrUnauthorized, ErrDeviceNotFound, ErrValidation, ErrNotSupported, ErrInvalidRequest work with errors.Is.

LAN (govee/lan)
  • lan.Scan(ctx) ([]Device, error) — multicast discovery (239.255.255.250:4001), replies on 4002.
  • lan.NewClient(ip) — commands on port 4003: Turn, Brightness, Color, ColorWC, Scene, MusicMode, DevStatus. Timeout and sockets are injectable for tests.

Rate limits (per Govee's docs)

API Actor Limit
GET /router/api/v1/user/devices Account 30 req/min
POST /router/api/v1/device/control Account 12 req/s (burst 80)
POST /router/api/v1/device/control Device 2 req/s (burst 6)
POST /router/api/v1/device/state Device 30 req/min
POST /router/api/v1/device/scenes Device 30 req/min

The client enforces the account control limit and, via Client.Device(...), the per-device control limit locally, so a sustained integration stays within budget instead of discovering it via 429s.

Performance

Measured on this machine (Apple M3, macOS) with go test -bench . -benchmem -run '^$':

Benchmark ns/op B/op allocs/op
BenchmarkControl (steady state, local fake API) ~11,000 ~9,900 ~121

Under sustained use, the soak test (go test -run TestSoak500Calls -v) drives 600 concurrent control calls through a server that injects three transient failures (429/503/500) per call, then asserts all 600 succeed — every failure absorbed by the retry layer. Log line from the run: soak: 600/600 calls succeeded; 2400 requests, 1800 injected failures.

Project layout

.
├── cmd/govee/        CLI
├── examples/         basic (cloud) and lanctl (LAN) example programs
├── lan/              LAN control sub-package
├── testdata/         API fixtures taken from the official documentation
├── *.go              library sources (see Architecture)
└── *.go tests        unit, integration (httptest/loopback UDP), race, soak, benchmarks

Testing

go test ./...          # unit + integration + soak (skipped with -short)
go test -race ./...    # race detector (CI does this)
go vet ./...           # static checks

The test suite covers request shapes, response parsing against fixtures copied from the official docs, error mapping, retry/backoff behavior, token-bucket semantics, capability validation, and LAN discovery/commands against a loopback fake device.

License

MIT — see LICENSE. Copyright (c) 2026 Gurshawn Kaloty.

This project is not affiliated with or endorsed by Govee. Govee is a trademark of its owner.

Documentation

Overview

Package govee is a complete, strongly typed Go client for the Govee Developer Platform OpenAPI (https://openapi.api.govee.com).

It covers the full device catalogue exposed by the official API - lights, air purifiers, thermometers, sockets, sensors, heaters, humidifiers, dehumidifiers, ice makers, aroma diffusers and more - via a small set of type-safe endpoints, plus a LAN control sub-package for low-latency discovery and control on the local network.

The client is concurrency-safe and designed for sustained use: requests are rate limited with a token bucket honoring Govee's per-account and per-device limits, and transient failures (HTTP 429/5xx) are retried with exponential backoff and jitter.

See https://developer.govee.com for the official API documentation.

Index

Constants

View Source
const (
	CapOnOff          = "devices.capabilities.on_off"
	CapToggle         = "devices.capabilities.toggle"
	CapRange          = "devices.capabilities.range"
	CapMode           = "devices.capabilities.mode"
	CapColorSetting   = "devices.capabilities.color_setting"
	CapSegmentColor   = "devices.capabilities.segment_color_setting"
	CapMusicSetting   = "devices.capabilities.music_setting"
	CapDynamicScene   = "devices.capabilities.dynamic_scene"
	CapWorkMode       = "devices.capabilities.work_mode"
	CapTemperatureSet = "devices.capabilities.temperature_setting"
	CapOnline         = "devices.capabilities.online"
	CapProperty       = "devices.capabilities.property"
	CapEvent          = "devices.capabilities.event"
)

Capability type constants, as documented under "capabilities" at https://developer.govee.com/reference/get-you-devices.

View Source
const (
	DeviceTypeLight             = "devices.types.light"
	DeviceTypeAirPurifier       = "devices.types.air_purifier"
	DeviceTypeThermometer       = "devices.types.thermometer"
	DeviceTypeSocket            = "devices.types.socket"
	DeviceTypeSensor            = "devices.types.sensor"
	DeviceTypeHeater            = "devices.types.heater"
	DeviceTypeHumidifier        = "devices.types.humidifier"
	DeviceTypeDehumidifier      = "devices.types.dehumidifier"
	DeviceTypeIceMaker          = "devices.types.ice_maker"
	DeviceTypeAromaDiffuser     = "devices.types.aroma_diffuser"
	DeviceTypeBox               = "devices.types.box"
	DeviceTypeFan               = "devices.types.fan"
	DeviceTypeKettle            = "devices.types.kettle"
	DeviceTypeFrozenTreatMaker  = "devices.types.frozen_treat_maker"
	DeviceTypeAirQualityMonitor = "devices.types.air_quality_monitor"
	DeviceTypeKitchenComposter  = "devices.types.kitchen_composter"
	DeviceTypeTimer             = "devices.types.timer"
)

Device type constants returned in Device.Type. The list covers every device family the official API documents; Govee adds more over time, so treat unknown values as opaque strings.

View Source
const (
	InstancePowerSwitch         = "powerSwitch"
	InstanceBrightness          = "brightness"
	InstanceHumidity            = "humidity"
	InstanceColorRgb            = "colorRgb"
	InstanceColorTemperatureK   = "colorTemperatureK"
	InstanceSegmentedColorRgb   = "segmentedColorRgb"
	InstanceSegmentedBrightness = "segmentedBrightness"
	InstanceWorkMode            = "workMode"
	InstanceTargetTemperature   = "targetTemperature"
	InstanceSliderTemperature   = "sliderTemperature"
	InstanceLightScene          = "lightScene"
	InstanceDIYScene            = "diyScene"
	InstanceOnline              = "online"
	InstanceVolume              = "volume"
	InstanceTemperature         = "temperature"
)

Standard instance names for the most common capabilities.

View Source
const DefaultBaseURL = "https://openapi.api.govee.com"

Default base URL of the Govee Developer Platform OpenAPI.

View Source
const DefaultTimeout = 30 * time.Second

Default timeout for individual HTTP requests.

Variables

View Source
var (
	// ErrRateLimited is returned when the local rate limiter refuses a
	// request or when the API returns HTTP 429 and retries are exhausted.
	ErrRateLimited = errors.New("govee: rate limit exceeded")

	// ErrUnauthorized is returned when the API rejects the API key
	// (HTTP 401 or 403).
	ErrUnauthorized = errors.New("govee: unauthorized (invalid or missing API key)")

	// ErrDeviceNotFound is returned when the API reports an unknown
	// device or SKU (HTTP 404).
	ErrDeviceNotFound = errors.New("govee: device not found")

	// ErrValidation is returned by client-side validation helpers when a
	// control value violates the capability parameters advertised by the
	// device (e.g. brightness outside the advertised range).
	ErrValidation = errors.New("govee: validation failed")

	// ErrNotSupported is returned when the requested capability is not
	// advertised by the device.
	ErrNotSupported = errors.New("govee: capability not supported by device")

	// ErrInvalidRequest is returned for malformed client-side requests,
	// capability values of the wrong shape, and empty required fields.
	ErrInvalidRequest = errors.New("govee: invalid request")
)

Sentinel errors returned by the client. Use errors.Is to test for them.

Functions

func ColorToRGBInt

func ColorToRGBInt(c Color) int

ColorToRGBInt converts an RGB color to the API's 0xRRGGBB integer.

func ValidateCommand

func ValidateCommand(d *Device, cmd CapabilityCommand) error

ValidateCommand checks a CapabilityCommand against the capability parameters advertised by the device. It enforces:

  • the device advertises the capability (type+instance),
  • enum values are among the advertised options,
  • numeric values fall within the advertised range and honor precision,
  • struct values include every required field with a valid value.

It returns ErrNotSupported when the capability is missing, ErrValidation when a value violates the advertised parameters, or nil when the command is valid. Devices() must have been called first so Capabilities is populated.

Types

type APIError

type APIError struct {
	// HTTP status code of the response. Zero for API-level errors that
	// came inside an HTTP 200 body.
	Status int
	// Code is the Govee API code from the response body, when present.
	Code int
	// Message is the human-readable error message, when present.
	Message string
	// RequestID echoes the requestId sent with the request, when the
	// API returned it. Useful for support conversations.
	RequestID string
	// Endpoint is the API path the error came from (e.g. "/router/api/v1/device/control").
	Endpoint string
	// RetryAfter is the number of seconds the API asked the client to
	// wait before retrying (from the Retry-After header on 429/503), or
	// -1 when absent.
	RetryAfter int
}

APIError is the error type returned for non-2xx HTTP responses and for API-level failures reported inside a 200 response body (code != 200).

func AsError

func AsError(err error) (*APIError, bool)

AsError converts an error returned by this package to *APIError, when possible. It returns nil when the error is not an APIError.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is reports whether target matches one of the sentinel errors, without requiring the exact error value. This makes sentinel matching work with APIError values that were created without going through Unwrap.

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap makes APIError compatible with errors.Unwrap/errors.Is chains so callers can still match on the sentinel errors above.

type Capability

type Capability struct {
	Type       string           `json:"type"`
	Instance   string           `json:"instance"`
	AlarmType  int              `json:"alarmType,omitempty"`
	Parameters json.RawMessage  `json:"parameters"`
	EventState *StateDescriptor `json:"eventState,omitempty"`
}

Capability describes a single capability of a device, exactly as the API reports it (see GET /router/api/v1/user/devices).

type CapabilityCommand

type CapabilityCommand = capabilityCommand

CapabilityCommand is a typed command for a device capability (see the typed constructors OnCommand, BrightnessCommand, ...).

func ColorCommand

func ColorCommand(col Color) CapabilityCommand

ColorCommand builds a CapabilityCommand that sets an RGB color: devices.capabilities.color_setting, instance colorRgb, value as 0xRRGGBB.

func ColorTemperatureCommand

func ColorTemperatureCommand(kelvin int) CapabilityCommand

ColorTemperatureCommand builds a CapabilityCommand for colorTemperatureK (Kelvin, typically 2000-9000).

func EnumCommand

func EnumCommand(capType, instance string, value int) CapabilityCommand

EnumCommand builds a CapabilityCommand for an enum-valued capability (mode, on_off, toggle) with an int value.

func MusicSettingCommand

func MusicSettingCommand(on bool) CapabilityCommand

MusicSettingCommand builds a CapabilityCommand for the music mode (devices.capabilities.music_setting). value is typically 0 (off) or 1 (on).

func OnCommand

func OnCommand(on bool) CapabilityCommand

OnCommand builds a CapabilityCommand that turns a device on or off (devices.capabilities.on_off, instance powerSwitch).

func RangeCommand

func RangeCommand(instance string, value int) CapabilityCommand

RangeCommand builds a CapabilityCommand for a range capability (e.g. brightness with instance "brightness").

func SceneCommand

func SceneCommand(sceneName string) CapabilityCommand

SceneCommand builds a CapabilityCommand that applies a scene by name. The scene must be one of the device's advertised options (see Device.Options(CapDynamicScene, ...) or ListScenes).

func SceneCommandID

func SceneCommandID(id int) CapabilityCommand

SceneCommandID builds a CapabilityCommand that applies a scene by its numeric ID (as returned by ListScenes).

func SegmentBrightnessCommand

func SegmentBrightnessCommand(segments []int, brightness int) CapabilityCommand

SegmentBrightnessCommand builds a CapabilityCommand setting brightness on a range of segments (segmentedBrightness).

func SegmentColorCommand

func SegmentColorCommand(segments []int, col Color) CapabilityCommand

SegmentColorCommand builds a CapabilityCommand setting colors on a range of segments (devices.capabilities.segment_color_setting, segmentedColorRgb).

func TemperatureCommand

func TemperatureCommand(kelvinOrDegrees int, unit string, autoStop int) CapabilityCommand

TemperatureCommand builds a CapabilityCommand for targetTemperature (devices.capabilities.temperature_setting). unit is "Celsius" or "Fahrenheit". autoStop (0/1) optionally stops the device when the target is reached; pass -1 to omit it (server default).

func ToggleCommand

func ToggleCommand(instance string, on bool) CapabilityCommand

ToggleCommand builds a CapabilityCommand for a toggle instance (e.g. oscillationToggle, nightlightToggle, gradientToggle).

func WorkModeCommand

func WorkModeCommand(workMode, modeValue int) CapabilityCommand

WorkModeCommand builds a CapabilityCommand setting a work mode and its value (devices.capabilities.work_mode): e.g. WorkModeCommand(1, 1) for gear mode Low on a purifier.

type CapabilityOption

type CapabilityOption struct {
	Name    string             `json:"name"`
	Value   any                `json:"value"`
	Options []CapabilityOption `json:"options,omitempty"`
	// Message is present on event options (e.g. "Lack of Water").
	Message string `json:"message,omitempty"`
}

CapabilityOption is a named choice a capability offers (e.g. on/off, a scene, a mode).

func (CapabilityOption) ValueString

func (o CapabilityOption) ValueString() string

ValueString renders the option value as a string, descending into sub-options when the value is nested (e.g. scene {paramId, id} objects render as their id).

type CapabilityParameters

type CapabilityParameters struct {
	DataType     string             `json:"dataType"`
	Unit         string             `json:"unit"`
	Range        *ValueRange        `json:"range,omitempty"`
	ElementRange *ValueRange        `json:"elementRange,omitempty"`
	ElementType  string             `json:"elementType,omitempty"`
	Size         *ValueRange        `json:"size,omitempty"`
	Options      []CapabilityOption `json:"options"`
	Fields       []ParameterField   `json:"fields"`
	// Raw keeps the unparsed JSON for forward compatibility.
	Raw json.RawMessage `json:"-"`
}

CapabilityParameters are the parsed parameters of a capability. Not all fields are meaningful for all capabilities; the decoder fills what the server sent. For STRUCT capabilities, Fields describes the struct; for RANGE capabilities, Range/Precision apply.

func UnmarshalCapabilityParameters

func UnmarshalCapabilityParameters(c Capability) (CapabilityParameters, error)

UnmarshalCapabilityParameters parses a capability's parameters into a typed struct.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a Govee OpenAPI client. It is safe for concurrent use by multiple goroutines: both the underlying http.Client and the token bucket are concurrency-safe.

func NewClient

func NewClient(apiKey string, opts ...Option) *Client

NewClient returns a Client for the given API key. It performs no network I/O and never panics; an empty or malformed key surfaces as an API error from the first request.

func (*Client) Control

func (c *Client) Control(ctx context.Context, sku, deviceID string, cmd CapabilityCommand) error

Control sends a single capability command to a device: POST /router/api/v1/device/control.

func (*Client) Device

func (c *Client) Device(sku, deviceID string, dev *Device) *DeviceHandle

Device returns a per-device handle. If dev is non-nil (e.g. from Devices()), the handle validates commands against its advertised capabilities and derives sku/id from it; otherwise the sku and deviceID parameters are used as-is. The handle enforces Govee's per-device control limit of 2 req/s (burst 6) locally.

func (*Client) Devices

func (c *Client) Devices(ctx context.Context) ([]Device, error)

Devices fetches all devices and their advertised capabilities for the account: GET /router/api/v1/user/devices. The returned slice is a fresh copy; mutating it does not affect the client.

func (*Client) ListDIYScenes

func (c *Client) ListDIYScenes(ctx context.Context, sku, deviceID string) ([]Scene, error)

ListDIYScenes queries the DIY light scenes of a device: POST /router/api/v1/device/diy-scenes.

func (*Client) ListScenes

func (c *Client) ListScenes(ctx context.Context, sku, deviceID string) ([]Scene, error)

ListScenes queries the dynamic light scenes of a device: POST /router/api/v1/device/scenes.

func (*Client) SetBrightness

func (c *Client) SetBrightness(ctx context.Context, sku, deviceID string, percent int) error

SetBrightness sets the brightness of a device in percent (1-100). The value is validated against the device's advertised range when the optional device is non-nil and has the range capability.

func (*Client) SetColorRGB

func (c *Client) SetColorRGB(ctx context.Context, sku, deviceID string, col Color) error

SetColorRGB sets the color of a light to col.

func (*Client) SetColorTemperature

func (c *Client) SetColorTemperature(ctx context.Context, sku, deviceID string, kelvin int) error

SetColorTemperature sets the color temperature in Kelvin (typically 2000-9000 K).

func (*Client) SetHumidity

func (c *Client) SetHumidity(ctx context.Context, sku, deviceID string, percent int) error

SetHumidity sets the target humidity of a humidifier (range capability, instance "humidity").

func (*Client) SetMode

func (c *Client) SetMode(ctx context.Context, sku, deviceID, instance string, value int) error

SetMode sets an enum mode (devices.capabilities.mode, e.g. nightlightScene).

func (*Client) SetMusicMode

func (c *Client) SetMusicMode(ctx context.Context, sku, deviceID string, on bool) error

SetMusicMode toggles the music mode of a device (devices.capabilities.music_setting).

func (*Client) SetPower

func (c *Client) SetPower(ctx context.Context, sku, deviceID string, on bool) error

SetPower sends an on/off command to the device: on=true turns it on.

func (*Client) SetScene

func (c *Client) SetScene(ctx context.Context, sku, deviceID, sceneName string) error

SetScene applies a dynamic light scene by name (from ListScenes or the device's advertised lightScene options).

func (*Client) SetSceneID

func (c *Client) SetSceneID(ctx context.Context, sku, deviceID string, sceneID int) error

SetSceneID applies a dynamic light scene by numeric ID (from ListScenes).

func (*Client) SetSegmentBrightness

func (c *Client) SetSegmentBrightness(ctx context.Context, sku, deviceID string, segments []int, brightness int) error

SetSegmentBrightness sets brightness on the given segments of a light strip (segmentedBrightness).

func (*Client) SetSegmentColor

func (c *Client) SetSegmentColor(ctx context.Context, sku, deviceID string, segments []int, col Color) error

SetSegmentColor sets an RGB color on the given segments of a light strip (devices.capabilities.segment_color_setting, segmentedColorRgb).

func (*Client) SetTargetTemperature

func (c *Client) SetTargetTemperature(ctx context.Context, sku, deviceID string, temp int, unit string, autoStop int) error

SetTargetTemperature sets the target temperature of a heater or thermostat (devices.capabilities.temperature_setting). unit is "Celsius" or "Fahrenheit"; autoStop is 0 (maintain), 1 (auto stop), or -1 (omit).

func (*Client) SetWorkMode

func (c *Client) SetWorkMode(ctx context.Context, sku, deviceID string, workMode, modeValue int) error

SetWorkMode sets the work mode of a device (devices.capabilities.work_mode): e.g. SetWorkMode(ctx, sku, id, 1, 1) selects gear mode "Low" on a purifier.

func (*Client) State

func (c *Client) State(ctx context.Context, sku, deviceID string) (*State, error)

State queries the current state of a device: POST /router/api/v1/device/state.

func (*Client) Toggle

func (c *Client) Toggle(ctx context.Context, sku, deviceID, instance string, on bool) error

Toggle toggles a toggle-type instance (e.g. oscillationToggle, nightlightToggle) on or off.

func (*Client) WithAPIKey

func (c *Client) WithAPIKey(apiKey string) *Client

WithAPIKey returns a client sharing this client's configuration and HTTP machinery but bound to a different API key. The receiver is not mutated.

type Color

type Color struct {
	R, G, B uint8
}

Color is an RGB color (each channel 0-255).

func RGBColor

func RGBColor(rgb int) Color

RGBColor converts a 0xRRGGBB integer (0-16777215) to a Color.

func (Color) RGB

func (c Color) RGB() int

RGB returns the 24-bit 0xRRGGBB integer the Govee API expects (range 0-16777215).

type ControlPayload

type ControlPayload struct {
	SKU        string            `json:"sku"`
	Device     string            `json:"device"`
	Capability CapabilityCommand `json:"capability"`
}

ControlPayload is the payload of a ControlRequest.

type ControlRequest

type ControlRequest struct {
	RequestID string         `json:"requestId"`
	Payload   ControlPayload `json:"payload"`
}

ControlRequest is the documented JSON body of POST /router/api/v1/device/control.

type Device

type Device struct {
	SKU          string       `json:"sku"`
	ID           string       `json:"device"`
	Name         string       `json:"deviceName"`
	Type         string       `json:"type"`
	Capabilities []Capability `json:"capabilities"`
}

Device is a Govee device discovered via the account API. It carries the capability descriptions the API advertises for the device, which the client uses for validation and discovery (Supports, Range, Options).

func (*Device) Capability

func (d *Device) Capability(typeName, instance string) (Capability, bool)

Capability returns the device's capability of the given type/instance.

func (*Device) IsOnlineInCapabilities

func (d *Device) IsOnlineInCapabilities() bool

IsOnlineInCapabilities reports whether the device advertises an "online" capability (most devices do).

func (*Device) Options

func (d *Device) Options(typeName, instance string) ([]CapabilityOption, bool)

Options returns the enum options of a capability (e.g. scenes, modes, toggles, on/off). The second return value is false when the capability does not exist or has no options.

func (*Device) Range

func (d *Device) Range(typeName, instance string) (ValueRange, bool)

Range returns the numeric range (min/max/precision) of a range-typed capability (e.g. brightness) on this device. The second return value is false when the device has no such capability or it has no range.

func (*Device) Supports

func (d *Device) Supports(typeName, instance string) bool

Supports reports whether the device advertises a capability of the given type (e.g. CapOnOff), optionally filtering by instance.

type DeviceHandle

type DeviceHandle struct {
	Device *Device
	// contains filtered or unexported fields
}

Device is the per-device convenience wrapper returned by Client.Device(sku, id). It carries the device's advertised capabilities (fetched via Devices) so helpers can validate values before sending, and it enforces Govee's per-device control limit (2 req/s sustained, burst 6) with its own token bucket.

func (*DeviceHandle) BrightnessRange

func (h *DeviceHandle) BrightnessRange() (ValueRange, bool)

BrightnessRange returns the advertised brightness range of the device.

func (*DeviceHandle) Control

func (h *DeviceHandle) Control(ctx context.Context, cmd CapabilityCommand) error

Control sends a command through the client, after validating it against the device's advertised capabilities when available.

func (*DeviceHandle) SetBrightness

func (h *DeviceHandle) SetBrightness(ctx context.Context, percent int) error

SetBrightness sets the device brightness in percent.

func (*DeviceHandle) SetColorRGB

func (h *DeviceHandle) SetColorRGB(ctx context.Context, col Color) error

SetColorRGB sets the device color.

func (*DeviceHandle) SetColorTemperature

func (h *DeviceHandle) SetColorTemperature(ctx context.Context, kelvin int) error

SetColorTemperature sets the color temperature in Kelvin.

func (*DeviceHandle) SetPower

func (h *DeviceHandle) SetPower(ctx context.Context, on bool) error

SetPower turns the device on or off.

func (*DeviceHandle) SetScene

func (h *DeviceHandle) SetScene(ctx context.Context, sceneName string) error

SetScene applies a scene by name.

func (*DeviceHandle) SetSegmentColor

func (h *DeviceHandle) SetSegmentColor(ctx context.Context, segments []int, col Color) error

SetSegmentColor sets an RGB color on the given segments.

func (*DeviceHandle) SetWorkMode

func (h *DeviceHandle) SetWorkMode(ctx context.Context, workMode, modeValue int) error

SetWorkMode sets the work mode.

func (*DeviceHandle) State

func (h *DeviceHandle) State(ctx context.Context) (*State, error)

State fetches the device state.

func (*DeviceHandle) Supports

func (h *DeviceHandle) Supports(typeName, instance string) bool

Supports reports whether the device advertises the given capability.

func (*DeviceHandle) Toggle

func (h *DeviceHandle) Toggle(ctx context.Context, instance string, on bool) error

Toggle toggles a toggle instance.

type Option

type Option func(*Client)

Option configures a Client. All options are applied in order; invalid values are ignored or clamped rather than panicking.

func WithBaseURL

func WithBaseURL(base string) Option

WithBaseURL overrides the API base URL. Useful for the Govee test environment (https://test-openapi.api.govee.com) or local testing.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient replaces the default http.Client. Callers that supply their own client take responsibility for its Transport; the default client uses a connection-reusing Transport with sane timeouts.

func WithNoRateLimit

func WithNoRateLimit() Option

WithNoRateLimit disables client-side rate limiting. Only use when your application enforces Govee's published limits itself.

func WithRateLimit

func WithRateLimit(allow int, window time.Duration) Option

WithRateLimit overrides the client-side token bucket. allow is the number of requests permitted per window of time. See Govee's published limits:

GET  /router/api/v1/user/devices:    30 req/min/account
POST /router/api/v1/device/control:   12 req/s/account (720/min), burst 80
POST /router/api/v1/device/control:   2 req/s/device  (120/min), burst 6
POST /router/api/v1/device/state:     30 req/min/device
POST /router/api/v1/device/scenes:    30 req/min/device

func WithRetryPolicy

func WithRetryPolicy(maxAttempts int, baseDelay time.Duration) Option

WithRetryPolicy overrides retry behavior for transient failures (HTTP 429 and 5xx). maxAttempts counts the first attempt (must be >= 1); baseDelay is the initial backoff, doubled on each retry with jitter added.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-request HTTP timeout.

type ParameterField

type ParameterField struct {
	FieldName    string             `json:"fieldName"`
	DataType     string             `json:"dataType"`
	Required     bool               `json:"required"`
	Options      []CapabilityOption `json:"options"`
	Range        *ValueRange        `json:"range,omitempty"`
	ElementRange *ValueRange        `json:"elementRange,omitempty"`
	Size         *ValueRange        `json:"size,omitempty"`
	DefaultValue any                `json:"defaultValue,omitempty"`
}

ParameterField describes one field of a STRUCT-typed capability parameter.

type Scene

type Scene struct {
	Name    string `json:"name"`
	ParamID int    `json:"paramId"`
	ID      int    `json:"id"`
}

Scene is a dynamic light scene as returned by ListScenes.

type State

type State struct {
	SKU          string            `json:"sku"`
	Device       string            `json:"device"`
	DeviceName   string            `json:"deviceName"`
	Capabilities []StateCapability `json:"capabilities"`
}

State is the typed state of a device returned by State.

func (*State) Bool

func (s *State) Bool(instance string) (bool, bool)

Bool returns the state value of instance as a bool. The API reports on_off and toggle states as 0/1 numbers and online as true/false, so both shapes are accepted. ok is false when unavailable.

func (*State) Number

func (s *State) Number(instance string) (float64, bool)

Number returns the state value of instance as a float64 (for ranges, RGB, temperature...). ok is false when unavailable.

func (*State) Online

func (s *State) Online() (bool, bool)

Online reports whether the device state says it is online, when the device reports the online capability.

func (*State) StateValue

func (s *State) StateValue(instance string) (any, bool)

StateValue returns the parsed state value of a capability instance.

func (*State) String

func (s *State) String(instance string) (string, bool)

String returns the state value of instance as a string. ok is false when unavailable.

type StateCapability

type StateCapability struct {
	Type     string `json:"type"`
	Instance string `json:"instance"`
	State    struct {
		Value any `json:"value"`
	} `json:"state"`
}

StateCapability is one capability value of a state report. Value holds the parsed value: bool for online, float64 for numeric ranges, string for enums, map[string]any for structs (work mode, temperature settings).

type StateDescriptor

type StateDescriptor struct {
	Options []CapabilityOption `json:"options"`
}

StateDescriptor describes a reported event/property state (used for events, which have alarmType + eventState).

type StatePayload

type StatePayload struct {
	SKU    string `json:"sku"`
	Device string `json:"device"`
}

StatePayload identifies a device for a state query.

type StateRequest

type StateRequest struct {
	RequestID string       `json:"requestId"`
	Payload   StatePayload `json:"payload"`
}

StateRequest is the documented JSON body of POST /router/api/v1/device/state.

type StateResponse

type StateResponse struct {
	RequestID string `json:"requestId"`
	Msg       string `json:"msg"`
	Code      int    `json:"code"`
	Payload   State  `json:"payload"`
}

StateResponse is the JSON response of POST /router/api/v1/device/state.

type ValueRange

type ValueRange struct {
	Min       float64 `json:"min"`
	Max       float64 `json:"max"`
	Precision float64 `json:"precision"`
}

ValueRange is a numeric range with optional precision/step.

Directories

Path Synopsis
cmd
govee command
govee is a command-line client for the Govee Developer Platform and LAN APIs.
govee is a command-line client for the Govee Developer Platform and LAN APIs.
examples
basic command
Command basic shows the core cloud API: listing devices, querying state, and sending typed commands.
Command basic shows the core cloud API: listing devices, querying state, and sending typed commands.
lanctl command
Command lanctl shows LAN discovery and direct device control without any API key or cloud round trip:
Command lanctl shows LAN discovery and direct device control without any API key or cloud round trip:
Package lan implements Govee's LAN control API: UDP multicast discovery, status queries, and direct device commands over the local network.
Package lan implements Govee's LAN control API: UDP multicast discovery, status queries, and direct device commands over the local network.

Jump to

Keyboard shortcuts

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