Created
July 23, 2015 14:21
-
-
Save zerog2k/696630ad8b63771ec0c9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That's a really nice skeleton, thanks. IMO it's only missing something like the following:
That would allow you to work around the heartbeat.