leancpms-cli 0.1.6__tar.gz → 0.1.7__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: leancpms-cli
3
- Version: 0.1.6
3
+ Version: 0.1.7
4
4
  Summary: The cpms command alone: a client of a LeanCPMS instance's JSON API
5
5
  License-Expression: AGPL-3.0-or-later
6
6
  License-File: LICENSE
@@ -36,7 +36,7 @@ cpms --help
36
36
  ```
37
37
 
38
38
  - **Upgrade:** `uv tool upgrade leancpms-cli`. To pin a version:
39
- `uv tool install leancpms-cli==0.1.6`.
39
+ `uv tool install leancpms-cli==0.1.7`.
40
40
  - **pipx** works too, if Python 3.14 is already installed:
41
41
  `pipx install leancpms-cli`.
42
42
  - Do not install it where the LeanCPMS server is installed: the server
@@ -64,6 +64,7 @@ readable only by you.
64
64
 
65
65
  ```bash
66
66
  cpms whoami # which key is in use, whose, for which organization
67
+ cpms --version # which cpms this is
67
68
  cpms logout # revokes the key on the server and forgets it
68
69
  ```
69
70
 
@@ -81,9 +82,22 @@ cpms sessions --since 2026-11-01 --status ended
81
82
  cpms sessions --since 2026-11-01 --csv > november.csv
82
83
  cpms session SIM-0001/42 # one session: <charge point>/<transaction>
83
84
  cpms session SIM-0001/42 stop # acts at once, no confirmation
85
+ cpms session SIM-0001/42 quarters # its energy per UTC quarter-hour
86
+ cpms quarters --since 2026-11-01 --until 2026-12-01 --csv > november-quarters.csv
84
87
  cpms report settlements --month 2026-10 # the month's settlements per site, with bookkeeping proposals
85
88
  ```
86
89
 
90
+ `cpms quarters` gives one row per session and UTC clock quarter-hour
91
+ (:00, :15, :30, :45): the Wh delivered in it, to set against quarter-hour
92
+ spot prices. `--site` narrows, `--json` gives the same rows as JSON. The
93
+ first and last quarter of a session are usually shorter than 15 minutes
94
+ (`seconds`); `estimated` marks a quarter computed across a gap in the meter
95
+ samples, and `final` is `False` (the table says `open`) for the quarter a
96
+ running session is in, which will still grow. `phases` is how many phases
97
+ carried charging current in the quarter (the most at once, at least 1 A,
98
+ as the box measured it; empty when the box reported no currents in it). A session's quarters sum to
99
+ exactly its `wh`. Energy only: there are no prices in it.
100
+
87
101
  **Who is a member, and with which role**
88
102
 
89
103
  ```bash
@@ -255,7 +269,7 @@ Raise `version` in both `cli/pyproject.toml` and the root `pyproject.toml`
255
269
  (a test keeps them equal), then tag and push:
256
270
 
257
271
  ```bash
258
- git tag cli-v0.1.6 && git push origin cli-v0.1.6
272
+ git tag cli-v0.1.7 && git push origin cli-v0.1.7
259
273
  ```
260
274
 
261
275
  `.github/workflows/release-cli.yml` builds the wheel and sdist, smoke-tests
@@ -24,7 +24,7 @@ cpms --help
24
24
  ```
25
25
 
26
26
  - **Upgrade:** `uv tool upgrade leancpms-cli`. To pin a version:
27
- `uv tool install leancpms-cli==0.1.6`.
27
+ `uv tool install leancpms-cli==0.1.7`.
28
28
  - **pipx** works too, if Python 3.14 is already installed:
29
29
  `pipx install leancpms-cli`.
30
30
  - Do not install it where the LeanCPMS server is installed: the server
@@ -52,6 +52,7 @@ readable only by you.
52
52
 
53
53
  ```bash
54
54
  cpms whoami # which key is in use, whose, for which organization
55
+ cpms --version # which cpms this is
55
56
  cpms logout # revokes the key on the server and forgets it
56
57
  ```
57
58
 
