Jump to content
Guides for the Forum Read more... ×
Poradniki na Forum Read more... ×

Recommended Posts

Witam serdecznie.

Szukam kogoś kto zainteresuję się rozwinięciem użycia Paw Serwera w systemie fibaro ,wiadomości tekstowe na tablecie który jest w centralnej części domu to bardzo fajne rozwiązanie informuje o wydarzeniach ...

 

-------------------------------------------------------------------------------------------
 -------------------------------------------------------------------------------------------
 -- Toolkit Framework, lua library extention for HC2, hope that it will be useful.  -- This Framework is an addon for HC2 Toolkit application in a goal to aid the integration.

 -- This Framework is an addon for HC2 Toolkit application in a goal to aid the integration.
 -- Tested on Lua 5.1 with Fibaro HC2 3.572 beta
 --
 -- Version 1.0.2 [12-13-2013]
 --
 -- Use: Toolkit or Tk shortcut to access Toolkit namespace members.
 --
 -- Example:
 -- Toolkit:trace("value is %d", 35); or Tk:trace("value is %d", 35);
 -- Toolkit.assertArg("argument", arg, "string"); or Tk.assertArg("argument", arg, "string");
 --
 -- current release:

Please login or register to see this link.


 -- latest release:

Please login or register to see this link.


 --
 -- Memory is preserved: The code is loaded only the first time in a virtual device
 -- main loop and reloaded only if application pool restarded.
 --
 -- Copyright (C) 2013 Jean-Christophe Vermandé
 --
 -- This program is free software: you can redistribute it and/or modify
 -- it under the terms of the GNU General Public License as published by
 -- the Free Software Foundation, either version 3 of the License, or
 -- at your option) any later version.
 -------------------------------------------------------------------------------------------
 -------------------------------------------------------------------------------------------
 if not Toolkit then Toolkit = {
   __header = "Toolkit",
   __version = "1.0.2",
   __luaBase = "5.1.0",
   __copyright = "Jean-Christophe Vermandé",
   __licence = [[
     Copyright (C) 2013 Jean-Christophe Vermandé

     This program is free software: you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
     the Free Software Foundation, either version 3 of the License, or
     (at your option) any later version.

     This program is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses></http:>.
   ]],
   __frameworkHeader = (function(self)
     self:traceEx("green", "-------------------------------------------------------------------------");
     self:traceEx("green", "-- HC2 Toolkit Framework version %s", self.__version);
     self:traceEx("green", "-- Current interpreter version is %s", self.getInterpreterVersion());
     self:traceEx("green", "-- Total memory in use by Lua: %.2f Kbytes", self.getCurrentMemoryUsed());
     self:traceEx("green", "-------------------------------------------------------------------------");
   end),
   -- chars
   chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
   -- hex
   hex = "0123456789abcdef",
   -- now(), now("*t", 906000490)
   -- system date shortcut
   now = os.date,
   -- toUnixTimestamp(t)
   -- t (table)        - {year=2013, month=12, day=20, hour=12, min=00, sec=00}
   -- return Unix timestamp
   toUnixTimestamp = (function(t) return os.time(t) end),
   -- fromUnixTimestamp(ts)
   -- ts (string/integer)    - the timestamp
   -- Example : fromUnixTimestamp(1297694343) -> 02/14/11 15:39:03
   fromUnixTimestamp = (function(s) return os.date("%c", ts) end),
   -- currentTime()
   -- return current time
   currentTime = (function() return tonumber(os.date("%H%M%S")) end),
   -- comparableTime(hour, min, sec)
   -- hour (string/integer)
   -- min (string/integer)
   -- sec (string/integer)
   comparableTime = (function(hour, min) return tonumber(string.format("%02d%02d%02d", hour, min, sec)) end),
   -- isTraceEnabled
   -- (boolean)    get or set to enable or disable trace
   isTraceEnabled = true,
   -- isAutostartTrigger()
   isAutostartTrigger = (function() local t = fibaro:getSourceTrigger();return (t["type"]=="autostart") end),
   -- isOtherTrigger()
   isOtherTrigger = (function() local t = fibaro:getSourceTrigger();return (t["type"]=="other") end),
   -- raiseError(message, level)
   -- message (string)    - message
   -- level (integer)    - level
   raiseError = (function(message, level) error(message, level); end),
   -- colorSetToRgbwTable(colorSet)
   -- colorSet (string) - colorSet string
   -- Example: local r, g, b, w = colorSetToRgbwTable(fibaro:getValue(354, "lastColorSet"));
   colorSetToRgbw = (function(self, colorSet)
     self.assertArg("colorSet", colorSet, "string");
     local t, i = {}, 1;
     for v in string.gmatch(colorSet,"(%d+)") do t = v; i = i + 1; end
     return t[1], t[2], t[3], t[4];
   end),
   -- isValidJson(data, raise)
   -- data (string)    - data
   -- raise (boolean)- true if must raise error
   -- check if json data is valid
   isValidJson = (function(self, data, raise)
     self.assertArg("data", data, "string");
     self.assertArg("raise", raise, "boolean");
     if (string.len(data)>0) then
       if (pcall(function () return json.decode(data) end)) then
         return true;
       else
         if (raise) then self.raiseError("invalid json", 2) end;
       end
     end
     return false;
   end),
   -- assert_arg(name, value, typeOf)
   -- (string)    name: name of argument
   -- (various)    value: value to check
   -- (type)        typeOf: type used to check argument
   assertArg = (function(name, value, typeOf)
     if type(value) ~= typeOf then
       Tk.raiseError("argument "..name.." must be "..typeOf, 2);
     end
   end),
   -- trace(value, args...)
   -- (string)    value: value to trace (can be a string template if args)
   -- (various)    args: data used with template (in value parameter)
   trace = (function(self, value, ...)
     if (self.isTraceEnabled) then
       if (value~=nil) then        
         return fibaro:debug(string.format(value, ...));
       end
     end
   end),
   -- traceEx(value, args...)
   -- (string)    color: color use to display the message (red, green, yellow)
   -- (string)    value: value to trace (can be a string template if args)
   -- (various)    args: data used with template (in value parameter)
   traceEx = (function(self, color, value, ...)
     self:trace(string.format('<%s style="color:%s;">%s</%s>', "span", color, string.format(value, ...), "span"));
   end),
   -- getInterpreterVersion()
   -- return current lua interpreter version
   getInterpreterVersion = (function()
     return _VERSION;
   end),
   -- getCurrentMemoryUsed()
   -- return total current memory in use by lua interpreter
   getCurrentMemoryUsed = (function()
     return collectgarbage("count");
   end),
   -- trim(value)
   -- (string)    value: the string to trim
   trim = (function(s)
     Tk.assertArg("value", s, "string");
     return (string.gsub(s, "^%s*(.-)%s*$", "%1"));
   end),
   -- filterByPredicate(table, predicate)
   -- table (table)        - table to filter
   -- predicate (function)    - function for predicate
   -- Description: filter a table using a predicate
   -- Usage:
   -- local t = {1,2,3,4,5};
   -- local out, n = filterByPredicate(t,function(v) return v.item == true end);
   -- return out -> {2,4}, n -> 2;
   filterByPredicate = (function(table, predicate)
     Tk.assertArg("table", table, "table");
     Tk.assertArg("predicate", predicate, "function");
     local n, out = 1, {};
     for i = 1,#table do
       local v = table;
       if (v~=nil) then
         if predicate(v) then
             out[n] = v;
             n = n + 1;    
         end
       end
     end  
     return out, #out;
   end)
 };Toolkit:__frameworkHeader();Tk=Toolkit;
 end;
 -------------------------------------------------------------------------------------------
 -------------------------------------------------------------------------------------------
 -- Toolkit.Debug library extention
 -- Provide help to trace and debug lua code on Fibaro HC2
 -- Tested on Lua 5.1 with HC2 3.572 beta
 --
-- Copyright 2013 Jean-christophe Vermandé
 --
 -- Version 1.0.1 [12-12-2013]
 -------------------------------------------------------------------------------------------
 -------------------------------------------------------------------------------------------
 if not Toolkit.Debug then Toolkit.Debug = {
   __header = "Toolkit.Debug",
   __version = "1.0.1",
   -- The os.clock function returns the number of seconds of CPU time for the program.
   __clocks = {["fragment"]=os.clock(), ["all"]=os.clock()},
   -- benchmarkPoint(name)
   -- (string)    name: name of benchmark point
   benchmarkPoint = (function(self, name)
     __clocks[name] = os.clock();
   end),
   -- benchmark(message, template, name, reset)
   -- (string)     message: value to display, used by template
   -- (string)     template: template used to diqplay message
   -- (string)     name: name of benchmark point
   -- (boolean)     reset: true to force reset clock
   benchmark = (function(self, message, template, name, reset)
     Toolkit.assertArg("message", message, "string");
     Toolkit.assertArg("template", message, "string");
     if (reset~=nil) then Toolkit.assertArg("reset", reset, type(true)); end
     Toolkit:traceEx("yellow", "Benchmark ["..message.."]: "..
       string.format(template, os.clock() - self.__clocks[name]));
     if (reset==true) then self.__clocks[name] = os.clock(); end
   end)
 };
 Toolkit:traceEx("red", Toolkit.Debug.__header.." loaded in memory...");
 -- benchmark code
 if (Toolkit.Debug) then Toolkit.Debug:benchmark(Toolkit.Debug.__header.." lib", "elapsed time: %.3f cpu secs\n", "fragment", true); end ;
 end;
 -------------------------------------------------------------------------------------------
 -------------------------------------------------------------------------------------------
 -- Toolkit.Net library extention
 -- Toolkit.Net.HttpRequest provide http request with advanced functions
 -- Tested on Lua 5.1 with HC2 3.572 beta
 --
