Creating an event to send to an alternative event server.

Hi

Taking bits for other posts I’ve read, I’ve had a go at creating a function that will send an event to an alternate event server when a temperature value changes. (This all relates to @Quinten’s Event Server post)

Please could you let me know if I’m on the right track…

[code]local temp_device_to_watch = 137

luup.variable_watch(“updateTempLastUpdated”, “urn:micasaverde-com:serviceId:TemperatureSensor1”, “CurrentTemperature”, temp_device_to_watch)
–sets up the callback to the function pasted below

function updateTempLastUpdated(dev_id,service, variable, old_val, new_val)
– called when a temperature device changes

if new_val > old_val then
– send temp has increased notification to thealternative Vera event server MySQL db

  https://192.168.1.111:8001/alert?PK_AccessPoint=35102036&HW_Key=BlahBlah&DeviceID=33&LocalDate=2013-08-21%2003:12:17&LocalTimestamp=1377051137&AlertType=3&SourceType=3&Argument=12&Format=&Code=CurrentTemperature&Value=18&Description=House%20Temp%20Increases%20From%20..old_val..%20to%20..new_val..%20&Users=157707

   else

if old_val > new_val then
– send temp has decreased notification to the alternative Vera event server MySQL db

  https://192.168.1.111:8001/alert?PK_AccessPoint=35102036&HW_Key=BlahBlah&DeviceID=33&LocalDate=2013-08-21%2003:12:17&LocalTimestamp=1377051137&AlertType=3&SourceType=3&Argument=12&Format=&Code=CurrentTemperature&Value=18&Description=House%20Temp%20Drops%20From%20..old_val..%20to%20..new_val..%20&Users=157707

else

end
end
end[/code]

I’m not sure how to address the date times values so they are taken fresh/dynamically every time, I assume it’s os.date() but not sure where to put it, or how to format it appropriately. Also I’d like as much of the event URL to be created dynamically so it can work for other variables too.

Many thanks for any help you people can give

