reboot all default
/**
- Script TURBO – RESET (Reboot) des bornes FAULTED
- Commande : OCPP Reset
- Optimisations : Parallélisme (10x plus rapide)
- Utilisation :
-
- Refresh (F5) pour nettoyer
-
- Coller le script
-
- Lancer : triggerResetToFaultedStations() */
let stopResetScriptFlag = false; const RESET_TYPE = "Soft"; // "Soft" (Logiciel) ou "Hard" (Matériel/Électrique)
function stopResetScript() { stopResetScriptFlag = true; console.log("🛑 Arrêt du script demandé..."); }
function getStationId(station) { return ( station.id ?? station.chargingStationId ?? station.stationId ?? station.idChargingStation ?? null ); }
async function triggerResetToFaultedStations(customApiUrl = null) {
stopResetScriptFlag = false;
console.log(🚀 Envoi RESET (${RESET_TYPE}) aux bornes FAULTED);
try { // 🔑 Auth & Config const token = localStorage.getItem("token"); if (!token) throw new Error("Token non trouvé");
const selectedRole = JSON.parse(localStorage.getItem("selectedRole") || "{}");
if (!selectedRole.groupId) throw new Error("groupId manquant");
const groupId = selectedRole.groupId;
const origin = window.location.origin;
let API_URL = customApiUrl || (origin.includes("localhost") ? origin.replace(":4200", ":3000") : origin + "/api");
console.log(`🔗 API: ${API_URL} | Groupe: ${groupId}`);
// =========================
// 1. Récupération (Pagination)
// =========================
const pageSize = 100;
let page = 1;
let hasMorePages = true;
let allStations = [];
console.log("📡 Récupération des bornes FAULTED...");
while (hasMorePages && !stopResetScriptFlag) {
const url = `${API_URL}/charging-stations/group/${groupId}/list?offset=${(page - 1) * pageSize}&limit=${pageSize}&status=faulted`;
const res = await fetch(url, {
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }
});
if (!res.ok) throw new Error(`Erreur HTTP listing: ${res.status}`);
const data = await res.json();
const records = data.records || data;
allStations = allStations.concat(records);
const totalRecords = parseInt(res.headers.get("X-Total-Count") || "0");
const totalPages = Math.ceil(totalRecords / pageSize);
console.log(`✅ Page ${page}/${totalPages || '?'} (+${records.length} bornes)`);
if (records.length === 0 || page >= totalPages) {
hasMorePages = false;
} else {
page++;
}
}
// =========================
// 2. Filtrage & Préparation
// =========================
const stationsToprocess = allStations
.map(s => ({ ...s, _stationId: getStationId(s) }))
.filter(s => s._stationId != null);
console.log(`📋 ${stationsToprocess.length} bornes FAULTED prêtes.`);
if (stationsToprocess.length === 0) return console.warn("⚠️ Rien à traiter.");
const confirmMessage =
`⚠️ ATTENTION : RESET MASSIF\n\n` +
`Vous allez redémarrer (${RESET_TYPE}) ${stationsToprocess.length} bornes.\n` +
`Cela va couper les charges en cours si elles existent.\n\n` +
`Continuer ?`;
if (!confirm(confirmMessage)) {
return console.log("❌ Opération annulée");
}
// =========================
// 3. Traitement Parallèle (Concurrency Queue)
// =========================
const CONCURRENCY_LIMIT = 10;
let finishedCount = 0;
let successCount = 0;
let errorCount = 0;
// Fonction worker
const processQueue = async () => {
while (stationsToprocess.length > 0 && !stopResetScriptFlag) {
const station = stationsToprocess.shift();
const name = station.name || station.chargeboxIdentity || station._stationId;
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000);
// --- CHANGEMENT VERS ROUTE RESET ---
const res = await fetch(`${API_URL}/ocpp/reset/${station._stationId}`, {
method: "POST",
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
body: JSON.stringify({ type: RESET_TYPE }), // Payload Reset
signal: controller.signal
}).finally(() => clearTimeout(timeoutId));
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const json = await res.json();
const status = json?.status || json?.result?.status;
if (String(status).toLowerCase() === "accepted") {
successCount++;
console.log(`✅ [${++finishedCount}] ${name} : RESET SEND`);
} else {
throw new Error(`Refusé (${status})`);
}
} catch (err) {
errorCount++;
console.warn(`❌ [${++finishedCount}] ${name} : ${err.message}`);
}
}
};
console.log(`🔥 Démarrage de ${CONCURRENCY_LIMIT} workers...`);
const workers = [];
for (let i = 0; i < CONCURRENCY_LIMIT; i++) {
workers.push(processQueue());
}
await Promise.all(workers);
console.log("\n==============================");
console.log("🏁 TERMINÉ");
console.log(`✅ Succès: ${successCount} | ❌ Erreurs: ${errorCount}`);
console.log("==============================");
} catch (err) { console.error("❌ Crash:", err); } }
// Exposition globale window.triggerResetToFaultedStations = triggerResetToFaultedStations; window.stopResetScript = stopResetScript;
console.log(✅ Script RESET (${RESET_TYPE}) chargé);
console.log("➡️ triggerResetToFaultedStations()");
No comments to display
No comments to display