Skip to content

Instantly share code, notes, and snippets.

@Elwell
Created September 6, 2015 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Elwell/70642753a73895727376 to your computer and use it in GitHub Desktop.
Save Elwell/70642753a73895727376 to your computer and use it in GitHub Desktop.
ESP-01 temp/humidity publishing
if wifi.sta.status() ~= 5 then tmr.alarm(6, 10000,0, function(d) dofile('init.lua') end) return end
if wifi.sta.status() == 5 then dofile('pub.lua') return end
ID = 'ESP-'..node.chipid()
m = mqtt.Client(ID,90,'' ,'')
-- setup Last Will and Testament (optional)
m:lwt("status/"..ID, "offline", 0, 0)
m:on("connect", function(con) print ("connected") end)
m:on("offline", function(con) print ("offline") end)
-- on publish message receive event
m:on("message", function(conn, topic, data)
print(topic .. ":" )
if data ~= nil then
print(data)
end
end)
function readpub ()
status,temp,humi,temp_decimial,humi_decimial = dht.read(4)
if( status == dht.OK ) then
jstr = '{ "temp": '..temp..', "humidity": '..humi..' }'
-- print("DHT Temperature:"..temp..";".."Humidity:"..humi.."JSON:"..jstr)
m:publish("sensors/"..ID.."/json",jstr,0,0, function(conn) print(jstr) end)
elseif( status == dht.ERROR_CHECKSUM ) then
print( "DHT Checksum error." );
elseif( status == dht.ERROR_TIMEOUT ) then
print( "DHT Time out." );
end
end
m:connect("10.1.1.251", 1883, 0, function(conn) print("connected") end)
-- start timer to read temp/hum and publish
tmr.alarm(0,5000,1,readpub)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment