-
Notifications
You must be signed in to change notification settings - Fork 5
/
commom.go
67 lines (54 loc) · 1.58 KB
/
commom.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
package common
import (
"flag"
"fmt"
"os"
"time"
esphome "github.com/mycontroller-org/esphome_api/pkg/client"
"google.golang.org/protobuf/proto"
)
const (
EnvHostAddress = "ESPHOME_ADDRESS"
EnvPassword = "ESPHOME_PASSWORD"
EnvEncryptionKey = "ESPHOME_ENCRYPTION_KEY"
)
var (
HostAddressFlag = flag.String("address", "", "esphome node hostname or IP with port. example: my_esphome.local:6053")
PasswordFlag = flag.String("password", "", "esphome node API password")
EncryptionKeyFlag = flag.String("encryption-key", "", "esphome node API encryption key")
TimeoutFlag = flag.Duration("timeout", 10*time.Second, "communication timeout")
)
func GetClient(handlerFunc func(msg proto.Message)) (*esphome.Client, error) {
flag.Parse()
// update hostaddress
if *HostAddressFlag == "" {
if os.Getenv(EnvHostAddress) != "" {
*HostAddressFlag = os.Getenv(EnvHostAddress)
} else {
*HostAddressFlag = "esphome.local:6053"
}
}
// update password
if *PasswordFlag == "" {
*PasswordFlag = os.Getenv(EnvPassword)
}
// update encryption key
if *EncryptionKeyFlag == "" {
*EncryptionKeyFlag = os.Getenv(EnvEncryptionKey)
}
if handlerFunc == nil {
handlerFunc = handlerFuncImpl
}
client, err := esphome.GetClient("mycontroller.org", *HostAddressFlag, *EncryptionKeyFlag, *TimeoutFlag, handlerFunc)
if err != nil {
return nil, err
}
if err = client.Login(*PasswordFlag); err != nil {
_ = client.Close()
return nil, err
}
return client, nil
}
func handlerFuncImpl(msg proto.Message) {
fmt.Printf("received a message, type: %T, value: [%v]\n", msg, msg)
}