【OpenWRT之旅】如何自定義一個配置文件的設置界面


作者:gnuhpc
出處:http://www.cnblogs.com/gnuhpc/

1. 引言

OpenWRT中采用LuCI作為它的Web interface界面框架,采用Lua語言。在本文中將以一個簡單的示例詳細描述如何自定義開發一個界面,對一個配置文件進行操作。

2.Model與Controler

MVC的設計理念是進行LuCI開發的一個關鍵,什么是MVC請參看如下Blog:

http://www.cnblogs.com/gnuhpc/archive/2012/12/21/2827597.html

在LuCI中Controller的文件定義在固件中的/usr/lib/lua/luci/controller目錄中,模版目錄在/usr/lib/lua/luci/view目錄下,而model則是在/usr/lib/lua/luci/model中。而model中有一個特殊的模塊叫做CBI,被稱為LuCI中最酷的功能,該模塊的功能是方便的對一個配置文件進行修改。

3.示例

本文中的頁面建立在LuCI界面的network下,不單獨創建頁面,因此無需寫view,只用些controller和model就可以了。

1)首先創建一個controller

ccontroller/mycbi.lua

module("LUCI.controller.mycbi", package.seeall)

function index()
	entry({"admin", "network", "mycbi_change"}, cbi("mycbi-model/mycbimodule"), "Change My Conf", 30).dependent=false
end

解釋一下關鍵代碼:

image

在index()函數中,使用entry函數來完成每個模塊函數的注冊,官方說明文檔如下:

entry(path, target, title=nil, order=nil)

  • path is a table that describes the position in the dispatching tree: For example a path of {"foo", "bar", "baz"} would insert your node in foo.bar.baz.
  • target describes the action that will be taken when a user requests the node. There are several predefined ones of which the 3 most important (call, template, cbi) are described later on on this page
  • title defines the title that will be visible to the user in the menu (optional)
  • order is a number with which nodes on the same level will be sorted in the menu (optional)

其中target主要分為三類:call,template和cbi。call用來調用函數,template用來調用已有的htm模版,而CBI模塊則是使用非常頻繁也非常方便的模塊,包含的一系列lua文件構成界面元素的組合,所有cbi模塊中的控件都需要寫在luci.cbi.Map中,在cbi模塊中定義各種控件,Luci系統會自動執行大部分處理工作。在cbi.lua文件中封裝了所有的控件元素,例如復選框,下拉列表等。

 

2)創建model

#mkdir /usr/lib/lua/luci/model/cbi/mycbi-model

#vim /usr/lib/lua/luci/model/cbi/mycbi-model/mycbimodule.lua

m = Map("mycbi", "mycbi conf change interface")
s = m:section(TypedSection, "MySection")
s.addremove = true
s:option(Value, "username", "Name:")
key=s:option(Value, "password", "Password")
key.password=true;
return m

解釋一下關鍵代碼:

image

3)創建配置文件

#vim /etc/config/mycbi

config  'MySection'  'mycbi'

option 'username' 'youruser'
option 'password' 'yourpass'

4. 測試

進入OpenWRT界面,登陸后就可以點擊“網絡”,如果是英文就點擊network,可以看到我們添加的子頁面入口:

image

點擊后進入頁面如下:

image

輸入用戶名密碼:root/test,點擊保存,后台查看配置文件已經被更改:

image

 

5. 問題記錄

1)首先,配置文件不能有任何后綴,否則頁面加載后是空頁面

2)如果出現500 錯誤,說明lua文件寫的有問題,要么是路徑錯誤,要么是語法錯誤,暫時沒找到寫日志的方法,可以用wireshark抓包看錯誤,如下:

image

6.參考文獻

http://www.cnblogs.com/dwayne/archive/2012/04/18/2455145.html

http://www.cnblogs.com/dwayne/archive/2012/04/21/2460830.html

 

作者:gnuhpc
出處:http://www.cnblogs.com/gnuhpc/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM