
function Application()

	SMC:Log("debug", "Starting Application")

	port = SMC:NewSerialPort("config1")

	local firstTime, thisTime, delta, waitTime

	thisTime = SMC:SystemUptime()
	firstTime = thisTime-1

	while true
	do
		delta = thisTime-firstTime
		waitTime = delta-math.floor(delta)

		if (waitTime >= 0) and (waitTime < 1) then
			waitTime = math.ceil(1000*(1-waitTime))
		else
			waitTime = 1000
		end

		SMC:Log("debug", "Waiting "..tostring(waitTime))
		Wait(waitTime)
		SMC:Log("debug", "Back from waiting")

		local i
		local awaitResult

		i = 1
		awaitResult = false

		while (i <= 3) and (awaitResult == false)
		do
			port:Transmit("AT\r")
			awaitResult = Await("OK\r\n", 300)
			i = i+1
		end

		thisTime = SMC:SystemUptime()

	end

end

function Await(sequence,timeout)

	SMC:Log("debug", "Await sequence="..sequence.." timeout="..timeout)

	local rxd, result

	awaitTimer = SMC:NewTimer("await", timeout)
	result = false

	while (awaitTimer ~= nil) and (result == false)
	do
		rxd = coroutine.yield()
		if (rxd == sequence) then result = true end
	end

	SMC:Log("debug", "Await rxd="..rxd.." at loop exit")

	awaitTimer = nil
	collectgarbage("collect")

	SMC:Log("debug", "Await:"..tostring(result))
	return result

end

function Wait(timeout)

	waitTimer = SMC:NewTimer("wait", timeout)

	while waitTimer ~= nil
	do
		coroutine.yield()
	end 

end

function SMCReportSerialData(portName,data)

	SMC:Log("debug", "Recieved "..data.." on "..portName)

	if awaitTimer ~= nil then
		awaitTimer = nil
		collectgarbage("collect")
		coroutine.resume(appRtn, data)
	end

end

function SMCReportTimeout(timerName)

	SMC:Log("debug", "SMCReportTimeout timerName="..timerName)

	if timerName == "wait" then
		waitTimer = nil
		collectgarbage("collect")
		coroutine.resume(appRtn, nil)
	elseif timerName == "await" then
		awaitTimer = nil
		collectgarbage("collect")
		coroutine.resume(appRtn, nil)
	end

	SMC:Log("debug", "exiting SMCReportTimeout")

end

SMC:Log("debug", "Starting test4")
waitTimer = nil
awaitTimer = nil

appRtn = coroutine.create(function()
	Application()
end)
coroutine.resume(appRtn)

SMC:Log("debug", "test4 started")

