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"])
}
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 CamSingle(ctx context.Context, c SmartCaller, verb, module string, body 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 TPAPPasscode(password string, extraCrypt map[string]any, camera bool) (string, error)
- func TPAPPasscodeSHA1(password string) string
- func TapoKelvinRange(info map[string]any) (lo, hi float64)
- func TapoProbe(pubPEM []byte) []byte
- func TimezoneOffset(d time.Duration) string
- type AESClient
- type AESLogin
- type AESSession
- type CamAlert
- type CamConnection
- type CamDetection
- type CamDetectionKind
- type CamDisk
- type CamInfo
- type CamLastAlarm
- type CamPreset
- type CamRecording
- type CamSiren
- type CamTime
- type Credential
- type DustMode
- 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 TPAPCipher
- type TPAPClient
- type TPAPInfo
- type TPAPVerifier
- type TapoAutoOff
- type TapoAutoUpdate
- type TapoCamera
- func (c TapoCamera) Alert(ctx context.Context) (CamAlert, error)
- func (c TapoCamera) Calibrate(ctx context.Context) error
- func (c TapoCamera) Call(ctx context.Context, method string, params any) (map[string]any, error)
- func (c TapoCamera) Components(ctx context.Context) (map[string]int, error)
- func (c TapoCamera) Connection(ctx context.Context) (CamConnection, error)
- func (c TapoCamera) DayNight(ctx context.Context) (string, error)
- func (c TapoCamera) DeletePreset(ctx context.Context, ids ...string) error
- func (c TapoCamera) Detection(ctx context.Context, kind CamDetectionKind) (CamDetection, error)
- func (c TapoCamera) FormatSDCard(ctx context.Context) error
- func (c TapoCamera) GotoPreset(ctx context.Context, id string) error
- func (c TapoCamera) Info(ctx context.Context) (CamInfo, error)
- func (c TapoCamera) LED(ctx context.Context) (bool, error)
- func (c TapoCamera) LastAlarm(ctx context.Context) (CamLastAlarm, error)
- func (c TapoCamera) ManualAlarm(ctx context.Context, start bool) error
- func (c TapoCamera) Move(ctx context.Context, x, y int) error
- func (c TapoCamera) MoveStep(ctx context.Context, angle int) error
- func (c TapoCamera) NightVision(ctx context.Context) (string, error)
- func (c TapoCamera) Presets(ctx context.Context) ([]CamPreset, error)
- func (c TapoCamera) Privacy(ctx context.Context) (bool, error)
- func (c TapoCamera) Reboot(ctx context.Context) error
- func (c TapoCamera) RecordingDays(ctx context.Context, from, to time.Time, childID string) ([]string, error)
- func (c TapoCamera) Recordings(ctx context.Context, from, to time.Time, start, end int, childID string) ([]CamRecording, error)
- func (c TapoCamera) SDCards(ctx context.Context) ([]CamDisk, error)
- func (c TapoCamera) SavePreset(ctx context.Context, name string) error
- func (c TapoCamera) SetAlert(ctx context.Context, fields map[string]any) error
- func (c TapoCamera) SetAlias(ctx context.Context, name string) error
- func (c TapoCamera) SetDayNight(ctx context.Context, mode string) error
- func (c TapoCamera) SetDetection(ctx context.Context, kind CamDetectionKind, on bool) error
- func (c TapoCamera) SetDetectionConfig(ctx context.Context, kind CamDetectionKind, fields map[string]any) error
- func (c TapoCamera) SetLED(ctx context.Context, on bool) error
- func (c TapoCamera) SetNightVision(ctx context.Context, mode string) error
- func (c TapoCamera) SetPrivacy(ctx context.Context, on bool) error
- func (c TapoCamera) SetSiren(ctx context.Context, sound string, volume, duration int) error
- func (c TapoCamera) SetTimezone(ctx context.Context, zoneID, offset string) error
- func (c TapoCamera) Siren(ctx context.Context) (CamSiren, error)
- func (c TapoCamera) SoundSiren(ctx context.Context, on bool) error
- func (c TapoCamera) Time(ctx context.Context) (CamTime, error)
- func (c TapoCamera) WifiScan(ctx context.Context) ([]WifiNetwork, error)
- type TapoCountdownRule
- type TapoDevice
- func (d TapoDevice) AddCountdown(ctx context.Context, delay int, on bool) (string, error)
- func (d TapoDevice) AddScheduleRule(ctx context.Context, r TapoScheduleRule) (string, error)
- 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) CountdownRules(ctx context.Context) ([]TapoCountdownRule, 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) EditScheduleRule(ctx context.Context, r TapoScheduleRule) 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) RemoveCountdowns(ctx context.Context) error
- func (d TapoDevice) RemoveScheduleRules(ctx context.Context, ids ...string) error
- func (d TapoDevice) ReplaceCountdown(ctx context.Context, delay int, on bool) (string, error)
- func (d TapoDevice) Rules(ctx context.Context, kind TapoRuleKind) (TapoRules, error)
- func (d TapoDevice) ScheduleRules(ctx context.Context) ([]TapoScheduleRule, 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 TapoScheduleRule
- type TapoTime
- type TapoUsage
- type TapoVacuum
- func (v TapoVacuum) AreaUnit(ctx context.Context) (VacuumAreaUnit, error)
- func (v TapoVacuum) CarpetBoost(ctx context.Context) (bool, error)
- func (v TapoVacuum) CleanRecords(ctx context.Context) (VacuumRecords, error)
- func (v TapoVacuum) CleanRooms(ctx context.Context, mapID int64, rooms []int) error
- func (v TapoVacuum) Consumables(ctx context.Context) (VacuumConsumables, error)
- func (v TapoVacuum) DustCollection(ctx context.Context) (VacuumDustCollection, error)
- func (v TapoVacuum) EmptyDustbin(ctx context.Context) error
- func (v TapoVacuum) Locate(ctx context.Context) error
- func (v TapoVacuum) Maps(ctx context.Context) (VacuumMaps, error)
- func (v TapoVacuum) MopAttached(ctx context.Context) (bool, error)
- func (v TapoVacuum) Pause(ctx context.Context) error
- func (v TapoVacuum) ResetConsumable(ctx context.Context, name string) error
- func (v TapoVacuum) Resume(ctx context.Context) error
- func (v TapoVacuum) ReturnHome(ctx context.Context) error
- func (v TapoVacuum) Rooms(ctx context.Context, mapID int64) ([]VacuumRoom, error)
- func (v TapoVacuum) SetCarpetBoost(ctx context.Context, on bool) error
- func (v TapoVacuum) SetCleanCount(ctx context.Context, n int) error
- func (v TapoVacuum) SetDustCollection(ctx context.Context, d VacuumDustCollection) error
- func (v TapoVacuum) SetSuction(ctx context.Context, s VacuumSuction) error
- func (v TapoVacuum) SetVolume(ctx context.Context, volume int) error
- func (v TapoVacuum) SetWaterLevel(ctx context.Context, w VacuumWater) error
- func (v TapoVacuum) Start(ctx context.Context) error
- func (v TapoVacuum) Status(ctx context.Context) (VacuumStatus, error)
- func (v TapoVacuum) StopReturn(ctx context.Context) error
- func (v TapoVacuum) Volume(ctx context.Context) (int, error)
- type TriggerLog
- type VacuumAreaUnit
- type VacuumCleanMode
- type VacuumConsumables
- type VacuumDustCollection
- type VacuumMap
- type VacuumMaps
- type VacuumRecord
- type VacuumRecords
- type VacuumRoom
- type VacuumStatus
- type VacuumStatusCode
- type VacuumSuction
- type VacuumWater
- 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 ( 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).
const ( ScheduleAtTime = "normal" ScheduleSunrise = "sunrise" ScheduleSunset = "sunset" )
Schedule start kinds (s_type): a clock time, or an offset from sunrise or sunset.
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.
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").
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 ( // 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.
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 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).
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 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 ¶
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 TPAPPasscode ¶ added in v0.4.0
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
TPAPPasscodeSHA1 is the passcode of extra_crypt password_shadow with passwd_id 2: the lower-case hex SHA-1 of the password.
func TapoKelvinRange ¶
TapoKelvinRange is a Tapo bulb's range from its get_device_info.
func TimezoneOffset ¶ added in v0.3.0
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.
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 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
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
ParseCamInfo reads a basic_info answer.
type CamLastAlarm ¶ added in v0.3.0
CamLastAlarm is the last detection the camera alarmed on (getLastAlarmInfo).
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
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 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 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.
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
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.
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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) 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
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
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
// 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 ¶
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 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
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}).
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.