mosquitto的windows系统安装和使用方法

下载地址https://mosquitto.org/download/

安装之后是这样的

 

然后设置账号密码流程如下:

      1: 打开mosquitto.conf文件,找到allow_anonymous节点,这个节点作用是,是否开启匿名用户登录,默认是true。打开此项配置(将前面的 # 号去掉)之后将其值改为true

    修改前:#allow_anonymous

    修改后:allow_anonymous false

  2: 找到password_file节点,这个节点是告诉服务器你要配置的用户将存放在哪里。打开此配置并指定pwfile.example文件路劲(注意是绝对路劲)

    修改前:#password_file

    修改后:password_file /etc/mosquitto/pwfile.example (这里的地址根据自己文件实际位置填写)

  3: 创建用户名和密码、打开命令窗口 键入如下命令:  

mosquitto_passwd -c /etc/mosquitto/pwfile.example admin
    提示连续两次输入密码、创建成功。命令解释: -c 创建一个用户、/etc/mosquitto/pwfile.example 是将用户创建到 pwfile.example  文件中、admin 是用户名。

  4: 创建mosquitto用户。在命令窗口键入如下命令:

mosquitto_passwd /etc/mosquitto/pwfile.example mosquitto
    同样连续会提示连续输入两次密码。注意第二次创建用户时不用加 -c 如果加 -c 会把第一次创建的用户覆盖。

至此两个用户创建成功,此时如果查看 pwfile.example 文件会发现其中多了两个用户。

下来我们来验证下:

打开cmd启动服务:

mosquitto.exe -v -c mosquitto.conf

注意这里的端口号1883  会用到下面的发布和订阅

另外在打开一个cmd:

mosquitto_pub.exe -h 127.0.0.1 -p 1883 -u admin -P 123456 -t topic -m 'hello'

再继续打开一个cmd:

mosquitto_sub.exe -h 127.0.0.1 -p 1883 -u admin -P 123456 -v -t #

以上就是完整的安装流程。另外两篇安装方法文章值得去看一下:

https://blog.csdn.net/qq_22111417/article/details/84142509

https://blog.csdn.net/qq_28537277/article/details/86659160

 

下来我们看看php的使用方法

首先我们要下载个mosquitto库,以下是我整理好的,或者是其他地方下载,下载地址:

 https://github.com/MongoYun/IotmanMqttDemoWebSites/tree/master/wechatMqttDemo/Application/Iot/Controller 
<?php
namespace app\apk\controller;

use think\Controller;
/* phpMQTT */

class MqttController extends Controller
{
    private $socket;               /* holds the socket          */
    private $msgid = 1;            /* counter for message id    */
    public  $keepalive = 10;       /* default keepalive timmer  */
    public  $timesinceping;        /* host unix time, used to detect disconects */
    public  $topics = array();     /* used to store currently subscribed topics */
    public  $debug = false;        /* should output debug messages */
    public  $address;              /* broker address */
    public  $port;                 /* broker port */
    public  $clientid;             /* client id sent to brocker */
    public  $will;                 /* stores the will of the client */
    private $username;             /* stores username */
    private $password;             /* stores password */
    public  $cafile;

    public function __construct($address, $port, $clientid, $cafile = NULL){
        $this->broker($address, $port, $clientid, $cafile);
    }

    /* sets the broker details */
    public function broker($address, $port, $clientid, $cafile = NULL){
        $this->address = $address;
        $this->port = $port;
        $this->clientid = $clientid;
        $this->cafile = $cafile;
    }

    public function connect_auto($clean = true, $will = NULL, $username = NULL, $password = NULL){
        while($this->connect($clean, $will, $username, $password)==false){
            sleep(10);
        }
        return true;
    }

    /* connects to the broker
        inputs: $clean: should the client send a clean session flag */
    public function connect($clean = true, $will = NULL, $username = NULL, $password = NULL){

        if($will) $this->will = $will;
        if($username) $this->username = $username;
        if($password) $this->password = $password;


        if ($this->cafile) {
            $socketContext = stream_context_create(array("ssl" => array(
                "verify_peer_name" => true,
                "cafile" => $this->cafile
            )));
            $this->socket = stream_socket_client("tls://" . $this->address . ":" . $this->port, $errno, $errstr, 60, STREAM_CLIENT_CONNECT, $socketContext);
        } else {
            $this->socket = stream_socket_client("tcp://" . $this->address . ":" . $this->port, $errno, $errstr, 60, STREAM_CLIENT_CONNECT);
        }

        if (!$this->socket ) {
            if($this->debug) error_log("stream_socket_create() $errno, $errstr \n");
            return false;
        }

        stream_set_timeout($this->socket, 5);
        stream_set_blocking($this->socket, 0);

        $i = 0;
        $buffer = "";

        $buffer .= chr(0x00); $i++;
        $buffer .= chr(0x06); $i++;
        $buffer .= chr(0x4d); $i++;
        $buffer .= chr(0x51); $i++;
        $buffer .= chr(0x49); $i++;
        $buffer .= chr(0x73); $i++;
        $buffer .= chr(0x64); $i++;
        $buffer .= chr(0x70); $i++;
        $buffer .= chr(0x03); $i++;

        //No Will
        $var = 0;
        if($clean) $var+=2;

        //Add will info to header
        if($this->will != NULL){
            $var += 4; // Set will flag
            $var += ($this->will['qos'] << 3); //Set will qos
            if($this->will['retain'])    $var += 32; //Set will retain
        }

        if($this->username != NULL) $var += 128;    //Add username to header
        if($this->password != NULL) $var += 64;    //Add password to header

        $buffer .= chr($var); $i++;

        //Keep alive
        $buffer .= chr($this->keepalive >> 8); $i++;
        $buffer .= chr($this->keepalive & 0xff); $i++;

        $buffer .= $this->strwritestring($this->clientid,$i);

        //Adding will to payload
        if($this->will != NULL){
            $buffer .= $this->strwritestring($this->will['topic'],$i);
            $buffer .= $this->strwritestring($this->will['content'],$i);
        }

        if($this->username) $buffer .= $this->strwritestring($this->username,$i);
        if($this->password) $buffer .= $this->strwritestring($this->password,$i);

        $head = "  ";
        $head{0} = chr(0x10);
        $head{1} = chr($i);

        fwrite($this->socket, $head, 2);
        fwrite($this->socket,  $buffer);

        $string = $this->read(4);

        if(ord($string{0})>>4 == 2 && $string{3} == chr(0)){
            if($this->debug) echo "Connected to Broker\n";
        }else{
            error_log(sprintf("Connection failed! (Error: 0x%02x 0x%02x)\n",
                ord($string{0}),ord($string{3})));
            return false;
        }

        $this->timesinceping = time();
        
        return true;
    }

    /* read: reads in so many bytes */
    public function read($int = 8192, $nb = false){
        //print_r(socket_get_status($this->socket));
        $string="";
        $togo = $int;

        if($nb){
            return fread($this->socket, $togo);
        }

        while (!feof($this->socket) && $togo>0) {
            $fread = fread($this->socket, $togo);
            $string .= $fread;
            $togo = $int - strlen($string);
        }
        return $string;
    }

    /* subscribe: subscribes to topics */
    public function subscribe($topics, $qos = 0){
        $i = 0;
        $buffer = "";
        $id = $this->msgid;
        $buffer .= chr($id >> 8);  $i++;
        $buffer .= chr($id % 256);  $i++;

        foreach($topics as $key => $topic){
            $buffer .= $this->strwritestring($key,$i);
            $buffer .= chr($topic["qos"]);  $i++;
            $this->topics[$key] = $topic;
        }

        $cmd = 0x80;
        //$qos
        $cmd +=    ($qos << 1);
        $head = chr($cmd);
        $head .= chr($i);

        fwrite($this->socket, $head, 2);
        fwrite($this->socket, $buffer, $i);
        $string = $this->read(2);

        $bytes = ord(substr($string,1,1));
        $string = $this->read($bytes);
    }

    /* ping: sends a keep alive ping */
    public function ping(){
        $head = " ";
        $head = chr(0xc0);
        $head .= chr(0x00);
        fwrite($this->socket, $head, 2);
        if($this->debug) echo "ping sent\n";
    }

    /* disconnect: sends a proper disconect cmd */
    public function disconnect(){
        $head = " ";
        $head{0} = chr(0xe0);
        $head{1} = chr(0x00);
        fwrite($this->socket, $head, 2);
    }

    /* close: sends a proper disconect, then closes the socket */
    public function close(){
        $this->disconnect();
        stream_socket_shutdown($this->socket, STREAM_SHUT_WR);
    }

    /* publish: publishes $content on a $topic */
    public function publish($topic, $content, $qos = 0, $retain = 0){

        $i = 0;
        $buffer = "";

        $buffer .= $this->strwritestring($topic,$i);
        //$buffer .= $this->strwritestring($content,$i);

        if($qos){
            $id = $this->msgid++;
            $buffer .= chr($id >> 8);  $i++;
            $buffer .= chr($id % 256);  $i++;
        }

        $buffer .= $content;
        $i+=strlen($content);

        $head = " ";
        $cmd = 0x30;
        if($qos) $cmd += $qos << 1;
        if($retain) $cmd += 1;

        $head{0} = chr($cmd);
        $head .= $this->setmsglength($i);
        
        fwrite($this->socket, $head, strlen($head));
        fwrite($this->socket, $buffer, $i);
        
    }

    /* message: processes a recieved topic */
    public function message($msg){
        $tlen = (ord($msg{0})<<8) + ord($msg{1});
        $topic = substr($msg,2,$tlen);
        $msg = substr($msg,($tlen+2));
        $found = 0;
        foreach($this->topics as $key=>$top){
            if( preg_match("/^".str_replace("#",".*",
                    str_replace("+","[^\/]*",
                        str_replace("/","\/",
                            str_replace("$",'\$',
                                $key))))."$/",$topic) ){
                if(is_callable($top['function'])){
                    call_user_func($top['function'],$topic,$msg);
                    $found = 1;
                }
            }
        }

        if($this->debug && !$found) echo "msg recieved but no match in subscriptions\n";
    }

    /* proc: the processing loop for an "allways on" client
        set true when you are doing other stuff in the loop good for watching something else at the same time */
    public function proc( $loop = true){

        if(1){
            $sockets = array($this->socket);
            $w = $e = NULL;
            $cmd = 0;

            //$byte = fgetc($this->socket);
            if(feof($this->socket)){
                if($this->debug) echo "eof receive going to reconnect for good measure\n";
                fclose($this->socket);
                $this->connect_auto(false);
                if(count($this->topics))
                    $this->subscribe($this->topics);
            }

            $byte = $this->read(1, true);

            if(!strlen($byte)){
                if($loop){
                    usleep(100000);
                }
            }else{
                $cmd = (int)(ord($byte)/16);
                if($this->debug) echo "Recevid: $cmd\n";

                $multiplier = 1;
                $value = 0;
                do{
                    $digit = ord($this->read(1));
                    $value += ($digit & 127) * $multiplier;
                    $multiplier *= 128;
                }while (($digit & 128) != 0);

                if($this->debug) echo "Fetching: $value\n";

                if($value)
                    $string = $this->read($value);

                if($cmd){
                    switch($cmd){
                        case 3:
                            $this->message($string);
                            break;
                    }

                    $this->timesinceping = time();
                }
            }

            if($this->timesinceping < (time() - $this->keepalive )){
                if($this->debug) echo "not found something so ping\n";
                $this->ping();
            }

            if($this->timesinceping<(time()-($this->keepalive*2))){
                if($this->debug) echo "not seen a package in a while, disconnecting\n";
                fclose($this->socket);
                $this->connect_auto(false);
                if(count($this->topics))
                    $this->subscribe($this->topics);
            }
        }
        return 1;
    }

    /* getmsglength: */
    public function getmsglength(&$msg, &$i){

        $multiplier = 1;
        $value = 0 ;
        do{
            $digit = ord($msg{$i});
            $value += ($digit & 127) * $multiplier;
            $multiplier *= 128;
            $i++;
        }while (($digit & 128) != 0);

        return $value;
    }


    /* setmsglength: */
    public function setmsglength($len){
        $string = "";
        do{
            $digit = $len % 128;
            $len = $len >> 7;
            // if there are more digits to encode, set the top bit of this digit
            if ( $len > 0 )
                $digit = ($digit | 0x80);
            $string .= chr($digit);
        }while ( $len > 0 );
        return $string;
    }

    /* strwritestring: writes a string to a buffer */
    public function strwritestring($str, &$i){
        $ret = " ";
        $len = strlen($str);
        $msb = $len >> 8;
        $lsb = $len % 256;
        $ret = chr($msb);
        $ret .= chr($lsb);
        $ret .= $str;
        $i += ($len+2);
        return $ret;
    }

    public function printstr($string){
        $strlen = strlen($string);
        for($j=0;$j<$strlen;$j++){
            $num = ord($string{$j});
            if($num > 31)
                $chr = $string{$j}; else $chr = " ";
            printf("%4d: %08b : 0x%02x : %s \n",$j,$num,$num,$chr);
        }
    }
}

以上代码我新建文件MqttController.php,具体情况,请自行修改,因为我的程序thinkphp5,所以这样写的。

下来我们就可以调用了:

发布主题:

        header("content-type:text/html;charset=utf-8");
        $topic='test';
        $server = $this->server;
        $port = $this->port;
        $username = $this->username;
        $password = $this->password;
        $mqtt = new MqttController($server, $port, time()); //实例化MQTT类
        if ($mqtt->connect(true, NULL, $username, $password)) {
            //如果创建链接成功
    
            $re = $mqtt->publish($topic,'{"doorOpen":"customer"}',0);
            $mqtt->close();    //发送后关闭链接
            //return true;
            echo 'OK';
        } else {
            echo "Time out!\n";
        }

然后再控制台看下效果:

 好了,大功告成,觉得有用的话请关注我一下!

posted @ 2019-04-13 14:15  浪、子  阅读(311)  评论(0)    收藏  举报