对接天猫精灵(11)终端编程

init.lua

--init.lua
print("set up wifi mode")
wifi.setmode(wifi.STATION)

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

wifi.sta.config(station_cfg);

wifi.sta.connect()
tmr.alarm(1, 1000, 1, function()
    if wifi.sta.getip() == nil then
        print("IP unavaiable, Waiting...")
    else
        tmr.stop(1)
        print("Config done, IP is" ..wifi.sta.getip())
        dofile("httpclick.lua"); --调用其他的脚本文件
    end
end)

httpclick.lua

--httpclick.lua
lightdata = "turn_on"
lightvalue = -1
pwm.setup(4, 500, 0)
pwm.start(4)
tmr.alarm(2, 1000, 1, function()
    str = string.format("", lightdata, lightvalue)
    --print(str)
    http.get(str, nil, function(code, data)
        if(code < 0) then
            print("HTTP request failed")
        else
            --
            print(code, data)
            t = sjson.decode(data)

            if(t["entity_id"] == "light.gateway_light_...") then
                if t["data"] == "turn_on" then
                    pwm.setduty(4, 0)
                    -- gpio.write(pin, gpio.LOW)
                elseif t["data"] == "turn_off" then
                    pwm.setduty(4, 1023)
                elseif t["data"] == "set_bright" then
                    lightvalue = math.ceil(t["value"]*10.24)
                    pwm.setduty(, 1024-lightvalue)
                    --pwm.setduty(4, 500)
                    --gpio.write(pin, gpio.HIGH)
                else
                end
                lightdata = t["data"]
                lightvalue = t["value"]
            end
        end
    end)
end)

你可能感兴趣的:(物联网)