--[[
---------------------------------------------------------------------------
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
-- Tag Detection Test
title = "Tag Detection Test (Using Active Engines)";
require("defines");
require("functions");

TagCount = 0;
-- all tables in Lua are 1 based, that is, T[1] is the first item in the list
EngineDetectionOrder = {};	-- clear the tables
EnginesUsedNum = {};
EnginesUsedFlag = {};
EngineSpeedSave = {};
Got = {};
iEngineCount = 0;

Tags = {};		-- table to hold all of the tags detected in sequence
-- Counter Labels
Counter01Label = "Engine Tags";
Counter02Label = "Car Tags";

-- Configuration Variables
AutoBellWhistle = true;
	
--[[---------------------------------------------------------------------------------------]]
function setup(Engine, TIU)
	-- 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()");
	-- make sure that RFID is connected
	TIUSerialPortConnected, TIUConnected, RFIDSerialPortConnected = CommStatus();
	if (not RFIDSerialPortConnected) then
		print("RFID Port must be enabled for this script");
		return false;	-- false=setup failed
		end

	MyEngineNo = Engine;	-- Engine number selected on the RTC Main window
	MyTIUNo = TIU;		-- TIU number selected on the RTC Main window
	-- debug level as selected on the Debug window, values 0 (off) to 9 (maximum)
	if (Debug() > 0) then 
		print(string.format("setup(): Debug level %d", Debug())); 
		print("setup(): Engine Number " .. MyEngineNo .. " TIU Number " .. MyTIUNo);
		end
	print("TIU : " .. MyTIUNo);
	assert((MyTIUNo >= 1 and MyTIUNo <= 5),"TIU Number out of range");
	--

	for iEng = 1, 99 do	-- check all possible engines on one TIU
		if (Exists(iEng)) then
			if (IsActive(iEng)) then
				print("Engine " .. iEng .. " Starting");
				EngineStartUp(iEng, MyTIUNo);
				Sleep(2);
				end
			end
			
		if (IsEngineRunning(iEng)) then	-- IsEngineRunning() REQUIRES use of StartUpActiveEngines() or EngineStartUp()
			print(string.format("Initalizing Engine %d", iEng));
			-- save the numbers of all started engines
			iEngineCount = iEngineCount + 1;			-- Count the number of engines running
			EnginesUsedNum[iEngineCount] = iEng;		-- EnginesUsedXXXX[] is 1 based
			EnginesUsedFlag[iEngineCount] = NOTDETECTED;-- flag as not yet detected in motion
	   		-- Numberboards
			Setting(CMD_NUMBERBOARDS_ON,  18, iEng, MyTIUNo);	-- not a dedicated switch
			-- Set smoke off
			Smoke(OFF, 2, iEng, MyTIUNo);
			-- Cab Chatter Off
			CabChat(OFF, 3, iEng, MyTIUNo);
			-- Set Marker lights on
			Markers(ON, 15, iEng, MyTIUNo);
			-- Set Acc/Dec rate to 1/1 Smph/sec
			Rate(1, 1, 0, iEng, MyTIUNo);
			end
		end
	print(string.format("Engines Started %d", iEngineCount));
	-- Start each train moving forward - go slow to help insure tag detection
	-- Since we don't know the position of each engine, we start each at exactly
	-- the same speed at exactly the same time, once we have detected the engines
	-- and located them on the layout, we can vary the movement times and running speeds.
	for iDex = 1, iEngineCount do	-- for each running engine, set the speed to 12 Smph
		local iEng = EnginesUsedNum[iDex];	-- EnginesUsedXXXX[] is 1 based
		print(string.format("SetSpeed for Engine : %d", iEng));
		SetSpeed(19, 20, iEng, MyTIUNo);
		end

	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 is detected
	-- Line below shows a different way to quote a string using brackets
	Beep();	-- sound a tone

		if (EngineNo > 0) then	-- its an engine
			BumpCounter(COUNTER01);
			print(string.format([[tag() : Detector %d Reader %d EngineNo %d TagLocation %d EngineModel %d]],
				Detector, Reader, EngineNo, TagLocation, CarModel));
			else	-- it's a car
			BumpCounter(COUNTER02);
			print(string.format([[tag() : Detector %d Reader %d CarModel %d]],
				Detector, Reader, CarModel));
			-- ignore non engine tags
			return true;	-- true=continue to process tags, false=stop processing tags
			end

	-- The complete packet received is in TagPacket 
	-- (some of the most used fields have already been extracted into the first parameters to tag()
	--   First 8 digits are the 4 byte Tag UID in hexidecimal
	--   Final 32 digits are the 16 bytes of Block 4 Information read from the Tag in hexidecimal
	if (Debug() > 4) then print(string.format("Packet  %s", TagPacket)); end
	Tags[string.sub(TagPacket,1,8)] = string.sub(TagPacket,9);
	TagCount = TagCount + 1;	-- count the number of tags
	return true;	-- true=continue to process tags, false=stop processing tags
	end
--[[---------------------------------------------------------------------------------------]]
function cleanup(Engine, TIU)
	-- this function is called once when the user presses the [STOP] button
	-- this function is called once when the user presses the [STOP] button
	print("cleanup()");
	for idx,Engine in ipairs(EnginesUsedNum) do
		print(idx .. " Shutdown Engine " .. Engine);
		EngineShutdown(Engine, MyTIUNo);
		end	

	print("All Newly Detected Tags:");
	for k,v in  pairs(Tags) do		-- dump out the Tags table
		print(k .. "  " .. v);
		end
	print(string.format("cleanup() Complete at %.2f", RunTime()));
	--
	return true;		-- false=cleanup failed, true=cleanup succeeded
	end
--[[---------------------------------------------------------------------------------------]]
function tick(Engine, TIU)
	-- this is called once per second while waiting for RFID tags to arrive
	-- Do not call Sleep() from this function
	--print(string.format("RunTime = %.2f seconds", RunTime()));
	return true;
	end
--[[---------------------------------------------------------------------------------------]]
function PauseButton(Eng, TIU)
	print("PauseButton()");
	for idx,Engine in ipairs(EnginesUsedNum) do
		S1 = GetSetSpeed(Engine, MyTIUNo);	-- get Requested Speed
		print(idx .. " Pause Engine " .. Engine .. " Speed " .. S1);
		EngineSpeedSave[idx] = S1;
		SetSpeed(0, 0, Engine, MyTIUNo);
		end
	return true;
end
Function06Name, Function06Label = PauseButton, "Pause";
--[[---------------------------------------------------------------------------------------]]
function ResumeButton(Eng, TIU)
	print("ResumeButton()");
	for idx,Engine in ipairs(EnginesUsedNum) do
		S1 = EngineSpeedSave[idx];		
		print(idx .. " Resume Engine " .. Engine .. " Speed " .. S1);
		SetSpeed(S1, 0, Engine, MyTIUNo);
		end
	return true;
end
Function07Name, Function07Label = ResumeButton, "Resume";
--[[---------------------------------------------------------------------------------------]]
