本帖最后由 沙漠之痕 于 2018-11-7 12:48 编辑
1. 连接路由器,创建服务器监听8080端口 init.lua文件: tmr.alarm(0,5000,0,function() dofile("tcpserver.lua") end) init.lua文件结束 tcpserver.lua文件: wifi.setmode(wifi.STATIONAP) local stacfg = { ssid = "qqqqq", pwd = "11223344" } wifi.sta.config(stacfg) wifi.sta.autoconnect(1) local ClientSocket = nil Server = net.createServer(net.TCP,28800) Server:listen(8080,function(socket) ClientSocket=socket ClientSocket:on("receive",function(sck,data) uart.write(0,data) end) ClientSocket:on("disconnection",function() ClientSocket=nil print("Disconnec") end) end) printip = 0 wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED,function(T) printip = 0 end) wifi.eventmon.register(wifi.eventmon.STA_GOT_IP,function(T) if printip==0 then print("+IP: "..T.IP) end printip=1 end) tcpserver.lua文件结束 手机连接上路由器,并去连接模块开启的服务器,模块ip即为服务器ip通过串口已经打印出 通过手机客户端给模块服务器发送数据通过模块的串口输出 2. 通过手机发送”open”打开继电器;发送 “close”关闭继电器 init.lua文件 RELAY_Pin = 1 gpio.mode(RELAY_Pin,gpio.OUTPUT) gpio.write(RELAY_Pin,0) tmr.alarm(0,5000,0,function() dofile("tcpserver.lua") end) init.lua文件结束 tcpserver.lua文件: ServerReceData = "" ServerReceCnt = 0 ServerReceStat = false wifi.setmode(wifi.STATIONAP) local stacfg = { ssid = "qqqqq", pwd = "11223344" } wifi.sta.config(stacfg) wifi.sta.autoconnect(1) local ClientSocket = nil Server = net.createServer(net.TCP,28800) Server:listen(8080,function(socket) ClientSocket=socket ClientSocket:on("receive",function(sck,data) ServerReceData = ServerReceData..data ServerReceStat = true ServerReceCnt = 0 end) ClientSocket:on("disconnection",function() ClientSocket=nil print("Disconnec") end) end ) tmr.alarm(1,10,1,function() if ServerReceStat == true then ServerReceCnt = ServerReceCnt + 1 if ServerReceCnt >= 10 then if ServerReceData == "open" then gpio.write(RELAY_Pin,1) end if ServerReceData == "close" then gpio.write(RELAY_Pin,0) end uart.write(0,ServerReceData) ServerReceData = "" ServerReceCnt = 0 ServerReceStat = false end end end) ---------------Got IP ------------------- printip = 0 wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED,function(T) printip = 0 end) wifi.eventmon.register(wifi.eventmon.STA_GOT_IP,function(T) if printip==0 then print("+IP: "..T.IP) end printip=1 end) -------------END Got IP ------------------ tcpserver.lua文件结束
手机连接路由器并连接服务器
|