--[[
---------------------------------------------------------------------------
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 = "Signals - P&LERR"
--
-- Signal Processing runs on PC2 
--
require("defines");
require("functions");

TagCount = 0;
-- Counter Labels
Counter01Label = "Detected";
Counter02Label = "Signals";
Counter04Label = "State";

Tags = {};		-- table to hold all of the tags detected in sequence
TagCount = 0;
-- state machine states
IDLE = 0;
SM = IDLE;
--[[---------------------------------------------------------------------------------------]]
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();	
	--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

	print("TIU : " .. TIU);
	assert((TIU >= 1 and TIU <= 5),"TIU Number out of range");
	SM = IDLE;
	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(COUNTER01);	

	-- 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)));
		-- 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
	
	-- 
	print("Process Signal");	
	BumpCounter(COUNTER02);	
	-- Detection of engine tag causes the trailing signal to go red

	-- Detection of caboose tag causes the trailing signal to go green
	
	
--[[---------------------------------------------------------------------------------------]]
-- 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(Engine, TIU)
	-- 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
--[[---------------------------------------------------------------------------------------]]