close all

% --------- setup email
mail = 'TYPE EMAIL HERE';
password = 'TYPE PASSWORD HERE';
setpref('Internet','SMTP_Server','smtp.gmail.com');
setpref('Internet','E_mail',mail);
setpref('Internet','SMTP_Username',mail);
setpref('Internet','SMTP_Password',password);
props = java.lang.System.getProperties;
props.setProperty('mail.smtp.auth','true');
props.setProperty('mail.smtp.socketFactory.class', 'javax.net.ssl.SSLSocketFactory');
props.setProperty('mail.smtp.socketFactory.port','465');


num_point = 30;
theta_deg = linspace(0,180,num_point);
dist_range = linspace(0,30,6);

% create radius matrix: each row is 
radius = [];
radius = [radius; ones(1,num_point)*dist_range(6)];
radius = [radius; ones(1,num_point)*dist_range(5)];
radius = [radius; ones(1,num_point)*dist_range(4)];
radius = [radius; ones(1,num_point)*dist_range(3)];
radius = [radius; ones(1,num_point)*dist_range(2)];
radius = [radius; ones(1,num_point)*dist_range(1)];
radius = [radius; zeros(1,num_point)];

% setup the radar grid
figure(1);
whitebg(figure(1));
hold on
[row, col] = size(radius);

for i=1:row
    [x y] = pol2cart(theta_deg*pi/180, radius(i,:));
    field = plot(x,y,'--b');
end

pause(0.2);

%%%%%%%%%%% Simulating Radar Arm %%%%%%%%%%%%%%%%
radar_arm = radius';
[row, col] = size(radar_arm);


% --------- Since the rs232 is shared by the sensor and MATLAB, some
% streams are meant to sensor, and some are meant for MATLAB. The stream
% that is for MATLAB will have the format: [1, dist, pos, 1]
delete(instrfind);
s1 = serial('COM4', 'BaudRate', 9600);  % check port number before use
fopen(s1);
new_signal = 0;
while(1)
    % poll for data
    stream = fread(s1, 4)
    while(isempty(stream))
        stream = fread(s1, 4)
    end
    
    % set flag if new signal to MATLAB is detected
    if ((stream(1)==1) && (stream(4)==1))
        new_signal = 1;
        dist = stream(2)
        pos = stream(3)
    else
        new_signal = 0;
    end
    
    % Send email!
    if new_signal == 1
        disp('sending email!!!!!!!');
        d = datestr(now);
        sendmail('gm348@cornell.edu',['Security Notice ' date],['Detected on: ' d(length(d)-8:length(d))])
        
        % add trace in the radar plot
        [x y] = pol2cart(pos*6*pi/180, dist);
        field = plot(x, y, 'rs');
    end
    pause(0.1);
end