My objective is to try and dynamically create that elements with the Event Server notification URL (http://wiki.micasaverde.com/index.php/AlternateEventServer)

[url=https://192.168.1.111/alert?]https://192.168.1.111/alert?[/url]
PK_AccessPoint= [serial number of Vera - fixed value]
&HW_Key= [hardware key of Vera - fixed value]
&DeviceID= [device id that is associated with the alert - dynamic]
&LocalDate= [the time the alert happened as human readable text - dynamic - how do convert?]
&LocalTimestamp=[the time the alert happened as a unix timestamp in UTC - dynamic - could this be os.date()?]
&AlertType= [one of the alert types - fixed - so for this it would be 4 or “ALERT_VARIABLE” ?- see above URL)
&SourceType= [one of the source types - fixed - so for it would be 4 or “SOURCE_VARIABLE”?- see above URL]
&Argument= [an optional argument depending on the alert type - not sure what this is so - fixed?]
&Format= [a file format, not normally used - dynamic - ok can be left blank]
&Code= [a code for the alert, usually the variable that changed - dynamic ]
&Value= [the value corresponding to the code above - dynamic]
&Description= [a human readable description of the event, or comments regarding it - dynamic?]
&Users= [a comma separated list of user id’s that should be notified of the event - fixed]

[url=https://192.168.1.111:8001/alert?PK_AccessPoint=35102036&HW_Key=1234567&DeviceID=33&LocalDate=2013-08-21%2003:12:17&LocalTimestamp=1377051137&AlertType=3&SourceType=3&Argument=12&Format=&Code=CurrentTemperature&Value=18&Description=House%20Temp%20Increases%20From%2017%20to%2018%20&Users=157707]https://192.168.1.111:8001/alert?PK_AccessPoint=35102036&HW_Key=1234567&DeviceID=33&LocalDate=2013-08-21%2003:12:17&LocalTimestamp=1377051137&AlertType=3&SourceType=3&Argument=12&Format=&Code=CurrentTemperature&Value=18&Description=House%20Temp%20Increases%20From%2017%20to%2018%20&Users=157707[/url]

Ok, so I’m thinking…

Should I specify the fixed ones dynamic ones as local values?
Or can they just go directly in URL? I assume the fixed ones can…

– fixed

Local AP = 1234567 – to be used for Pk_AccessPoint
Local HKey = 1234567 – to be used for &HW_Key
Local Dev = 124 – to be used for the DeviceID

– dynamic

Local Date = os.date() – to be used for &LocalDate
Local Time = os.time() – to be used for &LocalTimestamp

To create…

//veraIP:8001/alert?PK_AccessPoint=AP&HW_Key=HKey&DeviceID=Dev&LocalDate=Date&LocalTimestamp=Time&AlertType=3&SourceType=3&Argument=12&Format=&Code=CurrentTemperature&Value=18&Description=House%20Temp%20Increases%20From%2017%20to%2018%20&Users=157707’

I can at least help you with the Lua string-building side of things.

There are two ways to build up a string with constant bits and dynamic bits.

One is to use the string concatenation operator, spelled … (two dots). Put the constant bits in quotes, and the variable bits not in quotes.

local now = os.time()
local val = luup.variable_get(...)
local s = "time=" .. now .. "&data=" .. val

Two is to use string.format() which selectively replaces magic sequences in a string with supplied values. The magic sequences look like %d for a number, %s for a string, and so on:

local now = os.time()
local val = luup.variable_get(...)
local s = string.format("time=%d&data=%s", now, val)

One or the other of these may be more natural for a given tasks; the end result is the same.

Once you’ve formed s, you can pass it to luup.inet.wget().

Thanks so much @futzle for responding :slight_smile:

Am I on the right track?

[code]Local URL = “https://192.168.1.111:8001/alert?”
Local AP = “1234567” – to be used for Pk_AccessPoint
Local HKey = “1234567” – to be used for &HW_Key
Local Dev = 124 – to be used for the DeviceID
Local Date = os.date() – to be used for &LocalDate
Local Time = os.time() – to be used for &LocalTimestamp
Local Alert = 3 – to be used for &AlertType
Local Source = 3 – to be used for &SourceType
Local Argument = 12 – to be used for &Argument
Local Format = – to be used for &Format
Local Code = – to be used for &Code
Local Description = – to be used for &Description
Local Users = – to be used for &Users
Local Value =

Option 1

Local s = … URL … “PK_AccessPoint=” … AP … “&HW_Key=” … HKey … “&DeviceID=” … Dev … “&LocalDate=” … Date … “&LocalTimestamp=” … Time … “&AlertType=” … Alert … “&SourceType=” … Type … “&Argument=” … Argument … “&Format=” “&Code=” CurrentTemperature “&Value=” … new_val … "&Description=“House%20Temp%20Increases%20From%20” …old_val… “%20to%20” …new_val… “&Users=” … Users

Option 2

Local t = string.format(“%sPK_AccessPoint=%s&HW_Key=%d&DeviceID=%d&LocalDate=%s&LocalTimestamp=%s&AlertType=%d&Argument=%d&Format=%d&Code=%s&Value=”, URL, AP, HKey, Dev, Date, Time, Alert, Source, Argument, Format, Code, Description, Users)[/code]

Very much. (Note that … is an infix operator like * so you should remove the … that you’ve put straight after the =.)

At some point in the future you will need to learn about the url.escape() function. Not yet, but if you want to read ahead, search the forum for examples of it and why it’s needed.

It’s definitely worth trying this kind of coding out on a real computer running Lua rather than having to mess with the Vera shell or plugin interface. You can run lines of code one at a time and print the results out. You can even send the HTTP request if you’ve got Luasocket installed.

Hi, I think I’m close, but as much as I try I still get an error…

Code =

[code] – my test script

local URL = “https://192.168.1.111:8001/alert?”
local AP = “1234567” – to be used for Pk_AccessPoint
local HKey = “1234567” – to be used for &HW_Key
local Dev = 124 – to be used for the DeviceID
local Date = os.date() – to be used for &LocalDate
local Time = os.time() – to be used for &LocalTimestamp
local Alert = 3 – to be used for &AlertType
local Source = 3 – to be used for &SourceType
local Argument = 12 – to be used for &Argument
local Format = 5 – to be used for &Format
local Code = 4 – to be used for &Code
local Description = “Hello World” – to be used for &Description
local Users = 6 – to be used for &Users
local Value = 6 – to be used for &value

local s = URL … “PK_AccessPoint=” … AP … “&HW_Key=” … HKey … “&DeviceID=” … Dev … “&LocalDate=” … Date … “&LocalTimestamp=” … Time … “&AlertType=” … Alert … “&SourceType=” … Source … “&Argument=” … Argument … “&Format=” … Format … “&Code=” … Code … “&Value=” … Value … “&Description=” … Description … “&Users=” … Users

local Print (s)

end

[/code]

Error =

string " -- my test script ..."]:23: syntax error near 'end'PANIC: unprotected error in call to Lua API ([string " -- my test script ..."]:23: syntax error near 'end')

[quote=“parkerc, post:7, topic:177051”]string " -- my test script ..."]:23: syntax error near 'end'PANIC: unprotected error in call to Lua API ([string " -- my test script ..."]:23: syntax error near 'end') [/quote]

You should have as many "end"s as you do "if"s*. You have zero "if"s so that “end” should not be there.

BTW, I don’t know what “Print” is, so unless you’ve defined it somewhere else it’s going to be your next error.

  • “end” matches other things too, but you haven’t got any of those either.

That’s what I thought, and I didn’t have one at first, but the error before was this - [string " – my test script …“]:24: syntax error near ''PANIC: unprotected error in call to Lua API ([string " – my test script …”]:24: syntax error near ‘’)

