【问题标题】:MQTT Subscribe with PHP to IBM BluemixMQTT 使用 PHP 订阅 IBM Bluemix
【发布时间】:2016-02-17 14:28:55
【问题描述】:

我想使用 PHP 通过 MQTT 协议连接到 IBM Bluemix,以订阅来自 IoT Foundation 的消息。 我使用此代码:

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

?>

但浏览器显示此消息:

致命错误:/Library/WebServer/Documents/phpMQTT/phpMQTT.php 第 167 行的最大执行时间超过 30 秒

【问题讨论】:

    标签: php ibm-cloud mqtt iot phpmqtt


    【解决方案1】:

    订阅并不意味着在网络浏览器中运行,因为它具有无限的外观,最好从命令行运行。

    如果您使用 subscribe 方法接收消息,您可以查看持久性消息并在消息接收时打破循环。

    文件中有一个如何在web浏览器中使用phpMQTT的例子 此存储库的 web-app.php https://github.com/vvaswani/bluemix-iotf-device-tracker

    【讨论】:

    • 我正在尝试这个例子。但有时我没有得到这些值。我为我的发布者保持保留标志为真,以确保代理不会删除值但仍然失败。任何线索为什么会发生这种情况。我在这里发布了一个单独的线程stackoverflow.com/questions/42532305/…
    【解决方案2】:

    你没有提供太多关于你想通过这样做实现什么的信息;是否要继续向浏览器发送消息,直到页面在浏览器中关闭?

    服务器发送事件或 Websockets 可能是更好的选择,而 PHP 可能不是最好的选择,因为每个连接会占用大量内存(例如,与 node.js 相比)。

    但是,如果您只想删除 30 秒 PHP 超时,则可以使用此函数: http://php.net/manual/en/function.set-time-limit.php

    或者在 php.ini 中设置 max_execution_time: http://php.net/manual/en/info.configuration.php

    将最大执行时间设置为 0 应该会阻止它超时。

    但请注意,PHP 和/或您的网络服务器的并发 HTTP 连接数量有限。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      相关资源
      最近更新 更多