Quellcode durchsuchen

Initial version

Innocenty Enikeew vor 7 Jahren
Commit
697adfdfb2
3 geänderte Dateien mit 162 neuen und 0 gelöschten Zeilen
  1. 79 0
      application.lua
  2. 9 0
      credentials.lua
  3. 74 0
      init.lua

+ 79 - 0
application.lua

@@ -0,0 +1,79 @@
+-- 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)
+
+-- -- on publish message receive event
+-- m:on("message", function(client, topic, data)
+--   print(topic .. ":" )
+--   if data ~= nil then
+--     print(data)
+--   end
+-- 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
+
+local ow_pin = TEMP_PIN
+ds18b20.setup(ow_pin)
+
+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)
+         print(ind,mac,res,temp,raw_temp)
+         ok, json = pcall(sjson.encode, {rom=mac, res=res, temp=temp, raw=raw_temp})
+         if ok then
+            m:publish(MQTT_TOPIC, json, 0, 0, function(client) print("sent "..json.." to "..MQTT_TOPIC) end)
+         else
+            print("failed to encode!")
+         end
+    end,{});
+end
+
+function handle_mqtt_connected(client)
+  print("mqtt connected")
+  -- subscribe topic with qos = 0
+  -- client:subscribe(MQTT_TOPIC, 0, function(client) print("subscribe success") end)
+  -- publish a message with data = hello, QoS = 0, retain = 0
+  -- client:publish("/topic", "hello", 0, 0, function(client) print("sent") end)
+
+  -- start temp reading
+  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()

+ 9 - 0
credentials.lua

@@ -0,0 +1,9 @@
+SSID = "mms"
+PASSWORD = "9219402286"
+STATIC_IP = {ip = "192.168.1.41", netmask = "255.255.255.0", gateway = "192.168.1.1"}
+MQTT_SERVER = "192.168.1.11"
+MQTT_TOPIC = "sensors/esp/temp/balcony"
+TEMP_PIN = 3
+TEMP_RATE = 20 * 1000
+TEMP_BOIL = 100
+TEMP_ICE = 0.01

+ 74 - 0
init.lua

@@ -0,0 +1,74 @@
+-- load credentials, 'SSID' and 'PASSWORD' declared and initialize in there
+dofile("credentials.lua")
+
+function startup()
+    if file.open("init.lua") == nil then
+        print("init.lua deleted or renamed")
+    else
+        print("Running")
+        file.close("init.lua")
+        -- the actual application is stored in 'application.lua'
+        dofile("application.lua")
+    end
+end
+
+-- Define WiFi station event callbacks
+wifi_connect_event = function(T)
+  print("Connection to AP("..T.SSID..") established!")
+  print("Waiting for IP address...")
+  if disconnect_ct ~= nil then disconnect_ct = nil end
+end
+
+wifi_got_ip_event = function(T)
+  -- Note: Having an IP address does not mean there is internet access!
+  -- Internet connectivity can be determined with net.dns.resolve().
+  print("Wifi connection is ready! IP address is: "..T.IP)
+  print("Startup will resume momentarily, you have 3 seconds to abort.")
+  print("Waiting...")
+  tmr.create():alarm(3000, tmr.ALARM_SINGLE, startup)
+end
+
+wifi_disconnect_event = function(T)
+  if T.reason == wifi.eventmon.reason.ASSOC_LEAVE then
+    --the station has disassociated from a previously connected AP
+    return
+  end
+  -- total_tries: how many times the station will attempt to connect to the AP. Should consider AP reboot duration.
+  local total_tries = 75
+  print("\nWiFi connection to AP("..T.SSID..") has failed!")
+
+  --There are many possible disconnect reasons, the following iterates through
+  --the list and returns the string corresponding to the disconnect reason.
+  for key,val in pairs(wifi.eventmon.reason) do
+    if val == T.reason then
+      print("Disconnect reason: "..val.."("..key..")")
+      break
+    end
+  end
+
+  if disconnect_ct == nil then
+    disconnect_ct = 1
+  else
+    disconnect_ct = disconnect_ct + 1
+  end
+  if disconnect_ct < total_tries then
+    print("Retrying connection...(attempt "..(disconnect_ct+1).." of "..total_tries..")")
+  else
+    wifi.sta.disconnect()
+    print("Aborting connection to AP!")
+    disconnect_ct = nil
+  end
+end
+
+-- Register WiFi Station event callbacks
+wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, wifi_connect_event)
+wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, wifi_got_ip_event)
+wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, wifi_disconnect_event)
+
+print("Connecting to WiFi access point...")
+wifi.setmode(wifi.STATION)
+if STATIC_IP ~= nil then
+   wifi.sta.setip(STATIC_IP)
+end
+wifi.sta.config({ssid=SSID, pwd=PASSWORD})
+-- wifi.sta.connect() not necessary because config() uses auto-connect=true by default