-- init mqtt client without logins, keepalive timer 120s m = mqtt.Client("esp", 120) -- init mqtt client with logins, keepalive timer 120sec --m = mqtt.Client("", 120, "user", "password") -- setup Last Will and Testament (optional) -- Broker will publish a message with qos = 0, retain = 0, data = "offline" -- to topic "/lwt" if client don't send keepalive packet --m:lwt("/lwt", "offline", 0, 0) m:on("connect", function(client) print ("connected") end) m:on("offline", function(client) print ("offline") end) -- Ice-boil calibration -- function calibrate(temp) -- local ReferenceLow = 0.01 -- local ReferenceHigh = 100 -- local ReferenceRange = ReferenceHigh - ReferenceLow -- local RawLow = TEMP_ICE -- local RawHigh = TEMP_BOIL -- local RawRange = RawHigh - RawLow -- local RawValue = temp -- local CorrectedValue = (((RawValue - RawLow) * ReferenceRange) / RawRange) + ReferenceLow -- if RawLow == nil or RawHigh == nil then -- return temp -- end -- return CorrectedValue -- end ds_read_counter = 0 function ds_start_read() ds18b20.read( function(ind,rom,res,raw_temp,tdec,par) local mac = string.format("%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X",string.match(rom,"(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+)")) --local temp = calibrate(raw_temp) local temp = raw_temp print(ind,mac,res,temp,raw_temp) ok, json = pcall(sjson.encode, {rom=mac, res=res, temp=temp, raw=raw_temp, cnt=ds_read_counter}) if ok then m:publish(MQTT_TOPIC, json, 0, 0, function(client) print("sent "..json.." to "..MQTT_TOPIC) ds_read_counter = ds_read_counter + 1 if file.open("counter.txt", "w") then file.write(ds_read_counter) file.close() end end) else print("failed to encode!") end end,{}); end function handle_mqtt_connected(client) print("mqtt connected") -- read last counter if file.open("counter.txt", "r") then ds_read_counter = file.read() file.close() end -- start temp reading ds18b20.setup(TEMP_PIN) ds_start_read() tmr.create():alarm(TEMP_RATE, tmr.ALARM_AUTO, function(timer) ds_start_read() end) end function handle_mqtt_error(client, reason) tmr.create():alarm(10 * 1000, tmr.ALARM_SINGLE, do_mqtt_connect) end function do_mqtt_connect() m:connect(MQTT_SERVER, handle_mqtt_connected, handle_mqtt_error) end do_mqtt_connect()