mqtt接收设备的消息,wss server连接微信小程序,如何把一方的消息转发到另一方?

LongJuanHong

问题描述

mqtt接收设备的消息,wss server连接微信小程序,如何把一方的消息转发到另一方?

$mqtt_worker = new Worker();
$mqtt_worker->onWorkerStart = function(){
    $options = [
        'username' => 'mq_user_00001',
        'password' => 'qiR89ns',
        'resubscribe' => true,
        'client_id' => 'client_id_00001',
        'clean_session' => true,
    ];

    $mqtt = new Workerman\Mqtt\Client('mqtt://127.0.0.1:1883',$options);

    $mqtt->onConnect = function($mqtt) {
        echo("\n mqtt-onConnect \n");
        echo(date('Y-m-d H:i:s')."\n");
        $mqtt->subscribe('pzb/ws/v1/up/+');//$mqtt->subscribe('pzb/ws/v1/up/Dev00001');
        log_mqtt('[onConnect]');
    };

    $mqtt->onMessage = function($topic, $content, $mqtt){
            echo("\n mqtt-onMessage \n");
            echo(date('Y-m-d H:i:s')."\n");
            //如何把$content通过wss发送出去?
    };

    $mqtt->connect();
};

// 证书最好是申请的证书
$context = array(
    // 更多ssl选项请参考手册 http://php.net/manual/zh/context.ssl.php
    'ssl' => array(
        // 请使用绝对路径
        'local_cert'        => '/www/wwwroot/www.dog.com/dog_com.pem', // 也可以是crt文件
        'local_pk'          => '/www/wwwroot/www.dog.com/dog_com.key',
        'verify_peer'       => false,
        'allow_self_signed' => false, //如果是自签名证书需要开启此选项
    )
);
// 这里设置的是websocket协议(端口任意,但是需要保证没被其它程序占用)
$wss_worker = new Worker('websocket://0.0.0.0:8282', $context);
// 设置transport开启ssl,websocket+ssl即wss
$wss_worker->transport = 'ssl';
$wss_worker->onConnect = function(TcpConnection $con) {
        echo("\n\nwss_worker--onConnect:\n");
        echo(date('Y-m-d H:i:s')."\n");
        echo($con->getRemoteIp()."\n");
        log_wss('['.$con->getRemoteIp().'][onConnect]');
};

$wss_worker->onMessage = function(TcpConnection $con, $msg) {
        echo("\n\nwss_worker--onMessage:\n");
        echo(date('Y-m-d H:i:s')."\n");
        echo($con->getRemoteIp()."\n");
        log_wss('['.$con->getRemoteIp().'][onMessage]'.$msg);
        var_dump($msg);
        $con->send('ok');
        //如何把msg通过mqtt发送出去?
};
375 1 0
1个回答

jianqi

mqtt本质就是订阅/发布,

用emqx做服务端, emqx是支持wss方式接入的。

设备发布topic到emqx , 小程序订阅相同的topic , 就会收到消息,不用额外操作 。

如果涉及更复杂的转发,emqx支持消息入mysql, 还有hook

×
🔝