-----------------------------------------------------------------------------
-- SMCCallback.lua
--
-- These methods attempt to handle events (callbacks from the wrapper) in a
-- standardized way.  In general:
--
-- * If there is a global object called "appEventQueue", it is assumed to be
--   an EventQueue class instance, and an event is posted to the queue.  The
--   events posted are:
--
--	Event("serialData", { portName=name, serialData = data })
--	Event("timerExpired", { timerName=name })
--
-- * Otherwise, if there is a global object called "app" and it has an
--   appropriate method to handle the callback, that method is called with
--   the callback's methods.  The methods are:
--
--	app.SerialCallback(portName,data)
--	app.TimeoutCallback(timerName)
--
-- * Otherwise, if there is a global object called "app" and it has a
--   "PostEvent" method, an event formatted as above is sent to it.
--
-----------------------------------------------------------------------------

require "Event"
require "UtilFunc"

-- Handles the callback from the wrapper process for serial port data reported.
--
-- (Note that this callback will receive one or more callbacks with non-zero
-- length data followed by one callback with zero length data to indicate
-- that nothing more is immediately available.)
function SMCReportSerialData(portNameParam,dataParam)
	SMC:Log("debug", "SMCReportSerialData portName="..portNameParam.." data="..UtilFunc.TranslateString(dataParam))
	local handled = false

	if appEventQueue then
		handled = true
		local evt = Event("serialData", { portName=portNameParam, serialData=dataParam })
		appEventQueue.pushBack(evt)
		appEventQueue.dispatch()
	elseif app then
		if app.SerialCallback then
			handled = true
			app.SerialCallback(portNameParam, dataParam)
		elseif app.PostEvent then
			handled = true
			local evt = Event("serialData", { portName=portNameParam, serialData=dataParam })
			app.PostEvent(evt)
		end
	end

	if not handled then
		SMC:Log("warning", "SMCReportSerialData callback for portName="..portNameParam.." was not handled")
	end

end

-- Handles the callback from the wrapper process for timer expiration
function SMCReportTimeout(timerNameParam)
	SMC:Log("debug", "SMCReportTimeout timerName="..timerNameParam)
	local handled = false

	if appEventQueue then
		handled = true
		local evt = Event("timerExpired", { timerName=timerNameParam })
		appEventQueue.pushBack(evt)
		appEventQueue.dispatch()
	elseif app then
		if app.TimeoutCalback then
			handled = true
			app.TimeoutCallback(timerNameParam)
		elseif app.PostEvent then
			handled = true
			local evt = Event("timerExpired", { timerName=timerNameParam })
			app.PostEvent(evt)
		end
	end

	if not handled then
		SMC:Log("warning", "SMCReportTimeout callback for timerName="..timerNameParam.." was not handled")
	end

end

