Skip to content

Instantly share code, notes, and snippets.

@sebastian-ruiz
Last active September 27, 2015 21:03
Show Gist options
  • Save sebastian-ruiz/a7c577f439f13d638125 to your computer and use it in GitHub Desktop.
Save sebastian-ruiz/a7c577f439f13d638125 to your computer and use it in GitHub Desktop.
Lua code for the ESP8266 to subscribe to a topic and output everything published to the topic. There is a bug where the ESP8266 will go offline after a few minutes if a lot of messages are being published to the topic.
-- Configuration to connect to the MQTT broker.
BROKER = "...com" -- Ip/hostname of MQTT broker
BRPORT = 12054 -- MQTT broker port
BRUSER = "..." -- If MQTT authenitcation is used then define the user
BRPWD = "..." -- The above user password
CLIENTID = "ESP8266-" .. node.chipid() -- The MQTT ID
-- MQTT topics to subscribe
topic = "/maxFrequency" -- Add/remove topics to the array
-- connect to the broker
function mqtt_connect()
print "Connecting to MQTT broker. Please wait..."
m = mqtt.Client( CLIENTID, 120, BRUSER, BRPWD)
m:connect( BROKER , BRPORT, 0, function(conn)
print("Connected to MQTT:" .. BROKER .. ":" .. BRPORT .." as " .. CLIENTID )
mqtt_sub() --run the subscription function
end)
end
mqtt_connect()
function mqtt_sub()
m:subscribe(topic, 0, function(conn)
print("Subscribing topic: " .. topic)
end)
run_main_prog()
end
--main program to run after the subscriptions are done
function run_main_prog()
print("Main program")
-- Callback to receive the subscribed topic messages.
m:on("message", function(conn, topic, data)
print(topic .. ":" )
if (data ~= nil ) then
print ( data )
end
end )
m:on("offline", function(con)
print ("offline")
print ("reconnecting...")
print(node.heap())
tmr.alarm(1, 10000, 0, function()
mqtt_connect()
end)
end)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment