tagarray={}
paramarray={}
dataTypearray={}

profile= '[{"tag": 1,"identifier":"Work","dataType": "char"},{"tag": 2,"identifier": "Light", "dataType": "short"},{"tag": 3,"identifier": "Drying","dataType": "int"}]'


function getLuaScriptVersion()
	return "yat_jd_lua_1.0"
end

function tableToString(cmd) --函数，将表数据转为字符串
	local strcmd="" --变量定义
	local I --变量定义
	for i=1,#cmd do
	strcmd=strcmd..string.char(cmd[i]) --表中的每个成员转化为 char，添加到串后面
	end
	return strcmd --返回串
end

function arraytostringinByte(tdlist)
	local res ="";
	local initIndex = 1
	if tdlist[0] ~=nil then
		initIndex = 0
	end
	for i=initIndex,#tdlist do
		res = res..string.char(tdlist[i])
	end
	return res;
end

function decode(cmd)
	local tb --定义局部变量
	if cjson == nil then --如果全局变量 cjson 是 nil
	cjson = (require 'JSON') --加载外部对象 JSON 为全局变量 cjson 赋值
	--为了方便代码管理，通常会把 lua 代码分成不同的模块，然后在通过 require 函数把它们加载进来
	tb = cjson:decode(cmd) --使用外部对象的 decode 函数处理 cmd
	else
	tb = cjson.decode(cmd) --使用自定义对象的 decode 函数处理 cmd
	end
	return tb --返回 tb
end

function toArray(strCmd)
	local arrayResult = {}
	local strCmdLen = string.len(strCmd)
	local byteLen = strCmdLen/2
	local startIndex = 0
	while startIndex <= byteLen do
		arrayResult[startIndex+1]=tonumber(getbyte(strCmd,startIndex),16)
		startIndex=startIndex+1
	end
	return arrayResult,byteLen
end

function getbyte(str,byteindex)
	local b15 = string.sub(str, ( byteindex *2)+1, ((byteindex+1) *2))
	return tonumber(b15, 16)
end

function getbit(number, bitindex)
	for i = 31,0,-1 do
		if i ~= bitindex then
			local temp = 2 ^ i
			if temp <= number then
				number = number - temp
			end
		end
	end
	if number == 0 then
		return 0
	else
		return 1
	end
end

function getKVTable(t,keyName,valueName)
	print(serialize(t))
	local kvTable = {}
	for i=1, #t do
		key = t[i][''..keyName]
		val = t[i][''..valueName]
		kvTable[''..key] = ''..val
	end
	return kvTable
end
function getJD_KVTable(t)
	return getKVTable(t,'stream_id','current_value')
end

	-- 自定义函数
-- 判断某个byte中低位第几位是否是1
-- decNum：十进制数字
-- binInex：byte中低位第几位，从1开始
function isEnableByBinIndex(decNum , binIndex)
	local calcNum = 2^binIndex
	decNum = decNum % calcNum
	return decNum >= calcNum/2
end

function byteArrayToHexStr( byteTable )
	local hexStr = '';
	local length = #byteTable
	for i=1, length, 1 do
		hexStr = hexStr..string.format("%02X",byteTable[i])
	end
	return hexStr
end


function decodeprofile()

	local jsonarray=cjson.decode(profile)

	for i=1,#jsonarray do
		tagarray[i]=jsonarray[i]["tag"]
		paramarray[i]=jsonarray[i]["identifier"]
		dataTypearray[i]=jsonarray[i]["dataType"]
	end
end


function jds2pri(code, cmd) --code:biz_code； cmd: 待转换的 json 串
	local binpayload = {} --定义局部变量
	local temp
	local temp1
	local flag
	local hour
	local minute
	local ret


	decodeprofile()

	if code == 1002 then --如果 code 是 1002
		local json = decode(cmd) --定义局部变量，并赋值
		local streams = json["streams"] --定义局部变量，并赋值
       	        local streamcount = #streams
        
		for i=1, #streams do --for 循环，从 1 到表 streams 的最大键值
			local key = streams[i]['stream_id'] --定义局部变量，值为 streams[i]的['stream_id']
            local val = streams[i]['current_value'] --定义局部变量，值为 streams[i]的[' current_value ']

            for i=1, #paramarray do 
			    if key == paramarray[i] then		
					binpayload[#binpayload+1] = tagarray[i]            

                    if dataTypearray[i]=="char" then
						binpayload[#binpayload + 1] = 1			
                        binpayload[#binpayload + 1] = tonumber(val, 10)
                    elseif dataTypearray[i]=="short" then
						binpayload[#binpayload + 1] = 2						
						temp=tonumber(val, 10)										

						binpayload[#binpayload + 1] =temp%0x100										
						binpayload[#binpayload + 1] =0
                   	elseif dataTypearray[i]=="int" then
						binpayload[#binpayload + 1] = 4					
						temp=tonumber(val, 10)

						binpayload[#binpayload + 1] =temp%0x100
						binpayload[#binpayload + 1] = 0 	
						binpayload[#binpayload + 1] = 0 	
						binpayload[#binpayload + 1] = 0 	
                    else

			    	end
			    end
			end
		end		
        
		ret = byteArrayToHexStr(binpayload)

	elseif code == 1004 then
		bin = {0xFE,0xFF, 0xFE, 0xFE,0xFE, 0xFE, 0xFE,0xFE,0xFE, 0xFE, 0xFF,0xFF}
		ret = byteArrayToHexStr(bin)
	end

	return 0, string.len(ret), ret
end


function pri2jds(bizcode, length, bin)
-- return 0, "zhaohytest " .. type(bin) .. " " .. bin, bizcode
-- end
	local retTable = {} --定义局部变量
	local value0
	local value1
	local value2
	local errh
	local errl
	local nFilterlife
	local strFilterlife

	local streams = {}
	local streamcount = 0
	local bincount = 0
	local proplen = 0
	local datatypelen = 0

	decodeprofile()
	-- cloudmenu
	if bizcode == 150 then --云菜谱响应
		return 0, "{150}", 150
	--no payload
	else
		-- control 102 ; report 103 ; snapshot 104
		for i=1, #tagarray do --for 循环，从 1 到表 streams 的最大键值
			if getbyte(bin, bincount) == tagarray[i] then
			streamcount = streamcount + 1
			streams[streamcount] = {}
			streams[streamcount]["stream_id"] = paramarray[i]
			
			if dataTypearray[i]=="char" then
				streams[streamcount]["current_value"] = tostring(getbyte(bin, bincount+2))
				datatypelen=1
			elseif dataTypearray[i]=="short" then
				--streams[streamcount]["current_value"] = tostring(getbyte(bin, bincount+2)*(0xff+1)+getbyte(bin, bincount+3))
				streams[streamcount]["current_value"] = tostring(getbyte(bin, bincount+3)*(0xff+1)+getbyte(bin, bincount+2))
				datatypelen=2
			elseif dataTypearray[i]=="int" then
				--streams[streamcount]["current_value"] = tostring(getbyte(bin, bincount+2)*(0xffffff+1)+getbyte(bin, bincount+3)*(0xffff+1)+getbyte(bin, bincount+4)*(0xff+1)+getbyte(bin, bincount+5))
				streams[streamcount]["current_value"] = tostring(getbyte(bin, bincount+5)*(0xffffff+1)+getbyte(bin, bincount+4)*(0xffff+1)+getbyte(bin, bincount+3)*(0xff+1)+getbyte(bin, bincount+2))
				datatypelen=4
			else
			end
			bincount =bincount+ 2+datatypelen;
			--bincount =bincount+ 1+datatypelen;
		end
    end
        
	 streamcount = streamcount + 1
	 streams[streamcount] = {}
	 streams[streamcount]["stream_id"] = "code"
	 streams[streamcount]["current_value"] = bizcode

	 retTable["streams"] = streams
   	end
	retTable["code"] = 0
	--tLeveli retTable["msg"] = "done"
	local jsonStr = cjson.encode(retTable)

	return 0, jsonStr, bizcode
end

--[[
cjson = require "cjson"
 tagarray={}
 paramarray={}
 dataTypearray={}
 
 local profile=  '[{"tag": 1, "identifier": "Power", "dataType": "char"},{"tag": 2, "identifier": "AqiLight", "dataType": "char"}, {"tag": 3, "identifier": "PM2.5Value", "dataType": "short"}, {"tag": 4,     "identifier": "Iai", "dataType": "char"}, {"tag": 5, "identifier": "PrimaryFilterRemaining", "dataType": "short"},{"tag": 6, "identifier": "Mode", "dataType": "short"},{"tag": 7, "identifier": "Error"    , "dataType": "char"}]'
 
 --print(getLuaScriptVersion())
 
 jsonarray=cjson.decode(profile)
 
 for i=1,#jsonarray do
         tagarray[i]=jsonarray[i]["tag"]
         paramarray[i]=jsonarray[i]["identifier"]
         dataTypearray[i]=jsonarray[i]["dataType"]
 end
 
 
 for i=1,#jsonarray do
         print(tagarray[i])
         print(paramarray[i])
         print(dataTypearray[i])
 end
 
 local testpri2jds="010101020101030203ff040103050204ff060102070105"
 local res,json,code=pri2jds(103,string.len(testpri2jds), testpri2jds)
 
 print(string.len(testpri2jds))
 print("testpri2jds",testpri2jds)
 print("res", res)
 print("json",json)
 print("code", code)
 --]]

