Example Scripts

Description

A place where scripts developed by users can be shared. Please make sure that all submissions are well commented.

Hi All,

    Thought I would share this little iphone app and configuration file with you all in case its of any use to others.
I wanted a Joggler style user interface for the Iphone and after much digging stumbled upon an app called "mote".
link here: http://www.worriedcat.com/Mote/Home.html
this is a nice little app that allows you to use your iPhone/iPod touch to control any ethernet-enabled device which communicates via TCP, UDP, HTTP, or HTTPS. Mote is programmable directly on your iPhone/iPod touch, allowing you to lay out buttons the way you want, with full macro functionality.

I use this to send xap messages via UDP to control my HAH relays and rf. I have also setup up a DynDns service so this can even operate over 3G outside the house (with port forwarding setup on the router). Coupled with Brett's Webserver Applet this can also poll 1wire, relay status etc and display on screen.
It can also be setup to poll and display current Pachube values.

This takes a little time to get your head round how it works but is very powerful when you do!. I have attached a basic config file that should be easy enough to modify to suit individuals needs. If you like and need more help setting it up just let me know. The tricky bit is that the Xap messages content need to be entered in HEX, but there are plenty of online TEXT to HEX converters that do the business (i have also done most of this for you in the config file).

Have Fun,

Garry.
p.s. wanted to post some screenshots but got defeated. will try to amend post later with these.

config file link.  https://docs.google.com/document/d/10rH6PuCo6xVKq6TvP2VEG96eZIPBQAnT8ItSPCVPBGo/edit?hl=en_US

Occasionally one might need to post data to more than one Pachube feed .. like me ;)

With this applet one can catch specific events / info and post data to Pachube, also to a different feed that is specified in main hah setup.

Note that applet below is not collecting events for bulk send like the main logic does.  For my own need this was quite ok as I knew events of interest would come up once per minute.

Using together with / data from CcSensorsApplet.lua

Enjoy,
Aivo


PachubeApplet.lua


require("xap")
module (...,package.seeall)
 
info = {version="1.0", description="Post to Pachube (when e.g. feed differs from main HAH setup)"}

