Mohammad Eskandari
Mohammad Eskandari

Reputation: 27

MQTT Subscribe with PHP to IBM Bluemix

I want to connect to IBM Bluemix through the MQTT protocol using PHP to subscribe to messages come from IoT Foundation. I use this code:

<?php

require("../phpMQTT.php");


$config = array(
  'org_id' => 't9m318',
  'port' => '1883',
  'app_id' => 'phpmqtt',
  'iotf_api_key' => 'my api key',
  'iotf_api_secret' => 'my api secret',
  'device_id' => 'phpmqtt'
);

$config['server'] = $config['org_id'] .'.messaging.internetofthings.ibmcloud.com';
$config['client_id'] = 'a:' . $config['org_id'] . ':' .$config['app_id'];
$location = array();

// initialize client
$mqtt = new phpMQTT($config['server'], $config['port'], $config['client_id']); 
$mqtt->debug = false;

// connect to broker
if(!$mqtt->connect(true, null, $config['iotf_api_key'], $config['iotf_api_secret'])){
  echo 'ERROR: Could not connect to IoT cloud';
    exit();
} 

$topics['iot-2/type/+/id/phpmqtt/evt/+/fmt/json'] = 
  array("qos"=>0, "function"=>"procmsg");
$mqtt->subscribe($topics, 0);

// process messages
while ($mqtt->proc(true)) { 

}
// disconnect
$mqtt->close();
function procmsg($topic, $msg) {
 echo "Msg Recieved: $msg";
}

?>

But the browser show this message:

Fatal error: Maximum execution time of 30 seconds exceeded in /Library/WebServer/Documents/phpMQTT/phpMQTT.php on line 167

Upvotes: 0

Views: 919

Answers (2)

Frank Calderon
Frank Calderon

Reputation: 11

subscribe is not meant to run in the web browser as it has an infinite look, its best being run from the command line.

If you are using the subscribe method to receive messages you can look at persistent msgs and breaking out of the loop on msg receipt.

There is an example of how to use phpMQTT in the web browser in the file web-app.php of this respository https://github.com/vvaswani/bluemix-iotf-device-tracker

Upvotes: 1

njh
njh

Reputation: 812

You don't provide very much information about what you want to achieve by doing this; do you want to keep sending messages to the browser until the page is closed in the browser?

Server Sent Events or Websockets might be a better bet, and PHP might not be the best choice for this, because it uses up quite a lot of memory per connection (compared to node.js for example).

However if you just want to remove the 30 second PHP timeout, then you can use this function: http://php.net/manual/en/function.set-time-limit.php

Or set max_execution_time in php.ini: http://php.net/manual/en/info.configuration.php

Setting the maximum execution time to 0 should stop it from timing out.

But be warned that PHP and/or your webserver will have a limited number of concurrent HTTP connections.

Upvotes: 0

Related Questions