@@ -69,9 +70,22 @@ cpms sessions --since 2026-11-01 --status ended
69
70
  cpms sessions --since 2026-11-01 --csv > november.csv
70
71
  cpms session SIM-0001/42 # one session: <charge point>/<transaction>
71
72
  cpms session SIM-0001/42 stop # acts at once, no confirmation
73
+ cpms session SIM-0001/42 quarters # its energy per UTC quarter-hour
74
+ cpms quarters --since 2026-11-01 --until 2026-12-01 --csv > november-quarters.csv
72
75
  cpms report settlements --month 2026-10 # the month's settlements per site, with bookkeeping proposals
73
76
  ```
74
77
 
78
+ `cpms quarters` gives one row per session and UTC clock quarter-hour
79
+ (:00, :15, :30, :45): the Wh delivered in it, to set against quarter-hour
80
+ spot prices. `--site` narrows, `--json` gives the same rows as JSON. The
81
+ first and last quarter of a session are usually shorter than 15 minutes
82
+ (`seconds`); `estimated` marks a quarter computed across a gap in the meter
83
+ samples, and `final` is `False` (the table says `open`) for the quarter a
84
+ running session is in, which will still grow. `phases` is how many phases
85
+ carried charging current in the quarter (the most at once, at least 1 A,
86
+ as the box measured it; empty when the box reported no currents in it). A session's quarters sum to
87
+ exactly its `wh`. Energy only: there are no prices in it.
88
+
75
89
  **Who is a member, and with which role**
76
90
 
77
91
  ```bash
@@ -243,7 +257,7 @@ Raise `version` in both `cli/pyproject.toml` and the root `pyproject.toml`
243
257
  (a test keeps them equal), then tag and push:
244
258
 
245
259
  ```bash
246
- git tag cli-v0.1.6 && git push origin cli-v0.1.6
260
+ git tag cli-v0.1.7 && git push origin cli-v0.1.7
247
261
  ```
248
262
 
249
263
  `.github/workflows/release-cli.yml` builds the wheel and sdist, smoke-tests
@@ -95,11 +95,22 @@ def load_config(profile: str | None) -> Config:
95
95
  url = instance_url(None, url, named_profile=bool(profile))
96
96
  if not key:
97
97
  login = f"cpms login --profile {profile}" if profile else "cpms login"
98
- raise UsageError(f"no API key for {describe(url)}: run {login}, or set CPMS_API_KEY "
99
- f"(or a profile in {config_path()})")
98
+ others = _profiles() if not profile else []
99
+ hint = (f"; profiles in {config_path()}: {', '.join(others)} (use --profile or CPMS_PROFILE)"
100
+ if others else f" (or a profile in {config_path()})")
101
+ raise UsageError(f"no API key for {describe(url)}: run {login}, or set CPMS_API_KEY{hint}")
100
102
  return Config(url, key)
101
103
 
102
104
 
105
+ def _profiles() -> list[str]:
106
+ """The named profiles in the config file, for the hint when none was chosen and [default] has no key."""
107
+ try:
108
+ data = tomllib.loads(config_path().read_text())
109
+ except (OSError, tomllib.TOMLDecodeError):
110
+ return []
111
+ return [k for k, v in data.items() if k != "default" and isinstance(v, dict) and v.get("api_key")]
112
+
113
+
103
114
  class Api:
104
115
  """The JSON API. Without a key (`cpms login` starting) only the routes that need none answer.
105
116
  `transport` is for tests."""
@@ -54,6 +54,13 @@ def _hm(ts: str | None) -> str:
54
54
  return ts[:19].replace("T", " ") if ts else ""
55
55
 
56
56
 
57
+ def _link(cp: dict[str, Any]) -> str:
58
+ """up, down, or silent: connected, but the gateway has heard nothing for two heartbeats."""
59
+ if not cp["connected"]:
60
+ return "down"
61
+ return "silent" if cp.get("responsive") is False else "up" # None: an older server, or no gateway answer
62
+
63
+
57
64
  def _amps(c: dict[str, Any]) -> str:
58
65
  return " ".join(f"{p} {float(c.get(p) or 0):.1f}" for p in ("L1", "L2", "L3"))
59
66
 
@@ -73,24 +80,24 @@ def cmd_status(api: Api, a: argparse.Namespace) -> int:
73
80
  if not body["sites"]:
74
81
  _print("no sites")
75
82
  for site in body["sites"]:
76
- _print(f"{site['organization']}/{site['key']} {site['name']} station A: {_amps(site['station_current'])}")
83
+ _print(f"{site['organization']}/{site['key']} {site['name']} current (main fuse phases): {_amps(site['current'])}")
77
84
  for fg in site["fuse_groups"]:
78
85
  _print(f" fuse group {fg['key']}: budget {fg['budget_amps']} A of {fg['physical_fuse_amps']} A, "
79
- f"{fg['active_sessions']} active, station A: {_amps(fg['station_current'])}")
86
+ f"{fg['active_sessions']} active, current (main fuse phases): {_amps(fg['current'])}")
80
87
  rows = []
81
88
  for cp in fg["charge_points"]:
82
89
  for o in cp["outlets"]:
83
90
  s = o["session"]
84
91
  rows.append([
85
- cp["key"], cp["ocpp_id"], "up" if cp["connected"] else "down", o["key"],
92
+ cp["key"], cp["ocpp_id"], _link(cp), o["key"],
86
93
  o["status"] or "-", s["transaction_id"] if s else "", s["wh"] if s else "",
87
94
  _money(s["amount_incl_vat"], s["currency"]) if s else "",
88
- _amps(o["station_current"]), (o["issued_limit"] or {}).get("amps", ""), o["verdict"],
95
+ _amps(o["current"]), (o["issued_limit"] or {}).get("amps", ""), o["verdict"],
89
96
  _hm(cp["last_event_at"]),
90
97
  ])
91
98
  if rows:
92
99
  _print()
93
- table(rows, ["CP", "OCPP ID", "LINK", "OUTLET", "STATUS", "TX", "WH", "INCL VAT", "STATION A",
100
+ table(rows, ["CP", "OCPP ID", "LINK", "OUTLET", "STATUS", "TX", "WH", "INCL VAT", "CURRENT (MAIN FUSE PHASES)",
94
101
  "LIMIT", "VERDICT", "LAST EVENT"])
95
102
  _print()
96
103
  if body.get("unclaimed"):
@@ -145,7 +152,8 @@ def cmd_chargepoints(api: Api, a: argparse.Namespace) -> int:
145
152
 
146
153
  SESSION_CSV = ["ocpp_id", "transaction_id", "organization", "site", "charge_point", "outlet", "connector", "status",
147
154
  "started_at", "ended_at", "end_reason", "end_inferred", "learned", "wh", "plan", "tariff",
148
- "price_per_kwh", "price_amounts", "vat_rate", "amount_incl_vat", "amount_excl_vat", "currency"]
155
+ "price_per_kwh", "price_amounts", "vat_rate", "amount_incl_vat", "amount_excl_vat", "currency",
156
+ "spot_area", "spot_markup_per_kwh", "spot_missing_from"]
149
157
 
150
158
 
151
159
  def cmd_sessions(api: Api, a: argparse.Namespace) -> int:
@@ -182,6 +190,15 @@ def _event_rows(events: list[dict[str, Any]]) -> None:
182
190
  summary(e)] for e in events], ["SEQ", "TS (UTC)", "CHARGE POINT", "C", "TX", "EVENT", "DATA"])
183
191
 
184
192
 
193
+ def _session_price(s: dict[str, Any], side: str) -> str:
194
+ """The price line of `cpms session`: a flat price, or a spot tariff's rule and the average it gave."""
195
+ if s.get("spot_area"):
196
+ average = f", average {s['price_per_kwh']} {s['currency']}/kWh {side}" if s["price_per_kwh"] else ""
197
+ return (f"spot {s['spot_area']} + {s['spot_markup_per_kwh']} {s['currency']}/kWh {side}{average}, "
198
+ f"plan {s['plan']}")
199
+ return f"{s['price_per_kwh']} {s['currency']}/kWh {side}, plan {s['plan']}" if s["price_per_kwh"] else "-"
200
+
201
+
185
202
  def cmd_session(api: Api, a: argparse.Namespace) -> int:
