使用nodemcu玩转物联网系列(六):notemcu通过mqtt协议获取温湿度传感器值上传onenet服务器

gpio.mode(2,gpio.OUTPUT)
wifi.setmode(wifi.STATION)
cfg = {}
cfg.ssid = "kyn"
cfg.pwd = "20160118"
wifi.sta.config(cfg)
wifi.sta.connect()

DeviceId = "587667371"
ProductId = "325428"
AuthoInfo = "test"
host = "183.230.40.39"
port = 6002

url = 'http://api.heclouds.com/devices/'..DeviceId..'/datapoints?type=3'
headers = 'api-key:BO6XuBiKw07JRXakBNvn4JKX7MI=\r\n'

dht_pin = 5


timer = tmr.create()
function con()
    if wifi.sta.getip() == nil then
        print("coneting........")
    else
        timer:stop()
        print("success!~")
        gpio.write(2,gpio.HIGH)
        print(wifi.sta.getip())

        client_hum = mqtt.Client(DeviceId,120,ProductId,AuthoInfo)
        client_hum:connect(host,port,0,function(client)
        print("connect success!")
        end)

        function h()
        status,temp,humi,temp_dec, humi_dec = dht.read11(dht_pin)
        print("DHT Temperature:"..temp..";".."Humidity:"..humi)

		--代码如下:
		weather表用来存储数据流Temperature和Humidity
        weather = {}
        weather.Temperature = temp
        weather.Humidity = humi
		--使用pacall方法将weather表中的数据转换为sjson格式,返回状态state和weather的值weather_message
        state,weather_message = pcall(sjson.encode,weather)
        --内容主体(参照下边的图来理解):string.char()方法是将字符转化为一个对应的ascii码
        payload = string.char(3,0,string.len(weather_message))..weather_message
        --通过官网查询mqtt的推送方法 mqtt:publish(topic, payload, qos, retain[, function(client)])topic:订阅Field名称,payload:数据主体,qos:QoS等级(百度下),retain:保留标志(百度下),后边位回调函数
        client_hum:publish("$dp", payload, 0, 0, function(client)
            print("upload success!~")
        end)
         
        end
        
        tmr.create():alarm(1500,tmr.ALARM_AUTO,h)

    end
end

timer:alarm(1000,tmr.ALARM_AUTO,con)


关于几点说明:
1、pcall()方法:lua中pcall函数提供了一种安全的环境来运行函数,同时会捕获函数运行时的异常。pcall函数第一个返回值是函数的运行状态(true,false),第二个返回值是pcall中函数的返回值。参见博文
2、sjson格式:
在这里插入图片描述
3、payload(内容主体):
在这里插入图片描述
转换的sjson有四部分组成的:
在这里插入图片描述
Byte1(3)+ Byte2(0,也就是最低位)+ Byte3(string.len(weather_message),也就是最高位)+ 内容主体(weather_message)
payload = string.char(3,0,string.len(weather_message))…weather_message
4、mqtt推送方法:
在这里插入图片描述
topic:参见MQTT协议
payload:内容主体(参见上边内容)
在这里插入图片描述
function(client):回调函数

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值