local dst = require("ds18b20")
timing = 900000 -- Sending timer
local srv = nil -- TCP client
local uid = '' -- MAC UID
local dhtpin_room = 6 -- DHT11 room pin
local dhtpin_cellar = 1 -- DHT11 cellar pin
local dhtpin_weather = 2 -- DHT11 weather pin
local ds_pin = 7

local results = {} -- DS1822 results

-- Read DS1822

local function readout(temp)	
    if dst.sens then
        print("Total number of DS18B20 sensors: ".. #dst.sens)
        for i, s in ipairs(dst.sens) do
            print(string.format("  sensor #%d address: %s%s",  i, ('%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X'):format(s:byte(1,8)), s:byte(9) == 1 and " (parasite)" or ""))
        end
    else
        print('No sensors')
    end
	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()
    dst:read_temp(readout, ds_pin, dst.C)
end

-- Read the DHT11 sensor

local function dht_read(dhtpin)
	local status, temp, humi, temp_dec, humi_dec = dht.read11(dhtpin)
	if status == dht.OK then
		print("DHT Temperature:"..temp..";".."Humidity:"..humi.." Pin:"..dhtpin)
		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

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

function connectwifi()
    if wifi.sta.getip() == nil then
        print("Connect to Wi-fi.")
    else
        print("Success")
        print("IP: " .. wifi.sta.getip())
        wifitimer:stop()
        uid = string.gsub(wifi.ap.getmac(),':','')
        srv = net.createConnection(net.TCP, 0)    
		if srv then 
			print('TCP Connection start')       
			tcptimer:start()       
		else 
			print('Error connect to TCP') 
		end
    end
end

wifi.setmode(wifi.STATION)

dst:enable_debug()

station_cfg = {}
station_cfg.ssid = "ASUS"
station_cfg.pwd = "89648566170"
station_cfg.save = true

wifi.sta.config(station_cfg)

-- Setup timers

tcptimer = tmr.create()
tcptimer:register(timing, tmr.ALARM_AUTO,send)

wifitimer = tmr.create()
wifitimer:register(1000, tmr.ALARM_AUTO,connectwifi)

wifitimer:start()
