Sync with GitHub fork (upstream v0.4.0b1 + BLE fixes), own the library dependency, bump tooling #1

Merged
tim merged 33 commits from chore/sync-github-fork into main 2026-10-12 08:36:20 +00:00
Owner

Brings this repo up to date with timstoop/nissan-leaf-obd-ble on GitHub and moves the dependency path under our control.

Commits

  1. Merge GitHub fork main: upstream v0.4.0b1 (override system, UUID setup flow) plus the BLE reliability fixes. Tree is identical to GitHub main at cd1c8f1. The one commit that only existed here is already contained there (evolved with a fallback), so it is not re-applied.
  2. fix(deps): py-nissan-leaf-obd-ble now comes from git.timstoop.nl/tim/py-nissan-leaf-obd-ble, pinned to a tag, instead of the moving main of a GitHub fork.
  3. chore: pre-commit revs (pyupgrade v3.22.0, black 26.10.1, codespell v2.4.3, ruff v0.17.0 from astral-sh with hook id ruff-check, mypy v2.4.0).
  4. chore: ruff.toml pins the lint rules to the previous defaults (E4/E7/E9/F). ruff 0.17 defaults are much broader and would flag existing code.
  5. chore: codespell ignore list gets thirdparty (isort section name in setup.cfg).
  6. style: ruff format. Python ASTs of all changed modules are identical before and after.
  7. fix(deps): pin moved to v0.2.0 (the library release was renamed from 0.1.2.post1).

Merge order

This integration cannot install its dependency until the library has the tag:

  1. Merge tim/py-nissan-leaf-obd-ble!1 (release 0.2.0).
  2. Create tag v0.2.0 on the merge commit.
  3. Merge this MR.

Checked

  • pre-commit run --all-files passes (all hooks).
  • Library tests: 182 passed on Python 3.14.8 with bleak 3.0.2 and bleak-retry-connector 4.7.1.
  • Not tested: running inside Home Assistant (no HA test suite in this repo).

Not included

  • Upstream library PRs for ZE0 odometer and per-model command sets (not relevant for a ZE1).
  • Broader lint rules, pyupgrade --py37-plus and setup.cfg mypy python_version = 3.7 are stale but unchanged here.

Generated with Claude Code

Brings this repo up to date with timstoop/nissan-leaf-obd-ble on GitHub and moves the dependency path under our control. ## Commits 1. **Merge GitHub fork `main`**: upstream v0.4.0b1 (override system, UUID setup flow) plus the BLE reliability fixes. Tree is identical to GitHub `main` at `cd1c8f1`. The one commit that only existed here is already contained there (evolved with a fallback), so it is not re-applied. 2. **fix(deps)**: `py-nissan-leaf-obd-ble` now comes from `git.timstoop.nl/tim/py-nissan-leaf-obd-ble`, pinned to a tag, instead of the moving `main` of a GitHub fork. 3. **chore**: pre-commit revs (pyupgrade v3.22.0, black 26.10.1, codespell v2.4.3, ruff v0.17.0 from astral-sh with hook id `ruff-check`, mypy v2.4.0). 4. **chore**: `ruff.toml` pins the lint rules to the previous defaults (E4/E7/E9/F). ruff 0.17 defaults are much broader and would flag existing code. 5. **chore**: codespell ignore list gets `thirdparty` (isort section name in `setup.cfg`). 6. **style**: `ruff format`. Python ASTs of all changed modules are identical before and after. 7. **fix(deps)**: pin moved to `v0.2.0` (the library release was renamed from 0.1.2.post1). ## Merge order This integration cannot install its dependency until the library has the tag: 1. Merge tim/py-nissan-leaf-obd-ble!1 (release 0.2.0). 2. Create tag `v0.2.0` on the merge commit. 3. Merge this MR. ## Checked - `pre-commit run --all-files` passes (all hooks). - Library tests: 182 passed on Python 3.14.8 with bleak 3.0.2 and bleak-retry-connector 4.7.1. - Not tested: running inside Home Assistant (no HA test suite in this repo). ## Not included - Upstream library PRs for ZE0 odometer and per-model command sets (not relevant for a ZE1). - Broader lint rules, `pyupgrade --py37-plus` and `setup.cfg` mypy `python_version = 3.7` are stale but unchanged here. Generated with [Claude Code](https://claude.com/claude-code)
tim added 32 commits 2026-10-12 08:12:53 +00:00
DataUpdateCoordinator.async_request_refresh() uses a debouncer lock held for
the entire BLE read. When async_get_data never returned, the lock stayed held
and subsequent advertisement callbacks logged but did not trigger updates
(debouncer returned in ~70ms with no refresh).

- Wrap async_get_data in asyncio.wait_for with default 90s timeout
  (override via options fetch_timeout when exposed in config).
- On timeout, raise UpdateFailed and log agent NDJSON fetch_timeout.
- Register debug NDJSON under hass.config.config_dir plus optional paths;
  advert wakeup task logs debouncer duration for diagnosis.
- Ignore .DS_Store in git.

Made-with: Cursor
fix: recover from hung BLE fetch so advert wakeups work again
- Drop _debug_agent module and instrumentation from coordinator and setup
- On BLE rediscovery, call coordinator.async_request_refresh() directly
- Release version 0.3.1 (was 0.3.1b2)

Co-authored-by: Cursor <cursoragent@cursor.com>
The ble_device object captured at integration setup becomes stale after
a GATT disconnect (error 133). bleak_retry_connector needs fresh
advertisement data to reliably reconnect, so fetch it from HA's
bluetooth stack on every _async_update_data call.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
After GATT error 133, async_get_data can hang indefinitely, holding
the DataUpdateCoordinator debouncer lock forever. Subsequent
async_request_refresh() calls no-op (~70ms) without refreshing.

- Wrap async_get_data in asyncio.wait_for(timeout=90s) so UpdateFailed
  is raised and the lock is released, allowing the next poll to retry.
- Refresh ble_device from HA's BT stack before each connection attempt
  so bleak_retry_connector always has current advertisement data after
  a disconnect (stale object causes repeated GATT 133 on Linux/BlueZ).

Timeout cherry-picked from pbutterworth/fix/ble-stall-and-advert-wakeup
(debug logging stripped). Device refresh from fix/ble-device-refresh.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- On connection exception (timeout or BLE error): switch to slow poll
  interval instead of staying at fast poll, so the dongle has time to
  recover between retries (was 10s, now 30s backoff).
- When cache_values=True and cached data exists, return cached data
  instead of raising UpdateFailed so entities stay available rather
  than going unavailable on transient connection failures.
- Increase DEFAULT_FAST_POLL from 10s to 30s to reduce connection
  frequency and improve reconnection reliability.
- DEFAULT_SLOW_POLL from 300s to 30s for faster recovery detection.
- Bump version to 0.3.1b3.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The dongle stops advertising after each GATT session ends, causing
async_address_present(connectable=True) to return False and switching
the coordinator to xs_poll (1 hour). This meant updates only happened
at HA restart, not during normal 30s polling.

Fix: use async_ble_device_from_address with connectable=True falling
back to connectable=False. The device object persists in HA's BLE
registry even without active advertisements, so we can still attempt
a connection. xs_poll is now only triggered when the device has not
been seen at all. Remove unused async_address_present import.

Bump version to 0.3.1b4.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
After a GATT session ends, the dongle stops advertising and leaves
HA's BLE registry within minutes. async_ble_device_from_address()
then returns None for both connectable=True and connectable=False,
silently switching the coordinator to xs_poll (1 hour) with cached
data -- identical to the original symptom.

Mirror the __init__.py approach: add get_device() as a final
fallback. It does an active BLE scan and finds the dongle even
when it is not continuously advertising. Only switch to xs_poll
if the active scan also fails (device truly out of range).

Bump version to 0.3.1b5.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
After a GATT session ends the dongle stops advertising briefly. The HA
BLE registry returns None for both connectable and non-connectable
lookups during this window. Previously the coordinator fell through to
get_device() (active scan) which raised UpdateFailed before the try/except
block, causing the integration to go unavailable on the very first refresh.

Now: if async_ble_device_from_address returns a fresh device we update
self.api._ble_device; if it returns None we fall through with the existing
object that __init__.py set via get_device() at setup time.
bleak_retry_connector will still attempt the GATT connection via the proxy
and fail gracefully if the device is truly unreachable.

xs_poll is now only triggered when no device object exists at all (i.e.
setup never completed), preventing the coordinator from getting stuck in
a 1-hour poll cycle after every disconnect.

Bump version to 0.3.1b6.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Both were incorrectly set to 30s in a previous commit. Restore to match
the existing named constants (FAST_POLL_INTERVAL=10s, SLOW_POLL_INTERVAL=5min).
Live instances that have custom values set via the options UI are unaffected.

