Documentation
¶
Overview ¶
Package tplink speaks the local protocols of TP-Link Kasa and Tapo smart-home devices: the Kasa legacy protocol on port 9999 (KasaRequest, KasaDiscover), KLAP v1 and v2 over HTTP and HTTPS (KLAPClient, with KLAPAuths to try the account and blank credentials, and KLAPAuthsWith for more accounts the caller supplies), the older Tapo securePassthrough transport (AESClient), the HTTPS transport of Tapo cameras, doorbells and the H200 hub (SSLAESClient), the Kasa camera transport (LinkieClient), the plain HTTPS transport of older robot vacuum firmware (SSLClient), the Tapo request family with batching (MultiCall), component negotiation (Components) and hub and strip children (ChildList, ControlChild), the UDP 20002 discovery probe with its encrypted part (TapoDiscover), and the colour-temperature ranges of bulbs.
Typed helpers cover what the devices do beyond switching: KasaDevice (energy meter and runtime statistics, schedules, countdowns and away mode, dimmer transitions and fades, light state with transitions, light strip effects, LED, name, reboot, cloud and firmware information, Wi-Fi scan and join) and TapoDevice (lights, transitions, presets and effects, energy use, history and readings, rule lists, auto-off, LED, firmware update, Wi-Fi scan and set-up, hub sensors and button logs).
It needs the owner's TP-Link account for KLAP and securePassthrough devices (cameras: the device's local user), and no cloud connection. It ships no vendor setup account or default login.
TP-Link does not publish these protocols; this package follows public descriptions (see PROVENANCE.md). Simulated devices for tests are in github.com/cB-Sigma/tplink-sim.
Example ¶
Find Tapo devices and switch the first one on over KLAP or securePassthrough, whichever it asks for. It needs devices on the LAN, so it is not run; github.com/cB-Sigma/tplink-sim runs the same steps against simulated devices.
package main
import (
"context"
"fmt"
"net/http"
"time"
"github.com/cB-Sigma/tplink"
)
func main() {
ctx := context.Background()
const email, password = "user@example.invalid", "the TP-Link account's password"
found, err := tplink.TapoDiscover(ctx, "255.255.255.255:20002", 3*time.Second)
if err != nil || len(found) == 0 {
fmt.Println(found, err)
return
}
f := found[0]
base := "http://" + f.Host
if f.HTTPPort != 0 && f.HTTPPort != 80 {
base = fmt.Sprintf("http://%s:%d", f.Host, f.HTTPPort)
}
var c tplink.SmartCaller
if f.Protocol() == "aes" {
c = &tplink.AESClient{Base: base, Logins: tplink.AESLogins(email, password, f.LoginVersion), HTTP: &http.Client{Timeout: 5 * time.Second}}
} else {
c = &tplink.KLAPClient{Base: base, Auths: tplink.KLAPAuths(email, password), HTTP: &http.Client{Timeout: 5 * time.Second}}
}
if _, err := c.Call(ctx, "set_device_info", map[string]any{"device_on": true}); err != nil {
fmt.Println(err)
return
}
info, _ := c.Call(ctx, "get_device_info", nil)
fmt.Println(f.Model, info["device_on"])
}
Output:
Index ¶
- Constants
- Variables
- func AuthHash(username, password string) []byte
- func AuthHashV1(username, password string) []byte
- func CamChildList(ctx context.Context, c SmartCaller) ([]map[string]any, error)
- func CamControlChild(ctx context.Context, c SmartCaller, deviceID, method string, params any) (map[string]any, error)
- func CamDeviceInfo(ctx context.Context, c SmartCaller) (map[string]any, error)
- func CamGet(ctx context.Context, c SmartCaller, method string, params map[string]any) (map[string]any, error)
- func CheckTapoProbe(b []byte) ([]byte, error)
- func ChildComponents(ctx context.Context, c SmartCaller) (map[string]map[string]int, error)
- func ChildList(ctx context.Context, c SmartCaller) ([]map[string]any, error)
- func Components(ctx context.Context, c SmartCaller) (map[string]int, error)
- func ControlChild(ctx context.Context, c SmartCaller, deviceID, method string, params any) (map[string]any, error)
- func DecodeNickname(s string) string
- func Decrypt(cipher []byte) []byte
- func DecryptTapoAnswer(f *TapoFound, key *rsa.PrivateKey) error
- func Encrypt(plain []byte) []byte
- func Frame(plain []byte) []byte
- func InsecureHTTP(timeout time.Duration) *http.Client
- func IsKasaUnsupported(err error) bool
- func IsUnsupported(err error) bool
- func KasaError(m map[string]any) error
- func KasaKelvinRange(model string) (lo, hi float64, known bool)
- func KasaRequest(ctx context.Context, addr string, req any, timeout time.Duration) (map[string]any, error)
- func NormaliseMAC(s string) string
- func ReadFrame(r io.Reader) ([]byte, error)
- func SSLAESConfirm(cnonce, nonce, pwdHash string) string
- func SSLAESDigest(cnonce, nonce, pwdHash string) string
- func SSLAESKeys(cnonce, nonce, pwdHash string) (key, iv []byte)
- func SSLAESPasswordHashes(password string) []string
- func SSLAESTag(body []byte, cnonce, pwdHash string, seq int) string
- func SealTapoDiscovery(pubPEM []byte, data any) (map[string]any, error)
- func SmartList(ctx context.Context, c SmartCaller, method, listKey string, ...) ([]map[string]any, map[string]any, error)
- func TapoKelvinRange(info map[string]any) (lo, hi float64)
- func TapoProbe(pubPEM []byte) []byte
- type AESClient
- type AESLogin
- type AESSession
- type Credential
- type EnergyInterval
- type Found
- type KLAPAuth
- type KLAPClient
- func (k *KLAPClient) BadSignatures() int
- func (k *KLAPClient) Call(ctx context.Context, method string, params any) (map[string]any, error)
- func (k *KLAPClient) Handshake(ctx context.Context) error
- func (k *KLAPClient) KasaCall(ctx context.Context, req any) (map[string]any, error)
- func (k *KLAPClient) Matched() KLAPAuth
- func (k *KLAPClient) Send(ctx context.Context, plain []byte) ([]byte, error)
- type KasaCaller
- type KasaConn
- type KasaDevice
- func (d *KasaDevice) AddRule(ctx context.Context, k KasaRuleKind, r KasaRule) (string, error)
- func (d *KasaDevice) Child(id string) *KasaDevice
- func (d *KasaDevice) CloudInfo(ctx context.Context) (map[string]any, error)
- func (d *KasaDevice) DeleteAllRules(ctx context.Context, k KasaRuleKind) error
- func (d *KasaDevice) DeleteRule(ctx context.Context, k KasaRuleKind, id string) error
- func (d *KasaDevice) DimTo(ctx context.Context, brightness, ms int) error
- func (d *KasaDevice) DimmerParameters(ctx context.Context) (map[string]any, error)
- func (d *KasaDevice) EditRule(ctx context.Context, k KasaRuleKind, r KasaRule) error
- func (d *KasaDevice) Emeter(ctx context.Context) (KasaEmeter, error)
- func (d *KasaDevice) EmeterDays(ctx context.Context, year, month int) ([]KasaStat, error)
- func (d *KasaDevice) EmeterMonths(ctx context.Context, year int) ([]KasaStat, error)
- func (d *KasaDevice) EraseEmeter(ctx context.Context) error
- func (d *KasaDevice) EraseRuntime(ctx context.Context) error
- func (d *KasaDevice) FactoryReset(ctx context.Context) error
- func (d *KasaDevice) FirmwareList(ctx context.Context) ([]map[string]any, error)
- func (d *KasaDevice) LightDetails(ctx context.Context) (map[string]any, error)
- func (d *KasaDevice) LightState(ctx context.Context) (map[string]any, error)
- func (d *KasaDevice) NextAction(ctx context.Context) (map[string]any, error)
- func (d *KasaDevice) Query(ctx context.Context, module, method string, params any) (map[string]any, error)
- func (d *KasaDevice) Reboot(ctx context.Context, delay int) error
- func (d *KasaDevice) Rules(ctx context.Context, k KasaRuleKind) (KasaRules, error)
- func (d *KasaDevice) RuntimeDays(ctx context.Context, year, month int) ([]KasaStat, error)
- func (d *KasaDevice) RuntimeMonths(ctx context.Context, year int) ([]KasaStat, error)
- func (d *KasaDevice) SetAlias(ctx context.Context, alias string) error
- func (d *KasaDevice) SetBrightness(ctx context.Context, b int) error
- func (d *KasaDevice) SetDimmerFade(ctx context.Context, which string, ms int) error
- func (d *KasaDevice) SetLED(ctx context.Context, on bool) error
- func (d *KasaDevice) SetLight(ctx context.Context, l KasaLight) (map[string]any, error)
- func (d *KasaDevice) SetLightingEffect(ctx context.Context, effect map[string]any) error
- func (d *KasaDevice) SetPreferredState(ctx context.Context, state map[string]any) error
- func (d *KasaDevice) SetRampRate(ctx context.Context, rate int) error
- func (d *KasaDevice) SetRelay(ctx context.Context, on bool) error
- func (d *KasaDevice) SetRulesEnabled(ctx context.Context, k KasaRuleKind, on bool) error
- func (d *KasaDevice) Sysinfo(ctx context.Context) (map[string]any, error)
- func (d *KasaDevice) Time(ctx context.Context) (time.Time, error)
- func (d *KasaDevice) WifiJoin(ctx context.Context, ssid, password string, keyType int) error
- func (d *KasaDevice) WifiScan(ctx context.Context) ([]WifiNetwork, error)
- type KasaEmeter
- type KasaLight
- type KasaModuleError
- type KasaRule
- type KasaRuleKind
- type KasaRules
- type KasaStat
- type LinkieClient
- type SSLAESClient
- type SSLClient
- type Session
- type SmartCaller
- type SmartError
- type SmartRequest
- type SmartResult
- type TapoAutoOff
- type TapoAutoUpdate
- type TapoDevice
- func (d TapoDevice) AutoOff(ctx context.Context) (TapoAutoOff, error)
- func (d TapoDevice) AutoUpdate(ctx context.Context) (TapoAutoUpdate, error)
- func (d TapoDevice) Call(ctx context.Context, method string, params any) (map[string]any, error)
- func (d TapoDevice) Child(deviceID string) TapoDevice
- func (d TapoDevice) Children(ctx context.Context) ([]TapoInfo, error)
- func (d TapoDevice) CurrentPower(ctx context.Context) (float64, error)
- func (d TapoDevice) DynamicEffects(ctx context.Context) (TapoRules, error)
- func (d TapoDevice) EditPreset(ctx context.Context, index int, state map[string]any) error
- func (d TapoDevice) Emeter(ctx context.Context) (TapoEmeter, error)
- func (d TapoDevice) EnergyData(ctx context.Context, start, end time.Time, interval EnergyInterval) (TapoEnergyData, error)
- func (d TapoDevice) EnergyUsage(ctx context.Context) (TapoEnergyUsage, error)
- func (d TapoDevice) FactoryReset(ctx context.Context) error
- func (d TapoDevice) FirmwareState(ctx context.Context) (TapoFirmwareState, error)
- func (d TapoDevice) Info(ctx context.Context) (TapoInfo, error)
- func (d TapoDevice) LED(ctx context.Context) (map[string]any, error)
- func (d TapoDevice) LatestFirmware(ctx context.Context) (TapoFirmware, error)
- func (d TapoDevice) LightingEffect(ctx context.Context) (map[string]any, error)
- func (d TapoDevice) Presets(ctx context.Context) ([]map[string]any, error)
- func (d TapoDevice) Reboot(ctx context.Context, delay int) error
- func (d TapoDevice) Rules(ctx context.Context, kind TapoRuleKind) (TapoRules, error)
- func (d TapoDevice) SetAccount(ctx context.Context, username, password string) error
- func (d TapoDevice) SetAutoOff(ctx context.Context, a TapoAutoOff) error
- func (d TapoDevice) SetAutoUpdate(ctx context.Context, a TapoAutoUpdate) error
- func (d TapoDevice) SetDynamicEffect(ctx context.Context, id string, enable bool) error
- func (d TapoDevice) SetLEDRule(ctx context.Context, rule string) error
- func (d TapoDevice) SetLight(ctx context.Context, l TapoLight) error
- func (d TapoDevice) SetLightingEffect(ctx context.Context, effect map[string]any) error
- func (d TapoDevice) SetNickname(ctx context.Context, name string) error
- func (d TapoDevice) SetOn(ctx context.Context, on bool) error
- func (d TapoDevice) SetTransitions(ctx context.Context, version int, enable bool, onSecs, offSecs int) error
- func (d TapoDevice) StartFirmwareUpdate(ctx context.Context) error
- func (d TapoDevice) Time(ctx context.Context) (TapoTime, error)
- func (d TapoDevice) Transitions(ctx context.Context) (map[string]any, error)
- func (d TapoDevice) TriggerLogs(ctx context.Context, pageSize, startID int) ([]TriggerLog, error)
- func (d TapoDevice) Usage(ctx context.Context) (TapoUsage, error)
- func (d TapoDevice) WifiJoin(ctx context.Context, username, password, ssid, wifiPassword, keyType string) error
- func (d TapoDevice) WifiScan(ctx context.Context) ([]WifiNetwork, error)
- type TapoEmeter
- type TapoEnergyData
- type TapoEnergyUsage
- type TapoFirmware
- type TapoFirmwareState
- type TapoFound
- type TapoInfo
- type TapoLight
- type TapoPeriods
- type TapoRuleKind
- type TapoRules
- type TapoTime
- type TapoUsage
- type TriggerLog
- type WifiNetwork
Examples ¶
Constants ¶
const ( KasaActionNone = -1 KasaActionOff = 0 KasaActionOn = 1 KasaTimeNone = -1 KasaTimeMinutes = 0 // minutes after midnight KasaTimeSunrise = 1 KasaTimeSunset = 2 )
Rule actions and time options.
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.
const DefaultBatchSize = 5
DefaultBatchSize is how many requests MultiCall puts in one multipleRequest when the caller does not say.
const KLAPHTTPSPort = 4433
KLAPHTTPSPort is the port of KLAP over HTTPS.
const KasaPort = 9999
KasaPort is the legacy protocol's port (TCP and UDP).
const LinkiePort = 10443
LinkiePort is the port of the Kasa camera transport.
const TapoPort = 20002
TapoPort is the discovery port of Tapo and KLAP devices.
Variables ¶
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).
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 ¶
AuthHash is the KLAP v2 auth hash of an account: SHA-256(SHA-1(username) ‖ SHA-1(password)).
func AuthHashV1 ¶
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
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
CamDeviceInfo asks a camera or H200 hub its basic information (getDeviceInfo, device_info.basic_info: device_model, device_type, sw_version, mac, device_alias, ...).
func CamGet ¶ added in v0.2.0
func CamGet(ctx context.Context, c SmartCaller, method string, params map[string]any) (map[string]any, error)
CamGet sends one camera request in a multipleRequest and returns its result.
func CheckTapoProbe ¶
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
ChildComponents asks a hub or strip for its children's components (get_child_device_component_list, paged), by child device_id.
func Components ¶ added in v0.2.0
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
DecodeNickname decodes a base64 nickname; a value that is not base64 is returned as it is.
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 ¶
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 InsecureHTTP ¶ added in v0.2.0
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
IsKasaUnsupported reports whether err is a Kasa module or method the device does not have (codes -1 and -2).
func IsUnsupported ¶
IsUnsupported reports whether err is a Tapo "method not supported" (or "params" error) answer.
func KasaError ¶
KasaError returns the first module error of a Kasa answer (an err_code that is set and not 0), or nil.
func KasaKelvinRange ¶
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"])
}
Output:
func NormaliseMAC ¶
NormaliseMAC gives a MAC address as 12 lower-case hexadecimal digits, dropping separators ("" if it is not one).
func SSLAESConfirm ¶ added in v0.2.0
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
SSLAESDigest is the client's proof in the second login step.
func SSLAESKeys ¶ added in v0.2.0
SSLAESKeys derives the session's AES key and IV from the login.
func SSLAESPasswordHashes ¶ added in v0.2.0
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
SSLAESTag is the Tapo_tag header of a request body with its sequence.
func SealTapoDiscovery ¶ added in v0.2.0
SealTapoDiscovery builds an encrypt_info for data, encrypted to the PEM public key of a probe, as a device does (for simulators and tests).
func SmartList ¶ added in v0.2.0
func SmartList(ctx context.Context, c SmartCaller, method, listKey string, params map[string]any) ([]map[string]any, map[string]any, error)
SmartList reads a list the device answers in pages ({"start_index", "sum", and the list under listKey}), asking from start_index until sum entries are read. params are sent with each page (start_index is set). It returns the entries and the first page's other fields.
func TapoKelvinRange ¶
TapoKelvinRange is a Tapo bulb's range from its get_device_info.
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.
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 ¶
AESLogins are the login_device parameters tried, in order: the account with the login version the device announced first (2 when unknown), then the other version.
func AESLoginsWith ¶
func AESLoginsWith(username, password string, version int, extra ...Credential) []AESLogin
AESLoginsWith is AESLogins with more accounts, each tried after the owner's with login version 2, then 1.
type AESSession ¶
type AESSession struct {
// contains filtered or unexported fields
}
AESSession is the symmetric part of a securePassthrough session.
func NewAESSession ¶
func NewAESSession(keyIV []byte) (*AESSession, error)
NewAESSession takes the 32 bytes the device sent (key ‖ IV).
func (*AESSession) Decrypt ¶
func (s *AESSession) Decrypt(b64 string) ([]byte, error)
Decrypt reverses Encrypt.
func (*AESSession) Encrypt ¶
func (s *AESSession) Encrypt(plain []byte) string
Encrypt pads (PKCS#7), encrypts and base64-encodes a payload.
type Credential ¶
type Credential struct {
Name string // reported as KLAPAuth.Name or AESLogin.Name when it matches
Username string
Password string
}
Credential is an account to try besides the owner's: devices that were reset, set up only locally or unbound from the cloud may hold a setup account instead. This module ships none; an application that wants to try such accounts passes them to KLAPAuthsWith and AESLoginsWith.
type EnergyInterval ¶ added in v0.2.0
type EnergyInterval int
EnergyInterval is the bucket of an energy history.
const ( EnergyHourly EnergyInterval = 60 EnergyDaily EnergyInterval = 1440 EnergyMonthly EnergyInterval = 43200 )
The buckets get_energy_data takes, in minutes.
type 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 ¶
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 ¶
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 ¶
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).
type KasaCaller ¶ added in v0.2.0
KasaCaller sends one legacy Kasa request: KasaConn (TCP 9999) or KLAPClient (Kasa devices on KLAP firmware).
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
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
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
EmeterDays asks the energy per day of a month, in Wh (get_daystat).
func (*KasaDevice) EmeterMonths ¶ added in v0.2.0
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
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
LightDetails asks get_light_details (lamp ratings and colour rendering).
func (*KasaDevice) LightState ¶ added in v0.2.0
LightState asks get_light_state.
func (*KasaDevice) NextAction ¶ added in v0.2.0
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
RuntimeDays asks the minutes on per day of a month (the schedule module's get_daystat).
func (*KasaDevice) RuntimeMonths ¶ added in v0.2.0
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
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
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
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
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
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
Time asks the device clock (get_time), in the device's zone.
func (*KasaDevice) WifiJoin ¶ added in v0.2.0
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
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
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 KasaStat ¶ added in v0.2.0
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.
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
Call sends {"method", "params"} and returns the result, as KLAPClient and AESClient do. Cameras take most requests in a multipleRequest (MultiCall, CamGet).
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.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session holds the keys of one KLAP handshake.
func NewSession ¶
NewSession derives the session keys from the seeds and the auth hash.
func (*Session) Encrypt ¶
Encrypt returns the next sequence number and the request body (signature ‖ ciphertext).
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 ¶
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
SmartRequest is one request of a batch.
type SmartResult ¶ added in v0.2.0
SmartResult is the answer to one request of a batch: Result, or Err (a *SmartError when the device answered an error code).
func MultiCall ¶ added in v0.2.0
func MultiCall(ctx context.Context, c SmartCaller, reqs []SmartRequest, batch int) ([]SmartResult, error)
MultiCall sends the requests in multipleRequest batches of batch (0: DefaultBatchSize; 1: one by one) and returns one result per request, in order. A device that refuses the batch as a whole is asked one request at a time. The error is set only when the transport failed.
func MultiCallChild ¶ added in v0.2.0
func MultiCallChild(ctx context.Context, c SmartCaller, deviceID string, reqs []SmartRequest) ([]SmartResult, error)
MultiCallChild sends several requests to one child of a hub or strip in one control_child carrying a multipleRequest, and returns one result per request, in order. A child that refuses the batch is asked one request at a time.
type TapoAutoOff ¶ added in v0.2.0
TapoAutoOff is get_auto_off_config: switch off DelayMin minutes after switching on.
type TapoAutoUpdate ¶ added in v0.2.0
type TapoAutoUpdate struct {
Enable bool `json:"enable"`
Time int `json:"time"`
RandomRange int `json:"random_range"`
}
TapoAutoUpdate is get_auto_update_info: automatic updates and their time (minutes after midnight) with a random spread (minutes).
type TapoDevice ¶ added in v0.2.0
type TapoDevice struct {
Caller SmartCaller // a KLAPClient or AESClient
ChildID string
}
TapoDevice is a Tapo device, or one child of a hub or strip, with typed helpers for the requests open-source clients describe: device information, switching and lights, energy and use, schedules and other rules, firmware, Wi-Fi and account set-up. Each helper is one request (see the method); Call and MultiCall reach anything else.
A child is reached through its parent with control_child: set ChildID to its device_id. The zero ChildID is the device itself. TapoDevice is a SmartCaller, so it can be passed to ChildList, SmartList, Components and MultiCall.
func (TapoDevice) AutoOff ¶ added in v0.2.0
func (d TapoDevice) AutoOff(ctx context.Context) (TapoAutoOff, error)
AutoOff asks get_auto_off_config.
func (TapoDevice) AutoUpdate ¶ added in v0.2.0
func (d TapoDevice) AutoUpdate(ctx context.Context) (TapoAutoUpdate, error)
AutoUpdate asks get_auto_update_info.
func (TapoDevice) Call ¶ added in v0.2.0
Call sends one request to the device, or to the child through control_child.
func (TapoDevice) Child ¶ added in v0.2.0
func (d TapoDevice) Child(deviceID string) TapoDevice
Child is the TapoDevice of one child.
func (TapoDevice) Children ¶ added in v0.2.0
func (d TapoDevice) Children(ctx context.Context) ([]TapoInfo, error)
Children reads a hub's or strip's children, typed.
func (TapoDevice) CurrentPower ¶ added in v0.2.0
func (d TapoDevice) CurrentPower(ctx context.Context) (float64, error)
CurrentPower asks get_current_power, in W.
func (TapoDevice) DynamicEffects ¶ added in v0.2.0
func (d TapoDevice) DynamicEffects(ctx context.Context) (TapoRules, error)
DynamicEffects reads a bulb's light effects (get_dynamic_light_effect_rules, paged), with whether one is running.
func (TapoDevice) EditPreset ¶ added in v0.2.0
EditPreset replaces one saved state (edit_preset_rules).
func (TapoDevice) Emeter ¶ added in v0.2.0
func (d TapoDevice) Emeter(ctx context.Context) (TapoEmeter, error)
Emeter asks get_emeter_data: voltage, current, power and energy.
func (TapoDevice) EnergyData ¶ added in v0.2.0
func (d TapoDevice) EnergyData(ctx context.Context, start, end time.Time, interval EnergyInterval) (TapoEnergyData, error)
EnergyData asks get_energy_data for the energy history between start and end. Devices answer a day of hours (EnergyHourly), a quarter of days from its first day (EnergyDaily) and a year of months (EnergyMonthly); start and end are sent as Unix seconds as given.
func (TapoDevice) EnergyUsage ¶ added in v0.2.0
func (d TapoDevice) EnergyUsage(ctx context.Context) (TapoEnergyUsage, error)
EnergyUsage asks get_energy_usage.
func (TapoDevice) FactoryReset ¶ added in v0.2.0
func (d TapoDevice) FactoryReset(ctx context.Context) error
FactoryReset resets the device to its factory settings (device_reset).
func (TapoDevice) FirmwareState ¶ added in v0.2.0
func (d TapoDevice) FirmwareState(ctx context.Context) (TapoFirmwareState, error)
FirmwareState asks get_fw_download_state.
func (TapoDevice) Info ¶ added in v0.2.0
func (d TapoDevice) Info(ctx context.Context) (TapoInfo, error)
Info asks get_device_info.
func (TapoDevice) LED ¶ added in v0.2.0
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
LightingEffect asks a light strip's current effect (get_lighting_effect).
func (TapoDevice) Presets ¶ added in v0.2.0
Presets reads a light's saved states (get_preset_rules, paged).
func (TapoDevice) Reboot ¶ added in v0.2.0
func (d TapoDevice) Reboot(ctx context.Context, delay int) error
Reboot restarts the device after delay seconds (device_reboot). A delay of 0 makes the device restart without answering.
func (TapoDevice) Rules ¶ added in v0.2.0
func (d TapoDevice) Rules(ctx context.Context, kind TapoRuleKind) (TapoRules, error)
Rules reads a rule list (get_schedule_rules paged, get_countdown_rules, get_antitheft_rules). Changing Tapo rules is not offered (see the README); Call reaches the device's own methods.
func (TapoDevice) SetAccount ¶ added in v0.2.0
func (d TapoDevice) SetAccount(ctx context.Context, username, password string) error
SetAccount replaces the TP-Link account the device knows (set_qs_info with the account and the device's time); clients must then use the new account.
func (TapoDevice) SetAutoOff ¶ added in v0.2.0
func (d TapoDevice) SetAutoOff(ctx context.Context, a TapoAutoOff) error
SetAutoOff sends set_auto_off_config.
func (TapoDevice) SetAutoUpdate ¶ added in v0.2.0
func (d TapoDevice) SetAutoUpdate(ctx context.Context, a TapoAutoUpdate) error
SetAutoUpdate sends set_auto_update_info.
func (TapoDevice) SetDynamicEffect ¶ added in v0.2.0
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
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
Transitions asks get_on_off_gradually_info: {"enable"} on firmware of component version 1, {"on_state", "off_state"} with durations in seconds on later ones.
func (TapoDevice) TriggerLogs ¶ added in v0.2.0
func (d TapoDevice) TriggerLogs(ctx context.Context, pageSize, startID int) ([]TriggerLog, error)
TriggerLogs reads a child's log, newest first (get_trigger_logs with page_size and start_id; 0 starts at the newest).
func (TapoDevice) Usage ¶ added in v0.2.0
func (d TapoDevice) Usage(ctx context.Context) (TapoUsage, error)
Usage asks get_device_usage.
func (TapoDevice) WifiJoin ¶ added in v0.2.0
func (d TapoDevice) WifiJoin(ctx context.Context, username, password, ssid, wifiPassword, keyType string) error
WifiJoin sets a device up on a Wi-Fi network and binds it to the TP-Link account (username, password), as the app does for a new device in its set-up mode (set_qs_info with the account, the network and the device's own time). keyType is the network's security as WifiScan reports it ("wpa2_psk" when ""). The device usually switches networks without answering, so a transport error after sending is expected and returned as nil.
func (TapoDevice) WifiScan ¶ added in v0.2.0
func (d TapoDevice) WifiScan(ctx context.Context) ([]WifiNetwork, error)
WifiScan asks the networks the device sees (get_wireless_scan_info, paged; SSIDs are base64 on the wire).
type TapoEmeter ¶ added in v0.2.0
type TapoEmeter struct {
VoltageMV float64 `json:"voltage_mv"`
CurrentMA float64 `json:"current_ma"`
PowerMW float64 `json:"power_mw"`
EnergyWh float64 `json:"energy_wh"`
}
TapoEmeter is get_emeter_data (newer energy-monitoring firmware).
type TapoEnergyData ¶ added in v0.2.0
type TapoEnergyData struct {
Start time.Time
Interval EnergyInterval
Wh []float64
LocalTime string
Raw map[string]any
}
TapoEnergyData is an energy history: Wh per bucket from Start.
type TapoEnergyUsage ¶ added in v0.2.0
type TapoEnergyUsage struct {
TodayRuntime int `json:"today_runtime"`
MonthRuntime int `json:"month_runtime"`
TodayEnergy int `json:"today_energy"`
MonthEnergy int `json:"month_energy"`
CurrentPower float64 `json:"current_power"`
LocalTime string `json:"local_time"`
}
TapoEnergyUsage is get_energy_usage: energy in Wh, runtimes in minutes; CurrentPower is in mW on the firmware that reports it here.
type TapoFirmware ¶ added in v0.2.0
type TapoFirmware struct {
Type int `json:"type"` // 0: no update
NeedUpgrade bool `json:"need_to_upgrade"`
Version string `json:"fw_ver"`
ReleaseDate string `json:"release_date"`
ReleaseNote string `json:"release_note"`
Size int `json:"fw_size"`
}
TapoFirmware is get_latest_fw. The device asks TP-Link's cloud, so a device without a cloud connection answers no update.
func (TapoFirmware) Available ¶ added in v0.2.0
func (f TapoFirmware) Available() bool
Available reports whether an update is offered.
type TapoFirmwareState ¶ added in v0.2.0
type TapoFirmwareState struct {
Status int `json:"status"`
Progress int `json:"download_progress"`
RebootTime int `json:"reboot_time"`
UpgradeTime int `json:"upgrade_time"`
AutoUpgrade bool `json:"auto_upgrade"`
}
TapoFirmwareState is get_fw_download_state. Status 0 is idle, 2 downloading, 3 flashing (wait UpgradeTime seconds), negative an error.
type TapoFound ¶
type TapoFound struct {
// Addr is where the answer came from (host:port).
Addr string
// Host is the device's address: the answer's source, else its "ip".
Host string
DeviceType string // SMART.TAPOPLUG, SMART.KASAPLUG, SMART.TAPOHUB, IOT.SMARTPLUGSWITCH, …
Model string // without the region, "P110"
DeviceID string
MAC string // 12 hex digits
// Encrypt is KLAP or AES (securePassthrough); "" when not told.
Encrypt string
HTTPPort int
LoginVersion int
HTTPS bool
Name string
Result map[string]any
// Decrypted is the answer's encrypt_info decrypted (newer firmware), or
// nil. TapoDiscover fills it.
Decrypted map[string]any
}
TapoFound is a device that answered the 20002 probe.
func ParseTapoAnswer ¶
ParseTapoAnswer reads a 20002 answer.
func TapoDiscover ¶
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
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.
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
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
TapoRules is a rule list: whether it is on, its rules as the device gives them, and how many it holds at most.
type TapoTime ¶ added in v0.2.0
type TapoTime struct {
Timestamp int64 `json:"timestamp"` // Unix seconds
TimeDiff int `json:"time_diff"` // minutes from UTC
Region string `json:"region"`
}
TapoTime is get_device_time.
type TapoUsage ¶ added in v0.2.0
type TapoUsage struct {
Time TapoPeriods `json:"time_usage"`
Power TapoPeriods `json:"power_usage"`
Saved TapoPeriods `json:"saved_power"`
}
TapoUsage is get_device_usage: minutes on, energy used and saved (Wh).
type TriggerLog ¶ added in v0.2.0
type TriggerLog struct {
ID int `json:"id"`
Event string `json:"event"` // singleClick, doubleClick, rotation, open, close, motion, ...
EventID string `json:"eventId"`
Timestamp int64 `json:"timestamp"`
Params map[string]any `json:"params"`
}
TriggerLog is one entry of a button's or sensor's log.