Months kWh usage to virtual counter  [Solved]

Easy to use, 100% Lua-based event scripting framework.

Moderator: leecollings

Post Reply
User avatar
djdevil
Posts: 101
Joined: Friday 26 July 2019 18:19
Target OS: Raspberry Pi / ODroid
Domoticz version: 2021.1
Contact:

Months kWh usage to virtual counter

Post by djdevil »

Hi everyone, I need to create a virtual kWh counter used monthly and read the data from my energy meter. place the photos to better understand, I tried to use this script but it shows me the daily Khw and not the total monthly ones

Code: Select all

local httpResponses = "monthTotal"

return {
    on      =   {   
                    timer           =   { "every 15 minutes" },
                    httpResponses   =   { httpResponses .. "*" } 
                },

    logging =   {   
                    level           =   domoticz.LOG_DEBUG, -- set to LOG_ERROR when script works as expected
                    marker          =   httpResponse   
                },
                
    execute = function(dz, item)
        -- ****************************** Your settings below this line ***************************************************
        usageDevice = dz.devices(xxxx)          -- Replace xxxx with ID of energyDevice you want to track
        monthTotal = dz.devices(yyyy)        -- Create as virtual managed counter (energy) and change yyyy to the ID of the new device
        -- ****************************** No changes required below this line *********************************************
        
        local function logWrite(str,level)
            dz.log(tostring(str),level or dz.LOG_DEBUG)
        end
        
        local function triggerJSON(id, period, delay)
            local delay = delay or 0
            local  URLString   =    dz.settings['Domoticz url'] .. "/json.htm?type=graph&sensor=counter&range=" .. 
                                    period .. "&idx=" .. id 
            dz.openURL({    url = URLString,
                            method = "GET",
                            callback = httpResponses .. "_" .. period}).afterSec(delay)                      
        end
        
        local function calculateMonthTotal(rt)
            local monthTotal = 0
            local currentMonth = dz.time.rawDate:sub(1,7)
            for id, result in  ipairs(rt) do 
                if rt[id].d:sub(1,7) == currentMonth then
                    logWrite(rt[id].d .. " ==>> " .. rt[id].v)
                    monthTotal = monthTotal + rt[id].v
                end
            end
            return monthTotal * 1000
        end    
        
        if not item.isHTTPResponse then
            triggerJSON(usageDevice.id, "month")
        elseif item.ok then                                      -- statusCode == 2xx
            monthTotal.update(0,calculateMonthTotal(item.json.result))
        else
            logWrite("Could not get (good) data from domoticz. Error (" .. (item.statusCode or 999) .. ")"  ,dz.LOG_ERROR)
            logWrite(item.data)
        end
    end
}
Image
hosting immagini gratis
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Months kWh usage to virtual counter

Post by waaren »

djdevil wrote: Monday 09 December 2019 20:08 Hi everyone, I need to create a virtual kWh counter used monthly and read the data from my energy meter. place the photos to better understand, I tried to use this script but it shows me the daily Khw and not the total monthly ones
rl=https://it.imgbb.com/]hosting immagini gratis[/url]
You created a virtual device counter. You should create a virtual device managed counter

btw. Please also change

Code: Select all

marker = httpResponse
to

Code: Select all

marker = httpResponses
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
User avatar
djdevil
Posts: 101
Joined: Friday 26 July 2019 18:19
Target OS: Raspberry Pi / ODroid
Domoticz version: 2021.1
Contact:

Re: Months kWh usage to virtual counter

Post by djdevil »

thank you very much! works great! if you want instead I want to extrapolate the result of the last two months by adding them together?
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Months kWh usage to virtual counter

Post by waaren »

djdevil wrote: Monday 09 December 2019 22:12 if you want instead I want to extrapolate the result of the last two months by adding them together?
Please help me understand what you want to see in the target device.
If today is december 9th, do you then want the whole of november plus 1-9 december or do you want october 9th - december 9th. ?
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
User avatar
djdevil
Posts: 101
Joined: Friday 26 July 2019 18:19
Target OS: Raspberry Pi / ODroid
Domoticz version: 2021.1
Contact:

Re: Months kWh usage to virtual counter

Post by djdevil »

I want every virtual counter to be able to see the sum of the kWh used such as October and November
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Months kWh usage to virtual counter

Post by waaren »

djdevil wrote: Monday 09 December 2019 22:21 I want every virtual counter to be able to see the sum of the kWh used such as October and November
Is this what you mean ?

Code: Select all

local httpResponses = 'twoMonthTotal'

return {
    on      =   {   
                    timer           =   { 'on 1/* at 04:17' }, -- if you get data from previous months you only have to do this once a month at a quiet time
                    httpResponses   =   { httpResponses .. '*' } 
                },

    logging =   {   
                    level           =   domoticz.LOG_DEBUG, -- set to LOG_ERROR when script works as expected
                    marker          =   httpResponses
                },
                
    execute = function(dz, item)
        -- ****************************** Your settings below this line ***************************************************
        usageDevice = dz.devices(xxxx)          -- Replace xxxx with ID of energyDevice you want to track
        twoMonthTotals = dz.devices(yyyy)        -- Create as virtual managed counter (energy) and change yyyy to the ID of the new device
        -- ****************************** No changes required below this line *********************************************
        
        local function logWrite(str,level)
            dz.log(tostring(str),level or dz.LOG_DEBUG)
        end
        
        local function triggerJSON(id, period, delay)
            local delay = delay or 0
            local  URLString   =    dz.settings['Domoticz url'] .. '/json.htm?type=graph&sensor=counter&range=' .. 
                                    period .. '&idx=' .. id 
		   dz.openURL({    url = URLString,
                            method = 'GET',
                            callback = httpResponses .. '_' .. period}).afterSec(delay)                      
        end
        
        local function calculateTwoMonthTotal(rt)
            local twoMonthTotal = 0
			local dateFmt = '%Y-%m'
            monthMinus1 = os.date(dateFmt,os.time{day=1, year=dz.time.year, month=dz.time.month - 1 })
            monthMinus2 = os.date(dateFmt,os.time{day=1, year=dz.time.year, month=dz.time.month - 2 })
            for id, result in  ipairs(rt) do 
                if result.d:sub(1,7) == monthMinus1 or result.d:sub(1,7) == monthMinus2 then
                    logWrite(result.d .. ' ==>> ' .. result.v)
                    twoMonthTotal = twoMonthTotal + result.v
                end
            end
            return twoMonthTotal * 1000
        end    
        
        if not item.isHTTPResponse then
            triggerJSON(usageDevice.id, 'year')
        elseif item.ok then                                      -- statusCode == 2xx
            twoMonthTotals.update(0,calculateTwoMonthTotal(item.json.result))
        else
            logWrite('Could not get (good) data from domoticz. Error (' .. (item.statusCode or 999) .. ')'  ,dz.LOG_ERROR)
            logWrite(item.data)
        end
    end
}
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
User avatar
djdevil
Posts: 101
Joined: Friday 26 July 2019 18:19
Target OS: Raspberry Pi / ODroid
Domoticz version: 2021.1
Contact:

Re: Months kWh usage to virtual counter  [Solved]

Post by djdevil »

Tested and worked thanks to waaren as you always are a magician! Resolved! :) :D
RduPre
Posts: 53
Joined: Thursday 11 August 2016 18:41
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Location: The Netherlands
Contact:

Re: Months kWh usage to virtual counter

Post by RduPre »

I changed the script to 1 month total, see below.

Did I do this correctly, because the device doesn't get update and there are no errors.

Code: Select all

local httpResponses = 'oneMonthTotal'

