Page 1 of 2

Virtual meter that is the sum of two other meters

Posted: Friday 04 August 2017 21:05
by benbammens
Is there a way to create a virtual energy meter that is the sum/subtraction of 2 or more other meters?

I now have a meter that logs the production of my solar panels , one that logs the exported electricity and one that logs the imported energy from the grid.

From this I could calculate my total consumption as: total = generated - exported + imported.

Seems easy enough, but I don't know if this is possible in Domoticz...

Re: Virtual meter that is the sum of two other meters

Posted: Sunday 06 August 2017 23:39
by niceandeasy
I don't think Domoticz has a ready-made virtual meter that can add up the values of a list of other meters. However, you can do that with scripting.

Re: Virtual meter that is the sum of two other meters

Posted: Monday 07 August 2017 8:48
by freijn
This is the lua code I am using to do this virtual meter, however.....

Updates from my solare panel are much slower than from my P1 smart meter.
On a steady ( no clouds ) day it works great. On a cloudy day it could be the solar panels are still reporting "no power" and the house
is consuming a lot, while on my P1 updates I do see a different indication. So this can only be used as a guideline but gives you a good
indication during the day.

Cheers,

Frank

Code: Select all

--
-- Domoticz passes information to scripts through a number of global tables
--
-- device changed contains state and svalues for the device that changed.
--   devicechanged['yourdevicename'] = state 
--   devicechanged['svalues'] = svalues string 
--
commandArray = {}

--powersensor = "Power"

--if (devicechanged[powersensor]) then
 --  print( " ####Power debug: "..devicechanged[powersensor])
   -- commandArray['Variable:LUX']=tostring(devicechanged[luxsensor])
--  var1, var2,var3,var4,var5,var6 = string.match(otherdevices_svalues['Power'], "(%d+%.*%d*);(%d+%.*%d*);(%d+%.*%d*);(%d+%.*%d*);(%d+%.*%d*);(%d+%.*%d*)")
--   print( " ####Power debug: "..var6)
 --  end

solarsensor = "SolarEdge kWh"
if (devicechanged[solarsensor]) then
   --print( " ####Solar debug: "..devicechanged[solarsensor])
   Solarvar1, var2 = string.match(otherdevices_svalues[solarsensor], "(%d+%.*%d*);(%d+%.*%d*)")
   print( " ####Solar debug: "..Solarvar1)

   powersensor = "Power"
   -- if (devicechanged[powersensor]) then
   --print( " ####Power debug: "..devicechanged[powersensor])
   var1, var2,var3,var4,Powervar5,Powervar6 = string.match(otherdevices_svalues['Power'], "(%d+%.*%d*);(%d+%.*%d*);(%d+%.*%d*);(%d+%.*%d*);(%d+%.*%d*);(%d+%.*%d*)")
   print( " ####Power debug: "..Powervar5)

   powercount = tonumber(Powervar6)
   solarcount = tonumber(Solarvar1)
 
   consume = solarcount - powercount
   print( " ####Consume debug: "..consume)
 
   ttidx = otherdevices_idx['PowerConsumtion']
   commandArray['UpdateDevice'] = ttidx..'|0|'..consume
end

return commandArray

Re: Virtual meter that is the sum of two other meters

Posted: Wednesday 13 December 2017 14:49
by gajotnt
Hello, tried to figure out the code you provided :/

I have a meter for the main house, and another meter for a small apartement on the back (that is connected to the main house)
So i would like to subtract the apartment meter from the main house meter, so the resulte gives me what i im actualy using in the main house.
But by looking at the code above i have no ideia how to do this :/

Re: Virtual meter that is the sum of two other meters

Posted: Wednesday 13 December 2017 15:20
by l0gic
Hi,
I've also done something similar.
I've a number of power clamps monitoring power into my main consumer unit, outside consumer unit plus I have a feed from my SunnyBoy solar.
I use these to indicate via a dummy power devices the instantaneous usage (Kw) and historical (Kwh).
The devices indicate the total house load (House + Outside) as well as the incoming demand (Total - Solar).

