我用的是网上继电器模块上可以插8266-01S那种5V取电,自带5转3.3电源,模块是安装在顶灯里面的。原始开关还在,考虑到单火取电难度太大,主要是8266功率太大了。所以既能在开关处控制灯,也能智能音箱控制,前提是老式开关处于通电状态,不过这样一来就有个问题,要是中途停电了在来电不是要一直亮着了?当然,也可以把8266开关状态写入芯片,让再次启动时按上次状态开启,这样要是在灯亮着的情况下停电了,再来电要是没关老式开关灯就会一直亮着,我就用了个定时来控制继电器的通断。大概流程是:
老式开关:开-继电器通-10分钟后-继电器断
智能音箱控制继电器通与断
老式开关关:关-继电器断(废话,电源都没了)
智能音箱不能控制继电器也不能连接8266
init.lua代码
LED = 3 --8266-0s
gpio.mode(LED,gpio.OUTPUT)
gpio.write(LED, gpio.LOW)
d = 0
wifi.setmode(wifi.STATION)
station_cfg = {}
station_cfg.ssid = "WIFI"
station_cfg.pwd = "WIFI密码"
station_cfg.save = true
wifi.sta.config(station_cfg)
--链接wifi
--wifi.sta.connect()
--自动重连
wifi.sta.autoconnect(1)
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("kaiguan.lua")
end
end)
kaiguan.lua代码
DEVICEID = "贝壳物联设备ID"
APIKEY = "贝壳物联设备APIKEY"
UD = "贝壳物联用户ID"
host = "121.42.180.30" --连接服务器
port = 8181 -- 端口
local function run()
local cu = net.createConnection(net.TCP)
cu:connect(port, host)
s2 = {M="checkin",ID=DEVICEID,K=APIKEY}
ok, s1 = pcall(sjson.encode,s2)
cu:send(s1.."\n")
cu:on("receive", function(cu, c)
print(c)
r = sjson.decode(c)
--print(r.C)
--print(r.ID)
if r.M == "say" and r.ID == "UD" then
--print("ok0001")
if r.C == "play" then
gpio.write(LED, gpio.LOW)
d = 1
ok, played = pcall(sjson.encode, {M="say",ID=r.ID,C="LED turn on!"})
cu:send( played.."\n" )
--print(played.."\n")
end
if r.C == "stop" then
gpio.write(LED, gpio.HIGH)
d= 1
ok, stoped = pcall(sjson.encode, {M="say",ID=r.ID,C="LED turn off!"})
cu:send( stoped.."\n" )
--print(stoped.."\n")
end
end
end)
tmr.alarm(3, 50000, 1, function() -- 发送心跳包
s2 = {M="checkin",ID=DEVICEID,K=APIKEY}
ok, s1 = pcall(sjson.encode,s2)
cu:send(s1.."\n")
print(s1)
end)
end
tmr.alarm(2, 600000, 1, function() --重新上电后,定时关灯
if d == 0 then
gpio.write(LED, gpio.HIGH)
d=1
tmr.stop(2)
end
end)
run()
贝壳物联官网
然后在智能音箱里绑定贝壳物联账号,添加设备,OK
用贝壳的话,01S就够了,智能音箱只能控制一个IO口。