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 (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 Tapo request family with hub and strip children (ChildList, ControlChild), the UDP 20002 discovery probe (TapoDiscover), and the colour-temperature ranges of bulbs. It needs the owner's TP-Link account for KLAP and securePassthrough devices, and no cloud connection. It ships no vendor setup account.
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 CheckTapoProbe(b []byte) ([]byte, error)
- func ChildList(ctx context.Context, c SmartCaller) ([]map[string]any, error)
- func ControlChild(ctx context.Context, c SmartCaller, deviceID, method string, params any) (map[string]any, error)
- func Decrypt(cipher []byte) []byte
- func Encrypt(plain []byte) []byte
- func Frame(plain []byte) []byte
- 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 TapoKelvinRange(info map[string]any) (lo, hi float64)
- func TapoProbe(pubPEM []byte) []byte
- type AESClient
- type AESLogin
- type AESSession
- type Credential
- 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 Session
- type SmartCaller
- type SmartError
- type TapoFound
Examples ¶
Constants ¶
const KasaPort = 9999
KasaPort is the legacy protocol's port (TCP and UDP).
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 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 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 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 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 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 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 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 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
}
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.