moat-ems-battery 0.2.11__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ The code in this repository, and all MoaT submodules it refers to,
2
+ is part of the MoaT project.
3
+
4
+ Unless a submodule's LICENSE.txt states otherwise, all included files are
5
+ licensed under the LGPL V3, as published by the FSF at
6
+ https://www.gnu.org/licenses/lgpl-3.0.html .
7
+
8
+ In addition to the LGPL's terms, the author(s) respectfully ask all users of
9
+ this code to contribute any bug fixes or enhancements. Also, please link back to
10
+ https://M-o-a-T.org.
11
+
12
+ Thank you.
13
+
14
+ Copyright © 2021 ff.: the MoaT contributor(s), as per the git changelog(s).
@@ -0,0 +1,24 @@
1
+ Metadata-Version: 2.4
2
+ Name: moat-ems-battery
3
+ Version: 0.2.11
4
+ Summary: REPLACE ME
5
+ Author-email: Matthias Urlichs <matthias@urlichs.de>
6
+ Project-URL: homepage, https://m-o-a-t.org
7
+ Project-URL: repository, https://github.com/M-o-a-T/moat
8
+ Keywords: MoaT
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Framework :: AnyIO
11
+ Classifier: Framework :: Trio
12
+ Classifier: Framework :: AsyncIO
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Intended Audience :: Developers
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/x-rst
17
+ License-File: LICENSE.txt
18
+ Requires-Dist: anyio~=3.0
19
+ Requires-Dist: msgpack
20
+ Requires-Dist: serialpacker
21
+ Requires-Dist: pyfuse3
22
+ Requires-Dist: moat-util~=0.56.4
23
+ Requires-Dist: moat-micro~=0.15.1
24
+ Dynamic: license-file
@@ -0,0 +1,89 @@
1
+ # MoaT EMS Battery
2
+
3
+ This module implements a generic battery controller.
4
+
5
+ The client is a microcontroller, e.g. an ESP32 or a RP2040. It runs
6
+ MicroPython and talks to the server via the MoaT messaging protocol.
7
+
8
+ The server side runs in the MoaT multiplexer that talks to the battery.
9
+ It typically uses a web page for setup, and/or connects to DBus.
10
+
11
+
12
+ ## Rationale
13
+
14
+ One of the MoaT project's objectives is to implement a uniform,
15
+ multiplexable front-end for various devices.
16
+
17
+ Battery management systems typically have interfaces with device-specific
18
+ command sets that can only be talked to by a single client, so devising a
19
+ common language makes sense.
20
+
21
+ Also, a BMS may not have the required features. For instance, you might
22
+ want to chain multiple batteries in series or in parallel. Or, the BMS
23
+ firmware does not understand that some battery chemistries require adaptive
24
+ strategies for charging that cannot be expressed with a single charge
25
+ curve.
26
+
27
+
28
+ ### Why so complex?
29
+
30
+ The client connects to the actual BMS hardware with TTL serial, SPI, I²C,
31
+ RS485, CAN, or similar. For the most part, these interfaces do not support
32
+ galvanic separation, may not even exist on a server.
33
+
34
+ The client needs to constantly monitor battery current, cell and system
35
+ voltage, battery temperature et al.. It must be able to disconnect the
36
+ battery's relay if any parameter exceeds the cell and battery
37
+ specifications. This function should run continuously even if communication
38
+ with the server fails.
39
+
40
+
41
+ ## Setup
42
+
43
+ As typical clients are resource-constrained, you need to add the Battery
44
+ management code to the MicroPython flash image. Add this repository's
45
+ manifest, from `moat/micro/_embed/manifest_bms.py`, alongside the one from
46
+ `moat.micro`.
47
+
48
+ Add a "BMS" app to the "moat.micro" configuration::
49
+
50
+ apps:
51
+ …
52
+ bat1: bms.std.Cmd
53
+
54
+ bat1:
55
+ …
56
+
57
+ The "bat1" section (or however you want to name it) is described in
58
+ `moat/ems/battery/_cfg.yaml`. More extensive documentation is TODO.
59
+
60
+ Start the client and multiplexer normally; the MoaT BMS will run as part of
61
+ the multiplexer.
62
+
63
+
64
+ ### Server-only operation
65
+
66
+ Some systems don't need a client. A commercial BMS with an RS485 interface
67
+ e.g. can be connected directly to the server, no intermediate client required.
68
+
69
+ In this case, set the "dev:" entry in the "port:" section to "null".
70
+
71
+
72
+ ## Modules
73
+
74
+ Right now the only battery model is "std". It connects several subsystems:
75
+
76
+ * system voltage, current and temperature
77
+
78
+ * cell voltage and temperature
79
+
80
+ It controls
81
+
82
+ * the balancing system(s)
83
+
84
+ * the battery relay
85
+
86
+ Also, it sends the battery's SoC and its voltage and current limits to
87
+ whichever program requires them, as well as displaying them to the user.
88
+
89
+
File without changes
@@ -0,0 +1,731 @@
1
+ """
2
+ Basic BMS classes
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from moat.util import as_proxy, attrdict, val2pos
8
+ from moat.micro.alert import Alert
9
+ from moat.micro.cmd.array import ArrayCmd
10
+ from moat.micro.cmd.base import BaseCmd
11
+ from moat.micro.rtc import state as rtc_state
12
+ from moat.util.compat import (
13
+ Event,
14
+ TaskGroup,
15
+ TimeoutError,
16
+ log,
17
+ sleep_ms,
18
+ ticks_diff,
19
+ ticks_ms,
20
+ wait_for_ms,
21
+ )
22
+
23
+ from typing import TYPE_CHECKING # isort:skip
24
+
25
+ if TYPE_CHECKING:
26
+ from moat.micro.cmd.alert import AlertHandler
27
+ from moat.micro.cmd.tree.dir import SubDispatcher
28
+ from moat.micro.part.relay import Relay
29
+
30
+
31
+ class BatteryAlert(Alert):
32
+ """
33
+ For a given battery there will at most be one open alert of each type.
34
+ """
35
+
36
+
37
+ @as_proxy("bms_SH", replace=True)
38
+ class HighSOC(BatteryAlert):
39
+ "Charge exceeds limit"
40
+
41
+
42
+ @as_proxy("bms_SL", replace=True)
43
+ class LowSOC(BatteryAlert):
44
+ "Charge below limit"
45
+
46
+
47
+ @as_proxy("bms_UH", replace=True)
48
+ class HighVoltage(BatteryAlert):
49
+ "Total voltage exceeds limit"
50
+
51
+
52
+ @as_proxy("bms_UL", replace=True)
53
+ class LowVoltage(BatteryAlert):
54
+ "Total voltage below limit"
55
+
56
+
57
+ @as_proxy("bms_CH", replace=True)
58
+ class HighCellVoltage(BatteryAlert):
59
+ "Cell voltage exceeds limit"
60
+
61
+
62
+ @as_proxy("bms_CL", replace=True)
63
+ class LowCellVoltage(BatteryAlert):
64
+ "Cell voltage below limit"
65
+
66
+
67
+ @as_proxy("bms_CI", replace=True)
68
+ class CellImbalance(BatteryAlert):
69
+ "Excessive cell imbalance"
70
+
71
+
72
+ @as_proxy("bms_UD", replace=True)
73
+ class VoltageDelta(BatteryAlert):
74
+ "High diff between cell sum and total voltage"
75
+
76
+
77
+ @as_proxy("bms_IH", replace=True)
78
+ class HighChargeCurrent(BatteryAlert):
79
+ "Charge current exceeds limit"
80
+
81
+
82
+ @as_proxy("bms_IL", replace=True)
83
+ class HighDischargeCurrent(BatteryAlert):
84
+ "Discharge current exceeds limit"
85
+
86
+
87
+ @as_proxy("bms_TH", replace=True)
88
+ class HighTemperature(BatteryAlert):
89
+ "Temperature exceeds limit"
90
+
91
+
92
+ @as_proxy("bms_TL", replace=True)
93
+ class LowTemperature(BatteryAlert):
94
+ "Temperature below operational limit"
95
+
96
+
97
+ @as_proxy("bms_NBD", replace=True)
98
+ class NoBatteryData(BatteryAlert):
99
+ "no battery data seen"
100
+
101
+
102
+ @as_proxy("bms_NCD", replace=True)
103
+ class NoCellData(BatteryAlert):
104
+ "no cell data seen"
105
+
106
+
107
+ @as_proxy("bms_EL", replace=True)
108
+ class EnergyLow(BatteryAlert):
109
+ "total energy below zero"
110
+
111
+
112
+ @as_proxy("bms_EH", replace=True)
113
+ class EnergyHigh(BatteryAlert):
114
+ "total energy larger than Wmax"
115
+
116
+
117
+ def _s(r):
118
+ # Helper to create a sequence
119
+ return (x for x in r if x is not None)
120
+
121
+
122
+ class BaseCell(BaseCmd):
123
+ """
124
+ Skeleton for a single cell.
125
+
126
+ Configuration::
127
+
128
+ lim:
129
+ u:
130
+ abs:
131
+ max: 3.65
132
+ min: 2.55
133
+ ext:
134
+ max: 3.55
135
+ min: 2.9
136
+ std:
137
+ max: 3.5
138
+ min: 2.95
139
+ t:
140
+ abs:
141
+ min: 0
142
+ max: 45
143
+ ext:
144
+ min: 5
145
+ max: 40
146
+ std:
147
+ min: 10
148
+ max: 35
149
+ bal:
150
+ abs: 80
151
+ ext: 70
152
+ std: 60
153
+
154
+ The limits are:
155
+
156
+ * abs: exceed this and the relay triggers.
157
+ * ext: outside of these the current limit is zero.
158
+ * std: normal operation within this range
159
+
160
+ The balancer doesn't have minimum temperatures.
161
+ Comtrollers are free to implement more complicated curves.
162
+
163
+ """
164
+
165
+ vchg: float | None = None
166
+ vdis: float | None = None
167
+ fchg: bool = False
168
+ fdis: bool = False
169
+
170
+ async def cmd_c(self):
171
+ "read cell charge level [0…1]"
172
+ raise NotImplementedError("no idea how")
173
+
174
+ async def cmd_u(self):
175
+ "read cell voltage"
176
+ raise NotImplementedError("no idea how")
177
+
178
+ async def cmd_t(self):
179
+ "read cell temperature"
180
+ raise NotImplementedError("no idea how")
181
+
182
+ async def cmd_tb(self):
183
+ "read cell balancer temperature"
184
+ raise NotImplementedError("no idea how")
185
+
186
+ async def cmd_dis(self, v: float | None = None, f: bool | None = None):
187
+ """
188
+ balance low: drain cell until below @v.
189
+
190
+ If @f (force) is set, the cell will be skipped by the balancer;
191
+ changing @v will be ignored if @f is `None`.
192
+
193
+ Returns (voltage,force) tuple.
194
+ """
195
+ if f is not None:
196
+ self.fdis = f
197
+ if v is not None: # noqa:SIM102
198
+ if not self.fdis or f:
199
+ self.vdis = v
200
+ await self.set_dis()
201
+ return (self.vdis, self.fdis)
202
+
203
+ async def set_dis(self):
204
+ """set discharging balancer"""
205
+ raise NotImplementedError("no idea how")
206
+
207
+ async def cmd_chg(self, v: float | None = None, f: bool | None = None):
208
+ """
209
+ balance high: charge cell until above @v
210
+
211
+ Obviously this only works with an active balancer.
212
+
213
+ If @force is set, the cell will be skipped by the balancer.
214
+
215
+ Returns (voltage,force) tuple.
216
+ """
217
+ if f is not None:
218
+ self.fchg = f
219
+ if v is not None: # noqa:SIM102
220
+ if not self.fchg or f:
221
+ self.vchg = v
222
+ await self.set_chg()
223
+ return (self.vchg, self.fchg)
224
+
225
+ async def set_chg(self):
226
+ """set charging balancer"""
227
+ raise NotImplementedError("no idea how")
228
+
229
+ async def cmd_lim(self, soc: float = 0.5):
230
+ """
231
+ Limits (as fraction of C) depending on @soc, cell
232
+ temperature, voltage, and whatnot.
233
+
234
+ May raise an exception, in which case the relay should disengage.
235
+
236
+ Otherwise, returns (chg,dis) factors to limit max cell charge/discharge.
237
+ """
238
+ u = await self.cmd_u()
239
+ t = await self.cmd_t()
240
+
241
+ lu = self.cfg["lim"]["u"]
242
+ lt = self.cfg["lim"]["t"]
243
+
244
+ if t is None: # some cells might not have a sensor
245
+ tf = 1
246
+ else:
247
+ if t > lt["abs"]["max"]:
248
+ raise HighTemperature(t, self.path)
249
+ if t < lt["abs"]["min"]:
250
+ raise LowTemperature(t, self.path)
251
+
252
+ tf = val2pos(lt["abs"]["max"], t, lt["ext"]["max"], clamp=True) * val2pos(
253
+ lt["abs"]["min"],
254
+ t,
255
+ lt["ext"]["min"],
256
+ clamp=True,
257
+ )
258
+
259
+ if u > lu["abs"]["max"]:
260
+ raise HighCellVoltage(u, self.path)
261
+ chg = tf * val2pos(lu["ext"]["max"], u, lu["std"]["max"], clamp=True)
262
+
263
+ if u < lu["abs"]["min"]:
264
+ raise LowCellVoltage(u, self.path)
265
+ dis = tf * val2pos(lu["ext"]["min"], u, lu["std"]["min"], clamp=True)
266
+
267
+ # TODO use an exponent != 1
268
+ lc = self.cfg["lim"]["c"]
269
+ if soc < lc["min"]:
270
+ dis *= soc / lc["min"]
271
+ if soc > lc["max"]:
272
+ chg *= (1 - soc) / (1 - lc["max"])
273
+ return (chg, dis)
274
+
275
+
276
+ class BalBaseCell(BaseCell):
277
+ "A BaseCell with balancing state"
278
+
279
+ in_balance: bool = False
280
+ balance_pwm: float = None # percentage of time the balancer is on
281
+ balance_over_temp: bool = False
282
+ balance_threshold: float = None
283
+ balance_forced: bool = False
284
+
285
+ async def cmd_bal(self):
286
+ "Get Balancer state/data"
287
+ res = dict(b=self.in_balance, f=self.balance_forced, ot=self.balance_over_temp)
288
+ if self.balance_pwm is not None:
289
+ res["pwm"] = self.balance_pwm
290
+ if self.balance_threshold is not None:
291
+ res["th"] = self.balance_threshold
292
+ return res
293
+
294
+
295
+ class BaseCells(ArrayCmd):
296
+ """
297
+ Skeleton for a cell array.
298
+
299
+ Basic configuration::
300
+
301
+ apps:
302
+ a: bms._test.Cells
303
+ a:
304
+ app: bms._test.Cell
305
+ cfg: {}
306
+ n: 8
307
+ w: 1000000 # battery's total energy, in watt seconds
308
+ lim:
309
+ ud: 0.02 # relativ difference u/ud
310
+ t:
311
+ w: 500 # calculate cumulative energy every this-many-msec
312
+ ud: 5000 # watch the difference between cell and cumulative voltage
313
+ alarm: !P path.to.alarm.handler
314
+ loss: 0.01 # average capacity loss when charging
315
+
316
+ """
317
+
318
+ w: attrdict = None
319
+ w_max: float = None
320
+ p: float = None
321
+ al: SubDispatcher[AlertHandler] | None = None
322
+ rly: SubDispatcher[Relay] | None = None
323
+ n_warn_w = 0
324
+ n_warn_ud = 0
325
+ n_save = 98
326
+
327
+ def __init__(self, cfg):
328
+ super().__init__(cfg)
329
+ self._reloaded = Event()
330
+ self.clear_work()
331
+
332
+ async def _setup(self):
333
+ cfg = self.cfg
334
+ self.al = self.root.sub_at(cfg["alarm"]) if "alarm" in cfg else None
335
+ self.rly = self.root.sub_at(cfg["rly"]) if "relay" in cfg else None
336
+ try:
337
+ self.ud_max = cfg["lim"]["ud"]
338
+ except KeyError:
339
+ self.ud_max = 0.02
340
+ try:
341
+ self.t_w = cfg["t"]["w"]
342
+ except KeyError:
343
+ self.t_w = 500
344
+
345
+ c = self.cfg["cfg"]["lim"]["u"]["ext"]
346
+ n = self.cfg["n"]
347
+ self.u_mid = (c["min"] + c["max"]) * n / 2
348
+
349
+ async def setup(self):
350
+ await super().setup()
351
+ await self._setup()
352
+ try:
353
+ w = rtc_state[("state",) + self.path]
354
+ except KeyError:
355
+ pass
356
+ else:
357
+ self.work = attrdict(**w)
358
+
359
+ async def cmd_c(self):
360
+ """fetch charge state"""
361
+ if self.w_max is None:
362
+ return 0.5
363
+ return self.w / self.w_max
364
+
365
+ async def cmd_u(self):
366
+ """fetch voltage sum"""
367
+ r = await self.cmd_all("u")
368
+ return sum(r)
369
+
370
+ async def cmd_t(self):
371
+ """fetch temperature min/max"""
372
+ r = await self.cmd_all("t")
373
+ return min(_s(r), default=None), max(_s(r), default=None)
374
+
375
+ async def cmd_tb(self):
376
+ """fetch balancer temperature min/max"""
377
+ r = await self.cmd_all("tb")
378
+ return min(_s(r), default=None), max(_s(r), default=None)
379
+
380
+ async def cmd_lim(self):
381
+ """return charge,discharge limit factors"""
382
+ chg, dis = None, None
383
+ try:
384
+ for c, d in await self.cmd_all("lim"):
385
+ if chg is None or chg > c:
386
+ chg = c
387
+ if dis is None or dis > d:
388
+ dis = d
389
+ return chg, dis
390
+
391
+ except BatteryAlert:
392
+ if self.rly is not None:
393
+ await self.rly.w(v=False)
394
+ raise
395
+
396
+ async def reload(self):
397
+ await super().reload()
398
+ self._reloaded.set()
399
+ self._reloaded = Event()
400
+
401
+ async def monitor_ud(self):
402
+ while True:
403
+ try:
404
+ await sleep_ms(self.cfg["t"]["ud"])
405
+ except KeyError:
406
+ await self._reloaded.wait()
407
+ continue
408
+ u = await self.cmd_u()
409
+ ud = sum(await self.cmd_all("u"))
410
+ if abs((u - ud) / ud) > self.ud_max:
411
+ if self.al and not (self.n_warn_ud % 10):
412
+ await self.al.w(a=VoltageDelta, p=self.path, d=dict(u=u, ud=ud))
413
+ self.n_warn_ud += 1
414
+ elif self.n_warn_ud:
415
+ self.n_warn_ud = 0
416
+ await self.al.w(a=VoltageDelta, p=self.path)
417
+
418
+ async def get_energy(self):
419
+ """
420
+ loop to calculate battery energy
421
+
422
+ The base version sums up (u*i), i.e. watt seconds.
423
+ """
424
+ t1 = ticks_ms()
425
+ i = await self.cmd_i()
426
+ while True:
427
+ await sleep_ms(self.t_w)
428
+ u = await self.cmd_u()
429
+ t2 = ticks_ms()
430
+ self.p = p = i * u
431
+ await self._add_w(p, ticks_diff(t2, t1) / 1000, u > self.u_mid)
432
+
433
+ await sleep_ms(self.t_w)
434
+ i = await self.cmd_i()
435
+ t1 = ticks_ms()
436
+ self.p = p = i * u
437
+ await self._add_w(p, ticks_diff(t1, t2) / 1000, u > self.u_mid)
438
+
439
+ async def cmd_w(self, w: float | None = None) -> float:
440
+ """get, or manually override, battery energy content"""
441
+ wx = self.w
442
+ if w is not None:
443
+ self.clear_work(w)
444
+ return wx
445
+
446
+ def clear_work(self, w=None):
447
+ if w is None:
448
+ pass
449
+ elif w < 0 or (self.w_max is not None and w > self.w_max):
450
+ return False
451
+ self.work = attrdict()
452
+ self.work.sum = w or 0
453
+ self.work.t = 0
454
+ self.work.chg = 0
455
+ self.work.dis = 0
456
+ self.work.xchg = 0
457
+ self.work.xdis = 0
458
+ return True
459
+
460
+ async def _add_w(self, w, t, hi):
461
+ hi # noqa:B018
462
+ self.work.t += t
463
+ w *= t
464
+
465
+ if w > 0:
466
+ self.work.chg += w
467
+ w *= 1 - self.cfg.get("loss", 0)
468
+ else:
469
+ self.work.dis -= w
470
+ self.work.sum += w
471
+
472
+ # outside "standard" limits
473
+ if self.work.sum < 0:
474
+ self.work.xdis += -self.work.sum
475
+ self.work.sum = 0
476
+ if w < 0:
477
+ if self.al and not (self.n_warn_w % 10):
478
+ await self.al.w(a=EnergyLow, p=self.path, d=dict(w=self.work.xdis, wd=w))
479
+ self.n_warn_w += 1
480
+
481
+ elif self.w_max is not None and self.work.sum > self.w_max:
482
+ self.work.xchg += self.work.sum - self.w_max
483
+ self.work.sum = self.w_max
484
+
485
+ if w > 0:
486
+ if self.al and not (self.n_warn_w % 10):
487
+ await self.al.w(a=EnergyHigh, p=self.path, d=dict(w=self.work.xchg, wd=w))
488
+ self.n_warn_w += 1
489
+
490
+ elif self.n_warn_w:
491
+ self.n_warn_w = 0
492
+ if self.w_max is None or self.work.sum < self.w_max / 2:
493
+ await self.al.w(
494
+ a=EnergyLow if self.work.sum < self.w_max / 2 else EnergyHigh,
495
+ p=self.path,
496
+ )
497
+
498
+ self.n_save += 1
499
+ if self.n_save > 99:
500
+ self.n_save = 0
501
+ rtc_state[("state",) + self.path] = self.work
502
+
503
+ def get_work(self, clear: bool = False, poll: bool = False):
504
+ poll # noqa:B018
505
+ res = self.work
506
+ if clear:
507
+ self.clear_work()
508
+ return res
509
+
510
+ async def start_tasks(self, tg):
511
+ await tg.spawn(self.get_energy)
512
+ await tg.spawn(self.monitor_ud)
513
+
514
+ async def task(self):
515
+ async with TaskGroup() as tg:
516
+ await self.start_tasks(tg)
517
+ await super().task()
518
+
519
+
520
+ class BaseBattery(BaseCells):
521
+ """
522
+ Skeleton for a balanced battery.
523
+ """
524
+
525
+ # superclass does sum of cell voltages
526
+ # async def cmd_u(self):
527
+ # """fetch battery voltage"""
528
+ # raise RuntimeError
529
+
530
+ async def cmd_i(self):
531
+ """fetch battery current"""
532
+ raise RuntimeError
533
+
534
+ async def cmd_ud(self):
535
+ """Get delta between cell voltage sum and battery voltage."""
536
+ u1 = await self.cmd_u()
537
+ u2 = sum(await self.all("u"))
538
+ return u2 - u1
539
+
540
+
541
+ class BaseBalancer(BaseCmd):
542
+ """
543
+ Basic battery balancing.
544
+
545
+ Config::
546
+ bat: !P battery.to.balance
547
+ t:
548
+ chk: 1000 # time between checks when not balancing
549
+ run: 500 # time between updates when balancing
550
+ h:
551
+ n: 3 # max parallel balancing
552
+ d: 0.1 # min absolute voltage delta high vs. low
553
+ u:
554
+ max: 3.45 # no discharging below this point
555
+ min: 3.05 # no charging above this point
556
+ """
557
+
558
+ # currently configured limits
559
+ uh: float = None
560
+ ul: float = None
561
+
562
+ # configured limits, battery
563
+ chg_max: float = None
564
+ chg_min: float = None
565
+ dis_max: float = None
566
+ dis_min: float = None
567
+
568
+ def __init__(self, cfg):
569
+ super().__init__(cfg)
570
+ self._reloaded = Event()
571
+ self._run = Event()
572
+
573
+ async def reload(self):
574
+ await super().reload()
575
+ await self._setup()
576
+
577
+ async def _setup(self):
578
+ self.n = self.cfg.get("n", 9999)
579
+ self.bat = self.root.sub_at(self.cfg["bat"]) if "bat" in self.cfg else None
580
+ if self.bat is not None:
581
+ # get battery limits
582
+ c = await self.bat.cfg_(("cfg", "lim", "u", "ext"))
583
+ self.dis_max = c["max"]
584
+ self.chg_min = c["min"]
585
+ c = await self.bat.cfg_(("cfg", "lim", "u", "std"))
586
+ self.dis_min = c["max"]
587
+ self.chg_max = c["min"]
588
+ c = self.cfg.get("u", {})
589
+ self.dis_min = max(self.dis_min, c.get("max", 0))
590
+ self.chg_max = max(self.chg_max, c.get("min", 9999))
591
+ if self.dis_min >= self.dis_max:
592
+ raise RuntimeError("Cf dis")
593
+ if self.chg_min >= self.chg_max:
594
+ raise RuntimeError("Cf Chg")
595
+
596
+ self._reloaded.set()
597
+ self._reloaded = Event()
598
+
599
+ async def setup(self):
600
+ await super().setup()
601
+ await self._setup()
602
+
603
+ async def start_tasks(self, tg):
604
+ await tg.spawn(self.run_bms)
605
+
606
+ async def task(self):
607
+ async with TaskGroup() as tg:
608
+ await self.start_tasks(tg)
609
+ await super().task()
610
+
611
+ async def cmd_u(self, h: float | None = None, l: float | None = None):
612
+ "set desired voltage levels"
613
+ if h is not None:
614
+ self.uh = min(self.dis_max, max(self.dis_min, h))
615
+ if l is not None:
616
+ self.ul = min(self.chg_max, max(self.chg_min, l))
617
+ self._run.set()
618
+
619
+ async def run_bms(self):
620
+ res = False
621
+ while True:
622
+ try:
623
+ await wait_for_ms(self.cfg["t"]["run" if res else "chk"], self._run.wait)
624
+ except KeyError:
625
+ await self._reloaded.wait()
626
+ continue
627
+ except TimeoutError:
628
+ pass
629
+ if self.bat is None:
630
+ await self._reloaded.wait()
631
+ continue
632
+
633
+ u = await self.bat.all("u")
634
+ res = await self._run_h(u)
635
+ # res = (await self._run_l(u)) || res
636
+
637
+ async def _run_h(self, u):
638
+ maxv = max(u)
639
+ minv = min(u)
640
+
641
+ # discharger states
642
+ st = await self.bat.all("dis")
643
+
644
+ if not self.uh or self.uh > maxv:
645
+ for uv, f in st:
646
+ if uv and not f:
647
+ await self.bat.all("dis", v=0)
648
+ break
649
+ return
650
+ try:
651
+ d = self.cfg["h"]["d"]
652
+ except KeyError:
653
+ d = 0.05
654
+
655
+ if maxv - minv < 2 * d or maxv < self.uh:
656
+ # all OK. Don't do any (more) work.
657
+ log("Bal- %.3f %.3f %.3f %.3f", minv, maxv, d, self.dis_min)
658
+ await self.bat.all("dis", v=0)
659
+ return
660
+
661
+ thrv1 = self.uh
662
+ minv = max(minv, self.dis_min)
663
+ thrv2 = minv + 0.8 * (thrv1 - minv) # small hysteresis
664
+ cc = list(enumerate(u))
665
+ cc.sort(key=lambda x: x[1], reverse=True)
666
+ ret = False
667
+
668
+ log("Bal %.3f %.3f %s %s", thrv1, thrv2, cc[0], cc[-1])
669
+
670
+ want = 0
671
+ cur = 0
672
+ # Step 1, count what we currently have+need (and do some cleanup)
673
+ for i, cv in cc:
674
+ if st[i][1]:
675
+ cur += 1
676
+ continue
677
+
678
+ if st[i][0] is not None:
679
+ if st[i][0] < cv:
680
+ cur += 1
681
+ if st[i][0] < minv:
682
+ # don't balance below the minimum
683
+ log("Balance1 %s", cv)
684
+ await self.bat(i, "dis", v=cv)
685
+ # don't spam the system when the min level changes
686
+ else:
687
+ # goal reached.
688
+ log("Unbalance1 %s", cv)
689
+ await self.bat(i, "dis", v=0)
690
+
691
+ elif cv >= thrv1 + d:
692
+ want += 1
693
+
694
+ # if cur:
695
+ # # update balancer power levels
696
+ # h, res = await self.send(RequestBalancePower())
697
+ # for c, r in zip(self.cells, res):
698
+ # r.to_cell(c)
699
+
700
+ if cur or want:
701
+ ret = True
702
+
703
+ # Step 1, if there are too many active cells, reduce the load
704
+ for i, cv in cc[::-1]:
705
+ if want + cur <= self.n:
706
+ # done
707
+ break
708
+ if st[i][1]:
709
+ continue
710
+ if st[i][0] > cv and cv < thrv2:
711
+ log("Unbalance2 %s", cv)
712
+ await self.bat(i, "dis", v=0)
713
+ cur -= 1
714
+
715
+ # Step 2, turn on balancing on cells that need it
716
+ for i, cv in cc:
717
+ if st[i][1]:
718
+ continue
719
+ if st[i][0]:
720
+ continue
721
+ if cur > self.n:
722
+ break
723
+ if cv >= thrv1 + d:
724
+ log("Balance2 %d %s", i, cv)
725
+ await self.bat(i, "dis", v=minv)
726
+ cur += 1
727
+ ret = True
728
+ continue
729
+ break
730
+
731
+ return ret
@@ -0,0 +1,6 @@
1
+ paths: {}
2
+ # in your config, add something like:
3
+ #paths:
4
+ # std: !P r.r.bms.bat1
5
+ # assuming a connection 'r' to the master with a connection 'r'
6
+ # to a satellite with a 'bms' directory with a 'bat1' battery
@@ -0,0 +1,84 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Basic tool support
4
+
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from contextlib import asynccontextmanager
10
+ import logging # pylint: disable=wrong-import-position
11
+
12
+ import asyncclick as click
13
+ from moat.util import load_subgroup, P, Path, yprint
14
+ from moat.micro.cmd.tree.dir import Dispatch
15
+
16
+ log = logging.getLogger()
17
+
18
+
19
+ @load_subgroup(sub_pre="moat.bms")
20
+ @click.option("-b", "--bat", "--battery", type=P, help="Battery to talk to. Default:'std'")
21
+ @click.pass_obj
22
+ async def cli(obj, bat):
23
+ """Battery Manager"""
24
+ cfg = obj.cfg
25
+ if not bat:
26
+ try:
27
+ bat = cfg.ems.battery.paths["std"]
28
+ except KeyError:
29
+ raise click.UsageError(
30
+ "No default battery. Set config 'ems.battery.paths.std' or use '--batt'.",
31
+ )
32
+ if len(bat) == 1:
33
+ try:
34
+ bat = cfg.ems.battery.paths["bat[0]"]
35
+ except KeyError:
36
+ p = P("ems.battery.paths") / bat[0]
37
+ raise click.UsageError(f"Couldn't find path at {bat}")
38
+ else:
39
+ if not isinstance(bat, Path):
40
+ raise click.UsageError(
41
+ "--battery: requires a path (directly or at 'ems.battery.paths')",
42
+ )
43
+ obj.bat = bat
44
+
45
+
46
+ @asynccontextmanager
47
+ async def _bat(obj):
48
+ async with Dispatch(cfg, run=True) as dsp, dsp.sub_at(obj.bat) as bat:
49
+ yield bat
50
+
51
+
52
+ @cli.group
53
+ @click.argument("cell", type=int)
54
+ @click.pass_obj
55
+ async def cell(obj, cell):
56
+ obj.cell = cell
57
+
58
+
59
+ @cell.command
60
+ @click.pass_obj
61
+ async def state(obj):
62
+ async with _bat(obj) as bat:
63
+ c = bat.sub_at(obj.cell)
64
+ p = await c.param()
65
+ u = await c.u()
66
+ t = await c.t()
67
+ tb = await c.tb()
68
+ res = dict(param=p, u=u, t=dict(cell=t, balancer=tb))
69
+ yprint(res, stream=obj.stdout)
70
+
71
+
72
+ @cell.command
73
+ @click.pass_obj
74
+ async def cfg(obj):
75
+ print("TODO", file=sys.stderr)
76
+ async with _bat(obj) as bat:
77
+ c = bat.sub_at(obj.cell)
78
+ await c.foo()
79
+
80
+
81
+ @cli.command
82
+ @click.pass_obj
83
+ async def state(obj):
84
+ pass
@@ -0,0 +1,17 @@
1
+ from __future__ import annotations
2
+ from moat.util import as_proxy
3
+
4
+
5
+ @as_proxy("err_eb_NSC")
6
+ class NoSuchCell(RuntimeError):
7
+ pass
8
+
9
+
10
+ @as_proxy("err_eb_ME")
11
+ class MessageError(RuntimeError):
12
+ pass
13
+
14
+
15
+ @as_proxy("err_eb_ML")
16
+ class MessageLost(RuntimeError):
17
+ pass
@@ -0,0 +1,24 @@
1
+ Metadata-Version: 2.4
2
+ Name: moat-ems-battery
3
+ Version: 0.2.11
4
+ Summary: REPLACE ME
5
+ Author-email: Matthias Urlichs <matthias@urlichs.de>
6
+ Project-URL: homepage, https://m-o-a-t.org
7
+ Project-URL: repository, https://github.com/M-o-a-T/moat
8
+ Keywords: MoaT
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Framework :: AnyIO
11
+ Classifier: Framework :: Trio
12
+ Classifier: Framework :: AsyncIO
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Intended Audience :: Developers
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/x-rst
17
+ License-File: LICENSE.txt
18
+ Requires-Dist: anyio~=3.0
19
+ Requires-Dist: msgpack
20
+ Requires-Dist: serialpacker
21
+ Requires-Dist: pyfuse3
22
+ Requires-Dist: moat-util~=0.56.4
23
+ Requires-Dist: moat-micro~=0.15.1
24
+ Dynamic: license-file
@@ -0,0 +1,13 @@
1
+ LICENSE.txt
2
+ README.md
3
+ pyproject.toml
4
+ moat/ems/battery/__init__.py
5
+ moat/ems/battery/_base.py
6
+ moat/ems/battery/_cfg.yaml
7
+ moat/ems/battery/_main.py
8
+ moat/ems/battery/errors.py
9
+ moat_ems_battery.egg-info/PKG-INFO
10
+ moat_ems_battery.egg-info/SOURCES.txt
11
+ moat_ems_battery.egg-info/dependency_links.txt
12
+ moat_ems_battery.egg-info/requires.txt
13
+ moat_ems_battery.egg-info/top_level.txt
@@ -0,0 +1,6 @@
1
+ anyio~=3.0
2
+ moat-micro~=0.15.1
3
+ moat-util~=0.56.4
4
+ msgpack
5
+ pyfuse3
6
+ serialpacker
@@ -0,0 +1,115 @@
1
+ [build-system]
2
+ requires = [
3
+ "wheel",
4
+ "setuptools >= 42",
5
+ ]
6
+ build-backend = "setuptools.build_meta"
7
+
8
+ [tool.black]
9
+ skip-string-normalization = true
10
+ line-length = 99
11
+
12
+ [tool.isort]
13
+ profile = "black"
14
+ # known_first_party = "foo"
15
+ line_length = 99
16
+ multi_line_output = 3
17
+
18
+ [tool.setuptools_scm]
19
+ local_scheme = "no-local-version"
20
+
21
+ [tool.pytest.ini_options]
22
+ log_cli_level = "DEBUG"
23
+
24
+ [tool.moat]
25
+
26
+ [tool.flake8]
27
+ max-line-length = 99
28
+ ignore = ["F841","F401","E731","E502","E402","E127","E123","E203","E231","W503"]
29
+
30
+ [tool.tox]
31
+ legacy_tox_ini = """
32
+ [tox]
33
+ isolated_build = True
34
+ envlist = py310,check
35
+
36
+ [testenv]
37
+ setenv =
38
+ PYTHONPATH = {env:PYTHONPATH}{:}{toxinidir}
39
+ deps =
40
+ trio
41
+ pytest
42
+ commands =
43
+ python3 -mpytest tests/
44
+
45
+ [testenv:check]
46
+ commands =
47
+ pylint moat tests
48
+ flake8p moat tests
49
+ black --check moat tests
50
+ deps =
51
+ pytest
52
+ pylint
53
+ black
54
+ flake8-pyproject
55
+ flake8
56
+
57
+ """
58
+
59
+ [tool.setuptools]
60
+ packages = ["moat.ems.battery"]
61
+
62
+ [tool.setuptools.package-data]
63
+ "*" = ["*.yaml"]
64
+
65
+ [tool.pylint.messages_control]
66
+ disable = "wrong-import-order,use-dict-literal,unspecified-encoding,ungrouped-imports,too-many-statements,too-many-return-statements,too-many-nested-blocks,too-many-locals,too-many-instance-attributes,too-many-branches,too-many-arguments,too-few-public-methods,superfluous-parens,no-else-return,no-else-continue,invalid-name,fixme"
67
+
68
+ [project]
69
+ classifiers = ["Development Status :: 4 - Beta","Framework :: AnyIO","Framework :: Trio","Framework :: AsyncIO","Programming Language :: Python :: 3","Intended Audience :: Developers"]
70
+ dependencies = [
71
+ "anyio ~= 3.0",
72
+ "msgpack",
73
+ "serialpacker",
74
+ "pyfuse3",
75
+ "moat-util ~= 0.56.4",
76
+ "moat-micro ~= 0.15.1",
77
+ ]
78
+ keywords = ["MoaT"]
79
+ requires-python = ">=3.8"
80
+ name = "moat-ems-battery"
81
+ authors = [{email = "matthias@urlichs.de",name = "Matthias Urlichs"}]
82
+ description = "REPLACE ME"
83
+ readme = "README.rst"
84
+ version = "0.2.11"
85
+ license-files = ["LICENSE.txt"]
86
+
87
+ [project.urls]
88
+ homepage = "https://m-o-a-t.org"
89
+ repository = "https://github.com/M-o-a-T/moat"
90
+
91
+ [tool.ruff]
92
+ select = ["ALL"]
93
+ ignore = ["BLE001","ERA","N","FIX","TD","RET50","C","PLR","EM10","TRY003","FBT","T2","D4","D3","D2","PLW1514","RUF002","RUF001","S101","A003","PERF","PTH","ANN","D105","D107","TID252","INP001","RUF005","SIM118","B904","TRY300","S311","SIM105","SIM108","E741","ISC003","RUF003"]
94
+
95
+ line-length = 99
96
+ preview = true
97
+ explicit-preview-rules = true
98
+
99
+ [tool.ruff.isort]
100
+ no-lines-before = ["future"]
101
+ required-imports = ["from __future__ import annotations"]
102
+ section-order = ["future", "typing", "standard-library", "first-party", "upy", "moat", "local-folder", "third-party"]
103
+ extra-standard-library = ["pytest", "anyio"]
104
+ force-to-top = ["moat.util"]
105
+
106
+ [tool.ruff.isort.sections]
107
+ "moat" = ["moat"]
108
+ "upy" = ["micropython", "machine", "esp"]
109
+ "typing" = ["typing"]
110
+
111
+ [tool.ruff.flake8-comprehensions]
112
+ allow-dict-calls-with-keyword-arguments = true
113
+
114
+ [tool.ruff.flake8-builtins]
115
+ builtins-ignorelist = ["help","id"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+