luci范例

LuCI (Lua Configiration Interface) 是OpenWRT 的Web 管理介面。LuCI 是一个MVC (Model View Controller) framework,所以我们可以在LuCI 的基础上写Web 的应用程式。
第一个controller 模组
假设我们想做一件事:「当使用者浏览/cgi-bin/luci/myapp/mymodule/time.htm 时,便在网页上显示OpenWRT 目前的系统时间」。那么可以写一段程式码如下(mymodule.lua):

 

-- Save this to /usr/lib/lua/luci/controller/myapp/mymodule.lua
-- Browse to: /cgi-bin/luci/myapp/mymodule/time.htm

module("luci.controller.myapp.mymodule", package.seeall)

function index()
-- 定義節點, request 時會呼叫 action_time
page = entry({"myapp", "mymodule", "time.htm"}, call("action_time"))

-- 沒有上層節點
page.dependent = false 
-- 假如是葉節點, 就設成 true 避免錯誤
page.leaf = true
end

function action_time()
luci.http.prepare_content("text/html") 
luci.http.write("<h1>Hello LuCi</h1>")
luci.http.write("<h2>Current time: " .. os.date("%D %T") .. "</h2")
end

 


其中,以entry() 定义了一个节点,作用是「当使用者浏览/cgi-bin/luci/myapp/mymodule/time.htm 时,便会呼叫action_time() 函式」,而action_time() 函式则会负责产生一个显示目前系统时间的网页。
把mymodule.lua 放到/usr/lib/lua/luci/controller/myapp/mymodule.lua,然后浏览/cgi-bin/luci/myapp/mymodule/time.htm,就会看到底下的结果:

 

建立VIEW
跟PHP, ASP.NET, JSP 一样,LuCI 也有template 的功能,可以在HTML 里混用Lua Script 产生动态网页。底下做个示范。
首先,建立了一个template 档如下,并把它存到/usr/lib/lua/luci/view/myapp_mymodule/time.htm:

 

<!-- Save this to /usr/lib/lua/luci/view/myapp_mymodule/time.htm -->
<%+header%>
<h1>Hello LuCI</h1>
<h2>Current Time: <%= os.date("%D %T")%></h2> 
<%+footer%>

 


接着写个controller 模组如下,把它存到/usr/lib/lua/luci/controller/myapp/mymodule.lua:

 

-- Save this to /usr/lib/lua/luci/controller/myapp/mymodule.lua
-- Browse to: /cgi-bin/luci/myapp/mymodule/

module("luci.controller.myapp.mymodule", package.seeall)

function index()
-- 定義節點, 當作 myapp.mymodule.time.htm 的別名
page = entry({"myapp", "mymodule"}, 
alias("myapp", "mymodule", "time.htm"), "My Module")
page.dependent = false

-- 定義節點, request 時會 render view/myapp_mymodule/time.htm
page = entry({"myapp", "mymodule", "time.htm"}, 
template("myapp_mymodule/time"), "Time") 
page.dependent = false; page.leaf = true 
end

 

LuCI 现在预设都是用bootstrap CSS frontend,time.htm 引入了header template,因此享受bootstrap 的好处,变得比较美观了。
暂除LuCI 模组暂存档
在学习写LuCI 模组时,有件特别注意的事。由于LuCI 会把module 暂存起来,就算你写的module 有做过变动,LuCI 也不会跑更新过后的版本。所以当你更新module 时,记得删除LuCI 的模组暂存档,这样LuCI 才会跑新版本的模组。
删除LuCI 模组暂存档的指令为:
  rm /tmp/luci-indexcache /tmp/luci-modulecache/*
参考资料
HOWOT: Write Modules

posted @ 2015-05-18 13:55  souroot  阅读(1686)  评论(0编辑  收藏  举报