local tmr = tmr local wifi = wifi local sta = wifi.sta local eventmon = wifi.eventmon local function Log (message, ...) if #arg > 0 then message = message:format(unpack(arg)) end print (("%.6f %s"):format (tmr.now()/1000000, message)) end local ip = "192.168.2.73" -- my IP (esp-07i) local gateway = "192.168.2.7" -- server IP local netmask = "255.255.255.0" local startup_delay = 50 -- ms local sleep_time = 2 -- seconds local retry_max = 1 local busy_time = 1000 -- millis local timeout = tmr.create() local function dosleep() Log("deep sleep %ss\n", sleep_time) node.dsleep (sleep_time*1000000, 1, 1) -- wakeup with WiFi, sleep immediately end local function have_connection() Log("have connection sta.status=%d sta.getip=%s/%s", sta.status(), sta.getip()) dosleep() end local retry_count = 0 local function retry() if retry_count >= retry_max then Log ("retry failed") dosleep() return end retry_count = retry_count + 1 Log ("retry %d", retry_count) end local function delay(ms) Log("busy delay %dms", ms) tmr.delay(ms*1000) Log("delay done") end local function wifi_setup() sta.setip({ip=ip, netmask=netmask, gateway=gateway}) Log("sta.status=%d sta.getip=%s/%s", sta.status(), sta.getip()) end local function dowifi() delay(busy_time) Log ("registering eventmons") eventmon.register(eventmon.STA_GOT_IP, function(T) Log("STA_GOT_IP") have_connection() end) eventmon.register(eventmon.STA_CONNECTED, function(T) Log("STA_CONNECTED") end) eventmon.register(eventmon.STA_DISCONNECTED, function(T) Log("DISCONNECTED reason %d", T.reason) retry() end) eventmon.register(eventmon.STA_AUTHMODE_CHANGE, function(T) Log("AUTHMODE_CHANGE") end) -- this is not expected - we do not use dhcp eventmon.register(eventmon.STA_DHCP_TIMEOUT, function(T) Log("STA_DHCP_TIMEOUT") retry() end) -- in case we were too late and missed the STA_GOT_IP event if wifi.STA_GOTIP == sta.status() then Log ("already connected") have_connection() return end end local function show_reason() local _, reset_reason, EXCCAUSE, EPC1, EPC2, EPC3, EXCVADDR, depc = node.bootreason() if (reset_reason ~= 0 and reset_reason ~= 5 and reset_reason ~= 6) then if (reset_reason == 2) then print(string.format("\treset_reason:%i EXCCAUSE:%i EPC1:%X EPC2:%X EPC3:%X EXCVADDR:%X DEPC:%i", reset_reason, EXCCAUSE, EPC1, EPC2, EPC3, EXCVADDR, depc)) else print(string.format("\treset_reason:%i", reset_reason)) end end end local magic_pin = 1 -- gpio5 or D1 gpio.mode (magic_pin, gpio.INPUT, gpio.PULLUP) if 0 == gpio.read (magic_pin) then Log ("aborting by magic") else show_reason() wifi_setup() Log ("startup delayed %dms", startup_delay) timeout:alarm(startup_delay, tmr.ALARM_SINGLE, dowifi) end