186
203
  ocpp_id, tx = _ref(a.ref)
187
204
  base = f"/sessions/{ocpp_id}/{tx}"
@@ -195,6 +212,15 @@ def cmd_session(api: Api, a: argparse.Namespace) -> int:
195
212
  result = api.post(f"{base}/close", {"reason": a.message})
196
213
  _dump(result) if a.json else _print(f"closed {ocpp_id}/{tx}" if result["closed"] else "not closed")
197
214
  return 0
215
+ if a.verb == "quarters":
216
+ body = api.get(f"{base}/quarters")
217
+ if a.json:
218
+ _dump(body)
219
+ return 0
220
+ table([[_hm(q["start"]), q["seconds"], q["energy_wh"], q["phases"], _flags(q)] for q in body["quarters"]],
221
+ ["QUARTER (UTC)", "SECONDS", "WH", "PHASES", ""])
222
+ _print(f"{body['wh']} Wh in {len(body['quarters'])} quarter-hours ({body['status']})")
223
+ return 0
198
224
  s = api.get(base)
199
225
  events = api.get(f"{base}/events")["events"] if a.events else None
200
226
  if a.json:
@@ -211,9 +237,10 @@ def cmd_session(api: Api, a: argparse.Namespace) -> int:
211
237
  ("ended (UTC)", f"{_hm(s['ended_at'])} {s['end_reason']}" + (
212
238
  " (not the box's own stop)" if s["end_inferred"] else "") if s["ended_at"] else "-"),
213
239
  ("energy", f"{s['wh']} Wh (register {s['meter_start_wh']} → {s['meter_last_wh']})"),
214
- ("price", f"{s['price_per_kwh']} {s['currency']}/kWh {side}, plan {s['plan']}" if s["price_per_kwh"] else "-"),
240
+ ("price", _session_price(s, side)),
215
241
  ("amount", f"{s['amount_incl_vat']} incl. VAT, {s['amount_excl_vat']} excl. VAT {s['currency']}"
216
- if s["amount_incl_vat"] is not None else "-"),
242
+ if s["amount_incl_vat"] is not None else
243
+ f"- (waits for the spot price from {_hm(s['spot_missing_from'])} UTC)" if s.get("spot_missing_from") else "-"),
217
244
  ("samples", str(len(s["samples"]))),
218
245
  ]
219
246
  if s.get("close"):
@@ -226,6 +253,39 @@ def cmd_session(api: Api, a: argparse.Namespace) -> int:
226
253
  return 0
227
254
 
228
255
 
256
+ def _flags(q: dict[str, Any]) -> str:
257
+ return " ".join(w for w, on in (("estimated", q["estimated"]), ("open", not q["final"])) if on)
258
+
259
+
260
+ QUARTER_CSV = ["start", "energy_wh", "seconds", "estimated", "final", "phases", "ocpp_id", "transaction_id", "organization",
261
+ "site", "charge_point", "outlet"]
262
+
263
+
264
+ def cmd_quarters(api: Api, a: argparse.Namespace) -> int:
265
+ """Every page of the interval, so the output is the whole of it."""
266
+ rows: list[dict[str, Any]] = []
267
+ after = None
268
+ while True:
269
+ body = api.get("/energy/quarters", since=a.since, until=a.until, organization=a.org, site=a.site,
270
+ after=after, limit=10000)
271
+ rows += body["quarters"]
272
+ after = body["next"]
273
+ if not after:
274
+ break
275
+ if a.json:
276
+ _dump({"quarters": rows})
277
+ return 0
278
+ if a.csv:
279
+ w = csv.DictWriter(sys.stdout, fieldnames=QUARTER_CSV, extrasaction="ignore", lineterminator="\n")
280
+ w.writeheader()
281
+ w.writerows(rows)
282
+ return 0
283
+ table([[_hm(q["start"]), f"{q['ocpp_id']}/{q['transaction_id']}", q["site"], q["outlet"], q["seconds"],
284
+ q["energy_wh"], q["phases"], _flags(q)] for q in rows],
285
+ ["QUARTER (UTC)", "SESSION", "SITE", "OUTLET", "SECONDS", "WH", "PHASES", ""])
286
+ return 0
287
+
288
+
229
289
  def cmd_events(api: Api, a: argparse.Namespace) -> int:
230
290
  body = api.get("/events", since=a.since, limit=a.limit, chargepoint=a.chargepoint, event=a.event)
231
291
  if a.json:
@@ -780,6 +840,18 @@ def cmd_ocpi_preview(api: Api, a: argparse.Namespace) -> int:
780
840
  # --- the parser ------------------------------------------------------------------------------
781
841
 
782
842
 
843
+ def _package_version() -> str:
844
+ """The installed version: leancpms-cli alone, or the server package that also contains cpms."""
845
+ from importlib.metadata import PackageNotFoundError, version
846
+
847
+ for dist in ("leancpms-cli", "leancpms"):
848
+ try:
849
+ return f"{version(dist)} ({dist})"
850
+ except PackageNotFoundError:
851
+ continue
852
+ return "unknown (not installed as a package)"
853
+
854
+
783
855
  class _Parser(argparse.ArgumentParser):
784
856
  def error(self, message: str) -> Any: # exit 2, as argparse does, but through our handler
785
857
  raise UsageError(f"{self.prog}: {message}")
@@ -799,6 +871,7 @@ def parser() -> argparse.ArgumentParser:
799
871
  " CPMS_API_KEY the key, instead of a profile's (scripts, CI, agents)\n"
800
872
  " CPMS_PROFILE the profile, as --profile\n"
801
873
  " CPMS_CONFIG the config file (default ~/.config/cpms/config.toml)")
874
+ p.add_argument("--version", action="version", version=f"cpms {_package_version()}")
802
875
  sub = p.add_subparsers(dest="command", parser_class=_Parser)
803
876
 
804
877
  def cmd(name: str, fn: Callable[..., int], help: str, **kw: Any) -> argparse.ArgumentParser:
@@ -824,12 +897,20 @@ def parser() -> argparse.ArgumentParser:
824
897
  s.add_argument("--limit", type=int, default=100)
825
898
  s.add_argument("--csv", action="store_true")
826
899
 
827
- s = cmd("session", cmd_session, "one session: <ocpp_id>/<transaction_id> [stop|close -m REASON]")
900
+ s = cmd("session", cmd_session, "one session: <ocpp_id>/<transaction_id> [quarters|stop|close -m REASON]")
828
901
  s.add_argument("ref")
829
- s.add_argument("verb", nargs="?", choices=["stop", "close"])
902
+ s.add_argument("verb", nargs="?", choices=["quarters", "stop", "close"],
903
+ help="quarters: its energy per UTC quarter-hour")
830
904
  s.add_argument("--events", action="store_true", help="the box's events for this session")
831
905
  s.add_argument("-m", "--message", help="the reason for close")
832
906
 
907
+ s = cmd("quarters", cmd_quarters, "delivered energy per session and UTC quarter-hour over an interval")
908
+ s.add_argument("--since", required=True, help="ISO date (UTC) or time: quarters starting at or after it")
909
+ s.add_argument("--until", help="ISO date (UTC) or time: quarters starting before it")
910
+ s.add_argument("--site")
911
+ s.add_argument("--org")
912
+ s.add_argument("--csv", action="store_true")
913
+
833
914
  s = cmd("events", cmd_events, "the gateway's event log (pass-through)")
834
915
  s.add_argument("--since", type=int, default=0)
835
916
  s.add_argument("--chargepoint")
@@ -966,11 +1047,13 @@ def parser() -> argparse.ArgumentParser:
966
1047
 
967
1048
 
968
1049
  def main(argv: list[str] | None = None) -> int:
1050
+ alone = False
969
1051
  try:
970
1052
  a = parser().parse_args(argv)
971
1053
  a.json = getattr(a, "json", False)
972
1054
  fn = getattr(a, "fn", None)
973
- if fn is None: # `cpms` alone: the live state
1055
+ alone = fn is None
1056
+ if alone: # `cpms` alone: the live state
974
1057
  a.site = a.org = None
975
1058
  fn = cmd_status
976
1059
  if fn in (cmd_validate, cmd_schema, cmd_login): # offline, or a login: no key yet
@@ -982,6 +1065,8 @@ def main(argv: list[str] | None = None) -> int:
982
1065
  api.close()
983
1066
  except UsageError as e:
984
1067
  _err(str(e) if str(e).startswith("cpms") else f"cpms: {e}")
1068
+ if alone:
1069
+ _err("cpms --help lists the commands; cpms --version says which cpms this is")
985
1070
  return 2
986
1071
  except ApiError as e:
987
1072
  if getattr(e, "detail", None):
@@ -198,7 +198,16 @@ class FlatPrice(Strict):
198
198
  class SpotPrice(Strict):
199
199
  from_: dt.date = Field(alias="from")
200
200
  spot_markup_per_kwh: Money = Field(ge=0)
201
- fallback_per_kwh: Money | None = Field(default=None, ge=0)
201
+
202
+ @model_validator(mode="before")
203
+ @classmethod
204
+ def _drop_fallback(cls, data: object) -> object:
205
+ """`fallback_per_kwh` was a field until 2026-11-26 and was never read: a session whose market
206
+ price is missing waits for it. Stored versions carry it and are parsed on every read, and a
207
+ row that has taken effect cannot be re-applied without it, so it is dropped here, not refused."""
208
+ if isinstance(data, dict) and "fallback_per_kwh" in data:
209
+ return {k: v for k, v in data.items() if k != "fallback_per_kwh"}
210
+ return data
202
211
 
203
212
 
204
213
  class _TariffBase(Strict):
@@ -238,9 +247,16 @@ class Fee(Strict):
238
247
 
239
248
 
240
249
  class Billing(Strict):
250
+ """How a subscription plan is billed (architecture §6.1, §8). Every field has one value so far, or a
251
+ default: the document says what the system does, and a second way of doing it is a new value."""
252
+
241
253
  period: Literal["month"] = "month"
242
254
  fee: Literal["in_advance"] = "in_advance"
243
255
  energy: Literal["in_arrears"] = "in_arrears"
256
+ # A new subscriber pays the rest of the first month at signup; every later invoice is on the 1st.
257
+ first_month: Literal["prorate"] = "prorate"
258
+ # An invoice still unpaid after this many days moves the subscriber's starts to the ad hoc channel.
259
+ unpaid_days: int = Field(default=14, ge=1, le=90)
244
260
  on_end: Literal["public"] = "public"
245
261
 
246
262
 
@@ -250,8 +266,12 @@ class Plan(Strict):
250
266
  tariff: Key
251
267
  requires: Literal["none", "subscription", "roaming"]
252
268
  preauth_amount: Money | None = Field(default=None, gt=0) # incl. VAT, reserved on the card
269
+ # The monthly fee of a subscription plan, in dated rows, on the side its tariff's `amounts` names.
253
270
  fees: list[Fee] = []
254
271
  billing: Billing | None = None
272
+ # Where a subscription plan applies (architecture §6.1): these sites and nowhere else. Left out: at
273
+ # every site of the organization.
274
+ sites: list[Key] | None = None
255
275
 
256
276
 
257
277
  class RoamingChannel(Strict):
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "leancpms-cli"
3
- version = "0.1.6"
3
+ version = "0.1.7"
4
4
  description = "The cpms command alone: a client of a LeanCPMS instance's JSON API"
5
5
  readme = "README.md"
6
6
  license = "AGPL-3.0-or-later"
File without changes
File without changes