官網有一篇MQTT的安裝教學

Building and running Mosquitto MQTT on Intel Edison

我按照上面的步驟操作,但在編譯時卡住了

read_handle_server.c:31:25: fatal error: uuid/uuid.h: No such file or directory

於是參考網路上其他人的教學,安裝paho-mqtt 這個套件,使用Python來開發


安裝pip套件管理工具

為了要安裝python套件,我們必須先安裝好pip管理工具 首先新增opkg的repositories

# vi /etc/opkg/base-feeds.conf

src/gz all http://repo.opkg.net/edison/repo/all
src/gz edison http://repo.opkg.net/edison/repo/edison
src/gz core2-32 http://repo.opkg.net/edison/repo/core2-32

接著更新package list

# opkg update

安裝pip前,先安裝setuptools

# wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py Then run python ez_setup.py --no-check-certificate
# python ez_setup.py

使用opkg安裝pip

# opkg install python-pip


安裝MQTT

# pip install paho-mqtt


測試MQTT

我們先用下面的範例程式,來測試MQTT是否可以成功訂閱Topic Subscriber端python測試程式

# SubscriberTest.py
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("IOT_NEAT_TOPIC01")

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("mqtt.phodal.com", 1883, 60)
client.loop_forever()

# python SubscriberTest.py
Connected with result code 0
IOT_NEAT_TOPIC01 {'member':'luke','age':11}

mqtt.phodal.com這是一個測試server,已經發佈一個名稱為IOT_NEAT_TOPIC01的Topic,因此我們可以收到Topic內容

{'member':'luke','age':11}

client.connect第1欄為server位置,第2欄是port,第3欄是timeout時間(秒)。如果要強制離開程式,按Ctrl+C會繼續進入loop,我這邊用Ctrl+Z讓他進入背景執行,再用kill把他terminate

# jobs
[1]+ Stopped(SIGTSTP) python SubscriberTest.py
# kill %1


在本機進行Subscriber與Publisher測試

測試過Subscriber後,我們就來建立Publisher,在本機端使用MQTT傳遞訊息。 這邊將server都改為localhost,Topic名稱改為MYTOPIC。 Subscriber端python測試程式

# Subscriber.py
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("MYTOPIC")

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost", 1883, 60)
client.loop_forever()

Publisher端python測試程式

# Publisher.py
import paho.mqtt.client as mqtt

_g_cst_ToMQTTTopicServerIP = "localhost"
_g_cst_ToMQTTTopicServerPort = 1883 #port
_g_cst_MQTTTopicName = "MYTOPIC" #TOPIC name

mqttc = mqtt.Client("python_pub")
mqttc.connect(_g_cst_ToMQTTTopicServerIP, _g_cst_ToMQTTTopicServerPort)
mqttc.publish(_g_cst_MQTTTopicName, "Hello")

執行Publisher後,Subscriber就會收到一個Hello訊息。 測試的時候需要開兩個命令視窗,記得將edison連上網,使用ssh連線登入。如果透過serial port開兩個screen,會發現兩個視窗會同步動作,因為走同一條線XD 執行Subscriber,讓他一直監聽MYTOPIC 只要在另一個命令列執行Publisher,Subscriber就會接收到Hello

# python Subscriber.py
Connected with result code 0
MYTOPIC Hello

這樣就完成MQTT在本機的傳遞測試囉


參考資料