application.lua 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. -- init mqtt client without logins, keepalive timer 120s
  2. m = mqtt.Client("esp", 120)
  3. -- init mqtt client with logins, keepalive timer 120sec
  4. --m = mqtt.Client("", 120, "user", "password")
  5. -- setup Last Will and Testament (optional)
  6. -- Broker will publish a message with qos = 0, retain = 0, data = "offline"
  7. -- to topic "/lwt" if client don't send keepalive packet
  8. --m:lwt("/lwt", "offline", 0, 0)
  9. m:on("connect", function(client) print ("connected") end)
  10. m:on("offline", function(client) print ("offline") end)
  11. -- Ice-boil calibration
  12. -- function calibrate(temp)
  13. -- local ReferenceLow = 0.01
  14. -- local ReferenceHigh = 100
  15. -- local ReferenceRange = ReferenceHigh - ReferenceLow
  16. -- local RawLow = TEMP_ICE
  17. -- local RawHigh = TEMP_BOIL
  18. -- local RawRange = RawHigh - RawLow
  19. -- local RawValue = temp
  20. -- local CorrectedValue = (((RawValue - RawLow) * ReferenceRange) / RawRange) + ReferenceLow
  21. -- if RawLow == nil or RawHigh == nil then
  22. -- return temp
  23. -- end
  24. -- return CorrectedValue
  25. -- end
  26. ds_read_counter = 0
  27. function ds_start_read()
  28. ds18b20.read(
  29. function(ind,rom,res,raw_temp,tdec,par)
  30. local mac = string.format("%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X",string.match(rom,"(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+)"))
  31. --local temp = calibrate(raw_temp)
  32. local temp = raw_temp
  33. print(ind,mac,res,temp,raw_temp)
  34. ok, json = pcall(sjson.encode, {rom=mac, res=res, temp=temp, raw=raw_temp, cnt=ds_read_counter})
  35. if ok then
  36. m:publish(MQTT_TOPIC, json, 0, 0, function(client)
  37. print("sent "..json.." to "..MQTT_TOPIC)
  38. ds_read_counter = ds_read_counter + 1
  39. if file.open("counter.txt", "w") then
  40. file.write(ds_read_counter)
  41. file.close()
  42. end
  43. end)
  44. else
  45. print("failed to encode!")
  46. end
  47. end,{});
  48. end
  49. function handle_mqtt_connected(client)
  50. print("mqtt connected")
  51. -- read last counter
  52. if file.open("counter.txt", "r") then
  53. ds_read_counter = file.read()
  54. file.close()
  55. end
  56. -- start temp reading
  57. ds18b20.setup(TEMP_PIN)
  58. ds_start_read()
  59. tmr.create():alarm(TEMP_RATE, tmr.ALARM_AUTO, function(timer) ds_start_read() end)
  60. end
  61. function handle_mqtt_error(client, reason)
  62. tmr.create():alarm(10 * 1000, tmr.ALARM_SINGLE, do_mqtt_connect)
  63. end
  64. function do_mqtt_connect()
  65. m:connect(MQTT_SERVER, handle_mqtt_connected, handle_mqtt_error)
  66. end
  67. do_mqtt_connect()