Skip to content

Instantly share code, notes, and snippets.

@mikerodrigues
Created December 13, 2020 07:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikerodrigues/86dd370ca38ddc8d0743dd5c7b052edc to your computer and use it in GitHub Desktop.
Save mikerodrigues/86dd370ca38ddc8d0743dd5c7b052edc to your computer and use it in GitHub Desktop.
-- init.lua
------------
-- Altitude for calculating pressure
alt = 50 -- change this to your altitude in meters
-- Sensor Pins
sda, scl = 3, 4 -- leave these unless you're using different pins
print("Set up i2c...")
i2c.setup(0, sda, scl, i2c.SLOW)
print("Set up temp sensor...")
bme280.setup()
-- load params file if exists
if file.exists('eus_params.lua') then
print("Load saved EUS params...")
params = dofile('eus_params.lua')
end
-- https://stackoverflow.com/a/57299034 # Brian Tompsett, 7/13/2019
function round(number, precision)
local fmtStr = string.format('%%0.%sf',precision)
number = string.format(fmtStr,number)
return number
end
-- if the params file exists, and has wifi creds, connect using them
if params and params.wifi_ssid and params.wifi_password then
-- connect with cred ssaved in eus_params.lua
wifi.setmode(wifi.STATION)
print("Setting up wifi client...")
station_cfg={}
station_cfg.ssid=params.wifi_ssid
station_cfg.pwd=params.wifi_password
station_cfg.save=false -- we'll load it from this file, not flash
wifi.sta.config(station_cfg)
function callback()
print('wifi status ' .. wifi.sta.status())
end
wifi.sta.connect(callback)
else
-- start the EUS to get credentails
print("Initializing (EUS)...")
enduser_setup.start(
function()
print("EUS: Connected to wifi!")
end,
function(err, str)
print("EUS: Err #" .. err .. ": " .. str)
end
)
end
-- every 30 seconds, run update_sensors() function to get new values
update_timer = tmr.create():alarm( 30000, tmr.ALARM_AUTO, function() update_sensors() end )
-- data array that holds the current sensor values
data = {}
-- Webserver for retrieving sensor data. Runs on port 8080, returns the `data` object as JSON
srv = net.createServer(net.TCP, 30)
if srv then
srv:listen(8080,
function(conn)
conn:on("receive",function(conn,payload)
conn:send("HTTP/1.1 200 OK\n\n")
if string.match(payload, "GET") then
conn:send(sjson.encode(data))
end
if string.match(payload, "POST") then
conn:send("Reseting...")
file.remove("eus_params.lua")
end
conn:on("sent",function(conn) conn:close() end)
conn = nil
end)
end)
end
-- reads from the BME280 and updates the `data` array
function update_sensors()
local raw_data = {bme280.read(alt)}
data["temp_c"] = round(raw_data[1]/100.0, 2)
data["temp_f"] = round(((raw_data[1]/100.0) * 1.8) + 32, 2)
data["pressure_mmhg"] = round(raw_data[2] * 0.000750061683, 2)
data["humidity"] = round(raw_data[3]/1000.0, 2)
state = wifi.sta.getip()
end
update_sensors()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment