wiz

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

README

wiz

A Go client for the local UDP API of WiZ lights and plugs; not affiliated with the owner of the WiZ brand.

Go Reference test Go

Requests with resends, light, fan and plug state, configuration, maintenance (reboot, factory reset, firmware update), module classes and their features, built-in scenes, broadcast discovery, and push registration with the pushes the devices send. No cloud account, no cgo. The only dependency outside the standard library is lanbcast (Apache-2.0, standard library only).

Features

Feature Status
getPilot, setPilot and setState (state, dimming, r/g/b, c/w, temp, sceneId, speed, ratio, the fan keys); setState sets the same keys without switching the light on yes; any other method can be sent with Request
Module classes colour (RGB), tunable white, dimmable white, plug, ceiling fan with a dimmable light (FANDIM), ceiling fan with a tunable-white light (DDTW); ClassOfTypeID for old firmware without a module name
Colour from hue and saturation or RGB HSToRGBCW, RGBToRGBCW: our own mapping to r, g, b and the two white LEDs (the grey part goes to the white LEDs), not a measured colour model
Features per module (FeaturesOf) brightness, colour, colour temperature, scenes, fan, breeze mode, reverse, dual head
Fans yes: fanState, fanMode (normal, breeze), fanSpeed checked against the device's number of speeds, fanRevrs (FanParams, FanSpeedMax)
Dual-head lamps the up/down split (ratio, RatioParams); per-head control (the devices key seen in pywizlight's development branch) is not implemented, as its numbering is not consistently described
Power getPower in milliwatts (GetPower), pc in the pilot on newer firmware; devices without metering answer "method not found"; there is no energy counter in the local API
Configuration getSystemConfig (with locks, group, region, drvConf, fwOtaStatus), getModelConfig, getUserConfig, the kelvin range (KelvinRange), setUserConfig with the params the vendor's library describes, getWifiConfig as sent
Factory settings setSystemConfig and setModelConfig with params as given: they can misconfigure the driver, so there are no helpers that pick values
Maintenance Reboot, Reset (factory reset) and UpdateFirmware, each sent once; firmware-update progress arrives as updateOta pushes
Discovery (the discovery form of registration sent to a broadcast address; the limited broadcast also goes to each LAN's directed broadcast) yes
Push registration; syncPilot, firstBeat (firmware, Matter version, product ID) and updateOta pushes; acknowledgement echoing the push's id yes
Scenes the built-in scene numbers with their app names, per class (fan lights: no published list)
Wi-Fi setup of new devices no: see below
WiZ Pro, the WiZ cloud no: see below

The vendor does not publish the local API; there is no standard to cite. The behaviour follows public descriptions of it (see PROVENANCE.md).

What is not implemented, and why
  • Wi-Fi setup of a new device (in its access-point mode). The method that would do it, setWifiConfig, appears in public descriptions only as a name; its parameters and the setup sequence are not publicly documented. Implementing it would need capturing the WiZ app's traffic during setup. Set devices up with the WiZ app.
  • Firmware images of one's own. UpdateFirmware asks the device to fetch a version; the device fetches the image itself (presumably from the vendor's servers), so no image can be supplied. The numbers in the progress pushes (updateStatus) and in fwOtaStatus are reported as sent: their meanings are not publicly described.
  • WiZ Pro. Its API is a GraphQL cloud API (docs.pro.wizconnected.com) with OAuth (PKCE) sign-in that needs a client ID issued by WiZ; there is no public sign-up for one, so it cannot be implemented or tested without a vendor account.
  • The consumer WiZ cloud. No public API for it was found.
  • pulse and other named-only methods (getDevInfo and others): public descriptions name them without parameters that could be checked. Request sends them as given.
  • Meanings not described anywhere public: the user config's po, the values of startupMode, and the content of getWifiConfig (openHAB notes an encrypted string, unverified). They are passed through as sent.

Ranges, as public descriptions give them (they disagree in places, so this package checks only where stated): dimming 1 to 100 (the vendor's library; older descriptions say 10), temp 1000 to 10000 K (pywizlight) or 1500 to 9000 K (the vendor's library), r, g, b, c, w 0 to 255, sceneId 1 to 150 plus 1000 (Rhythm), speed 10 to 200 (pywizlight, Home Assistant) or 20 to 200 (the vendor's library), ratio 0 to 100, fanSpeed 1 to the number of speeds the device reports (6 when it reports none).

Choosing a WiZ client

Compared from each library's source at the versions named, in October 2026; pywizlight is in Python and listed for reference. Check the projects themselves before relying on a row.

this module achetronic/wizgo v0.1.0 Dadido3/D3iot wiz driver (2022 commit) ctrox/gowiz (2021 commit) pywizlight 0.6.6 (Python)
Licence Apache-2.0 Apache-2.0 MIT MIT MIT
Last release or commit v0.x, 2026 tag 2023-09-19, last commit 2026-06-30 2022-11-23 2021-11-24 2026-08-05
Timeout on a request yes, context.Context no (the read blocks) yes yes yes
Resends a lost request yes, with a growing gap no yes, 10 retries by default no yes, up to 6 sends
Discovery by broadcast yes, limited and every LAN's directed broadcast no no no yes
Push registration yes sends the request no no yes
Receives syncPilot pushes yes (ServePush) no no no yes
Class from the module name, scenes per class yes yes class for three listed products, colour set in CIE XYZ (one bulb measured); a scene list without classes no yes
Fans yes (v0.2.0) no no no yes
Dependencies outside the standard library lanbcast golang.org/x/exp the D3iot module (gonum, a screenshot package) go.uber.org/zap Python

Pick this module to find, control and follow WiZ devices, fans included, from a Go service: it is the only Go client found that discovers lights and receives their pushes. Pick D3iot's driver when you want colours given in CIE XYZ on the bulb it has measured. Use pywizlight in Python or Home Assistant, when you want its own conversion of hue and saturation to the bulbs' channels (this module has a simpler one of its own, HSToRGBCW and RGBToRGBCW, not a measured colour model), or for per-head control of dual-head lamps (in its development branch).

Beyond the table, this module (v0.2.0) also has the configuration, reboot, factory reset and firmware-update calls; of the others, only pywizlight was checked for them (it has getModelConfig, getUserConfig, reboot and reset, and no firmware update).

Install

go get github.com/cB-Sigma/wiz@latest

Requires Go 1.22 or later.

Quick start

Find the lights on the LAN, read each one's module and switch it to a scene (from Example in example_test.go; it needs lights on the LAN, so it is compiled but not run):

ctx := context.Background()

// The MAC is the one this client reports as its own.
found, err := wiz.Discover(ctx, "255.255.255.255:38899", "02aabbccddee", time.Second)
if err != nil {
	return err
}
for mac, addr := range found {
	raw, err := wiz.Request(ctx, addr, wiz.MethodGetSystemConfig, nil, 3*time.Second)
	if err != nil {
		continue
	}
	cfg, _ := wiz.ParseSystemConfig(raw)
	class, _ := wiz.ClassOf(cfg.ModuleName)
	fmt.Println(mac, cfg.ModuleName, "is", class)

	if id, _ := wiz.SceneID("warm white"); wiz.HasScene(class, id) {
		_, err := wiz.Request(ctx, addr, wiz.MethodSetPilot, map[string]any{"sceneId": id}, 3*time.Second)
		fmt.Println("scene set:", err == nil)
	}
}

Telling a device's class from its module name (ExampleClassOf, run by go test):

for _, m := range []string{"ESP01_SHRGB1C_31", "ESP05_SHDW9_01", "ESP10_SOCKET_06", "ESP03_FANDIMS_31", "ESP20_DDTW1_01", "ESP99_XYZ_01"} {
	c, ok := wiz.ClassOf(m)
	fmt.Println(m, c, ok)
}
// Output:
// ESP01_SHRGB1C_31 rgb true
// ESP05_SHDW9_01 dw true
// ESP10_SOCKET_06 socket true
// ESP03_FANDIMS_31 fandim true
// ESP20_DDTW1_01 fantw true
// ESP99_XYZ_01 unknown false

Switching a ceiling fan on at speed 3, checked against the number of speeds the fan reports; its light is not touched (ExampleFanParams; it needs a fan on the LAN, so it is compiled but not run):

ctx := context.Background()
addr := "192.168.1.60:38899" // a fan module

model, _ := wiz.GetModelConfig(ctx, addr, 3*time.Second) // zero when the firmware has none
user, _ := wiz.GetUserConfig(ctx, addr, 3*time.Second)
on := true
params, err := wiz.FanParams{On: &on, Mode: wiz.FanModeNormal, Speed: 3}.Params(wiz.FanSpeedMax(model, user))
if err != nil {
	fmt.Println(err)
	return
}
_, err = wiz.Request(ctx, addr, wiz.MethodSetPilot, params, 3*time.Second)
fmt.Println("fan on:", err == nil)

ExampleFeaturesOf and ExampleKelvinRange (run by go test) show the features of a module and the colour-temperature range read from the configuration.

Pushes: open a UDP socket on port 38900, Register each device from it (again every 20 seconds or so), and run ServePush on it. Follow a device's address with PushedAddr, never with a push's source port: lights push from a port of their own. ServePush hands on syncPilot, firstBeat and updateOta (firmware-update progress) pushes; ignore methods your handler does not know.

Documentation

pkg.go.dev/github.com/cB-Sigma/wiz

Package What it does
wiz (module root) Request (one method, resent with a growing gap until the timeout; refusals as *DeviceError), Pilot/ParsePilot, SystemConfig/ParseSystemConfig, ClassOf/ClassOfTypeID/ClassOfConfig, FeaturesOf, FanParams/FanSpeedMax, RatioParams, HSToRGBCW/RGBToRGBCW, ModelConfig/UserConfig with GetModelConfig/GetUserConfig/KelvinRange, SetUserConfig, SetSystemConfig/SetModelConfig (raw, dangerous), GetWifiConfig, GetPower, Reboot, Reset, UpdateFirmware, Scenes/SceneID/SceneName/ScenesFor/HasScene, Discover, Register, ServePush, PushedAddr, LocalIPFor

Changes per version are in CHANGELOG.md.

Testing

go test -race ./...

The library's tests use a small fake light on the loopback interface. Discovery, registration and pushes against the full simulator are tested in wiz-sim.

Tests carry // Covers: SIG-... comments. These are requirement IDs of the compliance report of SigmaM2M, the oneM2M platform this module was written for; they have no meaning outside it.

Interop tested against

The automated tests run against a fake light and the simulator in wiz-sim, both written from the same descriptions as the client; that is not independent.

Checked by hand against a real WiZ colour bulb on a home LAN (October 2026, through SigmaM2M): colour, dimming at 20% and 100%, off and on, and scene selection. Discovery, pushes, tunable-white and dimmable-white bulbs and plugs have not been checked against real devices, and nothing added in v0.2.0 has (fans, dual-head ratio, setState, the configuration calls, reboot, reset, firmware update, power in the pilot): those follow the public descriptions and are tested only against the simulator.

  • wiz-sim: simulated WiZ lights, a plug and ceiling fans, as a Go package for tests and as a command.
  • lanbcast: the LAN broadcast helper used by Discover.

Status

v0.x; the API may change before v1.

Contributing

See CONTRIBUTING.md.

Security

See SECURITY.md.

Licence

Apache-2.0 (LICENSE). Copyright Abhinav Gautam. NOTICE lists the projects whose public descriptions supplied the protocol facts. WiZ is a trademark of its owner; the name is used only to say which devices this module talks to.

Documentation

Overview

Package wiz speaks the local UDP API of WiZ Wi-Fi lights, plugs and ceiling fans: JSON requests to port 38899 of the device with resends (Request), the light and fan state (Pilot, FanParams, RatioParams), the module classes (colour, tunable white, dimmable white, plug, fan with a dimmable or a tunable-white light) with their features (FeaturesOf) and built-in scenes, the system, model and user configuration (ParseSystemConfig, GetModelConfig, GetUserConfig, KelvinRange, FanSpeedMax, SetUserConfig), power readings (GetPower), maintenance (Reboot, Reset, UpdateFirmware), broadcast discovery (Discover), and push registration with the pushes devices send to port 38900 (Register, ServePush, PushedAddr). It needs no cloud account.

The local API is not published by its vendor; this package follows the behaviour public clients describe (see PROVENANCE.md). Where those descriptions stop (Wi-Fi setup of new devices, the meaning of some values), the package passes data through as sent and says so. Simulated devices for tests are in the separate module github.com/cB-Sigma/wiz-sim.

Example

Find the lights, read one and switch it to a scene. It needs lights on the LAN, so it is not run; github.com/cB-Sigma/wiz-sim runs the same steps against simulated lights.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/cB-Sigma/wiz"
)

func main() {
	ctx := context.Background()

	// The MAC is the one this client reports as its own.
	found, err := wiz.Discover(ctx, "255.255.255.255:38899", "02aabbccddee", time.Second)
	if err != nil {
		fmt.Println(err)
		return
	}
	for mac, addr := range found {
		raw, err := wiz.Request(ctx, addr, wiz.MethodGetSystemConfig, nil, 3*time.Second)
		if err != nil {
			fmt.Println(mac, err)
			continue
		}
		cfg, _ := wiz.ParseSystemConfig(raw)
		class, _ := wiz.ClassOf(cfg.ModuleName)
		fmt.Println(mac, cfg.ModuleName, "is", class)

		if id, _ := wiz.SceneID("warm white"); wiz.HasScene(class, id) {
			_, err := wiz.Request(ctx, addr, wiz.MethodSetPilot, map[string]any{"sceneId": id}, 3*time.Second)
			fmt.Println("scene set:", err == nil)
		}
	}
}

Index

Examples

Constants

View Source
const (
	DefaultKelvinMin = 2200
	DefaultKelvinMax = 6500
)

Default kelvin range for a light that reports none: openHAB's default.

View Source
const (
	DevicePort = 38899
	PushPort   = 38900
)

The WiZ local API: JSON objects in single UDP datagrams to port 38899 of the device, answered from that port. Pushes (syncPilot, firstBeat) go to port 38900 of the registered phone address.

View Source
const (
	MethodGetPilot        = "getPilot"
	MethodSetPilot        = "setPilot"
	MethodGetSystemConfig = "getSystemConfig"
	MethodGetPower        = "getPower"
	MethodRegistration    = "registration"
	MethodSyncPilot       = "syncPilot"
	MethodFirstBeat       = "firstBeat"

	// MethodSetState takes the params of setPilot but, unlike setPilot,
	// does not switch the light on.
	MethodSetState = "setState"
	// Configuration (see config.go).
	MethodGetModelConfig  = "getModelConfig"
	MethodGetUserConfig   = "getUserConfig"
	MethodGetWifiConfig   = "getWifiConfig"
	MethodSetUserConfig   = "setUserConfig"
	MethodSetSystemConfig = "setSystemConfig"
	MethodSetModelConfig  = "setModelConfig"
	// Maintenance (see maintenance.go). updateOta is also the method of
	// the progress messages a device sends during a firmware update.
	MethodReboot    = "reboot"
	MethodReset     = "reset"
	MethodUpdateOta = "updateOta"
)

Methods of the local API used here.

View Source
const (
	// CodeMethodNotFound: the device does not have the method, such as
	// getPower on a device without power metering.
	CodeMethodNotFound = -32601
	// CodeInvalidParams: a parameter is missing or out of range.
	CodeInvalidParams = -32602
)

Error codes devices answer with (JSON-RPC style).

View Source
const DefaultFanSpeedMax = 6

DefaultFanSpeedMax is the number of fan speeds assumed when the device does not report one (see FanSpeedMax).

Variables

View Source
var ErrDevice = errors.New("the device refused the request")

ErrDevice is wrapped by errors the device returned.

View Source
var ErrNoReading = errors.New("the answer carried no reading")

ErrNoReading is returned when an answer carries no value where one was expected, such as a getPower answer without power.

View Source
var Scenes = []Scene{
	{1, "Ocean"}, {2, "Romance"}, {3, "Sunset"}, {4, "Party"}, {5, "Fireplace"}, {6, "Cozy"},
	{7, "Forest"}, {8, "Pastel colors"}, {9, "Wake-up"}, {10, "Bedtime"}, {11, "Warm white"},
	{12, "Daylight"}, {13, "Cool white"}, {14, "Night light"}, {15, "Focus"}, {16, "Relax"},
	{17, "True colors"}, {18, "TV time"}, {19, "Plantgrowth"}, {20, "Spring"}, {21, "Summer"},
	{22, "Fall"}, {23, "Deep dive"}, {24, "Jungle"}, {25, "Mojito"}, {26, "Club"}, {27, "Christmas"},
	{28, "Halloween"}, {29, "Candlelight"}, {30, "Golden white"}, {31, "Pulse"}, {32, "Steampunk"},
	{33, "Diwali"}, {34, "White"}, {35, "Alarm"}, {36, "Snowy sky"}, {40, "Dim-to-warm"}, {1000, "Rhythm"},
}

Scenes are the built-in scene IDs of the WiZ local API with their names as the WiZ app shows them.

Functions

func AnswerAddr

func AnswerAddr(from *net.UDPAddr) string

AnswerAddr is a device's API address (host:port) taken from an answer to a request or to discovery: devices answer from their API port.

func Discover

func Discover(ctx context.Context, broadcast, phoneMAC string, wait time.Duration) (map[string]string, error)

Discover sends the discovery form of a registration to broadcast (host:port; "255.255.255.255:38899" also goes to the directed broadcast address of every LAN interface) three times, a second apart, and collects the answers until wait has passed or ctx ends. It returns each device's API address by normalised MAC.

func FanSpeedMax added in v0.2.0

func FanSpeedMax(model ModelConfig, user UserConfig) int

FanSpeedMax is the number of fan speeds of a fan module: fanSpeed of the model config (firmware 1.22 and later), else of the user config, else DefaultFanSpeedMax. A fanSpeed of 0, which lights without a fan report, counts as absent.

func GetPower added in v0.2.0

func GetPower(ctx context.Context, addr string, timeout time.Duration) (milliwatts float64, err error)

GetPower asks a metering device (a plug) for its power draw and returns it in milliwatts. A device without metering answers CodeMethodNotFound (a *DeviceError). Newer firmware also reports the draw in the pilot (Pilot.PC). The local API has no energy counter.

func GetWifiConfig added in v0.2.0

func GetWifiConfig(ctx context.Context, addr string, timeout time.Duration) (json.RawMessage, error)

GetWifiConfig asks a device for its Wi-Fi configuration and returns the result as sent. Its content is not publicly described (openHAB notes it as an encrypted string, unverified).

func HasScene

func HasScene(c Class, id int) bool

HasScene reports whether a class of light offers the scene.

func KelvinRange added in v0.2.0

func KelvinRange(model ModelConfig, user UserConfig) (min, max int, ok bool)

KelvinRange is the colour-temperature range of a light: the lowest and highest value of the first list present among the model config's extRange and cctRange, then the user config's extRange and cctRange (the order pywizlight reads them in; pass a zero ModelConfig when the device has no getModelConfig). ok is false, with DefaultKelvinMin and DefaultKelvinMax, when none is present.

Example
package main

import (
	"fmt"

	"github.com/cB-Sigma/wiz"
)

func main() {
	model, _ := wiz.ParseModelConfig([]byte(`{"cctRange":[2200,2700,6500,6500],"fanSpeed":0}`))
	min, max, ok := wiz.KelvinRange(model, wiz.UserConfig{})
	fmt.Println(min, max, ok)
	min, max, ok = wiz.KelvinRange(wiz.ModelConfig{}, wiz.UserConfig{})
	fmt.Println(min, max, ok)
}
Output:
2200 6500 true
2200 6500 false

func LocalIPFor

func LocalIPFor(dev *net.UDPAddr) string

LocalIPFor returns the local IPv4 address the route to dev uses: the address to register when none is configured. "" when there is no route.

func NormaliseMAC

func NormaliseMAC(s string) string

NormaliseMAC lower-cases a MAC address and drops separators; "" when it is not 12 hexadecimal digits.

func PushedAddr

func PushedAddr(from *net.UDPAddr, prev string) string

PushedAddr is a device's API address after a push from it. A light pushes from a port of its own, not from its API port, so only the IP is taken from the push (which keeps a changed DHCP lease current); the port stays the one in prev, the address the device was known at, or 38899 when prev has none. Taking the push's source port instead would send later requests to a port nothing listens on.

func RatioParams added in v0.2.0

func RatioParams(ratio int) (map[string]any, error)

RatioParams sets the split of a dual-head module's light between its up and down heads, 0 to 100, as setPilot params.

func Reboot added in v0.2.0

func Reboot(ctx context.Context, addr string, timeout time.Duration) error

Reboot restarts a device. The request is sent once, not resent: a resend could reach the device after it has restarted. The device is silent while it restarts and announces itself with a firstBeat push afterwards.

func Register

func Register(conn *net.UDPConn, dev *net.UDPAddr, phoneMAC, phoneIP string) error

Register asks the device at dev to push its state changes (syncPilot) and power-ups (firstBeat) to phoneIP, port 38900. It is sent from conn, the socket the pushes are read from, so the device's answer reaches that socket too. Devices forget a registration after a while; send it again every 20 seconds or so.

func RegistrationParams

func RegistrationParams(phoneMAC, phoneIP string, register bool) map[string]any

RegistrationParams are the params of a registration: phoneMac (12 hexadecimal digits), phoneIp (where pushes go) and register (true asks for pushes; false is the discovery form).

func Request

func Request(ctx context.Context, addr, method string, params map[string]any, timeout time.Duration) (json.RawMessage, error)

Request sends a message to a device and waits for the answer with the same method, resending with a growing gap (0.75 s, doubling, at most 3 s) until timeout: UDP loses datagrams and a bulb on busy Wi-Fi misses some. An error answer is returned as a *DeviceError.

func Reset added in v0.2.0

func Reset(ctx context.Context, addr string, timeout time.Duration) error

Reset sets a device back to its factory settings. Sent once, as Reboot. What the device keeps (its Wi-Fi network, its pairing) is not publicly described; expect to have to set it up again with the WiZ app.

func SceneID

func SceneID(name string) (int, bool)

SceneID finds a scene by name (case, spaces and hyphens ignored, so "wake up" is Wake-up) or by its number.

func SceneName

func SceneName(id int) string

SceneName returns a scene's name; "" for 0 (no scene) and an unknown ID as "scene <id>".

func ScenesFor

func ScenesFor(c Class) []string

ScenesFor lists the scene names a class of light offers. It is nil for plugs and for the lights of fan modules, whose scene lists are not publicly described.

func ServePush

func ServePush(conn *net.UDPConn, phoneMAC string, handle func(Push)) error

ServePush reads pushes from conn until conn is closed and calls handle for each, in order. A syncPilot is acknowledged to its sender as phoneMAC before handle runs, echoing its id and env as the vendor's own library does; datagrams that are not pushes (answers to requests sent from conn, for example) are skipped. It returns the read error that ended it.

func SetModelConfig added in v0.2.0

func SetModelConfig(ctx context.Context, addr string, params map[string]any, timeout time.Duration) (json.RawMessage, error)

SetModelConfig sends setModelConfig with params as given (the getModelConfig keys; the vendor's own library requires confTs, pwmFreq, pwmRange, wcr, nowc, cctRange and renderFactor) and returns the result. Dangerous for the same reason as SetSystemConfig.

func SetSystemConfig added in v0.2.0

func SetSystemConfig(ctx context.Context, addr string, params map[string]any, timeout time.Duration) (json.RawMessage, error)

SetSystemConfig sends setSystemConfig with params as given and returns the result. Dangerous: it changes factory and calibration settings (such as env, moduleName, ewf, pwmConf, drvConf, fs and systemConfigTs, the params the vendor's own library sends), and a wrong value can leave the driver misconfigured or the device unusable. The package offers no helpers for it because the safe values are not publicly described.

func SetUserConfig added in v0.2.0

func SetUserConfig(ctx context.Context, addr string, u UserConfigParams, timeout time.Duration) error

SetUserConfig changes a device's user configuration.

func UpdateFirmware added in v0.2.0

func UpdateFirmware(ctx context.Context, addr, fw string, force bool, timeout time.Duration) (json.RawMessage, error)

UpdateFirmware asks a device to update its firmware (updateOta) to the version fw, or to the version the vendor offers when fw is "" (sent as "default"); force is sent as 1 or 0, as the vendor's own library does. The device fetches the image itself, presumably from the vendor's servers: an image of one's own cannot be given. The request is sent once, and the result is returned as sent. Progress arrives as updateOta pushes at the address registered for pushes (Push.UpdateStatus, whose values are not publicly described); getSystemConfig reports fwOtaStatus, and the new fwVersion once the device has restarted.

func WithPort

func WithPort(addr string, port int) string

WithPort adds the default port to an address without one.

Types

type Class

type Class string

Class is what a WiZ module can do, told from its module name.

const (
	ClassRGB     Class = "rgb"    // colour, tunable white, dimming, scenes
	ClassTW      Class = "tw"     // tunable white, dimming, scenes
	ClassDW      Class = "dw"     // dimming, a few scenes
	ClassSocket  Class = "socket" // on and off, power where reported
	ClassFanDim  Class = "fandim" // ceiling fan with a dimmable light
	ClassFanTW   Class = "fantw"  // ceiling fan with a tunable-white light
	ClassUnknown Class = "unknown"
)

The classes. The module name's second underscore-separated segment carries the class ("ESP01_SHRGB1C_31": RGB; "ESP56_SHTW3_01": tunable white; "ESP05_SHDW9_01": dimmable white; "ESP10_SOCKET_06": plug; "ESP03_FANDIMS_31": fan with a dimmable light; "ESP20_DDTW1_01": fan with a tunable-white light).

func ClassOf

func ClassOf(module string) (c Class, ok bool)

ClassOf tells the class of a module name. The second segment is checked for RGB, DDTW (fan, tunable white), TW, SOCKET and FANDIM (fan, dimmable), in that order, then DW. ok is false for a name that is not of that form or holds none of them; pywizlight treats such a module as dimmable white, this package leaves the choice to the caller.

Example
package main

import (
	"fmt"

	"github.com/cB-Sigma/wiz"
)

func main() {
	for _, m := range []string{"ESP01_SHRGB1C_31", "ESP05_SHDW9_01", "ESP10_SOCKET_06", "ESP03_FANDIMS_31", "ESP20_DDTW1_01", "ESP99_XYZ_01"} {
		c, ok := wiz.ClassOf(m)
		fmt.Println(m, c, ok)
	}
}
Output:
ESP01_SHRGB1C_31 rgb true
ESP05_SHDW9_01 dw true
ESP10_SOCKET_06 socket true
ESP03_FANDIMS_31 fandim true
ESP20_DDTW1_01 fantw true
ESP99_XYZ_01 unknown false

func ClassOfConfig added in v0.2.0

func ClassOfConfig(c SystemConfig) (Class, bool)

ClassOfConfig tells the class from a system configuration: from the module name when there is one, else from typeId.

func ClassOfTypeID added in v0.2.0

func ClassOfTypeID(typeID int) (Class, bool)

ClassOfTypeID tells the class from getSystemConfig's typeId, for old firmware (such as 1.8.0) that reports no module name. Only typeId 0 (dimmable white) is publicly described; ok is false for the others.

type DeviceError added in v0.2.0

type DeviceError struct {
	Method  string
	Code    int // such as CodeMethodNotFound or CodeInvalidParams
	Message string
}

DeviceError is the error object a device answered with. It wraps ErrDevice.

func (*DeviceError) Error added in v0.2.0

func (e *DeviceError) Error() string

func (*DeviceError) Unwrap added in v0.2.0

func (e *DeviceError) Unwrap() error

Unwrap returns ErrDevice.

type FanMode added in v0.2.0

type FanMode int

FanMode is a fan module's mode (the fanMode key).

const (
	FanModeNormal FanMode = 1
	FanModeBreeze FanMode = 2 // speed varies, like a breeze
)

The fan modes.

type FanParams added in v0.2.0

type FanParams struct {
	On      *bool   // fanState: 1 on, 0 off
	Mode    FanMode // fanMode; 0 leaves it
	Speed   int     // fanSpeed, 1 to the module's maximum; 0 leaves it
	Reverse *bool   // fanRevrs: 1 reverse, 0 forward
}

FanParams sets a fan module's fan, as setPilot (or setState) params. Zero fields are left out, so the device keeps their value. The fan is independent of the module's light: switching one does not switch the other.

Example

Switch a ceiling fan on at speed 3 of the speeds it reports; its light is not touched.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/cB-Sigma/wiz"
)

func main() {
	ctx := context.Background()
	addr := "192.168.1.60:38899" // a fan module

	model, _ := wiz.GetModelConfig(ctx, addr, 3*time.Second) // zero when the firmware has none
	user, _ := wiz.GetUserConfig(ctx, addr, 3*time.Second)
	on := true
	params, err := wiz.FanParams{On: &on, Mode: wiz.FanModeNormal, Speed: 3}.Params(wiz.FanSpeedMax(model, user))
	if err != nil {
		fmt.Println(err)
		return
	}
	_, err = wiz.Request(ctx, addr, wiz.MethodSetPilot, params, 3*time.Second)
	fmt.Println("fan on:", err == nil)
}

func (FanParams) Params added in v0.2.0

func (f FanParams) Params(maxSpeed int) (map[string]any, error)

Params returns the params, checking the speed against maxSpeed (from FanSpeedMax; DefaultFanSpeedMax when maxSpeed is 0 or less). Home Assistant sends FanModeNormal with a speed, and FanModeBreeze alone. To stop the fan send On false; openHAB's speed 0 means the same, but this package does not send speed 0.

type Features added in v0.2.0

type Features struct {
	Brightness bool // dimming
	Color      bool // r, g, b (and c, w)
	ColorTemp  bool // temp
	// Effects: public clients offer scenes (sceneId, with speed) for it.
	// Dimmable-white modules have them only when the second segment holds
	// SH or DH; fan modules with a dimmable light have none.
	Effects    bool
	Fan        bool // fanState, fanSpeed
	FanBreeze  bool // fanMode 2
	FanReverse bool // fanRevrs
	// DualHead: two light heads (DH in the second segment), whose split is
	// set with ratio (RatioParams). Some dual-head lights do not say so in
	// their name; Home Assistant also treats a device whose pilot carries
	// ratio (Pilot.Ratio not nil) as one.
	DualHead bool
}

Features are what a module offers, told from its module name the way public clients tell it (see PROVENANCE.md).

func FeaturesOf added in v0.2.0

func FeaturesOf(module string) Features

FeaturesOf tells a module's features from its name. A module ClassOf does not know has none.

Example
package main

import (
	"fmt"

	"github.com/cB-Sigma/wiz"
)

func main() {
	f := wiz.FeaturesOf("ESP03_FANDIMS_31")
	fmt.Println("fan:", f.Fan, "breeze:", f.FanBreeze, "reverse:", f.FanReverse, "colour temperature:", f.ColorTemp)
	fmt.Println("dual head:", wiz.FeaturesOf("ESP20_DHRGB_01").DualHead)
}
Output:
fan: true breeze: true reverse: true colour temperature: false
dual head: true

type Message

type Message struct {
	Method string          `json:"method"`
	Env    string          `json:"env,omitempty"`
	ID     any             `json:"id,omitempty"`
	Params map[string]any  `json:"params,omitempty"`
	Result json.RawMessage `json:"result,omitempty"`
	Error  *struct {
		Code    int    `json:"code"`
		Message string `json:"message"`
	} `json:"error,omitempty"`
}

Message is one datagram of the local API.

type ModelConfig added in v0.2.0

type ModelConfig struct {
	PS       *int  // ps
	PwmFreq  *int  // pwmFreq
	PwmRange []int // pwmRange
	WCR      *int  // wcr: white-to-colour ratio
	NoWC     *int  // nowc: number of white channels
	// CCTRange lists colour temperatures in kelvin, such as [2200, 2700,
	// 6500, 6500]; the range is its lowest to its highest (KelvinRange).
	CCTRange []int
	ExtRange []int // extRange, where present: the extended kelvin range
	FanSpeed *int  // fanSpeed: the number of fan speeds of a fan module
	PM       *int  // pm
	// HasAdjMinDim and HasTapSensor are hasAdjMinDim and hasTapSensor.
	HasAdjMinDim *bool
	HasTapSensor *bool
	ConfTs       *int // confTs
	MinDimLevel  *int // minDimLevel
	// Raw is every key as sent, including those not typed here:
	// renderFactor (a list in answers, a string in the vendor library's
	// setModelConfig), i2cTapSensor, drvIface, wizc1 and wizc2.
	Raw map[string]any
}

ModelConfig is a getModelConfig result (firmware 1.22 and later; older firmware answers CodeMethodNotFound). Fields the answer lacks stay nil. Numbers are accepted for the flags, as devices send them so.

func GetModelConfig added in v0.2.0

func GetModelConfig(ctx context.Context, addr string, timeout time.Duration) (ModelConfig, error)

GetModelConfig asks a device for its model configuration.

func ParseModelConfig added in v0.2.0

func ParseModelConfig(b []byte) (ModelConfig, error)

ParseModelConfig reads a getModelConfig result.

type Pilot

type Pilot struct {
	MAC     string   `json:"mac,omitempty"`
	State   *bool    `json:"state,omitempty"`
	Dimming *float64 `json:"dimming,omitempty"`
	R       *float64 `json:"r,omitempty"`
	G       *float64 `json:"g,omitempty"`
	B       *float64 `json:"b,omitempty"`
	C       *float64 `json:"c,omitempty"`
	W       *float64 `json:"w,omitempty"`
	Temp    *float64 `json:"temp,omitempty"`
	SceneID *float64 `json:"sceneId,omitempty"`
	Speed   *float64 `json:"speed,omitempty"`
	// Fan modules (ClassFanDim, ClassFanTW): FanState 0 off, 1 on;
	// FanMode 1 normal, 2 breeze; FanSpeed 1 to FanSpeedMax; FanRevrs 0
	// forward, 1 reverse. The light of a fan module keeps its own State,
	// Dimming and Temp.
	FanState *float64 `json:"fanState,omitempty"`
	FanMode  *float64 `json:"fanMode,omitempty"`
	FanSpeed *float64 `json:"fanSpeed,omitempty"`
	FanRevrs *float64 `json:"fanRevrs,omitempty"`
	// Ratio splits the light of a dual-head module between its up and
	// down heads, 0 to 100.
	Ratio *float64 `json:"ratio,omitempty"`
	// PC is the power draw in milliwatts that newer firmware of metering
	// devices puts in the pilot.
	PC *float64 `json:"pc,omitempty"`
	// Raw is every key as sent.
	Raw map[string]any `json:"-"`
}

Pilot is the light state of getPilot, setPilot and syncPilot. Fields the device leaves out stay nil.

func ParsePilot

func ParsePilot(b []byte) (Pilot, error)

ParsePilot reads a pilot object.

type Push

type Push struct {
	// Method is MethodSyncPilot, MethodFirstBeat or MethodUpdateOta.
	// Handlers should ignore methods they do not know: later versions may
	// hand on more kinds.
	Method string
	// MAC is the device's MAC address, normalised; "" when the push did not
	// carry a valid one (updateOta progress need not carry one: tell the
	// device by From's IP).
	MAC string
	// Pilot is the state a syncPilot carries.
	Pilot Pilot
	// From is the datagram's source. A device pushes from a port of its
	// own, not from its API port: use PushedAddr to follow its address.
	From *net.UDPAddr

	// FwVersion is the firmware version a firstBeat carries; MatterVersion
	// and ProductID are carried by newer devices only.
	FwVersion     string
	MatterVersion string
	ProductID     *int
	// UpdateStatus is the number an updateOta progress push carries. Its
	// values are not publicly described.
	UpdateStatus *int
	// Params are the push's params as sent.
	Params map[string]any
}

Push is one datagram a device pushed to the registered address.

type RGBCW added in v0.2.0

type RGBCW struct {
	R, G, B, C, W int
}

RGBCW is a setPilot colour.

func HSToRGBCW added in v0.2.0

func HSToRGBCW(hue, sat float64) (RGBCW, error)

HSToRGBCW converts a hue (degrees, any value; taken modulo 360) and a saturation (0 to 1) to the five channels: at saturation 1 the pure hue on r, g and b with the white LEDs off; at 0 both white LEDs full and r, g, b off; in between, the hue scaled by the saturation and the white LEDs by the rest.

Example

A hue and saturation from an app become the five channels of setPilot.

package main

import (
	"fmt"

	"github.com/cB-Sigma/wiz"
)

func main() {
	c, _ := wiz.HSToRGBCW(30, 0.8) // orange, a little washed out
	fmt.Printf("%+v\n", c)
	fmt.Println(len(c.Params()), "params")
}
Output:
{R:204 G:102 B:0 C:51 W:51}
5 params

func RGBToRGBCW added in v0.2.0

func RGBToRGBCW(r, g, b int) (RGBCW, error)

RGBToRGBCW moves the grey part of an RGB colour (its smallest channel) to the white LEDs, which are brighter and whiter than mixing r, g and b: (255, 128, 128) becomes r 127, g 0, b 0 with both white LEDs at 128. Channels outside 0 to 255 are refused.

func (RGBCW) Params added in v0.2.0

func (x RGBCW) Params() map[string]any

Params returns the setPilot params for the colour.

type Scene

type Scene struct {
	ID   int
	Name string
}

Scene is a built-in scene (light mode) of WiZ lights.

type SystemConfig

type SystemConfig struct {
	MAC        string `json:"mac"`
	ModuleName string `json:"moduleName"`
	FwVersion  string `json:"fwVersion"`
	TypeID     *int   `json:"typeId,omitempty"`
	HomeID     *int   `json:"homeId,omitempty"`
	RoomID     *int   `json:"roomId,omitempty"`

	// The fields below are filled by ParseSystemConfig only, from the keys
	// in brackets, when the answer has them; numbers are accepted for the
	// flags. Their meaning beyond the name is not publicly described.
	HomeLock    *bool  `json:"-"` // homeLock
	PairingLock *bool  `json:"-"` // pairingLock
	Lock        *bool  `json:"-"` // lock
	GroupID     *int   `json:"-"` // groupId
	Ping        *int   `json:"-"` // ping
	FwOtaStatus *int   `json:"-"` // fwOtaStatus: firmware update state, values undocumented
	Region      string `json:"-"` // rgn
	EWFHex      string `json:"-"` // ewfHex
	// WhiteToColorRatio and WhiteChannels come from drvConf
	// [ratio, channels], which firmware before 1.22 reports here instead of
	// in getModelConfig (wcr, nowc).
	WhiteToColorRatio *int `json:"-"`
	WhiteChannels     *int `json:"-"`
}

SystemConfig is the part of a getSystemConfig answer this package reads.

func ParseSystemConfig

func ParseSystemConfig(b []byte) (SystemConfig, error)

ParseSystemConfig reads a getSystemConfig result; MAC is normalised ("" when it is not a MAC address).

type UserConfig added in v0.2.0

type UserConfig struct {
	FadeIn    *int  // fadeIn
	FadeOut   *int  // fadeOut
	FadeNight *bool // fadeNight
	DftDim    *int  // dftDim: default dimming
	PwmRange  []int // pwmRange
	// WhiteRange and ExtRange are kelvin ranges [min, max]; CCTRange is
	// read where a device reports it here.
	WhiteRange []int
	ExtRange   []int
	CCTRange   []int
	OpMode     *int // opMode
	// PO is po. Its meaning is not publicly described.
	PO       *bool
	FanSpeed *int // fanSpeed: the number of fan speeds, on older firmware
	// Raw is every key as sent.
	Raw map[string]any
}

UserConfig is a getUserConfig result. Fields the answer lacks stay nil.

func GetUserConfig added in v0.2.0

func GetUserConfig(ctx context.Context, addr string, timeout time.Duration) (UserConfig, error)

GetUserConfig asks a device for its user configuration.

func ParseUserConfig added in v0.2.0

func ParseUserConfig(b []byte) (UserConfig, error)

ParseUserConfig reads a getUserConfig result.

type UserConfigParams added in v0.2.0

type UserConfigParams struct {
	WhiteRange *[2]int // whiteRange: kelvin [min, max]
	ExtRange   *[2]int // extRange: extended kelvin [min, max]
	PwmRange   *[2]int // pwmRange: [min, max]
	DftDim     *int    // dftDim: default dimming, 1 to 100
	// StartupMode is sent as given when not empty; its values are not
	// publicly listed.
	StartupMode  string
	UserConfigTs int // userConfigTs
}

UserConfigParams are the setUserConfig params the vendor's own library describes. Nil fields are left out; UserConfigTs is always sent (0 by default, as that library does).

func (UserConfigParams) Params added in v0.2.0

func (u UserConfigParams) Params() (map[string]any, error)

Params returns the params. Ranges must not be negative or reversed.

Jump to

Keyboard shortcuts

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