2017年5月24日 星期三

NodeMcu (1) - Mqtt

By using Lua, it is surprisingly simple to program the NodeMcu (i.e. ESP8266) to connect to a MQTT broker. Here I write a simple lua on NodeMcu, it will
1. connect to a home wifi router
2. connect to a mqtt broker server
3. subscribe to a topic
4. when a message is received, parse the message then turn on/off a LED.

Wifi router

  About the wifi router,  I just use WPA2, an 2.4GHz wifi router.

Mqtt broker

  For the Mqtt broker, you may use "test.mosquitto.org", of course you can setup your own(see my previous post).

Hardware Connection

  The NodeMCU that I use is just a popular one (using CH385 as the USB-to-Uart bridge), make sure you have install the USB-UART driver. Also install the popular nodcmcu development tools ESPlorer.
  I connect a LED to to GPIO0 (marked as D0 on PCB), a 100ohm resistor is used to limit the current draw from GPIO pin. According to the ESP8266 datasheet, the maximum GPIO output current is only 12mA, if no resistor is used, just connect a LED to GPIO and ground directly, I'm afraid it may damage the GPIO, I haven't try, I also don't suggest your try...
   Anyway, see the connection picture below, quite simple.


















Source code

  The code is quite strange forward, it will do the following
  1. Setup the wifi as station mode and connect the the router
  2. Repeat to get IP until a valid IP is obtained.
  3. Connect to the Mqtt broker (test.mosquitto.org)
  4. Once the Mqtt broker is connected, subscribed to the topic "wing"
  5. Every time a message is received, then parse the message. If the first character of the message is "0", then set the GPIO0 to low, otherwise set to high. (so as to turn on/off a LED)

wifi.setmode(wifi.STATION)
wifi.sta.config("YOUR_SSID","YOUR_PASSWORD")
wifi.sta.connect()

tmr.alarm(0, 1000, 1, function()
if wifi.sta.getip() == nil then
    print("Connecting")
else 
    print('ip:',wifi.sta.getip())
    tmr.stop(0)
end
end)

print ("start mqtt")
m = mqtt.Client("wingtest",120,"","",1)
m:connect("test.mosquitto.org", "1883", 0)

m:on("connect", function(con) print ("connected") 
    m:subscribe("wing",0)
end)

m:on("offline", function(con) print ("offline") end)

m:on("message", function(conn, topic, data)
    print (topic .. ":")
    print("message=>", data)
    print (string.byte(data,1))
--    print (string.byte(data,2))

    pin=0
    gpio.mode(pin, gpio.OUTPUT)

    if string.byte(data,1) == 48 then
        print ("LOW")
        gpio.write(pin, gpio.LOW)
    else    
        print ("HIGH")
        gpio.write(pin, gpio.HIGH)
    end
end)
 

沒有留言:

張貼留言