phpfunctionreturnphpmqtt

Return in function not working


I am subscribing to data from a MQTT broker with phpMQTT. I have successfully set up a pub / sub routine based on their basic implementation. I can echo the information just fine inside the procmsg() function.

However, I need to take the data I receive and use it for running a few database operations and such. I can't seem to get access to the topic or msg received outside of the procmsg() function. Using return as below seems to yield nothing.

<?php
function procmsg($topic, $msg){
  $value = $msg * 10;
  return $value;
}

echo procmsg($topic, $msg);
echo $value;
?>

Obviously I am doing something wrong - but how do I get at the values so I can use them outside the procmsg()? Thanks a lot.


Solution

  • I dont know about that lib, but in that code https://github.com/bluerhinos/phpMQTT/blob/master/phpMQTT.php , its possible see how works.

    in :

    $topics['edafdff398fb22847a2f98a15ca3186e/#'] = array("qos"=>0, "function"=>"procmsg");
    

    you are telling it that topic "edafdff398fb22847a2f98a15ca3186e/#" will have Quality of Service (qos) = 0, and an "event" called 'procmsg'. That's why you later wrote this

    function procmsg($topic,$msg){ ... }
    

    so in the while($mqtt->proc()) this function will check everytime if has a new message (line 332 calls a message function and then that make a call to procmsg of Source Code)

    thats are the reason why you cannot call in your code to procmsg

    in other words maybe inside the procmsg you can call the functions to process message ej :

    function procmsg($topic,$msg){ 
        $value = $msg * 10;
        doStuffWithDataAndDatabase($value);
    }
    

    Note that you can change the name of the function simply ej :

    $topics['edafdff398fb22847a2f98a15ca3186e/#'] = array("qos"=>0, "function"=>"onMessage");
    

    and then :

    function onMessage($topic,$msg){ 
        $value = $msg * 10;
        doStuffWithDataAndDatabase($value);
    }
    

    Sorry for my english, hope this help !