在小桴智能管家上进行Lua编程


  • administrators

    我们正在提供Lua插件,帮助有定制需要的客户进行快捷的脚本应用开发,下面是我们已经完成测试的代码:

    package.cpath = "/usr/lib/lua/?.so"
    require "hello"
    require "ubus"
    
    function ubus_event_handler(type, raw)
    	logger("Type: ", type)
    	logger("Raw: ", raw)
    end
    
    function ubus_test()
    
    	local conn = ubus.connect()
    	if not conn then
    		logger("Failed to connect to ubusd")
    		return 0
    	end
    
    	local namespaces = conn:objects()
    	for i, n in ipairs(namespaces) do
    		logger("namespace=" .. n)
    		local signatures = conn:signatures(n)
    		for p, s in pairs(signatures) do
    			logger("\tprocedure=" .. p)
    			for k, v in pairs(s) do
    				logger("\t\tattribute=" .. k .. " type=" .. v)
    			end
    		end
    	end
    
    	--local status = conn:call("test", "hello", { msg = "eth0" })
    
    	--for k, v in pairs(status) do
    	--	logger("key=" .. k .. " value=" .. tostring(v))
    	--end
    end
    
    function module_init()
    	local socket = require "socket"
    	local udp = socket.udp()
    	udp:settimeout(0)
    	udp:setsockname('*', 8080)
    
    	udp_ev = uloop.async_fd_add(udp, function(ufd, events)
    		local words, msg_or_ip, port_or_nil = ufd:receivefrom()
    		logger('Recv UDP packet from '..msg_or_ip..':'..port_or_nil..' : '..words)
    		if words == "Stop!" then
    			udp_ev:cancel()
    		end
    	end, uloop.EV_READ)
    end
    
    
    function tellme2()
    	logger("This is coming from lua.tellme.\n")
    	uloop.async_timer(function() logger("2000 ms timer run"); end, 2000)	
    end
    
    local json = require "json"
    
    function dump(o)
       if type(o) == 'table' then
          local s = '{ '
          for k,v in pairs(o) do
    	 if type(k) ~= 'number' then k = '"'..k..'"' end
    	 s = s .. '['..k..'] = ' .. dump(v) .. ','
          end
          return s .. '} '
       else
          return tostring(o)
       end
    end
    
    function module_main()
    	local def = {url='https://api.seniverse.com/v3/weather/now.json?key=cwe2cszx82jkqxmv&location=guangzhou', ssl_verify=false}
    	local data_body = ""
    	logger(_VERSION_RL)
    	logger("Testing Curl!!.\n")
    	logger(http.curl_version())
    	http1 = http.newConnection(def)
    	http1.ON_IO_EVENT = function(val, code)		
    		if val ~= nil then
    			logger("ON_IO_EVENT Failed "..val);
    		else
    			local headers1 = http1:getResponseHeaders()
    			for key_name, val in pairs(headers1) do
    				logger ("[" .. key_name .."] -> ".. val)
    			end
    
    			logger ("Body: " .. tostring(data_body))
    			local vj = json.decode(data_body)
    			
    			--logger(dump(vj["results"][1]["now"]));
    			logger(" location " .. vj["results"][1]["location"]["path"]..", ID:"..vj["results"][1]["location"]["id"] );
    			logger(" 温度 " .. vj["results"][1]["now"]["temperature"]..", 天气:"..vj["results"][1]["now"]["text"] );
    
    			if code == 200 then
    			 logger ("receive end, code ", http1:getHTTPStatusCode())
    			else
    			  logger ("get Response Headers ", http1:getLastError())
    			end
    			http1:disconnect()
    			return false
    		end
    	end
    	http1:get (function (val, code)              
    		logger ("In Http write callback")
    		data_body = data_body .. tostring(val)
    		return true
    		end) 
    end
    
    function config_test()
    	logger(raftlink.get_config('argment')); 
    	raftlink.set_config('hello', "111")
    	logger(raftlink.get_config('hello')); 
    	raftlink.set_config('hello', nil)
    end
    
    -------------
    local devinfo = {type='switch', id='123',notify=false,port=123}
    raftlink.identifier('luasource');
    dev1 = raftlink.create_device(devinfo)
    
    dev1.ON_IO_REQUEST = function(cmd, param)
    	logger("ON_IO_REQUEST called");
    end
    
    dev1.ON_IO_EVENT = function(event, msg)
    	logger("ON_IO_EVENT called");
    end
    
    dev1.ON_IO_ERROR = function(error)
    	logger("ON_IO_ERROR called");
    	if error == 10 then
    		logger ("receive device error ", error)
    		dev1:disconnect()
    		return false
    	end
    
    	logger ("receive device fail ", error)
    	dev1:destroy();
    	return true
    end
    
    dev1:start('once');
    
    -------------
    
    local MOSQ_NODE_ID       = "dd"
    local MOSQ_ID            = "flukso_" .. MOSQ_NODE_ID
    
    mosquitto.init();
    local mqtt = mosquitto.new(MOSQ_ID, true)
    logger("mosquitto version " .. mosquitto.version());
    
    mqtt.ON_MESSAGE = function(mid, topic, payload)
    	logger("Receive " .. topic, payload)
    end
    
    mqtt.ON_CONNECT = function()
    	mqtt:subscribe("/node/" .. MOSQ_NODE_ID .. "/#", 2)
    	mqtt:subscribe("my/topic/", 2)
    
    	logger("ON_CONNECT called");
    	mqtt:publish("world", "hello")
    	local qos = 1
    	local retain = true
    	local mid = mqtt:publish("my/topic/", "my payload", qos, retain)
    end
    
    mqtt.ON_PUBLISH = function()
    	logger("ON_PUBLISH called");
    	--mqtt:disconnect()
    end
    
    mqtt.ON_DISCONNECT = function()
    	logger("ON_DISCONNECT called");
    	mqtt:destroy();
    end
    
    mqtt.ON_IO_ERROR = function(errorid)
    	logger("ON_IO_ERROR called " .. errorid);
    	mqtt:reconnect();
    end
    
    mqtt.ON_LOG = function(level,msg)
    	logger("MQTT_LOG " ..  msg);
    end
    
    mqtt:connect("192.168.8.150", 1883, 300);
    
    local fd = mqtt:socket();
    logger("mqtt fd ", fd);
    
    -------------