一,环境
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