für die iobroker einsaetzen und ein javascript nutzen wollen - habe mir mit Unterstützung von Gemini eine Script geschrieben, welches aller x Minuten (konfigurierbar, Achtung Limit der API beachten) die Daten mit einem Abruf aus der API abholt. Es gibt auch Object für die Actions: Klima starten/stoppen, Ladevorgang starten/stoppen, ...
damit es funktioniert müssen der API KEY, die VIN und ggf. das PollIntervall angepasst werden.
Vlt nützt es dem ein oder anderen, ich iteriere es ab und an
Version 1.1
Code
/**
* ============================================================================
* ioBroker JavaScript: Škoda Connect Public API Importer (Optimiert)
* ============================================================================
* Swagger Docs: https://public.api.connect.skoda-auto.cz/docs/swagger-ui/index.html
* ============================================================================
*/
const axios = require('axios');
// ==================== KONFIGURATION ====================
const CONFIG = {
basePath: '0_userdata.0.skoda',
apiHost: 'https://public.api.connect.skoda-auto.cz',
apiKey: 'xxxxxAPIKEYxxxxxxxxxxx',
vin: 'xxxxxVINxxxxxxxxxx',
// 5 Minuten Intervall = 12 Anfragen/Stunde (Limit ist 20)
pollIntervalMinutes: 5
};
// =======================================================
const headers = {
'X-API-Key': CONFIG.apiKey,
'Accept': 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'ioBroker-Skoda-Script/1.0'
};
/**
* Erstellt einen ioBroker-Datenpunkt (falls nicht vorhanden) und setzt den Wert
*/
/**
* Erstellt einen ioBroker-Datenpunkt (falls nicht vorhanden) UND setzt den Wert immer neu.
*/
function createAndSetState(id, name, val) {
return new Promise((resolve) => {
let type = typeof val;
if (type === 'undefined' || val === null) type = 'string';
let role = 'state';
if (type === 'number') role = 'value';
if (type === 'boolean') role = 'indicator';
// 1. Prüfen ob Datenpunkt existiert
existsState(id, (exists) => {
if (!exists) {
// Datenpunkt anlegen
createState(id, val, {
name: name,
type: type,
role: role,
read: true,
write: false
}, () => {
// Wert explizit setzen (ack = true)
setState(id, val, true, () => resolve());
});
} else {
// Datenpunkt existiert bereits -> Wert DIREKT aktualisieren (Aktualisiert Zeitstempel)
setState(id, val, true, () => resolve());
}
});
});
}
/**
* Rekursive Funktion zur Umwandlung von JSON-Strukturen in ioBroker-Objekte
*/
async function processJsonObject(parentPath, data) {
if (data === null || data === undefined) return;
if (typeof data === 'object' && !Array.isArray(data)) {
for (const [key, value] of Object.entries(data)) {
const sanitizedKey = key.replace(/[^a-zA-Z0-9_-]/g, '_');
const currentPath = `${parentPath}.${sanitizedKey}`;
if (typeof value === 'object' && value !== null) {
await processJsonObject(currentPath, value);
} else {
await createAndSetState(currentPath, key, value);
}
}
} else if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
const currentPath = `${parentPath}.${i}`;
if (typeof data[i] === 'object' && data[i] !== null) {
await processJsonObject(currentPath, data[i]);
} else {
await createAndSetState(currentPath, `Index ${i}`, data[i]);
}
}
} else {
await createAndSetState(parentPath, parentPath.split('.').pop(), data);
}
}
/**
* Ruft die kompletten Fahrzeugdaten in EINER einzigen Anfrage ab
*/
async function fetchSkodaData() {
log('[Skoda API Debug] Starte Datenabruf...', 'info');
const fullUrl = `${CONFIG.apiHost}/api/v1/vehicles/${CONFIG.vin}`;
try {
log(`[Skoda API Debug] Sende Einzel-Anfrage an: ${fullUrl}`, 'info');
const response = await axios.get(fullUrl, { headers, timeout: 15000 });
log(`[Skoda API Debug] HTTP Status: ${response.status}`, 'info');
if (response.data) {
const targetBasePath = `${CONFIG.basePath}.${CONFIG.vin}`;
await processJsonObject(targetBasePath, response.data);
log('[Skoda API Debug] Fahrzeugdaten erfolgreich in ioBroker aktualisiert.', 'info');
}
} catch (error) {
if (error.response) {
if (error.response.status === 429) {
log('[Skoda API Debug] HTTP 429: Rate-Limit noch aktiv. Bitte Warten bis die Stunde abgelaufen ist.', 'warn');
} else {
log(`[Skoda API Debug] HTTP-FEHLER ${error.response.status}: ${JSON.stringify(error.response.data)}`, 'error');
}
} else {
log(`[Skoda API Debug] NETZWERK-FEHLER: ${error.message}`, 'error');
}
}
}
/**
* POST-Befehle an das Fahrzeug senden
*/
async function sendRemoteCommand(commandPath, payload = {}) {
const fullUrl = `${CONFIG.apiHost}/api/v1/vehicles/${CONFIG.vin}/${commandPath}`;
try {
log(`[Skoda API Debug] Sende Befehl an ${fullUrl}...`, 'info');
const response = await axios.post(fullUrl, payload, { headers, timeout: 15000 });
if (response.status === 200 || response.status === 202) {
log(`[Skoda API Debug] Befehl '${commandPath}' erfolgreich gesendet.`, 'info');
setTimeout(fetchSkodaData, 5000);
}
} catch (error) {
const errText = error.response ? JSON.stringify(error.response.data) : error.message;
log(`[Skoda API Debug] Fehler beim Ausführen von '${commandPath}': ${errText}`, 'error');
}
}
/**
* Steuerungsknöpfe & Test-Button anlegen
*/
function setupRemoteControls() {
return new Promise((resolve) => {
const basePath = `${CONFIG.basePath}.${CONFIG.vin}.remote`;
const actions = [
{ id: 'charging_start', cmd: 'charging/start', name: 'Ladevorgang starten' },
{ id: 'charging_stop', cmd: 'charging/stop', name: 'Ladevorgang stoppen' },
{ id: 'air_conditioning_start', cmd: 'air-conditioning/start', name: 'Klimatisierung starten' },
{ id: 'air_conditioning_stop', cmd: 'air-conditioning/stop', name: 'Klimatisierung stoppen' },
{ id: 'ventilation_start', cmd: 'active-ventilation/start', name: 'Standlüftung starten' },
{ id: 'ventilation_stop', cmd: 'active-ventilation/stop', name: 'Standlüftung stoppen' },
{ id: 'heating_start', cmd: 'auxiliary-heating/start', name: 'Standheizung starten' },
{ id: 'heating_stop', cmd: 'auxiliary-heating/stop', name: 'Standheizung stoppen' }
];
let pending = actions.length + 1;
for (const action of actions) {
const dpId = `${basePath}.${action.id}`;
createState(dpId, false, {
name: action.name,
type: 'boolean',
role: 'button',
read: true,
write: true
}, () => {
on({ id: dpId, change: 'any', val: true }, async () => {
await sendRemoteCommand(action.cmd);
setState(dpId, false, true);
});
pending--;
if (pending === 0) resolve();
});
}
const testDpId = `${basePath}.test_fetch`;
createState(testDpId, false, {
name: 'Manuellen Abruf JETZT testen',
type: 'boolean',
role: 'button',
read: true,
write: true
}, () => {
on({ id: testDpId, change: 'any', val: true }, async () => {
log('[Skoda API Debug] Manueller Abruf per Test-Button ausgelöst!', 'info');
await fetchSkodaData();
setState(testDpId, false, true);
});
pending--;
if (pending === 0) resolve();
});
});
}
/**
* Initialisierung
*/
async function init() {
log('[Skoda API Debug] Skript gestartet.', 'info');
await setupRemoteControls();
await fetchSkodaData();
schedule(`*/${CONFIG.pollIntervalMinutes} * * * *`, async () => {
log(`[Skoda API Debug] Automatischer Abruf (${CONFIG.pollIntervalMinutes} Min)...`, 'info');
await fetchSkodaData();
});
}
init();
Alles anzeigen