Mosquitto-1.5在Linux上的安裝以及Android客戶端的實現


一、關於MQTT

  MQTT(Message Queuing Telemetry Transport,消息隊列遙測傳輸協議),是一種基於發布/訂閱(publish/subscribe)模式的"輕量級"通訊協議,該協議構建於TCP/IP協議上,由IBM在1999年發布。MQTT最大優點在於,可以以極少的代碼和有限的帶寬,為連接遠程設備提供實時可靠的消息服務。作為一種低開銷、低帶寬占用的即時通訊協議,使其在物聯網、小型設備、移動應用等方面有較廣泛的應用。

  MQTT是一個基於客戶端-服務器的消息發布/訂閱傳輸協議。MQTT協議是輕量、簡單、開放和易於實現的,這些特點使它適用范圍非常廣泛。在很多情況下,包括受限的環境中,如:機器與機器(M2M)通信和物聯網(IoT)。其在,通過衛星鏈路通信傳感器、偶爾撥號的醫療設備、智能家居、及一些小型化設備中已廣泛使用。

 

  而Mosquitto是一個實現了MQTT3.1協議的代理服務器,由MQTT協議創始人之一的Andy Stanford-Clark開發,它為我們提供了非常棒的輕量級數據交換的解決方案,本文將基於mosquitto實現Android手機和阿里雲服務器的mqtt通訊。

 

二、Mosquitto在Ubuntu上安裝

1)下載源碼壓縮包 :https://mosquitto.org/download/

2)解壓源代碼包:

tar -zxvf mosquitto-1.5.tar.gz

3)安裝編譯環境:

sudo apt-get install gcc

sudo apt-get install libssl-dev

sudo apt-get install g++

sudo apt-get install uuid-dev

sudo apt-get install libc-ares-dev

sudo apt-get install libc-ares2

4)進入第2步中解壓開的源代碼目錄,對源代碼進行編譯:

cd mosquito-1.5

sudo make    // 編譯生成可執行文件

sudo make install    // 安裝到系統目錄,可省略

 注:其中config.mk包括了多個選項, 可按需關閉或開啟,但一旦開啟則需要先安裝對應的模塊:

    # 是否支持tcpd/libwrap功能.
    #WITH_WRAP:=yes

    # 是否開啟SSL/TLS支持
    #WITH_TLS:=yes

    # 是否開啟TLS/PSK支持
    #WITH_TLS_PSK:=yes

    # Comment out to disable client client threading support.
    #WITH_THREADING:=yes

    # 是否使用嚴格的協議版本(老版本兼容會有點問題)
    #WITH_STRICT_PROTOCOL:=yes

    # 是否開啟橋接模式
    #WITH_BRIDGE:=yes

    # 是否開啟持久化功能
    #WITH_PERSISTENCE:=yes

    # 是否監控運行狀態
    #WITH_MEMORY_TRACKING:=yes

5)啟動服務

cd src

mosquito -c mosquitto.conf.example      //通過示例配置文件啟動

  通過 mosquito --help 查看詳細選項說明:
 -c : specify the broker config file.
 -d : put the broker into the background after starting.
 -h : display this help.
 -p : start the broker listening on the specified port.
      Not recommended in conjunction with the -c option.
 -v : verbose mode - enable all logging types. This overrides
      any logging options given in the config file.
 另外 主題訂閱 和 消息發布 的客戶端文件生成在 client 目錄,同樣通過如下指令查看詳細參數說明:
 mosquitto_sub --help
mosquitto_sub is a simple mqtt client that will subscribe to a set of topics and print all messages it receives.
mosquitto_sub version 1.5 running on libmosquitto 1.5.0.

