Ich habe eine erste Iteration geschrieben, da mir der Anwendungsfall durchaus nützlich erschien.
Im Kern ist es ganz simpel. Meinen MQTT Logger einfach ignorieren, Script sollte auch ohne MQTT lauffähig sein.
Im KVS taucht nun folgende Information auf:
Der Inhalt kann nicht angezeigt werden, da Sie keine Berechtigung haben, diesen Inhalt zu sehen.
/// <reference path="../../shelly-script.d.ts" />
// created from vscode
/**
* operation hours counter for Shellies with switch component
*
* Autor: Marco Grießhammer (https://github.com/mgrie)
* Date: 2025-01-21
* Version: 0.1
*
* ToDo: write initial values on first run
* Idea: use 2 KVS entries instead of JSON
* ToDo: write periodic to virtual component, if available (InMemory)
* ToDo: support multiple switch components (array)
*/
const CONFIG = {
component: 'switch:0',
kvsKey: 'operation-hours-counter',
//componentSeconds: 'label:200',
//componentHours: 'label:201'
}
// set dynamic at initEnv()
let ENV = {
mqttTopicPrefix: undefined,
mqttClientId: undefined
};
// logger
function log(message) {
try {
if (typeof message === 'object') {
message = JSON.stringify(message);
} else if (typeof message !== 'string') {
message = message.toString();
}
print(message);
// Shelly.emitEvent("log", message);
if (MQTT.isConnected()) {
MQTT.publish(ENV.mqttTopicPrefix + "/log", message);
}
} catch (error) {
print("Error: " + JSON.stringify(error));
}
}
// init script environment
function initEnv(callback) {
Shelly.call('MQTT.GetConfig', {}, function (result, error_code, error_message, userdata) {
if (error_code) log({ error_code: error_code, error_message: error_message });
if (error_code === 0 && result) {
ENV.mqttTopicPrefix = result.topic_prefix;
ENV.mqttClientId = result.client_id;
}
callback();
});
}
function addTimespanToKVS(timespan){
Shelly.call('KVS.Get', {key: CONFIG.kvsKey}, function(result, error_code, error_message, ud){
let data = {totalHours:0,totalSeconds:0,lastSeconds:0, lastHours:0, cycles:0};
if(error_code) {
log(error_code + ': ' + error_message);
} else {
log(result);
data = JSON.parse(result.value);
}
data.lastSeconds = timespan;
data.lastHours = Math.round(timespan/360);
data.totalSeconds = data.totalSeconds + timespan;
data.totalHours = Math.round(data.totalSeconds/360);
data.cycles++;
Shelly.call('KVS.Set', {key:CONFIG.kvsKey, value:JSON.stringify(data)}, function(result, error_code, error_message, ud){
if(error_code) log(error_code + ': ' + error_message);
}, null);
},null);
}
function main(){
const userdata = {ts: null};
Shelly.addEventHandler(function(data, ud){
if(!data || !data.info) return;
if(data.component === CONFIG.component && data.info.event === 'toggle'){
// on
if(data.info.state === true){
ud.ts = data.info.ts;
}
// off
if(data.info.state === false){
if(ud.ts != null){
addTimespanToKVS(Math.round(data.info.ts - ud.ts));
}
}
}
}, userdata);
}
initEnv(main);
Alles anzeigen