108 lines
2.6 KiB
Lua
108 lines
2.6 KiB
Lua
local t = require("DS1820")
|
|
timing = 60000 -- Sending timer
|
|
srv = nil -- TCP client
|
|
uid = '' -- MAC UID
|
|
dhtpin_room = 1 -- DHT11 room pin
|
|
dhtpin_cellar = 2 -- DHT11 cellar pin
|
|
dhtpin_weather = 5 -- DHT11 weather pin
|
|
ds_pin = 6
|
|
|
|
local results = {} -- DS1822 results
|
|
|
|
-- Read DS1822
|
|
|
|
local function readout(temp)
|
|
for addr, temp in pairs(temp) do
|
|
local uid = string.format('%s',('%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X'):format(addr:byte(1,8)))
|
|
results[uid] = temp
|
|
print(uid,temp)
|
|
end
|
|
end
|
|
|
|
local function read_sensors()
|
|
t:read_temp(readout, ds_pin, t.C)
|
|
end
|
|
|
|
-- Read the DHT11 sensor
|
|
|
|
local function dht_read(dhtpin)
|
|
local status, temp, humi, temp_dec, humi_dec = dht.read(dhtpin)
|
|
if status == dht.OK then
|
|
print("DHT Temperature:"..temp..";".."Humidity:"..humi)
|
|
return {['temp'] = temp, ['humi'] = humi}
|
|
elseif status == dht.ERROR_CHECKSUM then
|
|
print( "DHT Checksum error." )
|
|
elseif status == dht.ERROR_TIMEOUT then
|
|
print( "DHT timed out." )
|
|
end
|
|
return {}
|
|
end
|
|
|
|
-- Data for TCP server
|
|
|
|
function data_out()
|
|
read_sensors()
|
|
local pack = {}
|
|
pack['id'] = uid
|
|
pack['room'] = dht_read(dhtpin_room)
|
|
pack['cellar'] = dht_read(dhtpin_cellar)
|
|
pack['weather'] = dht_read(dhtpin_weather)
|
|
pack['sensors'] = results
|
|
return encoder.toBase64(sjson.encode(pack))
|
|
end
|
|
|
|
-- Exchange data with server
|
|
|
|
local function send()
|
|
srv:connect(4999,"chan.ulgrad.ru")
|
|
srv:on("connection", function(sck, c)
|
|
print('connection')
|
|
sck:send(data_out().."\r\n")
|
|
end)
|
|
srv:on("disconnection", function(sck,c)
|
|
print('disconnection')
|
|
end)
|
|
end
|
|
|
|
-- On Internet connect
|
|
|
|
function on_connect()
|
|
-- Generate UID from MAC address
|
|
uid = string.gsub(wifi.ap.getmac(),':','')
|
|
print("Connected to wifi as: " .. wifi.sta.getip())
|
|
ssid,password,bssid_set,bssid = wifi.sta.getconfig()
|
|
sensor_start()
|
|
print(
|
|
"\nCurrent Station configuration:"
|
|
.."\nSSID : "..ssid
|
|
.."\nPassword : "..password
|
|
.."\nBSSID_set : "..bssid_set
|
|
.."\nBSSID: "..bssid
|
|
.."\nUID:"..uid
|
|
.."\nClient IP:"..wifi.sta.getip().."\n"
|
|
)
|
|
srv = net.createConnection(net.TCP, 0)
|
|
if srv then
|
|
print('TCP Connection start')
|
|
tcptimer:start()
|
|
else
|
|
print('Error connect to TCP')
|
|
end
|
|
end
|
|
|
|
-- Setup sensors
|
|
|
|
bme280.setup()
|
|
|
|
-- Setup timers
|
|
|
|
tcptimer = tmr.create()
|
|
tcptimer:register(timing, tmr.ALARM_AUTO,send)
|
|
|
|
inittimer = tmr.create()
|
|
inittimer:register(5000, tmr.ALARM_SINGLE, function()
|
|
enduser_setup.start('chan',on_connect)
|
|
end)
|
|
|
|
inittimer:start()
|