--[[
---------------------------------------------------------------------------
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
-- ftp Transfer Test
title = "UDP Client Test"
-- load the socket support and its friends
local socket = require("socket")
print(socket._VERSION)

local ip, port;
local udp;
local ReceivedTagCount = 0;
local TimeoutSeconds = 5;
--[[---------------------------------------------------------------------------------------]]
function setup() 
--
-- Setup the sketch as a Client. Use "server.lua" to serve packets.
-- Server sends one packet each time that Client runs and requests a packet.
--
local socket = require("socket")
port = 8888;
--ip = "*";	-- this failed to receive packet from client if the ip = "*"
--ip = "127.0.0.1";			-- this works
--ip = "0.0.0.0";			-- this does not work
ip = "192.168.1.100";		-- this works	

udp = socket.udp()
udp:setoption('reuseaddr',true);
udp:setpeername(ip, port)
udp:settimeout(TimeoutSeconds)

index, err, lastindex = udp:send("Data!")
if (index == nil) then
	print("send() error : " .. err);
	end;
print("Sent Request Packet");
print("Wait for Response Packet with ".. TimeoutSeconds .. " second timeout");
data = udp:receive()
if data then
	ReceivedTagCount = ReceivedTagCount + 1;
    print("Received: " .. data .. " ip = " ..  ip .. " port " .. port)
	return Stop();
end
print("No Request Packet Received");
return Stop();
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(ReceivedTagCount .. " Tags Received");
	udp:close();
	return true;		-- false=cleanup failed, true=cleanup succeeded
	end
--[[---------------------------------------------------------------------------------------]]