Usage: mosquitto_sub {[-h host] [-p port] [-u username [-P password]] -t topic | -L URL [-t topic]}
                     [-c] [-k keepalive] [-q qos]
                     [-C msg_count] [-R] [--retained-only] [-T filter_out] [-U topic ...]
                     [-F format]
                     [-W timeout_secs]
                     [-A bind_address]
                     [-i id] [-I id_prefix]
                     [-d] [-N] [--quiet] [-v]
                     [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]
                     [--proxy socks-url]
       mosquitto_sub --help

 -A : bind the outgoing socket to this host/ip address. Use to control which interface
      the client communicates over.
 -c : disable 'clean session' (store subscription and pending messages when client disconnects).
 -C : disconnect and exit after receiving the 'msg_count' messages.
 -d : enable debug messages.
 -F : output format.
 -h : mqtt host to connect to. Defaults to localhost.
 -i : id to use for this client. Defaults to mosquitto_sub_ appended with the process id.
 -I : define the client id as id_prefix appended with the process id. Useful for when the
      broker is using the clientid_prefixes option.
 -k : keep alive in seconds for this client. Defaults to 60.
 -L : specify user, password, hostname, port and topic as a URL in the form:
      mqtt(s)://[username[:password]@]host[:port]/topic
 -N : do not add an end of line character when printing the payload.
 -p : network port to connect to. Defaults to 1883 for plain MQTT and 8883 for MQTT over TLS.
 -P : provide a password
 -q : quality of service level to use for the subscription. Defaults to 0.
 -R : do not print stale messages (those with retain set).
 -t : mqtt topic to subscribe to. May be repeated multiple times.
 -T : topic string to filter out of results. May be repeated.
 -u : provide a username
 -U : unsubscribe from a topic. May be repeated.
 -v : print published messages verbosely.
 -V : specify the version of the MQTT protocol to use when connecting.
      Can be mqttv31 or mqttv311. Defaults to mqttv311.
 -W : Specifies a timeout in seconds how long to process incoming MQTT messages.
 --help : display this message.
 --quiet : don't print error messages.
 --retained-only : only handle messages with the retained flag set, and exit when the
                   first non-retained message is received.
 --will-payload : payload for the client Will, which is sent by the broker in case of
                  unexpected disconnection. If not given and will-topic is set, a zero
                  length message will be sent.
 --will-qos : QoS level for the client Will.
 --will-retain : if given, make the client Will retained.
 --will-topic : the topic on which to publish the client Will.
 --proxy : SOCKS5 proxy URL of the form:
           socks5h://[username[:password]@]hostname[:port]
           Only "none" and "username" authentication is supported.

See http://mosquitto.org/ for more information.

 mosquitto_pub --help

mosquitto_pub is a simple mqtt client that will publish a message on a single topic and exit.
mosquitto_pub version 1.5 running on libmosquitto 1.5.0.

Usage: mosquitto_pub {[-h host] [-p port] [-u username [-P password]] -t topic | -L URL}
                     {-f file | -l | -n | -m message}
                     [-c] [-k keepalive] [-q qos] [-r]
                     [-A bind_address]
                     [-i id] [-I id_prefix]
                     [-d] [--quiet]
                     [-M max_inflight]
                     [-u username [-P password]]
                     [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]
                     [--proxy socks-url]
       mosquitto_pub --help

 -A : bind the outgoing socket to this host/ip address. Use to control which interface
      the client communicates over.
 -d : enable debug messages.
 -f : send the contents of a file as the message.
 -h : mqtt host to connect to. Defaults to localhost.
 -i : id to use for this client. Defaults to mosquitto_pub_ appended with the process id.
 -I : define the client id as id_prefix appended with the process id. Useful for when the
      broker is using the clientid_prefixes option.
 -k : keep alive in seconds for this client. Defaults to 60.
 -L : specify user, password, hostname, port and topic as a URL in the form:
      mqtt(s)://[username[:password]@]host[:port]/topic
 -l : read messages from stdin, sending a separate message for each line.
 -m : message payload to send.
 -M : the maximum inflight messages for QoS 1/2..
 -n : send a null (zero length) message.
 -p : network port to connect to. Defaults to 1883 for plain MQTT and 8883 for MQTT over TLS.
 -P : provide a password
 -q : quality of service level to use for all messages. Defaults to 0.
 -r : message should be retained.
 -s : read message from stdin, sending the entire input as a message.
 -t : mqtt topic to publish to.
 -u : provide a username
 -V : specify the version of the MQTT protocol to use when connecting.
      Can be mqttv31 or mqttv311. Defaults to mqttv311.
 --help : display this message.
 --quiet : don't print error messages.
 --will-payload : payload for the client Will, which is sent by the broker in case of
                  unexpected disconnection. If not given and will-topic is set, a zero
                  length message will be sent.
 --will-qos : QoS level for the client Will.
 --will-retain : if given, make the client Will retained.
 --will-topic : the topic on which to publish the client Will.
 --proxy : SOCKS5 proxy URL of the form:
           socks5h://[username[:password]@]hostname[:port]
           Only "none" and "username" authentication is supported.

