local syslog=require("syslog") local math=require("math") local cjson=require("cjson") -------------------------[全局参数定义]------------------------- -------------------------[输入设备名称以及标识符]------------------------- device="201955555555" input_value_name="input" -------------------------[输出设备名称以及标识符]------------------------- output_value_name="output" -------------------------[系统变量]------------------------ raw_data_cache_size=100 --缓存大小 syslog.openlog( string.format("%s syslog",device), syslog.LOG_PERROR + syslog.LOG_ODELAY, "LOG_USER") function write_cache_to_file(path,ojb) local file=io.open(path, 'w+') file:seek('set') file:write(cjson.encode(ojb)) file:flush() file:close() end function read_cache_from_file(path) local file=io.open(path, 'a+') local ojb={} file:seek('set') ojb = file:read() file:close() if(ojb == nil) then return nil end return cjson.decode(ojb) end function process_data(raw_data) local curr_timestamp=os.time() --排序去头去尾 if #raw_data.list > 5 then --数据长度大于一定值才只用去头去尾 table.sort( raw_data.list ) table.remove( raw_data.list,#raw_data.list) table.remove( raw_data.list,1) end --求平均 local sum=0.0 for i=1,#raw_data.list,1 do sum = sum + raw_data.list[i] end local out_data={} out_data['timestamp']=os.time() out_data[output_value_name]=sum/#raw_data.list local json_str=cjson.encode(out_data) syslog.syslog("LOG_WARNING", json_str .. #json_str) return 0,json_str,#json_str end function udef_process(data) local err_code=0 local tmp_file=string.format("/tmp/%s.dat",device); local cache = read_cache_from_file(tmp_file) if not cache then cache={} cache.list={} end if #cache.list > raw_data_cache_size then table.remove( cache.list, 1 ) end table.insert(cache.list, data ) write_cache_to_file(tmp_file,cache) return process_data(cache) end function parser_input(obj) local source_a for i,v in pairs(obj["datas"]) do if(v["sn"] == device) then tag = v["tags"] if tag then source_a = tag[input_value_name] end end end return source_a end function protocol_decode(input_str, len) --出参格式化-- local obj = cjson.decode(input_str) --获取输入变量-- local source_a = parser_input(obj) if not source_a then return -1,0,0 end err_code,out_str,out_len=udef_process(source_a) return err_code,out_str,out_len end -- protocol_decode('{"datas":[{"sn":"201955555555","time":1574933970,"state":0,"quality":0,"identifier":"post","tags":{"input":10}}]}', 0) syslog.closelog()