local SSID = "xxxxxxxxxxxxx" local SSID_PASSWORD = "xxxxxxxxxxxxx" local SIGNAL_MODE = wifi.PHYMODE_N MQTT_CLIENT_ID = node.chipid() MQTT_CLIENT_USER = "openhabian" MQTT_CLIENT_PASSWORD = "openhabian" MQTT_CLIENT_KEEPALIVE_TIME = 120 MQTT_BROKER = "192.168.1.6" MQTT_BROKER_PORT = 1883 MQTT_TOPIC_IN = "/esp8266_station123/in" -- commands MQTT_TOPIC_OUT = "/esp8266_station123/out" -- send values MQTT_BROKER_SECURE = 0 m = nil function wait_for_wifi_conn ( callback ) tmr.alarm (1, 1000, 1, function ( ) if wifi.sta.getip ( ) == nil then print ("Waiting for Wifi connection") else tmr.stop (1) print("\n====================================") print ("ESP8266 mode is: " .. wifi.getmode ( )) print ("The module MAC address is: " .. wifi.ap.getmac ( )) print ("Config done, IP is " .. wifi.sta.getip ( )) print("====================================") callback() end end) end function mqtt_handler() m = mqtt.Client(MQTT_CLIENT_ID, MQTT_CLIENT_KEEPALIVE_TIME, MQTT_CLIENT_USER, MQTT_CLIENT_PASSWORD) -- on publish message receive event m:on("message", function(client, topic, data) print("Received:" .. topic .. ":" ) if data ~= nil then --print(data) if data == "req" then sendValue() end end end) m:on("offline", function(m) print ("\n\nDisconnected from broker") print("Heap: ", node.heap()) end) m:connect(MQTT_BROKER, MQTT_BROKER_PORT, MQTT_BROKER_SECURE, function(client) print("connected") client:subscribe(MQTT_TOPIC_IN, 0, function(client) print("subscribe success") end) end, function(client, reason) print("failed reason: " .. reason) end) -- send all 30 sec tmr.alarm (2, 30*1000, tmr.ALARM_AUTO, function ( ) sendValue() end) end function sendValue() -- do stuff local temperature = 20 + math.random()*20 -- publish to broker on topic m:publish(MQTT_TOPIC_OUT, temperature, 0, 0, function(client) print("sent value="..temperature) end) end -- Configure the ESP as a station (client) wifi.setmode(wifi.STATION) wifi.setphymode(SIGNAL_MODE) wifi.sta.config {ssid=SSID, pwd=SSID_PASSWORD} wifi.sta.autoconnect(1) -- Hang out until we get a wifi connection before the httpd server is started. wait_for_wifi_conn( mqtt_handler )