-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShellyLiveTariff.js
666 lines (642 loc) · 25.3 KB
/
ShellyLiveTariff.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
/*
Created by Leivo Sepp, 07.01.2025
Licensed under the MIT License
https://github.com/LeivoSepp/Shelly-Live-Tariff
This feature allows you to view the exact cost of your electricity usage
if you have any Shelly power monitoring device installed.
(https://www.shelly.com/collections/energy-metering)
This Shelly script automates electricity tariffs in the Shelly cloud
by retrieving energy market prices from Elering and updating the Live Tariff hourly.
*/
/* Electricity transmission fees (EUR/MWh) without VAT
Elektrilevi https://elektrilevi.ee/en/vorguleping/vorgupaketid/eramu
Imatra https://imatraelekter.ee/vorguteenus/vorguteenuse-hinnakirjad/
*/
const VORK1 = { dayRate: 77.2, nightRate: 77.2, dayMaxRate: 77.2, holidayMaxRate: 77.2 };
const VORK2 = { dayRate: 60.7, nightRate: 35.1, dayMaxRate: 60.7, holidayMaxRate: 35.1 };
const VORK4 = { dayRate: 36.9, nightRate: 21, dayMaxRate: 36.9, holidayMaxRate: 21 };
const VORK5 = { dayRate: 52.9, nightRate: 30.3, dayMaxRate: 81.8, holidayMaxRate: 47.4 };
const Partner24 = { dayRate: 60.7, nightRate: 60.7, dayMaxRate: 60.7, holidayMaxRate: 60.7 };
const Partner24Plus = { dayRate: 38.6, nightRate: 38.6, dayMaxRate: 38.6, holidayMaxRate: 38.6 };
const Partner12 = { dayRate: 72.4, nightRate: 42, dayMaxRate: 72.4, holidayMaxRate: 42 };
const Partner12Plus = { dayRate: 46.4, nightRate: 27.1, dayMaxRate: 46.4, holidayMaxRate: 27.1 };
const NONE = { dayRate: 0, nightRate: 0, dayMaxRate: 0, holidayMaxRate: 0 };
/****** PROGRAM INITIAL SETTINGS ******/
/*
After the initial run, all user settings are stored in the Shelly 1) KVS or 2) Virtual components (in case virtual components are supported).
To modify these user settings later, you’ll need to access the Shelly KVS via: Menu → Advanced → KVS on the Shelly web page.
Once you’ve updated the settings, restart the script to apply the changes or wait for the next scheduled run.
If the Shelly supports Virtual components, the script will automatically create them and store the settings there.
Virtual Components allows you to modify settings directly from the Shelly web page or Shelly mobile app.
Updating script code is easy, you only need to copy-paste new code as all the settings are pulled from the KVS or Virtual components.
*/
let s = {
networkPacket: "VORK2", // ELEKTRILEVI/IMATRA transmission fee: VORK1 / VORK2 / VORK4 /VORK5 / Partner24 / Partner24Plus / Partner12 / Partner12Plus / NONE
country: "ee", // Estonia-ee, Finland-fi, Lithuania-lt, Latvia-lv
apiUrl: "", // Shelly Cloud token
}
/****** PROGRAM INITIAL SETTINGS ******/
let _ = {
elering: "https://dashboard.elering.ee/api/nps/price/csv?fields=",
isUpdateRequired: false,
loopFreq: 300, //300 seconds / 5 min
loopRunning: false,
dayInSec: 60 * 60 * 24,
tsPrices: '',
updtDelay: Math.floor(Math.random() * 46) + 5, //delay for server requests (random between 23:05-23:50)
sId: Shelly.getCurrentScriptId(),
pId: "Id" + Shelly.getCurrentScriptId() + ": ",
networkProvider: "None",
rpcCl: 1,
oldVersion: 0,
version: 1.0,
};
let cntr = 0;
const virtualComponents = [
{
type: "group", id: 200, config: {
name: "Shelly Live Tariff"
}
},
{
type: "text", id: 200, config: {
name: "Shelly API URL",
default_value: "",
persisted: true,
meta: { ui: { view: "field" } }
}
},
{
type: "text", id: 201, config: {
name: "Live Tariff updated",
default_value: "",
persisted: true,
meta: { ui: { view: "label", webIcon: 13 } }
}
},
{
type: "enum", id: 200, config: {
name: "Network Package",
options: ["NONE", "VORK1", "VORK2", "VORK4", "VORK5", "Partner24", "Partner24Plus", "Partner12", "Partner12Plus"],
default_value: "VORK2",
persisted: true,
meta: { ui: { view: "dropdown", webIcon: 22, titles: { "NONE": "No package", "VORK1": "Võrk1 Base", "VORK2": "Võrk2 DayNight", "VORK4": "Võrk4 DayNight", "VORK5": "Võrk5 DayNightPeak", "Partner24": "Partner24 Base", "Partner24Plus": "Partner24Plus Base", "Partner12": "Partner12 DayNight", "Partner12Plus": "Partner12Plus DayNight" } } }
}
},
{
type: "enum", id: 201, config: {
name: "Market Price Country",
options: ["ee", "fi", "lv", "lt"],
default_value: "ee",
persisted: true,
meta: { ui: { view: "dropdown", webIcon: 9, titles: { "ee": "Estonia", "fi": "Findland", "lv": "Latvia", "lt": "Lithuania" } } }
}
},
];
function start() {
setAutoStart();
getKvsData();
}
/* set the script to sart automatically on boot */
function setAutoStart() {
if (!Shelly.getComponentConfig("script", _.sId).enable) {
Shelly.call('Script.SetConfig', { id: _.sId, config: { enable: true } },
function (res, err, msg, data) {
if (err != 0) {
console.log(_.pId, "Live Tariff script autostart is not enabled.", msg, ". After Shelly restart, this script will not start and Live Tariff does not work.");
}
});
}
}
// check if Shelly supports Virtual components
function isVirtualComponentsAvailable() {
const info = Shelly.getDeviceInfo();
return (info.gen === 3 || (info.gen === 2 && info.app.substring(0, 3) == "Pro")) && isNewerVersion('1.4.3', info.ver);
}
// compare versions
function isNewerVersion(oldVer, newVer) {
const oldParts = oldVer.split('.')
const newParts = newVer.split('.')
for (var i = 0; i < newParts.length; i++) {
let a = ~~newParts[i] // parse int
let b = ~~oldParts[i] // parse int
if (a > b) return true
if (a < b) return false
}
return false
}
function getKvsData() {
Shelly.call('KVS.GetMany', null, processKVSData);
}
function processKVSData(res, err, msg, data) {
let kvsData;
if (res) {
kvsData = res.items;
res = null;
}
//old version number is used to maintain backward compatibility
_.oldVersion = (kvsData["version" + _.sId] != null && typeof JSON.parse(kvsData["version" + _.sId].value) === "number") ? JSON.parse(kvsData["version" + _.sId].value) : 0;
if (isVirtualComponentsAvailable()) {
if (_.oldVersion < 1) {
console.log(_.pId, "New virtual component installation.");
getAllVirtualComponents();
} else {
// Script already in Virtual components mode
readAllVirtualComponents();
}
} else { // this is the KVS path if Shelly doesn't support Virtual components
// Script in KVS mode
let isExistInKvs = false;
let userCongfigNotInKvs = [];
//iterate settings and then KVS
for (var k in s) {
for (var i in kvsData) {
//check if settings found in KVS
if (i == k + _.sId) {
s[k] = kvsData[i].value; //do not convert strings
isExistInKvs = true;
break;
}
}
if (isExistInKvs) {
isExistInKvs = false;
} else if (typeof s[k] === "object") {
userCongfigNotInKvs.push([k, JSON.stringify(s[k])]);
} else {
userCongfigNotInKvs.push([k, s[k]]);
}
}
storeSettingsKvs(userCongfigNotInKvs);
}
}
function storeSettingsKvs(userCongfigNotInKvs) {
if (cntr < 6 - _.rpcCl) {
for (let i = 0; i < _.rpcCl && i < userCongfigNotInKvs.length; i++) {
let value = userCongfigNotInKvs[0][1];
let key = userCongfigNotInKvs.splice(0, 1)[0][0] + _.sId;
cntr++;
Shelly.call("KVS.set", { key: key, value: value },
function (res, error_code, error_message, data) {
if (error_code !== 0) {
console.log(_.pId, "Store settings", data.key, data.value, "in KVS failed.");
} else {
console.log(_.pId, "Store settings", data.key, data.value, "to KVS is OK");
}
cntr--;
},
{ key: key, value: value }
);
}
}
if (userCongfigNotInKvs.length > 0) {
Timer.set(1000, false, storeSettingsKvs, userCongfigNotInKvs);
} else {
waitForRpcCalls(main);
}
}
// Function to get all virtual components and delete them all before creating new
function getAllVirtualComponents() {
Shelly.call("Shelly.GetComponents", { dynamic_only: true, include: ["status"] }, checkComponents);
}
function checkComponents(res, err, msg, data) {
if (err === 0) {
if (res.components && res.components.length > 0) {
deleteVirtualComponents(res.components);
} else {
addVirtualComponent(virtualComponents);
}
} else {
console.log(_.pId, "Failed to get virtual components. Error: " + msg);
}
}
// Function to delete all virtual components
function deleteVirtualComponents(vComponents) {
if (cntr < 6 - _.rpcCl) {
for (let i = 0; i < _.rpcCl && i < vComponents.length; i++) {
let key = vComponents.splice(0, 1)[0].key;
cntr++;
Shelly.call("Virtual.Delete", { key: key },
function (res, err, msg, data) {
if (err === 0) {
console.log(_.pId, "Deleted " + data.key + " virtual component");
} else {
console.log(_.pId, "Failed to delete " + data.key + " virtual component. Error: " + msg);
}
cntr--;
},
{ key: key }
);
}
}
if (vComponents.length > 0) {
Timer.set(1000, false, deleteVirtualComponents, vComponents);
} else {
waitForRpcCalls([addVirtualComponent, virtualComponents]);
}
}
//add all new virtual components
function addVirtualComponent(virtualComponents) {
if (cntr < 6 - _.rpcCl) {
for (let i = 0; i < _.rpcCl && i < virtualComponents.length; i++) {
let component = virtualComponents.splice(0, 1)[0];
let type = component.type;
let id = component.id;
let config = component.config;
cntr++;
Shelly.call("Virtual.Add", { type: type, id: id, config: config },
function (res, err, msg, data) {
if (err === 0) {
console.log(_.pId, "Added virtual component: " + data.type + ":" + data.id);
} else {
console.log(_.pId, "Failed to add virtual component: " + data.type + ":" + data.id + ". Error: " + msg);
}
cntr--;
},
{ type: type, id: id, config: config }
);
}
}
if (virtualComponents.length > 0) {
Timer.set(1000, false, addVirtualComponent, virtualComponents);
} else {
waitForRpcCalls(setGroupConfig);
}
}
function setGroupConfig() {
const groupConfig = {
id: 200,
value: [
"text:201",
"text:200",
"enum:200",
"enum:201"
]
};
Shelly.call("Group.Set", groupConfig, function (res, err, msg) {
if (err !== 0) {
console.log(_.pId, "Failed to set group config. Error: " + msg);
}
});
readAllVirtualComponents();
}
function readAllVirtualComponents() {
//this function reads all virtual components and stores the values to memory
Shelly.call("Shelly.GetComponents", { dynamic_only: true, include: ["status"] }, processComponents);
}
function processComponents(res, err, msg) {
if (err === 0) {
const components = res.components;
res = null;
if (components && components.length > 0) {
for (let i in components) {
switch (components[i].key) {
case "text:200":
s.apiUrl = components[i].status.value;
break;
case "enum:200":
s.networkPacket = components[i].status.value;
break;
case "enum:201":
s.country = components[i].status.value;
break;
default:
break;
}
}
waitForRpcCalls(main);
} else {
console.log(_.pId, "No virtual components found.");
}
} else {
console.log(_.pId, "Failed to get virtual components. Error: " + msg);
}
}
/**
This is the main script where all the logic starts.
*/
function main() {
setKVS();
if (_.oldVersion === 0 || s.apiUrl === "") {
console.log(_.pId, "Please set API URL value in KVS or Virtual components and then restart the script.");
Shelly.call('Script.Stop', { id: _.sId });
return;
}
//check if Shelly has time
if (!isShellyTimeOk) {
handleError("Shelly has no time.");
return;
}
if (s.networkPacket.substring(0, 4) == "VORK") {
_.networkProvider = "Elektrilevi";
} else if (s.networkPacket.substring(0, 4) == "Part") {
_.networkProvider = "Imatra";
}
console.log(_.pId, "Network provider: ", _.networkProvider, s.networkPacket);
getElering();
}
//store the version and last calculation time to KVS
function setKVS() {
//schedulers are created, store the IDs to KVS
Shelly.call("KVS.set", { key: "version" + _.sId, value: _.version });
Shelly.call("KVS.set", { key: "lastcalculation" + _.sId, value: new Date().toString() },
function () {
console.log(_.pId, "Script v" + _.version, " next fetch for Elering prices at", nextChkHr(1) + (_.updtDelay < 10 ? ":0" : ":") + _.updtDelay);
_.loopRunning = false;
});
}
/* Get electricity market price CSV file from Elering. */
function getElering() {
const tzInSec = getShellyTimezone();
// Determine the date range for Elering query
const dtRange = getEleringDateRange(tzInSec);
// Build Elering URL
const elUrl = buildEleringUrl(dtRange[0], dtRange[1]);
console.log(_.pId, "Elering query: ", elUrl);
try {
Shelly.call("HTTP.GET", { url: elUrl, timeout: 5, ssl_ca: "*" }, priceCalc);
} catch (error) {
handleError("Elering HTTP.GET error" + error + "check again in " + _.loopFreq / 60 + " min.");
}
}
function getShellyTimezone() {
const shEpochUtc = Shelly.getComponentStatus("sys").unixtime;
const shDt = new Date(shEpochUtc * 1000);
const shHr = shDt.getHours();
const shUtcHr = shDt.toISOString().slice(11, 13);
let tz = shHr - shUtcHr;
if (tz > 12) { tz -= 24; }
if (tz < -12) { tz += 24; }
return tz * 60 * 60;
}
function getEleringDateRange(tzInSec) {
const shEpochUtc = Shelly.getComponentStatus("sys").unixtime;
const shHr = new Date(shEpochUtc * 1000).getHours();
// After 23:00 tomorrow's energy prices are used
// before 23:00 today's energy prices are used.
const addDays = shHr >= 23 ? 0 : -1;
const isoTime = new Date((shEpochUtc + tzInSec + _.dayInSec * addDays) * 1000).toISOString().slice(0, 10);
const isoTimePlusDay = new Date((shEpochUtc + tzInSec + (_.dayInSec * (addDays + 1))) * 1000).toISOString().slice(0, 10);
const dtStart = isoTime + "T" + (24 - tzInSec / 3600) + ":00Z";
const dtEnd = isoTimePlusDay + "T" + (24 - tzInSec / 3600 - 1) + ":00Z";
return [dtStart, dtEnd];
}
function buildEleringUrl(dtStart, dtEnd) {
return _.elering + s.country + "&start=" + dtStart + "&end=" + dtEnd;
}
/**
Price calculation logic.
*/
function priceCalc(res, err, msg) {
if (err != 0 || res === null || res.code != 200 || !res.body_b64) {
handleError("Elering JSON error, check again in " + _.loopFreq / 60 + " min.");
return;
}
//convert the networkPacket value to variable
s.networkPacket = eval(s.networkPacket);
// Convert base64 to text and discard header
res.body_b64 = atob(res.body_b64);
const csvData = res.body_b64.substring(res.body_b64.indexOf("\n") + 1);
res = null; //clear memory
let eleringPrices = parseEleringPrices(csvData);
//if elering API returns less than 23 rows, the script will try to download the data again after set of minutes
if (eleringPrices.length < 24) {
handleError("Elering API didn't return prices, check again in " + _.loopFreq / 60 + " min.");
return;
}
//store the timestamp into memory
_.tsPrices = epoch();
console.log(_.pId, "We got market prices from Elering ", new Date().toString());
for (let a = 0; a < eleringPrices.length; a++) {
let hour = new Date(eleringPrices[a][0] * 1000).getHours();
eleringPrices[a][0] = hour;
}
setShellyTariff(eleringPrices);
}
/**
* Parse Elering prices from the response body.
*/
function parseEleringPrices(body) {
let eleringPrices = [];
let activePos = 0;
while (activePos >= 0) {
body = body.substring(activePos);
activePos = 0;
let row = [0, 0];
activePos = body.indexOf("\"", activePos) + 1;
if (activePos === 0) {
break; // End of data
}
// Epoch
row[0] = Number(body.substring(activePos, body.indexOf("\"", activePos)));
// Skip "; after timestamp
activePos = body.indexOf("\"", activePos) + 2;
// Price
activePos = body.indexOf(";\"", activePos) + 2;
row[1] = Number(body.substring(activePos, body.indexOf("\"", activePos)).replace(",", "."));
// Add transfer fees
row[1] += calculateTransferFees(row[0]);
eleringPrices.push(row);
activePos = body.indexOf("\n", activePos);
}
return eleringPrices;
}
/**
* Calculate transfer fees based on the timestamp.
*/
function calculateTransferFees(epoch) {
if (_.networkProvider === "Elektrilevi") {
return calculateElektrileviTransferFees(epoch);
} else if (_.networkProvider === "Imatra") {
return calculateImatraTransferFees(epoch);
} else {
return 0;
}
}
function calculateElektrileviTransferFees(epoch) {
const hour = new Date(epoch * 1000).getHours();
const day = new Date(epoch * 1000).getDay();
const month = new Date(epoch * 1000).getMonth();
if ((month >= 10 || month <= 2) && (day === 0 || day === 6) && hour >= 16 && hour < 20) {
// peak holiday: Nov-Mar, SA-SU at 16:00–20:00
return s.networkPacket.holidayMaxRate;
} else if ((month >= 10 || month <= 2) && ((hour >= 9 && hour < 12) || (hour >= 16 && hour < 20))) {
// peak daytime: Nov-Mar: MO-FR at 09:00–12:00 and at 16:00–20:00
return s.networkPacket.dayMaxRate;
} else if (hour < 7 || hour >= 22 || day === 6 || day === 0) {
//night-time: MO-FR at 22:00–07:00, SA-SU all day
return s.networkPacket.nightRate;
} else {
//daytime: MO-FR at 07:00–22:00
return s.networkPacket.dayRate;
}
}
function isSummerTime() {
return getShellyTimezone() / 60 / 60 === 3;
}
function calculateImatraTransferFees(epoch) {
const hour = new Date(epoch * 1000).getHours();
const day = new Date(epoch * 1000).getDay();
if (isSummerTime()) {
if (hour < 8 || day === 6 || day === 0) {
//summer-night-time: MO-FR at 00:00–08:00, SA-SU all day
return s.networkPacket.nightRate;
} else {
//daytime: MO-FR at 08:00–24:00
return s.networkPacket.dayRate;
}
} else {
if (hour < 7 || hour >= 23 || day === 6 || day === 0) {
//winter-night-time: MO-FR at 23:00–07:00, SA-SU all day
return s.networkPacket.nightRate;
} else {
//daytime> MO-FR at 07:00–23:00
return s.networkPacket.dayRate;
}
}
}
// function to send the live tariff to Shelly cloud
let liveTariffTimer;
function setShellyTariff(eleringPrices) {
const shEpochUtc = Shelly.getComponentStatus("sys").unixtime;
const currentHour = new Date(shEpochUtc * 1000).getHours();
const decodedURL = manualDecodeURI(s.apiUrl); //decode the URL
let currentPrice = eleringPrices[currentHour][1]; //get the current price
currentPrice = currentPrice / 1000; //convert EUR/MWh to EUR/kWh
currentPrice = currentPrice * 1.22; //add VAT
currentPrice = Math.round(currentPrice * 1000) / 1000; //round to 3 decimals
const requestBody = JSON.stringify({ price: currentPrice }); //create the request body
Shelly.call(
"HTTP.POST", {
"url": decodedURL,
"content_type": " application/json",
"body": requestBody
}, processPostResponce, { eleringPrices: eleringPrices });
}
function processPostResponce(res, err, msg, data) {
if (err != 0 || res === null || res.code != 200) {
const errorMessage = res === null ? "No response" : JSON.parse(res.body).error;
handleError("Send Live Tariff to Shelly cloud error, try again in " + _.loopFreq / 60 + " min. " + errorMessage);
return;
}
const result = JSON.parse(res.body);
const nextUpdateInMinutes = Math.round(secondsToNextHour() / 60);
// schedule the next price update to be sent to Shelly cloud
liveTariffTimer = Timer.set(1000 * secondsToNextHour(), false, setShellyTariff, data.eleringPrices);
updateField(result.price);
_.isUpdateRequired = false;
console.log("Live Tariff of " + result.price + " EUR/kWh incl. VAT has been sent to the Shelly cloud. The next update will be sent in " + nextUpdateInMinutes + " minutes.");
}
function updateField(price) {
const time = getHHMMDDMMYYY(new Date());
const priceText = price + " €/kWh";
const text = time + " (" + priceText + ")";
Shelly.call("Text.Set", { id: 201, value: text },);
Shelly.call("KVS.set", { key: "LiveTariffUpdated" + _.sId, value: text });
}
function getHHMMDDMMYYY(date) {
return (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":"
+ (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + " "
+ date.getDate() + "."
+ (date.getMonth() + 1) + "."
+ date.getFullYear();
}
function secondsToNextHour() {
const now = new Date();
const seconds = now.getSeconds();
const minutes = now.getMinutes();
const remainingSecondsInMinute = 60 - seconds;
const remainingMinutes = 59 - minutes;
return remainingSecondsInMinute + (remainingMinutes * 60);
}
// Function to manually decode URI (Shelly doesn't support regex or decodeURI)
function manualDecodeURI(encodedURI) {
let decodedURI = '';
for (let i = 0; i < encodedURI.length; i++) {
if (encodedURI[i] === '%' && i + 2 < encodedURI.length) {
let hex = encodedURI.slice(i + 1, i + 3);
decodedURI += String.fromCharCode(parseInt(hex, 16));
i += 2;
} else {
decodedURI += encodedURI[i];
}
}
return decodedURI;
}
/**
* Handle errors. Retry after 5 minutes
*/
function handleError(error_message) {
console.log(_.pId, "# Internet error ", error_message);
_.isUpdateRequired = true;
_.loopRunning = false;
Timer.clear(liveTariffTimer);
}
/**
* Wait for the RPC calls to be completed before starting next function.
*/
function waitForRpcCalls(userdata) {
if (cntr !== 0) {
Timer.set(1000, false, waitForRpcCalls, userdata);
return;
}
if (typeof userdata === "function") {
userdata();
} else {
userdata[0](userdata[1]);
}
}
function epoch() {
return Math.floor(Date.now() / 1000.0);
}
/* Next hour for fetching Elering prices */
function nextChkHr(addHr) {
const chkT = 24;
const hr = (Math.ceil((new Date(Date.now() + (addHr * 60 * 60 * 1000)).getHours() + 1) / chkT) * chkT) - 1;
return hr > 23 ? 23 : hr;
}
//check if the update is required
function isUpdtReq(ts) {
const nextHour = nextChkHr(0);
const now = new Date();
const yestDt = new Date(now - _.dayInSec * 1000);
const tsDt = new Date(ts * 1000);
const isToday = tsDt.getFullYear() === now.getFullYear() && tsDt.getMonth() === now.getMonth() && tsDt.getDate() === now.getDate();
const isYesterday = tsDt.getFullYear() === yestDt.getFullYear() && tsDt.getMonth() === yestDt.getMonth() && tsDt.getDate() === yestDt.getDate();
const isTsAfterChkT = tsDt.getHours() === nextHour && isToday;
const isChkT = now.getHours() === nextHour && now.getMinutes() >= _.updtDelay;
return (isChkT && !isTsAfterChkT) || !(isToday || isYesterday);
}
//main loop function
function loop() {
if (_.loopRunning) {
return;
}
_.loopRunning = true;
if (isUpdtReq(_.tsPrices) || _.isUpdateRequired) {
start();
} else {
_.loopRunning = false;
}
}
let isShellyTimeOk = false;
let timer_handle;
//check if Shelly has time
function checkShellyTime() {
const shEpochUtc = Shelly.getComponentStatus("sys").unixtime;
if (shEpochUtc > 0) {
//if time is OK, then stop the timer
Timer.clear(timer_handle);
isShellyTimeOk = true;
} else {
//waiting timeserver response
return;
}
}
//execute the checkShellyTime when the script starts
checkShellyTime();
//start 1 sec loop-timer to check Shelly time
//if Shelly has already time, then this timer will be closed immediately
timer_handle = Timer.set(1000, true, checkShellyTime);
//start the loop component
Timer.set(_.loopFreq * 1000, true, loop);
loop();