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. -- -- on publish message receive event
  12. -- m:on("message", function(client, topic, data)
  13. -- print(topic .. ":" )
  14. -- if data ~= nil then
  15. -- print(data)
  16. -- end
  17. -- end)
  18. -- Ice-boil calibration
  19. function calibrate(temp)
  20. local ReferenceLow = 0.01
  21. local ReferenceHigh = 100
  22. local ReferenceRange = ReferenceHigh - ReferenceLow
  23. local RawLow = TEMP_ICE
  24. local RawHigh = TEMP_BOIL
  25. local RawRange = RawHigh - RawLow
  26. local RawValue = temp
  27. local CorrectedValue = (((RawValue - RawLow) * ReferenceRange) / RawRange) + ReferenceLow
  28. if RawLow == nil or RawHigh == nil then
  29. return temp
  30. end
  31. return CorrectedValue
  32. end
  33. local ow_pin = TEMP_PIN
  34. ds18b20.setup(ow_pin)
  35. function ds_start_read()
  36. ds18b20.read(
  37. function(ind,rom,res,raw_temp,tdec,par)
  38. local mac = string.format("%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X",string.match(rom,"(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+)"))
  39. local temp = calibrate(raw_temp)
  40. print(ind,mac,res,temp,raw_temp)
  41. ok, json = pcall(sjson.encode, {rom=mac, res=res, temp=temp, raw=raw_temp})
  42. if ok then
  43. m:publish(MQTT_TOPIC, json, 0, 0, function(client) print("sent "..json.." to "..MQTT_TOPIC) 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. -- subscribe topic with qos = 0
  52. -- client:subscribe(MQTT_TOPIC, 0, function(client) print("subscribe success") end)
  53. -- publish a message with data = hello, QoS = 0, retain = 0
  54. -- client:publish("/topic", "hello", 0, 0, function(client) print("sent") end)
  55. -- start temp reading
  56. ds_start_read()
  57. tmr.create():alarm(TEMP_RATE, tmr.ALARM_AUTO, function(timer) ds_start_read() end)
  58. end
  59. function handle_mqtt_error(client, reason)
  60. tmr.create():alarm(10 * 1000, tmr.ALARM_SINGLE, do_mqtt_connect)
  61. end
  62. function do_mqtt_connect()
  63. m:connect(MQTT_SERVER, handle_mqtt_connected, handle_mqtt_error)
  64. end
  65. do_mqtt_connect()