local json = require('cjson.safe')
local base64 = require('base64')
local guid = nil

-- Расшифровка сообщения от устройства

local function decode(rec) 
	rec = base64.decode(rec)
	ngx.log(ngx.INFO, rec) 
	return json.decode(rec)
end

local sock = assert(ngx.req.socket(true),'no socket')
sock:settimeout(10000)  -- one second timeout
local rec = sock:receive()  -- read a line from downstream


if rec == nil then 
	ngx.log(ngx.NOTICE, 'Empty data') 
	return ngx.exit(444)
else 
	rec = decode(rec)
	local res = db.add({['guid']=rec.id,['type']='bme',['alt']=rec.bme.alt,['temp']=rec.bme.temp,['press']=rec.bme.press})
	ngx.log(ngx.NOTICE, res) 
	res = db.add({['guid']=rec.id,['type']='dht',['humi']=rec.dht.humi,['temp']=rec.dht.temp})
	ngx.log(ngx.NOTICE, res) 
	res = db.add({['guid']=rec.id,['type']='solar',['uf']=rec.uf})
	ngx.log(ngx.NOTICE, res) 
	sock:send(base64.encode(json.encode(rec)))
end

