Page 3 of 76

Re: LUA Pass2php

Posted: Tuesday 29 November 2016 23:51
by G3rard
Egregius wrote:Did you revert the lua script to the original os.execute?
That did the trick :oops: Reverted back to the os.execute and now it's working fine.
At least the other command showed me the dl error :mrgreen:

Re: LUA Pass2php

Posted: Wednesday 30 November 2016 6:25
by Egregius
That I don't understand because I get all output generated by the script directly in the domoticz logfile.
Example:

Code: Select all

2016-11-30 06:19:04.585  User: Admin initiated a switch command (162/brander/On)
2016-11-30 06:19:04.585  OpenZWave: Domoticz has send a Switch command! NodeID: 22 (0x16)
2016-11-30 06:19:04.585  (ZWAVE) Light/Switch (brander)
2016-11-30 06:19:00.538  --- SWITCH On brander dif = -0.8 in , was off for 1:56 
2016-11-30 06:19:04.584  --- SWITCH On brander dif = -0.8 in , was off for 1:56 repeat 
2016-11-30 06:19:14.506  (ZWAVE) Temp (badkamer_temp)
2016-11-30 06:19:14.861  (ZWAVE) Light/Switch (pirinkom)
2016-11-30 06:19:24.278  (ZWAVE) Temp (living_temp)
2016-11-30 06:19:25.500  (ZWAVE) Thermostat (livingZE)
2016-11-30 06:19:30.573  (ZWAVE) Light/Switch (pirliving)

