User Tools

Site Tools


function_gevar
getvar.lua
-- Copyright (C) 2018 CurlyMo & Niek
 
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
local M = {}
 
-- Tokenize a string given in "str", delimited by single character given in "sep", 
-- ignoring those escaped with single character given in "esc".
-- All escape characters are retained in the result unless keepesc is true.
 
local function tokenize(str, sep, esc, keepesc)
    local strList, word, escaped, ch = {}, "", false
    for pos = 1, #str do
        ch = str:sub(pos, pos)
        if ch == esc then
            if escaped then
                word = word .. ch
				if keepesc then 
					word = word .. esc 	-- retain escape
				end
                escaped = false
            else
                escaped = true
            end
        elseif ch == sep then
            if escaped then
				if keepesc then 
					word = word .. esc 	-- retain escape
				end
                word = word .. ch
                escaped = false
            else
                table.insert(strList, word)
                word = ""
            end
        else
			if escaped and keepesc then
				word = word .. esc -- retain escape
			end
			word = word .. ch
			escaped = false
        end
    end
    table.insert(strList, word)
    return strList
end
 
 
function M.run(a, b, c) -- a = varname, b = device name
	if a == nil or c ~= nil then
		error("GETVAR requires one or two arguments")
		return nil
	end
 
	if b == nil then
		devname = "_VARSTORE_"
	else 
		devname = b
	end
 
	local devobj = pilight.config.device(devname);
	if devobj == nil then
		error("GETVAR action device \"" .. devname .. "\" does not exist");
	end
	if devobj.getLabel == nil then
		error("GETVAR action device \"" .. devname .. "\" isn't a generic_label device");
	end
 
	local varstore = devobj.getLabel()
 
	local value = "*undefined*" -- default result if variable doesn't exist
 
	if varstore ~= nil then
		haystack = tokenize(varstore, "&", "%", true)
		for i,n in pairs(haystack) do
		parts = tokenize(n, "=", "%", false)
			if parts[1] == "$default" and parts[2] ~= nil then
				value = parts[2] -- user defined result if variable doesn't exist
			end
			if parts[1] == a and parts[2] ~= nil then
				value = parts[2]
			end
		end
	end
	return value
end
 
function M.info()
	return {
		name = "GETVAR",
		version = "1.0",
		reqversion = "8.1.1",
		reqcommit = "0"
	}
end
 
return M
function_gevar.txt · Last modified: 2018/08/07 09:26 by Niek