tplink

package module
v0.4.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: 34 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 TPAP login of newer firmware, the camera and hub HTTPS transports and the 20002 discovery, with typed helpers for plugs, strips, dimmers, bulbs, light strips, hubs, cameras and robot vacuums; 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 TPAP login that newer Tapo firmware and cameras use when the app's third-party compatibility option is off (SPAKE2+ and AES-128-CCM), 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, TPAP 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
Changing Tapo schedules (add, edit, remove one or all; clock, sunrise and sunset starts; weekdays) and countdowns (AddScheduleRule, EditScheduleRule, RemoveScheduleRules, AddCountdown, ReplaceCountdown, RemoveCountdowns), typed reading (ScheduleRules, CountdownRules) yes, since v0.3.0
Camera helpers (TapoCamera, for a camera or doorbell, or a camera behind an H200 hub): information with battery, name, components, pan and tilt (Move, MoveStep, Calibrate), saved positions, privacy (lens mask), status light, ten detection settings (motion, person, pet, vehicle, baby cry, bark, meow, glass break, tamper, line crossing), last alarm, siren, alarm on detection and manual alarm, night vision and day/night mode, clock and time zone, SD cards and formatting, recording days and clips list, connection, Wi-Fi scan, reboot; the single request form (CamSingle) yes, since v0.3.0
Robot vacuum helpers (TapoVacuum, on any transport): status (state, errors, battery, progress, suction, water, mode), start, rooms, pause, resume, return to dock, suction, water level, pass count, consumables and their reset, clean records, maps and rooms, mop, dock emptying, volume and locate, carpet boost, area unit yes, since v0.3.0
Colour-temperature ranges Kasa by model table; Tapo from get_device_info
The TPAP login of newer firmware (TPAPClient): asking a device whether it is in TPAP mode (TPAPDiscover) or reading it from the 20002 answer (TapoFound.TPAP, protocol tpap), SPAKE2+ (RFC 9383, P-256) with the account password, the device's proof checked, AES-128-CCM requests numbered by sequence, sessions renewed when the device ends them; plugs, bulbs, hubs and strips, and cameras over HTTPS (Camera, TPAPCameraInfo); wrong password (ErrTPAPAuth), a locked device (ErrTPAPLocked) and a device that cannot prove the password (ErrTPAPDeviceProof) told apart yes, since v0.4.0: cipher suite 1, aes_128_ccm, passcode type 2 (account password) with password_shadow 2 or a camera's MD5; other variants in "Not yet"
Changing Tapo away rules, local Kasa firmware flashing, camera video, the cloud API no; see "Not yet"

