1
0
moha/mqtt_functions.php

123 lines
3.0 KiB
PHP

<?php
// mosquitto-php related functions
logger(DEBUG,"Including mqtt_functions.php");
function messageReceived($message)
{
global $topics, $logFh, $devices, $included;
$topic = explode ("/", $message->topic);
$callback = $topics[$topic[0]]->callback;
//logger(DEBUG, "message => " . var_export($message, true), __FILE__ . ":" . __LINE__);
$callback($topic, $message);
}
// payload is an array :
// $key is property and $value is value of the property
function publish($topic, $payloadArray, $commande="set") //, $eventKey)
{
global $client, $mids, $logFh, $testMode;
$string = $topic . "/" . $commande;
if ($testMode === false)
{
if ($client !== null)
{
$mid = $client->publish($string, json_encode($payloadArray) , 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 => " . json_encode($payloadArray), __FILE__ . ":" . __LINE__);
}else
{
logger(ERROR, $logFh, "MQTT client is null not publishing " . $string . " with payload => " . json_encode($payloadArray), __FILE__ . ":" . __LINE__);
}
}else
{
logger(INFO, _("Test mode on: no publishing "), __FILE__ . ":" . __LINE__);
}
}
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"), __FILE__ . ":" . __LINE__);
$connected = true;
break;
case 1:
logger(ERROR, _("Connection refused : unacceptable protocol version"), __FILE__ . ":" . __LINE__);
$connected = true;
break;
case 2:
logger(ERROR, _("Connection refused : identifier rejected"), __FILE__ . ":" . __LINE__);
$connected = true;
break;
case 3:
logger(ERROR, _("Connection refused (broker unavailable )"), __FILE__ . ":" . __LINE__);
$connected = true;
break;
}
}
function subscribeResponse($mid, $qosCount)
{
global $topics, $mids, $nSubscribed;
//print_r($mids);
$key = $mids[$mid];
logger(INFO, _("Subscribed to ") . $key, __FILE__ . ":" . __LINE__);
$topics[$key]->status = true;
$nSubscribed += 1;
}
function unsubscribeResponse($mid)
{
global $client; //$topics, $mids, $nSubscribed;
//$key = $mids[$mid];
logger(INFO, _("Unsubscribed", __FILE__ . ":" . __LINE__)); // from ") . $topics[$key]->name);
//$topics[$key]->status = false;
//$nSubscribed -= 1;
$client->disconnect();
}
function disconnectResponse($r)
{
global $connected;
if ($r != 0)
{
$str = _('Badly ');
}else
{
$str = _('Cleanly ');
}
logger(ALERT, $str . _("disconnected from server"));
$connected = false;
}
function publishResponse($mid)
{
global $mids, $events;
logger(LOG_INFO, sprintf(_("Event with mid = %d published by MQTT broker"), $mid), __FILE__ . ":" . __LINE__);
if (isset($mids[$mid]))
{
//echo "unsetting mids" . EOL;
unset ($mids[$mid]);
//print_r($mids);
}else
{
//echo "setting mids" . EOL;
$mids[$mid] = true;
}
}
?>