Skip to content

Instantly share code, notes, and snippets.

@thomo
Last active October 16, 2017 13:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thomo/54daf529a2df41731444b75c54dad35a to your computer and use it in GitHub Desktop.
Save thomo/54daf529a2df41731444b75c54dad35a to your computer and use it in GitHub Desktop.
ESP-01 + DHT22: send temperature and humidity to influxdb
--
-- send DHT22 sensor values to influxdb database
--
LOCATION = "upstairs.bathroom"
-- #################################
INFLUXDB_HOST = "sun.thomo.de"
INFLUXDB_DB = "lhw5"
-- DHT_PIN = 3 -- GPIO0
DHT_PIN = 4 -- GPIO2
-- #################################
FLOAT_FIRMWARE = (1/3) > 0
CRLF = "\r\n"
wifi.setmode(wifi.STATION)
-- set wifi config via console
-- wifi.sta.config(WIFI_SSID,WIFI_PASSWORD)
wifi.sta.autoconnect(1)
function convertValue(val,val_dec)
local result
if FLOAT_FIRMWARE then
-- Float firmware using this example
result = string.format("%.1f",val)
else
-- Integer firmware using this example
result = string.format("%d.%03d",val,val_dec)
end
return result
end
function buildTempHumiDataLine(format, temp, humi)
return string.format(format, "temperature", temp)..
"\n"..
string.format(format, "humidity", humi)
end
function buildStatusLine(format, msg)
return string.format(format, "status", msg)
end
function getDHT22Content(location)
local result
local dataPattern = "%s"..
",location="..location..
",sensor=dht22"..
" value=%s"
local status, temp, humi, temp_dec, humi_dec = dht.read(DHT_PIN)
if status == dht.OK then
local tValue = convertValue(temp, temp_dec)
local hValue = convertValue(humi, humi_dec)
result = buildTempHumiDataLine(dataPattern, tValue, hValue)
elseif status == dht.ERROR_CHECKSUM then
result = buildStatusLine(dataPattern, "\"Checksum\",ec=1" )
elseif status == dht.ERROR_TIMEOUT then
result = buildStatusLine(dataPattern, "\"Timeout\",ec=2" )
else
result = buildStatusLine(dataPattern, "\"Unknown\",ec=999")
end
return result
end
function buildPostRequest(host, db, data)
return "POST /write?db="..db.." HTTP/1.1"..CRLF..
"Host: "..host..CRLF..
"Connection: close"..CRLF..
"Content-Type: application/x-www-form-urlencoded"..CRLF..
"Content-Length: "..string.len(data)..CRLF..
CRLF..
data
end
function sendData()
local content = getDHT22Content(LOCATION)
socket = net.createConnection(net.TCP, 0)
socket:on("receive",function(sck, c) print(c) end)
socket:connect(8086, INFLUXDB_HOST)
socket:on("connection", function(sck)
local post_request = buildPostRequest(INFLUXDB_HOST, INFLUXDB_DB, content)
sck:send(post_request)
end)
end
-- ###### MAIN #########
tmr.alarm(0, 20 * 1000, tmr.ALARM_AUTO, sendData)
@thomo
Copy link
Author

thomo commented Apr 18, 2016

fix to post string values in case of error

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