MQTT 的安裝與測試

    MQTT 是一種輕量化的通訊技術,發佈資訊的角色稱為(Publisher),而需要取資料者稱為訂閱者(Subscriber),發佈者跟訂閱者是透過 MQTT Server (也可稱為MQTT Broker)間接傳遞資訊,為什麼說是間接呢? 因為發佈者只管在 MQTT Server 上開啟一個主題(Topic),並且把資訊傳遞到主題上,不用管訂閱者是誰;訂閱者也只要管自己想要訂閱(Subscribe)訂閱哪一個主題,而不用管發佈者是誰。 以下是我用 claude產生的架構圖

MQTT Topic 架構 Publisher 發布者 Topic: sensor/temp 溫度感測器主題 Topic: sensor/humid 濕度感測器主題 MQTT Broker Subscriber 1 訂閱 sensor/temp Subscriber 2 訂閱 sensor/# Subscriber 3 訂閱 sensor/humid Topic 說明: • sensor/temp: 溫度資料主題 • sensor/humid: 濕度資料主題 • sensor/#: 訂閱所有感測器資料 (使用萬用字元 #) 那如何實作呢? 首先要先安裝MQTT Server 套件,我這選用 Mosquitto - Eclipse Foundation ,下載網址如 https://mosquitto.org/download/,我這邊使用的是 mosquitto-2.0.15-install-windows-x64.exe,要注意的是不一樣的版本,組態設定上會有一點不同,這也算是一個小坑要注意,安裝完之後,打開 C:\Program Files\mosquitto\mosquitto.conf,這個是MQTT的組態檔(以下我描述的組態設定是沒有走安全連線的版本,等我搞定安全連線版本的時候再回來補充),要修改的地方如下: 
1. 在security區塊加入allow_anonymous true,如下
# =================================================================
# Security #
 ================================================================= 
# If set, only clients that have a matching prefix on their 
# clientid will be allowed to connect to the broker. By default, 
# all clients may connect. # For example, setting "secure-" here would mean a client "secure- 
# client" could connect but another with clientid "mqtt" couldn't. 
#clientid_prefixes # Boolean value that determines whether clients that connect 
# without providing a username are allowed to connect. If set to 
# false then a password file should be created (see the 
# password_file option) to control authenticated client access. 
# Defaults to false, unless there are no listeners defined in the configuration 
# file, in which case it is set to true, but connections are only allowed from 
# the local machine. 
allow_anonymous true

2. 在檔案最下面加入以下
listener 1883
protocol mqtt

listener 1884
protocol websockets
socket_domain ipv4

上述安裝設定安裝之後,基本上MQTT Server已就緒,接下來就是要處理Subscriber跟Publisher。
Publsher有很多測試模組,這邊採用的是 MQTT Explorer | An all-round MQTT client that provides a structured topic overview,開啟後新增一個連線如下,此時點選CONNECT就可以連上剛剛安裝的MQTT Server。

成功連線後會進入下面這一個畫面
重點來了,Publisher 要定義一個 Topic,並發佈資訊,我這邊發佈的Topic為 test/topic,資料為 555,所以Subscriber只要訂閱 test/topic就可以收到555。

接下來這邊要用js實作Subscriber並連接MQTT Server,code如下








留言