Created
February 21, 2016 14:28
-
-
Save mattfoster/d8960091b31795d89a90 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
-- Config | |
SSID = "ssid_name" | |
PASS = "ssid_pass" | |
MQTT_TEMP_TOPIC = "/sensors/study/temperature" | |
MQTT_HOST = "server IP" | |
MQTT_PORT = 1883 | |
MQTT_CLIENT_ID = "esp2866_study" | |
MQTT_USER = "" | |
MQTT_PASS = "" | |
MQTT_RECONNECT = 1 | |
MQTT_SECURE = 0 | |
-- TMP102 settings | |
TMP102_ID = 0 | |
TMP102_SDA = 6 | |
TMP102_SCL = 7 | |
-- Allow correcting temperatures by subtracting this | |
TMP102_BIAS = 0 | |
-- Number of seconds to wait for a wifi connection before restarting | |
MAX_RETRIES = 20 | |
-- Measurement interval (ms) | |
TEMP_INTERVAL = 10000 | |
function wifi_connect(ssid, pass) | |
wifi.setmode(wifi.STATION) | |
wifi.sta.config(ssid, pass) | |
local wifi_count = 0 | |
tmr.alarm(0, 1000, 1, function() | |
wifi_status = wifi.sta.status() | |
if wifi_status ~= 5 then | |
wifi_count = wifi_count + 1 | |
if wifi_count >= MAX_RETRIES then | |
print("Failed to connect. Restarting") | |
node.restart() | |
end | |
print("Not yet connected.") | |
else | |
ip, mask, gateway = wifi.sta.getip() | |
print("Connected") | |
print("IP address: ", ip) | |
print("Netmask: ", mask) | |
print("Gateway: ", gateway) | |
tmr.stop(0) | |
mqtt_setup() | |
end | |
end) -- end of alarm function | |
end | |
function mqtt_setup() | |
local mqtt_connection = 0 | |
-- Connect to the MQTT broker | |
mqtt = mqtt.Client(MQTT_CLIENT_ID, 120, MQTT_USER, MQTT_PASS) | |
mqtt:connect(MQTT_HOST, MQTT_PORT, MQTT_SECURE, MQTT_RECONNECT) | |
mqtt:on("connect", function(client) | |
print("Connected to MQTT server") | |
mqtt_connection = 1 | |
-- Load the TMP102 module | |
tmp102=dofile("tmp102.lua") | |
tmp102.begin(TMP102_ID, TMP102_SDA, TMP102_SCL) | |
tmr.alarm(0, TEMP_INTERVAL, 1, function() | |
temp=tmp102.celcius() - TMP102_BIAS | |
print("Read temperature from TMP102: ", temp) | |
mqtt:publish(MQTT_TEMP_TOPIC, temp, 0, 0) | |
end) | |
end) | |
-- TODO: reconnection logic if auto-reconnect fails | |
mqtt:on("offline", function(client) | |
print("Lost connection to MQTT server") | |
mqtt_connection = 0 | |
end) | |
end | |
function main() | |
-- Connect to the network | |
wifi_connect(SSID, PASS) | |
end | |
-- Run the main function | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment