tplink

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: 30 Imported by: 0

README

Clients for the local protocols of TP-Link Kasa and Tapo smart-home devices in pure Go: the Kasa legacy protocol, KLAP v1 and v2 over HTTP and HTTPS, securePassthrough, the camera and hub HTTPS transports and the 20002 discovery, with typed helpers for plugs, strips, dimmers, bulbs, light strips, hubs and cameras; not affiliated with TP-Link.

Go Reference test Go

It talks to devices on the LAN: the Kasa legacy protocol on port 9999 (TCP requests and UDP discovery), KLAP v1 and v2 over HTTP and HTTPS, the older Tapo securePassthrough transport, the HTTPS transport of Tapo cameras, doorbells and the H200 hub, the Kasa camera transport, the plain HTTPS transport of older robot vacuum firmware, Tapo hubs and power strips with their children, and the UDP 20002 discovery probe. Typed helpers cover what the devices do beyond switching. KLAP, securePassthrough and camera devices need the owner's account (cameras: the device's local user), but no cloud connection. Standard library and lanbcast only, no cgo. It was written for SigmaM2M, a oneM2M platform, whose TP-Link adapter is built on it.

Features

Feature Status
Kasa legacy protocol over TCP 9999, UDP discovery on 9999 yes
KLAP v2 (Tapo, some Kasa) and v1 (Kasa on newer firmware), with the legacy JSON inside for Kasa; the account and blank credentials tried from one handshake yes
KLAP over HTTPS (newer firmware, port 4433; InsecureHTTP for the self-signed certificate) yes, since v0.2.0
More accounts to try, such as a vendor setup account, from the caller (KLAPAuthsWith, AESLoginsWith) yes; none is shipped
securePassthrough with login version 1 and 2 yes
HTTPS transport of Tapo cameras, doorbells and the H200 hub: the nonce login with SHA-256 or MD5 password hashes, signed and numbered requests, the plain login of older firmware (SSLAESClient); camera requests (CamGet, CamDeviceInfo) and H200 children (CamChildList, CamControlChild) yes, since v0.2.0
Kasa cameras (KC series, port 10443, LinkieClient) and the plain HTTPS transport of older robot vacuum firmware (SSLClient) yes, since v0.2.0
Tapo request family, hub and strip children (paging, control_child) yes
multipleRequest batching with the device's limits and fallbacks (MultiCall, MultiCallChild), component negotiation (Components, ChildComponents), paged lists (SmartList) yes, since v0.2.0
Kasa helpers (KasaDevice, for 9999, KLAP and camera transports, strip outlets by child ID): energy meter readings in both firmware units, day and month energy and runtime statistics, schedules, countdowns and away mode (add, edit, delete), dimmer transitions, fades and ramp rate, bulb and light-strip light state with transitions, light strip effects, LED, name, reboot, factory reset, cloud and firmware information, Wi-Fi scan and join yes, since v0.2.0
Tapo helpers (TapoDevice, a device or a child): typed device information (plugs, bulbs, hub sensors), switching, lights, transitions, presets, light effects of bulbs and strips, energy use, readings and hourly, daily and monthly history, device use, rule lists, auto-off, LED, firmware check, update and progress, automatic updates, Wi-Fi scan, set-up onto a network with the account (WifiJoin), account change, reboot, factory reset, button and sensor logs yes, since v0.2.0
UDP 20002 discovery probe and answer, with the answer's encrypted part decrypted (TapoFound.Decrypted) and the URL to use (TapoFound.BaseURL) yes; the encrypted part since v0.2.0
Colour-temperature ranges Kasa by model table; Tapo from get_device_info
Changing Tapo schedules and countdowns, the TPAP login, local Kasa firmware flashing, camera-specific helpers, the cloud API no; see "Not yet"

Compared from each project's source at the version named, on 2026-10-11. Check the projects themselves before relying on a row.

this module fabiankachlock/tapo-api v1.4.0 kabukky/tapogo (2024-03-04) cloudkucooland/go-kasa (2026-08-29) python-kasa 0.11.0.1 (Python)
Kasa legacy protocol (9999) and its UDP discovery yes no no yes yes
KLAP v2 (Tapo) yes, HTTP and HTTPS yes yes no yes, HTTP and HTTPS
KLAP v1 (Kasa on newer firmware) yes no no no yes
securePassthrough (older Tapo firmware) yes, login v1 and v2 no no no yes
Cameras, doorbells, H200 hub (HTTPS transport) yes, transport and generic requests no no no yes, with camera modules
Kasa cameras, robot vacuums transports no no no yes, with device modules
20002 discovery yes, with the encrypted part no no no yes, with the encrypted part
Hub and strip children yes, typed sensors yes, typed (T300, T31x) no Kasa strips yes
multipleRequest, typed device helpers yes yes no Kasa models yes
Energy history Kasa day and month; Tapo hourly, daily, monthly Tapo no Kasa Kasa day and month
Schedules and countdowns Kasa read and write; Tapo read no no Kasa read Kasa read and delete
Firmware update Tapo check, update, progress; Kasa list no no no Tapo
Wi-Fi set-up Kasa and Tapo no no Kasa Kasa, Tapo, cameras
Vendor setup accounts caller-supplied no no n/a built in
Device simulators for tests yes, separate module no no no in-process fakes from recorded fixtures
Interop evidence against python-kasa both ways (below) none stated none stated none stated the reference, recorded fixtures
Go version, dependencies 1.22; lanbcast 1.20; none 1.21; none 1.25; a TUI and CLI stack n/a
Licence Apache-2.0 MIT Apache-2.0 BSD-2-Clause GPL-3.0

Pick this module when you need one Go client for every local transport a mixed Kasa and Tapo home uses, including discovery, the older firmware, cameras and hubs, with typed helpers and simulators to test against. Pick tapo-api if you prefer its per-model Tapo types and need nothing but KLAP v2 devices, and go-kasa for Kasa legacy devices with its command-line tool. python-kasa is still ahead in camera-specific modules (pan and tilt, detection settings, streams), robot vacuum modules, built-in light effect definitions and the number of firmware versions recorded from real devices; use it outside Go or when those matter.

Install

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

Requires Go 1.22 or later.

Quick start

import "github.com/cB-Sigma/tplink"

found, _ := tplink.TapoDiscover(ctx, "255.255.255.255:20002", 3*time.Second)
c := &tplink.KLAPClient{Base: "http://" + found[0].Host, Auths: tplink.KLAPAuths(email, password),
	HTTP: &http.Client{Timeout: 5 * time.Second}}
info, err := c.Call(ctx, "get_device_info", nil)
_, err = c.Call(ctx, "set_device_info", map[string]any{"device_on": true})

// A Kasa device on the legacy protocol needs no account:
m, err := tplink.KasaRequest(ctx, "192.168.1.40:9999",
	map[string]any{"system": map[string]any{"get_sysinfo": map[string]any{}}}, 3*time.Second)

// Typed helpers, on any transport:
plug := tplink.TapoDevice{Caller: c}
fw, _ := plug.LatestFirmware(ctx)
hours, _ := plug.EnergyData(ctx, dayStart, dayStart.Add(23*time.Hour), tplink.EnergyHourly)
kasa, _, _ := tplink.NewKasaDevice(ctx, tplink.KasaConn{Addr: "192.168.1.40:9999"})
days, _ := kasa.EmeterDays(ctx, 2026, 10)
id, _ := kasa.AddRule(ctx, tplink.KasaCountdown, tplink.KasaRule{Name: "off", Enable: true, Delay: 600, Action: tplink.KasaActionOff})

Use TapoFound.Protocol() and TapoFound.HTTPS to choose between KLAPClient, AESClient and SSLAESClient, and TapoFound.BaseURL() for the URL. Example and ExampleKasaRequest in example_test.go show the whole flow (they need devices, so they are not run); ExampleEncrypt runs. tplink-sim runs them, and every helper, against simulated devices.

Documentation

API reference: https://pkg.go.dev/github.com/cB-Sigma/tplink

