完整实例(个人测试版,subscribe-订阅可忽略)
require('json')
require('encdec')
mqtt = require('mosquitto')
num = math.random(0,1)
log(num)
data = json.encode({params = {
LightStatus = num,
--humidity=19
}})
deviceName = 'deviceName' -- deviceName
client = 'deviceName' -- 不一定是deviceName,这个是我随意命名
productKey = 'productKey' -- productKey
deviceSecret = 'deviceSecret' -- deviceSecret
broker = productKey..'.iot-as-mqtt.cn-shanghai.aliyuncs.com'
port = 1883
username = deviceName..'&'..productKey
password ='clientId'..client..'deviceName'..deviceName..'productKey'..productKey
device_id = client..'|securemode=3,signmethod=hmacsha1|'
password = string.upper(encdec.hmacsha1(password, deviceSecret))
client = mqtt.new(device_id)
running = true
topic = '/sys/'..productKey..'/'..deviceName..'/thing/event/property/post'
client.ON_CONNECT = function(stat, code, err)
if stat then
log('publish')
client:publish(topic, data) --发布
client:subscribe(topic) --订阅
else
log('mqtt connect error', err, code)
end
--running = false
--client:disconnect()
end
client.ON_MESSAGE = function(mid, topic, data)
log('message', topic, data)
client:disconnect()
end
client:version_set(mqtt.PROTOCOL_V311)
--client:tls_set('/home/ftp/ca.cer') -- securemode=1需要签证,此文件可在阿里文档寻找
client:login_set(username, password)
res, err = client:connect(broker, port)
if not res then
log('mqtt initial connect error', err)
running = false
end
if res then
while running do
res, err, code = client:loop()
if not res then
if running then
log('mqtt loop error', err, code)
end
break
end
end
else
log('mqtt connection failed', err)
end
用户,密码生成:http://mqtt.lovemcu.cn/
subscribe-订阅
client.ON_CONNECT = function(status, rc, err)
if status then
log('connect ok')
client:subscribe(topic)--订阅topic
else
log('connect error', rc, err)
end
end
client.ON_MESSAGE = function(mid, topic, data) --topic下发信息
log('message', topic, data)
end
个人测试版
require('json')
num = math.random(0,1)
log(num)
data = json.encode({params={
LightStatus=num,
--humidity=19
}})
broker = '。。。。'
port = 1883
device_id = '。。。'
username = '。。。。'
password = '。。。'
pk = '。。。'
mqtt = require('mosquitto')
client = mqtt.new(device_id)
running = true
topic = '/sys/。。。/light/thing/event/property/post'
client.ON_CONNECT = function(stat, code, err)
if stat then
log('publish')
client:publish(topic , data)
client:subscribe(topic)
else
log('mqtt connect error', err, code)
end
--running = false
--client:disconnect()
end
client.ON_MESSAGE = function(mid, topic, data)
log('message', topic, data)
client:disconnect()
end
client:version_set(mqtt.PROTOCOL_V311)
--client:tls_set('/home/ftp/ca.cer')
client:login_set(username, password)
res, err = client:connect(broker, port)
if not res then
log('mqtt initial connect error', err)
running = false
end
if res then
while running do
res, err, code = client:loop()
if not res then
if running then
log('mqtt loop error', err, code)
end
break
end
end
else
log('mqtt connection failed', err)
end