return {
    on      =   {  
      { timer   = { "every 5 minutes" }},                    -- script draait iedere 5 minuten

 --                   timer           =   { 'on 1/* at 04:17' }, -- if you get data from previous months you only have to do this once a month at a quiet time
                    httpResponses   =   { httpResponses .. '*' } 
                },

    logging =   {   
                    level           =   domoticz.LOG_DEBUG, -- set to LOG_ERROR when script works as expected
                    marker          =   httpResponses
                },
                
    execute = function(dz, item)
        -- ****************************** Your settings below this line ***************************************************
        usageDevice = dz.devices(513)          -- Replace xxxx with ID of energyDevice you want to track
        oneMonthTotal = dz.devices(1862)        -- Create as virtual managed counter (energy) and change yyyy to the ID of the new device
        -- ****************************** No changes required below this line *********************************************
        
        local function logWrite(str,level)
            dz.log(tostring(str),level or dz.LOG_DEBUG)
        end
        
        local function triggerJSON(id, period, delay)
            local delay = delay or 0
            local  URLString   =    dz.settings['192.168.0.186:8080'] .. '/json.htm?type=graph&sensor=counter&range=' .. 
                                    period .. '&idx=' .. id 
		   dz.openURL({    url = URLString,
                            method = 'GET',
                            callback = httpResponses .. '_' .. period}).afterSec(delay)                      
        end
        
        local function calculateoneMonthTotal(rt)
            local oneMonthTotal = 0
			local dateFmt = '%Y-%m'
            monthMinus1 = os.date(dateFmt,os.time{day=1, year=dz.time.year, month=dz.time.month - 1 })
            for id, result in  ipairs(rt) do 
                if result.d:sub(1,7) == monthMinus1 then
                    logWrite(result.d .. ' ==>> ' .. result.v)
                    oneMonthTotal = oneMonthTotal + result.v
                end
            end
            return oneMonthTotal * 1000
        end    
        
        if not item.isHTTPResponse then
            triggerJSON(usageDevice.id, 'year')
        elseif item.ok then                                      -- statusCode == 2xx
            oneMonthTotals.update(0,calculateoneMonthTotal(item.json.result))
        else
            logWrite('Could not get (good) data from domoticz. Error (' .. (item.statusCode or 999) .. ')'  ,dz.LOG_ERROR)
            logWrite(item.data)
        end
    end
}
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Months kWh usage to virtual counter

Post by waaren »

RduPre wrote: Sunday 12 January 2020 13:32 I changed the script to 1 month total, see below.
You should not change dz.settings['Domoticz url'] to something like dz.settings['192.168.0.186:8080']
dz.settings is a table and 'Domoticz url' is a key in that table. The value of that element is already your domoticz url.
So what you did here is asking dzVents to get the value of the element with key '192.168.0.186:8080' :D

Have not checked the rest of your modifications.
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
RduPre
Posts: 53
Joined: Thursday 11 August 2016 18:41
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Location: The Netherlands
Contact:

Re: Months kWh usage to virtual counter

Post by RduPre »

Ah Stupid of me....

I did change it back, but still without any update nor errors

Ow i think I see my error, wait...
RduPre
Posts: 53
Joined: Thursday 11 August 2016 18:41
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Location: The Netherlands
Contact:

Re: Months kWh usage to virtual counter

Post by RduPre »

Here is the script I use, which works for 1 month.

Code: Select all

local httpResponses = 'oneMonthTotal'

return {
    on      =   {  
                 timer           =   { 'every 5 minutes' }, -- if you get data from previous months you only have to do this once a month at a quiet time

 --                   timer           =   { 'on 1/* at 04:17' }, -- if you get data from previous months you only have to do this once a month at a quiet time
                    httpResponses   =   { httpResponses .. '*' } 
                },

    logging =   {   
                    level           =   domoticz.LOG_DEBUG, -- set to LOG_ERROR when script works as expected
                    marker          =   httpResponses
                },
                
    execute = function(dz, item)
        -- ****************************** Your settings below this line ***************************************************
        usageDevice = dz.devices(513)          -- Replace xxxx with ID of energyDevice you want to track
        oneMonthTotal = dz.devices(1862)        -- Create as virtual managed counter (energy) and change yyyy to the ID of the new device
        -- ****************************** No changes required below this line *********************************************
        
        local function logWrite(str,level)
            dz.log(tostring(str),level or dz.LOG_DEBUG)
        end
        
        local function triggerJSON(id, period, delay)
            local delay = delay or 0
            local  URLString   =    dz.settings['Domoticz url'] .. '/json.htm?type=graph&sensor=counter&range=' .. 
                                    period .. '&idx=' .. id 
		   dz.openURL({    url = URLString,
                            method = 'GET',
                            callback = httpResponses .. '_' .. period}).afterSec(delay)                      
        end
        
        local function calculateoneMonthTotal(rt)
            local oneMonthTotal = 0
			local dateFmt = '%Y-%m'
            monthMinus1 = os.date(dateFmt,os.time{day=1, year=dz.time.year, month=dz.time.month - 1 })
            for id, result in  ipairs(rt) do 
                if result.d:sub(1,7) == monthMinus1 then
                    logWrite(result.d .. ' ==>> ' .. result.v)
                    oneMonthTotal = oneMonthTotal + result.v
                end
            end
            return oneMonthTotal * 1000
        end    
        
        if not item.isHTTPResponse then
            triggerJSON(usageDevice.id, 'year')
        elseif item.ok then                                      -- statusCode == 2xx
            oneMonthTotal.update(0,calculateoneMonthTotal(item.json.result))
        else
            logWrite('Could not get (good) data from domoticz. Error (' .. (item.statusCode or 999) .. ')'  ,dz.LOG_ERROR)
            logWrite(item.data)
        end
    end
}
kniazio
Posts: 200
Joined: Thursday 06 October 2016 8:14
Target OS: Raspberry Pi / ODroid
Domoticz version: 3.7243
Contact:

Re: Months kWh usage to virtual counter

Post by kniazio »

I have such an error
Error: dzVents: local netWork not open for dzVents openURL call !
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Months kWh usage to virtual counter

Post by waaren »

kniazio wrote: Sunday 23 May 2021 0:37 I have such an error
Error: dzVents: local netWork not open for dzVents openURL call !
__________________________________________________________________________________________________________________________
When not yet familiar with dzVents please start with reading Get started Before implementing (~ 5 minutes). Special attention please for "In Domoticz go to Setup > Settings > Other and in the section EventSystem make sure the checkbox 'dzVents enabled' is checked. Also make sure that in the Security section in the settings you allow 127.0.0.1 (and / or ::1 when using IPv6 ) to not need a password. dzVents uses that port to send certain commands to Domoticz. Finally make sure you have set your current location in Setup > Settings > System > Location, otherwise there is no way to determine nighttime/daytime state."
___________________________________________________________________________________________________________________________
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
kniazio
Posts: 200
Joined: Thursday 06 October 2016 8:14
Target OS: Raspberry Pi / ODroid
Domoticz version: 3.7243
Contact:

Re: Months kWh usage to virtual counter

Post by kniazio »

Now I have

Code: Select all

Start internal script: FCounter: HTTPResponse: "oneMonthTotal_year"
2021-05-23 06:53:00.623 Status: dzVents: Debug: oneMonthTotal: Processing device-adapter for Dom: Custom sensor device adapter
2021-05-23 06:53:00.625 Status: dzVents: Debug: oneMonthTotal: Processing device-adapter for Zużycie_Dom: Counter device adapter
2021-05-23 06:53:00.625 Status: dzVents: Error (2.4.15): oneMonthTotal: An error occured when calling event handler FCounter
2021-05-23 06:53:00.625 Status: dzVents: Error (2.4.15): oneMonthTotal: .../domoticz/scripts/dzVents/generated_scripts/FCounter.lua:39: bad argument #1 to 'ipairs' (table expected, got nil)
2021-05-23 06:53:00.625 Status: dzVents: Info: oneMonthTotal: ------ Finished FCounter
Perhaps because the value that the script calculates for me is with a "minus" sign
Attachments
counter_log.jpg
counter_log.jpg (72.88 KiB) Viewed 2167 times
counter.jpg
counter.jpg (32.12 KiB) Viewed 2169 times
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Months kWh usage to virtual counter

Post by waaren »

kniazio wrote: Sunday 23 May 2021 6:54 2021-05-23 06:53:00.625 Status: dzVents: Error (2.4.15): oneMonthTotal: An error occured when calling event handler FCounter
2021-05-23 06:53:00.625 Status: dzVents: Error (2.4.15): oneMonthTotal: .../domoticz/scripts/dzVents/generated_scripts/FCounter.lua:39: bad
Sorry but your version is too old to give support. If you want help then please upgrade to a recent version and include the full script and log.
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
kniazio
Posts: 200
Joined: Thursday 06 October 2016 8:14
Target OS: Raspberry Pi / ODroid
Domoticz version: 3.7243
Contact:

Re: Months kWh usage to virtual counter

Post by kniazio »

waaren wrote: Sunday 23 May 2021 14:53
kniazio wrote: Sunday 23 May 2021 6:54 2021-05-23 06:53:00.625 Status: dzVents: Error (2.4.15): oneMonthTotal: An error occured when calling event handler FCounter
2021-05-23 06:53:00.625 Status: dzVents: Error (2.4.15): oneMonthTotal: .../domoticz/scripts/dzVents/generated_scripts/FCounter.lua:39: bad
Sorry but your version is too old to give support. If you want help then please upgrade to a recent version and include the full script and log.
What version is it about? Version of (what)?

