-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.go
More file actions
58 lines (46 loc) · 1.85 KB
/
command.go
File metadata and controls
58 lines (46 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package kasa
import (
"encoding/binary"
"fmt"
)
// BuildCommand takes a JSON command string, encrypts it, and prepends the length header.
// The length header is 4 bytes in big-endian format containing the length of the encrypted payload.
func BuildCommand(jsonCmd string) []byte {
// Encrypt the JSON command
encrypted := Encrypt([]byte(jsonCmd))
// Create the message with 4-byte length header
msg := make([]byte, 4+len(encrypted))
// Write the length as big-endian uint32
binary.BigEndian.PutUint32(msg[0:4], uint32(len(encrypted)))
// Copy the encrypted payload
copy(msg[4:], encrypted)
return msg
}
// BuildGetSysInfoCommand builds a command to retrieve device system information.
// This includes device name, model, hardware/software versions, and relay states.
func BuildGetSysInfoCommand() []byte {
return BuildCommand(CmdGetSysInfo)
}
// BuildGetEnergyMeterCommand builds a command to retrieve real-time energy meter data.
// This includes voltage, current, power, and total energy consumption.
func BuildGetEnergyMeterCommand() []byte {
return BuildCommand(CmdGetRealtimeEM)
}
// BuildGetPlugEnergyCommand builds a command to retrieve energy data for a specific plug/child.
// This is used for power strips like the HS300 that support per-plug power monitoring.
func BuildGetPlugEnergyCommand(childID string) []byte {
cmd := fmt.Sprintf(`{"context":{"child_ids":["%s"]},"emeter":{"get_realtime":{}}}`, childID)
return BuildCommand(cmd)
}
// BuildTurnOnCommand builds a command to turn on a device or relay.
func BuildTurnOnCommand() []byte {
return BuildCommand(CmdTurnOn)
}
// BuildTurnOffCommand builds a command to turn off a device or relay.
func BuildTurnOffCommand() []byte {
return BuildCommand(CmdTurnOff)
}
// BuildDiscoveryCommand builds a command for UDP device discovery.
func BuildDiscoveryCommand() []byte {
return BuildGetSysInfoCommand()
}