Compared from each project's source at the version named, on 2026-10-12. Check the projects themselves before relying on a row. python-kasa's master (commit 38a3184, 2026-10-09) adds nothing to its 0.11.0.1 release in these rows. kabukky/tapogo has had no commit since 2024-03-04 and fabiankachlock/tapo-api no release since v1.4.0 (2025-01-31). insomniacslk/tapo (Go, MIT, 2026-09-12) covers plugs on KLAP and securePassthrough only, and is not shown.

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) tapo crate 0.11.1 (Rust, Python bindings)
Kasa legacy protocol (9999) and its UDP discovery yes no no yes yes no
KLAP v2 (Tapo) yes, HTTP and HTTPS yes yes no yes, HTTP and HTTPS yes
KLAP v1 (Kasa on newer firmware) yes no no no yes no
securePassthrough (older Tapo firmware) yes, login v1 and v2 no no no yes no
TPAP login (newest firmware) yes, since v0.4.0: account password, suite 1, AES-128-CCM no no no no; an open pull request (#1592) with more variants yes, the same variants
Cameras, doorbells, H200 hub (HTTPS transport) yes, with typed helpers (no video) no no no yes, with camera modules and stream URLs yes, pan and tilt, presets, recordings, snapshots, hub children
Camera detection settings, siren, night vision, SD card yes no no no detections, siren, LED, privacy; no night vision or SD card no
Robot vacuums yes, typed helpers no no no yes, with device modules no
Kasa cameras transport no no no yes no
20002 discovery yes, with the encrypted part no no no yes, with the encrypted part yes
Hub and strip children yes, typed sensors yes, typed (T300, T31x) no Kasa strips yes yes, typed
multipleRequest, typed device helpers yes yes no Kasa models yes yes
Energy history Kasa day and month; Tapo hourly, daily, monthly Tapo no Kasa Kasa day and month Tapo
Schedules and countdowns Kasa and Tapo read and write no no Kasa read Kasa read and delete; Tapo read Tapo plugs read and write
Firmware update Tapo check, update, progress; Kasa list no no no Tapo no
Wi-Fi set-up Kasa and Tapo no no Kasa Kasa, Tapo, cameras no
Vendor setup accounts caller-supplied no no n/a built in n/a
Device simulators for tests yes, separate module no no no in-process fakes from recorded fixtures no
Interop evidence against python-kasa both ways and the tapo crate (below) none stated none stated none stated the reference, recorded fixtures real devices named in its support table
Go version, dependencies 1.22; lanbcast 1.20; none 1.21; none 1.25; a TUI and CLI stack n/a n/a
Licence Apache-2.0 MIT Apache-2.0 BSD-2-Clause GPL-3.0 MIT

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, robot vacuums 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. Outside Go, python-kasa is still ahead in built-in light effect definitions, camera stream URLs and the number of firmware versions recorded from real devices, and the tapo crate in camera snapshots and recordings download and in TPAP having been run against real devices. python-kasa's open TPAP pull request (#1592) describes more TPAP variants (the default passcode, more suites, the device certificate proof) than this module or the tapo crate implement.

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, SSLAESClient and TPAPClient, and TapoFound.BaseURL() for the URL. A device found by its address that refuses KLAP may be in TPAP mode; ask it:

if info, _ := tplink.TPAPDiscover(ctx, hc, "http://"+host); info != nil {
	c := &tplink.TPAPClient{Base: info.BaseURL(host), Password: password, HTTP: hc}
	info, err := c.Call(ctx, "get_device_info", nil)
}

TPAP logs in with the account password only (the login names the device's fixed local user, not the email). 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. TPAP: TPAPClient (Call, Send, Handshake), TPAPDiscover, TPAPInfo (BaseURL, PasscodeType), ParseTPAPInfo, TPAPCameraInfo, TPAPPasscode, TPAPPasscodeSHA1, TPAPVerifier and TPAPCipher (the device side, for simulators), ErrTPAPAuth, ErrTPAPLocked, ErrTPAPDeviceProof, ErrTPAPUnsupported. Tapo: SmartCaller, MultiCall, MultiCallChild, SmartList, Components, ChildComponents, ChildList, ControlChild, TapoDevice (Info, SetLight, EnergyData, Rules, ScheduleRules, AddScheduleRule, EditScheduleRule, RemoveScheduleRules, CountdownRules, AddCountdown, ReplaceCountdown, RemoveCountdowns, LatestFirmware, StartFirmwareUpdate, WifiJoin, Children, TriggerLogs, ...), TapoScheduleRule, ParseTapoScheduleRule, TapoCountdownRule, SmartError, IsUnsupported. Cameras: TapoCamera (Info, Move, Presets, GotoPreset, SetPrivacy, SetLED, Detection, SetDetection, Siren, SoundSiren, SetAlert, ManualAlarm, SetNightVision, Time, SetTimezone, SDCards, RecordingDays, Recordings, Reboot, ...), CamSingle, CamInfo, CamDetectionKind, ErrNoSingleRequests. Robot vacuums: TapoVacuum (Status, Start, CleanRooms, Pause, Resume, ReturnHome, SetSuction, SetWaterLevel, Consumables, CleanRecords, Maps, Rooms, DustCollection, EmptyDustbin, Volume, Locate, ...), VacuumStatus. 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).
  • Added in v0.3.0, 2026-10-12, Docker Desktop on arm64, the same python-kasa 0.11.0.1 and fixtures (the peer image is now tagged sigma-tplink-interop:python-kasa-0.11.0.1-r3), all passed:
    • camera helpers against a recorded C220(EU) 1.2.5 camera over the camera transport: information, the 48 app components, status light, privacy, all ten detection settings (motion, person, baby cry, tamper and line crossing compared with the recording), night vision, last alarm, clock and time zone, SD card, alarm on detection, connection, saved positions, Wi-Fi scan; the status light, person detection and night vision changed and read back; the motor move, a saved position and the manual alarm (single form) checked as the device received them;
    • the siren of a recorded H200(EU) 1.3.6 hub (answers without the module level), changed and read back;
    • robot vacuum helpers against the recorded RV30 Max(US) 1.2.0 over the plain HTTPS transport: status, clean records, consumables, maps, rooms, volume, mop, carpet boost, area unit compared with the recording, and its missing dust collection reported as unsupported.
  • Changing Tapo schedules and countdowns is not in python-kasa; it was checked against the tapo crate's client (below, in tplink-sim's interop: the tapo crate's Python bindings 0.11.1 and this module's client on one simulated plug, each reading what the other wrote).
  • Added in v0.4.0, 2026-10-12: TPAP. python-kasa has none to test against (neither 0.11.0.1 nor master 38a3184; its pull request #1592 is not merged), so:
    • SPAKE2+ is checked against RFC 9383's P-256 / SHA-256 test vector on both sides (shares, confirmations, shared key), and the passcode forms, the PBKDF2 split into w0 and w1 and the session cipher against the known answers in the tapo crate 0.11.1's unit tests (tpap_test.go);
    • the tapo crate's own client (Python bindings 0.11.1) logged in over TPAP to tplink-sim's TPAP plug and camera, which are built on this module's verifier and cipher, and read and switched them (in tplink-sim's interop); with the vectors above, that ties this client's side to tapo's.
    • Not checked: a real device in TPAP mode.
  • 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 away (antitheft) rules (reading them is supported) no open-source client sends their write requests: checked python-kasa 0.11.0.1 and master (2026-10-09), the tapo crate 0.11.1, plugp100 6.0.1 and pytapo 3.4.26 on 2026-10-12; Call reaches the device's methods
TPAP with the default passcode (passcode type 0), other passcode transforms (password_shadow 1, 3, 5 and others), cipher suites other than 1 and session ciphers other than AES-128-CCM the tapo crate, which has been run against real devices, implements none of them; python-kasa's unmerged pull request #1592 describes some, untested against real devices as far as its tests show. A device listing the default passcode next to the account password is offered the account password
TPAP's device certificate proof (dac) and TLS mode 2 with the vendor's CA needs the vendor's root certificate, which this module does not ship; with TLS mode 2 the caller's HTTP client decides what it trusts
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 video, snapshots and recording download streams belong outside this module; the clips are listed (Recordings)
Typed helpers for Kasa camera modules beyond the sysinfo the Kasa camera transport is supported (LinkieClient, KasaDevice); python-kasa, the only open client found for them, reads only their sysinfo and on state
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 TPAP login of newer firmware (TPAPClient, TPAPDiscover: SPAKE2+ and AES-128-CCM with the account password), 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, schedules and countdowns read and changed, auto-off, LED, firmware update, Wi-Fi scan and set-up, hub sensors and button logs), TapoCamera (pan and tilt with presets, privacy, status light, ten detection settings, siren and alarm, night vision, clock, SD card, recordings list) and TapoVacuum (status, cleaning, suction and water, consumables, records, maps and rooms, dustbin, volume).

It needs the owner's TP-Link account for KLAP, securePassthrough and TPAP 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 (
	NightVisionInfrared  = "inf_night_vision"
	NightVisionFullColor = "wtl_night_vision"
	NightVisionSmart     = "md_night_vision"
)

Night vision modes (night_vision_mode): infrared, full colour with the white light, and smart (infrared that switches to colour on motion).

View Source
const (
	ScheduleAtTime  = "normal"
	ScheduleSunrise = "sunrise"
	ScheduleSunset  = "sunset"
)

Schedule start kinds (s_type): a clock time, or an offset from sunrise or sunset.

View Source
const (
	Sunday uint8 = 1 << iota
	Monday
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday

	Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday
	Weekend  = Saturday | Sunday
	EveryDay = Weekdays | Weekend
)

Weekdays of a repeating schedule (week_day), Sunday the lowest bit.

