I think this copes with all the conditions.
// Given current total energy from Shelly in msg.payload
let runningTotalEnergy = global.get("runningTotalEnergy", "storeInFile") || 0
let previousShellyValue = global.get("previousShellyValue", "storeInFile") || 0
// test whether the Shelly has reset since last input
if (msg.payload < previousShellyValue) {
// yes it has, just add new value to the total
runningTotalEnergy += msg.payload
} else {
// no so add the difference between this and last to the running total
runningTotalEnergy += msg.payload - previousShellyValue
}
global.set("previousShellyValue", msg.payload, "storeInFile")
global.set("runningTotalEnergy",runningTotalEnergy, "storeInFile")
msg.payload = runningTotalEnergy
return msg;
Here is a test flow to check it out
[{"id":"565dd42b.e2948c","type":"debug","z":"514a90a5.c7bae8","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":560,"y":1119,"wires":[]},{"id":"d383a419.4cdff8","type":"inject","z":"514a90a5.c7bae8","name":"","topic":"","payload":"0","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":133,"y":1021,"wires":[["f3e295a2.fbe39"]]},{"id":"62fc919c.21a678","type":"inject","z":"514a90a5.c7bae8","name":"","topic":"","payload":"1","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":127,"y":1080,"wires":[["f3e295a2.fbe39"]]},{"id":"eb957dc3.1c2c5","type":"inject","z":"514a90a5.c7bae8","name":"","topic":"","payload":"10","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":129,"y":1145,"wires":[["f3e295a2.fbe39"]]},{"id":"444dffc.dac8a8","type":"inject","z":"514a90a5.c7bae8","name":"","topic":"","payload":"20","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":133,"y":1211,"wires":[["f3e295a2.fbe39"]]},{"id":"f3e295a2.fbe39","type":"function","z":"514a90a5.c7bae8","name":"Total Energy","func":"// Given current total energy from Shelly in msg.payload\nlet runningTotalEnergy = global.get(\"runningTotalEnergy\", \"storeInFile\") || 0\nlet previousShellyValue = global.get(\"previousShellyValue\", \"storeInFile\") || 0\n// test whether the Shelly has reset since last input\nif (msg.payload < previousShellyValue) {\n // yes it has, just add new value to the total\n runningTotalEnergy += msg.payload\n} else {\n // no so add the difference between this and last to the running total\n runningTotalEnergy += msg.payload - previousShellyValue\n}\nglobal.set(\"previousShellyValue\", msg.payload, \"storeInFile\")\nglobal.set(\"runningTotalEnergy\",runningTotalEnergy, \"storeInFile\")\nmsg.payload = runningTotalEnergy\nreturn msg;","outputs":1,"noerr":0,"x":362,"y":1119,"wires":[["565dd42b.e2948c"]]}]