Warning: file_get_contents(http://192.168.2.4/goform/formMainZone_MainZoneXml.xml?_=1480483126): failed to open stream: No route to host in /volume1/web/secure/pass2php.php on line 66

Warning: file_get_contents(http://192.168.2.4/MainZone/index.put.asp?cmd0=PutZone_OnOff%2FON&cmd1=aspMainZone_WebUpdateStatus%2F): failed to open stream: No route to host in /volume1/web/secure/pass2php.php on line 68

Warning: file_get_contents(http://192.168.2.4/MainZone/index.put.asp?cmd0=PutZone_InputFunction/TUNER): failed to open stream: No route to host in /volume1/web/secure/pass2php.php on line 69

Warning: file_get_contents(http://192.168.2.4/MainZone/index.put.asp?cmd0=PutZone_OnOff%2FON&cmd1=aspMainZone_WebUpdateStatus%2F&ZoneName=ZONE2): failed to open stream: No route to host in /volume1/web/secure/pass2php.php on line 70

Warning: file_get_contents(http://192.168.2.4/goform/formMainZone_MainZoneXml.xml?_=1480483139): failed to open stream: No route to host in /volume1/web/secure/pass2php.php on line 66

Warning: file_get_contents(http://192.168.2.4/MainZone/index.put.asp?cmd0=PutZone_OnOff%2FON&cmd1=aspMainZone_WebUpdateStatus%2F): failed to open stream: No route to host in /volume1/web/secure/pass2php.php on line 68

Warning: file_get_contents(http://192.168.2.4/MainZone/index.put.asp?cmd0=PutZone_InputFunction/TUNER): failed to open stream: Connection refused in /volume1/web/secure/pass2php.php on line 69

Warning: file_get_contents(http://192.168.2.4/MainZone/index.put.asp?cmd0=PutZone_OnOff%2FON&cmd1=aspMainZone_WebUpdateStatus%2F&ZoneName=ZONE2): failed to open stream: HTTP request failed!  in /volume1/web/secure/pass2php.php on line 70
2016-11-30 06:19:42.686  (ZWAVE) Light/Switch (pirliving)
2016-11-30 06:19:46.452  (ZWAVE) Temp (zolder_temp)
2016-11-30 06:19:54.609  (ZWAVE) Temp (badkamer_temp)
2016-11-30 06:20:13.850  (ZWAVE) Light/Switch (pirliving)
2016-11-30 06:20:14.655  (ZWAVE) Temp (badkamer_temp)
2016-11-30 06:20:22.630  (ZWAVE) Thermostat (alexZ)
2016-11-30 06:20:29.864  (ZWAVE) Thermostat (livingZZ)
2016-11-30 06:20:34.687  (ZWAVE) Temp (badkamer_temp)
2016-11-30 06:20:43.773  (ZWAVE) Light/Switch (pirliving)
2016-11-30 06:20:54.726  (ZWAVE) Temp (badkamer_temp)
2016-11-30 06:21:00.575	wunderground -5.0	-4.6	1.0 1.9 Newtemp=-4.2
2016-11-30 06:21:04.746  (ZWAVE) Temp (badkamer_temp)
2016-11-30 06:21:18.377  (ZWAVE) Light/Switch (pirkeuken)
Don't know, but could this work?

Code: Select all

os.execute('curl -s --data "c='..c..'&s='..s..'&i='..i..'&t='..t..'" http://127.0.0.1/secure/pass2php.php >> /var/log/pass2php.log &')

Re: LUA Pass2php

Posted: Wednesday 30 November 2016 8:35
by Egregius
I posted my latest stuff about this.

the lg($msg) function will add the message to the domoticz logfile in realtime. Before all output was only recorded at the end of the script.

https://egregius.be/2016/lua-pass2php-v ... ete-script
https://egregius.be/2016/lua-pass2php-v ... mal-script

Re: LUA Pass2php

Posted: Wednesday 30 November 2016 11:25
by Westcott
Hi Egregius,
Does pass2php.php get executed for every Domoticz device change?
Or does it run continuously?

Re: LUA Pass2php

Posted: Wednesday 30 November 2016 11:50
by Egregius
All script_device_xxx.lua files are executed upon every device change, so also script_device_pass2php.lua

In the php file you create the events array to handle individual parts of the script. This is done by naming the IDX that triggered the script. Ex 123 => 'PIRkitchen'
123 is then the IDX of your PIR
PIRkitchen is the name of the function in the script.

Code: Select all

$events=array(266=>'pirliving',268=>'pirliving',272=>'pirkeuken',276=>'pirgarage',280=>'pirinkom',284=>'pirhall'); 

$a = status of triggered device
$s = array of all statusses
$i = array of all IDXs
$t = array of all last update times

Code: Select all

function PIRkitchen(){
  global $a,$s,$i,$t;
  if($a=='On'){
    //do your stuff
    sw($i['LightKitchen'],'On');
  }
}
While typing this I came to the conclusion that using the IDX is maybe not the best way.
There's also a $c array (equals devicechanged in lua).

Code: Select all

Array
(
    [living_temp] => 20.7
    [living_temp_Temperature] => 20.700000762939
)
I'll see to alter my code so that functions are called more easily ;)

Re: LUA Pass2php

Posted: Wednesday 30 November 2016 13:28
by Westcott
Hi Egregius,
Thanks for the explanation, but does pass2php.php itself get executed for each Lua call?

Re: LUA Pass2php

Posted: Wednesday 30 November 2016 13:51
by Egregius
Yes

Re: LUA Pass2php

Posted: Wednesday 30 November 2016 14:43
by Westcott
Thanks!
I was thinking (dangerous) -
If pass2php.php ran continuously, and had a listener for Lua event data, then it could hold any state data as well?

Re: LUA Pass2php

Posted: Wednesday 30 November 2016 14:59
by Sneezydevil
I use pass2php with memcached to hold some states. I am pretty sure Egregius uses memcached aswell but did not dive into his code to check what for.

Re: LUA Pass2php

Posted: Wednesday 30 November 2016 15:15
by Egregius
Westcott wrote:and had a listener for Lua event data, then it could hold any state data as well?
Don't understand what you mean by this exactly.
The LUA tables devicechanged, otherdevices, otherdevices_idx and otherdevices_lastupdate are encoded and sent to pass2php.
All the data of those tables is available while executing the script in the arrays $a,$s,$i and $t.

Indeed, I also use memcached to store temp variables.
I once did a test and that seems the fastest solution. Faster than file based cache, MySQL or Domoticz uservariables.
I'm addicted to speed, I want the system to respond as fast as possible.
I'm now looking to speed up the json and base64 encoding.
Tests showed that it takes 4msec to load those 2 library's and another 12msec to encode.
So there's a possibility to substract 16msec of the 42msec of reaction time I know have.

Btw: the code is ready to be used just on devicename instead of idx. Even more easier to use.
The top of pass2php looks like this:

Code: Select all

error_reporting(E_ALL);
ini_set("display_errors","on");
date_default_timezone_set('Europe/Brussels');
define('time',$_SERVER['REQUEST_TIME']);
$c=json_decode(base64_decode($_REQUEST['c']),true);
$s=json_decode(base64_decode($_REQUEST['s']),true);
$i=json_decode(base64_decode($_REQUEST['i']),true);
$t=json_decode(base64_decode($_REQUEST['t']),true);
if(function_exists(key($c)))key($c)();
//START USERFUNCTIONS
function devicename(){
  if($s['devicename']=='On')sw($i['light'],'On');
}
 
If you have several devices that needs to trigger the same function it can easily be done by calling the function from within the other one:

Code: Select all

function alex_set(){verwarming();}
function alex_temp(){verwarming();}
function kamer_set(){verwarming();}
function kamer_temp(){verwarming();}
function living_set(){verwarming();}
function living_temp(){verwarming();}
function tobi_set(){verwarming();}
function tobi_temp(){verwarming();}

function verwarming(){
  //.....
}
 
So the the 8 devices all call the same function ('verwarming' is Dutch for 'Heating').

Re: LUA Pass2php

Posted: Wednesday 30 November 2016 22:57
by G3rard
Egregius wrote:That I don't understand because I get all output generated by the script directly in the domoticz logfile.
I just didn't got the DL error message in the log, other messages are written to the log, so that's working fine.
I am now using your 2.1 script and that's working fine, even the CURL function ;)

And indeed it's pretty fast :mrgreen:

Code: Select all

2016-11-30 22:51:24.592 User: Admin initiated a switch command
2016-11-30 22:51:24.592 Dummy: Lighting 1 | Test_switch 
2016-11-30 22:51:24.649 => SWITCH On 1
2016-11-30 22:51:24.649 User: Admin initiated a switch command
2016-11-30 22:51:24.649 RFXCOM: Lighting 2 | Ledlampen zolder 

Re: LUA Pass2php

Posted: Tuesday 06 December 2016 6:07
by Egregius
Published a new update wich is even easier to use. No more IDX to function name needed. If a function with the name of the updated device exists it's executed :)

https://egregius.be/2016/lua-pass2php-v ... te-script/
https://egregius.be/2016/lua-pass2php-v ... al-script/

Re: LUA Pass2php

Posted: Tuesday 06 December 2016 18:05
by sincze
A well I am no PHP wizard so just a question..

Can I use this as well with comands lijke "ON FOR X".. like 'On FOR 10'. as described here https://www.domoticz.com/wiki/Events

Or can we have PHP deal with the timing and just switch ON, OFF the devices.

Example:
It is dark.
The doorbell rings.
Doorbell executes the frontdoor light on for 3 minutes.
Doorbell executes a IP snapshot -> telegram
Doorbell executes KODI plugin to send live feed of people in front of the door to all ACTIVE KODI machines.

It is especially the on for 3 minutes I use a lot.
I open a door... lights on for 30 seconds..
I close the door.. and light goes out after the 30 seconds. Just to avoid on,off,on,off when people entering the kitchen opening and closing the door :D

Again I would be pleased to integrate this in my domoticz, however I'm not a PHP expert.

Re: LUA Pass2php

Posted: Tuesday 06 December 2016 18:21
by Egregius
No, ON FOR X doesn't work.
But that shouldn't be a problem ;)
My script is also executed every minute by updating a virtual sun sensor. At night I just update it every minute with a value of 0.
The function zon() of https://github.com/Egregius/PHP-Custom- ... ss2php.php handles all stuff that needs to run regurarly.
For example:

Code: Select all

if(strtotime($t['pirkeuken'])<time-118&&strtotime($t['wasbak'])<time-118&&$s['pirkeuken']=='Off'&&$s['wasbak']=='On'&&$s['werkblad']=='Off'&&$s['keuken']=='Off'&&$s['kookplaat']=='Off')
            sw($i['wasbak'],'Off');
 
Simplified for one pir and light this could be:

Code: Select all

if(strtotime($t['pirkeuken'])<time-118&&$s['wasbak']=='On')
            sw($i['wasbak'],'Off');
 
See the github link for more examples. You can go as advanced (or simple) in it as you like.
To explain the first code: I want my lights in the kitchen to stay on as soon as one of the other kitchen lights are on. After all lights are off and there's no motion for 118 seconds that light also switches off.

And to complete, this is my doorbell code:

Code: Select all

function belknop()
{
    global $s,$i;
    if($s['belknop']=="On"&&$s['meldingen']=='On')
    {
        if(cget('timetelegramdeurbel')<time-57)
        {
            cset('timetelegramdeurbel',time);
            if($s['weg']=='Off'&&$s['slapen']=='Off')
                sw($i['deurbel'],'On','deurbel');
            if($s['slapen']=='Off')
            {
                telegram('Deurbel',false,'Kirby');
                ios('Deurbel');
            }
            else 
                telegram('Deurbel',true,'Kirby');
            $ctx=stream_context_create(array('http'=>array('timeout'=>3)));
            file_get_contents('http://192.168.2.11/telegram.php?snapshot=true',false,$ctx);
            file_get_contents('http://192.168.2.11/fifo_command.php?cmd=record%20on%205%2055',false,$ctx);
            if($s['zon']<=10)
                sw($i['voordeur'],'On');
        }
    }
}
If someone rings the doorbell and the virtual switch notifications (meldingen in Dutch) is on we continue.
If that press is more than one minute ago and we're a sleep a telegram is sent without sound. If we're not a sleep a telegram is sent with sound and also a iOS notification is sent.
The doorbell itself is only activated when we're not a sleep and at home.
In each case the pikrellcam soft of the camera is triggered to sent a snapshot and record a movie.
If the sun power is less than 10W the light is switched on.

Re: LUA Pass2php

Posted: Tuesday 06 December 2016 18:33
by Egregius
Oh, forgot to mention:
My way is better than ON FOR X :P
On for X WILL switch off the switch after that time, no mather what.
My way has the possibility to check multiple stuff before switching of.

Re: LUA Pass2php

Posted: Tuesday 06 December 2016 22:50
by sincze
Egregius wrote:Oh, forgot to mention:
My way is better than ON FOR X :P
On for X WILL switch off the switch after that time, no mather what.
My way has the possibility to check multiple stuff before switching of.
:D
Nice , started with it today.

Code: Select all

sudo apt-get install php5 
sudo apt-get install php5-cli
I already had JSON.lua (VERSION = 20160916.19) and ee5_baste64.lua in my directory.

within /domoticz/scripts/lua created file script_device_pass2php.lua

Code: Select all

JSON=loadfile('/home/linaro/domoticz/scripts/lua/JSON.lua')()
base64=loadfile('/home/linaro/domoticz/scripts/lua/ee5_base64.lua')()
changed=base64.encode(JSON:encode(devicechanged))
devices=base64.encode(JSON:encode(otherdevices))
idx=base64.encode(JSON:encode(otherdevices_idx))
lastupdate=base64.encode(JSON:encode(otherdevices_lastupdate))
os.execute( '/home/linaro/domoticz/scripts/php/pass2php.php "'..changed..'" "'..devices..'" "'..idx..'" "'..lastupdate..'" &')
commandArray = {}
return commandArray
If I put an error in this one... domoticz log will go crazy so it is reading this file correctly.
Within my domoticz/scripts I created a directory php
Within that directory I created the file: pass2php.php based upon: https://egregius.be/2016/lua-pass2php-v ... al-script/

Code: Select all

#!/usr/bin/php
<?php
$c=json_decode(base64_decode($_REQUEST['c']),true);
$s=json_decode(base64_decode($_REQUEST['s']),true);
$i=json_decode(base64_decode($_REQUEST['i']),true);
$t=json_decode(base64_decode($_REQUEST['t']),true);
$a=$s[key($c)];$devidx=$i[key($c)];

$events=array(
226=>'motion_keuken',
672=>'motion_trap_boven',
524=>'motion_trap',
366=>'motion_kastenkamer'
);

if(isset($events[$devidx]))$events[$devidx]();
//START USERFUNCTIONS

function motion_kastenkamer(){
        global $a,$s,$i,$t;
        if($a=="On"){
//      sw($i['Lamp (Kastenkamer)'],'On');
                sw(62,'On');    // 62 = Lamp Kastenkamer
                }
        }



//END USERFUNCTIONS. Only change IP:PORT and ios,sms account details below
function sw($idx,$action="",$info="",$Usleep=600000){lg("SWITCH ".$action." ".$info);if(empty($action))curl("http://192.168.2.10:8080/json.htm?type=command&param=switchlight&idx=".$idx."&switchcmd=Toggle");else curl("http://192.168.2.10:8080/json.htm?type=command&param=switchlight&idx=".$idx."&switchcmd=".$action);usleep($Usleep);}

function sl($idx,$level,$info="",$Usleep=600000){lg("SETLEVEL ".$level." ".$info);curl("http://192.168.2.10:8080/json.htm?type=command&param=switchlight&idx=".$idx."&switchcmd=Set%20Level&level=".$level);usleep($Usleep);}

function ud($idx,$nvalue,$svalue,$info="",$Usleep=600000){if(!in_array($idx, array(395,532,534)))lg("UPDATE ".$nvalue." ".$svalue." ".$info);curl('http://192.168.2.10:8080/json.htm?type=command&param=udevice&idx='.$idx.'&nvalue='.$nvalue.'&svalue='.$svalue);usleep($Usleep);}

function double($idx,$action,$comment='',$wait=4000000){sw($idx,$action,$comment,$wait);sw($idx,$action,$comment.' repeat',0);}
function lg($msg){curl('http://192.168.2.10:8080/json.htm?type=command&param=addlogmessage&message='.urlencode('=> '.$msg));}
function curl($url){$headers=array('Content-Type: application/json');$ch=curl_init();curl_setopt($ch,CURLOPT_URL,$url);curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);curl_setopt($ch,CURLOPT_FRESH_CONNECT,TRUE);curl_setopt($ch,CURLOPT_TIMEOUT,5);$data=curl_exec($ch);curl_close($ch);return $data;}
All functions are in the script on 1 line (no carrier returns)

It seems I was not allowed to use 127.0.0.1 (not authorized)... So changed it to actual IP of Domoticz machine.
Tested that by manually executing curl ,,, and the switch command as described in domoticz json event wiki. :D

The idea... if 366=>'motion_kastenkamer' is triggered... it should switch on the light idx=62

Code: Select all

sw(62,'On');    // 62 = Lamp Kastenkamer
However for some reason that does not happen. I don't see anything in the log.
Did not see where this went wrong. Unfortunately.

Re: LUA Pass2php

Posted: Tuesday 06 December 2016 23:21
by Egregius
Try the newest version 2.2.
Then you don't need the array anymore.
Your function name is the trigger then. That has to be exactly as the device that triggers the event.
So in your case motion_kastenkamer
Don't know about the ( and ) in the name, not sure if php accepts that as a variable name.
For debugging, add some print statements, or if you have version 2.2 you can use the lg function to log to domoticz.

Code: Select all

<?php
error_reporting(E_ALL);
ini_set("display_errors","on");
date_default_timezone_set('Europe/Brussels');
define('time',$_SERVER['REQUEST_TIME']);
$c=json_decode(base64_decode($_REQUEST['c']),true);
$s=json_decode(base64_decode($_REQUEST['s']),true);
$i=json_decode(base64_decode($_REQUEST['i']),true);
$t=json_decode(base64_decode($_REQUEST['t']),true);
$r=str_replace(" ","_",key($c));
lg('Pass2PHP triggered by '.key($c));
if(function_exists(key($c)))
    key($c)();
elseif(function_exists($r))
    $r();

//START USER FUNCTIONS
function motion_kastenkamer()
{
    lg('Executing function motion_kastenkamer');
    global $s,$i,$t;
    if($s['motion_kastenkamer'=="On")
    {
            sw(62,'On');
    }
}
 
All lg or print statements should come in the Domoticz log. Use tail -f domoticz.log to see it in realtime.

Re: RE: Re: LUA Pass2php

Posted: Tuesday 06 December 2016 23:54
by sincze
Egregius wrote:Try the newest version 2.2.
Then you don't need the array anymore.
Your function name is the trigger then. That has to be exactly as the device that triggers the event.
So in your case motion_kastenkamer
Don't know about the ( and ) in the name, not sure if php accepts that as a variable name.
For debugging, add some print statements, or if you have version 2.2 you can use the lg function to log to domoticz.

Code: Select all

<?php
error_reporting(E_ALL);
ini_set("display_errors","on");
date_default_timezone_set('Europe/Brussels');
define('time',$_SERVER['REQUEST_TIME']);
$c=json_decode(base64_decode($_REQUEST['c']),true);
$s=json_decode(base64_decode($_REQUEST['s']),true);
$i=json_decode(base64_decode($_REQUEST['i']),true);
$t=json_decode(base64_decode($_REQUEST['t']),true);
$r=str_replace(" ","_",key($c));
lg('Pass2PHP triggered by '.key($c));
if(function_exists(key($c)))
    key($c)();
elseif(function_exists($r))
    $r();

//START USER FUNCTIONS
function motion_kastenkamer()
{
    lg('Executing function motion_kastenkamer');
    global $s,$i,$t;
    if($s['motion_kastenkamer'=="On")
    {
            sw(62,'On');
    }
}
All lg or print statements should come in the Domoticz log. Use tail -f domoticz.log to see it in realtime.
Will post results tomorrow :) Tnx already for your help. I want 40ms responsiveness too!

Sent from my SM-G925F using Tapatalk

Re: LUA Pass2php

Posted: Wednesday 07 December 2016 0:21
by lvsigo
For Speedup you may try full lua version.
Very easy to use

http://www.domoticz.com/forum/viewtopic ... 86#p105886

Re: LUA Pass2php

Posted: Wednesday 07 December 2016 5:18
by Egregius
For me it's not only the speed up of my script, it's the freedom of using a well documented code.
Just for the fun, type in Google lua and php and see the difference.
129000000 vs 10930000000 results!
When I started with Domoticz I googled a lot for lua but found that the userbase is so small and specific that it wasn't easy. PHP on the other hand has such a great userbase that for every issue you have already tons of people posted about it.
Plus, I've seen stuff here in lua of wich I think WTF, really?