module(...,package.seeall)

require"pm"

--ID,1Ӧuart1
local UART_ID = 1

--SND_UNIT_MAXÿηֻֽҪۻյݴڵֽûڷݵ̨ǰSND_UNIT_MAXֽݸ̨
--SND_DELAYÿδյʱӳSND_DELAYûյµݣûڷݵ̨ǰSND_UNIT_MAXֽݸ̨
--ʹãֻҪκһ㣬ᴥͶ
--磺SND_UNIT_MAX,SND_DELAY = 1024,1000¼
--յ500ֽݣ1000ûյݣûڷݵ̨500ֽݸ̨
--յ500ֽݣ800յ524ֽݣʱûڷݵ̨1024ֽݸ̨
local SND_UNIT_MAX,SND_DELAY = 1024,1000

--sndingtosvrǷڷݵ̨
local sndingtosvr

--unsndbufûз͵
--sndingbufڷ͵
local readbuf--[[,sndingbuf]] = ""--[[,""]]

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

--[[
sndtosvr
  ֪ͨݷ͹ģ飬׼ãԷ
  
ֵ
]]
local function sndtosvr()
	--print("sndtosvr",sndingtosvr)
	if not sndingtosvr then
		sys.dispatch("SND_TO_SVR_REQ")
	end
end

--[[
getsndingbuf
  ȡҪ͵
  
ֵstringͣҪ͵
]]
local function getsndingbuf()
	print("getsndingbuf",string.len(readbuf),sndingtosvr,sys.timer_is_active(sndtosvr))
	if string.len(readbuf)>0 and not sndingtosvr and (not sys.timer_is_active(sndtosvr) or string.len(readbuf)>=SND_UNIT_MAX) then
		local endidx = string.len(readbuf)>=SND_UNIT_MAX and SND_UNIT_MAX or string.len(readbuf)
		local retstr = string.sub(readbuf,1,endidx)
		readbuf = string.sub(readbuf,endidx+1,-1)
		sndingtosvr = true
		return retstr
	else
		sndingtosvr = false
		return ""
	end	
end

--[[
resumesndtosvr
  λб־ȡҪ͵
  
ֵstringͣҪ͵
]]
function resumesndtosvr()
	sndingtosvr = false
	return getsndingbuf()
end

--[[
sndcnf
  ͽ
  
		resultͽtrueɹֵʧ
ֵ
]]
--[[local function sndcnf(result)
	print("sndcnf",result)
	--sndingbuf = ""
	sndingtosvr = false
end]]

--[[
proc
  ڽյ
  
		dataǰһζȡĴ
ֵ
]]
local function proc(data)
	if not data or string.len(data) == 0 then return end
	--׷ӵδݻĩβ
	readbuf = readbuf..data
	if string.len(readbuf)>=SND_UNIT_MAX then sndtosvr() end
	sys.timer_start(sndtosvr,SND_DELAY)
end


--[[
snd
  ȡڽյ
  
ֵ
]]
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",string.len(data)--[[data,common.binstohexs(data)]])
		proc(data)
	end
end

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

--Ϣб
local procer =
{
	SVR_TRANSPARENT_TO_MCU = write,
	--SND_TO_SVR_CNF = sndcnf,
}

--עϢб
sys.regapp(procer)
--ϵͳڻ״̬
pm.wake("mcuart")
--עᴮڵݽպյݺ󣬻жϷʽreadӿڶȡ
sys.reguart(UART_ID,read)
--òҴ򿪴
uart.setup(UART_ID,9600,8,uart.PAR_NONE,uart.STOP_1)


