Created
December 22, 2015 06:05
-
-
Save rock3m/04623408ab1730c29d35 to your computer and use it in GitHub Desktop.
Lua script for Building a kid’s sleep training clock using NodeMCU and Parse (Prototype)
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
function changeLED(on) | |
pin = 1 | |
gpio.mode(pin,gpio.OUTPUT) | |
if on == true | |
then gpio.write(pin,gpio.HIGH) end | |
if on == false | |
then gpio.write(pin,gpio.LOW) end | |
end | |
changeLED(false) | |
--- Config | |
SSID = "WIFI_NAME" | |
PASSWORD = "WIFI_PASSWORD" | |
TIMEOUT = 30000000 -- 30s | |
--- Station modes | |
STAMODE = { | |
STATION_IDLE = 0, | |
STATION_CONNECTING = 1, | |
STATION_WRONG_PASSWORD = 2, | |
STATION_NO_AP_FOUND = 3, | |
STATION_CONNECT_FAIL = 4, | |
STATION_GOT_IP = 5 | |
} | |
--- Connect to WIFI and then periodically send data to ThingSpeak.com | |
function connect(timeout) | |
local time = tmr.now() | |
wifi.sta.connect() | |
-- Wait for IP address; check each 1000ms; timeout | |
tmr.alarm(1, 1000, 1, | |
function() | |
if wifi.sta.status() == STAMODE.STATION_GOT_IP then | |
tmr.stop(1) | |
print("Station: connected! IP: " .. wifi.sta.getip()) | |
checkSleepTimer() | |
tmr.alarm(0, 60000, 1, function() checkSleepTimer() end ) | |
else | |
if tmr.now() - time > timeout then | |
tmr.stop(1) | |
print("Timeout!") | |
if wifi.sta.status() == STAMODE.STATION_IDLE | |
then print("Station: idling") end | |
if wifi.sta.status() == STAMODE.STATION_CONNECTING | |
then print("Station: connecting") end | |
if wifi.sta.status() == STAMODE.STATION_WRONG_PASSWORD | |
then print("Station: wrong password") end | |
if wifi.sta.status() == STAMODE.STATION_NO_AP_FOUND | |
then print("Station: AP not found") end | |
if wifi.sta.status() == STAMODE.STATION_CONNECT_FAIL | |
then print("Station: connection failed") end | |
end | |
end | |
end) | |
end | |
--- Get temp and send data to thingspeak.com | |
function checkSleepTimer() | |
conn=net.createConnection(net.TCP, 0) | |
conn:on("receive", function(conn, payload) | |
print(payload) | |
if string.find(payload,"false") == nil | |
then changeLED(true) | |
else | |
changeLED(false) end | |
conn:close() | |
end) | |
conn:connect(80, "IP-YOUR-PARSE-APP") | |
conn:send("GET /is-timer-on HTTP/1.1\r\nHost: NAME-OF-YOUR-PARSE-APP.parseapp.com\r\n" | |
.. "Connection: keep-alive\r\nAccept: */*\r\n\r\n") | |
conn:on("disconnection", function(conn) | |
print("Got disconnection...") | |
end) | |
end | |
--- Main | |
print("Setting up Wi-Fi connection..") | |
wifi.setmode(wifi.STATION) | |
wifi.sta.config(SSID, PASSWORD) | |
connect(TIMEOUT) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment