tplink

package module
v0.1.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: 27 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, securePassthrough and the 20002 discovery; 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, the older Tapo securePassthrough transport, Tapo hubs and power strips with their children, and the UDP 20002 discovery probe. KLAP and securePassthrough devices need the owner's TP-Link account, 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
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
Tapo request family, hub and strip children (paging, control_child) yes
UDP 20002 discovery probe and answer yes; the answer's encrypted part is not decrypted
Colour-temperature ranges Kasa by model table; Tapo from get_device_info
multipleRequest batching, component negotiation, per-model helpers no; requests are sent one at a time and the caller reads the answers
HTTPS transports of the newest firmware (KLAP over TLS, the newer TPAP login), cameras (Tapo C-series), the cloud API, setting up new devices no

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

this module fabiankachlock/tapo-api v1.4.0 kabukky/tapogo (2024-03-04) cloudkucooland/go-kasa (2026-08-29) python-kasa 0.11.0.1 (Python)
Kasa legacy protocol (9999) and its UDP discovery yes no no yes yes
KLAP v2 (Tapo) yes yes yes no yes
KLAP v1 (Kasa on newer firmware) yes no no no yes
securePassthrough (older Tapo firmware) yes, login v1 and v2 no no no yes
20002 discovery yes no no no yes, with the encrypted part
Hub and strip children yes yes, typed (T300, T31x) no Kasa strips yes
multipleRequest, typed device models no yes no Kasa models yes
Vendor setup accounts caller-supplied no no n/a built in
Device simulators for tests yes, separate module no no no in-process fakes from recorded fixtures
Interop evidence against python-kasa both ways (below) none stated none stated none stated the reference, recorded fixtures
Go version, dependencies 1.22; lanbcast 1.20; none 1.21; none 1.25; a TUI and CLI stack n/a
Licence Apache-2.0 MIT Apache-2.0 BSD-2-Clause GPL-3.0

Pick this module when you need one client for every local transport a mixed Kasa and Tapo home uses, including discovery and the older firmware, under your own device model. Pick tapo-api for typed Tapo models (lights, strips, hub sensors) when your devices all speak KLAP v2, and go-kasa for Kasa legacy devices with its command-line tool. Use python-kasa outside Go: it covers the most devices and firmware, and its fixtures record real devices.

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)

Use TapoFound.Protocol() to choose between KLAPClient and AESClient. 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 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. KLAP: KLAPClient (Call, KasaCall, Send, Handshake, Matched, BadSignatures), KLAPAuths, KLAPAuthsWith, Credential, AuthHash, AuthHashV1, NewSession. securePassthrough: AESClient, AESLogins, AESLoginsWith. Tapo: SmartCaller, ChildList, ControlChild, SmartError, IsUnsupported. Discovery: TapoDiscover, TapoProbe, CheckTapoProbe, ParseTapoAnswer. 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.
  • python-kasa 0.11.0.1's client against the simulators, in tplink-sim.
  • Not yet: a real Kasa or Tapo device. No open-source network emulator of KLAP or securePassthrough devices was found; python-kasa tests with in-process fakes, so the device side here is a script on python-kasa's code.
  • tplink-sim: simulated Kasa and Tapo devices 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 (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"])
}

Index

Examples

Constants

View Source
const KasaPort = 9999

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

View Source
const TapoPort = 20002

TapoPort is the discovery port of Tapo and KLAP devices.

Variables

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

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

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

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

Functions

func AuthHash

func AuthHash(username, password string) []byte

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

func AuthHashV1

func AuthHashV1(username, password string) []byte

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

func 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 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 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 Decrypt

func Decrypt(cipher []byte) []byte

Decrypt reverses Encrypt.

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 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 TapoKelvinRange

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

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

func TapoProbe

func TapoProbe(pubPEM []byte) []byte

TapoProbe builds a discovery probe carrying the PEM public key.

Types

type AESClient

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

AESClient talks securePassthrough to one device, keeping its session.

func (*AESClient) Call

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

Call sends one Tapo request and returns its result.

func (*AESClient) Handshake

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

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

func (*AESClient) Matched

func (a *AESClient) Matched() string

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

type AESLogin

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

AESLogin is one set of login_device parameters to try.

func AESLogins

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

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

func AESLoginsWith

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

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

type AESSession

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

AESSession is the symmetric part of a securePassthrough session.

func NewAESSession

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

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

func (*AESSession) Decrypt

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

Decrypt reverses Encrypt.

func (*AESSession) Encrypt

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

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

type Credential

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

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

type 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 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 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

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) Protocol

func (f TapoFound) Protocol() string

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

Jump to

Keyboard shortcuts

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