User Tools

Site Tools


action_read
read.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 = {}
 
local function split(s, delimiter)
    local result = {}
    for match in (s..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match)
    end
    return result
end
 
function M.check(parameters)
	if parameters['FROM'] == nil then
		error("read action is missing a \"FROM\" statement");
	end
 
	if #parameters['FROM']['value'] ~= 1 or parameters['FROM']['value'][2] ~= nil then
		error("read action \"FROM\" only takes one argument");
	end
 
if parameters['DEVICE'] == nil then
		error("read action is missing a \"DEVICE\" statement");
	end
 
	if #parameters['DEVICE']['value'] ~= 1 or parameters['DEVICE']['value'][2] ~= nil then
		error("read action \"DEVICE\" only takes one argument");
	end
 
	local nrdev = #parameters['DEVICE']['value'];
	for i = 1, nrdev, 1 do
		local dev = pilight.config.device(parameters['DEVICE']['value'][i]);
		if dev == nil then
			error("device \"" .. parameters['DEVICE']['value'][i] .. "\" does not exist");
		end
		if dev.getLabel == nil then
			error("device \"" .. parameters['DEVICE']['value'][i] .. "\" isn't a label device");
		end
	end
return 1;
end
 
function M.thread(thread)
	local data = thread.getUserdata();
	local content = "";
	local fh, errmsg = io.open(data['from'], 'r');
	if fh ~= nil then
		content = fh:read("*all");
		io.close(fh);
		if string.len(content) > 254 then
			-- temporary limitation to prevent buffer overflow in devices.c
			content = string.sub(content, 1, 254)
		end
	else
		local array = pilight.common.explode(errmsg, ": ");
		content = "ERROR: " ..  array[2];		
	end
	local devname = data['device'];
	local devobj = pilight.config.device(devname);
	if devobj.getLabel() ~= content then
		if devobj.setLabel(content) == false then
			error("read action file \"" .. content .. "\" cannot be copied to device \"" .. devname .. "\"")
		end
 
		devobj.send();
	end
end
 
function M.run(parameters)
	local async = pilight.async.thread();
	local data = async.getUserdata();
	data['from'] = parameters['FROM']['value'][1];
	data['device'] = parameters['DEVICE']['value'][1];
	async.setCallback("thread");
	async.trigger();
 
return 1;
end
 
function M.parameters()
	return "FROM", "DEVICE";
end
 
function M.info()
	return {
		name = "read",
		version = "1.0",
		reqversion = "8.1.1",
		reqcommit = "0"
	}
end
 
return M;
action_read.txt · Last modified: 2018/08/08 12:31 by Niek