Bump version to 0.3.1b7.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Hammering the proxy every 5 min with up to 9 attempts each makes slot
exhaustion permanent. Catch BleakOutOfConnectionSlotsError, clear the
stored device reference, and switch to xs_poll (1h). The coordinator
stays dormant until the next BLE advertisement triggers a refresh via
_async_specific_device_found, at which point the device lookup
re-populates ble_device and normal polling resumes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
When bluetooth.async_ble_device_from_address returns nothing (dongle
absent from the passive registry), call get_device() for an active scan
before attempting the connection. This mirrors what __init__.py does at
startup and may wake the dongle out of a non-connectable stuck state.
The call is inside the try/except so failures are handled gracefully.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This fixes the longstanding "integration only reads data right after
restart, never during normal polling" symptom on the Leaf, which
manifested as State of Charge updating once at HA startup and then
staying frozen until the next restart even while the car was charging
on the driveway.

Root cause:
The Leaf's VCM ECU at CAN header 797 sleeps within seconds of bus
inactivity. py_nissan_leaf_obd_ble's command loop in api.py sends
0210C0 ("Mystery") as the very first query; if the response has zero
messages, the loop breaks out via:

    if command.name == "unknown" and len(response.messages) == 0:
        break

and async_get_data returns an empty dict. The first 0210C0 effectively
wakes the CAN bus, but the ECU is not responsive in time for that
query's own response. The coordinator sees an empty dict, treats it as
"car probably off", and switches to slow_poll (5 min). The next cycle
re-runs ATZ + full ELM init, which lets the ECU sleep again, so we are
right back to a single failed Mystery and the car is silently
mis-classified as off.

Why the integration restart appeared to "fix" it every time:
async_setup_entry runs async_config_entry_first_refresh, then registers
_async_specific_device_found via bluetooth.async_register_callback. The
register call fires the callback immediately for the currently visible
advertisement, which schedules a second coordinator.async_request_refresh
roughly 50ms after the first refresh's BLE session closes. That
back-to-back second refresh hits the ECU during the wake window left by
the first Mystery and succeeds. Regular polling has no equivalent
trigger, so single Mystery failures are sticky.

The fix:
When async_get_data returns an empty dict, immediately retry within the
same _async_update_data call. The retry's fresh OBD.create + ELM init +
Mystery takes roughly 10 seconds, by which time the ECU has woken up
and responds normally; the rest of the 797 / 743 / 79B sweep then
returns full data. Only after both attempts come back empty do we
conclude the car is off and back off to slow_poll, preserving the
original behavior for the genuinely-off case.

Verified live:
After deploying and restarting HA on a charging Leaf, each 30s fast_poll
cycle logs:
    first attempt returned type=dict len=0
    First attempt empty, retrying immediately to catch ECU wake-up
    retry attempt returned type=dict len=24-28
    Car is on, polling: interval = 0:00:30
and SoC ticks up as expected (87.5 -> 88.8 -> ... during charging).
The retry exists because the Leaf VCM ECU at CAN header 797 sleeps
within seconds of bus inactivity, py_nissan's first Mystery query wakes
the bus but the ECU isn't responsive in time, and async_get_data
returns an empty dict that the coordinator misreads as "car off". The
back-to-back refresh that bluetooth.async_register_callback queues
right after async_config_entry_first_refresh is what made integration
restarts always appear to "fix" the symptom. Capture both findings and
the rationale for retrying within the same _async_update_data call so
future maintainers (including future me) don't have to re-derive any
of this.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Upstream still ships 0.1.1, which swallows BleakOutOfConnectionSlotsError
in elm327.py and has no per-operation timeouts on the BLE client. As a
result, the coordinator's existing `except BleakOutOfConnectionSlotsError`
dormancy branch never fires, and the ESP32 BLE proxy fills its 3 connection
slots until manually power-cycled.

Pin to git+https://github.com/timstoop/py-nissan-leaf-obd-ble@main so the
slot-timeout + propagate-BleakError fix ships to HA immediately. Revert to
a pinned PyPI release once upstream merges the corresponding PR and
publishes a new version.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Temporarily re-add _debug_agent.py from upstream 65f2874 (stripped
pbutterworth workspace path; HA config dir + fallback only). Wires
set_debug_log_config_dir at setup, _run_advert_wakeup for refresh
duration tracing, and log points at enter/address_present/before+
after_async_get_data/fetch_timeout in coordinator._async_update_data.

TODO: remove once 2026-05 stability is confirmed (1 week clean run).

Bump VERSION to 0.3.1+timstoop so logs identify our build.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Increments _consecutive_failures on every TimeoutError, BleakOutOfConnectionSlotsError,
or generic exception. Resets on success. When the count reaches
proxy_unhealthy_threshold (default 5, options-configurable), fires a
nissan_leaf_obd_ble_proxy_unhealthy bus event so HA automations can notify
without taking any automatic recovery action.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Closes #11. Users can now supply custom GATT UUIDs (service, read
characteristic, write characteristic) during the initial integration
setup rather than only via the post-creation options flow.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
feat: add UUID configuration step to initial setup flow
Different Nissan Leaf generations use different OBD PIDs and message
formats. Users can now adapt the integration without modifying the
installed package or waiting for a release.

New files:
- custom_components/nissan_leaf_obd_ble/overrides.py: loads
  overrides.yaml and optionally decoders.py from the integration
  config directory, builds OBDCommand objects and sensor descriptions

Changes:
- __init__.py: calls load_overrides() at setup and passes results to
  the coordinator
- coordinator.py: accepts extra_commands, extra_sensor_descriptions,
  and disabled_commands; passes first and last to async_get_data()
- sensor.py: NissanLeafObdBleSensor now takes a SensorEntityDescription
  directly; async_setup_entry creates entities for user-defined commands
- const.py: adds OVERRIDES_FILE and DECODERS_MODULE_FILE constants
- manifest.json: bump py-nissan-leaf-obd-ble requirement to >=0.1.2,
  version 0.3.1 -> 0.4.0b1
- README.md: documents overrides.yaml format, decoder types, and
  the Python escape hatch

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Add OBD command and decoder override system (v0.4.0b1)
Merges pbutterworth/nissan-leaf-obd-ble@main (v0.4.0b1).

Added from upstream:
- OBD command/decoder override system via overrides.yaml (overrides.py)
- extra_commands/disabled_commands wired through coordinator -> api
- extra_sensor_descriptions for dynamic sensor entities
- UUID configuration step in initial setup flow
- version bump to 0.4.0b1

Kept from our fork:
- coordinator: retry-on-empty logic for ECU wake-up bug
- coordinator: consecutive failure counter + proxy_unhealthy event
- coordinator: fetch-timeout guard + debug agent logging
- manifest.json: py-nissan-leaf-obd-ble pinned to timstoop/main
- version suffix: 0.4.0b1+timstoop

Fixed:
- retry call in coordinator also passes extra_commands/disabled_commands

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Rebase and squash of local fork fixes onto pbutterworth/nissan-leaf-obd-ble
v0.4.0b1. Uses upstream version string (dropping +timstoop suffix).

Local changes included: BLE reconnection fixes, fetch timeout, slow-poll
backoff on errors, cached data on BLE errors, active device scan, consecutive-
failure counter with proxy_unhealthy HA event, NDJSON debug agent, and
dependency pin to timstoop fork for slot-timeout fix.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Debug session 67a564 has served its purpose. Remove _debug_agent.py
and revert __init__.py and coordinator.py to direct async_request_refresh
calls without instrumentation wrappers or agent_log calls.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Brings in upstream v0.4.0b1 (override system, UUID setup flow) and the
BLE reliability fixes squashed on top. The one commit only present here
(refresh BLE device before each connection attempt) is already contained
in the GitHub history.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The requirement pointed at the moving main branch of a GitHub fork, so a
Home Assistant restart could silently pull different code. Pin to the
v0.1.2.post1 tag of the fork now maintained on Forgejo.

The tag is created when tim/py-nissan-leaf-obd-ble!1 is merged; this
integration cannot install its dependency before that.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
pyupgrade v3.22.0, black 26.10.1, codespell v2.4.3, ruff v0.17.0 (repo
moved to astral-sh, hook id ruff-check), mypy v2.4.0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
ruff 0.17 defaults select a much broader rule set than 0.4.8 did, which
would flag existing code (blind-except, import order, pyupgrade). Keep
the E4/E7/E9/F selection the repo was linted with so the bump does not
change what passes; broaden deliberately later.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
codespell 2.4 flags the isort section name in setup.cfg.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Formatting only (line wrapping, quotes, import grouping); the Python
ASTs of all changed modules are identical before and after. Needed so
the ruff-format hook passes at the new rev. Also formats the Python code
block in the README.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The fork's release is versioned 0.2.0 (dependency floors and Python
requirement changed), replacing the earlier 0.1.2.post1 plan.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
tim merged commit 84a9dd6dbb into main 2026-10-12 08:36:20 +00:00
tim deleted branch chore/sync-github-fork 2026-10-12 08:36:21 +00:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
tim/hass-nissan-leaf-obd-ble!1
No description provided.