yii2mqttpublish-subscribeyii2-advanced-appphpmqtt

How to subscribe to mosquitto on a yii2 project


I have an yii2 project with the advanced template and I want to implement notifications using a mosquitto broker. I already have the publish part done and working, now I'd like to have some help on subscribing to a topic on my frontend app. I already tried, but the page seems to stop working when I subscribe to any topic. Is there any easy way or tutorial that I can use? If any more information is needed, please ask.

P.S: My idea was: When I open any page on frontend, I check for messages, save them in a array, set them as view param and then render my page.

EDIT: So far i've tried the following

Class

<?php

namespace common\models;

use Yii;


class Notificacoes
{
    private $listaNotificacoes;

    public function __construct($id, $name)
    {
        $this->listaNotificacoes = array();

        $server = "127.0.0.1";     
        $port = 1883;                     
        $username = "";                   
        $password = "";                   
        $client_id = $id;

        $mqtt = new \common\mosquitto\phpMQTT($server, $port, $client_id);

        if(!$mqtt->connect(true, NULL, $username, $password)) {
            exit(1);
        }

        $topics[$name] = array("qos" => 0, "function" => "procmsg");
        $mqtt->subscribe($topics, 0);

        while($mqtt->proc()){

        }
        $mqtt->close();
    }
    function procmsg($topic, $msg)
    {
        \array_push($this->listaNotificacoes, $msg);
    }

    public function getAll()
    {
        return $this->listaNotificacoes;
    }
}

SiteController: I tried to get the messages on the beforeAction method

public function beforeAction($action)
    {
        if (!parent::beforeAction($action)) {
            return false;
        }

        $notifications = array();

        if (!Yii::$app->user->isGuest) 
        {
            $notifs = new Notificacoes(Yii::$app->user->identity->getId(), Yii::$app->user->identity->username);
            $notifications = $notifs->getAll();
        }

        $this->view->params['notifications'] = $notifications;

        return true; 
    }

Solution

  • This model is unlikely to work because normally messages are only delivered by MQTT at the instant they are published.

    So unless you are using retained messages or persistent subscriptions for a given client id to queue messages. This means your while loop will never have any messages to process