pv1_log_proto = Proto("PV1_Log", "PV1 ES2 Log Protocol")

log_level_str = 
{
	[ 1 ] = "[F]",
    [ 2 ] = "[E]",
    [ 4 ] = "[W]",
    [ 8 ] = "[D]",
    [ 16 ] = "[I]",
    [ 32 ] = "[T]",
    [ 64 ] = "[I]",
    [ 128 ] = "[V]",
    [ 256 ] = "[S]",
    [ 512 ] = "[U]",
	[ 0xFFFFFFFF ] = "[A]", 
}

local log_content 	= ProtoField.string("logContent", 	"Message:\t")
local log_Seq 		= ProtoField.uint16("logSeq", 		"Sequence: \t", base.DEC)
local log_pid		= ProtoField.uint32("logPid", 		"PID: \t\t", base.DEC)
local log_datetime  = ProtoField.string("logDateTime",	"DateTime:\t\t")
local log_time 		= ProtoField.string("logTime", 		"Date:\t\t")
local log_level		= ProtoField.uint32("logLevel",		"Level: \t\t", base.DEC, log_level_str)

pv1_log_proto.fields = {
log_Seq, log_content, log_pid, log_datetime, log_level
}

function pv1_log_proto.dissector(buffer, pinfo, tree)
	pinfo.cols.protocol:set("LOG")	
	local offset = 0
	local buf_len = buffer:len()
	local logInfoTree = tree:add(pv1_log_proto, buffer(0, 18), "Log Message Information")
		
	logInfoTree:add(log_Seq, buffer(offset, 2))
	offset = offset + 2
	
	local l_pid = buffer(offset, 4):uint()
	logInfoTree:add(log_pid, buffer(offset, 4))
	offset = offset + 4
	
	local l_second = buffer(offset, 4):uint()
	offset = offset + 4
	
	local l_nsecond = buffer(offset, 4):uint()
	offset = offset + 4
			
	logInfoTree:add(log_datetime, "[" .. os.date("%c", l_second)  .. "." .. string.format("%03d", l_nsecond / 1000) .. "]")	
	
	local l_level = buffer(offset, 4):uint()
	local l_lvStr
	
	if l_level == 1 then
		l_lvStr = "F"	
	elseif l_level == 2 then
		l_lvStr = "E"
	elseif l_level == 4 then
		l_lvStr = "W"
	elseif l_level == 8 then
		l_lvStr = "D"
	elseif l_level == 16 then
		l_lvStr = "I"
	elseif l_level == 32 then
		l_lvStr = "T"
	elseif l_level == 64 then
		l_lvStr = "C"
	elseif l_level == 128 then
		l_lvStr = "V"
	elseif l_level == 256 then
		l_lvStr = "S"
	elseif l_level == 0xFFFFFFFF then
		l_lvStr = "A"	
	else
		l_lvStr = "U"
	end
	
	logInfoTree:add(log_level, buffer(offset, 4))
	offset = offset + 4
		
	local logInfo = buffer(offset, buf_len - 19):string()
	local logMsgTree = tree:add(pv1_log_proto, buffer(18, buf_len - 18), "Log Message Content")
	logMsgTree:add(log_content, logInfo)
	
	if buffer(buf_len - 1, 1):string() == '\n' then
		pinfo.cols.info:set("{" .. tostring(l_pid) .. "} [" ..  os.date("%X", l_second)  .. "." .. string.format("%03d", l_nsecond / 1000) .. "] [" .. tostring(l_lvStr) .. "] " .. buffer(18, buf_len - 19):string())		
	else 
		pinfo.cols.info:set("{" .. tostring(l_pid) .. "} [" ..  os.date("%X", l_second)  .. "." .. string.format("%03d", l_nsecond / 1000) .. "] [" .. tostring(l_lvStr) .. "] " .. buffer(18, buf_len - 18):string())		
	end
end

local pv1_log_udp_port_table = DissectorTable.get("udp.port")
--local pv1_log_port = 10000
pv1_log_udp_port_table:add("10000-10020", pv1_log_proto)
