Skip to content

Instantly share code, notes, and snippets.

@zerog2k
Created July 23, 2015 14:21
Show Gist options
  • Save zerog2k/696630ad8b63771ec0c9 to your computer and use it in GitHub Desktop.
Save zerog2k/696630ad8b63771ec0c9 to your computer and use it in GitHub Desktop.
-- based upon work by rutierut and MikeV
-- control gpio pin from mq
wifiname = "MYWIFINET"
wifipass = "MYWIFIPASS"
broker = "BROKERIP" -- IP or hostname of MQTT broker
mqttport = 1883 -- MQTT port (default 1883)
mqtttopic = "switch1"
userID = "" -- username for authentication if required
userPWD = "" -- user password if needed for security
clientID = "ESP1" -- Device ID
pin = 8 -- GPIO15 = 8
gpio.mode(pin, gpio.OUTPUT)
connected = 0 -- mq connected
ready = 0 -- wifi ready
-- Wifi credentials
wifi.setmode(wifi.STATION)
wifi.sta.config(wifiname, wifipass)
wifi.sta.connect()
mq = mqtt.Client(clientID, 15)
function mqtt_start()
if ready == 1 and connected ~= 1 then
mq:connect( broker , mqttport, 0, function(conn)
print("Connected to MQTT: " .. broker .. ":" .. mqttport .." as " .. clientID )
connected = 1
end)
end
end
function mqtt_action(conn, topic, input)
print(input)
if input == "ON" then
gpio.write(pin, gpio.HIGH)
elseif input == "OFF" then
gpio.write(pin, gpio.LOW)
else
print('ignored message')
end
end
function mqtt_sub()
if connected == 1 then
mq:publish(mqtttopic, clientID .. " connected", 0, 0,
function(conn) print("sent connected msg") end)
mq:subscribe(mqtttopic, 0, function(conn)
print('Subscribed to topic: ' .. mqtttopic)
end)
print("setting up message callback")
mq:on("message", mqtt_action)
tmr.stop(2)
end
end
function wifi_watch ()
status = wifi.sta.status()
if status == 5 and connected == 0 then
print("connected to wifi.")
ready = 1
elseif status < 5 then
ready = 0
if status == 1 then
if connected == 0 then
print('connecting to wifi...')
else
print("reconnecting to wifi...")
wifi.sta.connect()
end
end
end
end
function mqtt_heartbeat()
if connected == 1 then
mq:publish(mqtttopic, clientID .. " connected", 0, 0)
end
end
tmr.alarm(0, 1000, 1, wifi_watch)
tmr.alarm(1, 1111, 1, mqtt_start)
tmr.alarm(2, 1222, 1, mqtt_sub)
@marcelstoer
Copy link

That's a really nice skeleton, thanks. IMO it's only missing something like the following:

mq:on("offline", function(connection)
  print("MQTT: offline")
  mqttConnected = 0
end)

That would allow you to work around the heartbeat.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment