close all
clear all

LogFileName = 'SpotTrackerLog.txt';

WatchCircleRadius = 200;  

RecipientList{1} = '8317769044@vtext.com';  %Andy (Verizon)
%RecipientList{2} = 'francoiscav@gmail.com';  %Francois
%RecipientList{3} = '4013685634@txt.att.net';  %Eric Martin  (ATT)
%RecipientList{4} = '8318182769@vtext.com';  %Jared (Verizon)


addpath('./jsonlab');

SpotFeedID = '0ebZm2RHKeR0E5NAzuLSovobaf1NggUgO';

LatAnchor = 36.7434;
LonAnchor = -121.8844;

SpotJSON_URL = ['https://api.findmespot.com/spot-main-web/consumer/rest-api/2.0/public/feed/' SpotFeedID '/latest.json'];

LastUpdateDateNum = 0;

while(1)

  if(now < datenum (2016, 3, 13, 2, 0, 0))
    UTC_Adjust = -8;
    TimeZone = 'PDT';
  else
    UTC_Adjust = -7;
    TimeZone = 'PST';
  end

[s, success] = urlread (SpotJSON_URL);
if(success)
  data=loadjson(s);
  MostRecentLat = data.response.feedMessageResponse.messages.message.latitude;
  MostRecentLon = data.response.feedMessageResponse.messages.message.longitude;
  MostRecentTime = data.response.feedMessageResponse.messages.message.dateTime;

  Distance = pos2dist(MostRecentLat,MostRecentLon,LatAnchor,LonAnchor,2)*1000;

  MostRecentDateNum = datenum(MostRecentTime(1:end-5),'yyyy-mm-ddTHH:MM:SS')+UTC_Adjust/24;

  if(MostRecentDateNum > LastUpdateDateNum)
   msg = ['Buoy is ' num2str(Distance,4) ' meters from the anchor at ' datestr(MostRecentDateNum) ' (' TimeZone ')   Lat: ' num2str(MostRecentLat) '   Lon: ' num2str(MostRecentLon)];   
   disp(msg);
   fid = fopen(LogFileName,'a');
   if(fid ~= -1)
     fprintf(fid,'%s\n',msg);
     fclose(fid);
   end
   if(Distance > WatchCircleRadius)
     for i = 1:length(RecipientList)
       sendmail(RecipientList{i},'Watch Circle Alarm:  ', msg);
     end
   end
   LastUpdateDateNum = MostRecentDateNum;
  end
else
  msg = ['Spot Tracker URL Read Failed at ' datestr(now) ' (' TimeZone ')' ];
  sendmail(RecipientList{1},'URL Warning: ', msg);
end

pause(3*60);

end
