Archived
1
0

initial commit

This commit is contained in:
daniel Tartavel 2022-01-10 10:42:32 +01:00
parent 4bbf780d29
commit 534174fe13
3 changed files with 313 additions and 0 deletions

137
mqtt_functions.php Normal file
View File

@ -0,0 +1,137 @@
<?php
require "utils.php";
$mids = array();
$client = new Mosquitto\Client();
// log levels
define( "DEBUG", $client::LOG_DEBUG); // => 16
define( "INFO", $client::LOG_INFO); // => 1
define( "NOTICE", $client::LOG_NOTICE); // => 2
define( "WARNING", $client::LOG_WARNING); // => 4
define( "ERROR", $client::LOG_ERR); // => 8
define( "ALERT", 32);
define( "ALL", DEBUG | INFO | NOTICE | WARNING | ERROR | ALERT);
$logLevel = INFO | WARNING | ERROR | ALERT;
//$notificationLevel = WARNING | ERROR; // TODO send notification
logger(DEBUG, _("defining callback functions"));
// defining callback functions
$client->onConnect('connectResponse');
$client->onDisconnect('disconnectResponse');
$client->onSubscribe('subscribeResponse');
$client->onUnsubscribe('unsubscribeResponse');
$client->onMessage('messageReceived');
$client->onLog('logger');
$client->onPublish('publishResponse');
logger(DEBUG, _("connecting to mqtt server"));
$client->connect($mqttServerAddress, $mqttServerPort, 30);
logger(DEBUG, _("subscribing"));
$mid = $client->subscribe($topicName . "/#", 2);
function messageReceived($message)
{
global $topicName, $logFh;
$topic = explode ("/", $message->topic);
if($topic[array_key_last($topic)] != "get" and ($topic[array_key_last($topic)]) != "set")
{
$topic = explode ("/", $message->topic, 2); // get topic name
$fnTree = explode ("/" , $topic[1]); // get friendlyname
echo $topic[0] . " => " . $topic[1] . EOL;
logger(INFO, print_r(json_decode($message->payload), true));
}
}
// payload is an array :
// $key is property => $value is value of the parameter
function publish($payload, $commande="")
{
global $mids, $friendlyName, $topicName, $client, $logFh;
//print_r($payload);
$string = $topicName . "/" . $friendlyName;
$mid = $client->publish($string, $payload , 2);
if (isset($mids[$mid]))
{
//echo "unsetting mids" .EOL;
unset ($mids[$mid]);
}else
{
//echo "setting mids" .EOL;
$mids[$mid] = true;
}
logger(LOG_INFO, $logFh, "Publishing " . $string . " with payload => " . $payload);
}
function connectResponse($r, $message)
{
global $connected;
echo sprintf(_("I got code %d and message : '%s'"), $r, $message) . EOL;
switch ($r)
{
case 0:
logger(INFO, _("Successfull connection"));
$connected = true;
break;
case 1:
logger(INFO, _("Connection refused : unacceptable protocol version"));
$connected = false;
break;
case 2:
logger(INFO, _("Connection refused : identifier rejected"));
$connected = false;
break;
case 3:
logger(INFO, _("Connection refused (broker unavailable )"));
$connected = false;
break;
}
return $connected;
}
function subscribeResponse($mid, $qosCount)
{
global $topics;
logger(INFO, _("Subscribed"));
}
function unsubscribeResponse($mid)
{
global $client;
logger(INFO, _("Unsubscribed"));
$client->disconnect();
}
function disconnectResponse($r)
{
global $connected;
if ($r != 0)
{
$str = _('Badly ');
}else
{
$str = _('Cleanly ');
}
logger(INFO, $str . _("disconnected from server"));
$connected = false;
}
function publishResponse($mid)
{
global $mids, $events;
logger(LOG_INFO, "Event with mid = " . $mid . " published by MQTT broker");
if (isset($mids[$mid]))
{
//echo "unsetting mids" . EOL;
unset ($mids[$mid]);
//print_r($mids);
}else
{
//echo "setting mids" . EOL;
$mids[$mid] = true;
}
}
?>

93
pws2mqtt.php Normal file
View File

@ -0,0 +1,93 @@
<?php
declare(ticks = 1);
$ProcName = "pws2mqtt"; // name of the proceesus in ps, top, pstree, ...;
$topicName = "pws2mqtt"; // name of the topic in mqtt
$friendlyName = "WH2650A"; // friendly name of the device in mqtt
$macAddress = "0x483fda53cbcb"; // lan mac address as lan identity TODO get from device
$type = "Meteo";
$connected = false; // connected to mqtt server true/false
$logFh = null; // filehandle of log file
$configDir = "./config"; // path of the config file TODO change to /etc
$mqttServerAddress = "127.0.0.1";
$mqttServerPort = "1883";
$listenHost = "0.0.0.0";
$listenPort = 5000;
require "mqtt_functions.php";
logger(DEBUG, _("local pws server init ( no nblocking)"));
// server init: No Timeout
set_time_limit(0);
ob_implicit_flush();
$error_message = null;
$error_code = null;
$socket = stream_socket_server("tcp://" . $listenHost . ":" . $listenPort, $error_code, $error_message) or logger(ERROR, _("Could not create socket") . EOL);
stream_set_blocking($socket, false);
logger(DEBUG, _("looping"));
while(1)
{
$read = array( $socket );
$array = array();
$ipAddress = null;
$ipPort = null;
if ( stream_select( $read, $array, $array, 0 ))
{
logger(DEBUG,_("socket ready to read"));
$spawn = stream_socket_accept($socket);
if ($spawn !== false)
{
logger(DEBUG,_("socket accepted"));
$input = stream_get_line($spawn, 4096,"");
logger(DEBUG, $input);
if (!empty($input))
{
$input = substr($input,6);
$input = explode(" ", $input); // suppress text
$array = explode("&", $input[0]); // make array of properties
//echo "Array" .EOL;
//print_r($array);
$payload = mkPayload($array);
echo $payload;
publish($payload);
}
}
}
$client->loop();
sleep(1);
}
// Prepare payload to send to mqtt server
function mkPayload($array)
{
global $macAddress, $type;
unset ($array[0]);
unset ($array[1]);
$payload = '{"ieeeAddress":"' . $macAddress . '","type":"' . $type . '"';
foreach($array as $property)
{
$r = explode("=", $property);
$payload .= ',"' . $r[0] . '":';
if (is_numeric($r[1]))
{
$payload .= $r[1];
}else
{
$payload .= '"' . $r[1] . '"';
}
}
return $payload . "}";
}
function closeAll()
{
socket_close($spawn);
socket_close($socket);
}
?>

83
utils.php Normal file
View File

@ -0,0 +1,83 @@
<?php
define( "EOL", "\n");
cli_set_process_title($topicName);
file_put_contents("/proc/".getmypid()."/comm",$topicName);
function now()
{
return new DateTime("now");
}
function stopped()
{
global $client, $logFh, $connected;
$x = 0;
$exit = 0;
if ($connected)
{
$mid = $client->unsubscribe("#");
$client->disconnect();
while ($connected)
{
if ( $x++ <= 60)
{
$exit = 1;
break;
}
$client->loop();
}
}
closeAll();
fclose($logFh);
exit(0);
}
function signalHandler($signal)
{
global $connected, $client, $logFh;
$x = 0;
while ($connected)
{
if ( $x++ > 60)
{
$client->disconnect();
fclose($logFh);
exit (1);
}
$client->loop();
}
fclose($logFh);
exit(0);
}
function logger($level, $log, $notif = false)
{
global $logFh, $logLevel, $notificationLevel;
//echo "=====>>>> $level => $logLevel => $notificationLevel" . EOL ;
//echo $log .EOL;
var_dump($level);
var_dump($log);
if ($level & $logLevel)
{
fwrite($logFh, "$level : $log" . EOL);
print ("$level : $log" . EOL);
}
}
date_default_timezone_set('Europe/Paris');
if (! $logFh = fopen("/var/log/pws2mqtt.log", "w") )
{
echo _("error opening log file") . EOL;
}else
{
echo _("Log file opened") . EOL;
}
//signal handling
pcntl_signal(SIGTERM, 'signalHandler');// Termination ('kill' was called)
pcntl_signal(SIGHUP, 'signalHandler'); // Terminal log-out
pcntl_signal(SIGINT, 'signalHandler');
?>