openbyd 0.0.0-stage → 0.1.3
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 +169 -0
- package/dist/generated/methods.d.ts +516 -0
- package/dist/generated/methods.js +1028 -0
- package/dist/generated/models.d.ts +1499 -0
- package/dist/generated/models.js +206 -0
- package/dist/generated/shapes.d.ts +49 -0
- package/dist/generated/shapes.js +168 -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 })`. Preconditioning plans use `getStandbyPlans`, `saveStandbyPlan`, `createStandbyPlan`, `setDefaultStandbyPlan`, `deleteStandbyPlan` and `runStandbyPlan`; on a daily `StandbySchedule`, set `zone` to an IANA time zone name (such as `"Europe/Madrid"`) so the next run follows that zone's wall clock across daylight-saving changes.
|
|
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` (BYD's own expiry code, or `relogin_disabled` when there was no session).
|
|
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
|
+
}
|