-
Notifications
You must be signed in to change notification settings - Fork 0
/
switch.go
54 lines (44 loc) · 926 Bytes
/
switch.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
package wifitriggers
import (
"context"
"log"
"sync"
)
type switchState int
const (
unknownState switchState = iota
offState
onState
)
type SwitchOnIFTTT struct {
Key string
OnCmd string
OffCmd string
mu sync.Mutex
state switchState
}
func (s *SwitchOnIFTTT) gotoState(ctx context.Context, n switchState, cmd string) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.state == n {
return nil
}
if err := runIFTTT(ctx, s.Key, cmd); err != nil {
log.Printf("Error running IFTTT action %q: %v", cmd, err)
s.state = unknownState
} else {
log.Printf("Successfully ran IFTTT action %q", cmd)
s.state = n
}
return nil
}
func (s *SwitchOnIFTTT) OnAction() Action {
return func(ctx context.Context) error {
return s.gotoState(ctx, onState, s.OnCmd)
}
}
func (s *SwitchOnIFTTT) OffAction() Action {
return func(ctx context.Context) error {
return s.gotoState(ctx, offState, s.OffCmd)
}
}