-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnet.go
72 lines (63 loc) · 1.62 KB
/
net.go
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package kasa
import (
"encoding/binary"
"fmt"
"net"
"time"
)
func (d *Device) sendTCP(cmd string) ([]byte, error) {
conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{IP: d.parsed, Port: d.Port})
if err != nil {
klogger.Printf("Cannot connnect to device: %s", err.Error())
return nil, err
}
defer conn.Close()
// assume we are on the same LAN, one second is enough
conn.SetReadDeadline(time.Now().Add(time.Second))
// send the command with the uint32 "header"
payload := ScrambleTCP(cmd)
if _, err = conn.Write(payload); err != nil {
klogger.Printf("Cannot send command to device: %s", err.Error())
return nil, err
}
// read the uint32 "header" to get the size of the rest of the block
header := make([]byte, 4)
n, err := conn.Read(header)
if err != nil {
return nil, err
}
if n != 4 {
err := fmt.Errorf("header not 32 bits (4 bytes): %d", n)
klogger.Printf(err.Error())
return nil, err
}
size := binary.BigEndian.Uint32(header)
// read the entire rest of the block, then close the connection
// we could leave the connection open and send subsequent requests
// but for one-shot, this is enough
data := make([]byte, size)
totalread := 0
for {
n, err = conn.Read(data[totalread:])
if err != nil {
return nil, err
}
totalread = totalread + n
if totalread >= int(size) {
break
}
}
return Unscramble(data), nil
}
func (d *Device) sendUDP(cmd string) error {
conn, err := net.DialUDP("udp", nil, &net.UDPAddr{IP: d.parsed, Port: d.Port})
if err != nil {
return err
}
defer conn.Close()
payload := Scramble(cmd)
if _, err = conn.Write(payload); err != nil {
return err
}
return nil
}