% Acquisition TSG45 - SBE38 - sans GPS
% Decodage et enregistrement dans un fichier horaire

disp('---------- START ---------------------');

% % % Create a serial port object for Interface box.
obj2 = instrfind('Type', 'serial', 'Port', 'COM1', 'Tag', '');
% % % Create the serial port object if it does not exist
% % % otherwise use the object that was found.
if isempty(obj2)
    obj2 = serial('COM1');
else
    fclose(obj2);
    obj2 = obj2(1);
end
% % % Set the BaudRate
obj2.BaudRate = 9600;
% Set the TimeOut
obj2.Timeout= 50;
obj2.RequestToSend = 'off';
% % % Connect to instrument object, obj2.
fopen(obj2);
disp('TSG port open');
date0 = 0.5;

%% Boucle infinie !

for i=1:10000000000000000

    datenow = datestr(now,30);
    datenow(09) = '_';
    datefile = str2num(datenow(8));
    %if str2num(date) ~= jour0;
    if datefile ~= date0
        % Fermeture du fichier si ouvert
        fclose('all');
        % Creation du fichier a partir de cette date et de l'heure courante
        filename = ['tsg_' datenow '.txt'];
        fid=fopen(filename,'w');
        disp([filename ' created now !']);
        date0 = datefile;
    end

    dataint = 'hello';
    %   disp([dataint '  ' num2str(i) '   ' num2str(obj2.ValuesReceived)]);
    while isempty(strmatch('t1=',dataint)) == 1
        % readasync(obj2);
        dataint = fgetl(obj2);
        %   disp([dataint '  ' num2str(i) '   ' num2str(obj2.ValuesReceived)]);
    end
    %   fclose(obj2);
    % Concatenation de DATE, TIME, Latitude, Longitude, T(38), T(45), C(45)
    datenow = datestr(now,30);
    datenow(09) = '_';
    text = [dataint ', hms=' num2str(datenow(10:end)) ', dmy=' num2str(datenow(7:8)) num2str(datenow(5:6)) num2str(datenow(3:4)) ];
    fprintf(fid,'%s\n',text);
    disp(text);
end


%% Free the serial ports
fclose(obj2);
close('all');
