一,環境
1. lua-5.4.1安裝
curl -R -O http://www.lua.org/ftp/lua-5.4.1.tar.gz
tar zxf lua-5.4.1.tar.gz cd lua-5.4.1
make all test
make install
2. luarocks-3.3.1安裝(lua的包管理器)
wget https://luarocks.org/releases/luarocks-3.3.1.tar.gz
tar zxpf luarocks-3.3.1.tar.gz
cd luarocks-3.3.1
./configure && make && sudo make install
3.引入包
luarocks install xx
進入https://luarocks.org/網址搜索需要的包
下載.rockspec包,使用命令luarocks make xx 安裝
下載.rock包,使用命令luarocks build xx 安裝
5.安裝mosquitto
wget https://codeload.github.com/eclipse/mosquitto/zip/master
cd mosquitto && make
依賴:
sudo apt-get install openssl
sudo apt-get install libssl-dev
sudo apt-get install openssl
sudo apt-get install uuid-dev
sudo apt-get install docbook-xsl
測試命令:
mosquitto_sub -t "topic"
mosquitto_pub -t "topic" -m "message"
官方文檔:http://mosquitto.org/man/mosquitto-8.html
二、實例
#!/usr/bin/lua
local mqtt = require("mosquitto")
local cjson = require("cjson")
--初始化
client = mqtt.new()
--訂閱主題
client.ON_CONNECT = function()
print("connected")
client:subscribe("topic", 2)
end
--消息處理
client.ON_MESSAGE = function(mid, topic, payload)
if(topic == "topic") then
local obj = cjson.decode(payload);
if(obj.cmd == "123") then
os.execute("touch 123.txt")
elseif if(obj.cmd == "456") then
io.popen("touch 456.txt")
end
end
client:connect("127.0.0.1",1883)
client:loop_forever()
三、編譯二進制
編譯 luac -o mqtt mqtt.lua
執行 lua ./mqtt