0

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.

fiorebat
  • 3,247
  • 2
  • 16
  • 18
Mikkel
  • 43
  • 6

1 Answers1

1

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 !

Joa Barcena
  • 171
  • 2
  • 5
  • Hi Joa, thanks! I am now running the entire db loop etc in the procmsg(). I am not sure iti's the absolutely best way to do it, but it works for now. Is there really not a way to simply have the values of $msg and $topic available outside the procmsg function? – Mikkel May 09 '17 at 10:23
  • Hi !, the only way i can think of is placing that values into a global variables, but i dont recommend that too ,another way is thinking in a buffer (global too, a simply array that you can storage both values in order of arrival) – Joa Barcena May 09 '17 at 10:29