forked from stefanor/signalk-victron-ble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.py
289 lines (266 loc) · 9.47 KB
/
plugin.py
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import argparse
import asyncio
import datetime
import dataclasses
import json
import logging
import sys
from typing import Optional
from bleak.backends.device import BLEDevice
from victron_ble.devices import (
AuxMode,
BatterySenseData,
BatteryMonitorData,
SolarChargerData,
DcDcConverterData,
)
from victron_ble.exceptions import AdvertisementKeyMissingError, UnknownDeviceError
from victron_ble.scanner import Scanner
logger = logging.getLogger("signalk-victron-ble")
@dataclasses.dataclass
class ConfiguredDevice:
id: str
mac: str
advertisement_key: str
secondary_battery: Optional[str]
class SignalKScanner(Scanner):
def __init__(self, devices):
super().__init__()
self._devices: dict[str:ConfiguredDevice] = devices
def load_key(self, address):
try:
return self._devices[address].advertisement_key
except KeyError:
raise AdvertisementKeyMissingError(f"No key available for {address}")
def callback(self, bl_device: BLEDevice, raw_data: bytes):
logger.debug(
f"Received data from {bl_device.address.lower()}: {raw_data.hex()}"
)
try:
device = self.get_device(bl_device, raw_data)
except AdvertisementKeyMissingError:
return
except UnknownDeviceError as e:
logger.error(e)
return
data = device.parse(raw_data)
configured_device = self._devices[bl_device.address.lower()]
id_ = configured_device.id
transformers = {
BatteryMonitorData: self.transform_battery_data,
BatterySenseData: self.transform_battery_sense_data,
SolarChargerData: self.transform_solar_charger_data,
DcDcConverterData: self.transform_dcdc_converter_data,
}
for data_type, transformer in transformers.items():
if isinstance(data, data_type):
delta = transformer(bl_device, configured_device, data, id_)
logger.info(delta)
print(json.dumps(delta))
sys.stdout.flush()
return
else:
logger.debug("Unknown device", device)
def transform_battery_sense_data(
self,
bl_device: BLEDevice,
cfg_device: ConfiguredDevice,
data: BatterySenseData,
id_: str,
):
return {
"updates": [
{
"source": {
"label": "Victron",
"type": "Bluetooth",
"src": bl_device.address,
},
"timestamp": datetime.datetime.utcnow().isoformat() + "Z",
"values": [
{
"path": f"electrical.batteries.{id_}.voltage",
"value": data.get_voltage(),
},
{
"path": f"electrical.batteries.{id_}.temperature",
"value": data.get_temperature() + 273.15,
},
],
},
],
}
def transform_battery_data(
self,
bl_device: BLEDevice,
cfg_device: ConfiguredDevice,
data: BatteryMonitorData,
id_: str,
):
values = [
{
"path": f"electrical.batteries.{id_}.voltage",
"value": data.get_voltage(),
},
{
"path": f"electrical.batteries.{id_}.current",
"value": data.get_current(),
},
{
"path": f"electrical.batteries.{id_}.power",
"value": data.get_voltage() * data.get_current(),
},
{
"path": f"electrical.batteries.{id_}.capacity.stateOfCharge",
"value": data.get_soc() / 100,
},
{
"path": f"electrical.batteries.{id_}.capacity.dischargeSinceFull",
"value": data.get_consumed_ah() * 3600,
},
{
"path": f"electrical.batteries.{id_}.capacity.timeRemaining",
"value": data.get_remaining_mins() * 60,
},
]
if data.get_aux_mode() == AuxMode.STARTER_VOLTAGE:
if cfg_device.secondary_battery:
values.append(
{
"path": f"electrical.batteries.{cfg_device.secondary_battery}.voltage",
"value": data.get_starter_voltage(),
}
)
elif data.get_aux_mode() == AuxMode.TEMPERATURE:
values.append(
{
"path": f"electrical.batteries.{id_}.temperature",
"value": data.get_temperature() + 273.15,
}
)
return {
"updates": [
{
"source": {
"label": "Victron",
"type": "Bluetooth",
"src": bl_device.address,
},
"timestamp": datetime.datetime.utcnow().isoformat() + "Z",
"values": values,
},
],
}
def transform_solar_charger_data(
self,
bl_device: BLEDevice,
cfg_device: ConfiguredDevice,
data: SolarChargerData,
id_: str,
):
return {
"updates": [
{
"source": {
"label": "Victron",
"type": "Bluetooth",
"src": bl_device.address,
},
"timestamp": datetime.datetime.utcnow().isoformat() + "Z",
"values": [
{
"path": f"electrical.solar.{id_}.voltage",
"value": data.get_battery_voltage(),
},
{
"path": f"electrical.solar.{id_}.current",
"value": data.get_battery_charging_current(),
},
{
"path": f"electrical.solar.{id_}.chargingMode",
"value": data.get_charge_state().name.lower(),
},
{
"path": f"electrical.solar.{id_}.panelPower",
"value": data.get_solar_power(),
},
{
"path": f"electrical.solar.{id_}.loadCurrent",
"value": data.get_external_device_load(),
},
{
"path": f"electrical.solar.{id_}.yieldToday",
"value": data.get_yield_today(),
},
],
},
],
}
def transform_dcdc_converter_data(
self,
bl_device: BLEDevice,
cfg_device: ConfiguredDevice,
data: DcDcConverterData,
id_: str,
):
return {
"updates": [
{
"source": {
"label": "Victron",
"type": "Bluetooth",
"src": bl_device.address,
},
"timestamp": datetime.datetime.utcnow().isoformat() + "Z",
"values": [
{
"path": f"electrical.converters.{id_}.chargingMode",
"value": data.get_charge_state().name.lower(),
},
{
"path": f"electrical.converters.{id_}.chargerError",
"value": data.get_charger_error().name.lower(),
},
{
"path": f"electrical.converters.{id_}.input.voltage",
"value": data.get_input_voltage(),
},
{
"path": f"electrical.converters.{id_}.output.voltage",
"value": data.get_output_voltage(),
},
{
"path": f"electrical.converters.{id_}.chargerOffReason",
"value": data.get_off_reason().name.lower(),
},
],
},
],
}
async def monitor(devices):
scanner = SignalKScanner(devices)
await scanner.start()
await asyncio.Event().wait()
def main():
p = argparse.ArgumentParser()
p.add_argument(
"--verbose", "-v", action="store_true", help="Increase the verbosity"
)
args = p.parse_args()
logging.basicConfig(
stream=sys.stderr, level=logging.DEBUG if args.verbose else logging.WARNING
)
logging.debug("Waiting for config...")
config = json.loads(input())
logging.info("Configured: %s", json.dumps(config))
devices = {}
for device in config["devices"]:
devices[device["mac"].lower()] = ConfiguredDevice(
id=device["id"],
mac=device["mac"],
advertisement_key=device["key"],
secondary_battery=device.get("secondary_battery"),
)
asyncio.run(monitor(devices))
if __name__ == "__main__":
main()