DTux
/
dtux__pws2mqtt
Archived
1
0
Fork 0
This repository has been archived on 2023-11-30. You can view files and clone it, but cannot push or open issues or pull requests.
dtux__pws2mqtt/pws2mqtt.php

94 lines
2.2 KiB
PHP

<?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);
}
?>