module(...,package.seeall)

--[[

uart֡ṹΧ豸룬յȷָ󣬻ظASCIIַ

֡ṹ£
֡ͷ1ֽڣ0x01ʾɨָ0x02ʾGPIO0x03ʾƶ˿
֡壺ֽڲ̶֡ͷй
֡β1ֽڣ̶Ϊ0xC0

յָ֡ͷΪ0x01ʱظ"CMD_SCANNER\r\n"Χ豸
յָ֡ͷΪ0x02ʱظ"CMD_GPIO\r\n"Χ豸
յָ֡ͷΪ0x03ʱظ"CMD_PORT\r\n"Χ豸
յָ֡ͷΪʱظ"CMD_ERROR\r\n"Χ豸
]]


--ID,1Ӧuart1
--Ҫ޸Ϊuart2UART_IDֵΪ2
local UART_ID = 1
--֡ͷԼ֡β
local CMD_SCANNER,CMD_GPIO,CMD_PORT,FRM_TAIL = 1,2,3,string.char(0xC0)
--ڶݻ
local rdbuf = ""

--[[
print
  ӡӿڣļедӡtestǰ׺
  
ֵ
]]
local function print(...)
	_G.print("test",...)
end

--[[
parse
  ֡ṹһ֡
  
		dataδ
ֵһֵһ֡ĵĴڶֵδ
]]
local function parse(data)
	if not data then return end	
	
	local tail = string.find(data,string.char(0xC0))
	if not tail then return false,data end	
	local cmdtyp = string.byte(data,1)
	local body,result = string.sub(data,2,tail-1)
	
	print("parse",common.binstohexs(data),cmdtyp,common.binstohexs(body))
	
	if cmdtyp == CMD_SCANNER then
		write("CMD_SCANNER")
	elseif cmdtyp == CMD_GPIO then
		write("CMD_GPIO")
	elseif cmdtyp == CMD_PORT then
		write("CMD_PORT")
	else
		write("CMD_ERROR")
	end
	
	return true,string.sub(data,tail+1,-1)	
end

--[[
proc
  Ӵڶ
  
		dataǰһδӴڶ
ֵ
]]
local function proc(data)
	if not data or string.len(data) == 0 then return end
	--׷ӵ
	rdbuf = rdbuf..data	
	
	local result,unproc
	unproc = rdbuf
	--֡ṹѭδ
	while true do
		result,unproc = parse(unproc)
		if not unproc or unproc == "" or not result then
			break
		end
	end

	rdbuf = unproc or ""
end

--[[
read
  ȡڽյ
  
ֵ
]]
local function read()
	local data = ""
	--ײcoreУյʱ
	--ջΪգжϷʽ֪ͨLuaűյݣ
	--ջΪգ򲻻֪ͨLuaű
	--Luaűյж϶ʱÿζҪѽջеȫܱ֤ײcoreежreadеwhileоͱ֤һ
	while true do		
		data = uart.read(UART_ID,"*l")
		if not data or string.len(data) == 0 then break end
		--Ĵӡʱ
		--print("read",data,common.binstohexs(data))
		proc(data)
	end
end

--[[
write
  ͨڷ
  
		sҪ͵
ֵ
]]
function write(s)
	print("write",s)
	uart.write(UART_ID,s.."\r\n")
end

--ϵͳڻ״̬˴ֻΪ˲ҪԴģûеطpm.sleep("test")ߣ͹״̬
--ڿҪ󹦺ĵ͡ĿʱһҪ취֤pm.wake("test")ڲҪʱpm.sleep("test")
pm.wake("test")
--עᴮڵݽպյݺ󣬻жϷʽreadӿڶȡ
sys.reguart(UART_ID,read)
--òҴ򿪴
uart.setup(UART_ID,115200,8,uart.PAR_NONE,uart.STOP_1)

--[[
Ҫ򿪡ڷɺͨ첽Ϣ֪ͨĹܣ
local function txdone()
	print("txdone")
end
uart.setup(UART_ID,115200,8,uart.PAR_NONE,uart.STOP_1,nil,1)
sys.reguartx(UART_ID,txdone)
]]

