目的是用esp8266创建一个服务端,用来和前端交互,前端用htt或者scoket等形式向esp8266通信。esp8266通过解析传过来的数据,得到相关指令,控制硬件做出相关操作。
首先,在esp8266创建一个基于softap模式的局域网,然后创建一个service端。前端可以访问该服务。
代码如下:
wifi.setmode(wifi.SOFTAP)
apcfg={}
apcfg.ssid='Hellow8266'
apcfg.pwd='11223344'
wifi.ap.config(apcfg)
pin =1
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive",function(conn,payload)
print(payload)
local status, temp, humi , temp_dec, humi_dec = dht.read11(pin)
local html = string.format("HTTP/1.0200OK\r\n"
.."Content-Type: text/html\r\n"
.."Connection: Close\r\n\r\n"
.."<title>www</title>"
.."<h1>welcom</h1>"
.."<p>Temperature: "..temp.."."..temp_dec.."%</p>"
.."<p>Humidity: "..humi.."."..humi_dec.."%</p>"
)
conn:send(html)
end)
conn:on("sent",function(conn) conn:close() end)
end)