Package What it does
tplink (module root) Kasa: KasaRequest, KasaDiscover, Encrypt/Decrypt/Frame/ReadFrame, KasaError, KasaConn, KasaCaller, KasaDevice (NewKasaDevice, Query, Emeter, EmeterDays, EmeterMonths, RuntimeDays, Rules, AddRule, EditRule, DimTo, SetLight, SetLightingEffect, WifiJoin, ...), KasaRule, KasaModuleError, IsKasaUnsupported. KLAP: KLAPClient (Call, KasaCall, Send, Handshake, Matched, BadSignatures), KLAPAuths, KLAPAuthsWith, Credential, AuthHash, AuthHashV1, NewSession, KLAPHTTPSPort, InsecureHTTP. securePassthrough: AESClient, AESLogins, AESLoginsWith. Cameras and H200: SSLAESClient, CamGet, CamDeviceInfo, CamChildList, CamControlChild, SSLAESConfirm, SSLAESDigest, SSLAESKeys, SSLAESTag. Kasa cameras and robot vacuums: LinkieClient, SSLClient. Tapo: SmartCaller, MultiCall, MultiCallChild, SmartList, Components, ChildComponents, ChildList, ControlChild, TapoDevice (Info, SetLight, EnergyData, Rules, LatestFirmware, StartFirmwareUpdate, WifiJoin, Children, TriggerLogs, ...), SmartError, IsUnsupported. Discovery: TapoDiscover, TapoProbe, CheckTapoProbe, ParseTapoAnswer, DecryptTapoAnswer, SealTapoDiscovery, TapoFound.BaseURL. Kelvin ranges: KasaKelvinRange, TapoKelvinRange
interop (nested module, tests only) these clients against a device that answers from python-kasa's recorded fixtures with python-kasa's own crypto, in a container

Changes per version are in CHANGELOG.md.

Testing

go test -race ./...
cd interop && SIGMA_TPLINK_INTEROP=1 go test -v ./...   # needs Docker

Tests carry // Covers: SIG-... comments: requirement IDs of the SigmaM2M project's compliance report, with no meaning outside it. The client tests against simulated devices are in tplink-sim.

interop/ is a nested module with its own go.mod. Its tests build an image from interop/peer (python:3.12.10-slim with python-kasa 0.11.0.1 from PyPI and the fixtures of its 0.11.0.1 tag) and are skipped unless SIGMA_TPLINK_INTEROP=1 is set and Docker answers.

Interop tested against
  • python-kasa 0.11.0.1 (2026-10-11, Docker Desktop on arm64; interop): these clients against a device that answers from python-kasa's recorded fixtures and encrypts with python-kasa's own transport code (interop/peer/device.py: XorEncryption, KlapEncryptionSession and the KLAP v1 and v2 hash functions, AesEncyptionSession and the login hashing of AesTransport; the HTTP handling is the script's). Passed:
    • legacy protocol against the HS110(EU) 1.2.5 fixture: get_sysinfo, set_relay_state (decoded by the device), the energy meter, an unknown method, UDP discovery;
    • KLAP v2 against P110(UK) 1.3.0: handshake, get_device_info, set_device_info, several requests on one session, get_energy_usage, an unknown method, answer signatures all valid, a wrong password refused;
    • KLAP v1 with the Kasa JSON against HS100(UK) hardware 4.1;
    • a P300(EU) strip's three children read page by page, and a request to one child;
    • securePassthrough with login version 2 and 1 against P100(US) 1.1.3, the login checked with python-kasa's hashing; a wrong password refused;
    • the 20002 probe passed the device's checks (header as python-kasa builds it, CRC); the answers recorded in the P110, P100 and HS100 fixtures were read with their model, type and protocol.
  • Added in v0.2.0, same image (python:3.12.10-slim, python-kasa 0.11.0.1 and its fixtures), 2026-10-11, all passed:
    • Kasa helpers against recorded answers: the HS110(EU) 1.2.5 energy meter in the older units (V, A, W, kWh), the HS220(US) 1.5.7 dimmer parameters and its missing energy meter (a module-level error), the KL130(EU) 1.8.8 cloud information and firmware list, the KL430(US) hardware 2.0 light strip's module names (energy meter, light state and details, schedule rules, next action);
    • Tapo helpers against recorded answers: MultiCall with an unknown method in the batch and the rest of the batch asked one by one, component negotiation, typed information, energy readings, energy use, device use, firmware check and state, automatic updates, auto-off read and changed, schedule and countdown lists, Wi-Fi scan (P110(AU) 1.3.1); transitions, light effects and presets (L530E(EU) hardware 3.0 1.1.6); a light strip effect and presets paged to their end (L900-5(EU) 1.1.0); a hub's T315 sensor typed and the children's components (H100(EU) 1.5.5);
    • the 20002 answer's encrypted part: the peer seals it and first checks that python-kasa's own discovery decryption reads it, then TapoDiscover decrypts it;
    • the camera transport against a device whose confirm, digest, keys and request tags are computed with python-kasa's SslAesTransport functions: a recorded C210(EU) hardware 2.0 camera read, a setting read, changed and read again, every request's tag accepted, a wrong password refused; a recorded H200(EU) 1.3.6 hub's children;
    • KLAP v2 over HTTPS (P110(UK) 1.3.0), and a client that checks certificates refusing the self-signed one;
    • the Kasa camera transport with python-kasa's XorEncryption against a recorded EC60(US) camera (its sysinfo nested once more, read unnested; a module error passed through), a wrong password refused;
    • the plain HTTPS transport with python-kasa's login hashing against a recorded RV30 Max(US) robot vacuum, a wrong password refused;
    • the camera transport's hashes match values computed with python-kasa's functions (TestSSLAESVectors, a unit test).
  • python-kasa 0.11.0.1's client against the simulators, in tplink-sim.
  • get_energy_data (Tapo energy history) is not used by python-kasa, so it was checked only against the simulator; its request and answer fields follow tapo-api v1.4.0 and the tapo Rust crate (see PROVENANCE.md).
  • Not yet: a real Kasa or Tapo device. No open-source network emulator of these devices was found; python-kasa tests with in-process fakes, so the device side here is a script on python-kasa's code.

Not yet

Item Why
Changing Tapo schedules, countdowns and away rules (reading them is supported) python-kasa 0.11.0.1 only reads them, so there is no open-source client to check the write requests against; Call reaches the device's methods
The TPAP login of the newest firmware python-kasa 0.11.0.1 does not implement it (it only names it), and no other open description was found to build and check against
Flashing Kasa legacy firmware locally (download and flash requests) no open-source client we checked does it, a wrong request can leave a device unusable, and it needs real hardware to test; FirmwareList reads what the cloud offers
Camera-specific helpers (pan and tilt, detection, recording, streams) and robot vacuum helpers the transports and generic requests are supported (CamGet, SSLClient); typed helpers for these families are larger than this release, and video belongs outside this module
Built-in light strip effect definitions python-kasa's tables are GPL-3.0 data and are not copied; callers pass the device's own effect description
The TP-Link cloud API needs a TP-Link account and works against TP-Link's servers, not the LAN
Checks against real devices needs hardware
  • tplink-sim: simulated Kasa and Tapo devices, cameras and hubs, and a 20002 responder, as a Go package and a command.
  • lanbcast: the broadcast helper discovery uses.

Status

v0.x: the API may change before v1.

Contributing

See CONTRIBUTING.md.

Security

See SECURITY.md to report a vulnerability privately.

Licence

Apache-2.0 (see LICENSE and NOTICE). Copyright 2026 Abhinav Gautam. TP-Link, Kasa and Tapo are trademarks of their owner; the names are used only to say which devices this module talks to.

Documentation

Overview

Package tplink speaks the local protocols of TP-Link Kasa and Tapo smart-home devices: the Kasa legacy protocol on port 9999 (KasaRequest, KasaDiscover), KLAP v1 and v2 over HTTP and HTTPS (KLAPClient, with KLAPAuths to try the account and blank credentials, and KLAPAuthsWith for more accounts the caller supplies), the older Tapo securePassthrough transport (AESClient), the HTTPS transport of Tapo cameras, doorbells and the H200 hub (SSLAESClient), the Kasa camera transport (LinkieClient), the plain HTTPS transport of older robot vacuum firmware (SSLClient), the Tapo request family with batching (MultiCall), component negotiation (Components) and hub and strip children (ChildList, ControlChild), the UDP 20002 discovery probe with its encrypted part (TapoDiscover), and the colour-temperature ranges of bulbs.

Typed helpers cover what the devices do beyond switching: KasaDevice (energy meter and runtime statistics, schedules, countdowns and away mode, dimmer transitions and fades, light state with transitions, light strip effects, LED, name, reboot, cloud and firmware information, Wi-Fi scan and join) and TapoDevice (lights, transitions, presets and effects, energy use, history and readings, rule lists, auto-off, LED, firmware update, Wi-Fi scan and set-up, hub sensors and button logs).

It needs the owner's TP-Link account for KLAP and securePassthrough devices (cameras: the device's local user), and no cloud connection. It ships no vendor setup account or default login.

TP-Link does not publish these protocols; this package follows public descriptions (see PROVENANCE.md). Simulated devices for tests are in github.com/cB-Sigma/tplink-sim.