My script also writes out to a csv file, not necessary for the script though.
As it stands the script writes out to the log a lot, change it by setting the printdata / printdebug values to false.

Code: Select all

-- demo time script

-- Set printing to log options (true / false)
printData = true
-- printData = false						-- writes execution information to the log for script performance information
-- printDebug = false						-- writes detailed information for fault finding purposes
 printDebug = true

-- Get current date & time
t1 = os.time()
local currentDate = os.date("*t");  -- sets up currentDate.[table] 
-- (currentDate.year [full], .month [1-12], .day [1-31], .hour [0-23], .min [0-59], .sec [0-59], .wday [0-6 {Sun-Sat}])
sCurrentTime = currentDate.year .. "-" .. currentDate.month .. "-" .. currentDate.day .. " " .. currentDate.hour .. ":" .. currentDate.min .. ":" .. currentDate.sec

function update(device, id, power, energy, index)
commandArray[index] = {['UpdateDevice'] = id .. "|0|" .. power .. ";" .. energy}
end 


commandArray = {}

SolarPowerGeneration, SolarEnergyGeneration = otherdevices_svalues["Solar Generation"]:match("([^;]+);([^;]+)")

if printDebug == true then
	print(" ----- SolarPowerGeneration = " .. SolarPowerGeneration .. " W");
	print(" ----- SolarEnergyGeneration = " .. SolarEnergyGeneration .. " Wh");
end

MainCUPowerUsage, MainCUEnergyUsage = otherdevices_svalues["Main Consumer Unit"]:match("([^;]+);([^;]+)")

if printDebug == true then
	print(" ----- MainCUPowerUsage = " .. MainCUPowerUsage .. " W");
	print(" ----- MainCUEnergyUsage = " .. MainCUEnergyUsage .. " Wh");
end

GardenCUPowerUsage, GardenCUEnergyUsage = otherdevices_svalues["Garden Consumer Unit"]:match("([^;]+);([^;]+)")

if printDebug == true then
print(" ----- GardenCUPowerUsage = " .. GardenCUPowerUsage .. " W");
print(" ----- GardenCUEnergyUsage = " .. GardenCUEnergyUsage .. " Wh");
end
-- Do the calculations
-- CurrentPowerBalance = SolarPowerGeneration - (MainCUPowerUsage + GardenCUPowerUsage)
-- CurrentEnergyBalance = SolarEnergyGeneration - (MainCUEnergyUsage + GardenCUEnergyUsage)
CurrentPowerBalance = (MainCUPowerUsage + GardenCUPowerUsage) - SolarPowerGeneration
CurrentEnergyBalance = (MainCUEnergyUsage + GardenCUEnergyUsage) - SolarEnergyGeneration

HousePower = (MainCUPowerUsage + GardenCUPowerUsage)
HouseEnergy = (MainCUEnergyUsage + GardenCUEnergyUsage)

if printDebug == true then	
	print(" ----- CurrentPowerBalance = " .. CurrentPowerBalance .. " W");
	print(" ----- CurrentEnergyBalance = " .. CurrentEnergyBalance .. " Wh");
end

if printData == true then	

	if CurrentPowerBalance <0 then
		print("FREE Electric - Whoop!    " .. CurrentPowerBalance .. "W");
	end
end
	
-- update the counters	
-- Total power 
update("House Power Incoming", 475, CurrentPowerBalance, CurrentEnergyBalance, 1) -- 475 is the ID of the dummy incoming device
-- Load of the House	
update("House Load", 518, HousePower, HouseEnergy, 2) -- 518 is the ID of dummy house consumption device

