-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
94 lines (83 loc) · 1.92 KB
/
client.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"log"
"strconv"
"sync"
"time"
"github.com/coreos/go-systemd/daemon"
"golang.org/x/net/context"
"os/exec"
"cloud.google.com/go/pubsub"
"google.golang.org/api/option"
)
func main() {
log.Println("Starting...")
ctx := context.Background()
client, err := pubsub.NewClient(ctx, "kodicloud-169614",
option.WithServiceAccountFile("account.json"))
if err != nil {
log.Println("Failed new client")
return
}
var mu sync.Mutex
sub := client.Subscription("Test")
ok, err := sub.Exists(ctx)
if err != nil {
log.Println("Error checking subscription")
return
}
if !ok {
log.Println("Subscription doesn't exist")
return
}
lastSeen := time.Now()
daemon.SdNotify(false, "READY=1")
log.Println("Initialized")
go feedWatchdog()
err = sub.Receive(ctx, func(ctx context.Context, msg *pubsub.Message) {
msg.Ack()
mu.Lock()
defer mu.Unlock()
msgTime := msg.PublishTime
user := msg.Attributes["user"]
if msgTime.After(lastSeen) {
log.Printf("Got message from %s: %q at %q\n",
user, string(msg.Data), msg.PublishTime)
lastSeen = msgTime
handleCommand(string(msg.Data))
} else {
log.Printf("Ignored old message from %s: %q at %q\n",
user, string(msg.Data), msg.PublishTime)
}
})
if err != nil {
log.Println("Receive error", err)
panic(err)
}
}
func feedWatchdog() {
interval, err := daemon.SdWatchdogEnabled(false)
if err != nil || interval == 0 {
return
}
for {
daemon.SdNotify(false, "WATCHDOG=1")
time.Sleep(interval / 3)
}
}
func handleCommand(command string) {
if command != "off" {
if temp, err := strconv.Atoi(command); err != nil || temp < 16 || temp > 30 {
log.Printf("Invalid command %q\n", command)
return
}
}
cmd := exec.Command("irsend", "-d", "/run/lirc/lircd.socket",
"SEND_ONCE", "ac", command)
err := cmd.Run()
if err != nil {
log.Printf("failed launching irsend: %q", err)
return
}
log.Printf("Sent command %q\n", command)
}