Example

Find Tapo devices and switch the first one on over KLAP or securePassthrough, whichever it asks for. It needs devices on the LAN, so it is not run; github.com/cB-Sigma/tplink-sim runs the same steps against simulated devices.

package main

import (
	"context"
	"fmt"
	"net/http"
	"time"

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

func main() {
	ctx := context.Background()
	const email, password = "user@example.invalid", "the TP-Link account's password"

	found, err := tplink.TapoDiscover(ctx, "255.255.255.255:20002", 3*time.Second)
	if err != nil || len(found) == 0 {
		fmt.Println(found, err)
		return
	}
	f := found[0]
	base := "http://" + f.Host
	if f.HTTPPort != 0 && f.HTTPPort != 80 {
		base = fmt.Sprintf("http://%s:%d", f.Host, f.HTTPPort)
	}
	var c tplink.SmartCaller
	if f.Protocol() == "aes" {
		c = &tplink.AESClient{Base: base, Logins: tplink.AESLogins(email, password, f.LoginVersion), HTTP: &http.Client{Timeout: 5 * time.Second}}
	} else {
		c = &tplink.KLAPClient{Base: base, Auths: tplink.KLAPAuths(email, password), HTTP: &http.Client{Timeout: 5 * time.Second}}
	}
	if _, err := c.Call(ctx, "set_device_info", map[string]any{"device_on": true}); err != nil {
		fmt.Println(err)
		return
	}
	info, _ := c.Call(ctx, "get_device_info", nil)
	fmt.Println(f.Model, info["device_on"])
}

Index

Examples

Constants

View Source
const (
	KasaActionNone = -1
	KasaActionOff  = 0
	KasaActionOn   = 1

	KasaTimeNone    = -1
	KasaTimeMinutes = 0 // minutes after midnight
	KasaTimeSunrise = 1
	KasaTimeSunset  = 2
)

Rule actions and time options.

View Source
const (
	FadeOn    = "set_fade_on_time"
	FadeOff   = "set_fade_off_time"
	GentleOn  = "set_gentle_on_time"
	GentleOff = "set_gentle_off_time"
)

Dimmer fade settings for SetDimmerFade.

View Source
const DefaultBatchSize = 5

DefaultBatchSize is how many requests MultiCall puts in one multipleRequest when the caller does not say.

View Source
const KLAPHTTPSPort = 4433

KLAPHTTPSPort is the port of KLAP over HTTPS.

View Source
const KasaPort = 9999

KasaPort is the legacy protocol's port (TCP and UDP).

View Source
const LinkiePort = 10443

LinkiePort is the port of the Kasa camera transport.

View Source
const TapoPort = 20002

TapoPort is the discovery port of Tapo and KLAP devices.

Variables

View Source
var ErrKLAPAuth = errors.New("the device refused the TP-Link account credentials")

ErrKLAPAuth means the device does not know the account: the handshake hash did not match (wrong username or password, or a device of another account).

View Source
var ErrNotSmart = errors.New("the device did not answer the Tapo request")

ErrNotSmart means the device answered a Tapo request without a Tapo result (a Kasa device on KLAP, which wants the legacy JSON).

Functions

func AuthHash

func AuthHash(username, password string) []byte

AuthHash is the KLAP v2 auth hash of an account: SHA-256(SHA-1(username) ‖ SHA-1(password)).

func AuthHashV1

func AuthHashV1(username, password string) []byte

AuthHashV1 is the KLAP v1 auth hash, used by Kasa devices whose newer firmware moved to KLAP: MD5(MD5(username) ‖ MD5(password)).

func CamChildList added in v0.2.0

func CamChildList(ctx context.Context, c SmartCaller) ([]map[string]any, error)

CamChildList reads an H200 hub's children (getChildDeviceList, paged).

func CamControlChild added in v0.2.0

func CamControlChild(ctx context.Context, c SmartCaller, deviceID, method string, params any) (map[string]any, error)

CamControlChild sends one Tapo request ({"method", "params"}) to an H200 hub's child and returns its result.

func CamDeviceInfo added in v0.2.0

func CamDeviceInfo(ctx context.Context, c SmartCaller) (map[string]any, error)

CamDeviceInfo asks a camera or H200 hub its basic information (getDeviceInfo, device_info.basic_info: device_model, device_type, sw_version, mac, device_alias, ...).

func CamGet added in v0.2.0

func CamGet(ctx context.Context, c SmartCaller, method string, params map[string]any) (map[string]any, error)

CamGet sends one camera request in a multipleRequest and returns its result.

func CheckTapoProbe

func CheckTapoProbe(b []byte) ([]byte, error)

CheckTapoProbe tells whether b is a well-formed probe (version 2, op code 1, matching length and CRC), as a device checks it; it returns the payload.

func ChildComponents added in v0.2.0

func ChildComponents(ctx context.Context, c SmartCaller) (map[string]map[string]int, error)

ChildComponents asks a hub or strip for its children's components (get_child_device_component_list, paged), by child device_id.

func ChildList

func ChildList(ctx context.Context, c SmartCaller) ([]map[string]any, error)

ChildList reads every child of a hub or strip, page by page.

func Components added in v0.2.0

func Components(ctx context.Context, c SmartCaller) (map[string]int, error)

Components asks component_nego: the device's components (firmware features such as "energy_monitoring", "countdown", "light_strip") with their version codes. The versions choose request shapes.

func ControlChild

func ControlChild(ctx context.Context, c SmartCaller, deviceID, method string, params any) (map[string]any, error)

ControlChild sends one request to a child through its parent.

func DecodeNickname added in v0.2.0

func DecodeNickname(s string) string

DecodeNickname decodes a base64 nickname; a value that is not base64 is returned as it is.

func Decrypt

func Decrypt(cipher []byte) []byte

Decrypt reverses Encrypt.

func DecryptTapoAnswer added in v0.2.0

func DecryptTapoAnswer(f *TapoFound, key *rsa.PrivateKey) error

DecryptTapoAnswer decrypts the answer's encrypt_info with the private key whose public half the probe carried, and sets f.Decrypted. An answer without encrypt_info is left as it is.

func Encrypt

func Encrypt(plain []byte) []byte

Encrypt obscures a Kasa payload.

Example
package main

import (
	"fmt"

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

func main() {
	fmt.Printf("% x\n", tplink.Encrypt([]byte(`{"a":1}`)))
	fmt.Println(string(tplink.Decrypt(tplink.Encrypt([]byte(`{"a":1}`)))))
}
Output:
d0 f2 93 b1 8b ba c7
{"a":1}

func Frame

func Frame(plain []byte) []byte

Frame is a TCP message: length and obscured payload.

func InsecureHTTP added in v0.2.0

func InsecureHTTP(timeout time.Duration) *http.Client

InsecureHTTP is an HTTP client for the devices' self-signed certificates: it does not check the certificate, which a device on the LAN cannot have signed by a public authority. The sessions are still protected by the transports' own keys.

func IsKasaUnsupported added in v0.2.0

func IsKasaUnsupported(err error) bool

IsKasaUnsupported reports whether err is a Kasa module or method the device does not have (codes -1 and -2).

func IsUnsupported

func IsUnsupported(err error) bool

IsUnsupported reports whether err is a Tapo "method not supported" (or "params" error) answer.

func KasaError

func KasaError(m map[string]any) error

KasaError returns the first module error of a Kasa answer (an err_code that is set and not 0), or nil.

func KasaKelvinRange

func KasaKelvinRange(model string) (lo, hi float64, known bool)

KasaKelvinRange is a Kasa bulb's colour-temperature range by model ("KL120(EU)"); known reports whether the model is listed.

func KasaRequest

func KasaRequest(ctx context.Context, addr string, req any, timeout time.Duration) (map[string]any, error)

KasaRequest sends one request to addr (host:port) and returns the answer.

Example

Read a Kasa plug on the legacy protocol, which needs no account. It needs a device, so it is not run.

package main

import (
	"context"
	"fmt"
	"time"

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

func main() {
	m, err := tplink.KasaRequest(context.Background(), "192.168.1.40:9999",
		map[string]any{"system": map[string]any{"get_sysinfo": map[string]any{}}}, 3*time.Second)
	if err != nil {
		fmt.Println(err)
		return
	}
	info := m["system"].(map[string]any)["get_sysinfo"].(map[string]any)
	fmt.Println(info["alias"], info["relay_state"])
}

func NormaliseMAC

func NormaliseMAC(s string) string

NormaliseMAC gives a MAC address as 12 lower-case hexadecimal digits, dropping separators ("" if it is not one).

func ReadFrame

func ReadFrame(r io.Reader) ([]byte, error)

ReadFrame reads one TCP message.

func SSLAESConfirm added in v0.2.0

func SSLAESConfirm(cnonce, nonce, pwdHash string) string

SSLAESConfirm is the device's proof of the password in the first login step, for a password hash (SSLAESPasswordHashes).

func SSLAESDigest added in v0.2.0

func SSLAESDigest(cnonce, nonce, pwdHash string) string

SSLAESDigest is the client's proof in the second login step.

func SSLAESKeys added in v0.2.0

func SSLAESKeys(cnonce, nonce, pwdHash string) (key, iv []byte)

SSLAESKeys derives the session's AES key and IV from the login.

func SSLAESPasswordHashes added in v0.2.0

func SSLAESPasswordHashes(password string) []string

SSLAESPasswordHashes are the password hashes a device may hold, newest first: SHA-256 and MD5, upper-case hexadecimal.

func SSLAESTag added in v0.2.0

func SSLAESTag(body []byte, cnonce, pwdHash string, seq int) string

SSLAESTag is the Tapo_tag header of a request body with its sequence.

func SealTapoDiscovery added in v0.2.0

func SealTapoDiscovery(pubPEM []byte, data any) (map[string]any, error)

SealTapoDiscovery builds an encrypt_info for data, encrypted to the PEM public key of a probe, as a device does (for simulators and tests).

func SmartList added in v0.2.0

func SmartList(ctx context.Context, c SmartCaller, method, listKey string, params map[string]any) ([]map[string]any, map[string]any, error)

SmartList reads a list the device answers in pages ({"start_index", "sum", and the list under listKey}), asking from start_index until sum entries are read. params are sent with each page (start_index is set). It returns the entries and the first page's other fields.

func TapoKelvinRange

func TapoKelvinRange(info map[string]any) (lo, hi float64)

TapoKelvinRange is a Tapo bulb's range from its get_device_info.

func TapoProbe

func TapoProbe(pubPEM []byte) []byte

TapoProbe builds a discovery probe carrying the PEM public key.

Types

type AESClient

type AESClient struct {
	Base   string // http://host[:port]
	Logins []AESLogin
	HTTP   *http.Client
	// contains filtered or unexported fields
}

AESClient talks securePassthrough to one device, keeping its session.

func (*AESClient) Call

func (a *AESClient) Call(ctx context.Context, method string, params any) (map[string]any, error)

Call sends one Tapo request and returns its result.

func (*AESClient) Handshake

func (a *AESClient) Handshake(ctx context.Context) error

Handshake runs the securePassthrough key exchange now, without logging in: it succeeds on a device that speaks securePassthrough, whatever the account.

func (*AESClient) Matched

func (a *AESClient) Matched() string

Matched names the login the device accepted ("" before one).

type AESLogin

type AESLogin struct {
	Name   string // account, or the Name of an extra Credential
	Params map[string]any
}

AESLogin is one set of login_device parameters to try.

func AESLogins

func AESLogins(username, password string, version int) []AESLogin

AESLogins are the login_device parameters tried, in order: the account with the login version the device announced first (2 when unknown), then the other version.

func AESLoginsWith

func AESLoginsWith(username, password string, version int, extra ...Credential) []AESLogin

AESLoginsWith is AESLogins with more accounts, each tried after the owner's with login version 2, then 1.

type AESSession

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

AESSession is the symmetric part of a securePassthrough session.

func NewAESSession

func NewAESSession(keyIV []byte) (*AESSession, error)

NewAESSession takes the 32 bytes the device sent (key ‖ IV).

func (*AESSession) Decrypt

func (s *AESSession) Decrypt(b64 string) ([]byte, error)

Decrypt reverses Encrypt.

func (*AESSession) Encrypt

func (s *AESSession) Encrypt(plain []byte) string

Encrypt pads (PKCS#7), encrypts and base64-encodes a payload.

type Credential

type Credential struct {
	Name     string // reported as KLAPAuth.Name or AESLogin.Name when it matches
	Username string
	Password string
}

Credential is an account to try besides the owner's: devices that were reset, set up only locally or unbound from the cloud may hold a setup account instead. This module ships none; an application that wants to try such accounts passes them to KLAPAuthsWith and AESLoginsWith.

type EnergyInterval added in v0.2.0

type EnergyInterval int

EnergyInterval is the bucket of an energy history.

const (
	EnergyHourly  EnergyInterval = 60
	EnergyDaily   EnergyInterval = 1440
	EnergyMonthly EnergyInterval = 43200
)

The buckets get_energy_data takes, in minutes.

type Found

type Found struct {
	Addr    string
	Sysinfo map[string]any
}

Found is a device that answered discovery.

func KasaDiscover

func KasaDiscover(ctx context.Context, bcast string, wait time.Duration) ([]Found, error)

KasaDiscover broadcasts get_sysinfo to bcast (host:port) and collects answers for wait.

type KLAPAuth

type KLAPAuth struct {
	Version int    // 1: proofs over one seed (Kasa on newer firmware); 2: over both seeds
	Hash    []byte // AuthHashV1 for version 1, AuthHash for version 2
	Name    string // account, blank, or the Name of an extra Credential
}

KLAPAuth is one auth hash a device may hold, with the KLAP version whose handshake proofs use it.

func KLAPAuths

func KLAPAuths(username, password string) []KLAPAuth

KLAPAuths are the auth hashes tried in a handshake, in order: the account as KLAP v2 and v1, then blank credentials. The device's handshake1 proof tells which one it holds, so trying them costs no extra request.

func KLAPAuthsWith

func KLAPAuthsWith(username, password string, extra ...Credential) []KLAPAuth

KLAPAuthsWith is KLAPAuths with more accounts, tried after the owner's (each as KLAP v2 and v1) and before blank credentials.

type KLAPClient

type KLAPClient struct {
	Base string // http://host[:port]
	// Auth is a KLAP v2 auth hash, used when Auths is empty.
	Auth []byte
	// Auths are the auth hashes to try (KLAPAuths); the first whose proof
	// the device sends is used.
	Auths []KLAPAuth
	HTTP  *http.Client
	// contains filtered or unexported fields
}

KLAPClient talks KLAP to one device, keeping its session.

func (*KLAPClient) BadSignatures

func (k *KLAPClient) BadSignatures() int

BadSignatures counts answers whose signature did not match; they are used anyway (decryption and padding still check them), as other clients do not check answer signatures at all.

func (*KLAPClient) Call

func (k *KLAPClient) Call(ctx context.Context, method string, params any) (map[string]any, error)

Call sends one Tapo request ({"method": …, "params": …}) and returns its result.

func (*KLAPClient) Handshake

func (k *KLAPClient) Handshake(ctx context.Context) error

Handshake runs the two-step KLAP handshake now, without a request, and keeps the session. A device that answers the first step with 48 bytes speaks KLAP: then the error is nil, or ErrKLAPAuth when none of the auth hashes matched its proof.

func (*KLAPClient) KasaCall

func (k *KLAPClient) KasaCall(ctx context.Context, req any) (map[string]any, error)

KasaCall sends a legacy Kasa request through KLAP (Kasa devices on newer firmware) and returns the answer, as KasaRequest does on TCP 9999.

func (*KLAPClient) Matched

func (k *KLAPClient) Matched() KLAPAuth

Matched is the auth the last handshake matched (zero before one).

func (*KLAPClient) Send

func (k *KLAPClient) Send(ctx context.Context, plain []byte) ([]byte, error)

Send sends one plain request body and returns the device's plain answer, doing the handshake when there is no live session. The body is a Tapo request ({"method", "params"}) or, for Kasa devices on KLAP, the legacy Kasa JSON.

type KasaCaller added in v0.2.0

type KasaCaller interface {
	KasaCall(ctx context.Context, req any) (map[string]any, error)
}

KasaCaller sends one legacy Kasa request: KasaConn (TCP 9999) or KLAPClient (Kasa devices on KLAP firmware).

type KasaConn added in v0.2.0

type KasaConn struct {
	Addr    string        // host:port
	Timeout time.Duration // per request; 0 means 5 s
}

KasaConn is a Kasa device on the legacy protocol (TCP port 9999).

func (KasaConn) KasaCall added in v0.2.0

func (k KasaConn) KasaCall(ctx context.Context, req any) (map[string]any, error)

KasaCall sends one request with KasaRequest.

type KasaDevice added in v0.2.0

type KasaDevice struct {
	Caller     KasaCaller
	ChildID    string
	Bulb       bool
	LightStrip bool
}

KasaDevice is a Kasa device on the legacy JSON, or one outlet of a strip (ChildID), with typed helpers for its modules. Bulb selects the bulb module names; LightStrip the light-strip lighting service (KL4xx). NewKasaDevice sets both from the device's sysinfo.

func NewKasaDevice added in v0.2.0

func NewKasaDevice(ctx context.Context, c KasaCaller) (*KasaDevice, map[string]any, error)

NewKasaDevice reads the sysinfo and returns the device with Bulb and LightStrip set, and the sysinfo.

func (*KasaDevice) AddRule added in v0.2.0

func (d *KasaDevice) AddRule(ctx context.Context, k KasaRuleKind, r KasaRule) (string, error)

AddRule adds a rule (add_rule) and returns its ID.

func (*KasaDevice) Child added in v0.2.0

func (d *KasaDevice) Child(id string) *KasaDevice

Child is the KasaDevice of one strip outlet.

func (*KasaDevice) CloudInfo added in v0.2.0

func (d *KasaDevice) CloudInfo(ctx context.Context) (map[string]any, error)

CloudInfo asks the cloud binding (get_info: username, binded, cld_connection, server, fwDlPage).

func (*KasaDevice) DeleteAllRules added in v0.2.0

func (d *KasaDevice) DeleteAllRules(ctx context.Context, k KasaRuleKind) error

DeleteAllRules empties a rule module (delete_all_rules).

func (*KasaDevice) DeleteRule added in v0.2.0

func (d *KasaDevice) DeleteRule(ctx context.Context, k KasaRuleKind, id string) error

DeleteRule deletes one rule (delete_rule).

func (*KasaDevice) DimTo added in v0.2.0

func (d *KasaDevice) DimTo(ctx context.Context, brightness, ms int) error

DimTo moves a dimmer to brightness over ms milliseconds (set_dimmer_transition); brightness 0 fades it off.

func (*KasaDevice) DimmerParameters added in v0.2.0

func (d *KasaDevice) DimmerParameters(ctx context.Context) (map[string]any, error)

DimmerParameters asks get_dimmer_parameters (fade and gentle times in ms, ramp rate, minimum threshold, ...).

func (*KasaDevice) EditRule added in v0.2.0

func (d *KasaDevice) EditRule(ctx context.Context, k KasaRuleKind, r KasaRule) error

EditRule replaces the rule with r.ID (edit_rule).

func (*KasaDevice) Emeter added in v0.2.0

func (d *KasaDevice) Emeter(ctx context.Context) (KasaEmeter, error)

Emeter asks get_realtime.

func (*KasaDevice) EmeterDays added in v0.2.0

func (d *KasaDevice) EmeterDays(ctx context.Context, year, month int) ([]KasaStat, error)

EmeterDays asks the energy per day of a month, in Wh (get_daystat).

func (*KasaDevice) EmeterMonths added in v0.2.0

func (d *KasaDevice) EmeterMonths(ctx context.Context, year int) ([]KasaStat, error)

EmeterMonths asks the energy per month of a year, in Wh (get_monthstat).

func (*KasaDevice) EraseEmeter added in v0.2.0

func (d *KasaDevice) EraseEmeter(ctx context.Context) error

EraseEmeter clears the energy statistics (erase_emeter_stat).

func (*KasaDevice) EraseRuntime added in v0.2.0

func (d *KasaDevice) EraseRuntime(ctx context.Context) error

EraseRuntime clears the runtime statistics (erase_runtime_stat).

func (*KasaDevice) FactoryReset added in v0.2.0

func (d *KasaDevice) FactoryReset(ctx context.Context) error

FactoryReset resets the device (reset).

func (*KasaDevice) FirmwareList added in v0.2.0

func (d *KasaDevice) FirmwareList(ctx context.Context) ([]map[string]any, error)

FirmwareList asks the firmware updates the cloud offers the device (get_intl_fw_list); empty when there is none or no cloud connection.

func (*KasaDevice) LightDetails added in v0.2.0

func (d *KasaDevice) LightDetails(ctx context.Context) (map[string]any, error)

LightDetails asks get_light_details (lamp ratings and colour rendering).

func (*KasaDevice) LightState added in v0.2.0

func (d *KasaDevice) LightState(ctx context.Context) (map[string]any, error)

LightState asks get_light_state.

func (*KasaDevice) NextAction added in v0.2.0

func (d *KasaDevice) NextAction(ctx context.Context) (map[string]any, error)

NextAction asks the next scheduled action (get_next_action).

func (*KasaDevice) Query added in v0.2.0

func (d *KasaDevice) Query(ctx context.Context, module, method string, params any) (map[string]any, error)

Query sends one module method and returns its answer without err_code.

func (*KasaDevice) Reboot added in v0.2.0

func (d *KasaDevice) Reboot(ctx context.Context, delay int) error

Reboot restarts the device after delay seconds (reboot).

func (*KasaDevice) Rules added in v0.2.0

func (d *KasaDevice) Rules(ctx context.Context, k KasaRuleKind) (KasaRules, error)

Rules reads a rule module (get_rules).

func (*KasaDevice) RuntimeDays added in v0.2.0

func (d *KasaDevice) RuntimeDays(ctx context.Context, year, month int) ([]KasaStat, error)

RuntimeDays asks the minutes on per day of a month (the schedule module's get_daystat).

func (*KasaDevice) RuntimeMonths added in v0.2.0

func (d *KasaDevice) RuntimeMonths(ctx context.Context, year int) ([]KasaStat, error)

RuntimeMonths asks the minutes on per month of a year (get_monthstat).

func (*KasaDevice) SetAlias added in v0.2.0

func (d *KasaDevice) SetAlias(ctx context.Context, alias string) error

SetAlias renames the device or outlet (set_dev_alias).

func (*KasaDevice) SetBrightness added in v0.2.0

func (d *KasaDevice) SetBrightness(ctx context.Context, b int) error

SetBrightness sets a dimmer's brightness, 1-100 (set_brightness).

func (*KasaDevice) SetDimmerFade added in v0.2.0

func (d *KasaDevice) SetDimmerFade(ctx context.Context, which string, ms int) error

SetDimmerFade sets one of the dimmer's fade times, in ms (FadeOn, FadeOff, GentleOn, GentleOff).

func (*KasaDevice) SetLED added in v0.2.0

func (d *KasaDevice) SetLED(ctx context.Context, on bool) error

SetLED switches the status light (system.set_led_off).

func (*KasaDevice) SetLight added in v0.2.0

func (d *KasaDevice) SetLight(ctx context.Context, l KasaLight) (map[string]any, error)

SetLight changes a bulb or light strip and returns its new light state. A change without a colour, temperature or brightness turns the light on to its last state; one with them sets ignore_default so the light takes them.

func (*KasaDevice) SetLightingEffect added in v0.2.0

func (d *KasaDevice) SetLightingEffect(ctx context.Context, effect map[string]any) error

SetLightingEffect sends a light strip effect (set_lighting_effect): the device's own description (name, id, type, brightness, transition, colours or sequence, enable). This module ships no effect definitions; an effect with enable 0 stops the running one.

func (*KasaDevice) SetPreferredState added in v0.2.0

func (d *KasaDevice) SetPreferredState(ctx context.Context, state map[string]any) error

SetPreferredState saves a light preset (set_preferred_state with index and the state fields).

func (*KasaDevice) SetRampRate added in v0.2.0

func (d *KasaDevice) SetRampRate(ctx context.Context, rate int) error

SetRampRate sets how fast the dimmer's buttons dim (set_button_ramp_rate).

func (*KasaDevice) SetRelay added in v0.2.0

func (d *KasaDevice) SetRelay(ctx context.Context, on bool) error

SetRelay switches a plug, switch or outlet (system.set_relay_state).

func (*KasaDevice) SetRulesEnabled added in v0.2.0

func (d *KasaDevice) SetRulesEnabled(ctx context.Context, k KasaRuleKind, on bool) error

SetRulesEnabled switches a whole rule module on or off (set_overall_enable).

func (*KasaDevice) Sysinfo added in v0.2.0

func (d *KasaDevice) Sysinfo(ctx context.Context) (map[string]any, error)

Sysinfo asks system.get_sysinfo. Kasa cameras nest their answer once more under "system"; it is returned unnested.

func (*KasaDevice) Time added in v0.2.0

func (d *KasaDevice) Time(ctx context.Context) (time.Time, error)

Time asks the device clock (get_time), in the device's zone.

func (*KasaDevice) WifiJoin added in v0.2.0

func (d *KasaDevice) WifiJoin(ctx context.Context, ssid, password string, keyType int) error

WifiJoin sets a device in its set-up mode (its own access point) onto a Wi-Fi network (set_stainfo); keyType is the scan's key_type (3 for WPA2 when 0). The device leaves its access point without answering, so a transport error after sending is returned as nil.

func (*KasaDevice) WifiScan added in v0.2.0

func (d *KasaDevice) WifiScan(ctx context.Context) ([]WifiNetwork, error)

WifiScan asks the networks the device sees (get_scaninfo with refresh).

type KasaEmeter added in v0.2.0

type KasaEmeter struct {
	VoltageMV float64
	CurrentMA float64
	PowerMW   float64
	TotalWh   float64
}

KasaEmeter is a real-time reading, in the units newer firmware uses (older firmware's V, A, W and kWh are converted).

func ParseKasaEmeter added in v0.2.0

func ParseKasaEmeter(r map[string]any) KasaEmeter

ParseKasaEmeter reads a get_realtime answer of either firmware generation.

type KasaLight added in v0.2.0

type KasaLight struct {
	On         *bool
	Brightness *int // 0-100
	Hue        *int // 0-360
	Saturation *int // 0-100
	ColorTemp  *int // Kelvin; 0 selects the colour
	// TransitionMS is the transition time; 0 lets the device choose.
	TransitionMS int
}

KasaLight is a light change; nil fields are left as they are.

type KasaModuleError added in v0.2.0

type KasaModuleError struct {
	Module, Method string
	Code           int
	Msg            string
}

KasaModuleError is a module answer with an err_code that is not 0.

func (*KasaModuleError) Error added in v0.2.0

func (e *KasaModuleError) Error() string

type KasaRule added in v0.2.0

type KasaRule struct {
	ID      string
	Name    string
	Enable  bool
	WDay    [7]bool // Sunday first
	Repeat  bool
	SAction int // KasaAction*
	STime   int // KasaTime*
	SMin    int
	EAction int
	ETime   int
	EMin    int
	Delay   int // seconds (countdown)
	Action  int // countdown action
	Light   map[string]any
	Raw     map[string]any // the rule as the device gave it
}

KasaRule is one rule. Schedule and away-mode rules use the start (and, for away mode, end) action and time and the weekdays; countdown rules Delay and Action. Light is a bulb's light state for the start action.

type KasaRuleKind added in v0.2.0

type KasaRuleKind int

KasaRuleKind names a Kasa rule module.

const (
	KasaSchedule KasaRuleKind = iota
	KasaCountdown
	KasaAntiTheft
)

The rule modules: timed actions, a countdown, and the away mode that switches at random within a window.

type KasaRules added in v0.2.0

type KasaRules struct {
	Enable bool
	Rules  []KasaRule
}

KasaRules is a rule module's list and whether the module is on.

type KasaStat added in v0.2.0

type KasaStat struct {
	Year, Month, Day int // Day is 0 in monthly statistics
	Value            float64
}

KasaStat is one day's or month's figure: Wh for the energy meter, minutes for the runtime statistics.

type LinkieClient added in v0.2.0

type LinkieClient struct {
	Base     string // https://host[:port], port 10443 when not given
	Username string
	Password string
	HTTP     *http.Client // InsecureHTTP for the self-signed certificate
}

LinkieClient talks to a Kasa camera. The device's user and password are its local ones; this module ships no default.

func (*LinkieClient) KasaCall added in v0.2.0

func (l *LinkieClient) KasaCall(ctx context.Context, req any) (map[string]any, error)

KasaCall sends one legacy Kasa request and returns the answer.

type SSLAESClient added in v0.2.0

type SSLAESClient struct {
	Base     string // https://host[:port], port 443 when not given
	Username string
	Password string
	HTTP     *http.Client // InsecureHTTP for self-signed certificates
	// contains filtered or unexported fields
}

SSLAESClient talks to a Tapo camera, doorbell or H200 hub over HTTPS, keeping its session. Username is the device's local user (the TP-Link account's e-mail on most firmware; cameras that were set up locally have their own); this module ships no default user.

func (*SSLAESClient) Call added in v0.2.0

func (s *SSLAESClient) Call(ctx context.Context, method string, params any) (map[string]any, error)

Call sends {"method", "params"} and returns the result, as KLAPClient and AESClient do. Cameras take most requests in a multipleRequest (MultiCall, CamGet).

func (*SSLAESClient) Handshake added in v0.2.0

func (s *SSLAESClient) Handshake(ctx context.Context) error

Handshake logs in now, without a request.

func (*SSLAESClient) Send added in v0.2.0

func (s *SSLAESClient) Send(ctx context.Context, req any) (map[string]any, error)

Send sends one request object ({"method", ...}) and returns the device's answer as it is (with error_code), logging in when needed.

type SSLClient added in v0.2.0

type SSLClient struct {
	Base     string // https://host[:port], port 4433 when not given
	Username string
	Password string
	HTTP     *http.Client // InsecureHTTP for the self-signed certificate
	// contains filtered or unexported fields
}

SSLClient talks to a Tapo device on the plain HTTPS transport (older robot vacuum firmware), keeping its token.

func (*SSLClient) Call added in v0.2.0

func (s *SSLClient) Call(ctx context.Context, method string, params any) (map[string]any, error)

Call sends one Tapo request and returns its result, logging in when needed.

type Session

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

Session holds the keys of one KLAP handshake.

func NewSession

func NewSession(local, remote, auth []byte) *Session

NewSession derives the session keys from the seeds and the auth hash.

func (*Session) Decrypt

func (s *Session) Decrypt(seq int32, body []byte) ([]byte, error)

Decrypt opens a body for a sequence number and checks its signature.

func (*Session) Encrypt

func (s *Session) Encrypt(plain []byte) (int32, []byte)

Encrypt returns the next sequence number and the request body (signature ‖ ciphertext).

func (*Session) Open

func (s *Session) Open(seq int32, body []byte) ([]byte, bool, error)

Open decrypts a body for a sequence number and tells whether its signature matched.

func (*Session) Seal

func (s *Session) Seal(seq int32, plain []byte) []byte

Seal encrypts and signs a body for a sequence number (the device's answer uses the request's).

type SmartCaller

type SmartCaller interface {
	Call(ctx context.Context, method string, params any) (map[string]any, error)
}

SmartCaller is a Tapo transport: KLAPClient or AESClient.

type SmartError

type SmartError struct {
	Code   int
	Method string
}

SmartError is a Tapo request answered with an error code.

func (*SmartError) Error

func (e *SmartError) Error() string

Error describes the code and the method.

type SmartRequest added in v0.2.0

type SmartRequest struct {
	Method string
	Params any // nil for none
}

SmartRequest is one request of a batch.

type SmartResult added in v0.2.0

type SmartResult struct {
	Method string
	Result map[string]any
	Err    error
}

SmartResult is the answer to one request of a batch: Result, or Err (a *SmartError when the device answered an error code).

func MultiCall added in v0.2.0

func MultiCall(ctx context.Context, c SmartCaller, reqs []SmartRequest, batch int) ([]SmartResult, error)

MultiCall sends the requests in multipleRequest batches of batch (0: DefaultBatchSize; 1: one by one) and returns one result per request, in order. A device that refuses the batch as a whole is asked one request at a time. The error is set only when the transport failed.

func MultiCallChild added in v0.2.0

func MultiCallChild(ctx context.Context, c SmartCaller, deviceID string, reqs []SmartRequest) ([]SmartResult, error)

MultiCallChild sends several requests to one child of a hub or strip in one control_child carrying a multipleRequest, and returns one result per request, in order. A child that refuses the batch is asked one request at a time.

type TapoAutoOff added in v0.2.0

type TapoAutoOff struct {
	Enable   bool `json:"enable"`
	DelayMin int  `json:"delay_min"`
}

TapoAutoOff is get_auto_off_config: switch off DelayMin minutes after switching on.

type TapoAutoUpdate added in v0.2.0

type TapoAutoUpdate struct {
	Enable      bool `json:"enable"`
	Time        int  `json:"time"`
	RandomRange int  `json:"random_range"`
}

TapoAutoUpdate is get_auto_update_info: automatic updates and their time (minutes after midnight) with a random spread (minutes).

type TapoDevice added in v0.2.0

type TapoDevice struct {
	Caller  SmartCaller // a KLAPClient or AESClient
	ChildID string
}

TapoDevice is a Tapo device, or one child of a hub or strip, with typed helpers for the requests open-source clients describe: device information, switching and lights, energy and use, schedules and other rules, firmware, Wi-Fi and account set-up. Each helper is one request (see the method); Call and MultiCall reach anything else.

A child is reached through its parent with control_child: set ChildID to its device_id. The zero ChildID is the device itself. TapoDevice is a SmartCaller, so it can be passed to ChildList, SmartList, Components and MultiCall.

func (TapoDevice) AutoOff added in v0.2.0

func (d TapoDevice) AutoOff(ctx context.Context) (TapoAutoOff, error)

AutoOff asks get_auto_off_config.

func (TapoDevice) AutoUpdate added in v0.2.0

func (d TapoDevice) AutoUpdate(ctx context.Context) (TapoAutoUpdate, error)

AutoUpdate asks get_auto_update_info.

func (TapoDevice) Call added in v0.2.0

func (d TapoDevice) Call(ctx context.Context, method string, params any) (map[string]any, error)

Call sends one request to the device, or to the child through control_child.

func (TapoDevice) Child added in v0.2.0

func (d TapoDevice) Child(deviceID string) TapoDevice

Child is the TapoDevice of one child.

func (TapoDevice) Children added in v0.2.0

func (d TapoDevice) Children(ctx context.Context) ([]TapoInfo, error)

Children reads a hub's or strip's children, typed.

func (TapoDevice) CurrentPower added in v0.2.0

func (d TapoDevice) CurrentPower(ctx context.Context) (float64, error)

CurrentPower asks get_current_power, in W.

func (TapoDevice) DynamicEffects added in v0.2.0

func (d TapoDevice) DynamicEffects(ctx context.Context) (TapoRules, error)

DynamicEffects reads a bulb's light effects (get_dynamic_light_effect_rules, paged), with whether one is running.

func (TapoDevice) EditPreset added in v0.2.0

func (d TapoDevice) EditPreset(ctx context.Context, index int, state map[string]any) error

EditPreset replaces one saved state (edit_preset_rules).

func (TapoDevice) Emeter added in v0.2.0

func (d TapoDevice) Emeter(ctx context.Context) (TapoEmeter, error)

Emeter asks get_emeter_data: voltage, current, power and energy.

func (TapoDevice) EnergyData added in v0.2.0

func (d TapoDevice) EnergyData(ctx context.Context, start, end time.Time, interval EnergyInterval) (TapoEnergyData, error)

EnergyData asks get_energy_data for the energy history between start and end. Devices answer a day of hours (EnergyHourly), a quarter of days from its first day (EnergyDaily) and a year of months (EnergyMonthly); start and end are sent as Unix seconds as given.

func (TapoDevice) EnergyUsage added in v0.2.0

func (d TapoDevice) EnergyUsage(ctx context.Context) (TapoEnergyUsage, error)

EnergyUsage asks get_energy_usage.

func (TapoDevice) FactoryReset added in v0.2.0

func (d TapoDevice) FactoryReset(ctx context.Context) error

FactoryReset resets the device to its factory settings (device_reset).

func (TapoDevice) FirmwareState added in v0.2.0

func (d TapoDevice) FirmwareState(ctx context.Context) (TapoFirmwareState, error)

FirmwareState asks get_fw_download_state.

func (TapoDevice) Info added in v0.2.0

func (d TapoDevice) Info(ctx context.Context) (TapoInfo, error)

Info asks get_device_info.

func (TapoDevice) LED added in v0.2.0

func (d TapoDevice) LED(ctx context.Context) (map[string]any, error)

LED asks get_led_info: led_rule (always, never, auto) and the rest.

func (TapoDevice) LatestFirmware added in v0.2.0

func (d TapoDevice) LatestFirmware(ctx context.Context) (TapoFirmware, error)

LatestFirmware asks get_latest_fw.

func (TapoDevice) LightingEffect added in v0.2.0

func (d TapoDevice) LightingEffect(ctx context.Context) (map[string]any, error)

LightingEffect asks a light strip's current effect (get_lighting_effect).

func (TapoDevice) Presets added in v0.2.0

func (d TapoDevice) Presets(ctx context.Context) ([]map[string]any, error)

Presets reads a light's saved states (get_preset_rules, paged).

func (TapoDevice) Reboot added in v0.2.0

func (d TapoDevice) Reboot(ctx context.Context, delay int) error

Reboot restarts the device after delay seconds (device_reboot). A delay of 0 makes the device restart without answering.

func (TapoDevice) Rules added in v0.2.0

func (d TapoDevice) Rules(ctx context.Context, kind TapoRuleKind) (TapoRules, error)

Rules reads a rule list (get_schedule_rules paged, get_countdown_rules, get_antitheft_rules). Changing Tapo rules is not offered (see the README); Call reaches the device's own methods.

func (TapoDevice) SetAccount added in v0.2.0

func (d TapoDevice) SetAccount(ctx context.Context, username, password string) error

SetAccount replaces the TP-Link account the device knows (set_qs_info with the account and the device's time); clients must then use the new account.

func (TapoDevice) SetAutoOff added in v0.2.0

func (d TapoDevice) SetAutoOff(ctx context.Context, a TapoAutoOff) error

SetAutoOff sends set_auto_off_config.

func (TapoDevice) SetAutoUpdate added in v0.2.0

func (d TapoDevice) SetAutoUpdate(ctx context.Context, a TapoAutoUpdate) error

SetAutoUpdate sends set_auto_update_info.

func (TapoDevice) SetDynamicEffect added in v0.2.0

func (d TapoDevice) SetDynamicEffect(ctx context.Context, id string, enable bool) error

SetDynamicEffect starts (enable) or stops a bulb's light effect by its id (set_dynamic_light_effect_rule_enable).

func (TapoDevice) SetLEDRule added in v0.2.0

func (d TapoDevice) SetLEDRule(ctx context.Context, rule string) error

SetLEDRule sets the status light's rule (always, never or auto), keeping the other LED settings (get_led_info, then set_led_info).

func (TapoDevice) SetLight added in v0.2.0

func (d TapoDevice) SetLight(ctx context.Context, l TapoLight) error

SetLight changes a bulb or light strip in one set_device_info.

func (TapoDevice) SetLightingEffect added in v0.2.0

func (d TapoDevice) SetLightingEffect(ctx context.Context, effect map[string]any) error

SetLightingEffect sends a light strip effect (set_lighting_effect). The effect is the device's own description (name, type, sequence, colours, brightness, enable, ...); this module ships no effect definitions.

func (TapoDevice) SetNickname added in v0.2.0

func (d TapoDevice) SetNickname(ctx context.Context, name string) error

SetNickname renames the device (set_device_info nickname, base64).

func (TapoDevice) SetOn added in v0.2.0

func (d TapoDevice) SetOn(ctx context.Context, on bool) error

SetOn switches the device (set_device_info device_on).

func (TapoDevice) SetTransitions added in v0.2.0

func (d TapoDevice) SetTransitions(ctx context.Context, version int, enable bool, onSecs, offSecs int) error

SetTransitions sends set_on_off_gradually_info. On firmware whose on_off_gradually component is version 1 only enable counts (onSecs and offSecs are ignored); later firmware takes the durations, 0 for off.

func (TapoDevice) StartFirmwareUpdate added in v0.2.0

func (d TapoDevice) StartFirmwareUpdate(ctx context.Context) error

StartFirmwareUpdate tells the device to download and install the latest firmware (fw_download); follow it with FirmwareState.

func (TapoDevice) Time added in v0.2.0

func (d TapoDevice) Time(ctx context.Context) (TapoTime, error)

Time asks the device clock (get_device_time).

func (TapoDevice) Transitions added in v0.2.0

func (d TapoDevice) Transitions(ctx context.Context) (map[string]any, error)

Transitions asks get_on_off_gradually_info: {"enable"} on firmware of component version 1, {"on_state", "off_state"} with durations in seconds on later ones.

func (TapoDevice) TriggerLogs added in v0.2.0

func (d TapoDevice) TriggerLogs(ctx context.Context, pageSize, startID int) ([]TriggerLog, error)

TriggerLogs reads a child's log, newest first (get_trigger_logs with page_size and start_id; 0 starts at the newest).

func (TapoDevice) Usage added in v0.2.0

func (d TapoDevice) Usage(ctx context.Context) (TapoUsage, error)

Usage asks get_device_usage.

func (TapoDevice) WifiJoin added in v0.2.0

func (d TapoDevice) WifiJoin(ctx context.Context, username, password, ssid, wifiPassword, keyType string) error

WifiJoin sets a device up on a Wi-Fi network and binds it to the TP-Link account (username, password), as the app does for a new device in its set-up mode (set_qs_info with the account, the network and the device's own time). keyType is the network's security as WifiScan reports it ("wpa2_psk" when ""). The device usually switches networks without answering, so a transport error after sending is expected and returned as nil.

func (TapoDevice) WifiScan added in v0.2.0

func (d TapoDevice) WifiScan(ctx context.Context) ([]WifiNetwork, error)

WifiScan asks the networks the device sees (get_wireless_scan_info, paged; SSIDs are base64 on the wire).

type TapoEmeter added in v0.2.0

type TapoEmeter struct {
	VoltageMV float64 `json:"voltage_mv"`
	CurrentMA float64 `json:"current_ma"`
	PowerMW   float64 `json:"power_mw"`
	EnergyWh  float64 `json:"energy_wh"`
}

TapoEmeter is get_emeter_data (newer energy-monitoring firmware).

type TapoEnergyData added in v0.2.0

type TapoEnergyData struct {
	Start     time.Time
	Interval  EnergyInterval
	Wh        []float64
	LocalTime string
	Raw       map[string]any
}

TapoEnergyData is an energy history: Wh per bucket from Start.

type TapoEnergyUsage added in v0.2.0

type TapoEnergyUsage struct {
	TodayRuntime int     `json:"today_runtime"`
	MonthRuntime int     `json:"month_runtime"`
	TodayEnergy  int     `json:"today_energy"`
	MonthEnergy  int     `json:"month_energy"`
	CurrentPower float64 `json:"current_power"`
	LocalTime    string  `json:"local_time"`
}

TapoEnergyUsage is get_energy_usage: energy in Wh, runtimes in minutes; CurrentPower is in mW on the firmware that reports it here.

type TapoFirmware added in v0.2.0

type TapoFirmware struct {
	Type        int    `json:"type"` // 0: no update
	NeedUpgrade bool   `json:"need_to_upgrade"`
	Version     string `json:"fw_ver"`
	ReleaseDate string `json:"release_date"`
	ReleaseNote string `json:"release_note"`
	Size        int    `json:"fw_size"`
}

TapoFirmware is get_latest_fw. The device asks TP-Link's cloud, so a device without a cloud connection answers no update.

func (TapoFirmware) Available added in v0.2.0

func (f TapoFirmware) Available() bool

Available reports whether an update is offered.

type TapoFirmwareState added in v0.2.0

type TapoFirmwareState struct {
	Status      int  `json:"status"`
	Progress    int  `json:"download_progress"`
	RebootTime  int  `json:"reboot_time"`
	UpgradeTime int  `json:"upgrade_time"`
	AutoUpgrade bool `json:"auto_upgrade"`
}

TapoFirmwareState is get_fw_download_state. Status 0 is idle, 2 downloading, 3 flashing (wait UpgradeTime seconds), negative an error.

type TapoFound

type TapoFound struct {
	// Addr is where the answer came from (host:port).
	Addr string
	// Host is the device's address: the answer's source, else its "ip".
	Host       string
	DeviceType string // SMART.TAPOPLUG, SMART.KASAPLUG, SMART.TAPOHUB, IOT.SMARTPLUGSWITCH, …
	Model      string // without the region, "P110"
	DeviceID   string
	MAC        string // 12 hex digits
	// Encrypt is KLAP or AES (securePassthrough); "" when not told.
	Encrypt      string
	HTTPPort     int
	LoginVersion int
	HTTPS        bool
	Name         string
	Result       map[string]any
	// Decrypted is the answer's encrypt_info decrypted (newer firmware), or
	// nil. TapoDiscover fills it.
	Decrypted map[string]any
}

TapoFound is a device that answered the 20002 probe.

func ParseTapoAnswer

func ParseTapoAnswer(b []byte) (TapoFound, error)

ParseTapoAnswer reads a 20002 answer.

func TapoDiscover

func TapoDiscover(ctx context.Context, bcast string, wait time.Duration) ([]TapoFound, error)

TapoDiscover sends the 20002 probe to bcast (host:port) and collects answers for wait. The probe is sent three times over the wait, as datagrams get lost.

func (TapoFound) BaseURL added in v0.2.0

func (f TapoFound) BaseURL() string

BaseURL is the URL a client of the protocol the answer asks for starts from: http://host[:port] for KLAP and securePassthrough; https://host:port for KLAP over HTTPS (port 4433 when not told) and for the HTTPS transport of cameras and the H200 hub (SSLAESClient, port 443 when not told). Use InsecureHTTP for the https ones.

func (TapoFound) Protocol

func (f TapoFound) Protocol() string

Protocol is the row protocol the answer asks for: klap or aes ("" when not told).

type TapoInfo added in v0.2.0

type TapoInfo struct {
	DeviceID   string         `json:"device_id"`
	Model      string         `json:"model"`
	Type       string         `json:"type"`
	Category   string         `json:"category"` // children: plug.powerstrip.sub-plug, subg.trigger.temp-hmdt-sensor, ...
	FWVersion  string         `json:"fw_ver"`
	HWVersion  string         `json:"hw_ver"`
	MAC        string         `json:"mac"`
	IP         string         `json:"ip"`
	On         *bool          `json:"device_on"`
	Brightness *int           `json:"brightness"`
	Hue        *int           `json:"hue"`
	Saturation *int           `json:"saturation"`
	ColorTemp  *int           `json:"color_temp"`
	OnTime     int            `json:"on_time"`
	Overheated bool           `json:"overheated"`
	RSSI       int            `json:"rssi"`
	Region     string         `json:"region"`
	Status     string         `json:"status"` // children of a hub: online, offline
	Battery    *int           `json:"battery_percentage"`
	LowBattery bool           `json:"at_low_battery"`
	Temp       *float64       `json:"current_temp"`
	Humidity   *float64       `json:"current_humidity"`
	TempUnit   string         `json:"temp_unit"`
	Open       *bool          `json:"open"`     // contact sensors
	Detected   *bool          `json:"detected"` // motion sensors
	InAlarm    *bool          `json:"in_alarm"` // water-leak sensors
	Nickname   string         `json:"-"`        // decoded from base64
	Raw        map[string]any `json:"-"`
}

TapoInfo is the common part of get_device_info. Raw holds every field.

func ParseTapoInfo added in v0.2.0

func ParseTapoInfo(m map[string]any) TapoInfo

ParseTapoInfo reads a get_device_info answer (or a child list entry).

type TapoLight added in v0.2.0

type TapoLight struct {
	On         *bool
	Brightness *int // 1-100
	Hue        *int // 0-360
	Saturation *int // 0-100
	ColorTemp  *int // Kelvin; 0 selects the colour
}

TapoLight is a light change for SetLight; nil fields are left as they are. A colour (Hue, Saturation) is set with ColorTemp 0; a colour temperature replaces the colour.

type TapoPeriods added in v0.2.0

type TapoPeriods struct {
	Today  int `json:"today"`
	Past7  int `json:"past7"`
	Past30 int `json:"past30"`
}

TapoPeriods is a today, past 7 days and past 30 days triple.

type TapoRuleKind added in v0.2.0

type TapoRuleKind string

TapoRuleKind names a Tapo rule list.

const (
	TapoSchedule  TapoRuleKind = "schedule"
	TapoCountdown TapoRuleKind = "countdown"
	TapoAntitheft TapoRuleKind = "antitheft"
)

The rule lists of plugs and lights.

type TapoRules added in v0.2.0

type TapoRules struct {
	Enable bool
	Max    int
	Rules  []map[string]any
}

TapoRules is a rule list: whether it is on, its rules as the device gives them, and how many it holds at most.

type TapoTime added in v0.2.0

type TapoTime struct {
	Timestamp int64  `json:"timestamp"` // Unix seconds
	TimeDiff  int    `json:"time_diff"` // minutes from UTC
	Region    string `json:"region"`
}

TapoTime is get_device_time.

type TapoUsage added in v0.2.0

type TapoUsage struct {
	Time  TapoPeriods `json:"time_usage"`
	Power TapoPeriods `json:"power_usage"`
	Saved TapoPeriods `json:"saved_power"`
}

TapoUsage is get_device_usage: minutes on, energy used and saved (Wh).

type TriggerLog added in v0.2.0

type TriggerLog struct {
	ID        int            `json:"id"`
	Event     string         `json:"event"` // singleClick, doubleClick, rotation, open, close, motion, ...
	EventID   string         `json:"eventId"`
	Timestamp int64          `json:"timestamp"`
	Params    map[string]any `json:"params"`
}

TriggerLog is one entry of a button's or sensor's log.

type WifiNetwork added in v0.2.0

type WifiNetwork struct {
	SSID        string
	BSSID       string
	KeyType     string // Tapo: wpa2_psk, ...; Kasa: a number as text
	CipherType  int
	Channel     int
	SignalLevel int // Tapo: 1-3; Kasa: RSSI
}

WifiNetwork is a network a device sees.

Jump to

Keyboard shortcuts

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