%% FIFO file for evaluation and development
% FIFO - buffer - example with 
% data monitor and 
% data-logging on harddisk
% based on DEMOAI_FFT.m and own m-code collections
% S.Guttke, HTWK Leipzig, 2014

clear all
close all
clc
fs=100; % samplarate of source AI-system
dt=1/fs; % timestep for time vector

window=30 %window-size for size of the FIFO-buffer
Data=1:1:10; %Testdata for a start (that are the input data)
Time=[1:1:10]*dt; % time values for the start


% Take System Time for the name of logging file
SysTime=clock; %System time as year, month, day, hour, minute, seconds
SaveTime=[num2str(SysTime(1)) ,'_', num2str(SysTime(2)),...
    '_', num2str(SysTime(3)),'_', num2str(SysTime(4)),'_',...
    num2str(SysTime(5))];


%% Prepairing the loggingfile on harddisc for datalogging
datapath = pwd;  %also possible: datapath = 'c:\datacontainer\';
file = 'ECG'; %file=char(inputdlg('enter a filename')); %name of data
filename=[datapath,'\', file,'_logfile_',SaveTime,'.txt']; %for use at dlmwrite


% %example for save figure and a variable
%  saveas(handles.freqgang,[datapath 'Bodediagramm_',...
%      SaveTime,'.fig']); % save bodeplot figure to harddisc
%  save([datapath 'Data_',SaveTime,'.mat'],'D'); % save data matrix to harddisc


%% Initialize logging-file to log all AI-data to disk
 %dlmwrite('DataFile.txt',Data,'delimiter',' '); %direct way
 dlmwrite(filename,Data,'-append','delimiter',' ');

%% function data = localInitFig(data) % adapted from demoai_FFT.m 

    %% 
    % Initialize variables.
    btnColor=get(0,'DefaultUIControlBackgroundColor'); %screen (0) color

    %%
    % Position the GUI in the middle of the screen
    screenUnits=get(0,'Units');
    set(0,'Units','pixels');
    screenSize=get(0,'ScreenSize'); %get pixels of the screen
    set(0,'Units',screenUnits);
    figWidth=1200; %a bit bigger, original 600
    figHeight=650; %a bit bigger  original 360
    figPos=[(screenSize(3)-figWidth)/2 (screenSize(4)-figHeight)/2  ...
          figWidth                    figHeight];
    %see help "Positioning Figures" [left bottom width height]  
    %%
    % Create the figure window, but let it not visible (off)
    hFig=figure(...                    
       'Color'             ,btnColor                 ,...
       'IntegerHandle'     ,'off'                    ,...
       'DoubleBuffer'      ,'on'                     ,...
       'DeleteFcn'         ,'',...
       'MenuBar'           ,'none'                   ,...
       'HandleVisibility'  ,'on'                     ,...
       'Name'              ,'Input Monitor'  ,...
       'Tag'               ,'Input Monitor Tag'  ,...
       'NumberTitle'       ,'off'                    ,...
       'Units'             ,'pixels'                 ,...
       'Position'          ,figPos                   ,...
       'UserData'          ,[]                       ,...
       'Colormap'          ,[]                       ,...
       'Pointer'           ,'arrow'                  ,...
       'Visible'           ,'off'                     ...
       );
        %'DeleteFcn'         ,'demoai_fft(''close'',gcbf)',... ->here none
    %%
    % Create 1. Data subplot into Parent hfig. Here just one plot 
    hAxes(1) = axes(...
       'Position'          , [0.0700 0.1300 0.900 0.775],...
       'Parent'            , hFig,...
       'XLim'              , [0 dt*window],...
       'YLim'              , [-3 3]...
       );
        %'Position'          , [0.1300 0.5811 0.7750 0.3439]
        %'XLim'              , [0 get(data.ai, 'SamplesPerTrigger')],...
    %%
    % Plot the data.
    hLine(1) = plot(Time, Data); % is the line of values on the subplot
    set(hAxes(1), 'XLim', [Time(1) Time(end)]);
%     hLine(1) = plot(data.getdata(:,1));
%     set(hAxes(1), 'XLim', [0 get(data.ai, 'SamplesPerTrigger')]);
    

    %%
    % Label the plot.
    xlabel('t / s');
    ylabel('U / V');
    title('Datenmonitor');

%     %% In the case of a 2. Subplot take this following code
%     % Create the FFT subplot.
%     hAxes(2) = axes(...
%        'Position'          , [0.1300 0.1100 0.7750 0.3439],...
%        'Parent'            , hFig,...
%        'XLim'              , [0 max(data.daqfft(:,1))]...
%        );
% 
%     %%
%     % Plot the data.
%     hLine(2) = plot(data.daqfft(:,1),data.daqfft(:,2));
%     set(hAxes(2), 'XLim', [0 max(data.daqfft(:,1))]);
% 
%     %%
%     % Label the plot.
%     xlabel('Frequency (Hz)');
%     ylabel('Magnitude (dB)');

%     %%
%     % Create a start/stop pushbutton.
%     htoggle = uicontrol(...
%        'Parent'          , hFig,...
%        'Style'           , 'pushbutton',...
%        'Units'           , 'normalized',...
%        'Position'        , [0.0150 0.0111 0.1 0.0556],...
%        'Value'           , 1,...
%        'String'          , 'Stop',...
%        'Callback'        , 'demoai_fft(''stop'', gcbf);');

% %% now are made menu buttons on the figure (here not used)
%     hmenu(1) = uimenu('Parent', hFig,...
%        'Label', 'File');
%     hmenu(2) = uimenu(hmenu(1),...
%        'Label', 'Close demoai_fft',...
%        'Callback', 'demoai_fft(''close'',gcbf)');
%     hmenu(3) = uimenu('Parent', hFig,...
%        'Label', 'Help');
%     hmenu(4) = uimenu(hmenu(3),...
%        'Label', 'Data Acquisition Toolbox',...
%        'Callback', 'helpwin(''daq'')');
%     hmenu(5) = uimenu(hmenu(3),...
%        'Label', 'demoai_fft',...
%        'Callback', 'helpwin(''demoai_fft'')');

%% the handles are here not used
    % Store the handles in the data matrix.
    data.handle.figure = hFig;
    data.handle.axes = hAxes;
    data.handle.line = hLine;
 %   data.handle.toggle = htoggle;
 %   data.state = 0;

    %%
 %   % Set the axes handlevisibility to off.
 %   set(hAxes, 'HandleVisibility', 'off');

    %%
     % Store the data matrix and make figure visible.
     set(hFig,'Visible','on','UserData',data,'HandleVisibility', 'off');

%     %%
%     % Configure the callback to update the display.
%     set(data.ai, 'TimerFcn', @localfftShowData);
drawnow; %make all changes valid and working

%% FIFO - Routine 

% The loop can be controlled by a variable like while measure == "1" , "0"
% here just a number of loops for some tests
for i = 1:300
 % aquire new Data from AI- or RS232- or ...-interface (number can change)   
    Datanew=round(rand(1,5)*100); %for a test just random values
    Nvalue=length(Datanew);  %number of new values

    %% Append new data into the ASCII (_.txt) file (see current folder)
    % the file-size could be limited with a counter of values and than 
    % an Index in the filename can be increased.
    
    %dlmwrite('DataFile.txt',Data,'delimiter',' '); %direct form
    dlmwrite(filename,Datanew,'-append','delimiter',' ',...
        'coffset',1); % 'roffset', 1); 
    %'coffset' is important to get 'space' between the data packages
    %type('myFile.txt') %Display contents of file could be used
     
    
 % fill the FIFO-buffer 
    if length(Data)<=window  %until size of window is achieved  
        Data=[Data Datanew]; % collect all data as stream in a variable 
        %here in a row vector
        Time=(1:1:length(Data))*dt; % create a time vector for plotting 
    
    else %when more data as the wanted windowsize is available
         Data=[Data Datanew]; % collect all data as stream in a variable
         Time=[Time ((1:1:length(Datanew))*dt)+Time(end)]; 
         %create a matching time vector
         
 % cutting the FIFO-buffer, all data that is older than the window size 
         Ndata=length(Data); 
         Data=Data(Ndata-window:Ndata);
         Time=Time(Ndata-window:Ndata);
    end
    
   %%
% Update just the contents of the figure.
set(hLine(1), 'XData', Time, 'YData', Data);
%set(hLine(2), 'XData', f(:,1), 'YData', mag(:,1));
set(hAxes(1), 'XLim', [Time(1) Time(end)]);
% 
%% ask for button start / stop
% str=get(data.handle.toggle, 'String');
% if strcmp(str,'Start')
%     set(data.handle.toggle, 'String', 'Stop');
% end

drawnow; %make all changes valid and working
    
    
end
%fclose(ai)
%delete(ai)
clear all
