node-red-contrib-cardata 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +172 -2
- package/README.nl.md +177 -0
- package/examples/cardata-basic.json +136 -0
- package/examples/cardata-victron.json +200 -0
- package/lib/cardata-client.js +271 -0
- package/lib/cardata-parse.js +155 -0
- package/lib/cardata-trips.js +248 -0
- package/lib/geo.js +12 -0
- package/lib/token-file.js +36 -0
- package/nodes/cardata-account.html +154 -0
- package/nodes/cardata-account.js +153 -0
- package/nodes/cardata-stream.html +56 -0
- package/nodes/cardata-stream.js +157 -0
- package/nodes/cardata-target.html +55 -0
- package/nodes/cardata-target.js +48 -0
- package/nodes/cardata-trips.html +54 -0
- package/nodes/cardata-trips.js +60 -0
- package/nodes/locales/en-US/cardata-account.json +45 -0
- package/nodes/locales/en-US/cardata-stream.json +24 -0
- package/nodes/locales/en-US/cardata-target.json +19 -0
- package/nodes/locales/en-US/cardata-trips.json +18 -0
- package/nodes/locales/nl/cardata-account.json +45 -0
- package/nodes/locales/nl/cardata-stream.json +24 -0
- package/nodes/locales/nl/cardata-target.json +19 -0
- package/nodes/locales/nl/cardata-trips.json +18 -0
- package/package.json +51 -4
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"id": "cardata-full-tab",
|
|
4
|
+
"type": "tab",
|
|
5
|
+
"label": "CarData + Victron EV",
|
|
6
|
+
"disabled": false,
|
|
7
|
+
"info": "Complete flow: MINI/BMW CarData into a virtual EV device in VRM, with the charge target and trip tracking.\n\n1. Open the cardata-account node: client ID + VIN, deploy once, then Log in and Create container.\n2. Open the Electric vehicle node (victron-virtual): fill in the same VIN and the battery capacity in kWh (CarData has no capacity field), check the brand, and pick your EV charger (links the car to the charger).\n\nNeeds @victronenergy/node-red-contrib-victron (preinstalled on Venus OS) for the victron-virtual node."
|
|
8
|
+
},
|
|
9
|
+
{
|
|
10
|
+
"id": "cardata-full-account",
|
|
11
|
+
"type": "cardata-account",
|
|
12
|
+
"name": "",
|
|
13
|
+
"clientId": "",
|
|
14
|
+
"vin": "",
|
|
15
|
+
"containerId": "",
|
|
16
|
+
"homeLat": "",
|
|
17
|
+
"homeLon": "",
|
|
18
|
+
"homeRadiusM": 150
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
"id": "cardata-full-stream",
|
|
22
|
+
"type": "cardata-stream",
|
|
23
|
+
"z": "cardata-full-tab",
|
|
24
|
+
"name": "",
|
|
25
|
+
"account": "cardata-full-account",
|
|
26
|
+
"x": 200,
|
|
27
|
+
"y": 160,
|
|
28
|
+
"wires": [
|
|
29
|
+
[
|
|
30
|
+
"18d9be2079999b07",
|
|
31
|
+
"cardata-full-trips"
|
|
32
|
+
],
|
|
33
|
+
[
|
|
34
|
+
"cardata-full-dbg-unknown"
|
|
35
|
+
]
|
|
36
|
+
]
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
"id": "cardata-full-target",
|
|
40
|
+
"type": "cardata-target",
|
|
41
|
+
"z": "cardata-full-tab",
|
|
42
|
+
"name": "",
|
|
43
|
+
"account": "cardata-full-account",
|
|
44
|
+
"intervalMinutes": 60,
|
|
45
|
+
"x": 200,
|
|
46
|
+
"y": 260,
|
|
47
|
+
"wires": [
|
|
48
|
+
[
|
|
49
|
+
"18d9be2079999b07"
|
|
50
|
+
]
|
|
51
|
+
]
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"id": "18d9be2079999b07",
|
|
55
|
+
"type": "victron-virtual",
|
|
56
|
+
"name": "Electric vehicle",
|
|
57
|
+
"device": "ev",
|
|
58
|
+
"outputs": 1,
|
|
59
|
+
"default_values": true,
|
|
60
|
+
"ev_vin": "",
|
|
61
|
+
"ev_battery_capacity": "",
|
|
62
|
+
"ev_evcs_device_instance": null,
|
|
63
|
+
"evcs_nrofphases": 1,
|
|
64
|
+
"start_disconnected": false,
|
|
65
|
+
"acload_position": 0,
|
|
66
|
+
"acload_nrofphases": 1,
|
|
67
|
+
"acload_phasesetting": 1,
|
|
68
|
+
"acload_auto_energy": true,
|
|
69
|
+
"enable_s2support": false,
|
|
70
|
+
"s2_measurement_type": "L1",
|
|
71
|
+
"heatpump_position": 0,
|
|
72
|
+
"heatpump_nrofphases": 1,
|
|
73
|
+
"heatpump_phasesetting": 1,
|
|
74
|
+
"heatpump_auto_energy": true,
|
|
75
|
+
"battery_capacity": 25,
|
|
76
|
+
"include_battery_temperature": false,
|
|
77
|
+
"battery_voltage_preset": "24",
|
|
78
|
+
"battery_voltage_custom": 24,
|
|
79
|
+
"generator_type": "ac",
|
|
80
|
+
"generator_nrofphases": 1,
|
|
81
|
+
"include_engine_hours": false,
|
|
82
|
+
"include_starter_voltage": false,
|
|
83
|
+
"include_history_energy": false,
|
|
84
|
+
"generator_grid_meter_only": false,
|
|
85
|
+
"grid_nrofphases": 1,
|
|
86
|
+
"energymeter_role": "",
|
|
87
|
+
"energymeter_position": 0,
|
|
88
|
+
"energymeter_nrofphases": 1,
|
|
89
|
+
"energymeter_phasesetting": 1,
|
|
90
|
+
"include_motor_temp": false,
|
|
91
|
+
"include_controller_temp": false,
|
|
92
|
+
"include_coolant_temp": false,
|
|
93
|
+
"include_motor_rpm": true,
|
|
94
|
+
"include_motor_direction": true,
|
|
95
|
+
"position": 0,
|
|
96
|
+
"pvinverter_nrofphases": 1,
|
|
97
|
+
"pvinverter_auto_energy": true,
|
|
98
|
+
"switch_1_type": 1,
|
|
99
|
+
"switch_1_min": 0,
|
|
100
|
+
"switch_1_max": "",
|
|
101
|
+
"switch_1_initial": 0,
|
|
102
|
+
"switch_1_label": "",
|
|
103
|
+
"switch_1_unit": "",
|
|
104
|
+
"switch_1_step": 1,
|
|
105
|
+
"switch_1_customname": "",
|
|
106
|
+
"switch_1_group": "",
|
|
107
|
+
"switch_1_include_measurement": false,
|
|
108
|
+
"switch_1_rgb_color_wheel": false,
|
|
109
|
+
"switch_1_cct_wheel": false,
|
|
110
|
+
"switch_1_rgb_white_dimmer": false,
|
|
111
|
+
"switch_1_passthrough_mode": "auto_only",
|
|
112
|
+
"fluid_type": 0,
|
|
113
|
+
"include_tank_battery": false,
|
|
114
|
+
"include_tank_temperature": false,
|
|
115
|
+
"tank_battery_voltage": 3.3,
|
|
116
|
+
"tank_capacity": 0.2,
|
|
117
|
+
"auto_aggregate": false,
|
|
118
|
+
"pulsemeter_multiplier": 0.001,
|
|
119
|
+
"temperature_type": 2,
|
|
120
|
+
"include_humidity": false,
|
|
121
|
+
"include_pressure": false,
|
|
122
|
+
"include_temp_battery": false,
|
|
123
|
+
"temp_battery_voltage": 3.3,
|
|
124
|
+
"z": "cardata-full-tab",
|
|
125
|
+
"x": 620,
|
|
126
|
+
"y": 200,
|
|
127
|
+
"wires": [
|
|
128
|
+
[]
|
|
129
|
+
],
|
|
130
|
+
"ev_brand": "MINI"
|
|
131
|
+
},
|
|
132
|
+
{
|
|
133
|
+
"id": "cardata-full-trips",
|
|
134
|
+
"type": "cardata-trips",
|
|
135
|
+
"z": "cardata-full-tab",
|
|
136
|
+
"name": "",
|
|
137
|
+
"filePath": "",
|
|
138
|
+
"x": 200,
|
|
139
|
+
"y": 380,
|
|
140
|
+
"wires": [
|
|
141
|
+
[
|
|
142
|
+
"cardata-full-dbg-trip"
|
|
143
|
+
],
|
|
144
|
+
[
|
|
145
|
+
"cardata-full-dbg-inprogress"
|
|
146
|
+
]
|
|
147
|
+
]
|
|
148
|
+
},
|
|
149
|
+
{
|
|
150
|
+
"id": "cardata-full-dbg-unknown",
|
|
151
|
+
"type": "debug",
|
|
152
|
+
"z": "cardata-full-tab",
|
|
153
|
+
"name": "unknown fields",
|
|
154
|
+
"active": true,
|
|
155
|
+
"tosidebar": true,
|
|
156
|
+
"console": false,
|
|
157
|
+
"tostatus": false,
|
|
158
|
+
"complete": "payload",
|
|
159
|
+
"targetType": "msg",
|
|
160
|
+
"statusVal": "",
|
|
161
|
+
"statusType": "auto",
|
|
162
|
+
"x": 480,
|
|
163
|
+
"y": 100,
|
|
164
|
+
"wires": []
|
|
165
|
+
},
|
|
166
|
+
{
|
|
167
|
+
"id": "cardata-full-dbg-trip",
|
|
168
|
+
"type": "debug",
|
|
169
|
+
"z": "cardata-full-tab",
|
|
170
|
+
"name": "completed trip",
|
|
171
|
+
"active": true,
|
|
172
|
+
"tosidebar": true,
|
|
173
|
+
"console": false,
|
|
174
|
+
"tostatus": true,
|
|
175
|
+
"complete": "payload",
|
|
176
|
+
"targetType": "msg",
|
|
177
|
+
"statusVal": "payload.km",
|
|
178
|
+
"statusType": "jsonata",
|
|
179
|
+
"x": 480,
|
|
180
|
+
"y": 360,
|
|
181
|
+
"wires": []
|
|
182
|
+
},
|
|
183
|
+
{
|
|
184
|
+
"id": "cardata-full-dbg-inprogress",
|
|
185
|
+
"type": "debug",
|
|
186
|
+
"z": "cardata-full-tab",
|
|
187
|
+
"name": "trip in progress",
|
|
188
|
+
"active": false,
|
|
189
|
+
"tosidebar": true,
|
|
190
|
+
"console": false,
|
|
191
|
+
"tostatus": false,
|
|
192
|
+
"complete": "payload",
|
|
193
|
+
"targetType": "msg",
|
|
194
|
+
"statusVal": "",
|
|
195
|
+
"statusType": "auto",
|
|
196
|
+
"x": 480,
|
|
197
|
+
"y": 420,
|
|
198
|
+
"wires": []
|
|
199
|
+
}
|
|
200
|
+
]
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
// BMW/MINI CarData: OAuth (Device Code Flow), tokenvernieuwing, en de REST-API voor het
|
|
4
|
+
// laaddoel. Geen Node-RED-kennis hier — alleen fetch/crypto, zoals lib/peblar-client.js
|
|
5
|
+
// in node-red-peblar alleen http/https gebruikt. De MQTT-verbinding zelf (die wél
|
|
6
|
+
// node.send/node.status nodig heeft) zit in nodes/cardata-stream.js; deze klasse levert
|
|
7
|
+
// daarvoor alleen de credentials en het topic.
|
|
8
|
+
|
|
9
|
+
const crypto = require('node:crypto')
|
|
10
|
+
const { EventEmitter } = require('node:events')
|
|
11
|
+
|
|
12
|
+
const AUTH_BASE = 'https://customer.bmwgroup.com/gcdm/oauth'
|
|
13
|
+
const API_BASE = 'https://api-cardata.bmwgroup.com'
|
|
14
|
+
const STREAM_HOST = 'customer.streaming-cardata.bmwgroup.com'
|
|
15
|
+
const STREAM_PORT = 9000
|
|
16
|
+
|
|
17
|
+
// BMW's broker sluit een verbinding na ongeveer 60 s zonder verkeer. Staat de keepalive
|
|
18
|
+
// ook op 60, dan valt de eerste ping precies op die grens en ligt de verbinding er elke
|
|
19
|
+
// minuut uit. MQTT v5 is nodig om uberhaupt te zien waarom hij dichtgaat; v3.1.1 geeft
|
|
20
|
+
// een nietszeggende verbreking. sessionExpiry blijft leeg: met een hoge waarde blijft
|
|
21
|
+
// elke afgebroken sessie meetellen en blokkeert hij alle nieuwe verbindingen.
|
|
22
|
+
const STREAM_KEEPALIVE_S = 25
|
|
23
|
+
const STREAM_PROTOCOL_VERSION = 5
|
|
24
|
+
|
|
25
|
+
class CardataAuthError extends Error {
|
|
26
|
+
constructor (message, extra) {
|
|
27
|
+
super(message)
|
|
28
|
+
this.name = 'CardataAuthError'
|
|
29
|
+
Object.assign(this, extra)
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function form (fields) {
|
|
34
|
+
return new URLSearchParams(fields)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function postForm (url, fields) {
|
|
38
|
+
const res = await fetch(url, {
|
|
39
|
+
method: 'POST',
|
|
40
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
|
|
41
|
+
body: form(fields)
|
|
42
|
+
})
|
|
43
|
+
const data = await res.json().catch(() => ({}))
|
|
44
|
+
return { status: res.status, data }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// BMW staat 50 REST-aanroepen per dag toe; 30 minuten is 48 per dag, de ondergrens.
|
|
48
|
+
const MIN_TARGET_INTERVAL_MIN = 30
|
|
49
|
+
|
|
50
|
+
/** Een te klein, negatief of onleesbaar interval valt terug op de ondergrens (of de standaard 60). */
|
|
51
|
+
function clampIntervalMinutes (value) {
|
|
52
|
+
const n = Number(value)
|
|
53
|
+
if (!Number.isFinite(n) || n === 0) return 60
|
|
54
|
+
return Math.max(MIN_TARGET_INTERVAL_MIN, n)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Wachttijd voor poging `attempt` (0-based): 5 s, 10 s, 20 s, … met een plafond van 5 minuten. */
|
|
58
|
+
function nextBackoffMs (attempt) {
|
|
59
|
+
return Math.min(5 * 60 * 1000, 5000 * 2 ** Math.max(0, attempt))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
class CardataClient extends EventEmitter {
|
|
63
|
+
constructor ({ clientId, vin, containerId, tokens, authBase, apiBase } = {}) {
|
|
64
|
+
super()
|
|
65
|
+
this.clientId = clientId
|
|
66
|
+
this.vin = vin
|
|
67
|
+
this.containerId = containerId
|
|
68
|
+
this.tokens = tokens || null
|
|
69
|
+
// Per instantie overschrijfbaar zodat tests een lokale nepserver kunnen gebruiken.
|
|
70
|
+
this.authBase = authBase || AUTH_BASE
|
|
71
|
+
this.apiBase = apiBase || API_BASE
|
|
72
|
+
this._refreshTimer = null
|
|
73
|
+
this._retryTimer = null
|
|
74
|
+
this._refreshing = null
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Aangeroepen (door elke node die meeluistert) telkens als er nieuwe tokens zijn. */
|
|
78
|
+
onTokensUpdated (cb) {
|
|
79
|
+
this.on('tokens', cb)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
setTokens (tokens) {
|
|
83
|
+
this.tokens = tokens
|
|
84
|
+
this.emit('tokens', tokens)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
secondsLeft () {
|
|
88
|
+
if (!this.tokens) return -Infinity
|
|
89
|
+
return this.tokens.obtained_at + Number(this.tokens.expires_in || 3600) - Date.now() / 1000
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// --- Device Code Flow (inloggen) ------------------------------------------------------
|
|
93
|
+
|
|
94
|
+
static async startLogin (clientId, scopes, { authBase = AUTH_BASE } = {}) {
|
|
95
|
+
const verifier = crypto.randomBytes(48).toString('base64url')
|
|
96
|
+
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url')
|
|
97
|
+
const { status, data } = await postForm(`${authBase}/device/code`, {
|
|
98
|
+
client_id: clientId,
|
|
99
|
+
response_type: 'device_code',
|
|
100
|
+
scope: scopes,
|
|
101
|
+
code_challenge: challenge,
|
|
102
|
+
code_challenge_method: 'S256'
|
|
103
|
+
})
|
|
104
|
+
if (status !== 200 || !data.device_code) {
|
|
105
|
+
throw new CardataAuthError(`device code aanvragen mislukt (${status}): ${data.error || JSON.stringify(data)}`)
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
deviceCode: data.device_code,
|
|
109
|
+
userCode: data.user_code,
|
|
110
|
+
verificationUri: data.verification_uri,
|
|
111
|
+
intervalS: Number(data.interval || 5),
|
|
112
|
+
expiresInS: Number(data.expires_in || 300),
|
|
113
|
+
verifier
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Eén keer pollen; geeft { done:false } terug tijdens het wachten, of de tokens zodra ingelogd. */
|
|
118
|
+
static async pollLogin ({ clientId, deviceCode, verifier, authBase = AUTH_BASE }) {
|
|
119
|
+
const { status, data } = await postForm(`${authBase}/token`, {
|
|
120
|
+
client_id: clientId,
|
|
121
|
+
device_code: deviceCode,
|
|
122
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
|
|
123
|
+
code_verifier: verifier
|
|
124
|
+
})
|
|
125
|
+
if (status === 200 && data.id_token) {
|
|
126
|
+
return { done: true, tokens: Object.assign({}, data, { client_id: clientId, obtained_at: Date.now() / 1000 }) }
|
|
127
|
+
}
|
|
128
|
+
if (data.error === 'authorization_pending') return { done: false }
|
|
129
|
+
if (data.error === 'slow_down') return { done: false, slowDown: true }
|
|
130
|
+
throw new CardataAuthError(`inloggen mislukt: ${data.error || status} ${data.error_description || ''}`)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// --- Tokenvernieuwing ------------------------------------------------------------------
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Eén vernieuwing tegelijk: meerdere aanroepers (timer, retry, ensureFreshTokens) delen
|
|
137
|
+
* dezelfde lopende aanvraag. Anders draait de refresh-token tweemaal door en is de
|
|
138
|
+
* tweede aanvraag met de al ingewisselde token een 4xx.
|
|
139
|
+
*/
|
|
140
|
+
refresh () {
|
|
141
|
+
if (this._refreshing) return this._refreshing
|
|
142
|
+
this._refreshing = this._doRefresh().finally(() => { this._refreshing = null })
|
|
143
|
+
return this._refreshing
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async _doRefresh () {
|
|
147
|
+
if (!this.tokens || !this.tokens.refresh_token) throw new CardataAuthError('geen refresh_token, log opnieuw in')
|
|
148
|
+
const { status, data } = await postForm(`${this.authBase}/token`, {
|
|
149
|
+
grant_type: 'refresh_token',
|
|
150
|
+
refresh_token: this.tokens.refresh_token,
|
|
151
|
+
client_id: this.tokens.client_id || this.clientId
|
|
152
|
+
})
|
|
153
|
+
if (status !== 200 || !data.id_token) {
|
|
154
|
+
throw new CardataAuthError(`token vernieuwen mislukt (${status}): ${data.error || JSON.stringify(data)}`, { status, code: data.error })
|
|
155
|
+
}
|
|
156
|
+
this.setTokens(Object.assign({}, this.tokens, data, { obtained_at: Date.now() / 1000 }))
|
|
157
|
+
return this.tokens
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async ensureFreshTokens (marginS = 300) {
|
|
161
|
+
if (this.secondsLeft() < marginS) await this.refresh()
|
|
162
|
+
return this.tokens
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Vernieuwt elke intervalMs (standaard 45 min), met een nieuwe poging over 2 minuten bij
|
|
167
|
+
* een netwerkfout of 5xx — een 4xx (refresh-token verlopen/ingetrokken) lost zichzelf
|
|
168
|
+
* niet op en krijgt geen nieuwe poging. Er loopt hooguit één retry tegelijk, en bij het
|
|
169
|
+
* starten wordt alleen vernieuwd als de huidige token binnen een interval verloopt: een
|
|
170
|
+
* redeploy vlak na een inlog hoeft de stream niet meteen opnieuw te verbinden.
|
|
171
|
+
*/
|
|
172
|
+
startAutoRefresh ({ intervalMs = 45 * 60 * 1000, retryMs = 2 * 60 * 1000, onError } = {}) {
|
|
173
|
+
this.stopAutoRefresh()
|
|
174
|
+
const tick = () => {
|
|
175
|
+
clearTimeout(this._retryTimer)
|
|
176
|
+
this._retryTimer = null
|
|
177
|
+
this.refresh().catch((err) => {
|
|
178
|
+
if (onError) onError(err)
|
|
179
|
+
if (err.status >= 400 && err.status < 500) return
|
|
180
|
+
if (this._refreshTimer) this._retryTimer = setTimeout(tick, retryMs)
|
|
181
|
+
})
|
|
182
|
+
}
|
|
183
|
+
this._refreshTimer = setInterval(tick, intervalMs)
|
|
184
|
+
if (this.secondsLeft() * 1000 < intervalMs) tick()
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
stopAutoRefresh () {
|
|
188
|
+
if (this._refreshTimer) clearInterval(this._refreshTimer)
|
|
189
|
+
if (this._retryTimer) clearTimeout(this._retryTimer)
|
|
190
|
+
this._refreshTimer = null
|
|
191
|
+
this._retryTimer = null
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// --- De stream ---------------------------------------------------------------------
|
|
195
|
+
|
|
196
|
+
streamOptions (clientIdMqtt) {
|
|
197
|
+
if (!this.tokens || !this.tokens.gcid) throw new CardataAuthError('nog niet ingelogd')
|
|
198
|
+
return {
|
|
199
|
+
host: STREAM_HOST,
|
|
200
|
+
port: STREAM_PORT,
|
|
201
|
+
protocolVersion: STREAM_PROTOCOL_VERSION,
|
|
202
|
+
keepalive: STREAM_KEEPALIVE_S,
|
|
203
|
+
clientId: clientIdMqtt,
|
|
204
|
+
username: this.tokens.gcid,
|
|
205
|
+
password: this.tokens.id_token,
|
|
206
|
+
protocol: 'mqtts'
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
subscribeTopic () {
|
|
211
|
+
if (!this.tokens || !this.tokens.gcid) throw new CardataAuthError('nog niet ingelogd')
|
|
212
|
+
return `${this.tokens.gcid}/${this.vin}`
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// --- REST API (laaddoel) ----------------------------------------------------------
|
|
216
|
+
|
|
217
|
+
async _apiRequest (path, { method = 'GET', body } = {}) {
|
|
218
|
+
await this.ensureFreshTokens()
|
|
219
|
+
const token = this.tokens.access_token || this.tokens.id_token
|
|
220
|
+
const res = await fetch(this.apiBase + path, {
|
|
221
|
+
method,
|
|
222
|
+
headers: {
|
|
223
|
+
Authorization: `Bearer ${token}`,
|
|
224
|
+
'x-version': 'v1',
|
|
225
|
+
Accept: 'application/json',
|
|
226
|
+
...(body ? { 'Content-Type': 'application/json' } : {})
|
|
227
|
+
},
|
|
228
|
+
body: body ? JSON.stringify(body) : undefined
|
|
229
|
+
})
|
|
230
|
+
const data = await res.json().catch(() => ({}))
|
|
231
|
+
return { status: res.status, data }
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async createContainer (descriptors) {
|
|
235
|
+
const { status, data } = await this._apiRequest('/customers/containers/', {
|
|
236
|
+
method: 'POST',
|
|
237
|
+
body: {
|
|
238
|
+
name: 'victron-dess',
|
|
239
|
+
purpose: 'Laaddoel en laadinstellingen voor thuisbatterij-planning',
|
|
240
|
+
technicalDescriptors: descriptors
|
|
241
|
+
}
|
|
242
|
+
})
|
|
243
|
+
if (status >= 400) throw new CardataAuthError(`container aanmaken mislukt (${status})`, { status, data })
|
|
244
|
+
const id = data.containerId || data.id || data.container_id
|
|
245
|
+
if (!id) throw new CardataAuthError('geen container-ID in het antwoord', { status, data })
|
|
246
|
+
return id
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Haalt het laaddoel (en, ter info, de ingestelde AC-limiet) op uit de container. */
|
|
250
|
+
async fetchTarget () {
|
|
251
|
+
if (!this.containerId) throw new CardataAuthError('geen containerId ingesteld')
|
|
252
|
+
const path = `/customers/vehicles/${this.vin}/telematicData?containerId=${encodeURIComponent(this.containerId)}`
|
|
253
|
+
const { status, data } = await this._apiRequest(path)
|
|
254
|
+
if (status !== 200) throw new CardataAuthError(`CarData API gaf ${status}`, { status, data })
|
|
255
|
+
const items = (data && data.telematicData) || data || {}
|
|
256
|
+
let targetSoc
|
|
257
|
+
let acLimitA
|
|
258
|
+
Object.keys(items).forEach((naam) => {
|
|
259
|
+
const v = items[naam] && items[naam].value
|
|
260
|
+
if (v === null || v === undefined) return
|
|
261
|
+
const n = Number(v)
|
|
262
|
+
if (Number.isNaN(n)) return
|
|
263
|
+
if (/stateOfCharge\.target$/.test(naam)) targetSoc = n
|
|
264
|
+
if (/acLimit\.selected$/.test(naam)) acLimitA = n
|
|
265
|
+
})
|
|
266
|
+
if (targetSoc === undefined) throw new CardataAuthError('geen laaddoel in het antwoord', { status, data })
|
|
267
|
+
return { targetSoc, acLimitA }
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
module.exports = { CardataClient, CardataAuthError, clampIntervalMinutes, nextBackoffMs, MIN_TARGET_INTERVAL_MIN }
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
const { distanceM } = require('./geo')
|
|
4
|
+
|
|
5
|
+
// BMW/MINI CarData-berichten naar vlakke paden voor het virtuele EV-apparaat (victron-virtual).
|
|
6
|
+
// De klasse houdt zelf de laatst bekende waarde per pad bij (de stream stuurt alleen
|
|
7
|
+
// WIJZIGINGEN), zodat elk bericht naar victron-virtual de volledige, actuele toestand bevat.
|
|
8
|
+
|
|
9
|
+
// GOKKEN, controleren tegen de stream: de exacte waarden van charging.status.
|
|
10
|
+
const CHARGING = {
|
|
11
|
+
NOCHARGING: 0,
|
|
12
|
+
CHARGINGENDED: 0,
|
|
13
|
+
CHARGINGPAUSED: 0,
|
|
14
|
+
CHARGINGACTIVE: 3,
|
|
15
|
+
CHARGINGERROR: 250,
|
|
16
|
+
INVALID: 255
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const RULES = [
|
|
20
|
+
{ path: '/Soc', match: (n) => /stateOfCharge\.displayed$|batteryManagement\.header$/.test(n), conv: Number },
|
|
21
|
+
// Het laaddoel is stateOfCharge.target (BEVESTIGD via evcc/BavarianData); targetMin is de
|
|
22
|
+
// ondergrens voor slim laden/V2X en mag hier dus NIET op matchen (vandaar het anker $).
|
|
23
|
+
{ path: '/TargetSoc', match: (n) => /stateOfCharge\.target$|chargingTarget$|targetSoc$/i.test(n) && !/Professional/i.test(n), conv: Number },
|
|
24
|
+
{ path: '/RangeToGo', match: (n) => n.endsWith('kombiRemainingElectricRange'), conv: Number },
|
|
25
|
+
{ path: '/Odometer', match: (n) => n.endsWith('vehicle.travelledDistance'), conv: Number },
|
|
26
|
+
{ path: '/Ac/Power', match: (n) => /battery\.charging\.power$/.test(n), conv: (v) => Math.round(Number(v) < 100 ? Number(v) * 1000 : Number(v)) },
|
|
27
|
+
{
|
|
28
|
+
path: '/ChargingState',
|
|
29
|
+
match: (n) => n.endsWith('charging.status'),
|
|
30
|
+
conv: (v) => {
|
|
31
|
+
const k = String(v).toUpperCase().replace(/[^A-Z]/g, '')
|
|
32
|
+
return k.startsWith('INITIA') ? 0 : CHARGING[k] // INITIALIZING e.d.: nog niet aan het laden
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
{ path: '/Position/Latitude', match: (n) => /latitude/i.test(n) && !/destination/i.test(n), conv: Number },
|
|
36
|
+
{ path: '/Position/Longitude', match: (n) => /longitude/i.test(n) && !/destination/i.test(n), conv: Number }
|
|
37
|
+
]
|
|
38
|
+
// Van deze velden tonen we in de debug wel de naam, maar nooit de waarde.
|
|
39
|
+
const PRIVE = /location|latitude|longitude|vin|heading|altitude|gps|position/i
|
|
40
|
+
|
|
41
|
+
function walk (n, out) {
|
|
42
|
+
if (Array.isArray(n)) {
|
|
43
|
+
n.forEach((i) => walk(i, out))
|
|
44
|
+
} else if (n && typeof n === 'object') {
|
|
45
|
+
if ('name' in n && 'value' in n) out.push(n)
|
|
46
|
+
Object.keys(n).forEach((k) => {
|
|
47
|
+
const v = n[k]
|
|
48
|
+
if (v && typeof v === 'object' && !Array.isArray(v) && 'value' in v && String(k).startsWith('vehicle.')) {
|
|
49
|
+
out.push(Object.assign({ name: k }, v))
|
|
50
|
+
} else {
|
|
51
|
+
walk(v, out)
|
|
52
|
+
}
|
|
53
|
+
})
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Sommige velden (settingsList, charging.profile) zijn samengesteld: zoek daarin naar het laaddoel.
|
|
58
|
+
function zoekDoelIn (node, diepte) {
|
|
59
|
+
if (diepte > 5 || !node || typeof node !== 'object') return undefined
|
|
60
|
+
for (const k of Object.keys(node)) {
|
|
61
|
+
const v = node[k]
|
|
62
|
+
if (/chargingTarget|targetSoc|targetStateOfCharge/i.test(k) && !/Professional/i.test(k)) {
|
|
63
|
+
const n = Number(v)
|
|
64
|
+
if (!isNaN(n) && n > 0 && n <= 100) return n
|
|
65
|
+
}
|
|
66
|
+
const dieper = zoekDoelIn(v, diepte + 1)
|
|
67
|
+
if (dieper !== undefined) return dieper
|
|
68
|
+
}
|
|
69
|
+
return undefined
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
class StateParser {
|
|
73
|
+
constructor ({ home } = {}) {
|
|
74
|
+
this.home = home || null // { lat, lon, radiusM }
|
|
75
|
+
this.state = {}
|
|
76
|
+
this.gezien = {}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
setHome (home) {
|
|
80
|
+
this.home = home || null
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Zet een bewaarde toestand terug. Een bewaard "niet laden" betekent vermogen 0 (zie parse): dat gaat meteen op 0, want er komt pas een correctie als
|
|
85
|
+
* BMW een nieuwe laadstatus stuurt, en de auto kan dagen stilstaan.
|
|
86
|
+
*/
|
|
87
|
+
restore (saved) {
|
|
88
|
+
Object.assign(this.state, saved)
|
|
89
|
+
if (this.state['/ChargingState'] === 0) this.state['/Ac/Power'] = 0
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Geeft { state, unknown, warnings, updated } terug; `updated` zijn de paden die dit bericht vernieuwde. `state` is altijd de volledige, actuele toestand. */
|
|
93
|
+
parse (payload) {
|
|
94
|
+
const items = []
|
|
95
|
+
walk(payload, items)
|
|
96
|
+
if (items.length === 0) return null
|
|
97
|
+
|
|
98
|
+
const state = this.state
|
|
99
|
+
const gezien = this.gezien
|
|
100
|
+
const onbekend = []
|
|
101
|
+
const warnings = []
|
|
102
|
+
const updated = []
|
|
103
|
+
|
|
104
|
+
items.forEach((item) => {
|
|
105
|
+
const naam = String(item.name)
|
|
106
|
+
const regel = RULES.find((r) => r.match(naam))
|
|
107
|
+
if (!regel && item.value && typeof item.value === 'object') {
|
|
108
|
+
const doel = zoekDoelIn(item.value, 0)
|
|
109
|
+
if (doel !== undefined) {
|
|
110
|
+
state['/TargetSoc'] = doel
|
|
111
|
+
if (!updated.includes('/TargetSoc')) updated.push('/TargetSoc')
|
|
112
|
+
warnings.push(`laaddoel ${doel}% gevonden in ${naam}`)
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (!regel) {
|
|
116
|
+
// Melden zodra de WAARDE verandert, niet alleen de eerste keer.
|
|
117
|
+
const tekst = PRIVE.test(naam) ? '(waarde verborgen)' : JSON.stringify(item.value)
|
|
118
|
+
if (gezien[naam] !== tekst) onbekend.push(`${naam} = ${tekst}`)
|
|
119
|
+
gezien[naam] = tekst
|
|
120
|
+
return
|
|
121
|
+
}
|
|
122
|
+
// Number(null) is 0 en Number('') ook: een lege waarde zou de toestand op 0 zetten
|
|
123
|
+
// (SoC 0%, kilometerstand 0, positie 0,0). Een lege waarde is "geen meting".
|
|
124
|
+
if (item.value === null || item.value === undefined || item.value === '') return
|
|
125
|
+
const waarde = regel.conv(item.value)
|
|
126
|
+
if (waarde === undefined || (typeof waarde === 'number' && isNaN(waarde))) {
|
|
127
|
+
warnings.push(`onbekende waarde voor ${naam}: ${JSON.stringify(item.value)}`)
|
|
128
|
+
return
|
|
129
|
+
}
|
|
130
|
+
state[regel.path] = waarde
|
|
131
|
+
if (!updated.includes(regel.path)) updated.push(regel.path)
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
// BMW stuurt alleen wijzigingen, en het laadvermogen gaat niet vanzelf op 0 als het laden
|
|
135
|
+
// stopt: in VRM bleef 9310 W staan bij "Not charging". Een nieuwe laadstatus "niet laden"
|
|
136
|
+
// zonder eigen vermogensmelding betekent dus dat het vermogen 0 is. Ook als er nog geen
|
|
137
|
+
// vermogen bekend was (bv. na een herstart): anders blijft VRM de laatst gelogde waarde tonen.
|
|
138
|
+
if (updated.includes('/ChargingState') && state['/ChargingState'] === 0 &&
|
|
139
|
+
!updated.includes('/Ac/Power') && state['/Ac/Power'] !== 0) {
|
|
140
|
+
state['/Ac/Power'] = 0
|
|
141
|
+
updated.push('/Ac/Power')
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const lat = state['/Position/Latitude']
|
|
145
|
+
const lon = state['/Position/Longitude']
|
|
146
|
+
if (this.home && lat !== undefined && lon !== undefined) {
|
|
147
|
+
const afstand = distanceM({ lat, lon }, this.home)
|
|
148
|
+
state['/AtSite'] = afstand <= (this.home.radiusM || 150) ? 1 : 0
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
return { state, unknown: onbekend, warnings, updated }
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
module.exports = { StateParser }
|