app.route={}

function app.route.com(code,json)
    local data={}
    data.code=code
    data.data=json
    return sjson.encode(data)
end

--连接初始化，必须存在
function app.route.init(con,param)
    local sign={}
    sign.path=app.config.cloudPath
    local data={}
    data.type='dev'
    data.back='light'
    data.user=app.config.cloudUser
    data.pass=app.config.cloudPass
    data.devid=app.config.devid
    sign.data=data

    return sjson.encode(sign)
end

--连接初始化，必须存在
function app.route.regDev(code,json)
    local sign={}
    sign.path=app.config.cloudReg
    local data={}
    data.back='sign'
    data.name=app.config.name
    data.user=app.config.cloudUser
    data.pass=app.config.cloudPass
    data.devid=app.config.devid
    sign.data=data
    return sjson.encode(sign)
end

--注册设备后回调
function app.route.sign(param)
    if(param.code==0)then
        local obj={}
        obj.devmes="已注册，到服务器"
        app.global.update(obj)
        app.net.send(app.route.init())
    end
end

function app.route.light(param)
    local pin = 6 
    if(param ~= nil) then
        gpio.mode(pin,gpio.OUTPUT)
        if(param == 1) then
            gpio.write(pin,HIGH)
        else
            gpio.write(pin,gpio.LOW)
        end
        return
    end
    
    gpio.mode(pin,gpio.INPUT)
    if(gpio.read(pin)==0)then
        print(1,'set gpio')
        gpio.mode(pin,gpio.OUTPUT) 
        gpio.write(pin,gpio.HIGH)
    else
        print(2,'set gpio')
        gpio.mode(pin,gpio.OUTPUT) 
        gpio.write(pin,gpio.LOW)
    end
end

function app.route.onOff(param)
    if(param.data=='0') then
        app.route.light(gpio.HIGH)
    else
        app.route.light(gpio.LOW)
    end
end


function app.route.config(param)
    app.global.update(param)
    return app.route.com(0,'ok')
end

function app.route.nodeInfo(param)
    local json={}
    app.config.heap=node.heap()
    return app.route.com(0,app.config)
end

function app.route.restart(param)
    node.restart()
end

function app.route.webIndex(param)
    local url
    if(param ~= nil and param.type=='css')then
        url='@index.css'
    elseif(param ~= nil and param.type=='js')then
        url='@index.js'
    else
        url='@index.html'
    end
    
    return app.global.readFile(url)
end


function app.route.ato(param)
    local pin = 2
    if(type(param)=='number' and param%5==4)then
        gpio.mode(pin,gpio.OUTPUT)
        gpio.write(pin,gpio.HIGH)
        print('[notice]runing ato',param)
        tmr.create():alarm(3000, tmr.ALARM_SINGLE, function()
            gpio.write(pin,gpio.LOW)
            print('[notice]stop ato',param)
        end)
    end
end
