% TransmissionTemplate.m
% Template script for transmission of data from UCLA to UC.
% Will_Ferenc@hmc.edu
% 14 July 2011
% 2011 UCLA Applied Math REU

%=-=-=-=-=-=-=-=-=-=-=-=-=-=-=Instructions=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=
% This software is designed to allow communication and transfer of data
% between the UCLA AML in Los Angeles and the UC Robotics Lab in
% Cincinatti.
% General Usage:
% 0. Communicate with other office and determine daily parameters.
% 1. Check the constants in the CONFIGURATION DEFAULTS section.
% 2. Ensure serial transmitter is connected and functioning. Note its port.
%-------------------------------------------------------------------------

%=-=-=-=-=-=-=-=-=-=-=-=-CONFIGURATION DEFAULTS-=-=-=-=-=-=-=-=-=-=-=-=-=-=
PORT = [2448, 2448]; %[localPort, remotePort]
COM = 'COM5';
pause on
%-------------------------------------------------------------------------

display('Welcome to UCLA AML Transmission Software');
display('Select configuration options:');
display('Default -OR- Custom');
configMethod = input('>>>','s');
if(strcmpi(configMethod, 'default'))
    %use defaults
    REMOTEIP = input('Please input IP address of remote station','s');
else
    %begin custom configuration
    display('Begin Configuration');
    display('Please input IP address of remote station:\r\n');
    REMOTEIP = input('>>>','s');
    display(strcat('Serial COM Port Configuration. Default is ',COM));
    COM = input('Wi232 Device: ','s');
    display(strcat('TCP/IP Port Information. Default is',...
                    int2str(PORT(1)),', ',int2str(PORT(2)),'.'));
    display('Note: port overuse is possible');
    PORT(1) = input('Local Port: ');
    PORT(2) = input('Remote Port: ');
end

% Serial device config 
% wi232 = serial(COM, 'BaudRate', 115200);
try
% fopen(wi232);
% catch
%     set(wi232,'PORT','COM5');
%     fopen(wi232);
% end
% Setup tcpip object for internet data transfer.
tcpipClient = tcpip(REMOTEIP,'RemotePort',PORT(2),'LocalPort',PORT(1));
set(tcpipClient, 'Timeout', 99); %Allow long timeout for initial connection
display('Configureation complete. Ensure other party is online.');
display('Press ENTER to connect.');
pause();
try
fopen(tcpipClient);
catch err
    display(err);
end
set(tcpipClient, 'Timeout', 1); %Resume short timeout for normal running


while(1) % loop (infinite, I'm sorry)
    if(tcpipClient.BytesAvailable ~= 0) %as soon as data is available
        dataRecd = fread(tcpipClient,64,'double'); % get data from buffer
        fwrite(tcpipClient,dataRecd,'double'); %write data back
        fwrite(wi232,dataRecd,'double');
    end
%     if(wi232.BytesAvailable ~= 0)
%         dataRecd = fread(wi232,64,'double');
%         fwrite(tcpipClient,dataRecd,'double');
%     end
end

fclose(tcpip);
% fclose(wi232);