-- update the user variables (used to write to a csv for futher analysis)
-- House Load
commandArray['Variable:VarHouseLoad_Power'] = tostring(HousePower)
commandArray['Variable:VarHouseLoad_Energy'] = tostring(HouseEnergy)
-- Grid Load
commandArray['Variable:VarGridLoad_Power'] = tostring(CurrentPowerBalance)
commandArray['Variable:VarGridLoad_Energy'] = tostring(CurrentEnergyBalance)
-- MainCU Load
commandArray['Variable:VarMainCU_Power'] = tostring(MainCUPowerUsage)
commandArray['Variable:VarMainCU_Energy'] = tostring(MainCUEnergyUsage)
-- Garden CU Load
commandArray['Variable:VarGardenCU_Power'] = tostring(GardenCUPowerUsage)
commandArray['Variable:VarGardenCU_Energy'] = tostring(GardenCUEnergyUsage)
	


	
   -- save new values to file

   file = io.open("/opt/scripts/housepower.csv", "a") -- append
   file:write("\n")  -- new line
   file:write (sCurrentTime)
   file:write(",")
   file:write(HousePower) -- Total House Load
   file:write(",")
   file:write(MainCUPowerUsage) -- Main CU
   file:write(",")
   file:write(GardenCUPowerUsage) --  Garden CU
   file:write(",")
   file:write(CurrentPowerBalance) -- Grid Demand
   file:close()
   

return commandArray
Be careful with the type of dummy device you create, you need the Type = Usage and Energy Read = From Device

HTH

Kevin

Re: Virtual meter that is the sum of two other meters

Posted: Wednesday 13 December 2017 16:43
by gajotnt
-MainCU
-GardenCU
-Solar

are the names of your meter sensors in domoticz right?

Re: Virtual meter that is the sum of two other meters

Posted: Wednesday 13 December 2017 18:13
by gajotnt
Got it working, thanks :D

Re: Virtual meter that is the sum of two other meters

Posted: Wednesday 13 December 2017 18:40
by l0gic
gajotnt wrote: Wednesday 13 December 2017 16:43 -MainCU
-GardenCU
-Solar

are the names of your meter sensors in domoticz right?
Yeah, I'm a bit late in replying.
Glad it's all working.

Re: Virtual meter that is the sum of two other meters

Posted: Friday 15 December 2017 12:13
by gajotnt
Did some tweaking, in the sense i removed all of the CVS log stuff.
But have there some douts.
-- Total power
update("House Power Incoming", 475, CurrentPowerBalance, CurrentEnergyBalance, 1) -- 475 is the ID of the dummy incoming device
-- Load of the House
update("House Load", 518, HousePower, HouseEnergy, 2) -- 518 is the ID of dummy house consumption device
What does the 1 (in total power) and 2 (in House), mean?

Also im doing some troubleshooting because arround the time i started using this, the TOTAL meter stopped updating the "Energy Usage" graph, but i think its because of the firmware of the metering device and not the script, since i guess it only reads the value does the calculations and writes it to another virtual meter, but still can you take a look?

Total: is the meter that gets information from the whole house
Apartamento: is the meter that gets information from a apartment
Casa: the result of the subtration of the apartment from the Total value

This is the code im using:

Code: Select all

-- demo time script

-- Get current date & time
t1 = os.time()
local currentDate = os.date("*t");  -- sets up currentDate.[table] 
-- (currentDate.year [full], .month [1-12], .day [1-31], .hour [0-23], .min [0-59], .sec [0-59], .wday [0-6 {Sun-Sat}])
sCurrentTime = currentDate.year .. "-" .. currentDate.month .. "-" .. currentDate.day .. " " .. currentDate.hour .. ":" .. currentDate.min .. ":" .. currentDate.sec

function update(device, id, power, energy, index)
commandArray[index] = {['UpdateDevice'] = id .. "|0|" .. power .. ";" .. energy}
end 

commandArray = {}

TotalPowerUsage, TotalEnergyUsage = otherdevices_svalues["Total"]:match("([^;]+);([^;]+)")

ApartamentoPowerUsage, ApartamentoEnergyUsage = otherdevices_svalues["Apartamento"]:match("([^;]+);([^;]+)")

CurrentPowerBalance = TotalPowerUsage - ApartamentoPowerUsage
CurrentEnergyBalance = TotalEnergyUsage - ApartamentoEnergyUsage

update("Casa", 50, CurrentPowerBalance, CurrentEnergyBalance, 2) -- 50 is the ID of the dummy incoming device


return commandArray

Re: Virtual meter that is the sum of two other meters

Posted: Friday 15 December 2017 16:21
by l0gic
Hi,
The 1 and 2 refer to the commandArray[x] values.
If you only update one value when running the script then this value can be 1.
If you chose to update 2 or more values then they all need their own commandArray[x] value. Otherwise only the last commandArray value will be updated.

Your script looks fine to me, I can't see any reason why it wouldn't work.
Try putting some print commands in so you can see in the logs if the expected values are in there.

ATB

Kevin

Re: Virtual meter that is the sum of two other meters

Posted: Friday 15 December 2017 17:39
by gajotnt
Thanks :)
After some testing it was the FW of the sonoff that was sending the KWhToday instead of the KWhTotal, everything is working now :)
Thanks

Re: Virtual meter that is the sum of two other meters

Posted: Friday 11 May 2018 23:28
by SunnyBoy
I wanted to do the same, and using this thread and some other links I managed to get it to work as well.

I documented this in the wiki here for future reference, please expand where you can: https://www.domoticz.com/wiki/Virtual_meter. Hope this helps others :)

Re: Virtual meter that is the sum of two other meters

Posted: Monday 04 February 2019 9:56
by Gertschi
Hi,
I used this script

Code: Select all

-- /home/pi/domoticz/scripts/lua/script_device_calculate_consumption.lua

 
----------------------------------------------------------------------------------------------------------
-- Domoticz IDX and names of the needed devices
----------------------------------------------------------------------------------------------------------
local DeviceName1 = "kWh Meter L1"
local DeviceName2 = "kWh Meter L2"
local DeviceName3 = "kWh Meter L3"
local ConsumptionIDX = 343  		                	-- IDX of the energy device that shows calculated Consumption
local ConsumptionDeviceName = "Gesamtverbrauch" 		-- Name of the energy device that shows calculated Consumption

----------------------------------------------------------------------------------------------------------
-- Script parameters
----------------------------------------------------------------------------------------------------------
Energy1 = 0 -- in Watt hours
Power1 = 0 	-- in Watts
Energy2 = 0	-- in Watt hours
Power2 = 0	-- in Watts
Energy3 = 0 -- in Watt hours
Power3 = 0 	-- in Watts
EnergyConsumption = 0 	-- in Watt hours
PowerConsumption = 0 	-- in Watts
Debug = "NO" 	    	-- Turn debugging on ("YES") or off ("NO")
 
---------------------------------------------------------------------------------------------------------
-- Get current date & time
---------------------------------------------------------------------------------------------------------
--t1 = os.time()
--local currentDate = os.date("*t");  -- sets up currentDate.[table] 
-- --(currentDate.year [full], .month [1-12], .day [1-31], .hour [0-23], .min [0-59], .sec [0-59], .wday [0-6 {Sun-Sat}])
--sCurrentTime = currentDate.year .. "-" .. currentDate.month .. "-" .. currentDate.day .. " " .. currentDate.hour .. ":" .. currentDate.min .. ":" .. currentDate.sec
----------------------------------------------------------------------------------------------------------
-- Lua Functions
----------------------------------------------------------------------------------------------------------
function update(device, id, power, energy, index)
	commandArray[index] = {['UpdateDevice'] = id .. "|0|" .. power .. ";" .. energy}
end 

----------------------------------------------------------------------------------------------------------
-- CommandArray
----------------------------------------------------------------------------------------------------------
commandArray = {}
	Power1, Energy1 = otherdevices_svalues[DeviceName1]:match("([^;]+);([^;]+)")
	if Debug=="YES" then
		print("  ----- ".. DeviceName1 .. "Power = " .. Power1 .. " W");
		print("  ----- ".. DeviceName1 .. "Energy = " .. Energy1 .. " Wh");
	end
 
	Power2, Energy2 = otherdevices_svalues[DeviceName2]:match("([^;]+);([^;]+)")
	if Debug=="YES" then
		print("  ----- ".. DeviceName2 .. "Power = " .. Power2 .. " W");
		print("  ----- ".. DeviceName2 .. "Energy = " .. Energy2 .. " Wh");
	end
	
	Power3, Energy3 = otherdevices_svalues[DeviceName3]:match("([^;]+);([^;]+)")
	if Debug=="YES" then
		print("  ----- ".. DeviceName3 .. "Power = " .. Power3 .. " W");
		print("  ----- ".. DeviceName3 .. "Energy = " .. Energy3 .. " Wh");
	end

--	Power4, Energy4 = otherdevices_svalues[DeviceName4]:match("([^;]+);([^;]+)")
--	if Debug=="YES" then
--		print("  ----- ".. DeviceName4 .. "Power = " .. Power4 .. " W");
--		print("  ----- ".. DeviceName4 .. "Energy = " .. Energy4 .. " Wh");
--	end
 
--	Power5, Energy5 = otherdevices_svalues[DeviceName5]:match("([^;]+);([^;]+)")
--	if Debug=="YES" then
--		print("  ----- ".. DeviceName5 .. "Power = " .. Power5 .. " W");
--		print("  ----- ".. DeviceName5 .. "Energy = " .. Energy5 .. " Wh");
--	end
 
	-- Calculate consumption
	PowerConsumption = Power1 + Power2 + Power3
	if Debug=="YES" then
		print("  ----- PowerConsumption = " .. PowerConsumption .. "W");
	end
	EnergyConsumption = Energy1 + Energy2 + Energy3
	if Debug=="YES" then
		print("  ----- EnergyConsumption = " .. EnergyConsumption .. "Wh");
	end
 
	-- Update comsumption device in Domoticz
	if devicechanged[DeviceName1] or devicechanged[DeviceName2] or devicechanged[DeviceName3] then
		update(ConsumptionDeviceName, ConsumptionIDX, PowerConsumption, EnergyConsumption, 1)

	end
to sum energy and power from 3 meters (kWh Meter L1, kWh Meter L2 and kWh Meter L3), because my device for the whole powerconsumtion (kWh Meter Gesamt) shows only the sum of absolute Power [W].
But for this issue I have already opened a thread, https://www.domoticz.com/forum/viewtopi ... 24&t=26760 >>> no answer so far.

The script works, but the energy shows the whole energy consumption instead of energyconsumtion of the day.
energy.JPG
energy.JPG (51.73 KiB) Viewed 8708 times
What could I do, to get the daily energy consumption?

Re: Virtual meter that is the sum of two other meters

Posted: Monday 04 February 2019 13:59
by Gertschi
I don´t know but maybe this could help:

The device for the whole powerconsumtion (kWh Meter Gesamt):
Spoiler: show

Code: Select all

 {
         "AddjMulti" : 1.0,
         "AddjMulti2" : 1.0,
         "AddjValue" : 0.0,
         "AddjValue2" : 0.0,
         "BatteryLevel" : 255,
         "CounterToday" : "7.079 kWh",
         "CustomImage" : 0,
         "Data" : "220.368 kWh",
         "Description" : "",
         "Favorite" : 0,
         "HardwareID" : 2,
         "HardwareName" : "Zwave",
         "HardwareType" : "OpenZWave USB",
         "HardwareTypeVal" : 21,
         "HaveTimeout" : false,
         "ID" : "00001A01",
         "LastUpdate" : "2019-02-04 13:37:14",
         "Name" : "kWh Meter Gesamt",
         "Notifications" : "false",
         "Options" : "0",
         "PlanID" : "0",
         "PlanIDs" : [ 0 ],
         "Protected" : false,
         "ShowNotifications" : true,
         "SignalLevel" : "-",
         "SubType" : "kWh",
         "SwitchTypeVal" : 0,
         "Timers" : "false",
         "Type" : "General",
         "TypeImg" : "current",
         "Unit" : 1,
         "Usage" : "1168.77 Watt",
         "Used" : 1,
         "XOffset" : "0",
         "YOffset" : "0",
         "idx" : "240"
      },
The dummydevice Gesamtverbrauch. Here we can see that the "CounterToday" is the same as "Date":
Spoiler: show

Code: Select all