-- Copyright 2013 Jean-christophe Vermandé
 -- Thanks to rafal.m for the decodeChunks function used when reponse body is "chunked"
 --

Please login or register to see this link.


 --
 -- Version 1.0.3 [12-13-2013]
 -------------------------------------------------------------------------------------------
 -------------------------------------------------------------------------------------------
 if not Toolkit then error("You must add Toolkit", 2) end
 if not Toolkit.Net then Toolkit.Net = {
   -- private properties
   __header = "Toolkit.Net",
   __version = "1.0.3",
   __cr = string.char(13),
   __lf = string.char(10),
   __crLf = string.char(13, 10),
   __host = nil,
   __port = nil,
   -- private methods
   __trace = (function(v, ...)
     if (Toolkit.Net.isTraceEnabled) then Toolkit:trace(v, ...) end
   end),
   __writeHeader = (function(socket, data)
     assert(tostring(data) or data==nil or data=="", "Invalid header found: "..data);
     local head = tostring(data);
     socket:write(head..Toolkit.Net.__crLf);
     Toolkit.Net.__trace("%s.%s::request > Add header [%s]",
       Toolkit.Net.__header, Toolkit.Net.__Http.__header, head);
   end),
   __decodeChunks = (function(a)
     resp = "";
     line = "0";
     lenline = 0;
     len = string.len(a);
     i = 1;
     while i<=len do
       c = string.sub(a, i, i);
       if (lenline==0) then
         if (c==Toolkit.Net.__lf) then
           lenline = tonumber(line, 16);
           if (lenline==null) then
             lenline = 0;
           end
           line = 0;
         elseif (c==Toolkit.Net.__cr) then
           lenline = 0;
         else
           line = line .. c;
         end
       else
         resp = resp .. c;
         lenline = lenline - 1;
       end
       i = i + 1;
     end
     return resp;
   end),
   __readHeader = (function(data)
     if data == nil then
       error("Couldn't find header");
     end
     local buffer = "";
     local headers = {};
     local i, len = 1, string.len(data);
     while i<=len do
       local a = data:sub(i,i) or "";
       local b = data:sub(i+1,i+1) or "";
       if (a..b == Toolkit.Net.__crLf) then
         i = i + 1;
         table.insert(headers, buffer);
         buffer = "";
       else
         buffer = buffer..a;      
       end
       i = i + 1;
     end
     return headers;
   end),
   __readSocket = (function(socket)
     local err, len = 0, 1;
     local buffer, data = "", "";
     while (err==0 and len>0) do
       data, err = socket:read();
       len = string.len(data);
       buffer = buffer..data;
     end
     return buffer, err;
   end),
   __Http = {
     __header = "HttpRequest",
     __version = "1.0.3",    
     __tcpSocket = nil,
     __timeout = 250,
     __waitBeforeReadMs = 25,
     __isConnected = false,
     __isChunked = false,
     __url = nil,
     __method = "GET",  
     __headers = {},
     __body = nil,
     __authorization = nil,
     -- Toolkit.Net.HttpRequest:setBasicAuthentication(username, password)
     -- Sets basic credentials for all requests.
     -- username (string) – credentials username
     -- password (string) – credentials password
     setBasicAuthentication = (function(self, username, password)
       Toolkit.assertArg("username", username, "string");
       Toolkit.assertArg("password", password, "string");
       --see:

Please login or register to see this link.


       self.__authorization = Toolkit.Crypto.Base64:encode(tostring(username..":"..password));
     end),
     -- Toolkit.Net.HttpRequest:setBasicAuthenticationEncoded(base64String)
     -- Sets basic credentials already encoded. Avoid direct exposure for information.
     -- base64String (string)    - username and password encoded with base64
     setBasicAuthenticationEncoded = (function(self, base64String)
       Toolkit.assertArg("base64String", base64String, "string");
       self.__authorization = base64String;
     end),
     -- Toolkit.Net.HttpRequest:setWaitBeforeReadMs(ms)
     -- Sets ms
     -- ms (integer) – timeout value in milliseconds
     setWaitBeforeReadMs = (function(self, ms)
       Toolkit.assertArg("ms", ms, "integer");
       self.__waitBeforeReadMs = ms;
       Toolkit.Net.__trace("%s.%s::setWaitBeforeReadMs > set to %d ms",
         Toolkit.Net.__header, Toolkit.Net.__Http.__header, ms);
     end),
     -- Toolkit.Net.HttpRequest.getWaitBeforeReadMs()
     -- Returns the value in milliseconds
     getWaitBeforeReadMs = (function(self)
       return self.__waitBeforeReadMs;
     end),
     -- Toolkit.Net.HttpRequest.setReadTimeout(ms)
     -- Sets timeout
     -- ms (integer) – timeout value in milliseconds
       setReadTimeout = (function(self, ms)
       Toolkit.assertArg("ms", ms, "number");
       self.__timeout = ms;
       Toolkit.Net.__trace("%s.%s::setReadTimeout > Timeout set to %d ms",
         Toolkit.Net.__header, Toolkit.Net.__Http.__header, ms);
     end),
     -- Toolkit.Net.HttpRequest.getReadTimeout()
     -- Returns the timeout value in milliseconds
     getReadTimeout = (function(self)
       return self.__timeout;
     end),
     -- Toolkit.Net.HttpRequest:disconnect()
     -- Disconnect the socket used by httpRequest
     disconnect = (function(self)
       self.__tcpSocket:disconnect();
       self.__isConnected = false;
       Toolkit.Net.__trace("%s.%s::disconnect > Connected: %s",
         Toolkit.Net.__header, Toolkit.Net.__Http.__header, tostring(self.__isConnected));
     end),
     -- Toolkit.Net.HttpRequest:request(method, uri, headers, body)
     -- method (string)    - method used for the request
     -- uri (string)        - uri used for the request
     -- headers (table)    - headers used for the request (option)
     -- body (string)    - data sent with the request (option)
     request = (function(self, method, uri, headers, body)
       -- validation
       Toolkit.assertArg("method", method, "string");
       assert(method=="GET" or method=="POST" or method=="PUT" or method=="DELETE");
       assert(uri~=nil or uri=="");
       self.__isChunked = false;
       self.__tcpSocket:setReadTimeout(self.__timeout);
       self.__url = uri;
       self.__method = method;
       self.__headers = headers or {};
       self.__body = body or nil;
       local p = "";
       if (Toolkit.Net.__port~=nil) then
         p = ":"..tostring(Toolkit.Net.__port);
       end
           
       local r = self.__method.." ".. self.__url .." HTTP/1.1";
       Toolkit.Net.__trace("%s.%s::request > %s with method %s",
           Toolkit.Net.__header, Toolkit.Net.__Http.__header, self.__url, self.__method);

       local h = "Host: "..Toolkit.Net.__host .. p;
       -- write to socket headers method a host!
       Toolkit.Net.__writeHeader(self.__tcpSocket, r);
       Toolkit.Net.__writeHeader(self.__tcpSocket, h);
       -- add headers if needed
       for i = 1, #self.__headers do
         Toolkit.Net.__writeHeader(self.__tcpSocket, self.__headers);
       end
       if (self.__authorization~=nil) then
         Toolkit.Net.__writeHeader(self.__tcpSocket, "Authorization: Basic "..self.__authorization);
       end
       -- add data in body if needed
       if (self.__body~=nil) then
         Toolkit.Net.__writeHeader(self.__tcpSocket, "Content-Length: "..string.len(self.__body));
         Toolkit.Net.__trace("%s.%s::request > Body length is %d",
           Toolkit.Net.__header, Toolkit.Net.__Http.__header, string.len(self.__body));
       end
       self.__tcpSocket:write(Toolkit.Net.__crLf..Toolkit.Net.__crLf);
       -- write body
       if (self.__body~=nil) then
         self.__tcpSocket:write(self.__body);
       end
       -- sleep to help process
       fibaro:sleep(self.__waitBeforeReadMs);
       -- wait socket reponse
       local result, err = Toolkit.Net.__readSocket(self.__tcpSocket);
       Toolkit.Net.__trace("%s.%s::receive > Length of result: %d",
           Toolkit.Net.__header, Toolkit.Net.__Http.__header, string.len(result));
       -- parse data
       local response, status;
       if (string.len(result)>0) then
         local _flag = string.find(result, Toolkit.Net.__crLf..Toolkit.Net.__crLf);
         local _rawHeader = string.sub(result, 1, _flag + 2);
         if (string.len(_rawHeader)) then
           status = string.sub(_rawHeader, 10, 13);
           Toolkit.Net.__trace("%s.%s::receive > Status %s", Toolkit.Net.__header,
             Toolkit.Net.__Http.__header, status);
           Toolkit.Net.__trace("%s.%s::receive > Length of headers reponse %d", Toolkit.Net.__header,
             Toolkit.Net.__Http.__header, string.len(_rawHeader));
           __headers = Toolkit.Net.__readHeader(_rawHeader);
           for k, v in pairs(__headers) do
             --Toolkit.Net.__trace("raw #"..k..":"..v)
             if (string.find(string.lower( v or ""), "chunked")) then
               self.__isChunked = true;
               Toolkit.Net.__trace("%s.%s::receive > Transfer-Encoding: chunked",
                   Toolkit.Net.__header, Toolkit.Net.__Http.__header, string.len(result));
             end
           end
         end
         local _rBody = string.sub(result, _flag + 4);
         --Toolkit.Net.__trace("Length of body reponse: " .. string.len(_rBody));
         if (self.__isChunked) then
           response = Toolkit.Net.__decodeChunks(_rBody);
           err = 0;
         else
           response = _rBody;
           err = 0;
         end
       end
       -- return budy response
       return response, status, err;
     end),
     -- Toolkit.Net.HttpRequest.version()
     -- Return the version
     version = (function()
       return Toolkit.Net.__Http.__version;
     end),
     -- Toolkit.Net.HttpRequest:dispose()
     -- Try to free memory and resources
     dispose = (function(self)      
       if (self.__isConnected) then
           self.__tcpSocket:disconnect();
       end
       self.__tcpSocket = nil;
       self.__url = nil;
       self.__headers = nil;
       self.__body = nil;
       self.__method = nil;
       if pcall(function () assert(self.__tcpSocket~=Net.FTcpSocket) end) then
         Toolkit.Net.__trace("%s.%s::dispose > Successfully disposed",
           Toolkit.Net.__header, Toolkit.Net.__Http.__header);
       end
       -- make sure all free-able memory is freed
       collectgarbage("collect");
       Toolkit.Net.__trace("%s.%s::dispose > Total memory in use by Lua: %.2f Kbytes",
         Toolkit.Net.__header, Toolkit.Net.__Http.__header, collectgarbage("count"));
     end)
   },
   -- Toolkit.Net.isTraceEnabled
   -- true for activate trace in HC2 debug window
   isTraceEnabled = false,
   -- Toolkit.Net.HttpRequest(host, port)
   -- Give object instance for make http request
   -- host (string)    - host
   -- port (intager)    - port
   -- Return HttpRequest object
   HttpRequest = (function(host, port)
     assert(host~=Toolkit.Net, "Cannot call HttpRequest like that!");
     assert(host~=nil, "host invalid input");
     assert(port==nil or tonumber(port), "port invalid input");
     -- make sure all free-able memory is freed to help process
     collectgarbage("collect");
     Toolkit.Net.__host = host;
     Toolkit.Net.__port = port;
     local _c = Toolkit.Net.__Http;
     _c.__tcpSocket = Net.FTcpSocket(host, port);
     _c.__isConnected = true;
     Toolkit.Net.__trace("%s.%s > Total memory in use by Lua: %.2f Kbytes",
           Toolkit.Net.__header, Toolkit.Net.__Http.__header, collectgarbage("count"));
     Toolkit.Net.__trace("%s.%s > Create Session on port: %d, host: %s",
           Toolkit.Net.__header, Toolkit.Net.__Http.__header, port, host);
     return _c;
   end),
   -- Toolkit.Net.version()
   version = (function()
     return Toolkit.Net.__version;
   end)
 };

 Toolkit:traceEx("red", Toolkit.Net.__header.." loaded in memory...");
 -- benchmark code
 if (Toolkit.Debug) then Toolkit.Debug:benchmark(Toolkit.Net.__header.." lib", "elapsed time: %.3f cpu secs\n", "fragment", true); end;
 end;
 ----------------------------------------------------------------------------
 -- URL-encode a string (see RFC 2396)
 ----------------------------------------------------------------------------
 function urlencode(str)
   if (str) then
     str = string.gsub (str, "\n", "\r\n")
     str = string.gsub (str, "([^%w ])", function (c) return string.format ("%%%02X", string.byte(c)) end)
     str = string.gsub (str, " ", "+")
   end
   return str
 end
 -------------------------------------------------------------------------------------------
 -- Main process
 -------------------------------------------------------------------------------------------
 function SendVoice(message)
   local uri = "/app/gadaj.xhtml";
   local params = "?tekst=" .. urlencode(tostring(message or "empty"));
   Tk.Net.isTraceEnabled = false;
   local HttpClient = Tk.Net.HttpRequest(adres ip tabletu);
-- powyżej wpisujemy IP PAW serwera
   HttpClient:setReadTimeout(500);
   local response, status, errorCode = HttpClient:request("GET",
     uri..params, {
       "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:25.0) Gecko/20100101 Firefox/25.0",
       "Accept: text/html,application/xhtml+xml,application/xml;q=0.9"
     });
   HttpClient:disconnect();
   HttpClient:dispose();
   HttpClient = nil;
 end

 -- tu wpisujemy tekst do powiedzenia

SendVoice("");
fibaro:sleep(1000)
SendVoice("Uwaga ");
fibaro:sleep(1000)
SendVoice("Uwaga ");
fibaro:sleep(1000)
SendVoice("Uwaga ! ");
fibaro:sleep(1000)
SendVoice("Uwaga zalanie kuchni");
fibaro:sleep(4000)
SendVoice("Uwaga. zalanie kuchni");
fibaro:sleep(4000)
SendVoice("Zawór wody został zamknięty ");
fibaro:sleep(4000)
SendVoice("Prosze zakręcić główny zawór. Który znajduje sie za lodówką");
fibaro:sleep(10000)
SendVoice("Ostrożnie woda na podłodze w kuchni");

 


 --EOF

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×