See http://mosquitto.org/ for more information.

使用示例(通過三個終端分別輸入以下指令):

mosquitto -c mosquitto.conf -p 1884  //啟動服務,如果不指定端口則默認使用1883
mosquitto_sub -h 192.168.153.130 -p 1884 -u root -P 123456 -t topic01  //訂閱主題"topic01"
mosquitto_pub -h 192.168.153.130 -p 1884 -t topic01 -m "message01"   //發布消息給訂閱"topic01"的訂閱客戶端

 通過以上步驟大致了解mosquitto在Linux系統上的安裝和使用方法,同樣在阿里雲服務器上運行mosquitto后,即可通過手機MQTT客戶端與雲服務器端進行消息交互。

 PS:阿里雲服務器1883端口默認被屏蔽,需要自己另外配置一個端口

 

、Mqtt Android客戶端開發

 基於Android的Mqtt客戶端組件進行接口封裝,使用更加簡易:

 (1)構建MqttService對象

  /**
     * 構建EasyMqttService對象
     */
    private void buildEasyMqttService() {
        mqttService = new EasyMqttService.Builder()
                //設置自動重連
                .autoReconnect(true)
                //設置不清除回話session 可收到服務器之前發出的推送消息
                .cleanSession(false)
                //唯一標示 保證每個設備都唯一就可以 建議 imei
                .clientId("your clientId")
                //mqtt服務器地址 格式例如:tcp://10.0.261.159:1883
                .serverUrl("your mqtt servier url")
                //心跳包默認的發送間隔
                .keepAliveInterval(20)
                //構建出EasyMqttService 建議用application的context
                .bulid(this.getApplicationContext());
    }

(2)連接Mqtt服務器

  /**
     * 連接Mqtt服務器
     */
    private void connect() {
        mqttService.connect(new IEasyMqttCallBack() {
            @Override
            public void messageArrived(String topic, String message, int qos) {
                //推送消息到達
            }
     
            @Override
            public void connectionLost(Throwable arg0) {
                //連接斷開
            }
     
            @Override
            public void deliveryComplete(IMqttDeliveryToken arg0) {
     
            }
     
            @Override
            public void connectSuccess(IMqttToken arg0) {
                //連接成功
            }
     
            @Override
            public void connectFailed(IMqttToken arg0, Throwable arg1) {
                //連接失敗
            }
        });
    }

(3)訂閱主題

   /**
     * 訂閱主題 這里訂閱三個主題分別是"a", "b", "c"
     */
    private void subscribe() {
        String[] topics = new String[]{"a", "b", "c"};
        //主題對應的推送策略 分別是0, 1, 2 建議服務端和客戶端配置的主題一致
        // 0 表示只會發送一次推送消息 收到不收到都不關心
        // 1 保證能收到消息,但不一定只收到一條
        // 2 保證收到切只能收到一條消息
        int[] qoss = new int[]{0, 1, 2};
        mqttService.subscribe(topics, qoss);
    }

(4)關閉連接

     /**
     * 關閉連接
     */
    private void close() {
        mqttService.close();
    }

(5)斷開連接

   /**
     * 斷開連接
     */
    private void disconnect() {
        mqttService.disconnect();
    }

(6)判斷連接狀態

    /**
     * 判斷服務是否連接
     */
    private boolean isConnected() {
        return mqttService.isConnected();
    }

(7)發布消息

/**
  * 發布消息
  */
public void publish(String msg, String topic, int qos, boolean retained) {
    try {
        client.publish(topic, msg.getBytes(), qos, retained);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 

完整的Demo實現了UI動態輸入及消息顯示,可用於對mqtt服務器進行測試,已上傳至GitHub: https://github.com/dragonforgithub/SmartControl

編譯生成的Linux及Android客戶端軟件已傳至百度雲:鏈接:https://pan.baidu.com/s/1M_fCCITsW2cXGQLo3MWW0Q  提取碼:9r6p

另外可以參考eclipse出品的Android Demo進一步學習: https://github.com/eclipse/paho.mqtt.android

 

-end-

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM