Skip to content

Commit 03e9066

Browse files
committed
add cache
1 parent 51ac67f commit 03e9066

File tree

2 files changed

+76
-7
lines changed

2 files changed

+76
-7
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
/node_modules/
22
/MMM-Linky.js
33
/node_helper.js
4+
/linkyData.json

src/node_helper.js

+75-7
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
const NodeHelper = require("node_helper");
1+
const { writeFile, readFile, access, constants } = require("node:fs");
2+
const path = require("node:path");
23
const cron = require("node-cron");
34
const { CronExpressionParser } = require("cron-parser");
5+
const NodeHelper = require("node_helper");
46

57
var log = () => { /* do nothing */ };
68

79
module.exports = NodeHelper.create({
8-
910
start () {
1011
this.Linky = null;
1112
this.config = null;
@@ -14,6 +15,7 @@ module.exports = NodeHelper.create({
1415
this.consumptionData = {};
1516
this.cronExpression = "0 14 * * *";
1617
this.error = null;
18+
this.dataFile = path.resolve(__dirname, "linkyData.json");
1719
},
1820

1921
socketNotificationReceived (notification, payload) {
@@ -59,18 +61,36 @@ module.exports = NodeHelper.create({
5961
}
6062
}
6163
this.retryTimer();
64+
} else {
65+
console.error("[LINKY] ---------");
66+
console.error("[LINKY] Please report this error to developer");
67+
console.error("[LINKY] Core Error:", error);
68+
console.error("[LINKY] ---------");
6269
}
6370
});
71+
72+
await this.readChartData();
73+
if (Object.keys(this.chartData).length) {
74+
this.sendSocketNotification("DATA", this.chartData);
75+
}
76+
else {
77+
this.getConsumptionData();
78+
}
79+
this.scheduleDataFetch();
80+
},
81+
82+
async initLinky (callback) {
6483
const { Session } = await this.loadLinky();
6584
try {
6685
this.Linky = new Session(this.config.token, this.config.prm);
86+
log("API linky Prête");
87+
if (callback) callback();
6788
} catch (error) {
6889
console.error(`[LINKY] ${error}`);
6990
this.error = error.message;
7091
this.sendSocketNotification("ERROR", this.error);
71-
return;
92+
7293
}
73-
this.scheduleDataFetch();
7494
},
7595

7696
initWithCache () {
@@ -88,13 +108,15 @@ module.exports = NodeHelper.create({
88108
this.getConsumptionData();
89109
this.displayNextCron();
90110
});
91-
92-
this.getConsumptionData();
93111
this.displayNextCron();
94112
},
95113

96114
// Récupération des données
97115
async getConsumptionData () {
116+
if (!this.Linky) {
117+
this.initLinky(() => this.getConsumptionData());
118+
return;
119+
}
98120
this.consumptionData = {};
99121
var error = 0;
100122
await Promise.all(this.Dates.map(
@@ -183,9 +205,11 @@ module.exports = NodeHelper.create({
183205
labels: days,
184206
datasets: datasets,
185207
energie: this.config.annee_n_minus_1 === 1 ? this.setEnergie() : null,
186-
update: `Données du ${new Date(Date.now()).toLocaleString("fr")}`
208+
update: `Données du ${new Date(Date.now()).toLocaleString("fr")}`,
209+
seed: Date.now()
187210
};
188211
this.sendSocketNotification("DATA", this.chartData);
212+
this.saveChartData();
189213
},
190214

191215
// Selection schémas de couleurs
@@ -323,5 +347,49 @@ module.exports = NodeHelper.create({
323347
displayNextCron () {
324348
const next = CronExpressionParser.parse(this.cronExpression, { tz: "Europe/Paris" });
325349
log("Prochaine tâche planifiée pour le", new Date(next.next().toString()).toLocaleString("fr"));
350+
},
351+
352+
saveChartData () {
353+
const jsonData = JSON.stringify(this.chartData, null, 2);
354+
writeFile(this.dataFile, jsonData, "utf8", (err) => {
355+
if (err) {
356+
console.error("Erreur lors de l'exportation des données", err);
357+
} else {
358+
log("Les données ont été exporté vers", this.dataFile);
359+
}
360+
});
361+
},
362+
363+
readChartData () {
364+
return new Promise((resolve) => {
365+
access(this.dataFile, constants.F_OK, (error) => {
366+
if (error) {
367+
log("Pas de fichier cache trouvé");
368+
this.chartData = {};
369+
resolve();
370+
return;
371+
}
372+
373+
readFile(this.dataFile, (err, data) => {
374+
if (err) {
375+
console.error("[LINKY] Erreur de la lecture du fichier cache!", err);
376+
this.chartData = {};
377+
resolve();
378+
return;
379+
}
380+
const linkyData = JSON.parse(data);
381+
const now = Date.now();
382+
const next = linkyData.seed + (1000 * 60 * 60 * 24);
383+
if (now > next) {
384+
log("Les dernieres données reçues sont > 24h, utilisation de l'API...");
385+
this.chartData = {};
386+
} else {
387+
log("Utilisation du cache...");
388+
this.chartData = linkyData;
389+
}
390+
resolve();
391+
});
392+
});
393+
});
326394
}
327395
});

0 commit comments

Comments
 (0)