Code: Select all

  2021-05-23 15:32:00.482 Error: dzVents: Error: (3.0.2) oneMonthTotal: An error occurred when calling event handler FCounter
2021-05-23 15:32:00.482 Error: dzVents: Error: (3.0.2) oneMonthTotal: .../domoticz/scripts/dzVents/generated_scripts/FCounter.lua:39: bad argument #1 to 'ipairs' (table expected, got nil) 

Code: Select all

021-05-23 15:33:00.375 Status: dzVents: Info: oneMonthTotal: ------ Start internal script: FCounter:, trigger: "every minute"
2021-05-23 15:33:00.386 Status: dzVents: Debug: oneMonthTotal: Processing device-adapter for Dom: Custom sensor device adapter
2021-05-23 15:33:00.387 Status: dzVents: Debug: oneMonthTotal: Processing device-adapter for Zużycie_Dom: Counter device adapter
2021-05-23 15:33:00.387 Status: dzVents: Debug: oneMonthTotal: OpenURL: url = http://127.0.0.1:8082/json.htm?type=graph&sensor=counter&range=year&idx=63
2021-05-23 15:33:00.387 Status: dzVents: Debug: oneMonthTotal: OpenURL: method = GET
2021-05-23 15:33:00.387 Status: dzVents: Debug: oneMonthTotal: OpenURL: post data = nil
2021-05-23 15:33:00.387 Status: dzVents: Debug: oneMonthTotal: OpenURL: headers = nil
2021-05-23 15:33:00.387 Status: dzVents: Debug: oneMonthTotal: OpenURL: callback = oneMonthTotal_year
2021-05-23 15:33:00.387 Status: dzVents: Info: oneMonthTotal: ------ Finished FCounter
2021-05-23 15:33:00.388 Status: dzVents: Info: ------ Start internal script: FMeter:, trigger: "every minute"
2021-05-23 15:33:00.388 Status: dzVents: Debug: OpenURL: url = http://192.168.1.199/solar_api/v1/GetPowerFlowRealtimeData.fcgi
2021-05-23 15:33:00.388 Status: dzVents: Debug: OpenURL: method = GET
2021-05-23 15:33:00.388 Status: dzVents: Debug: OpenURL: post data = nil
2021-05-23 15:33:00.388 Status: dzVents: Debug: OpenURL: headers = nil
2021-05-23 15:33:00.388 Status: dzVents: Debug: OpenURL: callback = Fronius
2021-05-23 15:33:00.388 Status: dzVents: Info: ------ Finished FMeter
2021-05-23 15:33:00.389 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
2021-05-23 15:33:00.456 Status: dzVents: Info: Handling httpResponse-events for: "oneMonthTotal_year"
2021-05-23 15:33:00.456 Status: dzVents: Info: oneMonthTotal: ------ Start internal script: FCounter: HTTPResponse: "oneMonthTotal_year"
2021-05-23 15:33:00.469 Status: dzVents: Debug: oneMonthTotal: Processing device-adapter for Dom: Custom sensor device adapter
2021-05-23 15:33:00.470 Status: dzVents: Debug: oneMonthTotal: Processing device-adapter for Zużycie_Dom: Counter device adapter
2021-05-23 15:33:00.470 Status: dzVents: Info: oneMonthTotal: ------ Finished FCounter
2021-05-23 15:33:00.470 Error: dzVents: Error: (3.0.2) oneMonthTotal: An error occurred when calling event handler FCounter
2021-05-23 15:33:00.470 Error: dzVents: Error: (3.0.2) oneMonthTotal: .../domoticz/scripts/dzVents/generated_scripts/FCounter.lua:39: bad argument #1 to 'ipairs' (table expected, got nil) 
I ran the script on a brand new system on another Raspberry Pi4
kniazio
Posts: 200
Joined: Thursday 06 October 2016 8:14
Target OS: Raspberry Pi / ODroid
Domoticz version: 3.7243
Contact:

Re: Months kWh usage to virtual counter

Post by kniazio »

I chose another meter for counting monthly energy which shows positive values and the script worked immediately. Probably the problem lies in the negative results of the measurement
kniazio
Posts: 200
Joined: Thursday 06 October 2016 8:14
Target OS: Raspberry Pi / ODroid
Domoticz version: 3.7243
Contact:

Re: Months kWh usage to virtual counter

Post by kniazio »

Can it be solved somehow?
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest