Vera - Smarter Home Control Forum

General => Power Management => Topic started by: wezzix on January 24, 2016, 12:06:07 pm

Title: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: wezzix on January 24, 2016, 12:06:07 pm
I found a really nice looking service called emoncms.org to visualise energy consumption measured in Vera. It's free and open source. You can use emoncms.org or setup your own server at home. You can also use it to log arbitrary numerical variables in vera, such as battery level, light, temperature etc. You can create custom dashboards and export to CSV.

Here is how I did it:

Setup Vera (instructions for UI7)
Code: [Select]
require("EnergyMonitor.lua")
Setup emoncms inputs and feeds
You will immediately find your data here: http://emoncms.org/input/view (http://emoncms.org/input/view)
The inputs are by default not stored. Therefore, you will need to setup what is known as "feeds". Feeds is where the data is stored.

Feeds and inputs are very flexible, and therefore not very intuitive in the beginning. There are some guides at the bottom of this page which explains how to create feeds from your inputs:
http://openenergymonitor.org/emon/guide (http://openenergymonitor.org/emon/guide)

In short, what I did was this:

Setup emoncms energy app
Now for the fun part, setting up the dashboard.

The result
Attached is the code and examples of the two dashboards. My Electric displays current and historic energy consumption. I played around with My Solar to visualize how much energy I could save if I would switch to LED instead of halogen lights.
You can also design your own dashboard. I recommend that you watch the YouTube introduction before designing.

This code could be made into a Vera app. If anyone feels like taking the time to make an app, feel free to use my code as a base - just mention my name somewhere :)
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: FredrikY on January 24, 2016, 12:09:43 pm
Really realy nice, will give it a try! Good work!
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: konradwalsh on January 24, 2016, 04:33:03 pm
thanks for this...

still struggling to get the feeds running..

could do with some more examples..

track on time of a switch for example
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: wezzix on January 25, 2016, 02:11:22 am
I found an error in the code and just uploaded a fixed file (deviceId was missing from VARIABLES).

I also made "Total" exclude any variables but Watts. That means that you can easily do arbitrary logging of switches, light level, battery level etc.
I included an example for a switch also:
Set up the feed as in my first post (first feed), that is, use the "Log to feed" processing. You can simply check on your feed by clicking on the "eye"-icon in the feed list. Attached is a sample of how my switch looks really zoomed in (zoom in by click and select in the graph). Not sure if that fits your needs. You can always export the feed data as CSV.

Code: [Select]
-- Setup your devices here. You can use a function to calculate the power as illustrated in the sample.
-- For device logging, use: key, deviceId, serviceId, serviceVar
-- For function based logging, use: key, calculate, serviceVar
local VARIABLES = {
{ key="Livingroom", deviceId = 12, serviceId='urn:micasaverde-com:serviceId:EnergyMetering1', serviceVar="Watts" }, -- Send device energy
{ key="Kitchen", deviceId = 13, serviceId='urn:micasaverde-com:serviceId:EnergyMetering1', serviceVar="Watts" },
{ key='KitchenSwitch', deviceId=13, serviceId="urn:upnp-org:serviceId:SwitchPower1", serviceVar="Status"}, -- Send switch status
{ key='Computer', calculate=function() return (IsComputerPingSensorTripped() and 38 or 1) end, serviceVar="Watts" }, -- Send variable value
{ key='Other', calculate=function() return 15 end, serviceVar="Watts" } -- Send a constant value
}
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: amg0 on January 25, 2016, 02:31:59 am
yes it looks quite good.
for your info, I made an native integration for it in ALTUI plugin. http://apps.mios.com/plugin.php?id=8246
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: konradwalsh on January 25, 2016, 04:42:16 am
quality....

Thanks for that
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: wezzix on January 27, 2016, 03:25:22 pm
@amg0, ALTUI looks like a great piece of work, I might try that sometime.
I looked through the documentation but I didn't find any mention of emoncms. Did I miss something, or would you please shed a little light on the level of integration?
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: amg0 on January 27, 2016, 07:15:20 pm
@amg0, ALTUI looks like a great piece of work, I might try that sometime.
I looked through the documentation but I didn't find any mention of emoncms. Did I miss something, or would you please shed a little light on the level of integration?
yes it is integrated. From a variable you can configure a data push to emoncns.
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: simonclark on January 28, 2016, 02:22:26 am
I am guessing it only pushes to one of thingspeak, economy or datayours?
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: amg0 on January 28, 2016, 03:16:09 am
I am guessing it only pushes to one of thingspeak, economy or datayours?

out of the box, it pushes any variable value to either thingspeak or DataYours2; 
but it also provides an web interface to integrate some other data push destination. that requires though that a piece of code is calling a web service into ALTUI to register then it will receive, again as a web service, the value of the variables that the user has chosen to save; that piece of code can then do the push to whatever data storage they want.
more info here: http://forum.micasaverde.com/index.php/topic,35860.0.html
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: mmd on February 14, 2016, 11:26:58 am
UPDATE: Nevermind, figured out the device was urn:micasaverde-com:serviceId:EnergyMetering1

Having a bit of problem reading my energy monitor.  The script seems to be communicating with Emoncms, but not reading the watts.  Here's the code I put in.  I've also attached the device config.  I've tried modifiying the key name to only use a number and not include any spaces, but it doesn't seem to make a difference.  Any ideas?  Thanks!

local VARIABLES = {
   { key="Grid Total", deviceId = 25, serviceId='urn:schemas-micasaverde-com:device:PowerMeter:1', serviceVar="Watts" }, -- Send device energy
   { key='Other', calculate=function() return 15 end, serviceVar="Watts" } -- Send a constant value
}
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: mmd on February 16, 2016, 04:13:52 pm
Awesome info Wezzix!  I ended up writing a python script to pull SolarEdge data from their API and post to emoncms too.  The code runs on a Synology NAS that I can detail if anyone wants more info.  I have my HEM collecting usage data based on your script with the two being correlated on the My Solar app.

#! /usr/bin/python
import datetime
import http.client
import json, urllib.request

#Gather wattage from SolarEdge API
solarEdgeAPIKey="APIKEY"
url = "https://monitoringapi.solaredge.com/site/1/overview.json?api_key=" + solarEdgeAPIKey
#url = "https://monitoringapi.solaredge.com/site/1/power?api_key=" + solarEdgeAPIKey + "&startTime=2016-02-16%2008:00:00&endTime=2016-02-16%2011:30:00"
response = urllib.request.urlopen(url).read().decode('utf8')


data = json.loads(response)
watts = repr(data['overview']['currentPower']['power'])

#print(data['overview']['currentPower']['power'])

# Local EMONCMS API Key
#EMONKEY = "APIKEY"

# EMONCMS.org API Key
EMONKEY = "APIKEY"
now = datetime.datetime.now()

#---Local---#
#conn = http.client.HTTPConnection("192.168.3.20:80")
#request = "/emoncms/input/post.json?apikey=" + EMONKEY  + "&node=1&json={power:" + watts + "}"

#---Hosted---#
conn = http.client.HTTPConnection("emoncms.org:80")
request = "/input/post.json?apikey=" + EMONKEY  + "&node=20&json={power:" + watts + "}"
# emoncms uses a GET not a POST
conn.request("GET", request)
response = conn.getresponse()

Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: wezzix on February 17, 2016, 02:04:20 am
Thanks mmd, I'm glad you found it useful!
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: stibbzy on May 05, 2016, 12:58:58 am
Awesome info Wezzix!  I ended up writing a python script to pull SolarEdge data from their API and post to emoncms too.  The code runs on a Synology NAS that I can detail if anyone wants more info.  I have my HEM collecting usage data based on your script with the two being correlated on the My Solar app.

Hi mmd,

I'd love any more info you might have on pulling your SolarEdge data with the python script. I tried playing around with the script in your post, but kept getting urlopen error 3 for some reason :(

Thanks!
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: Spanners on July 25, 2016, 12:39:43 am
Hi All,

Had a go at setting this up today. Got the Lua file edited and uploaded and put the line into the Startup Lua to call it.

When I go to http://emoncms.org/input/view I'm not seeing any inputs, so I assume that something isn't working as expected.

I've attached my lua file - is there anything wrong in the code or do I have some other issue?


UPDATE: If I paste the code into the Test Luup box, it works and starts sending updates to Emoncms. So for some reason the startup Lua code:

-- emoncms.org data uploader
require("EnergyMonitor.lua")

Isn't working - they are the first lines in my startup.



Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: akbooer on July 25, 2016, 02:51:19 am
You wouldn't normally put the .lua extension into the require statement.

Does this work?

Code: [Select]
require "EnergyMonitor"
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: Spanners on July 25, 2016, 03:00:44 am
Hi akbooer,

No joy with that code change either.

The only other stuff in my startup is related to logging and restarts, not sure if it has a bearing.

Code: [Select]
-- Keep snapshots of LuaUPnP.log
local snapSecs = 180    -- Seconds of log to keep in snapshot.
local snapNum = 5 -- Total number of snapshots to keep.
local baseFile = "/www/logsnap"
local snapFile = baseFile .. "1.txt"
-- Rename the snapshot stack
if snapNum > 1 then
for i=snapNum-1,1,-1 do
os.rename(baseFile .. tostring(i) .. ".txt", baseFile .. tostring(i 1) .. ".txt")
end
end
-- Take snapshot of current log
local dt = {}
local cut = os.time() - snapSecs
local snapF,snapE = io.open(snapFile,"w ")
if snapF ~= nil then
local foundcut = false
for line in io.lines("/tmp/log/cmh/LuaUPnP.log") do
if not foundcut then
mStr,dStr,yStr,hhStr,mmStr,ssStr = string.match(line,"^89.-(9 )/(, )/(e ) (t ):(e ):(o )")
if mStr ~= nil then
dt.month = tonumber(mStr)
dt.year = tonumber(yStr)   2000
dt.day = tonumber(dStr)
dt.hour = tonumber(hhStr)
dt.min = tonumber(mmStr)
dt.sec = tonumber(ssStr)
tstamp = os.time(dt)
if (tstamp >= cut) then foundcut = true end
end
end
if foundcut then
snapF:write(line .. "\n")
-- Following line stops snapshot at point of crash.
if string.find(line,"LuaUPnP Terminated with Exit Code:") ~= nil then break end
end
end
snapF:close()
end


-- Log each restart.
local function restartLog(message, keepdays)
local lfs = require "lfs"
local socket = require("socket")
local time = socket.gettime() or os.time()
local tms = string.format(".d  ",math.floor (1000 * (time  1)))
local stamp = os.date("s o l  u",math.floor(time)) .. tms
local baseFile = "/www/restarts"
local logFile = baseFile .. ".txt"
local lastLog = lfs.attributes(logFile,"modification") or time
-- Log this restart
local uptime = time - lastLog
local uptimeStr = string.format("Uptime: s Days 4 Hrs 9 Mins. ",math.floor(uptime / 86400),
math.floor((uptime a86400) / 3600), math.floor((uptime o3600) / 60))
local file = io.open(logFile, "a ")
file:write(stamp .. "Restart. " .. uptimeStr .. (message or "").."\n")
file:close()
-- Remove old entries
local prevDays = keepdays or 30    -- Days to keep in addition to today.
local tmpFile = baseFile .. ".tmp"
local mTxt={Jan=1,Feb=2,Mar=3,Apr=4,May=5,Jun=6,Jul=7,Aug=8,Sep=9,Oct=10,Nov=11,Dec=12}
local dt = {}
local today = time - (time  86400)
local cut = today - ( prevDays * 86400)
local tmpF,tmpE = io.open(tmpFile,"w ")
if tmpF ~= nil then
for line in io.lines(logFile) do
dStr,mStr,yStr = string.match(line,"^(4 )3(8 )5(1 )9")
dt.month = mTxt[mStr]
dt.year = tonumber(yStr)
dt.day =tonumber(dStr)
date = os.time(dt)
if (date >= cut) then tmpF:write(line .. "\n") end
end
tmpF:close()
local retn,err = os.rename(tmpFile, logFile)
end
lfs.touch(logFile,time)
end

local netOK = "OK"
if os.execute("ping -c 1 8.8.8.8") ~= 0 then netOK = "Offline" end
restartLog("Network: " .. netOK, 30) -- Last argument is log history in days.




Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: akbooer on July 25, 2016, 06:31:08 am
So what does the log file show?
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: RichardTSchaefer on July 25, 2016, 06:33:12 am
Please review:
   http://forum.micasaverde.com/index.php/topic,33226.msg244015.html#new

Add a line to the beginning of the LUA File:
  module("EnergyMonitor", package.seeall)

For all of the functions that you callback by NAME from the various luup.xxx functions add a line as follows during some initialization (i.e. at bottom of file):

   _G.FunctionName = FunctionName

i.e.  EnergyMonitorOnTimer
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: Spanners on July 26, 2016, 01:05:05 am
I feel like I'm bringing a knife to a gun fight talking code with Akbooer and RTS... :)   Thanks to both of you for taking the time to answer questions.

Ok, modified the EnergyMontor.lua (attached) to include the elements Richard describes above.

Replaced my Lua Start up with:
Code: [Select]
emoncode = require("EnergyMonitor")
emoncode.EnergyMonitorOnTimer()

The code runs. However, if I try to add my original startup code back (see previous snippets, it's the log restart and capture luaupnp.log snapshots that's posted on the forum), the EnergyMonitor code no longer runs and Vera gives me an "Error in Lua Scenes and Events" message. But if I leave the Energymonitor bits out of startup, the other code runs fine.

Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: akbooer on July 26, 2016, 04:52:31 am
Sound like a simple syntax error in the combined code stopping it all from loading in the first place.

Hard to imagine how, since it should be very straight-forward, but can you in fact post the entire code that doesn't work in startup?  Otherwise it's just guesswork.
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: Spanners on July 26, 2016, 08:25:47 pm
Hi akbooer, copy of the rest of the startup lua attached if you want to cast your eye over it.

Thanks.
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: akbooer on July 27, 2016, 02:03:51 am
Hi akbooer, copy of the rest of the startup lua attached if you want to cast your eye over it.

Well, for a start, line 27 is invalid syntax:
Code: [Select]
os.rename(baseFile .. tostring(i) .. ".txt", baseFile .. tostring(i 1) .. ".txt")
... I believe you mean tostring(i-1).

line 55 also...
Code: [Select]
dt.year = tonumber(yStr)   2000

line 103...
Code: [Select]
local tms = string.format(".d  ",math.floor (1000 * (time  1)))
... I believe this should be string.format("%d ", ... although this might just be a text encoding issue?
... also (time 1) should just be (time) ?

line 119...
Code: [Select]
math.floor((uptime a86400) / 3600), math.floor((uptime o3600) / 60))

line 137...
Code: [Select]
local today = time - (time  86400)

Having fixed all those, there are also a number of undefined globals and other things you may want to fix...
Code: [Select]
Analyzing the source code: 12 warnings.
untitled.lua:39: unused local variable 'snapE'; consider removing or replacing with '_'
untitled.lua:49: first assignment to global variable 'mStr'
untitled.lua:49: first assignment to global variable 'dStr'
untitled.lua:49: first assignment to global variable 'yStr'
untitled.lua:49: first assignment to global variable 'hhStr'
untitled.lua:49: first assignment to global variable 'mmStr'
untitled.lua:49: first assignment to global variable 'ssStr'
untitled.lua:65: first assignment to global variable 'tstamp'
untitled.lua:141: unused local variable 'tmpE'; consider removing or replacing with '_'
untitled.lua:155: first assignment to global variable 'date'
untitled.lua:163: unused local variable 'retn'; consider removing or replacing with '_'
untitled.lua:163: unused local variable 'err'; consider removing or replacing with '_'

So, I can't see that this can ever have worked.  It looks like you come from the world of strongly typed languages?  Would strongly that you use an IDE with a good code analyzer.

Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: Spanners on July 27, 2016, 02:14:50 am
Hi Akbooer,

I can't take credit for writing any of that code - I just stole it from various forum posts.  :-[

http://forum.micasaverde.com/index.php/topic,31292.0.html

Thank you for the feedback on the issues with it, for now I've just removed it entirely as I'm not having Luup/Vera Restart issues (for the first time in years). But I swear it did work!  :)



Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: rafale77 on July 30, 2016, 11:22:25 am
Just gave it a try and it doesn't seem to post the inputs for me... similar to BlueSmurf

Edit: Figured it out.
1) Went back to the unmodified file from wezzix. The edit from BlueSmurf were one of the problems...
2) Uploading through the UI app creator compresses the lua file creating an .lzo file on the vera. I SCP'd the file to prevent the compression

Now it all works.
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: mvader on July 31, 2016, 10:12:21 pm
having an issue getting the data to show up correctly.
in my log emoncms log files i have this error
2016-08-01 02:08:55.105|ERROR|input_controller.php|Format error: csv value is not numeric
2016-08-01 02:09:05.103|ERROR|input_controller.php|Format error: csv value is not numeric

in my vera logs i have this
 luup_log:0: EnergyMonitor Logger: Updating with: &node=1&json={WashRoom Temp:69.4,Total:0}

(i was trying to log a temp sensor, the input shows up (the node, but the value is always zero)
i suspect it's because of the format error..
any idea what may be wrong?
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: akbooer on August 01, 2016, 02:56:33 am
I don't know if it helps, but this:

Code: [Select]
json={WashRoom Temp:69.4,Total:0}

is not valid JSON.

Try this instead?

Code: [Select]
json={"WashRoom Temp":69.4,"Total":0}
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: mvader on August 01, 2016, 09:54:06 am
I don't know if it helps, but this:

Code: [Select]
json={WashRoom Temp:69.4,Total:0}

is not valid JSON.

Try this instead?

Code: [Select]
json={"WashRoom Temp":69.4,"Total":0}


Thanks for the tip.. I'll give it a go this evening.
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: Spanners on October 15, 2016, 01:41:37 am
Hi Guys,

Hopefully this is an easy one for someone familiar with Lua.

Just finished the build of my 3-Phase energy monitoring system, a hybrid of Mysensors and Open Energy Monitor. I have it reporting into Vera, and uploading to emoncms.org

Code: [Select]
local VARIABLES = {
{ key="Emon1", deviceId = 70, serviceId='urn:micasaverde-com:serviceId:EnergyMetering1', serviceVar="Watts" }, -- Send device energy
{ key="Emon2", deviceId = 73, serviceId='urn:micasaverde-com:serviceId:EnergyMetering1', serviceVar="Watts" },
{ key="Emon3", deviceId = 74, serviceId='urn:micasaverde-com:serviceId:EnergyMetering1', serviceVar="Watts" }

All good so far. What I'd like to do is add a new key value which is the total of these 3 values. The original lua script has an example for sending a constant value

Code: [Select]
{ key="Other", calculate=function() return 15 end, serviceVar="Watts" } -- Send a constant value

Is there a way to modify that so the returned value is the sum of the first 3? Or does this require processing within the script itself - I see there's code there that effectively sums all of the values reported. Which is fine if you're only sending the 3 phase values, but I have other devices reporting watts that I don't want included in the total.


Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: hart on November 20, 2016, 04:47:29 pm
What I'd like to do is add a new key value which is the total of these 3 values. The original lua script has an example for sending a constant value

Code: [Select]
{ key="Other", calculate=function() return 15 end, serviceVar="Watts" } -- Send a constant value

Is there a way to modify that so the returned value is the sum of the first 3? Or does this require processing within the script itself - I see there's code there that effectively sums all of the values reported. Which is fine if you're only sending the 3 phase values, but I have other devices reporting watts that I don't want included in the total.

Something like:

Code: [Select]
{ key="Other", calculate=function() return luup.variable_get('urn:micasaverde-com:serviceId:EnergyMetering1', 'Watts', 70) + luup.variable_get('urn:micasaverde-com:serviceId:EnergyMetering1', 'Watts', 73) + luup.variable_get('urn:micasaverde-com:serviceId:EnergyMetering1', 'Watts', 74) end, serviceVar="Watts" }

Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: jamac on December 27, 2016, 01:58:26 am
I'm struggling to get this working and am hoping for some help.  :)

I've got a Vera3 running UI7.

I followed wezzix instructions at the top of this thread, ie, created an account at emoncms, amended and loaded the EnergyMonitor.lua file and entered the startup code.
This didn't generate any inputs in emoncms so I followed RTS's instructions and added the following to the start of the EnergyMonitor.lua file

Code: [Select]
module("EnergyMonitor", package.seeall)
This to the end of the file:

Code: [Select]
_G.EnergyMonitorOnTimer = EnergyMonitorOnTimer
And, this in the Edit Startup Lua window:
Code: [Select]
emoncode = require("EnergyMonitor")
emoncode.EnergyMonitorOnTimer()

However, I get the following error in the top of the dashboard:

ERROR: error in lua for scenes and events

When i look at the log file I see the following error on multiple occasions...

LuaInterface::CallFunction_Timer-5 function EnergyMonitorOnTimer failed [string "module("EnergyMonitor",package.seeall)..."]:17: attempt to perform arithmetic on a nil value

Any helpful tips?
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: jamac on January 03, 2017, 01:28:56 am
I got everything working. There was a syntax error in my code.

However, I've got a weird problem. I've set up a number of dashboards, all of which are visible via a url containing the relevant API. I can see the dashboards on my ipad via Safari but they refuse to display in a webtile from within Homewave.

Is there anything unusual about the way Emoncms displays dashboards that could explain this problem???

Of course, it's possible it's a Homewave issue and not an Emomcms issue...

Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: VallejoIII on February 27, 2017, 05:37:09 pm
No longer working after upgrade to version 1.7.919.

Getting "ERROR : Error in lua for scenes and events"  >:(
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: VallejoIII on March 05, 2017, 12:40:47 pm
UPDATE:

Code:
emoncode = require("EnergyMonitor")
emoncode.EnergyMonitorOnTimer()

Fixed and working. Syntax error!
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: worldburger on April 05, 2017, 12:58:19 pm
EDIT: Added complete EnergyMonitor.lua code
///////////////////////////////////////////////////

I'm having some trouble getting this to work.

My objective is to:
Measure/log energy consumption on my house. (Do I need two CT clamps or just one for this? Am in the USA)
Measure/log energy consumption on my 240v kiln. (Do I need two CT clamps or just one for this? Am in the USA)
I have TWO - Aeon Home Energy Monitor (v1)'s (one for the breaker box and one for the kiln). Presently only one is setup as I am trying to get the house consumption data working first...which is troublesome :)

Here's where I'm at...
I've successfully got the Aeon Home Energy Monitor (v1) to talk to my VeraPlus. I can see the actual Watts and KWH on the Vera Dashboard. I've also go the VeraPlus talking to Emoncms (it sends my INPUTs to Emoncms with the keys I've entered). I've also created a FEED in Emoncms.

Unfortunately, on Emoncms I am only seeing ZEROS ("0") as my inputs.  What could be the problem? Any ideas?

Setup:
VeraPlus. UI7 (latest update). Aeon Home Energy Monitor (v1) with two current clamps powered by USB (1s update interval to VeraPlus).

Questions:
Is "device name" in the VeraPlus UI the "key" needed in the VARIABLES section of the EnergyMonitor.lua file?
Where do you find the specific "serviceVar" for the devices?

Which of the following do I need (or can I) to publish to Emoncms?
My Aeon Home Energy Monitor shows up as 3 devices...
1st is the total Watts & KWH (in Vera UI, I named this "totalwkwh")
2nd is Watt & KWH from 1st CT Clamp reading (in Vera UI, I named this "hema")
3nd is Watt & KWH from 2nd CT Clamp reading (in Vera UI, I named this "hemb")

Screenshots are attached.
Normally, I'm pretty capable with mild programming and setup, but this is stumping me!

Thanks in advance :)

My code is below:
---Startup Lua---
Code: [Select]
module("EnergyMonitor", package.seeall)

-- Setup your account at http://emoncms.org/
-- See API documentation at http://emoncms.org/input/api

-- API Key
local API_KEY = "REMOVED FOR POST"

-- Setup your devices here. You can use a function to calculate the power as illustrated in the sample.
-- For device logging, use: key, deviceId, serviceId, serviceVar
-- For function based logging, use: key, calculate, serviceVar

local VARIABLES = {
{ key="totalwkwh", deviceId = 065, serviceId='urn:schemas-micasaverde-com:device:PowerMeter:1', serviceVar="Watts" }, -- Send Joined Device data
{ key="hema", deviceId = 67, serviceId='urn:schemas-micasaverde-com:device:PowerMeter:1', serviceVar="Watts" }, -- Send CT 1 device data
{ key="hema", deviceId = 67, serviceId='urn:schemas-micasaverde-com:device:PowerMeter:1', serviceVar="CurrentLevel" }, -- Send CT 1 device data
{ key="hemb", deviceId = 66, serviceId='urn:schemas-micasaverde-com:device:PowerMeter:1', serviceVar="Watts" }, -- Send CT 2 device data
{ key="hemb", deviceId = 66, serviceId='urn:schemas-micasaverde-com:device:PowerMeter:1', serviceVar="CurrentLevel" }, -- Send CT 2 device data
}

-- Add the following to your Vera's Startup Lua (without the preceding dashes) to run the logging on every Vera restart
-- emoncode = require("EnergyMonitor")
-- emoncode.EnergyMonitorOnTimer()

local NODE_ID = 10
local TOTAL_KEY = 'Total'


-- Upload Frequency in seconds ORIGINALLY 60
local updateInterval = 10

-- Log debug messages
local DEBUG = true


-- You shouldn't need to change anything below this line --


local http = require('socket.http')
http.TIMEOUT = 3

local BASE_URL = "http://emoncms.org/input/post.json?apikey=" .. API_KEY
local Log = function (text) luup.log('EnergyMonitor Logger: ' .. (text or "empty")) end
local lastFullUpload = 0

local items = {} -- contains items: { time, deviceId, value }

local function StartCallbackTimer(interval)
luup.call_delay("EnergyMonitorOnTimer", interval or updateInterval, nil)
end

local function InitWatch()
StartCallbackTimer(1)
end

local function AddKeyValuePair(key, value)
local item = string.format("%s:%s", key, tostring(value))
items[#items + 1] = item
end

local function SerializeData()
local dataText = "{" .. table.concat(items, ",") .. "}"
return dataText
end

local function ResetData()
items = {}
end

local function SendData()
local data = SerializeData()
ResetData()

local parameters = "&node=" .. tostring(NODE_ID) .. "&json=" .. data
local url = BASE_URL .. parameters
if (DEBUG) then Log("Updating with: " .. parameters) end
http.request(url)
end

local function AddAllVariablesAndTotal()
local total = 0
for i, v in ipairs(VARIABLES) do
local value
if v.deviceId then
value = luup.variable_get(v.serviceId, v.serviceVar, v.deviceId)
elseif v.calculate then
value = v.calculate()
end
value = tonumber(value) or 0
if v.serviceVar == "Watts" then
total = total + value
end
AddKeyValuePair(v.key, value)
end
AddKeyValuePair(TOTAL_KEY, total)
end

function EnergyMonitorOnTimer()
StartCallbackTimer()
AddAllVariablesAndTotal()
SendData()
end

_G.EnergyMonitorOnTimer = EnergyMonitorOnTimer
InitWatch()
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: VallejoIII on April 05, 2017, 07:13:42 pm
Hello world burger!

It looks like your EnergyMonitor.lua is missing the bottom part of the code.

There is a section of code where it states:
-- You shouldn't need to change anything below this line --

The code ends with:
_G.EnergyMonitorOnTimer = EnergyMonitorOnTimer
InitWatch()
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: worldburger on April 05, 2017, 08:13:52 pm
Hello world burger!

It looks like your EnergyMonitor.lua is missing the bottom part of the code.

There is a section of code where it states:
-- You shouldn't need to change anything below this line --

The code ends with:
_G.EnergyMonitorOnTimer = EnergyMonitorOnTimer
InitWatch()

My apologies I forgot to mention I truncated the code to only the top section where you modify it yourself. I've edited/updated my post to reflect that.

Any thoughts on why I'm having trouble getting it to function as expected?

Bonus: I'm also unable to get my USB flash drive to mount, any ideas? :)
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: worldburger on April 06, 2017, 11:55:33 am
EDIT: Added complete EnergyMonitor.lua code
///////////////////////////////////////////////////

I'm having some trouble getting this to work.

My objective is to:
Measure/log energy consumption on my house. (Do I need two CT clamps or just one for this? Am in the USA)
Measure/log energy consumption on my 240v kiln. (Do I need two CT clamps or just one for this? Am in the USA)
I have TWO - Aeon Home Energy Monitor (v1)'s (one for the breaker box and one for the kiln). Presently only one is setup as I am trying to get the house consumption data working first...which is troublesome :)

Here's where I'm at...
I've successfully got the Aeon Home Energy Monitor (v1) to talk to my VeraPlus. I can see the actual Watts and KWH on the Vera Dashboard. I've also go the VeraPlus talking to Emoncms (it sends my INPUTs to Emoncms with the keys I've entered). I've also created a FEED in Emoncms.

Unfortunately, on Emoncms I am only seeing ZEROS ("0") as my inputs.  What could be the problem? Any ideas?

Setup:
VeraPlus. UI7 (latest update). Aeon Home Energy Monitor (v1) with two current clamps powered by USB (1s update interval to VeraPlus).

Questions:
Is "device name" in the VeraPlus UI the "key" needed in the VARIABLES section of the EnergyMonitor.lua file?
Where do you find the specific "serviceVar" for the devices?

Which of the following do I need (or can I) to publish to Emoncms?
My Aeon Home Energy Monitor shows up as 3 devices...
1st is the total Watts & KWH (in Vera UI, I named this "totalwkwh")
2nd is Watt & KWH from 1st CT Clamp reading (in Vera UI, I named this "hema")
3nd is Watt & KWH from 2nd CT Clamp reading (in Vera UI, I named this "hemb")

Screenshots are attached.
Normally, I'm pretty capable with mild programming and setup, but this is stumping me!

Thanks in advance :)

My code is below:
---Startup Lua---
Code: [Select]
module("EnergyMonitor", package.seeall)

-- Setup your account at http://emoncms.org/
-- See API documentation at http://emoncms.org/input/api

-- API Key
local API_KEY = "REMOVED FOR POST"

-- Setup your devices here. You can use a function to calculate the power as illustrated in the sample.
-- For device logging, use: key, deviceId, serviceId, serviceVar
-- For function based logging, use: key, calculate, serviceVar

local VARIABLES = {
{ key="totalwkwh", deviceId = 065, serviceId='urn:schemas-micasaverde-com:device:PowerMeter:1', serviceVar="Watts" }, -- Send Joined Device data
{ key="hema", deviceId = 67, serviceId='urn:schemas-micasaverde-com:device:PowerMeter:1', serviceVar="Watts" }, -- Send CT 1 device data
{ key="hema", deviceId = 67, serviceId='urn:schemas-micasaverde-com:device:PowerMeter:1', serviceVar="CurrentLevel" }, -- Send CT 1 device data
{ key="hemb", deviceId = 66, serviceId='urn:schemas-micasaverde-com:device:PowerMeter:1', serviceVar="Watts" }, -- Send CT 2 device data
{ key="hemb", deviceId = 66, serviceId='urn:schemas-micasaverde-com:device:PowerMeter:1', serviceVar="CurrentLevel" }, -- Send CT 2 device data
}

-- Add the following to your Vera's Startup Lua (without the preceding dashes) to run the logging on every Vera restart
-- emoncode = require("EnergyMonitor")
-- emoncode.EnergyMonitorOnTimer()

local NODE_ID = 10
local TOTAL_KEY = 'Total'


-- Upload Frequency in seconds ORIGINALLY 60
local updateInterval = 10

-- Log debug messages
local DEBUG = true


-- You shouldn't need to change anything below this line --


local http = require('socket.http')
http.TIMEOUT = 3

local BASE_URL = "http://emoncms.org/input/post.json?apikey=" .. API_KEY
local Log = function (text) luup.log('EnergyMonitor Logger: ' .. (text or "empty")) end
local lastFullUpload = 0

local items = {} -- contains items: { time, deviceId, value }

local function StartCallbackTimer(interval)
luup.call_delay("EnergyMonitorOnTimer", interval or updateInterval, nil)
end

local function InitWatch()
StartCallbackTimer(1)
end

local function AddKeyValuePair(key, value)
local item = string.format("%s:%s", key, tostring(value))
items[#items + 1] = item
end

local function SerializeData()
local dataText = "{" .. table.concat(items, ",") .. "}"
return dataText
end

local function ResetData()
items = {}
end

local function SendData()
local data = SerializeData()
ResetData()

local parameters = "&node=" .. tostring(NODE_ID) .. "&json=" .. data
local url = BASE_URL .. parameters
if (DEBUG) then Log("Updating with: " .. parameters) end
http.request(url)
end

local function AddAllVariablesAndTotal()
local total = 0
for i, v in ipairs(VARIABLES) do
local value
if v.deviceId then
value = luup.variable_get(v.serviceId, v.serviceVar, v.deviceId)
elseif v.calculate then
value = v.calculate()
end
value = tonumber(value) or 0
if v.serviceVar == "Watts" then
total = total + value
end
AddKeyValuePair(v.key, value)
end
AddKeyValuePair(TOTAL_KEY, total)
end

function EnergyMonitorOnTimer()
StartCallbackTimer()
AddAllVariablesAndTotal()
SendData()
end

_G.EnergyMonitorOnTimer = EnergyMonitorOnTimer
InitWatch()

Any ideas, people? :)
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: tmaster on April 30, 2017, 07:57:16 am
hi. I found Energymonitor.lua file in other forum because i can't find it on emocms website. they remove it? By the way this is the code im running, but i have no input at all on emocms, already add on startup  : emoncode = require("EnergyMonitor")
emoncode.EnergyMonitorOnTimer()

it gives "error on scenes and events "  how can i compile lua code to check errors?i never used lua code

i didn't understand the node part? on code say node10?

Code: [Select]
module("EnergyMonitor", package.seeall)

-- Setup your account at http://emoncms.org/
-- See API documentation at http://emoncms.org/input/api

-- API Key
local API_KEY = b24925 [..my key...] dd9f775

-- Setup your devices here. You can use a function to calculate the power as illustrated in the sample.
-- For device logging, use: key, deviceId, serviceId, serviceVar
-- For function based logging, use: key, calculate, serviceVar

-- { key='Computer', calculate=function() return (IsComputerPingSensorTripped() and 38 or 1) end, serviceVar="Watts" }, -- Send variable value
-- { key='Other', calculate=function() return 15 end, serviceVar="Watts" } -- Send a constant value

local VARIABLES = {
--{ key="PoolFilter", deviceId = 869, serviceId='urn:micasaverde-com:serviceId:EnergyMetering1', serviceVar="Watts" }, -- Send device energy
{ key='ValvulaRega1', deviceId=105, serviceId="urn:upnp-org:serviceId:SwitchPower1", serviceVar="Status"}, -- Send switch status
{ key='TempExterior', deviceId=111, serviceId="urn:upnp-org:serviceId:TemperatureSensor1", serviceVar="CurrentTemperature"}, -- Send Temperature
{ key='HumidadeTerra', deviceId=109, serviceId="urn:micasaverde-com:serviceId:HumiditySensor1", serviceVar="CurrentLevel"}, -- Send Humidity
--{ key='FrontLight', deviceId=740, serviceId="urn:micasaverde-com:serviceId:LightSensor1", serviceVar="CurrentLevel"} -- Send Light Level
}

-- Add the following to your Vera's Startup Lua (without the preceding dashes) to run the logging on every Vera restart
-- emoncode = require("EnergyMonitor")
-- emoncode.EnergyMonitorOnTimer()

local NODE_ID = 10
local TOTAL_KEY = 'Total'

-- Upload Frequency in seconds


-- Log debug messages
local DEBUG = true




-- You shouldn't need to change anything below this line --


local http = require('socket.http')
http.TIMEOUT = 3

local BASE_URL = "http://emoncms.org/input/post.json?apikey=" .. API_KEY
local Log = function (text) luup.log('EnergyMonitor Logger: ' .. (text or "empty")) end
local lastFullUpload = 0

local items = {} -- contains items: { time, deviceId, value }

local function StartCallbackTimer(interval)
luup.call_delay("EnergyMonitorOnTimer", interval or updateInterval, nil)
end

local function InitWatch()
StartCallbackTimer(1)
end

local function AddKeyValuePair(key, value)
local item = string.format("%s:%s", key, tostring(value))
items[#items + 1] = item
end

local function SerializeData()
local dataText = "{" .. table.concat(items, ",") .. "}"
return dataText
end

local function ResetData()
items = {}
end

local function SendData()
local data = SerializeData()
ResetData()

local parameters = "&node=" .. tostring(NODE_ID) .. "&json=" .. data
local url = BASE_URL .. parameters
if (DEBUG) then Log("Updating with: " .. parameters) end
http.request(url)
end

local function AddAllVariablesAndTotal()
local total = 0
for i, v in ipairs(VARIABLES) do
local value
if v.deviceId then
value = luup.variable_get(v.serviceId, v.serviceVar, v.deviceId)
elseif v.calculate then
value = v.calculate()
end
value = tonumber(value) or 0
if v.serviceVar == "Watts" then
total = total + value
end
AddKeyValuePair(v.key, value)
end
AddKeyValuePair(TOTAL_KEY, total)
end

function EnergyMonitorOnTimer()
StartCallbackTimer()
AddAllVariablesAndTotal()
SendData()
end

_G.EnergyMonitorOnTimer = EnergyMonitorOnTimer
InitWatch()
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: tmaster on April 30, 2017, 12:52:43 pm
ok. its working. i just forget " " on api key  ::).

So there is the full code working with with,temperature and humidity sensors.
Code: [Select]
module("EnergyMonitor", package.seeall)

-- Setup your account at http://emoncms.org/
-- See API documentation at http://emoncms.org/input/api

-- API Key
local API_KEY = "b24925 [..CHANGE HERE YOUR API key...] dd9f775"

-- Setup your devices here. You can use a function to calculate the power as illustrated in the sample.
-- For device logging, use: key, deviceId, serviceId, serviceVar
-- For function based logging, use: key, calculate, serviceVar

-- { key='Computer', calculate=function() return (IsComputerPingSensorTripped() and 38 or 1) end, serviceVar="Watts" }, -- Send variable value
-- { key='Other', calculate=function() return 15 end, serviceVar="Watts" } -- Send a constant value

local VARIABLES = {
{ key="PoolFilter", deviceId = 869, serviceId='urn:micasaverde-com:serviceId:EnergyMetering1', serviceVar="Watts" }, -- Send device energy
{ key='ValvulaRega1', deviceId=105, serviceId="urn:upnp-org:serviceId:SwitchPower1", serviceVar="Status"}, -- Send switch status
{ key='TempExterior', deviceId=111, serviceId="urn:upnp-org:serviceId:TemperatureSensor1", serviceVar="CurrentTemperature"}, -- Send Temperature
{ key='HumidadeTerra', deviceId=109, serviceId="urn:micasaverde-com:serviceId:HumiditySensor1", serviceVar="CurrentLevel"}, -- Send Humidity
{ key='FrontLight', deviceId=740, serviceId="urn:micasaverde-com:serviceId:LightSensor1", serviceVar="CurrentLevel"} -- Send Light Level
}

-- Add the following to your Vera's Startup Lua (without the preceding dashes) to run the logging on every Vera restart
-- emoncode = require("EnergyMonitor")
-- emoncode.EnergyMonitorOnTimer()

local NODE_ID = 10
local TOTAL_KEY = 'Total'

-- Upload Frequency in seconds


-- Log debug messages
local DEBUG = true




-- You shouldn't need to change anything below this line --


local http = require('socket.http')
http.TIMEOUT = 3

local BASE_URL = "http://emoncms.org/input/post.json?apikey=" .. API_KEY
local Log = function (text) luup.log('EnergyMonitor Logger: ' .. (text or "empty")) end
local lastFullUpload = 0

local items = {} -- contains items: { time, deviceId, value }

local function StartCallbackTimer(interval)
luup.call_delay("EnergyMonitorOnTimer", interval or updateInterval, nil)
end

local function InitWatch()
StartCallbackTimer(1)
end

local function AddKeyValuePair(key, value)
local item = string.format("%s:%s", key, tostring(value))
items[#items + 1] = item
end

local function SerializeData()
local dataText = "{" .. table.concat(items, ",") .. "}"
return dataText
end

local function ResetData()
items = {}
end

local function SendData()
local data = SerializeData()
ResetData()

local parameters = "&node=" .. tostring(NODE_ID) .. "&json=" .. data
local url = BASE_URL .. parameters
if (DEBUG) then Log("Updating with: " .. parameters) end
http.request(url)
end

local function AddAllVariablesAndTotal()
local total = 0
for i, v in ipairs(VARIABLES) do
local value
if v.deviceId then
value = luup.variable_get(v.serviceId, v.serviceVar, v.deviceId)
elseif v.calculate then
value = v.calculate()
end
value = tonumber(value) or 0
if v.serviceVar == "Watts" then
total = total + value
end
AddKeyValuePair(v.key, value)
end
AddKeyValuePair(TOTAL_KEY, total)
end

function EnergyMonitorOnTimer()
StartCallbackTimer()
AddAllVariablesAndTotal()
SendData()
end

_G.EnergyMonitorOnTimer = EnergyMonitorOnTimer
InitWatch()

Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: worldburger on May 10, 2017, 11:49:48 pm
Can someone tell me what is wrong with this code? I can get the inputs to post to emoncms but the variables all post "0".  Where is my mistake?

Notes: I have setup the startup Lua code as directed. Both of my deviceId's match the two Aeon sensors I have (the main device, not the CT clamps).

Code: [Select]
module("EnergyMonitor", package.seeall)

-- Setup your account at http://emoncms.org/
-- See API documentation at http://emoncms.org/input/api

-- API Key
local API_KEY = "REMOVED FOR SECURITY REASONS"

-- Setup your devices here. You can use a function to calculate the power as illustrated in the sample.
-- For device logging, use: key, deviceId, serviceId, serviceVar
-- For function based logging, use: key, calculate, serviceVar

local VARIABLES = {
{ key="HEM", deviceId = 155, serviceId='urn:schemas-micasaverde-com:device:PowerMeter:1', serviceVar="Watts" },
{ key="HEM", deviceId = 155, serviceId='urn:schemas-micasaverde-com:device:PowerMeter:1', serviceVar="CurrentLevel" },
{ key="kilnwelder", deviceId = 135, serviceId='urn:schemas-micasaverde-com:device:PowerMeter:1', serviceVar="Watts" },
{ key="kilnwelder", deviceId = 135, serviceId='urn:schemas-micasaverde-com:device:PowerMeter:1', serviceVar="CurrentLevel" },
    { key='TestVar', calculate=function() return 15 end, serviceVar="dsmtest" } -- Send a constant value
}

-- Add the following to your Vera's Startup Lua (without the preceding dashes) to run the logging on every Vera restart
-- emoncode = require("EnergyMonitor")
-- emoncode.EnergyMonitorOnTimer()

local NODE_ID = 10
local TOTAL_KEY = 'Total'


-- Upload Frequency in seconds ORIGINALLY 60
local updateInterval = 10

-- Log debug messages
local DEBUG = true


-- You shouldn't need to change anything below this line --


local http = require('socket.http')
http.TIMEOUT = 3

local BASE_URL = "http://emoncms.org/input/post.json?apikey=" .. API_KEY
local Log = function (text) luup.log('EnergyMonitor Logger: ' .. (text or "empty")) end
local lastFullUpload = 0

local items = {} -- contains items: { time, deviceId, value }

local function StartCallbackTimer(interval)
luup.call_delay("EnergyMonitorOnTimer", interval or updateInterval, nil)
end

local function InitWatch()
StartCallbackTimer(1)
end

local function AddKeyValuePair(key, value)
local item = string.format("%s:%s", key, tostring(value))
items[#items + 1] = item
end

local function SerializeData()
local dataText = "{" .. table.concat(items, ",") .. "}"
return dataText
end

local function ResetData()
items = {}
end

local function SendData()
local data = SerializeData()
ResetData()

local parameters = "&node=" .. tostring(NODE_ID) .. "&json=" .. data
local url = BASE_URL .. parameters
if (DEBUG) then Log("Updating with: " .. parameters) end
http.request(url)
end

local function AddAllVariablesAndTotal()
local total = 0
for i, v in ipairs(VARIABLES) do
local value
if v.deviceId then
value = luup.variable_get(v.serviceId, v.serviceVar, v.deviceId)
elseif v.calculate then
value = v.calculate()
end
value = tonumber(value) or 0
if v.serviceVar == "Watts" then
total = total + value
end
AddKeyValuePair(v.key, value)
end
AddKeyValuePair(TOTAL_KEY, total)
end

function EnergyMonitorOnTimer()
StartCallbackTimer()
AddAllVariablesAndTotal()
SendData()
end

_G.EnergyMonitorOnTimer = EnergyMonitorOnTimer
InitWatch()
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: VallejoIII on May 20, 2017, 05:58:57 pm
Here is my code if it can help in finding the error.

Cheers!
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: peterv on July 21, 2017, 12:07:11 pm
I followed RTS's instructions and added the following to the start of the EnergyMonitor.lua file
Code: [Select]
module("EnergyMonitor", package.seeall)

This to the end of the file:
Code: [Select]
_G.EnergyMonitorOnTimer = EnergyMonitorOnTimer
And, this in the Edit Startup Lua window:
Code: [Select]
emoncode = require("EnergyMonitor")
emoncode.EnergyMonitorOnTimer()

I don't think that all three things are necessary. The first two should do the job. When I add emoncode.EnergyMonitorOnTimer() in start up lua, I can see two consecutive post requests in the log. Removing that line still keeps the script working.
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: rearden on January 30, 2018, 02:26:53 pm
I have a VeraPlus. EmonBase, EmonTxV3 with 4 CTs, temp sensor, etc.  From what I see here, the code posts from the Vera TO EmonCMS.  Is that correct?

I would like to read my CTs, VRMS, Power, Temp, etc. FROM EmonCMS and use them in the Vera for Scenes.  Has anyone done this?

Rearden
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: rearden on February 28, 2018, 06:16:19 pm
The plugin SiteSensor provides functionality to query a url and retrieve json values.

I have a VeraPlus. EmonBase, EmonTxV3 with 4 CTs, temp sensor, etc.  From what I see here, the code posts from the Vera TO EmonCMS.  Is that correct?

I would like to read my CTs, VRMS, Power, Temp, etc. FROM EmonCMS and use them in the Vera for Scenes.  Has anyone done this?

Rearden
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: jorisdekloris on March 12, 2018, 12:58:54 pm
Could someone help me out with my Lua file? I think i've missed configured it somehow because no data is reported on emoncms.

Code: [Select]
-- API Key
local API_KEY = "xxxx"

-- Setup your devices here. You can use a function to calculate the power as illustrated in the sample.
-- For device logging, use: key, deviceId, serviceId, serviceVar
-- For function based logging, use: key, calculate, serviceVar
local VARIABLES = {
{ key="Emon1", deviceId = 223, serviceId='urn:micasaverde-com:serviceId:EnergyMetering1', serviceVar="Watts" }, -- Send device energy
{ key="Emon2", deviceId = 224, serviceId='urn:micasaverde-com:serviceId:EnergyMetering1', serviceVar="Watts" },
{ key='Emon3', deviceId = 225, serviceId="urn:micasaverde-com:serviceId:EnergyMetering1", serviceVar="Watts"}, -- Send switch status
}

local NODE_ID = 10
local TOTAL_KEY = 'Total'
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: Spanners on March 12, 2018, 06:31:28 pm
Try removing the comma after the last entry in the variable list.
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: jorisdekloris on March 13, 2018, 03:56:33 am
I missed that. Thanks!

I also double checked the API write key but still no reading end up in emoncms. Is there something else i can check prior to finding out on how to get the logs out of the Vera?
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: akbooer on March 13, 2018, 04:08:04 am
It's not the comma.  That's perfectly valid Lua syntax.
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: jorisdekloris on March 14, 2018, 04:50:44 pm
What am i looking for in the logs?

Something like this?

Code: [Select]
06 03/14/18 21:40:50.131 Device_Variable::m_szValue_set device: 227 service: urn:upnp-org:serviceId:altui1 variable: Version was: v2.16 now: v2.16 #hooks: 0 upnp: 0 skip: 0 v:(nil)/NONE duplicate:1 <0x73db2520>
06 03/14/18 21:40:50.673 Device_Variable::m_szValue_set device: 227 service: urn:upnp-org:serviceId:altui1 variable: DataStorageProviders was: { "emoncms": { "url": "", "callback": "sendValueToStorage_emoncms", "parameters": [ { "default": 1, "type": "number", "key": "nodeid", "label": "Node ID" }, { "type": "number", "key": "feedid", "label": "Feed ID" }, { "type": "text", "key": "inputkey", "label": "Input Key name" }, { "type": "text", "key": "readwritekey", "label": "Read/Write API Key" }, { "type": "url", "key": "graphicurl", "label": "Graphic Url", "ifheight": 460, "default": "http://emoncms.org/vis/realtime?feedid={1}&embed=1&apikey={3}" } ] }, "thingspeak": { "url": "", "callback": "sendValueToStorage_thingspeak", "parameters": [ { "type": "number", "key": "channelid", "label": "Channel ID" }, { "type": "text", "key": "readkey", "label": "Read API Key" }, { "type": "text", "key": "writekey", "label": "Write API Key" }, { "default": 1, "type": "number", "key": "fieldnum", "label": "Field Number" }, { "default": "//api.thingspeak.com/channels/{0}/charts/{3}?key={1}&width=450&height=260&results=60&dynamic=true", "type": "url", "key": "graphicurl", "label": "Graphic Url" } ] }, "IFTTT": { "url": "", "callback": "sendValueToStorage_ifttt", "parameters": [ { "type": "text", "key": "webhookkey", "label": "Web Hook Key" }, { "default": "vera_data_published", "type": "text", "key": "eventname", "label": "Hook Event Name" } ] } } now: { "emoncms": { "url": "", "callback": "sendValueToStorage_emoncms", "parameters": [ { "key": "nodeid", "type": "number", "default": 1, "label": "Node ID" }, { "type": "number", "key": "feedid", "label": "Feed ID" }, { "type": "text", "key": "inputkey", "label": "Input Key name" }, { "type": "text", "key": "readwritekey", "label": "Read/Write API Key" }, { "type": "url", "key": "graphicurl", "label": "Graphic Url", "ifheight": 460, "default": "http://emoncms.org/vis/realtime?feedid={1}&embed=1&apikey={3}" } ] }, "IFTTT": { "url": "", "callback": "sendValueToStorage_ifttt", "parameters": [ { "type": "text", "key": "webhookkey", "label": "Web Hook Key" }, { "key": "eventname", "type": "text", "default": "vera_data_published", "label": "Hook Event Name" } ] }, "thingspeak": { "url": "", "callback": "sendValueToStorage_thingspeak", "parameters": [ { "type": "number", "key": "channelid", "label": "Channel ID" }, { "type": "text", "key": "readkey", "label": "Read API Key" }, { "type": "text", "key": "writekey", "label": "Write API Key" }, { "default": 1, "type": "number", "key": "fieldnum", "label": "Field Number" }, { "default": "//api.thingspeak.com/channels/{0}/charts/{3}?key={1}&width=450&height=260&results=60&dynamic=true", "type": "url", "key": "graphicurl", "label": "Graphic Url" } ] } } #hooks: 0 upnp: 0 skip: 0 v:(nil)/NONE duplicate:0 <0x73db2520>
06 03/14/18 21:40:50.715 Device_Variable::m_szValue_set device: 227 service: urn:upnp-org:serviceId:altui1 variable: DataStorageProviders was: { "emoncms": { "url": "", "callback": "sendValueToStorage_emoncms", "parameters": [ { "key": "nodeid", "type": "number", "default": 1, "label": "Node ID" }, { "type": "number", "key": "feedid", "label": "Feed ID" }, { "type": "text", "key": "inputkey", "label": "Input Key name" }, { "type": "text", "key": "readwritekey", "label": "Read/Write API Key" }, { "type": "url", "key": "graphicurl", "label": "Graphic Url", "ifheight": 460, "default": "http://emoncms.org/vis/realtime?feedid={1}&embed=1&apikey={3}" } ] }, "IFTTT": { "url": "", "callback": "sendValueToStorage_ifttt", "parameters": [ { "type": "text", "key": "webhookkey", "label": "Web Hook Key" }, { "key": "eventname", "type": "text", "default": "vera_data_published", "label": "Hook Event Name" } ] }, "thingspeak": { "url": "", "callback": "sendValueToStorage_thingspeak", "parameters": [ { "type": "number", "key": "channelid", "label": "Channel ID" }, { "type": "text", "key": "readkey", "label": "Read API Key" }, { "type": "text", "key": "writekey", "label": "Write API Key" }, { "default": 1, "type": "number", "key": "fieldnum", "label": "Field Number" }, { "default": "//api.thingspeak.com/channels/{0}/charts/{3}?key={1}&width=450&height=260&results=60&dynamic=true", "type": "url", "key": "graphicurl", "label": "Graphic Url" } ] } } now: { "emoncms": { "url": "", "callback": "sendValueToStorage_emoncms", "parameters": [ { "default": 1, "type": "number", "key": "nodeid", "label": "Node ID" }, { "type": "number", "key": "feedid", "label": "Feed ID" }, { "type": "text", "key": "inputkey", "label": "Input Key name" }, { "type": "text", "key": "readwritekey", "label": "Read/Write API Key" }, { "type": "url", "key": "graphicurl", "label": "Graphic Url", "ifheight": 460, "default": "http://emoncms.org/vis/realtime?feedid={1}&embed=1&apikey={3}" } ] }, "IFTTT": { "url": "", "callback": "sendValueToStorage_ifttt", "parameters": [ { "type": "text", "key": "webhookkey", "label": "Web Hook Key" }, { "key": "eventname", "type": "text", "default": "vera_data_published", "label": "Hook Event Name" } ] }, "thingspeak": { "url": "", "callback": "sendValueToStorage_thingspeak", "parameters": [ { "type": "number", "key": "channelid", "label": "Channel ID" }, { "type": "text", "key": "readkey", "label": "Read API Key" }, { "type": "text", "key": "writekey", "label": "Write API Key" }, { "default": 1, "type": "number", "key": "fieldnum", "label": "Field Number" }, { "default": "//api.thingspeak.com/channels/{0}/charts/{3}?key={1}&width=450&height=260&results=60&dynamic=true", "type": "url", "key": "graphicurl", "label": "Graphic Url" } ] } } #hooks: 0 upnp: 0 skip: 0 v:(nil)/NONE duplicate:0 <0x73db2520>
06 03/14/18 21:40:50.748 Device_Variable::m_szValue_set device: 227 service: urn:upnp-org:serviceId:altui1 variable: DataStorageProviders was: { "emoncms": { "url": "", "callback": "sendValueToStorage_emoncms", "parameters": [ { "default": 1, "type": "number", "key": "nodeid", "label": "Node ID" }, { "type": "number", "key": "feedid", "label": "Feed ID" }, { "type": "text", "key": "inputkey", "label": "Input Key name" }, { "type": "text", "key": "readwritekey", "label": "Read/Write API Key" }, { "type": "url", "key": "graphicurl", "label": "Graphic Url", "ifheight": 460, "default": "http://emoncms.org/vis/realtime?feedid={1}&embed=1&apikey={3}" } ] }, "IFTTT": { "url": "", "callback": "sendValueToStorage_ifttt", "parameters": [ { "type": "text", "key": "webhookkey", "label": "Web Hook Key" }, { "key": "eventname", "type": "text", "default": "vera_data_published", "label": "Hook Event Name" } ] }, "thingspeak": { "url": "", "callback": "sendValueToStorage_thingspeak", "parameters": [ { "type": "number", "key": "channelid", "label": "Channel ID" }, { "type": "text", "key": "readkey", "label": "Read API Key" }, { "type": "text", "key": "writekey", "label": "Write API Key" }, { "default": 1, "type": "number", "key": "fieldnum", "label": "Field Number" }, { "default": "//api.thingspeak.com/channels/{0}/charts/{3}?key={1}&width=450&height=260&results=60&dynamic=true", "type": "url", "key": "graphicurl", "label": "Graphic Url" } ] } } now: { "emoncms": { "url": "", "callback": "sendValueToStorage_emoncms", "parameters": [ { "default": 1, "type": "number", "key": "nodeid", "label": "Node ID" }, { "type": "number", "key": "feedid", "label": "Feed ID" }, { "type": "text", "key": "inputkey", "label": "Input Key name" }, { "type": "text", "key": "readwritekey", "label": "Read/Write API Key" }, { "type": "url", "key": "graphicurl", "label": "Graphic Url", "ifheight": 460, "default": "http://emoncms.org/vis/realtime?feedid={1}&embed=1&apikey={3}" } ] }, "IFTTT": { "url": "", "callback": "sendValueToStorage_ifttt", "parameters": [ { "type": "text", "key": "webhookkey", "label": "Web Hook Key" }, { "default": "vera_data_published", "type": "text", "key": "eventname", "label": "Hook Event Name" } ] }, "thingspeak": { "url": "", "callback": "sendValueToStorage_thingspeak", "parameters": [ { "type": "number", "key": "channelid", "label": "Channel ID" }, { "type": "text", "key": "readkey", "label": "Read API Key" }, { "type": "text", "key": "writekey", "label": "Write API Key" }, { "default": 1, "type": "number", "key": "fieldnum", "label": "Field Number" }, { "default": "//api.thingspeak.com/channels/{0}/charts/{3}?key={1}&width=450&height=260&results=60&dynamic=true", "type": "url", "key": "graphicurl", "label": "Graphic Url" } ] } } #hooks: 0 upnp: 0 skip: 0 v:(nil)/NONE duplicate:0 <0x73db2520>
06 03/14/18 21:40:50.749 Device_Variable::m_szValue_set device: 227 service: urn:upnp-org:serviceId:altui1 variable: VariablesToSend was:  now:  #hooks: 0 upnp: 0 skip: 0 v:(nil)/NONE duplicate:1 <0x73db2520>
06
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: jorisdekloris on March 14, 2018, 05:16:02 pm
I tried to run the EnergyMonitor.lua in the Test Luup code section and now it pushed to emoncms. All zero's that is :) and thats not correct.

I changed Watts to KWH in my Lua file and now its actually displaying values :)
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: onepointbrewing on April 03, 2018, 09:02:51 am
Im sort of there but not....

I dont code so im just trying to decypher what everyone has done on this thread and have no idea what Im doing.

Ive managed to get the lua file into my VE and put

emoncode = require("EnergyMonitor")
emoncode.EnergyMonitorOnTimer()

into startup lua

Should I be using the "read API" or the "read & write API" key?

I used the read and write API and eventually Emoncms populated, however it only did it once, and never updated again despite the feed saying updated (in 30+min increments)

And could some kind soul take a look at my lua file and tell me if there are any syntax issues

Code: [Select]
-- Setup your account at http://emoncms.org/
-- See API documentation at http://emoncms.org/input/api

module("EnergyMonitor", package.seeall)

-- API Key
local API_KEY = "e89.........d6e8f82"

-- Setup your devices here. You can use a function to calculate the power as illustrated in the sample.
-- For device logging, use: key, deviceId, serviceId, serviceVar
-- For function based logging, use: key, calculate, serviceVar
local VARIABLES = {
{ key="Test", deviceId = 37, serviceId='urn:micasaverde-com:serviceId:EnergyMetering1', serviceVar="Watts" }, -- Send device energy
{ key='Other1', calculate=function() return 15 end, serviceVar="Watts" } -- Send a constant value
}

local NODE_ID = 10
local TOTAL_KEY = 'Total'

-- Upload Frequency in seconds
local updateInterval = 10

-- Log debug messages
local DEBUG = true



-- You shouldn't need to change anything below this line --


local http = require('socket.http')
http.TIMEOUT = 3

local BASE_URL = "http://emoncms.org/input/post.json?apikey=" .. API_KEY
local Log = function (text) luup.log('EnergyMonitor Logger: ' .. (text or "empty")) end
local lastFullUpload = 0

local items = {} -- contains items: { time, deviceId, value }

local function StartCallbackTimer(interval)
luup.call_delay("EnergyMonitorOnTimer", interval or updateInterval, nil)
end

local function InitWatch()
StartCallbackTimer(1)
end

local function AddKeyValuePair(key, value)
local item = string.format("%s:%s", key, tostring(value))
items[#items + 1] = item
end

local function SerializeData()
local dataText = "{" .. table.concat(items, ",") .. "}"
return dataText
end

local function ResetData()
items = {}
end

local function SendData()
local data = SerializeData()
ResetData()

local parameters = "&node=" .. tostring(NODE_ID) .. "&json=" .. data
local url = BASE_URL .. parameters
if (DEBUG) then Log("Updating with: " .. parameters) end
http.request(url)
end

local function AddAllVariablesAndTotal()
local total = 0
for i, v in ipairs(VARIABLES) do
local value
if v.deviceId then
value = luup.variable_get(v.serviceId, v.serviceVar, v.deviceId)
elseif v.calculate then
value = v.calculate()
end
value = tonumber(value) or 0
if v.serviceVar == "Watts" then
total = total + value
end
AddKeyValuePair(v.key, value)
end
AddKeyValuePair(TOTAL_KEY, total)
end

function EnergyMonitorOnTimer()
StartCallbackTimer()
AddAllVariablesAndTotal()
SendData()
end

-- Added by RTS
_G.FunctionName = FunctionName

InitWatch()


any help would be greatly appreciated
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: onepointbrewing on April 30, 2018, 05:06:28 am
OK,
I posted some other posts here just now in frustration and have subsequently deleted them.

What I will do though is point people in a direction that ABSOLUTELY worked for me.

Follow the instructions in the link ive posted (im not related in any way to this company nor do I know them)

All you have to do is change your devices AND read/write API key, put this in startup.lua

emoncode = require("EnergyMonitor")
emoncode.EnergyMonitorOnTimer()

and bingo you have energy monitoring.

Heres the link:
https://www.livehouseautomation.com.au/blogs/news/using-emoncms-to-log-power-use

Thank you to "livehouseautomation.com.au" for this step by step.
Title: Re: Contribution: Monitor and visualize energy usage with emoncms.org in Vera
Post by: akbooer on April 30, 2018, 05:41:09 am
I was about to reply in detail to your Lua syntax issue, but I'm glad you don't need the response, now.

Also pleased to see that you are up and running and have shared your solutions with others here.  That's indeed what the forum is all about.