--[[
---------------------------------------------------------------------------
Remote Train Control Program for Windows

© Copyright 2019 by Mark DiVecchio

	This file is part of Remote Train Control.

	Remote Train Control is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Remote Train Control is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Remote Train Control.  If not, see <http://www.gnu.org/licenses/>.

 Home Page : http://www.silogic.com/trains/RTC_Running.html
---------------------------------------------------------------------------]]
-- Semicolons are not required in Lua code
title = "Dispatcher - P&LERR"
--
-- Dispatcher runs on PC1
--
require("defines");
require("functions");

local MyEngineNo, MyTIUNo;

-- Counter Labels
Counter01Label = "Engines Detected";
Counter02Label = "Cycles";
Counter03Label = "Tags Detected";
Counter04Label = "State";
Counter05Label = "OS Reports";

Tags = {};		-- table to hold all of the tags detected in sequence
TagCount = 0;
-- state machine states
IDLE = 0;
SM = IDLE;
-- Form A and Train Orders
FormAYoungstown = false;
FormAMCKEES_ROCKS = false;
TOYoungstown = false;
TOMCKEES_ROCKS = false;
--[[---------------------------------------------------------------------------------------]]
function setup(Engine)
	-- this function is called once when the [Run Script] button is pushed
	-- Engine : Engine number selected on the RTC Main window
	-- TIU : TIU number selected on the RTC Main window
	print("setup()");
	MyEngineNo = Engine;	-- Engine number selected on the RTC Main window
	MyTIUNo = GetTIUNo(MyEngineNo);	-- TIU associated with MyEngineNo		
	print("TIU : " .. MyTIUNo);
	assert((MyTIUNo >= 1 and MyTIUNo <= 5),"TIU Number out of range");
	
	-- make sure that RFID is connected
	TIUSerialPortConnected, TIUConnected, RFIDSerialPortConnected = CommStatus();	
	--print("TIUSerialPortConnected : " .. tostring(TIUSerialPortConnected) .. " - TIUConnected : " .. tostring(TIUConnected) .. " - RFIDSerialPortConnected : " .. tostring(RFIDSerialPortConnected));
	if (not RFIDSerialPortConnected) then
		print("RFID Port must be enabled for this script");
		return false;	-- false=setup failed
		end
	
	Resp = InputQuery("Engine # Leaving McKees Rocks Yard", "Enter Engine Number", MyEngineNo1);
	if (Resp == false or Resp == nil) then	-- user pressed [Cancel]
		return false;	-- false=setup failed, true=setup succeeded
		end;
	Enum = tonumber(Resp);
	if (Enum ~= nil) then	-- if the result is a number, then use it, otherwise, ignore it
		MyEngineNo1 = Enum;
		end
	print("Engine Number = " .. MyEngineNo1);
	SetGlobalInt(3, MyEngineNo1);	-- Engine leaving McKees Rocks Yard runs on PC3
									-- Engine leaving Youngstown Yard runs on PC4
	SM = IDLE;
	SetCounter(COUNTER04, SM);
	print(string.format("RunTime = %.2f seconds", RunTime()));
	return true;		-- false=setup failed, true=setup succeeded
	end

--[[---------------------------------------------------------------------------------------]]
function tag(Detector, Reader, EngineNo, TagLocation, CarModel, Railroad, CarNumber, TagPacket)
	-- This function is called each time a tag programmed with 32 bytes of data is detected (TAGDATABLOCK4)
	-- TagPacket contains 8 characters (4 hex digits) of UID and 32 characters
	-- of block 4 data from the programmed tag.
	Beep();	-- sound a tone
	BumpCounter(COUNTER03);		-- display the number of tags	

	-- index the table Tags[] by tag ID, value is the tag packet itself
	Tags[string.sub(TagPacket, 1, 8)] = string.sub(TagPacket, 9, 40);	-- remove checksum and EOP
	TagCount = TagCount + 1;	-- count the number of tags
	
	if (EngineNo > 0) then	-- its an engine
		-- next line shows a different way to quote a string using brackets
		print(string.format([[tag(%.2f) : Detector %d Reader %d Eng#%d %s %s #%s %s]],
			RunTime(), Detector, Reader, EngineNo, GetRailroadName(Railroad), GetEngineName(CarModel), CarNumber, GetTagLocation(TagLocation)));
			-- only process the front truck tag
			if (isTagRear(TagLocation)) then	-- ignore engine rear truck tags
				return true;	-- true=continue to process tags, false=stop processing tags
				end
		-- follow on to process the detected engine
		else	-- it's a car
		print(string.format([[tag(%.2f) : Detector %d Reader %d Car %s %s #%s]],
			RunTime(), Detector, Reader, GetRailroadName(Railroad), GetCarName(CarModel), CarNumber));
		-- follow on to process the detected Caboose	
		if (CarModel ~= CABOOSE) then	-- ignore cars other than Caboose
			return true;	-- true=continue to process tags, false=stop processing tags
			end
		end
	
	-- Process OS Report
	print("Process OS Report");	
	BumpCounter(COUNTER05);	-- this counts only for engines and cabooses detected	
	-- Detection of an engine sets OS for station	
	
--[[---------------------------------------------------------------------------------------]]
-- STATE MACHINE
--[[---------------------------------------------------------------------------------------]]	
	SetCounter(COUNTER04, SM);
--[[---------------------------------------------------------------------------------------]]	
	if (SM == IDLE) then	-- do nothing 
		-- continue in this state
		return true;
		end
--[[---------------------------------------------------------------------------------------]]		
	if (SM == IDLE) then

		-- continue in this state
		return true;
		end

	return true;	-- true=continue to process tags, false=stop processing tags
	end	
	
--[[---------------------------------------------------------------------------------------]]
function cleanup()
	-- this function is called once when the user presses the [STOP] button
	
	print("All Newly Detected Tags:");
	for k,v in  pairs(Tags) do		-- dump out the Tags table
		--                           . . . . . . . . . . . . . . . .
		-- print format:  6619044A  88080101030108011B02202031353536
		print(k .. "  " .. v);
		end
		
	print(string.format("cleanup() Complete at %.2f", RunTime()));
	return true;		-- false=cleanup failed, true=cleanup succeeded
	end
--[[---------------------------------------------------------------------------------------]]
function FormAMR()
	print("Form A McKees Rocks Button()");
	FormAMCKEES_ROCKS = true;
	return true;
end
Function01Name, Function01Label = FormAMR, "Form A McKees Rocks";
--[[---------------------------------------------------------------------------------------]]
function FormAY()
	print("Form A Youngstown Button()");
	FormAYoungstown = true;
	return true;
end
Function02Name, Function02Label = FormAY, "Form A Youngstown";
--[[---------------------------------------------------------------------------------------]]
function TOMR()
	print("Train Order McKees Rocks Button()");
	TOMCKEES_ROCKS = true;
	return true;
end
Function06Name, Function06Label = TOMR, "T.O. McKees Rocks";
--[[---------------------------------------------------------------------------------------]]
function TOY()
	print("Train Order Youngstown Button()");
	TOYoungstown = true;
	return true;
end
Function07Name, Function07Label = TOY, "T.O. Youngstown";
--[[---------------------------------------------------------------------------------------]]