https://www.zhihu.com/question/31579325html
uhttpd + Fast-CGI的开发要求:web
以“读取GET和POST数据”为例,所有使用默认值的状况下,如何具体实现:浏览器
第一步:使用“opkg update”更新“.ipk”包的源,而后使用“opkg install uhttpd”安装;缓存
第二步:使用“vi /etc/config/uhttpd”,在“config uhttpd main”下添加一行curl
list interpreter ".lua=/usr/bin/lua”
第三步:创建目录“/www/cgi-bin”,并增长“+x”属性;函数
root@OpenWrt:~# mkdir -p /www/cgi-bin/
root@OpenWrt:~# chmod +x /www/cgi-bin/
创建响应文件,并增长“+x”属性;测试
root@OpenWrt:~# touch /www/cgi-bin/webservice
root@OpenWrt:~# chmod +x /www/cgi-bin/webservice
将文件“/www/cgi-bin/webservice”内容修改成:ui
#!/usr/bin/lua
local WebService = require 'WebService'
WebService.Run()
第四步:创建Lua模块文件(再也不要求“+x”属性),并读取参数,返回响应:lua
root@OpenWrt:~# touch /usr/lib/lua/WebService.lua
将其内容修改成以下内容:url
local WebService = {}
function WebService.Run()
local client = os.getenv("REMOTE_ADDR")
local GET = os.getenv("QUERY_STRING")
local POST = nil
local POSTLength = tonumber(os.getenv("CONTENT_LENGTH")) or 0
if (POSTLength > 0) then
POST = io.read(POSTLength)
--POST = io.read("*a")
end
-- Fast-CGI+HTTP require HEADER
-- enable cache
--io.write("Content-type: text/html\n\n")
-- disable cache, especially for Internet Explorer
io.write("Content-type: text/html\nPragma: no-cache\n\n")
local reply = string.format("Client %s said: url: [%s], data: [%s]\n", client or '-', GET or '-', POST or '-')
io.write(reply)
end
return WebService
第五步:重启“uhttpd”服务(为了让更改的/etc/config/uhttpd生效):
root@OpenWrt:~# /etc/init.d/uhttpd restart
第六步:使用浏览器测试:
使用浏览器访问以下地址:
http://<openwrt_ipaddr>/cgi-bin/webservice?author=qige
这里假设OpenWrt开发板的IP为192.168.1.24:
http://192.168.1.24/cgi-bin/webservice?author=qige
最终效果以下图:
注意:
root@OpenWrt:~# opkg install coreutils
root@OpenWrt:~# opkg install coreutils-stty
再将如下内容添加到Lua模块的适当位置,并调用此函数便可:
function WebService.uartWrite(msg)
local uartConfig = 'stty -F /dev/ttyS0 raw speed 9600\n'
os.execute(uartConfig)
local cmd = string.format("echo '%s' > /dev/ttyS0\n", msg or '')
os.execute(cmd)
end