Skip to content

Fix Kamstrup timestamp timezone decode (#1191) + latent hour-array OOB guard - #1227

Merged
gskjold merged 3 commits into
mainfrom
fix/decoder-bounds-and-kamstrup-tz
Jul 17, 2026
Merged

gskjold merged 3 commits into
mainfrom
fix/decoder-bounds-and-kamstrup-tz

Conversation

@gskjold

@gskjold gskjold commented Jul 2, 2026

Copy link
Copy Markdown
Member

Two decoder fixes found while investigating #1191.

1. Kamstrup meter-timestamp timezone decode (the #1191 "1 hour off")

Kamstrup meters leave the DLMS clock deviation (UTC offset) field unspecified (0x8000) — confirmed across every timestamped Kamstrup fixture in the corpus. The decoder compensated with a hardcoded ts -= 3600 in adjustForKnownIssues(), which is only correct for CET. On a Finnish meter (EET) the timestamp came out 1–2 h off, and it was wrong for any non-CET zone generally.

Ground truth (a Norwegian capture with a healthy NTP clock — meter 21:14 CET vs true 20:14 UTC, in summer) confirms Kamstrup reports its clock in local standard time year-round — it does not spring forward for DST, and the DST status bit (when set) is only informational.

Fix: treat the wall-clock fields as the configured zone's standard local time and subtract that zone's standard UTC offset (probed from tz at a mid-winter date). Deterministic (no more libc-mktime dependence), CET stays correct in both seasons, EET/other zones are now correct. Aidon's path is unchanged.

Caveat / open item

We do not have a Finnish capture with a reliable clock to 100% confirm Finnish Kamstrup also reports standard time year-round (the #1191 reporter's device clock was itself days off). This fix is a strict improvement regardless — it's exact for CET/CEST and never worse than the old behaviour for EET. If Finnish meters turn out to spring forward, only the summer offset would need revisiting.

Tests

test_kamstrup_timezone pins the conversion across CET winter, CET/CEST summer, and EET:

The native Timezone stub gained a standard offset, and the harness can now decode with a supplied timezone. The golden master is unaffected (it doesn't capture meter timestamps). gh1191-1.hex is documented in the payload README and loaded directly by the test; I deliberately did not regenerate manifest.json/fixtures_generated.h/the golden here, because doing so also pulls in pre-existing, unrelated drift (an untracked elgama fixture and an order-dependent stale value in gh175-2's golden row) — best handled separately.

2. Latent out-of-bounds guard in hourly accessors

setHourImport/getHourImport/setHourExport/getHourExport guarded with hour > 24, allowing hour == 24 to index the 24-element hImport[24]/hExport[24] arrays one past the end (neighbour: lastMeterReadTime). No current caller passes 24, so it's latent — changed to hour >= 24. (The month-day accessors are already correct — they index dImport[day-1].)

Testing

  • pio test -e native → 16/16 pass (incl. new test_kamstrup_timezone, golden unchanged)
  • pio run -e esp8266dev and -e esp32dev → build SUCCESS

Related: #1191. Companion to the NTP-freshness diagnostic in #1221.

🤖 Generated with Claude Code

gskjold and others added 3 commits July 2, 2026 12:28
setHourImport/getHourImport/setHourExport/getHourExport guarded with
`hour > 24`, allowing hour == 24 to index day.hImport[24] / hExport[24]
— one past the 24-element arrays, whose neighbour is lastMeterReadTime.
No current caller passes 24 (the clearing loops use 24 as an exclusive
bound and breakTime only yields 0..23), so this is latent, but a single
refactor could activate it. Use `hour >= 24`.

The month-day accessors are already correct: they index dImport[day-1]
with a `day > 31` guard, so day 31 maps to index 30.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…d -1h

Kamstrup meters leave the DLMS clock `deviation` (UTC offset) field
unspecified (0x8000) — verified across every timestamped Kamstrup fixture
in the corpus. The decoder compensated with a hardcoded `ts -= 3600`,
which is only correct for CET. On a Finnish meter (EET, issue #1191) the
meter timestamp came out an hour+ off, and it was wrong for any non-CET
zone in general.

Ground truth (a Norwegian capture with a known-good NTP clock: meter
21:14 CET vs true 20:14 UTC, in summer) confirms Kamstrup reports its
clock in local STANDARD time year-round — it does not spring forward for
DST. So convert deterministically: treat the wall-clock fields as the
configured zone's standard local time and subtract that zone's standard
UTC offset (probed from `tz` at a mid-winter date). The DST status bit is
intentionally ignored — the clock value is standard time regardless.
Aidon's handling is left unchanged.

This keeps CET correct in both seasons (and removes the previous
libc-mktime dependence) while fixing EET and other zones.

Adds test_kamstrup_timezone covering CET winter, CET summer and EET
(Jonas's frame from #1191 as fixture gh1191-1.hex), plus the native
Timezone stub gains a standard offset and the harness can decode with a
given timezone.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Three small robustness fixes from Arne's investigation notes on #1191:

1. configTime() daylight offset: the 2nd argument is the incremental DST
   shift, but the code passed the full summer offset
   (toLocal(JULY1970)-JULY1970), double-counting the base offset during
   DST. Subtract the standard offset so it's the ~3600 s delta. Currently
   inert (nothing calls localtime(); the only mktime() forces isdst=0),
   but correct and future-proof.

2. Meter-clock seed is now one-shot. The boot-time fallback that seeds
   the system clock from the meter timestamp (when time() < BuildEpoch)
   could re-fire if the clock ever regressed mid-uptime, permanently
   overwriting a good clock with a meter time that some meters decode
   with an offset error. Guard it so it only runs once per boot.

3. thresholds[] out-of-bounds read: the tariff-step loop tested
   thresholds[idx] before the idx<10 bound (short-circuit order), reading
   thresholds[10] on a 10-element array once the index reached 10. Check
   the bound first, and clamp getCurrentThreshold() to 0..9.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@gskjold

gskjold commented Jul 16, 2026

Copy link
Copy Markdown
Member Author

Added a third commit with three small robustness fixes from Arne's #1191 investigation notes (verified against the code):

  • configTime() daylight offset (AmsToMqttBridge.cpp): the 2nd arg is the incremental DST shift, but the code passed the full summer offset (toLocal(JULY1970)-JULY1970), double-counting the base offset during DST. Now subtracts the standard offset for the ~3600 s delta. Currently inert — nothing calls localtime(), and the only mktime() forces tm_isdst=0 (ignores the daylight offset) — but correct and future-proof.
  • One-shot meter-clock seed (AmsToMqttBridge.cpp): the boot fallback that seeds the system clock from the meter timestamp (when time() < BuildEpoch) could re-fire if the clock ever regressed mid-uptime, permanently overwriting a good clock with a meter time that some meters decode with an offset error. Guarded to run once per boot.
  • thresholds[] OOB read (EnergyAccounting.cpp): the tariff-step loop tested thresholds[idx] before the idx<10 bound (short-circuit order), reading thresholds[10] on a 10-element array once the index hit 10. Bound checked first; getCurrentThreshold() clamped to 0..9.

Build note

native tests 16/16 pass and esp32dev builds clean. esp8266 (and esp8266dev) overflow flash — but this is pre-existing on main: base commit 653fa93d is already 1049923 B (dev) / 1046815 B (prod) vs the 1044464 B limit, before any change here. All commits on this branch together add only ~316 B. ESP8266 flash on main needs a separate diet; it's not introduced by these fixes.

@github-actions

Copy link
Copy Markdown

🔧 PR Build Artifacts

Version: 3048332

All environments built successfully. Download the zip files:

Artifacts expire after 7 days. View workflow run

@gskjold
gskjold marked this pull request as ready for review July 17, 2026 06:31
@gskjold
gskjold merged commit 53c4ad6 into main Jul 17, 2026
8 checks passed
@gskjold
gskjold deleted the fix/decoder-bounds-and-kamstrup-tz branch July 17, 2026 06:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant