Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/homey-hw0-values.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tesla-fleet-api": minor
---

Apply the BLE-00 (HW-0) measurements from a real Homey to the Homey Bluetooth adapter. `HOMEY_MAX_WRITE_SIZE` is now `null`, so a frame goes in one write (only a 114-byte frame was measured; pass `maxWriteSize: 20` to chunk again). The adapter sets a 15 s scan bound, `HOMEY_SCAN_TIMEOUT_MS`, because a fresh `discover()` takes about 10 s. `BleTransport` gains an optional `scanTimeoutMs`, which `scan_timeout_ms` overrides.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ class TeslaApp extends Homey.App {
export default TeslaApp;
```

The Homey adapter's defaults are conservative guesses until the BLE-00 probe has run on a Homey. `confirmation` sets how much proof a command needs: `"optimistic"`, `"ack"` (the default) or `"verify"`. New keys are enrolled with `vehicle.pair()`. [docs/bluetooth_vehicles.md](docs/bluetooth_vehicles.md) has every option and each adapter's limits.
The Homey adapter's defaults come from a BLE-00 run on a real Homey (one write per frame, a 15 s scan bound). `confirmation` sets how much proof a command needs: `"optimistic"`, `"ack"` (the default) or `"verify"`. New keys are enrolled with `vehicle.pair()`. [docs/bluetooth_vehicles.md](docs/bluetooth_vehicles.md) has every option and each adapter's limits.

## Local Powerwall

Expand Down
12 changes: 6 additions & 6 deletions docs/bluetooth_vehicles.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,18 +45,18 @@ const vehicle = new TeslaBluetooth({ privateKey }).vehicles.createBluetooth(vin,
});
```

The app needs the `homey:wireless:ble` permission. Options: `maxWriteSize`, bytes per write, default 20. `null` sends a whole frame in one write.
The app needs the `homey:wireless:ble` permission. Options: `maxWriteSize`, bytes per write, default `null`: a whole frame in one write. Pass `20` to chunk at the ATT minimum.

Limits:

- **The BLE-00 probe has not run on a Homey, so these defaults are conservative guesses.** Whether the vehicle's name is visible to `discover()` at all is unknown. If it is not, name matching cannot work, and you pass `device: { id: <peripheral uuid> }` yourself. Every value the probe may change is a constant in `src/bluetooth/adapters/homey.ts` that names its probe step.
- The scan window is about 5 s and fixed, and `scan` ignores `timeoutMs`.
- **Measured on a real Homey (BLE-00, HW-0, 2026-11-03).** The vehicle's name is visible to `discover()`, so name matching works. A 114-byte frame goes in one write. A signed frame of about 200 bytes is not yet measured: HW-5 confirms it.
- The scan window is about 10 s and fixed, and `scan` ignores `timeoutMs`. The adapter sets `scanTimeoutMs` to 15 s, which `scan_timeout_ms` overrides.
- `discover()` results stay cached for at least 30 s, so a fast retry sees old data. Treat repeated connect failures as a reason to wait, not to retry.
- The MTU is hidden, so a signed frame takes about 10 writes at 20 bytes.
- The MTU is hidden, but a frame goes in one write.
- `isConnected` can stay true after a silent drop, and the `disconnect` event is not guaranteed. So `listen_connection_status(false)` can be as late as the next operation to time out. `true` is reliable.
- Homey offers no connect, write or read timeout. The library adds them.
- Range is the largest limit, and nothing can fix it in software. A Homey sits indoors. Expect "in range" to mean parked close to it.
- `HOMEY_VEHICLE_OPTIONS` (one attempt, 4 s) suits a Flow action. Elsewhere, keep the library's defaults until the probe has measured Homey's connect time, as a link slower than 4 s never lands.
- `HOMEY_VEHICLE_OPTIONS` (one attempt, 4 s) suits a Flow action. Connect time measured p50 0.4 s and max 1.4 s over 10 connects, so these options suit any caller.

### noble

Expand Down Expand Up @@ -110,7 +110,7 @@ Implement `BleTransport` from `tesla-fleet-api/bluetooth`. `src/bluetooth/transp
| `wake_if_asleep` | `true` | Wake a sleeping car for an infotainment command, instead of raising. |
| `max_connect_attempts` | `3` | Attempts per connect. |
| `connect_timeout_ms` | `20000` | One attempt. |
| `scan_timeout_ms` | `10000` | One scan. It must outlast the backend's window. |
| `scan_timeout_ms` | `10000` (Homey: `15000`) | One scan. It must outlast the backend's window. |
| `wake_probe_timeout_ms` | `1000` | The reply wait of one infotainment readiness probe. |

## Methods
Expand Down
24 changes: 17 additions & 7 deletions src/bluetooth/adapters/homey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,28 @@
// file loads anywhere. It follows what the BLE-00 probe app does on a real Homey
// (`probe/ble-hw0/app.js` in Teslemetry/homey), not only what the SDK types allow:
// UUIDs in compact form, characteristics discovered with no filter and matched by
// normalized UUID. No run of that probe has reported yet, so every value it may
// change is a named constant below, with its step.
// normalized UUID. HW-0 ran it on a Homey Pro on 2026-11-03, and
// its measured values are the named constants below.
import { withTimeout } from "../async.js";
import { APPEARANCE_UUID, DEFAULT_CONNECT_TIMEOUT_MS, GENERIC_ACCESS_UUID, NAME_UUID, SERVICE_UUID, VEHICLE_NOTIFY_UUID, VEHICLE_WRITE_UUID, VERSION_UUID } from "../constants.js";
import { BleCharacteristic, BleConnection, BleDeviceRef, BleLinkHandlers, BleNotSubmittedError, BleScanOptions, BleTransport } from "../transport.js";
import { compactUuid, LinkClaims, quietly } from "./shared.js";

/**
* Bytes per write. Homey hides the MTU, so this is the ATT minimum, the one size
* sure to work. BLE-00 step 6: if a whole 114-byte frame gets a reply, this can
* become `null`. Otherwise step 7 keeps it, or the MTU estimate less 3 if larger.
* Bytes per write: `null`, a whole frame in one write. Homey hides the MTU.
* BLE-00 (HW-0, 2026-11-03) measured a 114-byte frame in one write at 232 ms to
* a reply, against 562 ms for 6 writes of 20 bytes. Only 114 bytes were tried:
* a signed frame (about 200 bytes) is confirmed by HW-5. Pass `maxWriteSize: 20`
* to `HomeyBleTransport` to chunk at the ATT minimum if that run shows a failure.
*/
export const HOMEY_MAX_WRITE_SIZE = 20;
export const HOMEY_MAX_WRITE_SIZE = null;

/**
* Bound on one scan. `discover()` takes a fixed 10.04 s when it is not cached
* (HW-0), so the library's 10 s default would time out about 40 ms early.
* `VehicleBluetooth` uses this when `scan_timeout_ms` is not set.
*/
export const HOMEY_SCAN_TIMEOUT_MS = 15_000;

/**
* For `connect_timeout_ms` and `max_connect_attempts`, not applied by this
Expand Down Expand Up @@ -72,7 +81,7 @@ export interface HomeyAdvertisementLike {

/** What this adapter needs of `this.homey.ble`. */
export interface HomeyBleManagerLike {
/** About 5 s, fixed. Called with no filter, because the vehicle advertises no service. */
/** About 10 s, fixed, when not cached (BLE-00 HW-0). Called with no filter, because the vehicle advertises no service. */
discover(): Promise<HomeyAdvertisementLike[]>;
find(uuid: string): Promise<HomeyAdvertisementLike>;
}
Expand Down Expand Up @@ -211,6 +220,7 @@ class HomeyConnection implements BleConnection {
export class HomeyBleTransport implements BleTransport {
private readonly maxWriteSize: number | null;
private readonly claims = new LinkClaims<HomeyConnection>();
readonly scanTimeoutMs = HOMEY_SCAN_TIMEOUT_MS;

/** @param ble `this.homey.ble`. The app needs the `homey:wireless:ble` permission. */
constructor(
Expand Down
2 changes: 1 addition & 1 deletion src/bluetooth/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export const DEFAULT_PAIR_POLL_INTERVAL_MS = 5000;
export const DEFAULT_CONNECT_ATTEMPTS = 3;
/** One connect attempt. Python takes the same figure from `bleak-retry-connector`. */
export const DEFAULT_CONNECT_TIMEOUT_MS = 20_000;
/** One scan. It must outlast the backend's window, which Homey fixes at about 5 s. */
/** One scan. It must outlast the backend's window, which Homey fixes at about 10 s: its adapter sets its own bound. */
export const DEFAULT_SCAN_TIMEOUT_MS = 10_000;
/** Bound on tearing down a link: the failure behind it is what gets reported. */
export const LINK_TEARDOWN_TIMEOUT_MS = 5000;
Expand Down
2 changes: 2 additions & 0 deletions src/bluetooth/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ export interface BleScanOptions {
}

export interface BleTransport {
/** How long one scan needs, for a backend with a fixed window. `scan_timeout_ms` overrides it. */
readonly scanTimeoutMs?: number;
/** Active, unfiltered scan. Resolves once a match is found, or when the scan ends with what was seen. */
scan(options: BleScanOptions): Promise<BleDeviceRef[]>;
/** Connect, discover, subscribe to notify. Resolves only when notifications are live. */
Expand Down
2 changes: 1 addition & 1 deletion src/bluetooth/vehiclebluetooth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ export default class VehicleBluetooth extends BroadcastListeners {
this.wake_if_asleep = options.wake_if_asleep ?? true;
this.maxConnectAttempts = options.max_connect_attempts ?? DEFAULT_CONNECT_ATTEMPTS;
this.connectTimeoutMs = options.connect_timeout_ms ?? DEFAULT_CONNECT_TIMEOUT_MS;
this.scanTimeoutMs = options.scan_timeout_ms ?? DEFAULT_SCAN_TIMEOUT_MS;
this.scanTimeoutMs = options.scan_timeout_ms ?? options.transport.scanTimeoutMs ?? DEFAULT_SCAN_TIMEOUT_MS;
this.wakeProbeTimeoutMs = options.wake_probe_timeout_ms ?? DEFAULT_WAKE_PROBE_TIMEOUT_MS;
if (this.wakeProbeTimeoutMs <= 0) {
throw new RangeError("wake_probe_timeout_ms must be greater than 0.");
Expand Down
19 changes: 15 additions & 4 deletions test/bluetooth/adapters/homey.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it, vi } from "vitest";
import { HOMEY_MAX_WRITE_SIZE, HOMEY_SETUP_TIMEOUT_MS, HOMEY_UNSUBSCRIBE_TIMEOUT_MS, HomeyBleTransport, HomeyPeripheralLike } from "../../../src/bluetooth/adapters/homey.js";
import { HOMEY_MAX_WRITE_SIZE, HOMEY_SCAN_TIMEOUT_MS, HOMEY_SETUP_TIMEOUT_MS, HOMEY_UNSUBSCRIBE_TIMEOUT_MS, HomeyBleTransport, HomeyPeripheralLike } from "../../../src/bluetooth/adapters/homey.js";
import { BleNotSubmittedError } from "../../../src/bluetooth/transport.js";
import { flush, noHandlers, STUB_NAME, stubHomey } from "../../helpers/stubbackends.js";

Expand Down Expand Up @@ -48,18 +48,29 @@ describe("HomeyBleTransport", () => {
expect(link.calls.find((call) => call.name === "characteristics")?.args).toEqual([]);
});

it("defaults to 20 bytes per write", async () => {
it("defaults to one write per frame, as measured by BLE-00 HW-0", async () => {
const { transport, device } = subject();
expect(HOMEY_MAX_WRITE_SIZE).toBe(20);
expect(HOMEY_MAX_WRITE_SIZE).toBeNull();
expect((await transport.connect(device, noHandlers())).maxWriteSize).toBeNull();
});

it("keeps 20-byte chunking available", async () => {
const { transport, device } = subject({ maxWriteSize: 20 });
expect((await transport.connect(device, noHandlers())).maxWriteSize).toBe(20);
});

it("bounds a scan at 15 s, above the fixed 10 s window", () => {
const { transport } = subject();
expect(HOMEY_SCAN_TIMEOUT_MS).toBe(15_000);
expect(transport.scanTimeoutMs).toBe(HOMEY_SCAN_TIMEOUT_MS);
});

it("takes a larger write size", async () => {
const { transport, device } = subject({ maxWriteSize: 100 });
expect((await transport.connect(device, noHandlers())).maxWriteSize).toBe(100);
});

it("keeps null, which BLE-00 step 6 may choose, instead of falling back to 20", async () => {
it("keeps null instead of falling back to the default", async () => {
const { transport, device } = subject({ maxWriteSize: null });
expect((await transport.connect(device, noHandlers())).maxWriteSize).toBeNull();
});
Expand Down
39 changes: 39 additions & 0 deletions test/bluetooth/vehiclebluetooth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,45 @@ describe("a round trip", () => {
expect(link.writes).toHaveLength(link.frames.length);
});

it("keeps a reply that arrives before write() resolves, as Homey's did by 93 ms", async () => {
const { link, tesla } = bleHarness();
// The car answers at once, but the backend's write only resolves 200 ms later.
const slow: BleTransport = {
scan: (options) => link.scan(options),
async connect(device, handlers) {
const connection = await link.connect(device, handlers);
return {
get isConnected() {
return connection.isConnected;
},
maxWriteSize: null,
async write(data) {
await connection.write(data);
await new Promise((resolve) => setTimeout(resolve, 200));
},
read: (characteristic) => connection.read(characteristic),
disconnect: () => connection.disconnect(),
};
},
};
const early = new TestVehicle(tesla.vehicles, VIN, { keepalive_interval_ms: null, transport: slow });
await finish(early.connect());
// The wait is shorter than the write, so only a reply held from before the write resolves can answer.
const reply = await finish(early.send(early.sessionRequest(VCSEC), "session_info", { timeoutMs: 50 }));
expect(reply.sessionInfo).toBeDefined();
await finish(early.disconnect());
});

it("scans for the transport's own bound when scan_timeout_ms is not set", async () => {
const { link, tesla } = bleHarness();
link.scanWindowMs = 12_000;
const transport = Object.assign(Object.create(link) as FakeBleLink, { scanTimeoutMs: 15_000 });
const long = new TestVehicle(tesla.vehicles, VIN, { keepalive_interval_ms: null, transport });
await expect(finish(long.find_vehicle())).resolves.toBeDefined();
const short = new TestVehicle(tesla.vehicles, VIN, { keepalive_interval_ms: null, transport: link });
await expect(finish(short.find_vehicle())).rejects.toThrow();
});

it("never interleaves the chunks of commands on both domains", async () => {
const { vehicle, link } = bleHarness({ mtu: 23 });
link.writeDelayMs = 5;
Expand Down
2 changes: 1 addition & 1 deletion test/consumers/cjs.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const { NobleBleTransport } = require("tesla-fleet-api/bluetooth/noble");
const { EsphomeBleTransport } = require("tesla-fleet-api/bluetooth/esphome");
assert.equal(typeof require("tesla-fleet-api/powerwall").PowerwallClient, "function");
assert.equal(typeof HomeyBleTransport, "function");
assert.equal(HOMEY_MAX_WRITE_SIZE, 20);
assert.equal(HOMEY_MAX_WRITE_SIZE, null);
(async () => {
await assert.rejects(new NobleBleTransport().scan({ timeoutMs: 1000 }), /@stoprocent\/noble/);
await assert.rejects(new EsphomeBleTransport({ host: "proxy.test" }).scan({ timeoutMs: 1000 }), /@2colors\/esphome-native-api/);
Expand Down
2 changes: 1 addition & 1 deletion test/consumers/esm.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { PowerwallClient } from "tesla-fleet-api/powerwall";
// Each adapter must load with no backend installed, and only fail once it is used.
assert.equal(typeof PowerwallClient, "function");
assert.equal(typeof HomeyBleTransport, "function");
assert.equal(HOMEY_MAX_WRITE_SIZE, 20);
assert.equal(HOMEY_MAX_WRITE_SIZE, null);
await assert.rejects(new NobleBleTransport().scan({ timeoutMs: 1000 }), /@stoprocent\/noble/);
await assert.rejects(new EsphomeBleTransport({ host: "proxy.test" }).scan({ timeoutMs: 1000 }), /@2colors\/esphome-native-api/);

Expand Down
4 changes: 4 additions & 0 deletions test/helpers/blevehicle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ export class TestVehicle extends VehicleBluetooth {
return this._send(msg, requires, options);
}

sessionRequest(domain: Domain): RoutableMessage {
return this.sessionInfoRequest(domain);
}

session(domain: Domain) {
return this.sessionFor(domain);
}
Expand Down
Loading