openbyd 0.0.0-stage → 0.1.2
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.
- package/README.md +147 -2
- package/dist/client.d.ts +168 -0
- package/dist/client.js +374 -0
- package/dist/functions.d.ts +32 -0
- package/dist/functions.js +48 -0
- package/dist/generated/errors.d.ts +114 -0
- package/dist/generated/errors.js +167 -0
- package/dist/generated/methods.d.ts +461 -0
- package/dist/generated/methods.js +926 -0
- package/dist/generated/models.d.ts +1361 -0
- package/dist/generated/models.js +191 -0
- package/dist/generated/shapes.d.ts +45 -0
- package/dist/generated/shapes.js +164 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +51 -0
- package/dist/native.d.ts +32 -0
- package/dist/native.js +53 -0
- package/dist/testing.d.ts +127 -0
- package/dist/testing.js +140 -0
- package/dist/wire.d.ts +32 -0
- package/dist/wire.js +130 -0
- package/package.json +53 -4
package/README.md
CHANGED
|
@@ -1,3 +1,148 @@
|
|
|
1
|
-
#
|
|
1
|
+
# openbyd for Node.js
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An unofficial client for the BYD overseas app API: [pyBYD](https://github.com/jkaberg/pyBYD)'s `BydClient` and `BydCar` for TypeScript and JavaScript, on openbyd's Rust core. Every request it builds and every reply it parses is compared with pyBYD in the repository's tests.
|
|
4
|
+
|
|
5
|
+
This project is not affiliated with, endorsed by or supported by BYD. It has not yet been run against BYD's live service; see the [status](../../README.md#status) of the whole project.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install openbyd
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
For Node.js 20 and later, on Windows (x64), Linux (x64 and arm64, glibc and musl) and macOS (arm64 and x64).
|
|
12
|
+
|
|
13
|
+
## Use it
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { Client } from "openbyd";
|
|
17
|
+
|
|
18
|
+
const client = new Client({ username: "you@example.com", password: "...", controlPin: "123456" });
|
|
19
|
+
try {
|
|
20
|
+
await client.login();
|
|
21
|
+
for (const vehicle of await client.getVehicles()) {
|
|
22
|
+
const realtime = await client.getVehicleRealtime(vehicle.vin);
|
|
23
|
+
console.log(vehicle.vin, realtime.elec_percent);
|
|
24
|
+
}
|
|
25
|
+
} finally {
|
|
26
|
+
client.close();
|
|
27
|
+
}
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
A car, with its state and its commands by feature:
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
const car = await client.getCar(vin, { onStateChanged: (vin, state) => console.log(state.realtime?.elec_percent) });
|
|
34
|
+
await client.verifyCommandAccess(vin);
|
|
35
|
+
await car.updateRealtime();
|
|
36
|
+
if (car.lock.available) await car.lock.lock();
|
|
37
|
+
await car.hvac.start({ temperature: 21, duration: 20 });
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Methods are pyBYD's, in camelCase: `get_vehicle_realtime` is `getVehicleRealtime`. One that waits on the network returns a promise; one that answers at once (`exportSession()`, `commandsEnabled`, `car.state`) returns its value. Optional arguments are an options object: `getVehicleRealtime(vin, { pollAttempts: 3 })`.
|
|
41
|
+
|
|
42
|
+
## Types
|
|
43
|
+
|
|
44
|
+
Everything is typed, and the types are generated from pyBYD's own models, so they follow upstream.
|
|
45
|
+
|
|
46
|
+
- **What you get back is pyBYD's JSON, untouched**: a model is exactly `model_dump(mode="json")`, so its fields keep pyBYD's snake_case names (`realtime.elec_percent`) and are read-only. A model's `raw` is the reply it was parsed from.
|
|
47
|
+
- **What you pass is camelCase**, like the rest of your code: the config (`controlPin`), options (`pollAttempts`) and parameter objects (`startClimate(vin, { temperature: 21, timeSpan: 2 })`).
|
|
48
|
+
- **Enums are their values**: `vehicle.energy_type` is `-1 | 0 | 1 | 2`, and `EnergyType.EV` is `0`. An argument that is not one of an enum's values does not compile.
|
|
49
|
+
- **A float JSON cannot hold** (NaN, an infinity) comes back as that number, only in fields that are floats.
|
|
50
|
+
|
|
51
|
+
The repository's tests check every model dump recorded from pyBYD (more than 11,000) against these types.
|
|
52
|
+
|
|
53
|
+
`parseModel("GpsInfo", raw)` parses a raw payload (an MQTT event's data, say) as one of pyBYD's models. `encodeEnvelope` and `decodeEnvelope` are the envelope cipher.
|
|
54
|
+
|
|
55
|
+
## Errors
|
|
56
|
+
|
|
57
|
+
Failures are pyBYD's exception classes, under one root:
|
|
58
|
+
|
|
59
|
+
```
|
|
60
|
+
OpenBydError .kind: the Python class name
|
|
61
|
+
├── BydError
|
|
62
|
+
│ ├── BydCryptoError ── BangcleError ── BangcleTableLoadError
|
|
63
|
+
│ ├── BydTransportError .statusCode, .endpoint
|
|
64
|
+
│ └── BydApiError .code, .endpoint
|
|
65
|
+
│ ├── BydAuthenticationError ── BydSessionExpiredError
|
|
66
|
+
│ ├── BydRemoteControlError
|
|
67
|
+
│ ├── BydControlPasswordError
|
|
68
|
+
│ ├── BydEndpointNotSupportedError
|
|
69
|
+
│ ├── BydDataUnavailableError
|
|
70
|
+
│ ├── BydRateLimitError
|
|
71
|
+
│ └── BydServiceBusyError
|
|
72
|
+
├── DataError a value could not be used (ValueError, TypeError, ...)
|
|
73
|
+
│ └── ValidationError .errorType, .loc
|
|
74
|
+
└── CancelledError a wait for a push was cut short
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
try {
|
|
79
|
+
await client.lock(vin);
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (error instanceof BydControlPasswordError) console.log("wrong PIN", error.code);
|
|
82
|
+
else throw error;
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Callbacks
|
|
87
|
+
|
|
88
|
+
Give them when the client is made. They run on JavaScript's thread.
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
const client = new Client({
|
|
92
|
+
username: "you@example.com",
|
|
93
|
+
password: "...",
|
|
94
|
+
onVehicleInfo: (vin, data) => console.log(vin, data.elec_percent),
|
|
95
|
+
onCommandAck: (ack) => console.log(ack.request_serial, ack.success),
|
|
96
|
+
gatePolicy: (vin, verdict) => verdict.supported || verdict.reason === "function_no_missing",
|
|
97
|
+
relogin: async () => loadSessionFromSomewhere(),
|
|
98
|
+
});
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
- `onVehicleInfo`, `onMqttEvent`, `onCommandAck`, `onCommandLifecycle`, `onMqttConnect`, `requestObserver`: pyBYD's callbacks, and one per request sent.
|
|
102
|
+
- `gatePolicy`: `"strict"` (pyBYD's), `"allow_missing_data"`, or a function deciding from the command gate's verdict.
|
|
103
|
+
- `pinResolver`: replaces pyBYD's rule for the `commandPwd` sent.
|
|
104
|
+
- `relogin`: `"password"` (pyBYD's), `"never"`, or a function returning a saved session.
|
|
105
|
+
- `commandAckTtlSeconds`, `commandRetries`.
|
|
106
|
+
|
|
107
|
+
A callback that throws does not affect the client. The failure goes to `onCallbackError(name, error)`, or is emitted as a process warning when there is none.
|
|
108
|
+
|
|
109
|
+
## Lifetime
|
|
110
|
+
|
|
111
|
+
A client costs a few small allocations: every client in the process shares one connection pool and one Rust runtime.
|
|
112
|
+
|
|
113
|
+
`close()` closes the cars, stops MQTT and makes later calls throw `BydError`; `start()` opens it again. `using client = new Client(...)` closes it at the end of the block.
|
|
114
|
+
|
|
115
|
+
A client with push callbacks (or a car with `onStateChanged`) keeps the process alive until it is closed, as an open socket would: it is waiting for pushes. A client without them does not.
|
|
116
|
+
|
|
117
|
+
Sessions can be saved and resumed without a password login: `client.exportSession()` gives the tokens, `Client.fromSession(tokens, options)` resumes them.
|
|
118
|
+
|
|
119
|
+
## The native add-on
|
|
120
|
+
|
|
121
|
+
The client is compiled code. Each platform's add-on is a package of its own, `@openbyd/<platform>` (`@openbyd/win32-x64-msvc`, `@openbyd/linux-x64-gnu`, `@openbyd/linux-arm64-musl`, `@openbyd/darwin-arm64`, ...), which `openbyd` lists as an optional dependency: npm installs the one that fits the machine. An install with `--omit=optional` or `--no-optional` leaves it out, and the package then fails to load, saying which one is missing.
|
|
122
|
+
|
|
123
|
+
On another platform, or to run your own build, put the add-on at `native/openbyd.<platform>.node` inside the package ([Build and test](#build-and-test)); that file is looked for first.
|
|
124
|
+
|
|
125
|
+
## Testing your own code
|
|
126
|
+
|
|
127
|
+
`openbyd/testing` has a fake BYD server that speaks the real wire protocol and an MQTT test broker. They need an add-on built with `--testing`; `hasTesting` tells whether the one loaded has them.
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
import { FakeServer } from "openbyd/testing";
|
|
131
|
+
|
|
132
|
+
using server = new FakeServer([{ username: "user@example.com", password: "secret" }]);
|
|
133
|
+
server.reply("/control/getStatusNow", { data: { acSwitch: 1 } });
|
|
134
|
+
const client = new Client({ username: "user@example.com", password: "secret", baseUrl: server.url, mqttEnabled: false });
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
## Build and test
|
|
138
|
+
|
|
139
|
+
You need a Rust toolchain and Node.js 22 or later (the tests use its test runner).
|
|
140
|
+
|
|
141
|
+
```sh
|
|
142
|
+
cd bindings/node
|
|
143
|
+
npm install
|
|
144
|
+
npm run build:native -- --debug --testing # the add-on, with the fake server; leave out --debug for a release build
|
|
145
|
+
npm test # compiles the package and runs its tests
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
`src/generated` is written by `python bindings/generate.py` from `bindings/spec.py` and pyBYD's models; see [the bindings' README](../README.md).
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The client: pyBYD's `BydClient` with a Rust core.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import { Client } from "openbyd";
|
|
6
|
+
*
|
|
7
|
+
* const client = new Client({ username: "user@example.com", password: "secret", controlPin: "123456" });
|
|
8
|
+
* try {
|
|
9
|
+
* await client.login();
|
|
10
|
+
* for (const vehicle of await client.getVehicles()) {
|
|
11
|
+
* const realtime = await client.getVehicleRealtime(vehicle.vin);
|
|
12
|
+
* console.log(vehicle.vin, realtime.elec_percent);
|
|
13
|
+
* }
|
|
14
|
+
* } finally {
|
|
15
|
+
* client.close();
|
|
16
|
+
* }
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* Methods are pyBYD's, in camelCase. What they return is exactly pyBYD's
|
|
20
|
+
* `model_dump(mode="json")`, so fields keep pyBYD's snake_case names; what
|
|
21
|
+
* you pass (the config, options, parameter objects) is camelCase. Failures
|
|
22
|
+
* are thrown as pyBYD's exception classes (`BydApiError` and its subclasses,
|
|
23
|
+
* with `code` and `endpoint`).
|
|
24
|
+
*
|
|
25
|
+
* Every client in a process shares one HTTP connection pool and one Rust
|
|
26
|
+
* runtime, so a client is cheap: thousands can be created.
|
|
27
|
+
*
|
|
28
|
+
* Callbacks always run on JavaScript's thread. One that throws is reported
|
|
29
|
+
* to `onCallbackError` (by default as a process warning) and does not affect
|
|
30
|
+
* the client.
|
|
31
|
+
*/
|
|
32
|
+
import { CarMethods, ClientMethods } from "./generated/methods.js";
|
|
33
|
+
import type { BydConfig, CommandAckEvent, CommandGateVerdict, CommandLifecycleEvent, JsonObject, RequestRecord, SessionTokens, VehicleRealtimeData, VehicleSnapshot } from "./generated/models.js";
|
|
34
|
+
/**
|
|
35
|
+
* Whether a command is sent, given the command gate's verdict:
|
|
36
|
+
*
|
|
37
|
+
* - `"strict"` (the default, pyBYD's): only when the gate says supported.
|
|
38
|
+
* - `"allow_missing_data"`: also when the car's capability data is
|
|
39
|
+
* incomplete (the reasons `function_no_missing` and `learn_info_missing`).
|
|
40
|
+
* - a function deciding from the verdict. If it throws, the verdict stands.
|
|
41
|
+
*/
|
|
42
|
+
export type GatePolicy = "strict" | "allow_missing_data" | ((vin: string, verdict: CommandGateVerdict) => boolean | Promise<boolean>);
|
|
43
|
+
/**
|
|
44
|
+
* Returns the `commandPwd` to send (empty for none) for the PIN a call was
|
|
45
|
+
* given and the config's `controlPin`, in place of pyBYD's rule (32 hex
|
|
46
|
+
* digits are a digest, anything else is hashed).
|
|
47
|
+
*/
|
|
48
|
+
export type PinResolver = (commandPwd: string | null, controlPin: string | null) => string | Promise<string>;
|
|
49
|
+
/**
|
|
50
|
+
* What to do when a new session is needed:
|
|
51
|
+
*
|
|
52
|
+
* - `"password"` (the default, pyBYD's): log in again.
|
|
53
|
+
* - `"never"`: fail with `BydSessionExpiredError` (code `relogin_disabled`).
|
|
54
|
+
* - a function returning a session (as `exportSession` gives it). What it
|
|
55
|
+
* throws is what the call throws.
|
|
56
|
+
*/
|
|
57
|
+
export type ReloginPolicy = "password" | "never" | (() => SessionTokens | Promise<SessionTokens>);
|
|
58
|
+
/** The options of a client besides pyBYD's config. */
|
|
59
|
+
export interface ClientHooks {
|
|
60
|
+
/** Every MQTT `vehicleInfo` push, parsed. */
|
|
61
|
+
onVehicleInfo?: ((vin: string, data: VehicleRealtimeData) => void) | undefined;
|
|
62
|
+
/** Every MQTT event that names a VIN, with its raw `respondData`. */
|
|
63
|
+
onMqttEvent?: ((event: string, vin: string, data: JsonObject) => void) | undefined;
|
|
64
|
+
/** Every remote-control acknowledgement. */
|
|
65
|
+
onCommandAck?: ((ack: CommandAckEvent) => void) | undefined;
|
|
66
|
+
/** A command was registered, matched, expired or acknowledged without a match. */
|
|
67
|
+
onCommandLifecycle?: ((event: CommandLifecycleEvent) => void) | undefined;
|
|
68
|
+
/** Every accepted MQTT connection. */
|
|
69
|
+
onMqttConnect?: (() => void) | undefined;
|
|
70
|
+
/** Every request the client sends, with its outcome and duration. */
|
|
71
|
+
requestObserver?: ((record: RequestRecord) => void) | undefined;
|
|
72
|
+
/** How long a command waits for its acknowledgement, in seconds. Default `300`. */
|
|
73
|
+
commandAckTtlSeconds?: number | undefined;
|
|
74
|
+
/** Attempts per remote command. Default `3`. */
|
|
75
|
+
commandRetries?: number | undefined;
|
|
76
|
+
/** Whether a command is sent, given the command gate's verdict. Default `"strict"`. */
|
|
77
|
+
gatePolicy?: GatePolicy | undefined;
|
|
78
|
+
/** Replaces pyBYD's rule for the `commandPwd` sent. */
|
|
79
|
+
pinResolver?: PinResolver | undefined;
|
|
80
|
+
/** What to do when a new session is needed. Default `"password"`. */
|
|
81
|
+
relogin?: ReloginPolicy | undefined;
|
|
82
|
+
/**
|
|
83
|
+
* Hears about a callback that threw: its option's name and what it threw.
|
|
84
|
+
* By default the failure is emitted as a process warning.
|
|
85
|
+
*/
|
|
86
|
+
onCallbackError?: ((callback: string, error: unknown) => void) | undefined;
|
|
87
|
+
}
|
|
88
|
+
/** What a client is made from: pyBYD's `BydConfig` fields in camelCase, and openbyd's options. */
|
|
89
|
+
export interface ClientOptions extends BydConfig, ClientHooks {
|
|
90
|
+
}
|
|
91
|
+
/** The options of {@link Client.getCar}. */
|
|
92
|
+
export interface GetCarOptions {
|
|
93
|
+
/** The vehicle's raw payload; the vehicle list is fetched when not given. */
|
|
94
|
+
vehicle?: JsonObject | undefined;
|
|
95
|
+
/** How long a command's projections stay active, in seconds. Default `30`. */
|
|
96
|
+
projectionTtl?: number | undefined;
|
|
97
|
+
/** Called after every change of the car's state. */
|
|
98
|
+
onStateChanged?: ((vin: string, state: VehicleSnapshot) => void) | undefined;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* One vehicle: pyBYD's `BydCar`. Get one from {@link Client.getCar}.
|
|
102
|
+
*
|
|
103
|
+
* It holds the vehicle's merged state and offers its commands by feature:
|
|
104
|
+
*
|
|
105
|
+
* ```ts
|
|
106
|
+
* const car = await client.getCar(vin);
|
|
107
|
+
* await car.updateRealtime();
|
|
108
|
+
* await car.lock.lock();
|
|
109
|
+
* await car.hvac.start({ temperature: 21, duration: 20 });
|
|
110
|
+
* car.state.realtime?.left_front_door_lock; // 2 (locked), projected
|
|
111
|
+
* ```
|
|
112
|
+
*
|
|
113
|
+
* A command lays the state it expects over the current state at once (a
|
|
114
|
+
* projection) and rolls it back when it fails; the next push or update that
|
|
115
|
+
* agrees confirms it. Each feature tells whether the car supports it; a
|
|
116
|
+
* command the car does not support throws `BydEndpointNotSupportedError`
|
|
117
|
+
* without sending anything. A car whose client is closed fails its calls
|
|
118
|
+
* with `BydError`.
|
|
119
|
+
*/
|
|
120
|
+
export declare class Car extends CarMethods {
|
|
121
|
+
/** The vehicle identification number. */
|
|
122
|
+
readonly vin: string;
|
|
123
|
+
}
|
|
124
|
+
/** The async client for the BYD API: pyBYD's `BydClient`. See the module's documentation. */
|
|
125
|
+
export declare class Client extends ClientMethods {
|
|
126
|
+
#private;
|
|
127
|
+
/**
|
|
128
|
+
* A client for an account, ready to use. A bad config value throws
|
|
129
|
+
* `ValidationError`.
|
|
130
|
+
*
|
|
131
|
+
* A client with push listeners (`onVehicleInfo`, `onMqttEvent`,
|
|
132
|
+
* `onCommandAck`, `onCommandLifecycle`, `onMqttConnect`, or a car's
|
|
133
|
+
* `onStateChanged`) keeps the process alive until {@link close}, as an
|
|
134
|
+
* open socket would.
|
|
135
|
+
*/
|
|
136
|
+
constructor(options: ClientOptions);
|
|
137
|
+
/**
|
|
138
|
+
* A client that resumes a session from {@link exportSession}, without a
|
|
139
|
+
* password login. Without a `password` it never logs in by itself
|
|
140
|
+
* (`relogin` defaults to `"never"`): when the session expires, calls throw
|
|
141
|
+
* `BydSessionExpiredError` until the application imports a new one.
|
|
142
|
+
*/
|
|
143
|
+
static fromSession(session: SessionTokens, options: Omit<ClientOptions, "password"> & {
|
|
144
|
+
password?: string | undefined;
|
|
145
|
+
}): Promise<Client>;
|
|
146
|
+
/** Whether {@link close} was called and {@link start} was not called since. */
|
|
147
|
+
get closed(): boolean;
|
|
148
|
+
/** Opens the client again after {@link close} (pyBYD's `async_start`). A new client is open already. */
|
|
149
|
+
start(): void;
|
|
150
|
+
/**
|
|
151
|
+
* Closes the cars, stops MQTT and makes later calls fail with `BydError`
|
|
152
|
+
* (pyBYD's `async_close`). Calls already in flight finish; one waiting
|
|
153
|
+
* for an MQTT push stops waiting with `CancelledError`.
|
|
154
|
+
*/
|
|
155
|
+
close(): void;
|
|
156
|
+
/** Closes the client: `using client = new Client(...)`. */
|
|
157
|
+
[Symbol.dispose](): void;
|
|
158
|
+
/**
|
|
159
|
+
* The {@link Car} of a vehicle, built once and kept.
|
|
160
|
+
*
|
|
161
|
+
* As pyBYD: a kept car is returned as it is, whatever the options.
|
|
162
|
+
* Otherwise the vehicle list is fetched unless `vehicle` is given, then
|
|
163
|
+
* the capabilities.
|
|
164
|
+
*
|
|
165
|
+
* @param vin - The vehicle identification number.
|
|
166
|
+
*/
|
|
167
|
+
getCar(vin: string, options?: GetCarOptions): Promise<Car>;
|
|
168
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* The client: pyBYD's `BydClient` with a Rust core.
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { Client } from "openbyd";
|
|
7
|
+
*
|
|
8
|
+
* const client = new Client({ username: "user@example.com", password: "secret", controlPin: "123456" });
|
|
9
|
+
* try {
|
|
10
|
+
* await client.login();
|
|
11
|
+
* for (const vehicle of await client.getVehicles()) {
|
|
12
|
+
* const realtime = await client.getVehicleRealtime(vehicle.vin);
|
|
13
|
+
* console.log(vehicle.vin, realtime.elec_percent);
|
|
14
|
+
* }
|
|
15
|
+
* } finally {
|
|
16
|
+
* client.close();
|
|
17
|
+
* }
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* Methods are pyBYD's, in camelCase. What they return is exactly pyBYD's
|
|
21
|
+
* `model_dump(mode="json")`, so fields keep pyBYD's snake_case names; what
|
|
22
|
+
* you pass (the config, options, parameter objects) is camelCase. Failures
|
|
23
|
+
* are thrown as pyBYD's exception classes (`BydApiError` and its subclasses,
|
|
24
|
+
* with `code` and `endpoint`).
|
|
25
|
+
*
|
|
26
|
+
* Every client in a process shares one HTTP connection pool and one Rust
|
|
27
|
+
* runtime, so a client is cheap: thousands can be created.
|
|
28
|
+
*
|
|
29
|
+
* Callbacks always run on JavaScript's thread. One that throws is reported
|
|
30
|
+
* to `onCallbackError` (by default as a process warning) and does not affect
|
|
31
|
+
* the client.
|
|
32
|
+
*/
|
|
33
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
34
|
+
exports.Client = exports.Car = exports.TEST_TLS = void 0;
|
|
35
|
+
const methods_js_1 = require("./generated/methods.js");
|
|
36
|
+
const shapes_js_1 = require("./generated/shapes.js");
|
|
37
|
+
const native_js_1 = require("./native.js");
|
|
38
|
+
const wire_js_1 = require("./wire.js");
|
|
39
|
+
/**
|
|
40
|
+
* Makes a client trust the certificate of the MQTT test broker. For tests,
|
|
41
|
+
* with an add-on built with the feature `testing`: `{ ...options, [TEST_TLS]: true }`.
|
|
42
|
+
*
|
|
43
|
+
* @internal
|
|
44
|
+
*/
|
|
45
|
+
exports.TEST_TLS = Symbol.for("openbyd.testTls");
|
|
46
|
+
/** How long the timer that keeps a listening client's process alive sleeps: the longest Node allows. */
|
|
47
|
+
const KEEP_ALIVE_MS = 0x7fffffff;
|
|
48
|
+
/** A client's connection to the core: calls out, events in. */
|
|
49
|
+
class Core {
|
|
50
|
+
#native;
|
|
51
|
+
#options;
|
|
52
|
+
#listens;
|
|
53
|
+
/** The state listener of each car, by VIN. */
|
|
54
|
+
stateListeners = new Map();
|
|
55
|
+
#keepAlive;
|
|
56
|
+
#pending = 0;
|
|
57
|
+
constructor(options) {
|
|
58
|
+
this.#options = options;
|
|
59
|
+
const events = [];
|
|
60
|
+
if (options.onVehicleInfo)
|
|
61
|
+
events.push("vehicle_info");
|
|
62
|
+
if (options.onMqttEvent)
|
|
63
|
+
events.push("mqtt_event");
|
|
64
|
+
if (options.onCommandAck)
|
|
65
|
+
events.push("command_ack");
|
|
66
|
+
if (options.onCommandLifecycle)
|
|
67
|
+
events.push("command_lifecycle");
|
|
68
|
+
if (options.onMqttConnect)
|
|
69
|
+
events.push("mqtt_connect");
|
|
70
|
+
this.#listens = events.length > 0;
|
|
71
|
+
if (options.requestObserver)
|
|
72
|
+
events.push("request");
|
|
73
|
+
const hostOptions = {
|
|
74
|
+
events,
|
|
75
|
+
command_ack_ttl_seconds: options.commandAckTtlSeconds,
|
|
76
|
+
command_retries: options.commandRetries,
|
|
77
|
+
gate_policy: typeof options.gatePolicy === "function" ? "host" : options.gatePolicy,
|
|
78
|
+
pin_resolver: options.pinResolver ? "host" : undefined,
|
|
79
|
+
relogin: typeof options.relogin === "function" ? "host" : options.relogin,
|
|
80
|
+
test_tls: options[exports.TEST_TLS] === true ? true : undefined,
|
|
81
|
+
};
|
|
82
|
+
// The add-on keeps this function for as long as its client lives, so it
|
|
83
|
+
// must not hold the client: a client nobody refers to is collected, and
|
|
84
|
+
// the add-on's client with it.
|
|
85
|
+
let target;
|
|
86
|
+
const onEvent = (name, payload) => target?.deref()?.dispatch(name, payload);
|
|
87
|
+
try {
|
|
88
|
+
this.#native = new native_js_1.native.NativeClient((0, wire_js_1.encode)((0, methods_js_1.encodeBydConfig)(options)), (0, wire_js_1.encode)(hostOptions), onEvent);
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
throw (0, wire_js_1.translate)(error);
|
|
92
|
+
}
|
|
93
|
+
target = new WeakRef(this);
|
|
94
|
+
}
|
|
95
|
+
call(method, args, shape) {
|
|
96
|
+
this.#pending += 1;
|
|
97
|
+
// The call's promise refers to this client until it settles, so a client
|
|
98
|
+
// is not collected while it has a call in flight (its callbacks may be needed).
|
|
99
|
+
return this.#native.call(method, (0, wire_js_1.encode)(args)).then((text) => {
|
|
100
|
+
this.#pending -= 1;
|
|
101
|
+
return (0, wire_js_1.decode)(text, shape);
|
|
102
|
+
}, (error) => {
|
|
103
|
+
this.#pending -= 1;
|
|
104
|
+
throw (0, wire_js_1.translate)(error);
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
callSync(method, args, shape) {
|
|
108
|
+
try {
|
|
109
|
+
return (0, wire_js_1.decode)(this.#native.callSync(method, (0, wire_js_1.encode)(args)), shape);
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
throw (0, wire_js_1.translate)(error);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/** The invoker of the car numbered `car`: every call names it. */
|
|
116
|
+
forCar(car) {
|
|
117
|
+
return {
|
|
118
|
+
call: (method, args, shape) => this.call(method, { ...args, car }, shape),
|
|
119
|
+
callSync: (method, args, shape) => this.callSync(method, { ...args, car }, shape),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/** Calls in flight. */
|
|
123
|
+
get pending() {
|
|
124
|
+
return this.#pending;
|
|
125
|
+
}
|
|
126
|
+
start() {
|
|
127
|
+
this.callSync("start", {}, null);
|
|
128
|
+
if (this.#listens)
|
|
129
|
+
this.hold();
|
|
130
|
+
}
|
|
131
|
+
close() {
|
|
132
|
+
this.stateListeners.clear();
|
|
133
|
+
this.release();
|
|
134
|
+
this.callSync("close", {}, null);
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Keeps the process alive until {@link release}, as an open socket would:
|
|
138
|
+
* a client with push listeners is waiting for pushes. The timer also
|
|
139
|
+
* refers to the client, so it is not collected while it listens.
|
|
140
|
+
*/
|
|
141
|
+
hold() {
|
|
142
|
+
this.#keepAlive ??= setInterval(() => void this, KEEP_ALIVE_MS);
|
|
143
|
+
}
|
|
144
|
+
release() {
|
|
145
|
+
clearInterval(this.#keepAlive);
|
|
146
|
+
this.#keepAlive = undefined;
|
|
147
|
+
}
|
|
148
|
+
dispatch(name, payload) {
|
|
149
|
+
const options = this.#options;
|
|
150
|
+
const data = JSON.parse(payload);
|
|
151
|
+
if ((0, wire_js_1.mayHoldNonFinite)(payload))
|
|
152
|
+
(0, wire_js_1.reviveFields)(data, shapes_js_1.EVENT_SHAPES[name]);
|
|
153
|
+
switch (name) {
|
|
154
|
+
case "vehicle_info":
|
|
155
|
+
this.#notify("onVehicleInfo", () => options.onVehicleInfo?.(data.vin, data.data));
|
|
156
|
+
break;
|
|
157
|
+
case "mqtt_event":
|
|
158
|
+
this.#notify("onMqttEvent", () => options.onMqttEvent?.(data.event, data.vin, data.data));
|
|
159
|
+
break;
|
|
160
|
+
case "command_ack":
|
|
161
|
+
this.#notify("onCommandAck", () => options.onCommandAck?.(data.ack));
|
|
162
|
+
break;
|
|
163
|
+
case "command_lifecycle":
|
|
164
|
+
this.#notify("onCommandLifecycle", () => options.onCommandLifecycle?.(data.event));
|
|
165
|
+
break;
|
|
166
|
+
case "mqtt_connect":
|
|
167
|
+
this.#notify("onMqttConnect", () => options.onMqttConnect?.());
|
|
168
|
+
break;
|
|
169
|
+
case "request":
|
|
170
|
+
this.#notify("requestObserver", () => options.requestObserver?.(data.record));
|
|
171
|
+
break;
|
|
172
|
+
case "state_changed": {
|
|
173
|
+
const vin = data.vin;
|
|
174
|
+
this.#notify("onStateChanged", () => this.stateListeners.get(vin)?.(vin, data.state));
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
case "gate_policy": {
|
|
178
|
+
const policy = options.gatePolicy;
|
|
179
|
+
if (typeof policy !== "function")
|
|
180
|
+
break;
|
|
181
|
+
this.#answer(data.request, "gatePolicy", true, () => policy(data.vin, data.verdict));
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
case "pin_resolver": {
|
|
185
|
+
const resolver = options.pinResolver;
|
|
186
|
+
if (resolver === undefined)
|
|
187
|
+
break;
|
|
188
|
+
this.#answer(data.request, "pinResolver", true, () => resolver(data.command_pwd, data.control_pin));
|
|
189
|
+
break;
|
|
190
|
+
}
|
|
191
|
+
case "relogin": {
|
|
192
|
+
const relogin = options.relogin;
|
|
193
|
+
if (typeof relogin !== "function")
|
|
194
|
+
break;
|
|
195
|
+
// What it throws is the failure of the call that needed the session, not a stray error.
|
|
196
|
+
this.#answer(data.request, "relogin", false, relogin);
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
default:
|
|
200
|
+
// An event of a newer core.
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/** Runs a notification callback; what it throws, now or later, is reported. */
|
|
205
|
+
#notify(name, run) {
|
|
206
|
+
try {
|
|
207
|
+
const result = run();
|
|
208
|
+
if (result instanceof Promise)
|
|
209
|
+
result.catch((error) => this.#report(name, error));
|
|
210
|
+
}
|
|
211
|
+
catch (error) {
|
|
212
|
+
this.#report(name, error);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
/** Runs a callback the core waits for, and hands its answer or its failure back. */
|
|
216
|
+
#answer(request, name, report, run) {
|
|
217
|
+
Promise.resolve()
|
|
218
|
+
.then(run)
|
|
219
|
+
.then((value) => this.#resolve({ request, value }), (error) => {
|
|
220
|
+
if (report)
|
|
221
|
+
this.#report(name, error);
|
|
222
|
+
this.#resolve({ request, error: (0, wire_js_1.errorToJson)(error) });
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
#resolve(answer) {
|
|
226
|
+
try {
|
|
227
|
+
this.#native.callSync("resolve", (0, wire_js_1.encode)(answer));
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
// The question is no longer waiting.
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
#report(name, error) {
|
|
234
|
+
const handler = this.#options.onCallbackError;
|
|
235
|
+
if (handler !== undefined) {
|
|
236
|
+
try {
|
|
237
|
+
handler(name, error);
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
// A failing error handler has nowhere to report to.
|
|
241
|
+
}
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
245
|
+
const warning = new Error(`the ${name} callback threw: ${message}`, { cause: error });
|
|
246
|
+
warning.name = "OpenBydCallbackWarning";
|
|
247
|
+
process.emitWarning(warning);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* One vehicle: pyBYD's `BydCar`. Get one from {@link Client.getCar}.
|
|
252
|
+
*
|
|
253
|
+
* It holds the vehicle's merged state and offers its commands by feature:
|
|
254
|
+
*
|
|
255
|
+
* ```ts
|
|
256
|
+
* const car = await client.getCar(vin);
|
|
257
|
+
* await car.updateRealtime();
|
|
258
|
+
* await car.lock.lock();
|
|
259
|
+
* await car.hvac.start({ temperature: 21, duration: 20 });
|
|
260
|
+
* car.state.realtime?.left_front_door_lock; // 2 (locked), projected
|
|
261
|
+
* ```
|
|
262
|
+
*
|
|
263
|
+
* A command lays the state it expects over the current state at once (a
|
|
264
|
+
* projection) and rolls it back when it fails; the next push or update that
|
|
265
|
+
* agrees confirms it. Each feature tells whether the car supports it; a
|
|
266
|
+
* command the car does not support throws `BydEndpointNotSupportedError`
|
|
267
|
+
* without sending anything. A car whose client is closed fails its calls
|
|
268
|
+
* with `BydError`.
|
|
269
|
+
*/
|
|
270
|
+
class Car extends methods_js_1.CarMethods {
|
|
271
|
+
/** The vehicle identification number. */
|
|
272
|
+
vin;
|
|
273
|
+
/** @internal */
|
|
274
|
+
constructor(invoker, vin) {
|
|
275
|
+
super(invoker);
|
|
276
|
+
this.vin = vin;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
exports.Car = Car;
|
|
280
|
+
/** The async client for the BYD API: pyBYD's `BydClient`. See the module's documentation. */
|
|
281
|
+
class Client extends methods_js_1.ClientMethods {
|
|
282
|
+
#core;
|
|
283
|
+
#cars = new Map();
|
|
284
|
+
#closed = false;
|
|
285
|
+
/**
|
|
286
|
+
* A client for an account, ready to use. A bad config value throws
|
|
287
|
+
* `ValidationError`.
|
|
288
|
+
*
|
|
289
|
+
* A client with push listeners (`onVehicleInfo`, `onMqttEvent`,
|
|
290
|
+
* `onCommandAck`, `onCommandLifecycle`, `onMqttConnect`, or a car's
|
|
291
|
+
* `onStateChanged`) keeps the process alive until {@link close}, as an
|
|
292
|
+
* open socket would.
|
|
293
|
+
*/
|
|
294
|
+
constructor(options) {
|
|
295
|
+
const core = new Core(options);
|
|
296
|
+
super(core);
|
|
297
|
+
this.#core = core;
|
|
298
|
+
core.start();
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* A client that resumes a session from {@link exportSession}, without a
|
|
302
|
+
* password login. Without a `password` it never logs in by itself
|
|
303
|
+
* (`relogin` defaults to `"never"`): when the session expires, calls throw
|
|
304
|
+
* `BydSessionExpiredError` until the application imports a new one.
|
|
305
|
+
*/
|
|
306
|
+
static async fromSession(session, options) {
|
|
307
|
+
const password = options.password ?? "";
|
|
308
|
+
const client = new Client({
|
|
309
|
+
...options,
|
|
310
|
+
password,
|
|
311
|
+
relogin: options.relogin ?? (password === "" ? "never" : "password"),
|
|
312
|
+
});
|
|
313
|
+
try {
|
|
314
|
+
await client.importSession(session);
|
|
315
|
+
}
|
|
316
|
+
catch (error) {
|
|
317
|
+
client.close();
|
|
318
|
+
throw error;
|
|
319
|
+
}
|
|
320
|
+
return client;
|
|
321
|
+
}
|
|
322
|
+
/** Whether {@link close} was called and {@link start} was not called since. */
|
|
323
|
+
get closed() {
|
|
324
|
+
return this.#closed;
|
|
325
|
+
}
|
|
326
|
+
/** Opens the client again after {@link close} (pyBYD's `async_start`). A new client is open already. */
|
|
327
|
+
start() {
|
|
328
|
+
this.#core.start();
|
|
329
|
+
this.#closed = false;
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Closes the cars, stops MQTT and makes later calls fail with `BydError`
|
|
333
|
+
* (pyBYD's `async_close`). Calls already in flight finish; one waiting
|
|
334
|
+
* for an MQTT push stops waiting with `CancelledError`.
|
|
335
|
+
*/
|
|
336
|
+
close() {
|
|
337
|
+
this.#cars.clear();
|
|
338
|
+
this.#core.close();
|
|
339
|
+
this.#closed = true;
|
|
340
|
+
}
|
|
341
|
+
/** Closes the client: `using client = new Client(...)`. */
|
|
342
|
+
[Symbol.dispose]() {
|
|
343
|
+
this.close();
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* The {@link Car} of a vehicle, built once and kept.
|
|
347
|
+
*
|
|
348
|
+
* As pyBYD: a kept car is returned as it is, whatever the options.
|
|
349
|
+
* Otherwise the vehicle list is fetched unless `vehicle` is given, then
|
|
350
|
+
* the capabilities.
|
|
351
|
+
*
|
|
352
|
+
* @param vin - The vehicle identification number.
|
|
353
|
+
*/
|
|
354
|
+
async getCar(vin, options = {}) {
|
|
355
|
+
const listener = options.onStateChanged;
|
|
356
|
+
const built = await this.#core.call("get_car", {
|
|
357
|
+
vin,
|
|
358
|
+
vehicle: options.vehicle,
|
|
359
|
+
projection_ttl: options.projectionTtl,
|
|
360
|
+
state_events: listener !== undefined,
|
|
361
|
+
}, null);
|
|
362
|
+
let car = this.#cars.get(built.car);
|
|
363
|
+
if (car === undefined) {
|
|
364
|
+
car = new Car(this.#core.forCar(built.car), built.vin);
|
|
365
|
+
this.#cars.set(built.car, car);
|
|
366
|
+
if (listener !== undefined) {
|
|
367
|
+
this.#core.stateListeners.set(built.vin, listener);
|
|
368
|
+
this.#core.hold();
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return car;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
exports.Client = Client;
|