bluerhinos / phpMQTT

a simple php class to connect/publish/subscribe to a MQTT broker
Other
770 stars 461 forks source link

How do I keep receiving subscibe messages ??? #70

Closed lxlin315 closed 4 years ago

lxlin315 commented 6 years ago

// 1、实例化mqtt并建立连接 $mqtt = new phpMQTT($this->server, $this->port, $this->client_id); //链接不成功再重复执行监听连接 if (!$mqtt->connect(true, NULL, $this->username, $this->password)) { exit(1); }

    // 2、订阅Topic
    if (empty($extend))//扩展节点为空
    {
        //定义订阅返回值的Topic
        $sub_topic[$type . '/dtc/' . $area . '/#'] = array("qos" => $qos, "function" => [$this, "callback"]);
    } else {
        //定义订阅返回值的Topic
        $sub_topic[$type . '/dtc/' . $area . '/' . $extend . '/#'] = array("qos" => $qos, "function" => [$this, "callback"]);
    }
    //订阅【主题:$sub_topic,qos:1,回调函数:callback】
    $mqtt->subscribe($sub_topic, intval($qos));

    // 3、发布Topic
    if (empty($extend))//扩展节点为空
    {
        //定义发布Topic
        $pub_topic = $type . '/ctd/' . $area . '/' . $devsn;
    } else {
        //定义发布Topic
        $pub_topic = $type . '/ctd/' . $area . '/' . $extend . '/' . $devsn;
    }
    //定义需要发送的消息内容
    $pub_data = array(
        'type' => 'set',
        'devsn' => $devsn,
        'lights' => array(
            array('did' => $did, 'sub' => intval($sub), 'bright' => intval($bright))
        ),
        'batctl' => 'single' //single:单灯控制
    );

    //Json to String
    $data = json_encode($pub_data);
    //发布【主题:lighting/1,qos:1】
    $mqtt->publish($pub_topic, $data, intval($qos));

   //Method One:too slow
    // Wait 10 x 0.3s for server to send us the previous messages(等待服务器发送rep数据过来)
    for ($l1 = 0; $l1 < 10; $l1++) {
        usleep(300000); //300000微秒 = 0.3秒
        $mqtt->proc();
    }

    //Method Two:time out(30s)
    //死循环监听
    while($mqtt->proc()){}

    $mqtt->close();

Question: Excuse me, is there any other way???

bluerhinos commented 4 years ago

I am restarting this project so having a clear out of old issues (If you believe this is still valid please reopen)

Recent updates should fix this