【OpenWRT之旅】如何自定义一个配置文件的设置界面

做者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/html

1. 引言node

OpenWRT中采用LuCI做为它的Web interface界面框架,采用Lua语言。在本文中将以一个简单的示例详细描述如何自定义开发一个界面,对一个配置文件进行操做。vim

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.示例this

本文中的页面创建在LuCI界面的network下,不单首创建页面,所以无需写view,只用些controller和model就能够了。lua

1)首先建立一个controllerspa

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/

相关文章
相关标签/搜索