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

© Copyright 2022 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
-- Tape Reading using Lua Sockets
title = "Tag Reader Test UDP w/Lua Sockets"
--
-- This sketch communicates with Tag Detectors using the UDP sockets support built into
-- Lua. This is different than the "normal" RTC Program Control based sketches. Those
-- sketches call complied c++ code that interfaces with components contained in the Internet 
-- Suite by Francois Piette (ICS) v5r20 for BCB4.0/6.0 code and v8w (pre v8.8) for CB10.1.
--
-- load the socket support and its friends
-- https://defold.com/ref/alpha/socket/
local socket = require("socket")
print(socket._VERSION)

local ip, port = "0.0.0.0", 8899;
local udp;
local ReceivedPacketCount = 0;
local TimeoutSeconds = 15;
--[[---------------------------------------------------------------------------------------]]
function setup() 
--
-- Setup the sketch as a server
--
port = 8899;	-- UDP Socket in RTC Program
--ip = "*";	-- this failed to receive packet from client if the ip = "*" in luasocket 3.0-rc1 (CB10.1)
			-- works ok in luasocket 2.0.2a (BCB4 and BCB6)
			-- in 2.0.2a, getsockname returns "0.0.0.0"
			-- in 3.0-rc1 getsockname returns "::"
--ip = "";	-- in 3.0-rc1 getsockname returns the ipv6 address eg: fe80::153c:6f9b:81b0:c9b3%15
--ip = "192.168.1.100";	-- this works but means we need to know our ip address which is hard to find
ip = "0.0.0.0";			-- this works with luasocket 2.0.2a and with luasocket 3.0-rc1
						-- using this value, getsockname() returns "0.0.0.0" in both versions of luasocket.
						-- We are binding to all possible ip for the local computer, ie 127.0.0.1 and
						-- its real ip address ie 192.168.1.100
--ip = "127.0.0.1";		-- this does not work

udp = socket.try(socket.udp());
udp:setoption('reuseaddr',true);	-- no effect that I can see
local success, err;
success, err = udp:setsockname(ip, port);
if (not success) then
	print("udp:setsockname failed for port " .. port .. " - " .. err);
	return Stop();
	end;
local newip, newport;
newip, newport = udp:getsockname();
if (newip) then
	print("udp:getsockname ip " .. newip);
	end;
if (newport) then
	print(" - port " .. newport);
	end;
--
udp:settimeout(TimeoutSeconds);	-- timeout in seconds, 0 = none, nil = infinite	
-- Now receive packets from the ESP8266
print("Listening on port " .. port);
return true;
end
--[[---------------------------------------------------------------------------------------]]
function loop()
	-- receive response(s) waiting for timeout seconds
	local data, ip, port = udp:receivefrom();
	if (data == nil) then	-- timedout
		print("Socket - " .. TimeoutSeconds .. " second timeout. " .. "(" .. ip .. ")");
		return Stop();
		end
	print("Packet : " .. data .. " (From " .. ip .. " - " .. port .. ")");
	ReceivedPacketCount = ReceivedPacketCount + 1;
	Yield();	-- check for [STOP] or function button
return true;
end
--[[---------------------------------------------------------------------------------------]]
function cleanup(Engine, TIU)
	-- this function is called once when the user presses the [STOP] button or the Stop() function is called
	print("cleanup() Running");
	print(ReceivedPacketCount .. " Packets Received");
	udp:close();
	return true;		-- false=cleanup failed, true=cleanup succeeded
	end
--[[---------------------------------------------------------------------------------------]]

