おもちゃ、家電、もろもろの修理の足跡と備忘録

色々と忘れるので、趣味のメモ

ESP8266DEVkit, nodeMCU, LUAで温度と気圧をInternetで送る(software編5-souce)

2020-02-09 12:05:51 | ESP8266DEVkitで遊ぶ
Luaで書いた、NodeMCU用のsource codeです。
 あちこちの先人達の知恵を頂いて作りました。とりあえず動いておりますがソフトは素人なので、try and errorの結果のcodeです。deep sleepは使っていません。実際のpasswordやtest用のcodeを消して、commentを入れました。
 これを動かすハードウェアについては、前の記載の通りです。
プログラムをコピペするとindentなどが飛んでしまうので、見ずらいですが、ご参考までに。
2020/2/9

-----------------------------------------------------------
-- Send Baro and Temp with NodeMCU over wifi connection using mqtt
-- writen in lua language.
-- tomoharika 2020/2/9 last update..
-----------------------------------------------------------
-- Connection:
-- [mqtt_server]--(wifi)--[NodeMCU]--(i2c)--[bmp280]
--
-- It will send status and messages on your serial line.
-- If it meets some errors, NodeMCU will restart from
-- begining of the source again.
-- So you can find the status by checking the access LED
-- on your NodeMCU, many flushes will be occured error
-- somewhere. Check the serial messages.
-- It goes no error, the access LED flushes every
-- main_loop_interval.
-----------------------------------------------------------

-- initial setting..
alt=50

--for i2c
sda=2 ---D2, GPIO04
scl=1 ---D1, GPIO05
--for main measurement loop timer
main_loop_interval = 300 --[sec]

--set your mqtt server address
mqtt_server_address = "aa.bb.cc.dd"

--for access LED indicator
ledpin = 0 --for D4

--for wifi retry counter
error_count = 0
error_max = 4

--set wifi environment
station_cfg.ssid="set_your_wifi_ssid"
station_cfg.pwd="set_your_wifi_password"

-----------------------------------------------------------------------------
m = mqtt.Client(node.chipid(), 120) -- clientID, keepalive, username, password, cleansession, max_message_length)

m:lwt("/lwt", "offline", 0, 0)
m:on("connect", function(client) print ("connected") end)
m:on("offline", function(client) print ("offline")
print("Restart..")
node.restart()
end)
m:on("message", function(client, topic, data)
print(topic .. ":" )
if data ~= nil then
print(data)
end
end)

-- on publish overflow receive event
m:on("overflow", function(client, topic, data)
print(topic .. " partial overflowed message: " .. data )
end)

function mqtt_loop()
gpio.write(ledpin, gpio.LOW)
P = bme280.baro()
T = bme280.temp()
print(string.format("QFE=%d.%03d Temp=%d.%02d", P/1000, P%1000, T/100, T%100))
m:publish("room1/temp", T/100, 0, 0, function(client) print("sent") end)
m:publish("room1/baro", P/1000, 0, 0, function(client) print("sent") end)
gpio.write(ledpin, gpio.HIGH)
mqtt_timer:start()

end
-----------------------------------------------------------------------------
--when wifi connected..
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T)
print("\n\tSTA - CONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: "..
T.BSSID.."\n\tChannel: "..T.channel.."\n")
wifi_Up = 1
wifi_timer:start()
end)

--when wifi disconnected..
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
print("\n\tSTA - DISCONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: "..
T.BSSID.."\n\tReasone: "..T.reason.."\n")
wifi_Up = 0
wifi_wait_ip()
end)

--when get ip address over the wifi
function wifi_wait_ip()
if wifi.sta.getip()== nil then
print("IP unavailable, Waiting.", error_count)
if error_count > error_max then
print("Error_max exceeded. Wifi reconnecting.")
error_count = 0
wifi.sta.connect()
else
error_count = error_count + 1
end
wifi_timer:start()
else
wifi_timer:stop()
print("\n====================================")
print("ESP8266 mode is: " .. wifi.getmode())
print("MAC address is: " .. wifi.ap.getmac())
print("IP is "..wifi.sta.getip())
print("====================================")
error_count = 0

--after getting ip address over the wifi, then connecting to mqtt server
print("Connecting to Mqtt server with ".. mqtt_server_address )
m:connect( mqtt_server_address, 1883, 0, function(client)
print("Connected to Mqtt server @"..mqtt_server_address)
mqtt_loop()
end,
function(client, reason)
print("Mqtt failed. reason: " .. reason)
print("Restart..")
node.restart()
end)
end
end
--------------------------------------------------------------------------------
-- Start main routine here...
--------------------------------------------------------------------------------
print("### Start Measurement at every "..main_loop_interval.."[sec] ###")

-- for access indicater
gpio.mode(ledpin, gpio.OUTPUT)
gpio.write(ledpin, gpio.HIGH)

-- i2c initializing
print("i2c initializing.")
if i2c.setup(0,sda,scl,i2c.SLOW) == 0 then
print("i2c initializing error. Check i2c connection. Restart.")
node.restart()
end

-- bmp280 initializing
print("bme280 initializing.")
if bme280.setup() == nil then
print("BME/P280 initializing error. Restart.")
node.restart()
end

-- wifi initializing
print("Wifi initializing.")
wifi.setmode(wifi.STATION)
station_cfg={}
-- station_cfg.ssid="xxxxxx" -> set at top of this source program..
-- station_cfg.pwd="xxxxxx" -> set at top of this source program..
station_cfg.auto=false -- true for wifi auto connect mode
station_cfg.save=false
wifi.sta.config(station_cfg)
wifi.sta.connect()
print("Connecting to wifi.")

-- ip connection timer set
wifi_timer = tmr.create()
wifi_timer:register( 3*1000, tmr.ALARM_SEMI, wifi_wait_ip)

-- mqtt connection timer set
mqtt_timer = tmr.create()
mqtt_timer:register( main_loop_interval * 1000, tmr.ALARM_SEMI, mqtt_loop )

wifi_timer:start()
-- end of program lua..



最新の画像もっと見る

コメントを投稿