nodeMCU-esp8266 连接阿里云物联网

折磨了三天了,终于将设备连接上阿里云平台了

1 刷固件库

基本上上一篇博客有讲到的,但是官方还是不定期的会更新固件库,导致很多API接口会发生变化,导致程序也需要更新,所以就将当前的固件库上传上来了esp8266wifi,iic,mqqt,adc固件库

2 连接阿里云

这边主要参考的是 【NodeMCU_LUA系列】NodeMCU连接阿里云这篇文章
需要修改的地方如下

nodeMCU-esp8266 连接阿里云物联网_第1张图片
nodeMCU-esp8266 连接阿里云物联网_第2张图片

wifitab={}
wifitab.ssid = "2.4G-603"      -- 自己的wifi名
wifitab.pwd = "CX071500"    --wifi密码
wifi.setmode(wifi.STATION)
wifi.sta.config(wifitab)
wifi.sta.connect()

timer1 = tmr.create()
timer2 = tmr.create()


ProductKey = "a1ti9YS1tqQ"        --阿里云三件值
DeviceName = "esp8266"
DeviceSecret = "kXlF1pZHdAUn1K2ixotJQXBsoy5l5h3y"
RegionId = "cn-shanghai"
ESP8266ClientId = 20200510

SubTopic="/a1ti9YS1tqQ/esp8266/user/get"             --需要下发和订阅的
Pubtopic="/sys/a1ti9YS1tqQ/esp8266/thing/event/property/post"

BrokerAddress = ProductKey..".iot-as-mqtt."..RegionId..".aliyuncs.com"
BrokerPort = 1883

HmacData = "clientId"..ESP8266ClientId.."deviceName"..DeviceName.."productKey"..ProductKey
MQTTClientId = ESP8266ClientId.."|securemode=3,signmethod=hmacsha1|"
MQTTUserName = DeviceName.."&"..ProductKey
MQTTPassword = crypto.toHex(crypto.hmac("sha1",HmacData,DeviceSecret))


function ConnectWifi()
    if wifi.sta.getip() == nil then
        print("Connecting...")
    else
        timer1:stop()
        print("Connect AP success")
        print(wifi.sta.getip())
        MQTTClient = mqtt.Client(MQTTClientId, 120, MQTTUserName, MQTTPassword, false)
        MQTTClient:connect(BrokerAddress, BrokerPort, 0, function(client)
        
            timer1:stop()
            print("MQTT connect success")

            MQTTClient:subscribe(SubTopic,0,function(conm)
                 print("MQTT subscribe success")
                 MQTTOn()
            end)

        end,

        function(client,reason)
            print("MQTT connect fail:"..reason)
        end)
    end
end

function MQTTOn()
    print("MQTT listen...")
    MQTTClient:on("message",function(client,topic,data)
        print("\n")
        print(topic..":")
        print(data)
        if data == "1" then
            MQTTPublish()
        end
    end)
end

function MQTTPublish()
    data = {}
    data.temp = 88.8
    data.humi = 88.8
    ok,json = pcall(sjson.encode, {params=data})
    MQTTClient:publish(Pubtopic, json, 0, 0, function(client)
        print("Publish weather success")
    end)
end

timer1:alarm(500, tmr.ALARM_AUTO, ConnectWifi)


你可能感兴趣的:(物联网)