-
Notifications
You must be signed in to change notification settings - Fork 1
/
avrpower.go
99 lines (87 loc) · 2.59 KB
/
avrpower.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
95
96
97
98
99
package main
import (
"encoding/json"
"time"
)
type avrPowerLoop struct {
statusLoop
midnaUnlocked bool
midnaDefaultSink string
michaelPhoneExpiration time.Time
leaPhoneExpiration time.Time
previous string
}
func (l *avrPowerLoop) ProcessEvent(ev MQTTEvent) []MQTTPublish {
var lease struct {
Expiration time.Time `json:"expiration"`
}
switch ev.Topic {
case "regelwerk/ticker/1s":
// current time influences our state
case "runstatus/midna/i3lock":
var runStatus struct {
Running bool `json:"running"`
}
if err := json.Unmarshal(ev.Payload.([]byte), &runStatus); err != nil {
l.statusf("unmarshaling runstatus: %v", err)
return nil
}
l.midnaUnlocked = !runStatus.Running
case "router7/dhcp4d/lease/Michaels-iPhone":
if err := json.Unmarshal(ev.Payload.([]byte), &lease); err != nil {
l.statusf("unmarshaling router7 lease: %v", err)
return nil
}
l.michaelPhoneExpiration = lease.Expiration
case "router7/dhcp4d/lease/Galaxy-S10e":
if err := json.Unmarshal(ev.Payload.([]byte), &lease); err != nil {
l.statusf("unmarshaling router7 lease: %v", err)
return nil
}
l.leaPhoneExpiration = lease.Expiration
case "github.com/stapelberg/defaultsink2mqtt/default_sink":
l.midnaDefaultSink = string(ev.Payload.([]byte))
case "$SYS/broker/connection/clients/https://github.com/stapelberg/defaultsink2mqtt@midna":
// example: {
// "clientID":"https://github.com/stapelberg/defaultsink2mqtt@midna",
// "online":false,
// "timestamp":"2023-01-22T11:42:26Z"
// }
var connectionEvent struct {
Online bool `json:"online"`
}
if err := json.Unmarshal(ev.Payload.([]byte), &connectionEvent); err != nil {
l.statusf("unmarshaling connection event: %v", err)
return nil
}
if !connectionEvent.Online {
// When defaultsink2mqtt goes offline, that’s most likely because
// midna suspended.
l.midnaUnlocked = false
}
default:
return nil // event did not influence our state
}
now := ev.Timestamp
weekday, hour, minute := now.Weekday(), now.Hour(), now.Minute()
_, _, _ = weekday, hour, minute // TODO
phoneHome := l.michaelPhoneExpiration.After(now) ||
l.leaPhoneExpiration.After(now)
_ = phoneHome
l.statusf("midnaUnlocked=%v, midnaDefaultSink=%s", l.midnaUnlocked, l.midnaDefaultSink)
payload := "OFF"
if l.midnaUnlocked && l.midnaDefaultSink == "alsa_output.pci-0000_00_1f.3.analog-stereo" {
payload = "ON"
}
if l.previous == payload {
return nil // skip, no change
}
l.previous = payload
return []MQTTPublish{
{
Topic: "cmnd/tasmota_68462F/Power",
Payload: payload,
Retained: true,
},
}
}