View Source
const (
	ConsumableMainBrush      = "roll_brush"
	ConsumableSideBrush      = "edge_brush"
	ConsumableFilter         = "filter"
	ConsumableSensor         = "sensor"
	ConsumableChargeContacts = "charge_contact"
	ConsumableMainBrushLid   = "main_brush_lid"
	ConsumableMop            = "rag"
)

The consumable names ResetConsumable takes (the getConsumablesInfo field without "_time").

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 (
	// ErrTPAPAuth means the device refused the password.
	ErrTPAPAuth = errors.New("the device refused the password (TPAP)")
	// ErrTPAPLocked means the device locked itself after too many failed
	// logins; it refuses every login for a while, so do not retry at once.
	ErrTPAPLocked = errors.New("the device is locked after too many failed TPAP logins")
	// ErrTPAPDeviceProof means the device accepted the login but could not
	// prove that it knows the password: not the device it claims to be.
	ErrTPAPDeviceProof = errors.New("the device could not prove it knows the password (TPAP)")
	// ErrTPAPUnsupported means the device asks for a part of TPAP this
	// module does not implement.
	ErrTPAPUnsupported = errors.New("the device asks for a TPAP variant this module does not support")
)

Errors of the TPAP login.

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 ErrNoSingleRequests = errors.New("this camera path does not take single requests")

ErrNoSingleRequests is returned for a camera request that only has the single form ({"method": "do", ...}) on a transport or path that cannot send it (a camera behind a hub, or a transport without Send).

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 CamSingle added in v0.3.0

func CamSingle(ctx context.Context, c SmartCaller, verb, module string, body any) (map[string]any, error)

CamSingle sends the single form of a camera request: {"method": verb, module: body}, with verb "get", "set" or "do" (some requests exist only in this form). c must send raw requests (SSLAESClient does). The answer is returned without its error_code; an error code is a *SmartError.

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 TPAPPasscode added in v0.4.0

func TPAPPasscode(password string, extraCrypt map[string]any, camera bool) (string, error)

TPAPPasscode is the string the login proves knowledge of, from the account password and the extra_crypt of the device's pake_register answer: for password_shadow with passwd_id 2 the hex SHA-1 of the password; for a camera that names none the hex MD5. Other forms are ErrTPAPUnsupported.

func TPAPPasscodeSHA1 added in v0.4.0

func TPAPPasscodeSHA1(password string) string

TPAPPasscodeSHA1 is the passcode of extra_crypt password_shadow with passwd_id 2: the lower-case hex SHA-1 of the password.

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.

func TimezoneOffset added in v0.3.0

func TimezoneOffset(d time.Duration) string

TimezoneOffset formats an offset from UTC as cameras write it ("UTC+05:30").

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 CamAlert added in v0.3.0

type CamAlert struct {
	Enabled  bool
	Modes    []string
	Volume   string
	Duration string
	Raw      map[string]any
}

CamAlert is a camera's alarm on detection (msg_alarm chn1_msg_alarm_info): on or off, the alarm kinds (sound, light), the volume and duration as the camera gives them; Raw holds every field.

type CamConnection added in v0.3.0

type CamConnection struct {
	Link  string // wifi, ethernet
	Level int
	RSSI  int
	SSID  string // decoded from base64
}

CamConnection is getConnectionType: link, signal level (0-4) and RSSI.

type CamDetection added in v0.3.0

type CamDetection struct {
	Enabled     bool
	Sensitivity string
	Raw         map[string]any
}

CamDetection is one detection setting: on or off, the sensitivity as the camera gives it (a level such as "medium", or a number as text; "digital_sensitivity" when present), and every field in Raw.

type CamDetectionKind added in v0.3.0

type CamDetectionKind string

CamDetectionKind names a detection setting.

const (
	DetectMotion       CamDetectionKind = "motion"
	DetectPerson       CamDetectionKind = "person"
	DetectPet          CamDetectionKind = "pet"
	DetectVehicle      CamDetectionKind = "vehicle"
	DetectBabyCry      CamDetectionKind = "baby_cry"
	DetectBark         CamDetectionKind = "bark"
	DetectMeow         CamDetectionKind = "meow"
	DetectGlassBreak   CamDetectionKind = "glass_break"
	DetectTamper       CamDetectionKind = "tamper"
	DetectLineCrossing CamDetectionKind = "line_crossing"
)

The detections cameras offer (each behind its own app component).

func CamDetectionKinds added in v0.3.0

func CamDetectionKinds() []CamDetectionKind

CamDetectionKinds lists every detection kind the helpers know.

type CamDisk added in v0.3.0

type CamDisk struct {
	Name       string
	Status     string
	TotalSpace string
	FreeSpace  string
	Raw        map[string]any
}

CamDisk is one storage card (getSdCardStatus harddisk_manage.hd_info): its status (normal, offline, ...), sizes as the camera writes them ("29.7GB") and every field in Raw.

type CamInfo added in v0.3.0

type CamInfo struct {
	Model     string // device_model
	Type      string // device_type: SMART.IPCAMERA, SMART.TAPODOORBELL, ...
	Alias     string // device_alias
	FWVersion string // sw_version
	HWVersion string // hw_version
	MAC       string
	DeviceID  string // dev_id
	// Battery cameras: the charge in percent, low battery, charging and
	// the power source (power: BATTERY or another value).
	Battery    *int
	LowBattery bool
	Charging   bool
	Power      string
	Raw        map[string]any
}

CamInfo is the camera's basic_info. Raw holds every field.

func ParseCamInfo added in v0.3.0

func ParseCamInfo(bi map[string]any) CamInfo

ParseCamInfo reads a basic_info answer.

type CamLastAlarm added in v0.3.0

type CamLastAlarm struct {
	Time time.Time // zero when there was none
	Type string    // motion, ...
}

CamLastAlarm is the last detection the camera alarmed on (getLastAlarmInfo).

type CamPreset added in v0.3.0

type CamPreset struct {
	ID   string
	Name string
}

CamPreset is a saved camera position.

type CamRecording added in v0.3.0

type CamRecording struct {
	Start, End time.Time
	Type       int // video_type: 1 timed, 2 motion, ... as the camera numbers them
}

CamRecording is one recorded clip.

type CamSiren added in v0.3.0

type CamSiren struct {
	Active   bool
	Sound    string
	Volume   int
	Duration int
	Sounds   []string
}

CamSiren is a siren's state and settings (doorbells, hubs, newer cameras): sounding or not, the sound, volume and duration in seconds, and the sounds it offers.

type CamTime added in v0.3.0

type CamTime struct {
	Time     time.Time // the clock, in the camera's zone when Go knows it
	ZoneID   string    // zone_id, an IANA name
	Timezone string    // timezone, "UTC+01:00"
}

CamTime is the camera's clock and time zone.

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 DustMode added in v0.3.0

type DustMode int

DustMode is how hard a dock empties the dustbin.

const (
	DustSmart    DustMode = 0
	DustLight    DustMode = 1
	DustBalanced DustMode = 2
	DustMax      DustMode = 3
)

The emptying modes.

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 TPAPCipher added in v0.4.0

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

TPAPCipher is the cipher of a TPAP session: AES-128-CCM with a 16-byte tag, the key and the nonce base derived from the shared key with HKDF; each body is the 4-byte big-endian sequence number, then the ciphertext and tag. The nonce is the base's first 8 bytes and the sequence number.

func NewTPAPCipher added in v0.4.0

func NewTPAPCipher(sharedKey []byte) (*TPAPCipher, error)

NewTPAPCipher derives the session cipher from the login's shared key.

func (*TPAPCipher) Open added in v0.4.0

func (t *TPAPCipher) Open(seq int32, body []byte) ([]byte, error)

Open checks a body's sequence number and tag and returns the message.

func (*TPAPCipher) Seal added in v0.4.0

func (t *TPAPCipher) Seal(seq int32, plain []byte) []byte

Seal returns the body for a sequence number: the device answers under the request's.

type TPAPClient added in v0.4.0

type TPAPClient struct {
	// Base is http://host:port or https://host:port: TPAPInfo.BaseURL.
	Base string
	// Password is the owner's TP-Link account password. The login names
	// the device's fixed local user, not the account email.
	Password string
	// Camera marks a camera, doorbell or camera hub: a password with no
	// transform named is hashed with MD5, and answers are read as camera
	// answers.
	Camera bool
	// PasscodeType is the passcode_type offered ("" is "userpw", the
	// account password).
	PasscodeType string
	// HTTP is the client; InsecureHTTP for a device on HTTPS (TLS 1).
	HTTP *http.Client
	// contains filtered or unexported fields
}

TPAPClient talks TPAP to one device, keeping its session. It is a SmartCaller: Tapo requests for plugs, bulbs, hubs and strips, camera requests (CamGet, MultiCall, TapoCamera) for cameras.

func (*TPAPClient) Call added in v0.4.0

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

Call sends {"method", "params"} and returns the result, as the other clients do.

func (*TPAPClient) Handshake added in v0.4.0

func (t *TPAPClient) Handshake(ctx context.Context) error

Handshake logs in now, without a request, and keeps the session.

func (*TPAPClient) Send added in v0.4.0

func (t *TPAPClient) 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 there is no session and again once when the device ended it.

type TPAPInfo added in v0.4.0

type TPAPInfo struct {
	// TLS is 0 for plain HTTP, 1 for HTTPS with a certificate the client
	// does not check, 2 for HTTPS with one it checks.
	TLS int
	// Port is the port the login and requests go to (0: 80, or 443 over
	// TLS).
	Port int
	// Pake are the passcode types the device takes: 0 the default
	// passcode, 2 the account password, others.
	Pake []int
	// DAC and NOC are the device's certificate flags, as announced.
	DAC, NOC int
}

TPAPInfo is how a device in TPAP mode wants to be logged in to: the "tpap" object of its discover answer or of its 20002 discovery answer.

func ParseTPAPInfo added in v0.4.0

func ParseTPAPInfo(v any) (TPAPInfo, error)

ParseTPAPInfo reads a "tpap" object.

func TPAPCameraInfo added in v0.4.0

func TPAPCameraInfo() TPAPInfo

TPAPCameraInfo is how a camera reached by its address is logged in to over TPAP: the account password over HTTPS on port 443. Cameras do not answer discover; these are the values a C220 announces in its 20002 answer, as the tapo crate records.

func TPAPDiscover added in v0.4.0

func TPAPDiscover(ctx context.Context, hc *http.Client, base string) (*TPAPInfo, error)

