使用nodemcu玩转物联网系列(七):notemcu通过mqtt协议“订阅功能”实现onenet设备的“开关”

一、实现订阅功能:
mqtt:subscribe(topic, qos[, function(client)])
二、实现触发功能:
mqtt:on(event, function(client[, topic[, message]]))
参数:
event 可以是“ connect”,“ suback”,“ unsuback”,“ puback”,“ message”,“ overflow”或“ offline”
function(client[, topic[, message]])回调函数。第一个参数是客户端。如果event为“ message”,则接收第二个和第三个参数主题和消息(字符串)。

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
--led灯连接在三脚
led_pin = 3
gpio.mode(dht_pin,gpio.INPUT)
gpio.mode(led_pin,gpio.OUTPUT)

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)
        
		--主要代码如下:
        client_hum:subscribe("$dp",0, function(client)
            print("subscribe success")
        end)
        --提前在onenet“应用管理”中新建on/off按钮
        client_hum:on("message", function(client,topic,message)
            print(message)
            if(message == "1") then
                gpio.write(led_pin,gpio.HIGH)
            else
                gpio.write(led_pin,gpio.LOW)
            end
        end)





--        http.post(url, headers, '{"DHT Temperature":'..temp..',"Humidity":'..humi..'}', function(code,date) 
--            if(code < 0) then
--                print("HTTP request failed")
--               else
--                print(code,date)
--            end
--            end)

        weather = {}
        weather.Temperature = temp
        weather.Humidity = humi
        state,weather_message = pcall(sjson.encode,weather)
        --mqtt:publish(topic, payload, qos, retain[, function(client)])
        payload = string.char(3,0,string.len(weather_message))..weather_message
        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)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值