homebridge-toyota 0.1.0 → 0.2.0
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 +17 -34
- package/auth.js +185 -0
- package/config.schema.json +27 -37
- package/index.js +9 -15
- package/login.js +68 -0
- package/package.json +7 -3
- package/toyota.js +287 -0
- package/requirements.txt +0 -2
- package/toyota.py +0 -133
package/README.md
CHANGED
|
@@ -5,76 +5,59 @@
|
|
|
5
5
|
|
|
6
6
|
A Homebridge accessory for Toyota Remote Connect. Apple Home gets a door lock control and a momentary remote-start switch. Turning the switch off has no effect on the engine. The lock reads Toyota's last reported status, which can lag behind the vehicle.
|
|
7
7
|
|
|
8
|
-
The plugin runs the Toyota North America client from [orienw/ha-toyota-na](https://github.com/orienw/ha-toyota-na). It uses that project's sign-in, vehicle capability checks, and generation-specific remote command routing. The Home Assistant server and HACS are unnecessary. The client is unofficial and Toyota can change its service. Live compatibility with the 2026 Sienna needs to be verified during setup.
|
|
9
|
-
|
|
10
8
|
## Requirements
|
|
11
9
|
|
|
12
|
-
|
|
10
|
+
- Node.js 22 or 24 and Homebridge 1.8 or 2.x.
|
|
11
|
+
- A compatible North American Toyota and an active Toyota Remote Connect subscription.
|
|
12
|
+
- Version 0.2.0 runs entirely in Node.js. Live testing with the 2026 Sienna is pending.
|
|
13
13
|
|
|
14
14
|
## Installation and setup
|
|
15
15
|
|
|
16
|
-
Run these commands on
|
|
16
|
+
Run these commands on the machine that runs Homebridge. Use a private session directory accessible to the user account running the Homebridge service.
|
|
17
|
+
|
|
18
|
+
Windows PowerShell:
|
|
17
19
|
|
|
18
20
|
```powershell
|
|
19
21
|
npm.cmd install -g homebridge-toyota
|
|
20
|
-
$
|
|
21
|
-
|
|
22
|
-
New-Item -ItemType Directory -Force $toyotaHome | Out-Null
|
|
23
|
-
git clone https://github.com/orienw/ha-toyota-na.git "$toyotaHome/client"
|
|
24
|
-
py -3.13 -m venv "$toyotaHome/venv"
|
|
25
|
-
$toyotaPython = "$toyotaHome/venv/Scripts/python.exe"
|
|
26
|
-
& $toyotaPython -m pip install -r "$plugin/requirements.txt"
|
|
27
|
-
$toyotaClient = "$toyotaHome/client/custom_components/toyota_na"
|
|
28
|
-
$toyotaSession = "$toyotaHome/session.json"
|
|
29
|
-
& $toyotaPython -I "$plugin/toyota.py" $toyotaClient $toyotaSession login
|
|
30
|
-
& $toyotaPython -I "$plugin/toyota.py" $toyotaClient $toyotaSession vehicles
|
|
22
|
+
$session = Join-Path $env:LOCALAPPDATA 'homebridge-toyota/session.json'
|
|
23
|
+
homebridge-toyota-login.cmd $session
|
|
31
24
|
```
|
|
32
25
|
|
|
33
|
-
|
|
26
|
+
macOS or Linux:
|
|
34
27
|
|
|
35
28
|
```sh
|
|
36
29
|
npm install -g homebridge-toyota
|
|
37
|
-
|
|
38
|
-
toyota_dir="$HOME/.homebridge-toyota"
|
|
39
|
-
mkdir -p "$toyota_dir"
|
|
40
|
-
git clone https://github.com/orienw/ha-toyota-na.git "$toyota_dir/client"
|
|
41
|
-
python3.13 -m venv "$toyota_dir/venv"
|
|
42
|
-
toyota_python="$toyota_dir/venv/bin/python"
|
|
43
|
-
"$toyota_python" -m pip install -r "$plugin/requirements.txt"
|
|
44
|
-
toyota_client="$toyota_dir/client/custom_components/toyota_na"
|
|
45
|
-
toyota_session="$toyota_dir/session.json"
|
|
46
|
-
"$toyota_python" -I "$plugin/toyota.py" "$toyota_client" "$toyota_session" login
|
|
47
|
-
"$toyota_python" -I "$plugin/toyota.py" "$toyota_client" "$toyota_session" vehicles
|
|
30
|
+
homebridge-toyota-login "$HOME/.homebridge-toyota/session.json"
|
|
48
31
|
```
|
|
49
32
|
|
|
50
|
-
Enter
|
|
33
|
+
Enter your Toyota credentials and, if prompted, the verification code. The command saves a local session file and lists the vehicles on your account. Keep that file private. It contains tokens that can access your Toyota account, and the plugin refreshes them as needed.
|
|
34
|
+
|
|
35
|
+
If you're upgrading from 0.1.0, keep your existing `sessionFile` and `vin`. Remove the `python` and `clientDirectory` fields from the accessory configuration. If Toyota requires a fresh sign-in, stop Homebridge, run the login command with your existing session path, and then restart Homebridge.
|
|
36
|
+
|
|
51
37
|
|
|
52
38
|
## Configuration
|
|
53
39
|
|
|
54
|
-
Add one entry to the existing Homebridge `accessories` array. Use the
|
|
40
|
+
Add one entry to the existing Homebridge `accessories` array. Use the VIN listed by the login command and the absolute session file path from setup. In JSON, use forward slashes for Windows paths or escape each backslash.
|
|
55
41
|
|
|
56
42
|
```json
|
|
57
43
|
{
|
|
58
44
|
"accessory": "Toyota",
|
|
59
45
|
"name": "Sienna",
|
|
60
46
|
"vin": "YOUR_17_CHARACTER_VIN",
|
|
61
|
-
"python": "/absolute/path/to/venv/bin/python",
|
|
62
|
-
"clientDirectory": "/absolute/path/to/client/custom_components/toyota_na",
|
|
63
47
|
"sessionFile": "/absolute/path/to/session.json"
|
|
64
48
|
}
|
|
65
49
|
```
|
|
66
50
|
|
|
67
51
|
Restart Homebridge and open Apple Home. Test the door lock with the Sienna in view. Test remote start outdoors with the vehicle empty. The start switch resets after the request, and vehicle state can be verified in the Toyota app. If Apple Home times out, check the Toyota app before trying again. Keep the remote-start switch out of unattended automations.
|
|
68
52
|
|
|
69
|
-
For an expired session, stop the plugin, rerun the setup login command, then restart Homebridge. The upstream client is loaded from the checkout on disk. Keep the same checkout once tested, as newer revisions may change its Python interfaces.
|
|
70
53
|
|
|
71
54
|
## Support
|
|
72
55
|
|
|
73
|
-
Use [GitHub Issues](https://github.com/dean1d/homebridge-toyota/issues) for reproducible bugs and feature requests. Include the vehicle model and year, Homebridge and Node.js versions, and the error
|
|
56
|
+
Use [GitHub Issues](https://github.com/dean1d/homebridge-toyota/issues) for reproducible bugs and feature requests. Include the vehicle model and year, Homebridge and Node.js versions, and the error shown in the Homebridge log. Remove VINs, credentials, verification codes, and session data from anything you share.
|
|
74
57
|
|
|
75
58
|
## Credits
|
|
76
59
|
|
|
77
|
-
- [orienw](https://github.com/orienw) and contributors for the [Toyota North America Home Assistant integration](https://github.com/orienw/ha-toyota-na),
|
|
60
|
+
- [orienw](https://github.com/orienw) and contributors for the [Toyota North America Home Assistant integration](https://github.com/orienw/ha-toyota-na), which served as a reference for the Node.js sign-in and remote-command implementation.
|
|
78
61
|
- [widewing](https://github.com/widewing) and contributors for the [original Toyota North America integration](https://github.com/widewing/ha-toyota-na).
|
|
79
62
|
|
|
80
63
|
## Disclaimer
|
package/auth.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { createHash, randomBytes, randomUUID } = require('node:crypto');
|
|
4
|
+
const { readFile, rename, unlink, writeFile } = require('node:fs/promises');
|
|
5
|
+
|
|
6
|
+
const origin = 'https://login.toyotadriverslogin.com';
|
|
7
|
+
const realm = '/realms/root/realms/tmna-native';
|
|
8
|
+
const oauth = origin + '/oauth2' + realm;
|
|
9
|
+
const clientId = 'oneappsdkclient';
|
|
10
|
+
const redirectUri = 'com.toyota.oneapp:/oauth2Callback';
|
|
11
|
+
|
|
12
|
+
async function request(fetch, url, options = {}) {
|
|
13
|
+
return fetch(url, { signal: AbortSignal.timeout(20_000), ...options, redirect: 'manual' });
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function exchange(fetch, params, previous = {}) {
|
|
17
|
+
const response = await request(fetch, oauth + '/access_token', {
|
|
18
|
+
method: 'POST',
|
|
19
|
+
body: new URLSearchParams({ client_id: clientId, ...params }),
|
|
20
|
+
});
|
|
21
|
+
if (!response.ok) throw new Error('Toyota rejected the session. Run the login command if it has expired.');
|
|
22
|
+
const result = await response.json();
|
|
23
|
+
const access = result.access_token;
|
|
24
|
+
const refresh = result.refresh_token ?? previous.refresh_token;
|
|
25
|
+
const id = result.id_token ?? previous.id_token;
|
|
26
|
+
const lifetime = Number(result.expires_in);
|
|
27
|
+
if (![access, refresh, id].every((value) => typeof value === 'string' && value)
|
|
28
|
+
|| !Number.isFinite(lifetime) || lifetime <= 0) {
|
|
29
|
+
throw new Error('Toyota returned incomplete OAuth tokens.');
|
|
30
|
+
}
|
|
31
|
+
// Read the account identifier from the token returned by Toyota over TLS.
|
|
32
|
+
const { sub: guid } = JSON.parse(Buffer.from(id.split('.')[1] ?? '', 'base64url'));
|
|
33
|
+
if (!guid) throw new Error('Toyota did not return an account identifier.');
|
|
34
|
+
const now = Date.now() / 1_000;
|
|
35
|
+
return {
|
|
36
|
+
access_token: access, refresh_token: refresh, id_token: id, guid,
|
|
37
|
+
updated_at: now, expires_at: now + lifetime, clock: 'unix',
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function login(fetch, { username, password, askCode }) {
|
|
42
|
+
const headers = {
|
|
43
|
+
'Content-Type': 'application/json',
|
|
44
|
+
'Accept-API-Version': 'resource=2.1, protocol=1.0',
|
|
45
|
+
'Accept-Language': 'en-US',
|
|
46
|
+
};
|
|
47
|
+
let challenge = {};
|
|
48
|
+
let passwordSent = false;
|
|
49
|
+
let otpSent = false;
|
|
50
|
+
for (let step = 0; step < 15 && !challenge.tokenId; step++) {
|
|
51
|
+
for (const callback of challenge.callbacks ?? []) {
|
|
52
|
+
const output = Object.fromEntries(callback.output.map(({ name, value }) => [name, value]));
|
|
53
|
+
const prompt = String(output.prompt ?? '').trim().toLowerCase();
|
|
54
|
+
const input = callback.input?.[0];
|
|
55
|
+
switch (callback.type) {
|
|
56
|
+
case 'NameCallback':
|
|
57
|
+
if (['ui_locales', 'ui locale'].includes(prompt)) input.value = 'en-US';
|
|
58
|
+
else if (!['deviceprint', 'mail'].includes(prompt)) input.value = username;
|
|
59
|
+
break;
|
|
60
|
+
case 'PasswordCallback':
|
|
61
|
+
if (prompt === 'one time password') {
|
|
62
|
+
if (otpSent) throw new Error('Toyota did not accept the verification code.');
|
|
63
|
+
input.value = await askCode();
|
|
64
|
+
if (!input.value) throw new Error('Enter the verification code sent by Toyota.');
|
|
65
|
+
otpSent = true;
|
|
66
|
+
} else {
|
|
67
|
+
if (passwordSent) throw new Error('Toyota did not accept the password.');
|
|
68
|
+
input.value = password;
|
|
69
|
+
passwordSent = true;
|
|
70
|
+
}
|
|
71
|
+
break;
|
|
72
|
+
case 'ChoiceCallback': {
|
|
73
|
+
const choices = (output.choices ?? []).map((choice) => String(choice).trim().toLowerCase());
|
|
74
|
+
const local = choices.indexOf('local');
|
|
75
|
+
const alternative = choices.findIndex((choice) => !['google', 'apple', 'facebook'].includes(choice));
|
|
76
|
+
const selected = local < 0 ? alternative : local;
|
|
77
|
+
if (selected < 0) throw new Error('Toyota did not offer a direct account sign-in method.');
|
|
78
|
+
input.value = selected;
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
case 'ConfirmationCallback':
|
|
82
|
+
input.value = 0;
|
|
83
|
+
break;
|
|
84
|
+
case 'HiddenValueCallback':
|
|
85
|
+
break;
|
|
86
|
+
case 'TextOutputCallback':
|
|
87
|
+
if (String(output.messageType) === '2' || String(output.message).toLowerCase() === 'invalid otp') {
|
|
88
|
+
throw new Error('Toyota rejected the login challenge.');
|
|
89
|
+
}
|
|
90
|
+
break;
|
|
91
|
+
default:
|
|
92
|
+
throw new Error('Toyota returned an unsupported sign-in challenge.');
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const response = await request(fetch, origin + '/json' + realm + '/authenticate', {
|
|
96
|
+
method: 'POST', headers, body: JSON.stringify(challenge),
|
|
97
|
+
});
|
|
98
|
+
if (!response.ok) throw new Error('Toyota sign-in failed.');
|
|
99
|
+
challenge = await response.json();
|
|
100
|
+
if (!challenge.tokenId && !challenge.callbacks?.some(({ input }) => input?.length)) {
|
|
101
|
+
throw new Error('Toyota returned no actionable sign-in challenge.');
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (!challenge.tokenId) throw new Error('Toyota sign-in did not finish.');
|
|
105
|
+
const verifier = randomBytes(64).toString('base64url');
|
|
106
|
+
const query = new URLSearchParams({
|
|
107
|
+
client_id: clientId, scope: 'openid profile write', response_type: 'code',
|
|
108
|
+
redirect_uri: redirectUri, code_challenge_method: 'S256',
|
|
109
|
+
code_challenge: createHash('sha256').update(verifier).digest('base64url'),
|
|
110
|
+
});
|
|
111
|
+
const response = await request(fetch, oauth + '/authorize?' + query, {
|
|
112
|
+
headers: { ...headers, Cookie: 'iPlanetDirectoryPro=' + challenge.tokenId },
|
|
113
|
+
});
|
|
114
|
+
const location = response.headers.get('location');
|
|
115
|
+
if (![301, 302, 303, 307, 308].includes(response.status) || !location) {
|
|
116
|
+
throw new Error('Toyota did not return an OAuth redirect.');
|
|
117
|
+
}
|
|
118
|
+
const redirect = new URL(location);
|
|
119
|
+
const codes = redirect.searchParams.getAll('code');
|
|
120
|
+
if (location.split('?')[0] !== redirectUri || redirect.hash
|
|
121
|
+
|| redirect.searchParams.has('error') || codes.length !== 1 || !codes[0]) {
|
|
122
|
+
throw new Error('Toyota returned an invalid OAuth redirect.');
|
|
123
|
+
}
|
|
124
|
+
const tokens = await exchange(fetch, {
|
|
125
|
+
grant_type: 'authorization_code', code: codes[0], code_verifier: verifier, redirect_uri: redirectUri,
|
|
126
|
+
});
|
|
127
|
+
return { tokens, device_id: randomBytes(32).toString('hex') };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function saveSession(path, session) {
|
|
131
|
+
const temporary = path + '.' + randomUUID() + '.tmp';
|
|
132
|
+
try {
|
|
133
|
+
await writeFile(temporary, JSON.stringify(session), { mode: 0o600, flag: 'wx' });
|
|
134
|
+
await rename(temporary, path);
|
|
135
|
+
} finally {
|
|
136
|
+
await unlink(temporary).catch(() => {});
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
class Session {
|
|
141
|
+
constructor(path, fetch) {
|
|
142
|
+
this.path = path;
|
|
143
|
+
this.fetch = fetch;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async get(rejectedToken) {
|
|
147
|
+
if (!this.pending) {
|
|
148
|
+
this.pending = this.read(rejectedToken).finally(() => { this.pending = undefined; });
|
|
149
|
+
}
|
|
150
|
+
return this.pending;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async read(rejectedToken) {
|
|
154
|
+
let session;
|
|
155
|
+
try {
|
|
156
|
+
session = this.cached ?? JSON.parse(await readFile(this.path, 'utf8'));
|
|
157
|
+
if (!session.tokens?.refresh_token || !session.device_id) throw new Error();
|
|
158
|
+
} catch {
|
|
159
|
+
throw new Error('Toyota session is missing or invalid. Run the login command.');
|
|
160
|
+
}
|
|
161
|
+
const { tokens } = session;
|
|
162
|
+
const margin = Math.min(60, (tokens.expires_at - tokens.updated_at) / 10);
|
|
163
|
+
if (tokens.clock !== 'unix' || !tokens.access_token || !tokens.guid
|
|
164
|
+
|| !(tokens.expires_at - margin > Date.now() / 1_000)
|
|
165
|
+
|| tokens.access_token === rejectedToken) {
|
|
166
|
+
session = {
|
|
167
|
+
...session,
|
|
168
|
+
tokens: await exchange(this.fetch, {
|
|
169
|
+
grant_type: 'refresh_token', refresh_token: tokens.refresh_token,
|
|
170
|
+
}, tokens),
|
|
171
|
+
};
|
|
172
|
+
this.cached = session;
|
|
173
|
+
this.needsSave = true;
|
|
174
|
+
}
|
|
175
|
+
if (this.needsSave) {
|
|
176
|
+
await saveSession(this.path, session);
|
|
177
|
+
this.needsSave = false;
|
|
178
|
+
}
|
|
179
|
+
this.cached = session;
|
|
180
|
+
return session;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
module.exports = { login, request, saveSession, Session };
|
|
185
|
+
|
package/config.schema.json
CHANGED
|
@@ -1,38 +1,28 @@
|
|
|
1
|
-
{
|
|
2
|
-
"pluginAlias": "Toyota",
|
|
3
|
-
"pluginType": "accessory",
|
|
4
|
-
"singular": true,
|
|
5
|
-
"schema": {
|
|
6
|
-
"type": "object",
|
|
7
|
-
"required": [
|
|
8
|
-
"name",
|
|
9
|
-
"vin",
|
|
10
|
-
"
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
"
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
"clientDirectory": {
|
|
29
|
-
"type": "string",
|
|
30
|
-
"title": "Absolute path to upstream custom_components/toyota_na"
|
|
31
|
-
},
|
|
32
|
-
"sessionFile": {
|
|
33
|
-
"type": "string",
|
|
34
|
-
"title": "Absolute path to the session file created by setup"
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"pluginAlias": "Toyota",
|
|
3
|
+
"pluginType": "accessory",
|
|
4
|
+
"singular": true,
|
|
5
|
+
"schema": {
|
|
6
|
+
"type": "object",
|
|
7
|
+
"required": [
|
|
8
|
+
"name",
|
|
9
|
+
"vin",
|
|
10
|
+
"sessionFile"
|
|
11
|
+
],
|
|
12
|
+
"properties": {
|
|
13
|
+
"name": {
|
|
14
|
+
"type": "string",
|
|
15
|
+
"default": "Sienna"
|
|
16
|
+
},
|
|
17
|
+
"vin": {
|
|
18
|
+
"type": "string",
|
|
19
|
+
"pattern": "^[A-HJ-NPR-Z0-9]{17}$",
|
|
20
|
+
"title": "Vehicle VIN"
|
|
21
|
+
},
|
|
22
|
+
"sessionFile": {
|
|
23
|
+
"type": "string",
|
|
24
|
+
"title": "Absolute path to the session file created by setup"
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
38
28
|
}
|
package/index.js
CHANGED
|
@@ -1,36 +1,30 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const {
|
|
4
|
-
const {
|
|
5
|
-
const { promisify } = require('node:util');
|
|
6
|
-
const exec = promisify(execFile);
|
|
3
|
+
const { isAbsolute } = require('node:path');
|
|
4
|
+
const { ToyotaClient } = require('./toyota');
|
|
7
5
|
|
|
8
6
|
module.exports = (api) => api.registerAccessory('homebridge-toyota', 'Toyota', Toyota);
|
|
9
7
|
|
|
10
8
|
class Toyota {
|
|
11
9
|
constructor(log, config, api) {
|
|
12
10
|
const { Service, Characteristic: C, HapStatusError, HAPStatus } = api.hap;
|
|
13
|
-
const { name, vin,
|
|
11
|
+
const { name, vin, sessionFile } = config;
|
|
14
12
|
const valid = /^[A-HJ-NPR-Z0-9]{17}$/.test(vin)
|
|
15
|
-
&&
|
|
16
|
-
|
|
17
|
-
);
|
|
13
|
+
&& typeof sessionFile === 'string' && isAbsolute(sessionFile);
|
|
14
|
+
const client = valid ? new ToyotaClient(sessionFile) : undefined;
|
|
18
15
|
|
|
19
16
|
const call = async (action) => {
|
|
20
17
|
if (!valid) {
|
|
21
|
-
log.error('Configure a valid VIN and absolute
|
|
18
|
+
log.error('Configure a valid VIN and an absolute Toyota session file path.');
|
|
22
19
|
throw new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
|
|
23
20
|
}
|
|
24
21
|
if (this.busy) throw new HapStatusError(HAPStatus.RESOURCE_BUSY);
|
|
25
22
|
this.busy = true;
|
|
26
23
|
try {
|
|
27
|
-
|
|
28
|
-
'-I', join(__dirname, 'toyota.py'), clientDirectory, sessionFile, action, vin,
|
|
29
|
-
], { timeout: 120_000, maxBuffer: 16_384, windowsHide: true });
|
|
30
|
-
return JSON.parse(stdout);
|
|
24
|
+
return await client.run(vin, action);
|
|
31
25
|
} catch (error) {
|
|
32
|
-
const
|
|
33
|
-
log.error(`Toyota ${action} failed
|
|
26
|
+
const detail = error.constructor === Error ? error.message : 'Unexpected connection or response error.';
|
|
27
|
+
log.error(`Toyota ${action} failed. ${detail}`);
|
|
34
28
|
throw new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
|
|
35
29
|
} finally {
|
|
36
30
|
this.busy = false;
|
package/login.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const { mkdir } = require('node:fs/promises');
|
|
5
|
+
const { dirname, isAbsolute } = require('node:path');
|
|
6
|
+
const { createInterface } = require('node:readline/promises');
|
|
7
|
+
const { Writable } = require('node:stream');
|
|
8
|
+
const { login, saveSession } = require('./auth');
|
|
9
|
+
const { ToyotaClient } = require('./toyota');
|
|
10
|
+
|
|
11
|
+
async function main() {
|
|
12
|
+
const sessionFile = process.argv[2];
|
|
13
|
+
if (process.argv.length !== 3 || !isAbsolute(sessionFile)) {
|
|
14
|
+
throw new Error('Usage: homebridge-toyota-login <absolute-session-file-path>');
|
|
15
|
+
}
|
|
16
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
17
|
+
throw new Error('Run this command in an interactive terminal.');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
let hidden = false;
|
|
21
|
+
const display = new Writable({
|
|
22
|
+
write(chunk, _encoding, done) {
|
|
23
|
+
if (!hidden) process.stdout.write(chunk);
|
|
24
|
+
done();
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
const terminal = createInterface({
|
|
28
|
+
input: process.stdin, output: display, terminal: true, historySize: 0,
|
|
29
|
+
});
|
|
30
|
+
const secret = async (prompt) => {
|
|
31
|
+
process.stdout.write(prompt);
|
|
32
|
+
hidden = true;
|
|
33
|
+
try {
|
|
34
|
+
return await terminal.question('');
|
|
35
|
+
} finally {
|
|
36
|
+
hidden = false;
|
|
37
|
+
process.stdout.write('\n');
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
terminal.on('SIGINT', () => {
|
|
41
|
+
terminal.close();
|
|
42
|
+
process.exitCode = 130;
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
let session;
|
|
46
|
+
try {
|
|
47
|
+
const username = (await terminal.question('Toyota account email: ')).trim();
|
|
48
|
+
const password = await secret('Toyota password (blank for OTP-only accounts): ');
|
|
49
|
+
session = await login(globalThis.fetch, {
|
|
50
|
+
username, password, askCode: async () => (await secret('Toyota verification code: ')).trim(),
|
|
51
|
+
});
|
|
52
|
+
} finally {
|
|
53
|
+
terminal.close();
|
|
54
|
+
}
|
|
55
|
+
await mkdir(dirname(sessionFile), { recursive: true, mode: 0o700 });
|
|
56
|
+
await saveSession(sessionFile, session);
|
|
57
|
+
console.log('Toyota session saved.');
|
|
58
|
+
const vehicles = await new ToyotaClient(sessionFile).vehicles();
|
|
59
|
+
for (const { vin, modelName, modelYear, generation } of vehicles) {
|
|
60
|
+
console.log([modelYear, modelName, vin, generation].filter(Boolean).join(' '));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
main().catch((error) => {
|
|
65
|
+
console.error(error.constructor === Error ? error.message : 'Toyota setup failed. Check your connection and try again.');
|
|
66
|
+
if (!process.exitCode) process.exitCode = 1;
|
|
67
|
+
});
|
|
68
|
+
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "homebridge-toyota",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Toyota Remote Connect for Homebridge",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"keywords": [
|
|
@@ -17,8 +17,9 @@
|
|
|
17
17
|
},
|
|
18
18
|
"files": [
|
|
19
19
|
"index.js",
|
|
20
|
-
"
|
|
21
|
-
"
|
|
20
|
+
"auth.js",
|
|
21
|
+
"toyota.js",
|
|
22
|
+
"login.js",
|
|
22
23
|
"config.schema.json",
|
|
23
24
|
"README.md",
|
|
24
25
|
"LICENSE"
|
|
@@ -50,5 +51,8 @@
|
|
|
50
51
|
],
|
|
51
52
|
"publishConfig": {
|
|
52
53
|
"access": "public"
|
|
54
|
+
},
|
|
55
|
+
"bin": {
|
|
56
|
+
"homebridge-toyota-login": "login.js"
|
|
53
57
|
}
|
|
54
58
|
}
|
package/toyota.js
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { randomUUID } = require('node:crypto');
|
|
4
|
+
const { on, once } = require('node:events');
|
|
5
|
+
const { Session, request } = require('./auth');
|
|
6
|
+
|
|
7
|
+
const gateway = 'https://onecdn.telematicsct.com';
|
|
8
|
+
const graphHost = 'oa-api.telematicsct.com';
|
|
9
|
+
const graph = 'https://' + graphHost + '/graphql';
|
|
10
|
+
const appSyncKey = 'da2-zgeayo2qh5eo7cj6pmdwhwugze';
|
|
11
|
+
const resolverKey = 'pypIHG015k4ABHWbcI4G0a94F7cC0JDo1OynpAsG';
|
|
12
|
+
const statusQuery = `query GetVehicleStatus($vin: String!) {
|
|
13
|
+
getVehicleStatus(vin: $vin) { vin vehicleState { doors {
|
|
14
|
+
driverSide { lock { status } }
|
|
15
|
+
passengerSide { lock { status } }
|
|
16
|
+
rearDriverSide { lock { status } }
|
|
17
|
+
rearPassengerSide { lock { status } }
|
|
18
|
+
} } }
|
|
19
|
+
}`;
|
|
20
|
+
const subscribeQuery = `subscription ReceiveRemoteCommandStatus($vin: String!) {
|
|
21
|
+
onPostRemoteCallback(vin: $vin) { appRequestNo status vin command commandEnded }
|
|
22
|
+
}`;
|
|
23
|
+
const commandQuery = `mutation SendRemoteCommand($command: String!, $autoFixCommands: [String]!) {
|
|
24
|
+
executeRemoteCommand(commandInputBody: { command: $command, autofixCommands: $autoFixCommands }) {
|
|
25
|
+
payload { requestNo correlationId returnCode }
|
|
26
|
+
status { messages { responseCode } }
|
|
27
|
+
}
|
|
28
|
+
}`;
|
|
29
|
+
|
|
30
|
+
const commands = {
|
|
31
|
+
lock: { name: 'door-lock', code: 'DL', value: 1 },
|
|
32
|
+
unlock: { name: 'door-unlock', code: 'DL', value: 2 },
|
|
33
|
+
start: { name: 'engine-start', code: 'RES', value: 1 },
|
|
34
|
+
};
|
|
35
|
+
const doors = new Set(['driver side door', 'passenger side door', 'driver side rear door', 'passenger side rear door']);
|
|
36
|
+
const graphDoors = ['driverSide', 'passengerSide', 'rearDriverSide', 'rearPassengerSide'];
|
|
37
|
+
|
|
38
|
+
function lockValue(value) {
|
|
39
|
+
switch (String(value).toLowerCase()) {
|
|
40
|
+
case 'lock':
|
|
41
|
+
case 'locked': return true;
|
|
42
|
+
case 'unlock':
|
|
43
|
+
case 'unlocked': return false;
|
|
44
|
+
default: return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function combineLocks(values) {
|
|
49
|
+
if (values.includes(false)) return false;
|
|
50
|
+
return values.includes(true) ? true : null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function restDoorLocks(status) {
|
|
54
|
+
const categories = status?.vehicleStatus ?? status?.status?.vehicleStatus;
|
|
55
|
+
if (!Array.isArray(categories)) return null;
|
|
56
|
+
const locks = [];
|
|
57
|
+
for (const category of categories) {
|
|
58
|
+
if (!Array.isArray(category?.sections)) continue;
|
|
59
|
+
for (const section of category.sections) {
|
|
60
|
+
if (!doors.has(`${category.category} ${section?.section}`.toLowerCase())
|
|
61
|
+
|| !Array.isArray(section?.values)) continue;
|
|
62
|
+
const entries = section.values.filter((item) => item && lockValue(item.value) !== null);
|
|
63
|
+
const active = entries.filter((item) => item.status === 1);
|
|
64
|
+
const fallback = entries.filter((item) => lockValue(item.value) || !Object.hasOwn(item, 'status'));
|
|
65
|
+
const candidates = new Set((active.length ? active : fallback).map((item) => lockValue(item.value)));
|
|
66
|
+
if (candidates.size === 1) locks.push(candidates.values().next().value);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return combineLocks(locks);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function checkCommand(vehicle, action) {
|
|
73
|
+
const remote = vehicle.remoteSubscriptionStatus;
|
|
74
|
+
const status = vehicle.subscriptionStatus;
|
|
75
|
+
const active = typeof remote === 'string' && remote
|
|
76
|
+
? remote.toUpperCase() === 'ACTIVE'
|
|
77
|
+
: typeof status === 'string' && status
|
|
78
|
+
? ['ACTIVE', 'SUBSCRIBED'].includes(status.toUpperCase())
|
|
79
|
+
: vehicle.remoteSubscriptionExists === true;
|
|
80
|
+
if (!active || [10, 11].includes(Number(vehicle.remoteDisplay))
|
|
81
|
+
|| (vehicle.features && vehicle.features.remoteCommands !== 1)) {
|
|
82
|
+
throw new Error('Toyota reports remote commands unavailable for this vehicle.');
|
|
83
|
+
}
|
|
84
|
+
const keys = action === 'start'
|
|
85
|
+
? ['estartEnabled', 'estartStopCapable', 'remoteEngineStartStop']
|
|
86
|
+
: ['dlockUnlockCapable', 'doorLockUnlockCapable'];
|
|
87
|
+
const reported = keys.flatMap((key) => [
|
|
88
|
+
vehicle.remoteServiceCapabilities?.[key], vehicle.extendedCapabilities?.[key],
|
|
89
|
+
]).find((value) => typeof value === 'boolean');
|
|
90
|
+
if (reported === false || (['NG86', 'GR86'].includes(vehicle.generation) && reported !== true)) {
|
|
91
|
+
throw new Error('Toyota reports this command is unsupported for this vehicle.');
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function authenticatedHeaders(session, vehicle = {}) {
|
|
96
|
+
return {
|
|
97
|
+
'Content-Type': 'application/json',
|
|
98
|
+
Authorization: 'Bearer ' + session.tokens.access_token,
|
|
99
|
+
'X-GUID': session.tokens.guid,
|
|
100
|
+
'X-APPBRAND': 'T',
|
|
101
|
+
'X-APPVERSION': '3.5.0',
|
|
102
|
+
'X-OSNAME': 'Android',
|
|
103
|
+
'X-OSVERSION': '14',
|
|
104
|
+
'X-LOCALE': 'en-US',
|
|
105
|
+
'User-Agent': 'okhttp/5.3.2',
|
|
106
|
+
'X-DEVICE-TIMEZONE': Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
107
|
+
'X-CORRELATIONID': randomUUID(),
|
|
108
|
+
'X-CHANNEL': 'ONEAPP',
|
|
109
|
+
'X-BRAND': vehicle.brand || 'T',
|
|
110
|
+
'x-region': vehicle.region || 'US',
|
|
111
|
+
Accept: 'application/json',
|
|
112
|
+
...(vehicle.vin && { VIN: vehicle.vin }),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
class ToyotaClient {
|
|
117
|
+
constructor(sessionFile, { fetch = globalThis.fetch, WebSocket = globalThis.WebSocket } = {}) {
|
|
118
|
+
this.fetch = fetch;
|
|
119
|
+
this.WebSocket = WebSocket;
|
|
120
|
+
this.session = new Session(sessionFile, fetch);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async api(url, method, vehicle, body, graphRequest = false) {
|
|
124
|
+
let session = await this.session.get();
|
|
125
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
126
|
+
const headers = authenticatedHeaders(session, vehicle);
|
|
127
|
+
headers['X-API-KEY'] = graphRequest ? appSyncKey : resolverKey;
|
|
128
|
+
if (graphRequest) {
|
|
129
|
+
headers['x-resolver-api-key'] = resolverKey;
|
|
130
|
+
headers['x-deviceid'] = session.device_id;
|
|
131
|
+
if (vehicle?.backdoorType) headers.backdoorType = vehicle.backdoorType;
|
|
132
|
+
} else if (vehicle?.generation) {
|
|
133
|
+
headers['X-GENERATION'] = vehicle.generation;
|
|
134
|
+
}
|
|
135
|
+
const response = await request(this.fetch, url, {
|
|
136
|
+
method: body ? 'POST' : 'GET', headers, body: body && JSON.stringify(body),
|
|
137
|
+
});
|
|
138
|
+
const data = await response.json().catch(() => null);
|
|
139
|
+
const errors = Array.isArray(data?.errors) ? data.errors : [];
|
|
140
|
+
const authRejected = response.status === 401 || errors.some((error) => (
|
|
141
|
+
['APIGW-403', 'APPSYNC-AUTH-403'].includes(error?.errorType ?? error?.extensions?.code)
|
|
142
|
+
|| /^unauthorized$|jwt expired/i.test(error?.message ?? '')
|
|
143
|
+
));
|
|
144
|
+
if (authRejected && attempt === 0) {
|
|
145
|
+
session = await this.session.get(session.tokens.access_token);
|
|
146
|
+
if (method === 'read') continue;
|
|
147
|
+
throw new Error('Toyota refreshed your session. Check the Toyota app before retrying.');
|
|
148
|
+
}
|
|
149
|
+
if (!response.ok || errors.length || !data) {
|
|
150
|
+
throw new Error(`Toyota rejected the request (HTTP ${response.status}).`);
|
|
151
|
+
}
|
|
152
|
+
return graphRequest ? data.data : data.payload ?? data;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async vehicles() {
|
|
157
|
+
const vehicles = await this.api(gateway + '/oneapi/v2/vehicle/guid', 'read');
|
|
158
|
+
if (!Array.isArray(vehicles)) throw new Error('Toyota did not return a vehicle list.');
|
|
159
|
+
return vehicles;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async run(vin, action) {
|
|
163
|
+
const matches = (await this.vehicles()).filter((vehicle) => vehicle?.vin === vin);
|
|
164
|
+
if (matches.length !== 1) throw new Error('The configured VIN was not found on your Toyota account.');
|
|
165
|
+
const vehicle = { ...matches[0], generation: String(matches[0].generation ?? '').trim().toUpperCase() };
|
|
166
|
+
const appSync = ['24MM', '26BEV'].includes(vehicle.generation);
|
|
167
|
+
const route = ['21MM', 'NG86', 'GR86'].includes(vehicle.generation);
|
|
168
|
+
const legacy = vehicle.generation === '17CY';
|
|
169
|
+
if (!appSync && !route && !legacy && vehicle.generation !== '17CYPLUS') {
|
|
170
|
+
throw new Error('Toyota reported an unsupported telematics generation.');
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (action === 'status') {
|
|
174
|
+
if (appSync) {
|
|
175
|
+
const data = await this.api(graph, 'read', { ...vehicle, backdoorType: vehicle.backdoorType || 'hatch' }, {
|
|
176
|
+
operationName: 'GetVehicleStatus', query: statusQuery, variables: { vin },
|
|
177
|
+
}, true);
|
|
178
|
+
const reported = data?.getVehicleStatus;
|
|
179
|
+
if (reported?.vin && reported.vin !== vin) throw new Error('Toyota returned status for a different vehicle.');
|
|
180
|
+
const states = reported?.vehicleState?.doors;
|
|
181
|
+
return { locked: combineLocks(graphDoors.map((door) => lockValue(states?.[door]?.lock?.status))) };
|
|
182
|
+
}
|
|
183
|
+
const path = route ? '/v1/remote/route/status'
|
|
184
|
+
: legacy ? '/oneapi/v2/legacy/remote/status' : '/oneapi/v1/global/remote/status';
|
|
185
|
+
return { locked: restDoorLocks(await this.api(gateway + path, 'read', vehicle)) };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (!Object.hasOwn(commands, action)) throw new Error('Unsupported Toyota command.');
|
|
189
|
+
checkCommand(vehicle, action);
|
|
190
|
+
const command = commands[action];
|
|
191
|
+
if (appSync) return this.appSyncCommand(vehicle, command.name);
|
|
192
|
+
|
|
193
|
+
const path = route ? '/v1/remote/route/command'
|
|
194
|
+
: legacy ? '/oneapi/v1/legacy/remote/command' : '/oneapi/v1/global/remote/command';
|
|
195
|
+
let body = { command: command.name };
|
|
196
|
+
if (route) body.autoFixPopup = false;
|
|
197
|
+
if (legacy) {
|
|
198
|
+
const session = await this.session.get();
|
|
199
|
+
body = {
|
|
200
|
+
vin, guid: session.tokens.guid, deviceId: session.device_id, deviceType: 'Android',
|
|
201
|
+
command: { code: command.code, value: command.value },
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
const result = await this.api(gateway + path, 'command', vehicle, body);
|
|
205
|
+
if (result.returnCode && result.returnCode !== 'ONE-RES-10000') {
|
|
206
|
+
throw new Error('Toyota refused the remote command.');
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async appSyncCommand(vehicle, command) {
|
|
211
|
+
const { vin } = vehicle;
|
|
212
|
+
const session = await this.session.get();
|
|
213
|
+
const authorization = {
|
|
214
|
+
host: graphHost, 'x-api-key': appSyncKey,
|
|
215
|
+
Authorization: 'Bearer ' + session.tokens.access_token,
|
|
216
|
+
'x-channel': 'ONEAPP', 'X-BRAND': 'T', 'X-APPBRAND': 'T',
|
|
217
|
+
'x-region': vehicle.region || 'US', vin, 'x-guid': session.tokens.guid,
|
|
218
|
+
'x-deviceid': session.device_id,
|
|
219
|
+
};
|
|
220
|
+
const query = new URLSearchParams({
|
|
221
|
+
header: Buffer.from(JSON.stringify(authorization)).toString('base64'),
|
|
222
|
+
payload: 'e30=',
|
|
223
|
+
});
|
|
224
|
+
const socket = new this.WebSocket('wss://' + graphHost + '/graphql/realtime?' + query, 'graphql-ws');
|
|
225
|
+
const abort = new AbortController();
|
|
226
|
+
const disconnected = () => abort.abort();
|
|
227
|
+
socket.addEventListener('error', disconnected, { once: true });
|
|
228
|
+
socket.addEventListener('close', disconnected, { once: true });
|
|
229
|
+
const messages = on(socket, 'message', { signal: abort.signal });
|
|
230
|
+
const id = randomUUID();
|
|
231
|
+
let timer = setTimeout(disconnected, 15_000);
|
|
232
|
+
const send = (message) => socket.send(JSON.stringify(message));
|
|
233
|
+
const waitFor = async (matches) => {
|
|
234
|
+
for (;;) {
|
|
235
|
+
const { value } = await messages.next();
|
|
236
|
+
const message = JSON.parse(value[0].data);
|
|
237
|
+
if (['connection_error', 'error'].includes(message.type)) {
|
|
238
|
+
throw new Error('Toyota rejected the remote command subscription.');
|
|
239
|
+
}
|
|
240
|
+
if (matches(message)) return;
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
try {
|
|
244
|
+
await once(socket, 'open', { signal: abort.signal });
|
|
245
|
+
send({ type: 'connection_init' });
|
|
246
|
+
await waitFor(({ type }) => type === 'connection_ack');
|
|
247
|
+
send({
|
|
248
|
+
id, type: 'start',
|
|
249
|
+
payload: {
|
|
250
|
+
data: JSON.stringify({ query: subscribeQuery, variables: { vin } }),
|
|
251
|
+
extensions: { authorization },
|
|
252
|
+
},
|
|
253
|
+
});
|
|
254
|
+
await waitFor((message) => message.type === 'start_ack' && message.id === id);
|
|
255
|
+
clearTimeout(timer);
|
|
256
|
+
timer = setTimeout(disconnected, 80_000);
|
|
257
|
+
const data = await this.api(graph, 'command', vehicle, {
|
|
258
|
+
operationName: 'SendRemoteCommand', query: commandQuery,
|
|
259
|
+
variables: { command, autoFixCommands: [] },
|
|
260
|
+
}, true);
|
|
261
|
+
const execution = data?.executeRemoteCommand?.payload;
|
|
262
|
+
if (!execution?.correlationId) throw new Error('Toyota did not accept the remote command.');
|
|
263
|
+
await waitFor((message) => {
|
|
264
|
+
if (message.type !== 'data' || message.id !== id) return false;
|
|
265
|
+
const update = message.payload?.data?.onPostRemoteCallback;
|
|
266
|
+
if (update?.vin !== vin || (execution.requestNo != null && update.appRequestNo != null
|
|
267
|
+
&& String(execution.requestNo) !== String(update.appRequestNo))) return false;
|
|
268
|
+
if (update.command && update.command !== command && update.appRequestNo == null) return false;
|
|
269
|
+
const state = String(update.status).toLowerCase();
|
|
270
|
+
if (state === 'completed') return true;
|
|
271
|
+
if (state === 'in_progress' && !update.commandEnded) return false;
|
|
272
|
+
throw new Error('Toyota did not complete the remote command.');
|
|
273
|
+
});
|
|
274
|
+
} catch (error) {
|
|
275
|
+
if (abort.signal.aborted) throw new Error('Toyota did not confirm the command. Check the Toyota app before retrying.');
|
|
276
|
+
if (error instanceof SyntaxError) throw new Error('Toyota returned an invalid command response.');
|
|
277
|
+
throw error;
|
|
278
|
+
} finally {
|
|
279
|
+
clearTimeout(timer);
|
|
280
|
+
await messages.return();
|
|
281
|
+
socket.close();
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
module.exports = { ToyotaClient };
|
|
287
|
+
|
package/requirements.txt
DELETED
package/toyota.py
DELETED
|
@@ -1,133 +0,0 @@
|
|
|
1
|
-
"""Run the upstream Toyota client independently of Home Assistant."""
|
|
2
|
-
import argparse
|
|
3
|
-
import asyncio
|
|
4
|
-
from getpass import getpass
|
|
5
|
-
import json
|
|
6
|
-
import logging
|
|
7
|
-
import os
|
|
8
|
-
from pathlib import Path
|
|
9
|
-
import sys
|
|
10
|
-
import tempfile
|
|
11
|
-
from types import ModuleType
|
|
12
|
-
|
|
13
|
-
COMMANDS = {"lock": "DoorLock", "unlock": "DoorUnlock", "start": "EngineStart"}
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
def save_session(path, tokens, device_id):
|
|
17
|
-
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
18
|
-
with tempfile.NamedTemporaryFile(
|
|
19
|
-
dir=path.parent, mode="w", encoding="utf-8", delete=False
|
|
20
|
-
) as stream:
|
|
21
|
-
temporary = Path(stream.name)
|
|
22
|
-
try:
|
|
23
|
-
json.dump({"tokens": tokens, "device_id": device_id}, stream)
|
|
24
|
-
stream.close()
|
|
25
|
-
temporary.replace(path)
|
|
26
|
-
finally:
|
|
27
|
-
temporary.unlink(missing_ok=True)
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
def load_client_modules(directory):
|
|
31
|
-
# The upstream package initializer imports Home Assistant. Its transport
|
|
32
|
-
# and vehicle modules can be imported through their own package namespace.
|
|
33
|
-
if not (directory / "client.py").is_file():
|
|
34
|
-
raise FileNotFoundError("Set the Toyota client directory.")
|
|
35
|
-
package = ModuleType("_homebridge_toyota_client")
|
|
36
|
-
package.__path__ = [str(directory)]
|
|
37
|
-
sys.modules[package.__name__] = package
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
async def run(args):
|
|
41
|
-
from _homebridge_toyota_client.auth import ToyotaOneAuth
|
|
42
|
-
from _homebridge_toyota_client.client import ToyotaOneClient
|
|
43
|
-
from _homebridge_toyota_client.vehicle import RemoteRequestCommand
|
|
44
|
-
from _homebridge_toyota_client.vehicle_discovery import get_vehicles
|
|
45
|
-
|
|
46
|
-
if args.action == "login":
|
|
47
|
-
if not sys.stdin.isatty():
|
|
48
|
-
raise RuntimeError("Run login interactively.")
|
|
49
|
-
auth = ToyotaOneAuth()
|
|
50
|
-
user = input("Toyota account email: ").strip()
|
|
51
|
-
password = getpass("Toyota password (leave empty for OTP-only login): ")
|
|
52
|
-
code = await auth.authorize(user, password)
|
|
53
|
-
if isinstance(code, dict):
|
|
54
|
-
code = await auth.authorize(user, password, getpass("Toyota verification code: "))
|
|
55
|
-
if not isinstance(code, str) or not code:
|
|
56
|
-
raise RuntimeError("Toyota did not issue an authorization code.")
|
|
57
|
-
await auth.request_tokens(code)
|
|
58
|
-
save_session(args.session, auth.get_tokens(), auth.get_device_id())
|
|
59
|
-
return {"signedIn": True}
|
|
60
|
-
|
|
61
|
-
try:
|
|
62
|
-
persisted = json.loads(args.session.read_text(encoding="utf-8"))
|
|
63
|
-
auth = ToyotaOneAuth()
|
|
64
|
-
auth.set_tokens(persisted["tokens"])
|
|
65
|
-
auth.set_device_id(persisted["device_id"])
|
|
66
|
-
except (OSError, ValueError, TypeError, KeyError):
|
|
67
|
-
fail("SESSION")
|
|
68
|
-
|
|
69
|
-
# Keep refresh-token rotation durable before sending a vehicle command.
|
|
70
|
-
await auth.check_tokens()
|
|
71
|
-
save_session(args.session, auth.get_tokens(), auth.get_device_id())
|
|
72
|
-
auth = ToyotaOneAuth(
|
|
73
|
-
initial_tokens=auth.get_tokens(),
|
|
74
|
-
callback=lambda tokens: save_session(args.session, tokens, auth.get_device_id()),
|
|
75
|
-
)
|
|
76
|
-
auth.set_device_id(persisted["device_id"])
|
|
77
|
-
client = ToyotaOneClient(auth=auth)
|
|
78
|
-
if args.action == "vehicles":
|
|
79
|
-
return [
|
|
80
|
-
{key: vehicle.get(key) for key in ("modelName", "modelYear", "vin", "generation")}
|
|
81
|
-
for vehicle in await client.get_user_vehicle_list()
|
|
82
|
-
]
|
|
83
|
-
|
|
84
|
-
# Restrict discovery to the selected VIN before the upstream status reads.
|
|
85
|
-
class SelectedVehicleClient(ToyotaOneClient):
|
|
86
|
-
async def get_user_vehicle_list(self):
|
|
87
|
-
vehicles = await super().get_user_vehicle_list()
|
|
88
|
-
if not isinstance(vehicles, list):
|
|
89
|
-
raise RuntimeError("Toyota returned no vehicle list.")
|
|
90
|
-
return [
|
|
91
|
-
row for row in vehicles
|
|
92
|
-
if isinstance(row, dict) and row.get("vin") == args.vin
|
|
93
|
-
]
|
|
94
|
-
|
|
95
|
-
vehicles = await get_vehicles(SelectedVehicleClient(auth=auth))
|
|
96
|
-
if len(vehicles) != 1:
|
|
97
|
-
fail("VEHICLE")
|
|
98
|
-
vehicle = vehicles[0]
|
|
99
|
-
if args.action == "status":
|
|
100
|
-
return {"locked": vehicle.doors_locked}
|
|
101
|
-
await vehicle.send_command(RemoteRequestCommand[COMMANDS[args.action]])
|
|
102
|
-
return {"submitted": True}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
def fail(category):
|
|
106
|
-
print(f"TOYOTA_{category}", file=sys.stderr)
|
|
107
|
-
raise SystemExit(1)
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
def main():
|
|
111
|
-
parser = argparse.ArgumentParser()
|
|
112
|
-
parser.add_argument("client_directory", type=Path)
|
|
113
|
-
parser.add_argument("session", type=Path)
|
|
114
|
-
parser.add_argument("action", choices=["login", "vehicles", "status", *COMMANDS])
|
|
115
|
-
parser.add_argument("vin", nargs="?")
|
|
116
|
-
args = parser.parse_args()
|
|
117
|
-
if args.action in {"status", *COMMANDS} and not args.vin:
|
|
118
|
-
parser.error("This operation requires a VIN.")
|
|
119
|
-
logging.disable(logging.CRITICAL)
|
|
120
|
-
if os.name != "nt":
|
|
121
|
-
os.umask(0o077)
|
|
122
|
-
try:
|
|
123
|
-
load_client_modules(args.client_directory.resolve())
|
|
124
|
-
result = asyncio.run(run(args))
|
|
125
|
-
except (ImportError, FileNotFoundError):
|
|
126
|
-
fail("CLIENT")
|
|
127
|
-
except Exception:
|
|
128
|
-
fail("SESSION" if args.action == "login" else "COMMAND")
|
|
129
|
-
print(json.dumps(result))
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
if __name__ == "__main__":
|
|
133
|
-
main()
|