Just a few notes....
$sunrise will always be less than $sunset so there is no need to test for this.
if ($now < $sunrise || $now > $sunset)
is all you need to get nighttime status (because just like the the first test - once it rolls over midnight, then $sunrise will be the time of the new day - it's always dark whenever $now < $sunrise or $now > $sunset)
Code: Select all
#!/usr/bin/php
<?php
function srss() {
$now = time();
$sunriset = date_sunrise($now, SUNFUNCS_RET_DOUBLE, 39, -104, 90, -7);
$sunsett = date_sunset($now, SUNFUNCS_RET_DOUBLE, 39, -104, 90, -7);
$t = explode(":",$sunriset);
$sunrise = mktime($t[0],$t[1]);
$t = explode(":",$sunsett);
$sunset = mktime($t[0],$t[1]);
if ($now > $sunrise && $now < $sunset) { return 1; }
else { return 0; }
}
function OnOff ($idx, $OO)
{
if (!srss())
{
$URL = "sg53:8080/json.htm?type=command¶m=switchlight&idx=$idx&switchcmd=$OO";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
}
}
#### main () ###
if (!isset($argv[1])) { exit; }
$OO = $argv[1];
OnOff (4, $OO); //front door
OnOff (5, $OO); //kitchen door
Converting the response of sunrise and sunset date funcs to unix timestamps makes them easier to work with - if you need to do anything more complicated in the future. As you can see to achieve this I just split the string using the ":" as the delimiter. As for the check to see what srss returns - if you are looking for it returning 1 (or true) then "if (srss()) { " is preferred - and for checking if it is false or 0 - then "if (!srss()) { "
Also I assigned time() to $now at the start of the function so that time() isn't called multiple times when calculating sunrise and sunset.
I added a quick check to make sure that $argv[1] actually contains something - otherwise since there is no check anywhere as to what $OO actually contains - you could be calling the script with no argument which will still attempt to connect to Domoticz but switchcmd will be empty.
Just some hints for the future
And thoughts for the further future -
I've replaced all this with MQTT - so instead of CURL connecting to the JSON domoticz endpoint - I would now just fire off 2 MQTT messages which Domoticz will receive and process.
{"command":"switchlight","idx":4,"switchcmd":"{$OO}"},{"command":"switchlight","idx":5,"switchcmd":"{$OO}"} published to "domoticz/in" would do the job - and while I could use phpMQTT to publish the messages - I tend to opt for executing mosquitto_pub.
Code: Select all
$t = "/usr/bin/mosquitto_pub -h $MQTT_BROKER -t \"{$MQTT_TOPIC}\" -u \"{$MQTT_USER}\" -P \"{$MQTT_PWD}\" -m \"{\\\"command\\\":\\\"switchlight\\\",\\\"idx\\\":{$idx},\\\"switchcmd\\\":\\\"{$OO}\\\"}\";
exec($t,$out);
AEOTEC ZStick, 11 ZWave Nodes, RFXCOMM, 50ish Byron Sockets.. HE851 (PIR), 2x HE852 (DoorContact)
WS2300, CM180, CC128, 2xTHGR122NX, 2xPiZeroW w/DS18B20, 8Ch 1W Relay Board.
8 Panasonic IP Cams, 1 16ch CCTV DVR + 15 CCTV Cams