-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
256 lines (212 loc) · 6.36 KB
/
main.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package main
import (
"context"
"flag"
"fmt"
"log"
"os"
"path/filepath"
"sync"
"time"
"github.com/brutella/hc"
"github.com/brutella/hc/accessory"
"github.com/brutella/hc/characteristic"
hclog "github.com/brutella/hc/log"
"github.com/brutella/hc/service"
"github.com/joeshaw/leaf"
"github.com/peterbourgon/ff/v3"
)
type Leaf struct {
session *leaf.Session
accessory *accessory.Accessory
battery *service.BatteryService
climate *service.Switch
charge *service.Switch
// The Leaf API doesn't allow us to see if the climate control is
// on. But it will be on for 15 minutes after we tell it to turn
// on, so track the state for that long.
climateOn bool
climateMu sync.Mutex
}
type config struct {
storagePath string
username string
password string
country string
accessoryName string
homekitPIN string
updateInterval time.Duration
debug bool
}
func main() {
var cfg config
fs := flag.NewFlagSet("leaf-homekit", flag.ExitOnError)
fs.StringVar(
&cfg.storagePath,
"storage-path",
filepath.Join(os.Getenv("HOME"), ".homecontrol", "leaf"),
"Storage path for information about the HomeKit accessory",
)
fs.StringVar(&cfg.username, "username", "", "Nissan username")
fs.StringVar(&cfg.password, "password", "", "Nissan password")
fs.StringVar(&cfg.country, "country", "US", "Leaf country")
fs.StringVar(&cfg.accessoryName, "accessory-name", "", "HomeKit accessory name")
fs.StringVar(&cfg.homekitPIN, "homekit-pin", "00102003", "HomeKit pairing PIN")
fs.DurationVar(&cfg.updateInterval, "update-interval", 15*time.Minute, "How often to update battery status")
fs.BoolVar(&cfg.debug, "debug", false, "Enable debug mode")
_ = fs.String("config", "", "Config file")
ff.Parse(fs, os.Args[1:],
ff.WithEnvVarPrefix("LEAF"),
ff.WithConfigFileFlag("config"),
ff.WithConfigFileParser(ff.PlainParser),
)
if cfg.username == "" || cfg.password == "" {
log.Fatal("username and password required")
}
s := &leaf.Session{
Username: cfg.username,
Password: cfg.password,
Country: cfg.country,
Debug: cfg.debug,
}
if cfg.debug {
hclog.Debug.Enable()
}
log.Println("Connecting to NissanConnect service")
vehicle, batteryRecord, _, err := s.Login()
if err != nil {
log.Fatal(err)
}
log.Printf("Found %s %s, VIN %s", vehicle.ModelYear, vehicle.ModelName, vehicle.VIN)
info := accessory.Info{
Name: vehicle.Nickname,
Manufacturer: "Nissan",
Model: fmt.Sprintf("%s %s", vehicle.ModelYear, vehicle.ModelName),
SerialNumber: vehicle.VIN,
}
if cfg.accessoryName != "" {
info.Name = cfg.accessoryName
}
l := &Leaf{
session: s,
accessory: accessory.New(info, accessory.TypeOther),
battery: service.NewBatteryService(),
climate: service.NewSwitch(),
charge: service.NewSwitch(),
}
l.accessory.OnIdentify(func() {
s.FlashLights()
})
l.accessory.AddService(l.battery.Service)
l.accessory.AddService(l.climate.Service)
l.accessory.AddService(l.charge.Service)
l.setBatteryCharacteristics(batteryRecord)
// It's too slow to pull battery info on demand, and too taxing on
// the car's 12V battery. Update the value in a loop instead.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go l.updateBatteryLoop(ctx, cfg.updateInterval)
// We have to use normal switches for these, because HomeKit doesn't
// have stateless buttons
n := characteristic.NewName()
n.SetValue("Climate Control")
l.climate.AddCharacteristic(n.Characteristic)
l.climate.On.OnValueRemoteUpdate(l.sendClimateRequest)
l.climate.On.OnValueRemoteGet(func() bool {
l.climateMu.Lock()
defer l.climateMu.Unlock()
return l.climateOn
})
n = characteristic.NewName()
n.SetValue("Charging")
l.charge.AddCharacteristic(n.Characteristic)
l.charge.On.OnValueRemoteUpdate(l.sendChargingRequest)
l.charge.On.OnValueRemoteGet(func() bool { return false })
hcConfig := hc.Config{
Pin: cfg.homekitPIN,
StoragePath: cfg.storagePath,
}
t, err := hc.NewIPTransport(hcConfig, l.accessory)
if err != nil {
log.Fatal(err)
}
hc.OnTermination(func() {
cancel()
<-t.Stop()
})
log.Println("Starting transport...")
t.Start()
}
func (l *Leaf) setBatteryCharacteristics(br *leaf.BatteryRecords) {
l.battery.BatteryLevel.SetValue(br.BatteryStatus.SOC.Value)
lowBatt := characteristic.StatusLowBatteryBatteryLevelNormal
if br.BatteryStatus.SOC.Value <= 20 {
lowBatt = characteristic.StatusLowBatteryBatteryLevelLow
}
l.battery.StatusLowBattery.SetValue(lowBatt)
status := characteristic.ChargingStateNotCharging
if br.BatteryStatus.BatteryChargingStatus.IsCharging() {
status = characteristic.ChargingStateCharging
}
l.battery.ChargingState.SetValue(status)
log.Printf("Battery Level: %d%% Charging: %s", br.BatteryStatus.SOC.Value, br.BatteryStatus.BatteryChargingStatus)
}
func (l *Leaf) updateBatteryLoop(ctx context.Context, interval time.Duration) {
log.Printf("Entering battery update loop, updating every %v", interval)
defer log.Println("Exited battery update loop")
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
log.Println("Updating battery information")
br, _, err := l.session.ChargingStatus()
if err != nil {
log.Printf("Error updating battery info: %v", err)
} else {
l.setBatteryCharacteristics(br)
}
}
}
}
func (l *Leaf) sendChargingRequest(on bool) {
// These are stateless switches, always set them to off
defer func() {
time.Sleep(1 * time.Second)
l.charge.On.SetValue(false)
}()
if !on {
return
}
log.Println("Sending charging request...")
if err := l.session.StartCharging(); err != nil {
log.Printf("Unable to send charging request: %v", err)
}
log.Println("Successfully sent charging request")
}
func (l *Leaf) sendClimateRequest(on bool) {
if on {
go func() {
time.Sleep(15 * time.Minute)
l.climateMu.Lock()
defer l.climateMu.Unlock()
l.climate.On.SetValue(false)
l.climateOn = false
}()
log.Println("Sending climate on request...")
if err := l.session.ClimateOn(); err != nil {
log.Printf("Unable to send climate on request: %v", err)
}
} else {
log.Println("Sending climate off request...")
if err := l.session.ClimateOff(); err != nil {
log.Printf("Unable to send climate off request: %v", err)
}
}
log.Println("Successfully sent climate request")
l.climateMu.Lock()
defer l.climateMu.Unlock()
l.climateOn = on
}