So I added an “end”.

I understood Print would just show me on screen what ‘s’ (the dynamic URL) looked like all together. E.g Print (“Hello World”)

Ok good and thanks so much again, if I remove the “print” and the “end” references I do not get any errors, (way-hay!!!) but how can I see what the finished URL looks like to know it’s right ?

It’s spelled print() rather than Print(), but the expected error message is being subverted because of the preceding use of local, which is priming the Lua parser to expect you to name a local variable.

Summary: use

print(s)

Not

local Print(s)

…Not that you can always see the output of print() on Vera. You would need to run Lua from the shell (Vera’s or a real computer’s). On Vera you often see luup.log(s) to put the string into the LuaUPnP.log file.

There’s such a fine line between success and failure. The wrong case used and it all fails !

I do wish some of these Lua programming apps would come with some intelligence to help the learner so they could say things like “did you mean that?”

Wow! Lower case ‘print()’ works a treat … I have finally compiled an event URL. ;D

Now I need to work on that a bit more, then I need to work it into the Luup.variable_watch functions…

@futzle you’re a star… Stay tuned for the next thrilling instalment :stuck_out_tongue: …

Hi.

All looks to be progressing well, one small hitch is that os.date() returns spaces which break up the URL, and I’m struggling to find a way to make it HTML friendly (either put a dash ‘-’ or ‘20%’ in between …

&LocalDate=Sat Sep 28 19:53:20 2013

Arrhh - I think this is the url.escape bit… So I’ll keep digging…

Add the following functions to your code:

local function to_hex(spec_char)
   return string.format("%%%2X", spec_char:byte(1))
end
local function escape(in_string)
   return string.gsub(in_string, "%W", to_hex)
end

@futzle warned you that you will probably need to worry about URL encoding!

Then for any argument that you want to pass using a URL call:
print(“http://SomeUrl/Cmd?Arg1=” … escape(Val1) … “&Arg2=” … escape(Val2) …

Thanks @RTS

I’ve been searching the forum and this evening I’ve been using this for the URL.encoding.

"&LocalDate=" .. url.escape(Date) ..

It seems to work, but I’ll see if I can learn yours too.

I’ve also been able to use Luup.inet.wget() and submit some events to the web server, although the date and time items are not updating. My guess is that this is a field type/format issue. (I stress guess :wink: )

Current code is as follows.

[code]-- version 0.2

local url = require(“socket.url”)
local URL = “https://192.168.1.111:8001/alert?”
local AP = “1234567” – to be used for Pk_AccessPoint
local HKey = “1234567” – to be used for &HW_Key
local Dev = 110 – to be used for the DeviceID
local Date = os.date() – to be used for &LocalDate
local Time = os.time() – to be used for &LocalTimestamp
local Alert = 3 – to be used for &AlertType
local Source = 3 – to be used for &SourceType
local Argument = 12 – to be used for &Argument
local Format = 5 – to be used for &Format
local Code = 4 – to be used for &Code
local Description = “The%20temperature%20has%20changed%20to%20” – to be used for &Description
local Users = 6 – to be used for &Users
local Value = luup.variable_get (“urn:upnp-org:serviceId:TemperatureSensor1”, “CurrentTemperature”, Dev) – to be used for &value

local s = URL … “PK_AccessPoint=” … luup.pk_accesspoint … “&HW_Key=” … luup.hw_key … “&DeviceID=” … Dev … “&LocalDate=” … url.escape(Date) … “&LocalTimestamp=” … Time … “&AlertType=” … Alert … “&SourceType=” … Source … “&Argument=” … Argument … “&Format=” … Format … “&Code=” … Code … “&Value=” … Value … “&Description=” … Description … “&Users=” … Users

luup.log(s)
luup.inet.wget(s)
[/code]

@parkerc - following your invitation to widen the discussion (I think you meant on this post), I’d like to go back to your original post here and ask what the motivation is to create a ‘pseudo-event’ for an alternate server? The idea, I thought, of events was that you set a threshold (typically) and get told when a value crosses that. If I’m not mistaken, you’re seeking to send an event whenever the value changes. That looks more like a variable_watch than an event? (ie. creating your own device log)? So perhaps I’m missing something.

I note that a by-product of this approach is that although your alternate event server will record what you send, the MiOS one will be oblivious to it. Is this a desired feature?

Hi @akbooer

Yes, the goal of this thread is indeed to create a luup.variable_watch facility to create ‘pseudo events’ on the Alternative Event Server. I do not believe such an ‘event’ is possible to set up via the UI, plus I liked the idea of having such Information captured and trended over time (think DataMine )

And as for the fact that these particular events would only be recorded on my alternative server is fine for me as it’s a personal requirement, plus (I assumed) that’s the only event server I can access/reference anyway ? Or can we access the MIOS one too ?

Only under the Account tab from the web GUI, so far as I know.
So yes, from the (programatic) reference point of view, it’s useless really.
This surely IS something which drives the interest in an alternative.

I know this thread is a bit old by now, but I don’t believe a complete working solution was posted here.
So here is what works for me for recording energy usage from an AEON Labs energy monitor:

  1. set up the Alternate Event Server

  2. put the following code into Startup Lua (Apps → “Develop Apps” → “Edit Startup Lua”) (adjust your deviceid and event server IP)

-- 
-- VeraLite Lua code to report variable changes
--
-- 
--
-- expected Format:
-- https://192.168.1.222/alert?PK_AccessPoint=35102036&HW_Key=12345&DeviceID=111&LocalDate=2014-01-26%2020:06:54&LocalTimeStamp=1390784814&AlertType=3&SourceType=3&Argument=12&Format=&Code=KWH&Value=1234&Description=Energy%2dMeter%3a%20KWh%20has%20changed

-- device id  of the Aeon Labs Energy Monitor
local device_id_HEM = 26

-- watch the KWh value
luup.variable_watch("sendVariableChangeKWh", "urn:micasaverde-com:serviceId:EnergyMetering1", "KWH", device_id_HEM)
-- watch the Watts value
luup.variable_watch("sendVariableChangeWatts", "urn:micasaverde-com:serviceId:EnergyMetering1", "Watts", device_id_HEM)


function sendVariableChangeKWh(dev_id, service, variable, old_val, new_val)

  if new_val ~= old_val then
    sendToEventServer(dev_id, "KWH", new_val, "Energy Meter: KWh")
  end
  
end

function sendVariableChangeWatts(dev_id, service, variable, old_val, new_val)

  if new_val ~= old_val then
    sendToEventServer(dev_id, "Watts", new_val, "Energy Meter: Watts")
  end
  
end


--
-- Example call: sendToEventServer(dev_id, "KWH", new_val, "Energy-Meter: KWh has changed")
--
function sendToEventServer (deviceId, varName, varValue, description)

  -- configure for your server
  local eventServerIP = "192.168.1.222"

  local serialNo = luup.pk_accesspoint 
  local hwKey = luup.hw_key

  local dateFormatted = os.date("%Y-%m-%d%%20%H:%M:%S")
  
  local url = require("socket.url")
  
  local payload = "&DeviceID=" .. tostring(deviceId) .. 
                  "&LocalDate=" .. dateFormatted ..
                  "&LocalTimeStamp=" .. tostring(os.time()) ..
                  "&AlertType=4&SourceType=4&Argument=&Format=" ..
                  "&Code=" .. url.escape(varName) ..
                  "&Value=" .. url.escape(tostring(varValue)) ..
                  "&Description=" .. url.escape(description) ..
                  "&Users="
  
  
  local baseUrl = "https://" .. eventServerIP .. "/alert?PK_AccessPoint=" .. serialNo .. "&HW_Key=" .. hwKey
  
  -- print(baseUrl .. payload)
  
  luup.inet.wget(baseUrl .. payload)
    
end

Hope this helps someone.

Thanks Mike, this was awesome!