{
         "AddjMulti" : 1.0,
         "AddjMulti2" : 1.0,
         "AddjValue" : 0.0,
         "AddjValue2" : 0.0,
         "BatteryLevel" : 255,
         "CounterToday" : "220.388 kWh",
         "CustomImage" : 0,
         "Data" : "220.388 kWh",
         "Description" : "",
         "Favorite" : 1,
         "HardwareID" : 26,
         "HardwareName" : "Electricity",
         "HardwareType" : "Dummy (Does nothing, use for virtual switches only)",
         "HardwareTypeVal" : 15,
         "HaveTimeout" : false,
         "ID" : "00082343",
         "LastUpdate" : "2019-02-04 13:37:14",
         "Name" : "Gesamtverbrauch",
         "Notifications" : "false",
         "Options" : "1",
         "PlanID" : "2",
         "PlanIDs" : [ 2, 9 ],
         "Protected" : false,
         "ShowNotifications" : true,
         "SignalLevel" : "-",
         "SubType" : "kWh",
         "SwitchTypeVal" : 0,
         "Timers" : "false",
         "Type" : "General",
         "TypeImg" : "current",
         "Unit" : 1,
         "Usage" : "-1168.77 Watt",
         "Used" : 1,
         "XOffset" : "32",
         "YOffset" : "113",
         "idx" : "343"
      },
The device for power and energyconsumption from kWh Meter L1, the same as L2 and L3:
Spoiler: show

Code: Select all

 {
         "AddjMulti" : 1.0,
         "AddjMulti2" : 1.0,
         "AddjValue" : 0.0,
         "AddjValue2" : 0.0,
         "BatteryLevel" : 255,
         "CounterToday" : "4.284 kWh",
         "CustomImage" : 0,
         "Data" : "144.733 kWh",
         "Description" : "",
         "Favorite" : 0,
         "HardwareID" : 2,
         "HardwareName" : "Zwave",
         "HardwareType" : "OpenZWave USB",
         "HardwareTypeVal" : 21,
         "HaveTimeout" : false,
         "ID" : "00001A02",
         "LastUpdate" : "2019-02-04 13:37:14",
         "Name" : "kWh Meter L1",
         "Notifications" : "false",
         "Options" : "0",
         "PlanID" : "0",
         "PlanIDs" : [ 0 ],
         "Protected" : false,
         "ShowNotifications" : true,
         "SignalLevel" : "-",
         "SubType" : "kWh",
         "SwitchTypeVal" : 0,
         "Timers" : "false",
         "Type" : "General",
         "TypeImg" : "current",
         "Unit" : 1,
         "Usage" : "-189.489 Watt",
         "Used" : 1,
         "XOffset" : "0",
         "YOffset" : "0",
         "idx" : "244"
      },
Hopefully this could help someone.

Re: Virtual meter that is the sum of two other meters

Posted: Wednesday 06 February 2019 1:23
by Gertschi
Ok, it´s solved :roll:

energy.JPG
energy.JPG (22.85 KiB) Viewed 8659 times

The one who could wait has a clear advantage ;)

Re: Virtual meter that is the sum of two other meters

Posted: Wednesday 06 February 2019 22:32
by thearr
I also have something similar to this, but as DzVents script

Code: Select all

return {

	on = {
	    timer = { 'every 5 minutes' }
	},
	
	execute = function(domoticz, item)
	    
	    local bhPower = domoticz.devices(3)      -- big house power meter
	    local fhPower = domoticz.devices(53)     -- forest house power meter
	    local totalPower = domoticz.devices(54)  -- total (big + forest houses) power meter
	    
	    totalPower.updateElectricity(
            	bhPower.WhActual + fhPower.WhActual,
            	bhPower.WhTotal + fhPower.WhTotal
            )
	    
	end
	
}

Re: Virtual meter that is the sum of two other meters

Posted: Tuesday 28 May 2019 10:07
by Heelderpeel
Gertschi wrote: Wednesday 06 February 2019 1:23 Ok, it´s solved :roll:


energy.JPG


The one who could wait has a clear advantage ;)
Hello Gertschi,

I used your script to add 3 different solar panel installations, it works fine.
Only the same problem with the total P instead of the day P

Would you like to post the script in which you solved it?
I don't have the programming knowledge to get this solved. :cry:

thank you.

Greetings,
Maurice

Re: Virtual meter that is the sum of two other meters

Posted: Saturday 01 February 2020 18:21
by tjabas
thearr wrote: Wednesday 06 February 2019 22:32 I also have something similar to this, but as DzVents script

Code: Select all

return {

	on = {
	    timer = { 'every 5 minutes' }
	},
	
	execute = function(domoticz, item)
	    
	    local bhPower = domoticz.devices(3)      -- big house power meter
	    local fhPower = domoticz.devices(53)     -- forest house power meter
	    local totalPower = domoticz.devices(54)  -- total (big + forest houses) power meter
	    
	    totalPower.updateElectricity(
            	bhPower.WhActual + fhPower.WhActual,
            	bhPower.WhTotal + fhPower.WhTotal
            )
	    
	end
	
}
i cant get this script to work, i have replaced the (3), (53) and (54) with my own idx for my sensors, but i dont think that the script is running.

Re: Virtual meter that is the sum of two other meters

Posted: Saturday 01 February 2020 23:10
by tjabas
Gertschi wrote: Monday 04 February 2019 9:56 Hi,
I used this script

Code: Select all

-- /home/pi/domoticz/scripts/lua/script_device_calculate_consumption.lua

 
----------------------------------------------------------------------------------------------------------
-- Domoticz IDX and names of the needed devices
----------------------------------------------------------------------------------------------------------
local DeviceName1 = "kWh Meter L1"
local DeviceName2 = "kWh Meter L2"
local DeviceName3 = "kWh Meter L3"
local ConsumptionIDX = 343  		                	-- IDX of the energy device that shows calculated Consumption
local ConsumptionDeviceName = "Gesamtverbrauch" 		-- Name of the energy device that shows calculated Consumption

----------------------------------------------------------------------------------------------------------
-- Script parameters
----------------------------------------------------------------------------------------------------------
Energy1 = 0 -- in Watt hours
Power1 = 0 	-- in Watts
Energy2 = 0	-- in Watt hours
Power2 = 0	-- in Watts
Energy3 = 0 -- in Watt hours
Power3 = 0 	-- in Watts
EnergyConsumption = 0 	-- in Watt hours
PowerConsumption = 0 	-- in Watts
Debug = "NO" 	    	-- Turn debugging on ("YES") or off ("NO")
 
---------------------------------------------------------------------------------------------------------
-- Get current date & time
---------------------------------------------------------------------------------------------------------
--t1 = os.time()
--local currentDate = os.date("*t");  -- sets up currentDate.[table] 
-- --(currentDate.year [full], .month [1-12], .day [1-31], .hour [0-23], .min [0-59], .sec [0-59], .wday [0-6 {Sun-Sat}])
--sCurrentTime = currentDate.year .. "-" .. currentDate.month .. "-" .. currentDate.day .. " " .. currentDate.hour .. ":" .. currentDate.min .. ":" .. currentDate.sec
----------------------------------------------------------------------------------------------------------
-- Lua Functions
----------------------------------------------------------------------------------------------------------
function update(device, id, power, energy, index)
	commandArray[index] = {['UpdateDevice'] = id .. "|0|" .. power .. ";" .. energy}
end 

----------------------------------------------------------------------------------------------------------
-- CommandArray
----------------------------------------------------------------------------------------------------------
commandArray = {}
	Power1, Energy1 = otherdevices_svalues[DeviceName1]:match("([^;]+);([^;]+)")
	if Debug=="YES" then
		print("  ----- ".. DeviceName1 .. "Power = " .. Power1 .. " W");
		print("  ----- ".. DeviceName1 .. "Energy = " .. Energy1 .. " Wh");
	end
 
	Power2, Energy2 = otherdevices_svalues[DeviceName2]:match("([^;]+);([^;]+)")
	if Debug=="YES" then
		print("  ----- ".. DeviceName2 .. "Power = " .. Power2 .. " W");
		print("  ----- ".. DeviceName2 .. "Energy = " .. Energy2 .. " Wh");
	end
	
	Power3, Energy3 = otherdevices_svalues[DeviceName3]:match("([^;]+);([^;]+)")
	if Debug=="YES" then
		print("  ----- ".. DeviceName3 .. "Power = " .. Power3 .. " W");
		print("  ----- ".. DeviceName3 .. "Energy = " .. Energy3 .. " Wh");
	end

--	Power4, Energy4 = otherdevices_svalues[DeviceName4]:match("([^;]+);([^;]+)")
--	if Debug=="YES" then
--		print("  ----- ".. DeviceName4 .. "Power = " .. Power4 .. " W");
--		print("  ----- ".. DeviceName4 .. "Energy = " .. Energy4 .. " Wh");
--	end
 
--	Power5, Energy5 = otherdevices_svalues[DeviceName5]:match("([^;]+);([^;]+)")
--	if Debug=="YES" then
--		print("  ----- ".. DeviceName5 .. "Power = " .. Power5 .. " W");
--		print("  ----- ".. DeviceName5 .. "Energy = " .. Energy5 .. " Wh");
--	end
 
	-- Calculate consumption
	PowerConsumption = Power1 + Power2 + Power3
	if Debug=="YES" then
		print("  ----- PowerConsumption = " .. PowerConsumption .. "W");
	end
	EnergyConsumption = Energy1 + Energy2 + Energy3
	if Debug=="YES" then
		print("  ----- EnergyConsumption = " .. EnergyConsumption .. "Wh");
	end
 
	-- Update comsumption device in Domoticz
	if devicechanged[DeviceName1] or devicechanged[DeviceName2] or devicechanged[DeviceName3] then
		update(ConsumptionDeviceName, ConsumptionIDX, PowerConsumption, EnergyConsumption, 1)

	end
to sum energy and power from 3 meters (kWh Meter L1, kWh Meter L2 and kWh Meter L3), because my device for the whole powerconsumtion (kWh Meter Gesamt) shows only the sum of absolute Power [W].
But for this issue I have already opened a thread, https://www.domoticz.com/forum/viewtopi ... 24&t=26760 >>> no answer so far.

The script works, but the energy shows the whole energy consumption instead of energyconsumtion of the day.

energy.JPG

What could I do, to get the daily energy consumption?
i have tried your script but i get these errors in the log:
2020-02-01 23:09:27.105 Error: EventSystem: in Script #1: [string "-- /home/pi/domoticz/scripts/lua/script_devic..."]:75: attempt to perform arithmetic on global 'Power1' (a nil value)
2020-02-01 23:09:33.108 Error: EventSystem: in Script #1: [string "-- /home/pi/domoticz/scripts/lua/script_devic..."]:75: attempt to perform arithmetic on global 'Power1' (a nil value)
2020-02-01 23:09:33.150 Error: EventSystem: in Script #1: [string "-- /home/pi/domoticz/scripts/lua/script_devic..."]:75: attempt to perform arithmetic on global 'Power1' (a nil value)

Re: Virtual meter that is the sum of two other meters

Posted: Friday 14 February 2020 8:45
by MikeyMan
tjabas wrote: Saturday 01 February 2020 18:21
thearr wrote: Wednesday 06 February 2019 22:32 I also have something similar to this, but as DzVents script

Code: Select all

return {

	on = {
	    timer = { 'every 5 minutes' }
	},
	
	execute = function(domoticz, item)
	    
	    local bhPower = domoticz.devices(3)      -- big house power meter
	    local fhPower = domoticz.devices(53)     -- forest house power meter
	    local totalPower = domoticz.devices(54)  -- total (big + forest houses) power meter
	    
	    totalPower.updateElectricity(
            	bhPower.WhActual + fhPower.WhActual,
            	bhPower.WhTotal + fhPower.WhTotal
            )
	    
	end
	
}
i cant get this script to work, i have replaced the (3), (53) and (54) with my own idx for my sensors, but i dont think that the script is running.
Did you enable dzvents in settings?