echo '' ;

ESP8266 NodeMCU Module – MQTT

Functions

  • mqtt.Client()  – Creates a MQTT client.
  • mqtt.client:close()  – Closes connection to the broker.
  • mqtt.client:connect() – Connects to the broker specified by the given host, port, and secure options.
  • mqtt.client:lwt( ) – Setup Last Will and Testament (optional).
  • mqtt.client:on()  – Registers a callback function for an event.
  • mqtt.client:publish()  – Publishes a message.
  • mqtt.client:subscribe()  – Subscribes to one or several topics.
  • mqtt.client:unsubscribe()  – Unsubscribes from one or several topics.

 

MQTT Example

  • MQTT subscribe and publish the data to
-- Required Modules :Mqtt,Wifi
-- https://www.aruneworld.com/
-- Tested By    : Arun(20170527)
-- Example Name : AEW_Mqtt.lua
---------------------------------------------------------------------------------
station_cfg={}
station_cfg.ssid= "ArunEworld" station_cfg.pwd= "ArunEworld.com"    --please change your SSID and Passworld

print("wifi init")
wifi.setmode(wifi.STATIONAP)
wifi.sta.config(station_cfg)
wifi.sta.connect()


--Initializing Mqtt
DEVICE_NAME     =   "ArunEworld-"..node.chipid()
PUBLISH_TOPIC   =   "ArunEworld/"..DEVICE_NAME.."-Result"
SUBSCRIBE_TOPIC =   "ArunEworld/"..DEVICE_NAME
CLIENT_ID       =   DEVICE_NAME
USERNAME        =   "username"              --  please change your username
PASSWORD        =   "Password"              --  please change your Password
HOSTNAME        =   "mqtt.aruneworld.com"   --  Please change your port
PORT            =   "Port_Number"                       --  Please change your port number

-- Mqtt Setup
m = mqtt.Client(CLIENT_ID, 120, USERNAME, PASSWORD, 0)
    m:connect(HOSTNAME, PORT, 0, function(conn) 
    m:publish(PUBLISH_TOPIC,DEVICE_NAME.." is Online", 1, 0, function(conn) end)
    m:subscribe(SUBSCRIBE_TOPIC, 1, function(conn)  end)
end)

--Mqtt Receive function
m:on("message", function(client, topic, payload)        
        if payload ~= nil then
            print(payload)
        else
            print("Mqtt Reccived nill payload message")
        end
    collectgarbage("collect")
end)

--Mqtt Send function
local function Send_MQTT(strings)
    m:publish(PUBLISH_TOPIC,strings, 1, 0, function(conn)   end)
end

--Wifi Event Monitoring
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T)
    print("\n\tSTA - CONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: "..T.BSSID.."\n\tChannel: "..T.channel)
end)

wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
    print("\n\tSTA - DISCONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: "..T.BSSID.."\n\treason: "..T.reason)
end)

wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
    print("\n\tSTA - GOT IP".."\n\tStation IP: "..T.IP.."\n\tSubnet mask: "..T.netmask.."\n\tGateway IP: "..T.gateway)
end)

 


 Read and Write files using MQTT

  • transfer files over mqtt
-- For More info :- https://www.aruneworld.com/ 
-- Tested By : Arun(20170527)
-- Required Modules : CJSON, FILE, MQTT, WiFi,

station_cfg={}
DEVICE_NAME = node.chipid()
station_cfg.ssid= "ArunEworld" station_cfg.pwd= "Arun"
PUBLISH_TOPIC = "MQTT_File_Ex_PUB"
SUBSCRIBE_TOPIC = "MQTT_File_Ex_SUB"
CLIENT_ID = DEVICE_NAME
USERNAME = ""
PASSWORD = ""
HOSTNAME = "iot.eclipse.org"
PORT = 1883

print("wifi init")
wifi.setmode(wifi.STATIONAP)
wifi.sta.config(station_cfg)
wifi.sta.connect()

-- test transfer files over mqtt.
m_dis={}            --Created the table and name is m_dis
function dispatch(m,t,pl)
    if pl~=nil and m_dis[t] then
        m_dis[t](m,pl)
    end
end

function pubfile(m,filename)
    file.close()
    file.open(filename)
    repeat
    local pl=file.read(1024)
    if pl then m:publish("/topic2",pl,0,0) end
    until not pl
    file.close()
end
-- payload(json): {"cmd":xxx,"content":xxx}
function topic1func(m,pl)
    print("get1: "..pl)
    local pack = cjson.decode(pl)
    if pack.content then
        if pack.cmd == "open" then file.open(pack.content,"w+")
        elseif pack.cmd == "write" then file.write(pack.content)
        elseif pack.cmd == "close" then file.close()
        elseif pack.cmd == "remove" then file.remove(pack.content)
        elseif pack.cmd == "run" then dofile(pack.content)
        elseif pack.cmd == "read" then pubfile(m, pack.content)
        end
    end
end

m_dis["/topic1"]=topic1func
-- Lua: mqtt.Client(clientid, keepalive, user, pass)
--m=mqtt.Client()
m = mqtt.Client(CLIENT_ID, 20, USERNAME, PASSWORD, 0)
m:on("connect",function(m) 
    print("connection "..node.heap()) 
    m:subscribe("/topic1",0,function(m) print("sub done") end)
    m:publish(PUBLISH_TOPIC,DEVICE_NAME.." is Live", 1, 0, function(m) print("[LOG]:- Mqtt "..DEVICE_NAME.." is Live in Online Mode") end)
    
    end )
m:on("offline", function(conn)
    print("disconnect to broker...")
    print(node.heap())
end)
m:on("message",dispatch )
-- Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
--m:connect(192.168.18.88,1883,0,1)
--host = "iot.eclipse.org"
m:connect(HOSTNAME,1883,0,1)

-- usage:
-- another client(pc) subscribe to /topic2, will receive the test.lua content.
-- and publish below message to /topic1
-- {"cmd":"open","content":"test.lua"}
-- {"cmd":"write","content":"print([[hello world]])\n"}
-- {"cmd":"write","content":"print(\"hello2 world2\")\n"}
-- {"cmd":"write","content":"test.lua"}
-- {"cmd":"run","content":"test.lua"}
-- {"cmd":"read","content":"test.lua"}

 


 

MQTT to cloud

-- test with cloudmqtt.com
m_dis={}
function dispatch(m,t,pl)
    if pl~=nil and m_dis[t] then
        m_dis[t](m,pl)
    end
end
function topic1func(m,pl)
    print("get1: "..pl)
end
function topic2func(m,pl)
    print("get2: "..pl)
end
m_dis["/topic1"]=topic1func
m_dis["/topic2"]=topic2func
-- Lua: mqtt.Client(clientid, keepalive, user, pass)
m=mqtt.Client("nodemcu1",60,"test","test123")
m:on("connect",function(m) 
    print("connection "..node.heap()) 
    m:subscribe("/topic1",0,function(m) print("sub done") end)
    m:subscribe("/topic2",0,function(m) print("sub done") end)
    m:publish("/topic1","hello",0,0) m:publish("/topic2","world",0,0)
    end )
m:on("offline", function(conn)
    print("disconnect to broker...")
    print(node.heap())
end)
m:on("message",dispatch )
-- Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
m:connect("m11.cloudmqtt.com",11214,0,1)
tmr.alarm(0,10000,1,function() local pl = "time: "..tmr.time() 
    m:publish("/topic1",pl,0,0)
    end)

 

 

 


Next :

Previous :


 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from ArunEworld

Subscribe now to keep reading and get access to the full archive.

Continue reading