TPAPDiscover asks the device at base (http://host[:port], port 80 on devices) whether it is in TPAP mode. It returns the device's TPAPInfo, or nil when the device does not answer as a device in TPAP mode (KLAP mode, older firmware). ErrTPAPLocked when the device is locked.

func (TPAPInfo) BaseURL added in v0.4.0

func (i TPAPInfo) BaseURL(host string) string

BaseURL is the URL of a device at host for TPAPClient.Base. A host that names a port (a forwarded port, a simulator) keeps it.

func (TPAPInfo) PasscodeType added in v0.4.0

func (i TPAPInfo) PasscodeType() (string, error)

PasscodeType is the passcode_type the client offers: "userpw" (the account password) when the device lists type 2. The Tapo app prefers the default passcode when a device lists it as well; this client offers the account password then too, as it has no default passcode.

type TPAPVerifier added in v0.4.0

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

TPAPVerifier is the device side of one TPAP login, for simulators and tests: NewTPAPVerifier at pake_register, Finish at pake_share.

func NewTPAPVerifier added in v0.4.0

func NewTPAPVerifier(passcode string, salt []byte, iterations int, userRandom, devRandom []byte) (*TPAPVerifier, error)

NewTPAPVerifier starts the device side for the passcode (TPAPPasscode of the account password), the salt and iterations it announces, and both randoms. Share is the device's share (dev_share).

func (*TPAPVerifier) Finish added in v0.4.0

func (t *TPAPVerifier) Finish(userShare, userConfirm []byte) (devConfirm, sharedKey []byte, err error)

Finish checks the client's share and confirmation (ErrTPAPAuth for a wrong password) and returns the device's confirmation and the shared key for NewTPAPCipher.

func (*TPAPVerifier) Share added in v0.4.0

func (t *TPAPVerifier) Share() []byte

Share is the device's share, uncompressed.

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 TapoCamera added in v0.3.0

type TapoCamera struct {
	Caller  SmartCaller
	ChildID string // a camera behind an H200 hub: its device_id
}

TapoCamera is a Tapo camera or doorbell, or one camera behind an H200 hub (ChildID), with typed helpers for the camera requests open clients describe: device information, name, pan and tilt with presets, privacy (the lens mask), status light, detection settings, siren and alarm, night vision, clock, SD card, recordings list, Wi-Fi scan and reboot. Video and pictures are not part of this module.

Caller is the transport: an SSLAESClient (or any SmartCaller whose device takes camera requests in a multipleRequest). Each helper names the request it sends; Call and CamSingle reach anything else.

func (TapoCamera) Alert added in v0.3.0

func (c TapoCamera) Alert(ctx context.Context) (CamAlert, error)

Alert asks getAlertConfig.

func (TapoCamera) Calibrate added in v0.3.0

func (c TapoCamera) Calibrate(ctx context.Context) error

Calibrate runs the motor calibration (manualCalibrate).

func (TapoCamera) Call added in v0.3.0

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

Call sends one camera request (in a multipleRequest, or through the hub with controlChild) and returns its result.

func (TapoCamera) Components added in v0.3.0

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

Components asks getAppComponentList: the camera's features with their versions (ptz, lensMask, detection, personDetection, siren, ...).

func (TapoCamera) Connection added in v0.3.0

func (c TapoCamera) Connection(ctx context.Context) (CamConnection, error)

Connection asks getConnectionType.

func (TapoCamera) DayNight added in v0.3.0

func (c TapoCamera) DayNight(ctx context.Context) (string, error)

DayNight asks the day and night switching of older firmware (getDayNightModeConfig, image.common.inf_type: auto, on, off).

func (TapoCamera) DeletePreset added in v0.3.0

func (c TapoCamera) DeletePreset(ctx context.Context, ids ...string) error

DeletePreset removes saved positions (deletePreset).

func (TapoCamera) Detection added in v0.3.0

func (c TapoCamera) Detection(ctx context.Context, kind CamDetectionKind) (CamDetection, error)

Detection reads a detection setting (getDetectionConfig, getPersonDetectionConfig, ...; see CamDetectionKind).

func (TapoCamera) FormatSDCard added in v0.3.0

func (c TapoCamera) FormatSDCard(ctx context.Context) error

FormatSDCard erases the storage card (formatSdCard).

func (TapoCamera) GotoPreset added in v0.3.0

func (c TapoCamera) GotoPreset(ctx context.Context, id string) error

GotoPreset turns the camera to a saved position (motorMoveToPreset).

func (TapoCamera) Info added in v0.3.0

func (c TapoCamera) Info(ctx context.Context) (CamInfo, error)

Info asks getDeviceInfo (device_info.basic_info).

func (TapoCamera) LED added in v0.3.0

func (c TapoCamera) LED(ctx context.Context) (bool, error)

LED reports whether the status light is on (getLedStatus).

func (TapoCamera) LastAlarm added in v0.3.0

func (c TapoCamera) LastAlarm(ctx context.Context) (CamLastAlarm, error)

LastAlarm asks getLastAlarmInfo.

func (TapoCamera) ManualAlarm added in v0.3.0

func (c TapoCamera) ManualAlarm(ctx context.Context, start bool) error

ManualAlarm starts or stops the alarm by hand ({"method": "do", "msg_alarm": {"manual_msg_alarm": {"action": "start"|"stop"}}}).

func (TapoCamera) Move added in v0.3.0

func (c TapoCamera) Move(ctx context.Context, x, y int) error

Move turns the camera by x (pan) and y (tilt) steps (motorMove). A camera that refuses it is sent the single form {"method": "do", "motor": {"move": ...}} where the transport allows.

func (TapoCamera) MoveStep added in v0.3.0

func (c TapoCamera) MoveStep(ctx context.Context, angle int) error

MoveStep turns the camera one step towards angle degrees (0-359; relativeMove).

func (TapoCamera) NightVision added in v0.3.0

func (c TapoCamera) NightVision(ctx context.Context) (string, error)

NightVision asks the night vision mode (getNightVisionModeConfig, image.switch.night_vision_mode).

func (TapoCamera) Presets added in v0.3.0

func (c TapoCamera) Presets(ctx context.Context) ([]CamPreset, error)

Presets reads the saved positions (getPresetConfig).

func (TapoCamera) Privacy added in v0.3.0

func (c TapoCamera) Privacy(ctx context.Context) (bool, error)

Privacy reports whether the lens mask (privacy mode) is on (getLensMaskConfig). With it on the camera does not film.

func (TapoCamera) Reboot added in v0.3.0

func (c TapoCamera) Reboot(ctx context.Context) error

Reboot restarts the camera (rebootDevice).

func (TapoCamera) RecordingDays added in v0.3.0

func (c TapoCamera) RecordingDays(ctx context.Context, from, to time.Time, childID string) ([]string, error)

RecordingDays lists the days between from and to (inclusive, as YYYYMMDD) that have recordings (searchDateWithVideo). For a camera behind a hub, childID is its device_id; "" otherwise.

func (TapoCamera) Recordings added in v0.3.0

func (c TapoCamera) Recordings(ctx context.Context, from, to time.Time, start, end int, childID string) ([]CamRecording, error)

Recordings lists the clips between from and to (searchVideoWithUTC), entries start to end (0 and 0: the first 100). childID as for RecordingDays.

func (TapoCamera) SDCards added in v0.3.0

func (c TapoCamera) SDCards(ctx context.Context) ([]CamDisk, error)

SDCards asks getSdCardStatus.

func (TapoCamera) SavePreset added in v0.3.0

func (c TapoCamera) SavePreset(ctx context.Context, name string) error

SavePreset saves the current position under name (addMotorPostion, the device's spelling).

func (TapoCamera) SetAlert added in v0.3.0

func (c TapoCamera) SetAlert(ctx context.Context, fields map[string]any) error

SetAlert changes the alarm on detection with the camera's field names (enabled "on"/"off", alarm_mode, alarm_volume, ...), as the single set request {"method": "set", "msg_alarm": {"chn1_msg_alarm_info": ...}}.

func (TapoCamera) SetAlias added in v0.3.0

func (c TapoCamera) SetAlias(ctx context.Context, name string) error

SetAlias renames the camera (setDeviceAlias).

func (TapoCamera) SetDayNight added in v0.3.0

func (c TapoCamera) SetDayNight(ctx context.Context, mode string) error

SetDayNight sets it (setDayNightModeConfig).

func (TapoCamera) SetDetection added in v0.3.0

func (c TapoCamera) SetDetection(ctx context.Context, kind CamDetectionKind, on bool) error

SetDetection switches a detection on or off.

func (TapoCamera) SetDetectionConfig added in v0.3.0

func (c TapoCamera) SetDetectionConfig(ctx context.Context, kind CamDetectionKind, fields map[string]any) error

SetDetectionConfig changes a detection's fields as the camera names them (enabled "on"/"off", sensitivity, digital_sensitivity, ...).

func (TapoCamera) SetLED added in v0.3.0

func (c TapoCamera) SetLED(ctx context.Context, on bool) error

SetLED switches the status light (setLedStatus).

func (TapoCamera) SetNightVision added in v0.3.0

func (c TapoCamera) SetNightVision(ctx context.Context, mode string) error

SetNightVision sets the night vision mode (setNightVisionModeConfig).

func (TapoCamera) SetPrivacy added in v0.3.0

func (c TapoCamera) SetPrivacy(ctx context.Context, on bool) error

SetPrivacy switches the lens mask (setLensMaskConfig).

func (TapoCamera) SetSiren added in v0.3.0

func (c TapoCamera) SetSiren(ctx context.Context, sound string, volume, duration int) error

SetSiren changes the siren's sound, volume (1-10) and duration in seconds (setSirenConfig); empty or zero values are left as they are.

func (TapoCamera) SetTimezone added in v0.3.0

func (c TapoCamera) SetTimezone(ctx context.Context, zoneID, offset string) error

SetTimezone sets the time zone (setTimezone): an IANA zone_id and its offset as "UTC+HH:MM". The camera keeps its clock by NTP; it takes no clock time.

func (TapoCamera) Siren added in v0.3.0

func (c TapoCamera) Siren(ctx context.Context) (CamSiren, error)

Siren asks getSirenStatus, getSirenConfig and getSirenTypeList.

func (TapoCamera) SoundSiren added in v0.3.0

func (c TapoCamera) SoundSiren(ctx context.Context, on bool) error

SoundSiren starts or stops the siren (setSirenStatus).

func (TapoCamera) Time added in v0.3.0

func (c TapoCamera) Time(ctx context.Context) (CamTime, error)

Time asks getClockStatus and getTimezone.

func (TapoCamera) WifiScan added in v0.3.0

func (c TapoCamera) WifiScan(ctx context.Context) ([]WifiNetwork, error)

WifiScan asks the networks the camera sees (scanApList).

type TapoCountdownRule added in v0.3.0

type TapoCountdownRule struct {
	ID     string
	Enable bool
	Delay  int
	Remain int
	On     bool
}

TapoCountdownRule is a countdown: switch to On after Delay seconds; Remain is what is left of a running one.

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) AddCountdown added in v0.3.0

func (d TapoDevice) AddCountdown(ctx context.Context, delay int, on bool) (string, error)

AddCountdown starts a countdown that switches the device to on after delay seconds (add_countdown_rule) and returns its id. Plugs hold one countdown: a second is refused (error -1902) until the first is removed (RemoveCountdowns); ReplaceCountdown does both.

func (TapoDevice) AddScheduleRule added in v0.3.0

func (d TapoDevice) AddScheduleRule(ctx context.Context, r TapoScheduleRule) (string, error)

AddScheduleRule adds a rule (add_schedule_rule) and returns the id the device gave it. A full schedule is refused with error -1802, a rule at the time of another with -1803.

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) CountdownRules added in v0.3.0

func (d TapoDevice) CountdownRules(ctx context.Context) ([]TapoCountdownRule, error)

CountdownRules reads the countdowns, typed (get_countdown_rules).

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) EditScheduleRule added in v0.3.0

func (d TapoDevice) EditScheduleRule(ctx context.Context, r TapoScheduleRule) error

EditScheduleRule replaces the rule with r.ID (edit_schedule_rule).

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) RemoveCountdowns added in v0.3.0

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

RemoveCountdowns removes every countdown (remove_countdown_rules).

func (TapoDevice) RemoveScheduleRules added in v0.3.0

func (d TapoDevice) RemoveScheduleRules(ctx context.Context, ids ...string) error

RemoveScheduleRules removes the rules with the ids, or every rule when none is given (remove_schedule_rules).

func (TapoDevice) ReplaceCountdown added in v0.3.0

func (d TapoDevice) ReplaceCountdown(ctx context.Context, delay int, on bool) (string, error)

ReplaceCountdown removes any countdown and starts a new one.

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). ScheduleRules and CountdownRules read them typed; AddScheduleRule, EditScheduleRule, RemoveScheduleRules, AddCountdown and RemoveCountdowns change them (taporules.go). Away rules are read only.

func (TapoDevice) ScheduleRules added in v0.3.0

func (d TapoDevice) ScheduleRules(ctx context.Context) ([]TapoScheduleRule, error)

ScheduleRules reads the schedule, typed (get_schedule_rules, paged).

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
	// TPAP is the answer's tpap object: how a device that takes the TPAP
	// login wants it (since v0.4.0). A camera announcing it may take its
	// HTTPS login too.
	TPAP *TPAPInfo
}

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, aes or, since v0.4.0, tpap ("" when not told). A device in TPAP mode answers with encrypt_type TPAP and a tpap object; use TPAPClient with TPAP.BaseURL(Host).

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 TapoScheduleRule added in v0.3.0

type TapoScheduleRule struct {
	ID     string // given by the device; empty for a new rule
	Enable bool
	// Start is ScheduleAtTime (Minute is the minute of the day, 0-1439) or
	// ScheduleSunrise / ScheduleSunset (Offset is minutes from the event,
	// negative before it).
	Start  string
	Minute int
	Offset int
	// Days are the weekdays a repeating rule runs on (Sunday, Monday, ...);
	// 0 runs the rule once.
	Days uint8
	On   bool // the state the rule switches to
	// Raw is the rule as the device gave it (ParseTapoScheduleRule); its
	// other fields are sent back unchanged by EditScheduleRule.
	Raw map[string]any
}

TapoScheduleRule is one rule of a plug's or light's schedule.

func ParseTapoScheduleRule added in v0.3.0

func ParseTapoScheduleRule(m map[string]any) TapoScheduleRule

ParseTapoScheduleRule reads a rule of get_schedule_rules. Older firmware gives the state as s_action ("on", "off") instead of desired_states.

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 TapoVacuum added in v0.3.0

type TapoVacuum struct {
	Caller SmartCaller // an SSLClient, KLAPClient or AESClient
}

TapoVacuum is a Tapo robot vacuum over any Tapo transport.

func (TapoVacuum) AreaUnit added in v0.3.0

func (v TapoVacuum) AreaUnit(ctx context.Context) (VacuumAreaUnit, error)

AreaUnit asks getAreaUnit.

func (TapoVacuum) CarpetBoost added in v0.3.0

func (v TapoVacuum) CarpetBoost(ctx context.Context) (bool, error)

CarpetBoost asks getCarpetClean: whether suction rises on carpet (carpet_clean_prefer "boost" rather than "normal").

func (TapoVacuum) CleanRecords added in v0.3.0

func (v TapoVacuum) CleanRecords(ctx context.Context) (VacuumRecords, error)

CleanRecords asks getCleanRecords.

func (TapoVacuum) CleanRooms added in v0.3.0

func (v TapoVacuum) CleanRooms(ctx context.Context, mapID int64, rooms []int) error

CleanRooms cleans the rooms (ids from Rooms) of a map (setSwitchClean with clean_mode 3, map_id, room_list and start_type 1), with the global suction, water and pass count.

func (TapoVacuum) Consumables added in v0.3.0

func (v TapoVacuum) Consumables(ctx context.Context) (VacuumConsumables, error)

Consumables asks getConsumablesInfo.

func (TapoVacuum) DustCollection added in v0.3.0

func (v TapoVacuum) DustCollection(ctx context.Context) (VacuumDustCollection, error)

DustCollection asks getDustCollectionInfo; firmware without it is asked getAutoDustCollection (Mode then stays DustSmart).

func (TapoVacuum) EmptyDustbin added in v0.3.0

func (v TapoVacuum) EmptyDustbin(ctx context.Context) error

EmptyDustbin makes the dock empty the dustbin now (setSwitchDustCollection {"switch_dust_collection": true}).

func (TapoVacuum) Locate added in v0.3.0

func (v TapoVacuum) Locate(ctx context.Context) error

Locate makes the vacuum call out (playSelectAudio {"audio_type": "seek_me"}).

func (TapoVacuum) Maps added in v0.3.0

func (v TapoVacuum) Maps(ctx context.Context) (VacuumMaps, error)

Maps asks getMapInfo.

func (TapoVacuum) MopAttached added in v0.3.0

func (v TapoVacuum) MopAttached(ctx context.Context) (bool, error)

MopAttached asks getMopState.

func (TapoVacuum) Pause added in v0.3.0

func (v TapoVacuum) Pause(ctx context.Context) error

Pause pauses a clean (setRobotPause {"pause": true}).

func (TapoVacuum) ResetConsumable added in v0.3.0

func (v TapoVacuum) ResetConsumable(ctx context.Context, name string) error

ResetConsumable zeroes a part's use after it was replaced (resetConsumablesTime {"reset_list": [name]}); name is a Consumable* constant (a trailing "_time" is dropped).

func (TapoVacuum) Resume added in v0.3.0

func (v TapoVacuum) Resume(ctx context.Context) error

Resume continues a paused clean (setRobotPause {"pause": false}).

func (TapoVacuum) ReturnHome added in v0.3.0

func (v TapoVacuum) ReturnHome(ctx context.Context) error

ReturnHome sends the vacuum to its dock (setSwitchCharge {"switch_charge": true}).

func (TapoVacuum) Rooms added in v0.3.0

func (v TapoVacuum) Rooms(ctx context.Context, mapID int64) ([]VacuumRoom, error)

Rooms reads the rooms of a map (getMapData {"map_id", "type": 0}, the area_list entries of type "room").

func (TapoVacuum) SetCarpetBoost added in v0.3.0

func (v TapoVacuum) SetCarpetBoost(ctx context.Context, on bool) error

SetCarpetBoost sends setCarpetClean with "boost" or "normal".

func (TapoVacuum) SetCleanCount added in v0.3.0

func (v TapoVacuum) SetCleanCount(ctx context.Context, n int) error

SetCleanCount sets the passes per clean, 1 to 3 on known firmware (setCleanAttr clean_number, type global).

func (TapoVacuum) SetDustCollection added in v0.3.0

func (v TapoVacuum) SetDustCollection(ctx context.Context, d VacuumDustCollection) error

SetDustCollection sends setDustCollectionInfo.

func (TapoVacuum) SetSuction added in v0.3.0

func (v TapoVacuum) SetSuction(ctx context.Context, s VacuumSuction) error

SetSuction sets the fan power (setCleanAttr suction, type global).

func (TapoVacuum) SetVolume added in v0.3.0

func (v TapoVacuum) SetVolume(ctx context.Context, volume int) error

SetVolume sends setVolume (0 to 100).

func (TapoVacuum) SetWaterLevel added in v0.3.0

func (v TapoVacuum) SetWaterLevel(ctx context.Context, w VacuumWater) error

SetWaterLevel sets the mop's water flow (setCleanAttr cistern, type global).

func (TapoVacuum) Start added in v0.3.0

func (v TapoVacuum) Start(ctx context.Context) error

Start cleans the whole home (setSwitchClean with clean_mode 0, clean_on, clean_order and force_clean false). A paused clean is continued with Resume.

func (TapoVacuum) Status added in v0.3.0

func (v TapoVacuum) Status(ctx context.Context) (VacuumStatus, error)

Status asks getVacStatus, getBatteryInfo, getCleanInfo, getCleanAttr {"type": "global"} and getCleanStatus in one MultiCall. The error is set only when the transport failed.

func (TapoVacuum) StopReturn added in v0.3.0

func (v TapoVacuum) StopReturn(ctx context.Context) error

StopReturn stops the way to the dock (setSwitchCharge {"switch_charge": false}).

func (TapoVacuum) Volume added in v0.3.0

func (v TapoVacuum) Volume(ctx context.Context) (int, error)

Volume asks getVolume (percent).

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 VacuumAreaUnit added in v0.3.0

type VacuumAreaUnit int

VacuumAreaUnit is the unit the vacuum reports areas in.

const (
	AreaSquareMetres VacuumAreaUnit = 0
	AreaSquareFeet   VacuumAreaUnit = 1
	AreaPing         VacuumAreaUnit = 2 // the Taiwanese unit, about 3.3 m²
)

The area units.

type VacuumCleanMode added in v0.3.0

type VacuumCleanMode int

VacuumCleanMode is what a clean covers (setSwitchClean clean_mode, getCleanStatus clean_status).

const (
	VacuumModeHome       VacuumCleanMode = 0 // every room alike
	VacuumModeHomeCustom VacuumCleanMode = 1 // every room with its own settings and order
	VacuumModeSpot       VacuumCleanMode = 2 // around where it stands
	VacuumModeRooms      VacuumCleanMode = 3 // the rooms named
	VacuumModeZones      VacuumCleanMode = 4 // drawn zones
	VacuumModePreset     VacuumCleanMode = 5 // a saved preset
)

The clean modes.

type VacuumConsumables added in v0.3.0

type VacuumConsumables struct {
	MainBrush      int
	SideBrush      int
	Filter         int
	Sensor         int
	ChargeContacts int
	MainBrushLid   int
	Mop            int
	Used           map[string]int
}

VacuumConsumables is getConsumablesInfo: minutes of use since each part was last reset. Used holds every *_time field by consumable name.

type VacuumDustCollection added in v0.3.0

type VacuumDustCollection struct {
	Auto bool     // empty after each clean
	Mode DustMode // dust_collection_mode
}

VacuumDustCollection is a self-emptying dock's setting (getDustCollectionInfo).

type VacuumMap added in v0.3.0

type VacuumMap struct {
	ID      int64
	Name    string // decoded from base64
	Saved   bool
	Locked  bool
	Updated int64 // Unix seconds
}

VacuumMap is one saved map.

type VacuumMaps added in v0.3.0

type VacuumMaps struct {
	Current    int64 // current_map_id; 0 before the first map
	AutoChange bool
	Maps       []VacuumMap
}

VacuumMaps is getMapInfo.

type VacuumRecord added in v0.3.0

type VacuumRecord struct {
	Timestamp      int64 `json:"timestamp"` // Unix seconds of the start
	Minutes        int   `json:"clean_time"`
	Area           int   `json:"clean_area"`
	DustCollection bool  `json:"dust_collection"`
	Error          int   `json:"error"`
	MapID          int64 `json:"map_id"`
	StartType      int   `json:"start_type"`
	TaskType       int   `json:"task_type"`
	Index          int   `json:"record_index"`
}

VacuumRecord is one clean of the history.

type VacuumRecords added in v0.3.0

type VacuumRecords struct {
	TotalMinutes int
	TotalArea    int
	TotalCount   int
	Records      []VacuumRecord
	Last         *VacuumRecord // lastest_day_record; nil when absent
	Raw          map[string]any
}

VacuumRecords is getCleanRecords: totals, the recent cleans and the latest day's clean.

type VacuumRoom added in v0.3.0

type VacuumRoom struct {
	ID         int
	Name       string // decoded from base64
	Color      int
	Suction    VacuumSuction
	Water      VacuumWater
	CleanCount int
}

VacuumRoom is a room of a map, with its own settings (zero when the room has none).

type VacuumStatus added in v0.3.0

type VacuumStatus struct {
	Status       VacuumStatusCode
	Errors       []int // err_status codes other than 0
	Battery      int   // percent
	CleanArea    int   // of the current or last clean, in AreaUnit
	CleanMinutes int
	CleanPercent int
	Suction      VacuumSuction
	Water        VacuumWater
	CleanCount   int // passes per clean
	Mode         VacuumCleanMode
	Mapping      bool
	Working      bool
	Relocating   bool
	Raw          map[string]map[string]any // the answers by method
}

VacuumStatus is a vacuum's state from one MultiCall of getVacStatus, getBatteryInfo, getCleanInfo, getCleanAttr and getCleanStatus. A request the device does not answer leaves its fields zero (Raw lacks it).

func (VacuumStatus) Faulted added in v0.3.0

func (s VacuumStatus) Faulted() bool

Faulted reports whether the vacuum reports an error.

type VacuumStatusCode added in v0.3.0

type VacuumStatusCode int

VacuumStatusCode is the state getVacStatus reports.

const (
	VacuumIdle      VacuumStatusCode = 0
	VacuumCleaning  VacuumStatusCode = 1
	VacuumMapping   VacuumStatusCode = 2
	VacuumGoingHome VacuumStatusCode = 4
	VacuumCharging  VacuumStatusCode = 5
	VacuumCharged   VacuumStatusCode = 6
	VacuumPaused    VacuumStatusCode = 7
	VacuumUndocked  VacuumStatusCode = 8
	VacuumFault     VacuumStatusCode = 100
)

The states a vacuum reports.

func (VacuumStatusCode) String added in v0.3.0

func (s VacuumStatusCode) String() string

String names the state ("status 3" for a code not known).

type VacuumSuction added in v0.3.0

type VacuumSuction int

VacuumSuction is the fan power (getCleanAttr suction).

const (
	SuctionQuiet    VacuumSuction = 1
	SuctionStandard VacuumSuction = 2
	SuctionTurbo    VacuumSuction = 3
	SuctionMax      VacuumSuction = 4
	SuctionUltra    VacuumSuction = 5
)

The suction levels, weakest first.

type VacuumWater added in v0.3.0

type VacuumWater int

VacuumWater is the mop's water flow (getCleanAttr cistern).

const (
	WaterOff    VacuumWater = 0
	WaterLow    VacuumWater = 1
	WaterMedium VacuumWater = 2
	WaterHigh   VacuumWater = 3
)

The water levels.

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