ApiKey = "5dcd -- cut --30c79"
FeedID = "14380"
URL="http://api.pachube.com/v2/feeds/"..FeedID..".xml"
sourcefilter = "Plugboard"
classfilter = "cd>"             -- cd* as for "current (cost) digital" sensor; counts water, gas, .. meter pulses
classes = { "cdgas", "cdwat" }  -- classes - xAPBSC. suffixes - we want to filter; same used for stream tags
streams = { 51, 52 }        -- stream id-s corresponding to classes
class2stream = { }          -- this array will have class from "classes" id-s as indexes
xmlmain=[[<?xml version=\"1.0\" encoding=\"UTF-8\"?><eeml xmlns=\"http://www.eeml.org/xsd/005\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" version=\"5\" xsi:schemaLocation=\"http://www.eeml.org/xsd/005 http://www.eeml.org/xsd/005/005.xsd\">%s</eeml>]]
xmlenv=[[<environment id=\"%s\">%s</environment>]]         -- xmlmain contains env; env contains feed id, data
xmldata=[[<data id=\"%s\"><tag>%s</tag><value>%s</value></data>]]    -- data contains stream id, tag, value

function init()
    f = xap.Filter()
    f:add("xap-header", "source", "dbzoo.livebox."..sourcefilter)
    f:add("xap-header", "class", "xAPBSC."..classfilter)
    for i = 1, table.getn(classes) do
        class2stream[classes[i]] = streams[i]
    end
    f:callback(post)
end

function post()
    local class = string.sub(xap.getValue("xap-header","class"), 8)             -- here only "suffix", part after "xAPBSC."
    local value = xap.getValue("input.state","extra")    -- text is primary data: pulse count; extra is liters (gas/water)
    local data = string.format(xmldata, class2stream[class], class, value)    -- stream id, tag, value
    local env = string.format(xmlenv, FeedID, data)                                 -- feed id, data
    local xml = string.format(xmlmain, env)
    local cmd = 'curl --request PUT --header "X-PachubeApiKey: '..ApiKey..'" --data "'..xml..'" '..URL
--    print(cmd)
    os.execute(cmd)
end

This applet is used to log CurrentCost sensor data and generate events for their minute totals.  Latter again can be configured to to posted on Pachube.

Using CurrentCost digital development boards and some TTL logic++ it is possible to count pulses from gas and water meters.

Enjoy,
Aivo


CcSensorsApplet.lua


require("xap")
module (...,package.seeall)
 
info = {version="1.0", description="Log CurrentCost sensor data & xAP send their 1min sums"}

senstates = { }      -- array holding sensor last states; these and next are reset after each send
sensums = { }        -- .. sensor pulse count sums
senlogtimes = { }    -- .. last log times
senofftimes = { }    -- .. last off times
senclasses = { "cdgas", "cdwat" }     -- events generated are with class=xAPBSC.cdgas and similar
senfactors = { 10, 8 }                    -- gas L: 10 * imp -- gas wh: 10 * 1.079723 * 33.7 / 3.6 -- water L: 8 * imp
logpath = '/mnt/usb/livebox/ccsensors'    -- folder on usb stick
period = 60            -- period in seconds we are counting for / send interval

function init()
    fs = xap.Filter()
    fs:add("xap-header", "source", "dbzoo.livebox.CurrentCost:sensor.*")
    fs:callback(savesensor)
    xap.Timer(sendcountsum, period):start()
end

function savesensor()
    local source = xap.getValue("xap-header","source")
    local sensor = tonumber(source:sub(-1))
    if sensor == nil then
        print('Type mismatch, cc sensor.')
        return
    end
    local state = xap.getValue("input.state","state")
    if state == "on" then
        if sensums[sensor] == nil then
            sensums[sensor] = 1
        else
            sensums[sensor] = sensums[sensor] + 1
        end
    end
--    print(sensor, senstates[sensor], state, os.date("%X", senlogtimes[sensor]), os.date("%X", senofftimes[sensor]), os.date("%X"))
    if state == "on" or state ~= senstates[sensor] then
        -- logged are "on" and "on"<->"off"
        -- for "off"->"on" also last "off" before "on" is logged (if not logged yet)
        if senstates[sensor] == "off" and senlogtimes[sensor] ~= senofftimes[sensor] then
            logdataoff(sensor)
        end
        senstates[sensor] = state
        logdata(sensor)
    end
    if state == "off" then
        senstates[sensor] = state
        senofftimes[sensor] = os.time()
    end
end

function logdataoff(sensor)
--    print("logdataoff")
    if senlogtimes[sensor] == nil or senofftimes[sensor] == nil then return end
    local cmd = string.format('echo %s,%s,%s,%s>>%s/%s', os.date("%Y-%m-%d %X", senofftimes[sensor]), sensor, "off", senofftimes[sensor] - senlogtimes[sensor], logpath, os.date("%Y%m%d"))
    os.execute(cmd)
--    print(cmd)
end

function logdata(sensor)
    if senlogtimes[sensor] == nil then senlogtimes[sensor] = 0 end
    local timediff = os.difftime(os.time(), senlogtimes[sensor])
    local cmd = string.format('echo %s,%s,%s,%s>>%s/%s', os.date("%Y-%m-%d %X"), sensor, senstates[sensor], timediff, logpath, os.date("%Y%m%d"))
    os.execute(cmd)
    senlogtimes[sensor] = os.time()
--    print(cmd)
end

function sendcountsum()
    for i = 1, table.getn(senclasses) do
        local sumtosend = 0
        if sensums[i] ~= nil then sumtosend = sensums[i] end
        local sumtosendextra = sumtosend * senfactors[i]
--        print(senclasses[i], sumtosend, sumtosendextra, os.time())
        local msg = string.format([[xap-header
{
target=dbzoo.livebox.CurrentCost:script
class=xAPBSC.%s
}
input.state
{
state=on
text=%s
extra=%s
}]], senclasses[i], sumtosend, sumtosendextra)
        xap.sendShort(msg)
--        print(msg)
    end
    sensums = { }
end

This applet is used 1) to log CurrentCost data to file on usb stick and 2) calculate house total load and generate xAP events for it (send respective message), latter again is configured to be posted on Pachube. 

I have small Linux box as home server (for samba, mythtv, dlna/ps3ms) that is up occasionally; when up it will periodically copy files from livebox and bulk load to mysql.  This data then can then be further analysed and visualized.  I have used Google Vis tools and mc-goog-visualization for this.

Enjoy,
Aivo


CcPowerApplet.lua


require("xap")
module (...,package.seeall)
 
info = {version="1.0", description="Log CurrentCost power data & xAP send house totals"}

load = { }      -- array of CurrentCost latest phase 1..3 values
temp = 0        -- Currentcost temperature
logtime = os.time()    -- using this we decide if current second event is already being sent
logpath = "/mnt/usb/livebox/currentcost"    -- folder on usb stick
oktolog = false         -- set to true when load and temp values all get initialised

function init()
    fp = xap.Filter()
    fp:add("xap-header", "source", "dbzoo.livebox.CurrentCost:ch.*")
    fp:callback(saveload)
    ft = xap.Filter()
    ft:add("xap-header", "source", "dbzoo.livebox.CurrentCost:temp")
--  ft:add("xap-header", "class", "xAPBSC.info")
    ft:callback(savetemp)
    xap.Timer(delaylogstart, 2):start()
end

-- Wait until all values initialized
function delaylogstart(self)
    if table.getn(load) < 3 or temp == 0 then return end
    oktolog = true
    self:delete()
end

function saveload()
    local source = xap.getValue("xap-header","source")
    local ch = tonumber(source:sub(-1))
    if ch == nil then
        print('Type mismatch, cc chnum.')
        return
    end
    load[ch] = xap.getValue("input.state","text")
--  print(string.format("%s,%s,%s,%s", os.date("%Y-%m-%d %X"), ch, xap.getValue("input.state","text"), temp))
    if oktolog and os.time() ~= logtime then   -- one log line/sum event for same second
        logtime = os.time()                           -- delaying send for 1 second,
        xap.Timer(logandsend, 1):start()        -- other possible events from same second are saved until then
    end
end

function savetemp()
    temp = xap.getValue("input.state","text")
end

function logandsend(self)
    local sumload = load[1] + load[2] + load[3]
    local cmd = string.format("echo %s,%s,%s,%s,%s,%s>>%s/%s", os.date("%Y-%m-%d %X"), sumload, load[1], load[2], load[3], temp, logpath, os.date("%Y%m%d"))
    os.execute(cmd)
--  print(cmd)
    local msg = string.format([[xap-header
{
target=dbzoo.livebox.CurrentCost:script
class=xAPBSC.ccel
}
input.state
{
state=on
text=%s
displaytext=%s watts
}]], sumload, sumload)
    xap.sendShort(msg)
--  print(msg)
    self:delete()
end

 

Hello,

My wish was to make more use of LCD and show some data of interest on it.  In particular I wanted to see CurrenCost and 1wire data, of course anything else "known" to HAH may be added.

Hopefully useful for someone else too, either in whole or partially ;)

Enjoy,
Aivo



runlcdApplet.lua, new plugboard format (some formatting - like tabs - is lost here, hopefully still well readable)

Edit: changed self:stop() to self:delete() on advice from Brett, no leakeage needed :)


require("xap")
module (...,package.seeall)
 
info = {version="1.0", description="Scrolling 1wire and CurrentCost data on lcd"}

lcdlen = 16
period = 2  -- scroll/shift speed in seconds
shift = 2  -- scroll/shift step in symbols
tarray = { } -- 1wire temperature data
parray = { } -- CC house/0 sensor data, phases 1 to 3
fill = "-"  -- Space does not work, gets trimmed
  
function init()
 ft = xap.Filter()
 ft:add("xap-header", "source", "dbzoo.livebox.Controller:1wire.*")
-- ft:add("xap-header", "class", "xAPBSC.info")
 ft:callback(catch1wire)
 fp = xap.Filter()
 fp:add("xap-header", "source", "dbzoo.livebox.CurrentCost:ch.*")
-- fp:add("xap-header", "class", "xAPBSC.info")
 fp:callback(catchCurrentCost)
 send2lcd("Scrolling LCD ..")
 xap.Timer(repeatlcd, 10):start()
end

function catch1wire()
 local source = xap.getValue("xap-header","source")
 local id = tonumber(source:sub(-1))
 tarray[id] = xap.getValue("input.state","displaytext")
end

function catchCurrentCost()
 local source = xap.getValue("xap-header","source")
 local id = tonumber(source:sub(-1))
 parray[id] = "P"..id.." "..xap.getValue("input.state","text")
end

-- Refresh infostring from t + p arrays and start new runlcd cycle
function repeatlcd(self)
 local arraylen = table.getn(tarray) + table.getn(parray)
 if arraylen > 0 then
  infostring = string.rep(fill, lcdlen) -- global
  for i,value in ipairs(tarray) do infostring = infostring.." "..value.." "..fill end
  for i,value in ipairs(parray) do infostring = infostring.." "..value.." "..fill end
  infostring = infostring..string.rep(fill, lcdlen - 1)
--  print(infostring)
  infostringlen = string.len(infostring) -- global
  startpos = 1  -- global
  endpos = lcdlen  -- global
  xap.Timer(runlcd, period):start()
  self:delete()
 end
end

-- Show lcdlen/16 wide window of infostring on lcd
function runlcd(self)
 lcdstring = string.sub(infostring, startpos, endpos)
-- print(infostringlen.."."..startpos.."."..endpos.."'"..lcdstring.."'")
 send2lcd(lcdstring)
 endpos = endpos + shift
 if endpos > infostringlen then
  xap.Timer(repeatlcd, period):start()
  self:delete()
 else
  startpos = startpos + shift
 end
end

function send2lcd(lcdstr)
 xap.sendShort(string.format([[xap-header
{
target=dbzoo.livebox.Controller:lcd
class=xAPBSC.cmd
}
output.state.1
{
id=*
state=on
text=%s
}]], lcdstr))
end

Hi,

Just thought I would share a script which may be of use to others. It is for updating the weather underground website.

I installed a outside probe today. Then decided I would do this, it is a bit crude. If I had a humidity sensor etc I would have include those.

It is more as another example. If there where more sensors it would be better to do a time based update and lookup of relevant readings. To post the url it uses linux/unix the "Curl" command.

https://docs.google.com/leaf?id=0B3lq5J_TSkjFYTQ4ZDg5MzQtNDVmMy00MmZmLT…

Hope someone finds it interesting.

I might order a humidity and pressure sensor soon. Would be good if we could get them added to the 1-wire library. Together with the 1-wire hub ic's.

Cheers

Dan

Not sure if this is the best way to share these.  I've created a drop box repository for you to be able to download my scripts.  Some of these are still work in prgress and I warn you, I'm no developer!

Script to bind some of my RF devices together.

http://dl.dropbox.com/u/12119032/Plugboard%20Scripts/bind_rfs.lua

This script controls my Fans in loft when temp gets too high

http://dl.dropbox.com/u/12119032/Plugboard%20Scripts/loft_fans.lua

Script to cleanly shutdown windows PC (needs Airytech Swoff running)

http://dl.dropbox.com/u/12119032/Plugboard%20Scripts/shutdown_win.lua

Turns my Slimp3 off when the rf control the amp it's connected to turns off

http://dl.dropbox.com/u/12119032/Plugboard%20Scripts/slimp3.lua

Sends a WOL message for a PC, mac supplied by xAPFlash button

http://dl.dropbox.com/u/12119032/Plugboard%20Scripts/wake_pc.lua

My attempt to create something of a personality for my HAH through SMS.  Using my android phone as location

aware notifier, it sends sms to HAH depending on where it is (Car, Not at home etc), Hah then does somethings

based on that.   VERY much WIP and not really scratching the surface yet but have had problems on the android end.

http://dl.dropbox.com/u/12119032/Plugboard%20Scripts/incoming_sms.lux

Some of you may snigger at my attempts at scripting, some of you may find this useful, feel free to use/hack/improve and feedback.