php // Checks to see if a delimited data file is changing or not (flatlined) // Requires that a text file named flatline-status.txt be on the server with write permissions (CHMOD 666) // Include this in a page where you want the message to show up if the data is flatlined // If flatlined an EMail can be sent // 1-4-09 // 5-9-12 - Updated to PHP 5 timezone function // 3-8-19 - Fixed some date() issues & removed the mail test variable // Jim McMurry - jcweather.us - jmcmurry@mwt.net // // Configuration date_default_timezone_set("America/Chicago"); // Zones available at http://us2.php.net/manual/en/timezones.php $cachefile = 'flatline-status.txt'; // File to hold cached data for comparison $watchfile = './clientraw.txt'; // Data file to watch for changes $delimit = " "; // Delimeter used in that file $offset1 = 4; // Temp $offset2 = 5; // Humidity $offset3 = 6; // Baro $offset4 = 1; // Wind Ave Speed $offset5 = 72; // DP $maxage = 30; // Minutes that the data can remain unchanged w/o email. Recommend minimum 30 $to = 'Your Email'; // EMail info $from = 'jcweather.us'; $subject = 'Weather Data Appears Flatlined.'; $subject2 = 'Weather Data Back Online.'; $body = ' now. Last data change recorded at '; // Will go between current date/time & last good date/time in the EMail Body. $HTMLMsg = '<div style="text-align:center;">Sorry, Weather Station Data Has Been Disrupted ... Notification Has Been Sent.</div>'; // End of configurable items $now = time(); $newdata = get_contents( $watchfile , $delimit); // read the target file $current = " (" . $newdata[$offset1] . " " . $newdata[$offset2] . " " . $newdata[$offset3] . " " . $newdata[$offset4] . " " . $newdata[$offset5] . ")"; $cachedata = get_contents( $cachefile , ","); // read the cache file $cachetime = $cachedata[0]; if ($newdata[0] != -9999 && $cachedata[0] != -9999) { // was able to read the files $flat = ($newdata[$offset1] == $cachedata[1]) && ($newdata[$offset2] == $cachedata[2]) && ($newdata[$offset3] == $cachedata[3]) && ($newdata[$offset4] == $cachedata[4]) && ($newdata[$offset5] == $cachedata[5]); // compare various offsets $status = substr(trim($cachedata[6]), 0, 4); // capture the "sent" if it's already there $WatchSpan = round(($now - $cachetime) / 60); // minutes since last data change if ($flat) { if ($WatchSpan >= $maxage) { // wait time is expired if ( $status != "sent" ) { // mail hasn't been sent yet mail($to, $subject , date("m-d-y H:i") . $body . date( "m-d-y H:i", $cachetime) . $current, 'From: ' . $from); $status ="sent " . date("m-d-y H:i", $now); } else { $status = trim($cachedata[6]); // carry over the original entry } echo $HTMLMsg; // put the message on the screen } else { $status="watching from " . date("g:i a", $cachetime) . ", now " . date("g:i a", $now) . ", static for " . $WatchSpan . " min"; } $now = $cachetime; // leave timestamp as it was for now } else { if ( $status == "sent" ) { // mail previously sent mail($to, $subject2 ,"Back active at " . date("m-d-y g:i a") . $current, 'From: ' . $from); } $status="active " . date("m-d-y g:i a", $now); } $fp = fopen($cachefile, "w") or die("HINT: Manually upload a file named " . $cachefile . " and give it write permissions (CHMOD 666)."); fputs($fp, $now . "," . $newdata[$offset1] . "," . $newdata[$offset2] . "," . $newdata[$offset3] . "," . $newdata[$offset4] . "," . $newdata[$offset5] . ", " . $status); fclose($fp); } // else we couldn't read one of the files function get_contents( $rawfile , $delimiter) { $rawdata = array(); $fd = fopen($rawfile, "r"); if ($fd) { $rawinfo = ''; while (! feof ($fd) ) { $rawinfo .= fread($fd, 8192); } fclose($fd); $rawinfo = preg_replace("/\x0D/", "", $rawinfo); $rawinfo = preg_replace("/\x0A/", "", $rawinfo); $rawdata = explode ($delimiter, $rawinfo); } else { $rawdata[0]= -9999; } return $rawdata; } ?> |
///////////Configuracion/////////////////////
$realtimefile = '/var/www/html/CumulusMX/realtime.txt';
$realtimecachefile = '/var/www/html/CumulusMX/realtimecache.txt';
$umbraltormenta = 4; //umbral en mm sobre el cual se considera tormenta
$tiempocomprobacion = 10; //minutos para la comprobación de la tormenta
$tiemporeanudacion = 120; //minutos comprobacion de reanudacion de lluvia
$direccionaenviar = '';
$test = false; //true, probar correo. false, no probar
/////////////////////////////////////////////
Mil gracias!!
Lo que si soy incapaz de ejecutar los php desde cron
si ejecuto crontab -e
al final tengo
/*2 * * * * php /var/www/html/webtest/alertalluvia.php
/*2 * * * * php /var/www/html/webtest/alertarealtime.php
Luego hago service cron restart
Veamos ya conseguir ejecutar el php desde cron. Eso sí solo el que tú me hiciste. El que postee aqui no. Si lo ejecutó mano si va. No lo entiendo, pero ya lo investigaré.
Sobre el script, usando el valor 9 de realtime. Cada vez que esté se modifica me envía un email. Sin querer darte más trabajo. Quizás lo ideal sería usando el valor 8 (intensidad). Si la intensidad se modifica que envíe el email (está lloviendo), si se ejecuta el cron cada 10 minutos que haya otro valor donde indicarle el tiempo a ignorarlo para que no envie el email.. Por ejemplo cada 6 horas.
No se si me explique...
root@meteoviso:~# sudo dpkg -l | grep php
ii libapache2-mod-php 2:7.4+75 all server-side, HTML-embedded scripting language (Apache 2 module) (default)
ii libapache2-mod-php7.4 7.4.3-4ubuntu2.4 amd64 server-side, HTML-embedded scripting language (Apache 2 module)
ii php 2:7.4+75 all server-side, HTML-embedded scripting language (default)
ii php-auth-sasl 1.0.6-3 all Abstraction of various SASL mechanism responses
ii php-cli 2:7.4+75 all command-line interpreter for the PHP scripting language (default)
ii php-common 2:75 all Common files for PHP packages
ii php-curl 2:7.4+75 all CURL module for PHP [default]
ii php-gd 2:7.4+75 all GD module for PHP [default]
ii php-mail 1.4.1-1 all Class that provides multiple interfaces for sending emails
ii php-net-smtp 1.9.0-1 all PHP PEAR module implementing SMTP protocol
ii php-net-socket 1.0.14-2 all Network Socket Interface
ii php-pear 1:1.10.9+submodules+notgz-1ubuntu0.20.04.2 all PEAR Base System
ii php-xml 2:7.4+75 all DOM, SimpleXML, WDDX, XML, and XSL module for PHP [default]
ii php7.4 7.4.3-4ubuntu2.4 all server-side, HTML-embedded scripting language (metapackage)
ii php7.4-cli 7.4.3-4ubuntu2.4 amd64 command-line interpreter for the PHP scripting language
ii php7.4-common 7.4.3-4ubuntu2.4 amd64 documentation, examples and common module for PHP
ii php7.4-curl 7.4.3-4ubuntu2.4 amd64 CURL module for PHP
ii php7.4-gd 7.4.3-4ubuntu2.4 amd64 GD module for PHP
ii php7.4-json 7.4.3-4ubuntu2.4 amd64 JSON module for PHP
ii php7.4-opcache 7.4.3-4ubuntu2.4 amd64 Zend OpCache module for PHP
ii php7.4-readline 7.4.3-4ubuntu2.4 amd64 readline module for PHP
ii php7.4-xml 7.4.3-4ubuntu2.4 amd64 DOM, SimpleXML, XML, and XSL module for PHP
root@meteoviso:~#
A mi, activar cualquier mailer me da un miedo atroz. Sobre todo Sendmail, que siempre se ha caracterizado por ser un agujero de seguridad.
Os sugiero usar la mensajería de Telegram
extremely simple MTA to get mail off the system to a mail hub
A secure, effective and simple way of getting mail off a system to your
mail hub. It contains no suid-binaries or other dangerous things - no mail
spool to poke around in, and no daemons running in the background. Mail is
simply forwarded to the configured mailhost. Extremely easy configuration.
.
WARNING: the above is all it does; it does not receive mail, expand aliases
or manage a queue. That belongs on a mail hub with a system administrator.
php -a es para ejecutar comandos de php en la línea de comandos.
Que no vaya en el crontab es raro. Prueba a poner */10 * * * * /usr/bin/php /var/www/html/webtest/alertalluvia.php
Como consejo.
A mi, activar cualquier mailer me da un miedo atroz. Sobre todo Sendmail, que siempre se ha caracterizado por ser un agujero de seguridad.
Os sugiero usar la mensajería de Telegram
Ya hace tiempo, en el subforo de weewx puse las instrucciones.
Yo lo tengo programado para que cada vez que mi Orange Pi o mi Raspberry Pi se reinicien, me manden un mensaje. La Orange se reinicia todos los días, y la Raspi solo cuando se necesita.
if (!file_exists($realtimecachefile)) file_put_contents($realtimecachefile, $fechar.','.$lluvia);
$realtimecache = explode(',', file_get_contents($realtimecachefile));
$flaglluviacache = 0;
if (substr($realtimecache[0],0,2) != $fecha[0]) {file_put_contents($realtimecachefile, $fechar.',0.0'); $flaglluviacache = 1;}
$fecha = strtotime($fechar);
$fechacache = strtotime($realtimecache[0]);
$lluviacache = $realtimecache[1];
if ($flaglluviacache) $lluviacache = "0.0";
$diff = $fecha - $fechacache;
$difflluvia = $lluvia - $lluviacache;
Como consejo.
A mi, activar cualquier mailer me da un miedo atroz. Sobre todo Sendmail, que siempre se ha caracterizado por ser un agujero de seguridad.
Os sugiero usar la mensajería de Telegram
Ya hace tiempo, en el subforo de weewx puse las instrucciones.
Yo lo tengo programado para que cada vez que mi Orange Pi o mi Raspberry Pi se reinicien, me manden un mensaje. La Orange se reinicia todos los días, y la Raspi solo cuando se necesita.
Ese certificado (el del SSL de Telegram) no lo reconoce PHP así que lo tira para atrás. Tendrías que ponerle un certificado válido a PHP. Me encontré eso esta mañana. Cogí y puse la última versión de PHP. Problema solucionado. La mayoría de veces se emiten nuevos certificados y si PHP es algo antiguo y también su cacert.pem te sale ese error.
Si quieres probarlo pasando ese error pon lo siguiente:
$opciones = [
"ssl" => [
"verify_peer"=>false,
"verify_peer_name"=>false,
]
];
file_get_contents('https://api.telegram.org/botXxxxxxxxxxx/sendMessage?chat_id=yyyyyyy&text=Prueba', false, stream_context_create($opciones));
*+* *+* *+* *+*Actualizado y ya funciona a pelo sin añadir nada plau2
Yo PHP lo tengo siempre a la última versión en mis dispositivos en Linux con el repositorio de https://deb.sury.org/
sudo apt -y install apt-transport-https lsb-release ca-certificates curl
sudo wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg
sudo sh -c 'echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list'
sudo apt update
Con esas líneas se instalan paquetes necesarios, la clave, el repositorio y se actualiza. Luego si se instala un nuevo PHP con sudo apt upgrade se reinicia apache2 con sudo service apache2 restart