%% Wireless serial interface via Bluetooth 
%***Instrument control toolbox is needed***
% Bluetooth connection via HC-06 (slave) and BT-Dongle ASUS BT-400 (master)  
% FIFO - buffer - example with 
% data monitor and 
% data-logging on harddisk
% based on DEMOAI_FFT.m and own m-code collection
% S.Guttke, HTWK Leipzig, 2014

close all hidden% close all opend and also hidden figures  
clear all       % clear all workspace variables
clc             % clear command window
comments = 1;   % If status comments are wanted 0 no, 1 yes
fullscreen = 0; % 1-if the monitor should fill the screen, 0-small 
fs=100;         % samplarate of source AI-system
dt=1/fs;        % timestep for time vector

measure = 1;    % Control parameter for measure = "0" off, "1" on 
numbersum = 0;  % counter for aquired values
i=1;            % Counter for "waiting for new Datata"-loop

window=5000;       % FIFO window-size number of numbers
Data=zeros(1,5); % testdata for a start
Time=[1:1:5]*dt; % time values for the start

if comments==1  disp('Starting file!'); pause(1); end 

%% Get system time for the name of logging file
if comments==1  disp('get system time'); pause(1); end 
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
if comments==1  disp('prepairing log file on disk'); pause(1); end  
datapath = pwd;  % also possible: datapath = 'c:\datacontainer\';
file = 'pulse';  % file=char(inputdlg('enter a filename')); %name of data

%make string filename for the use at dlmwrite
filename=[datapath,'\', file,'_logfile_',SaveTime,'.txt']; 


%% Make logging-file to log data-stream to disk
 if comments==1  disp('make log file on disk'); pause(1); end  
%dlmwrite('DataFile.txt',Data,'delimiter',' '); %direct way
 dlmwrite(filename,Data,'-append','delimiter',' ');

%% Initialize monitor for visualisation of new data.
    if comments==1  disp('initialize monitor window'); pause(1); end
    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);
    if fullscreen == 1   
        figWidth=1200; %a bit bigger, original 600
        figHeight=900; %a bit bigger  original 360
    else
        figWidth=400; %a bit bigger, original 600
        figHeight=240; %a bit bigger  original 360
    end
    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.130 0.150 0.800 0.700],...
       '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');

    %% For a 2. subplot for more channels use the 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'')');

%% Store the handles; the handles are here not in use
    % 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;

    %  First make figure hAxes invisible not to see it with close all
    % % 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


%% Bluetooth-connection start
    if comments==1  disp('deleting all interface-objects'); pause(1); end
    delete(instrfind)
    %fclose(instrfind)
    %% get information about availible bluetooth adapters
    %h=instrhwinfo('Bluetooth');
    % % ans = 
    % % 
    % %         RemoteNames: {'guttke1HC-06'}
    % %           RemoteIDs: {'btspp://98D3319005AB'}
    % %     BluecoveVersion: 'BlueCove-2.1.1-SNAPSHOT'
    % %      JarFileVersion: 'Version 3.2'  
    % instrhwinfo('Bluetooth','guttke1HC-06')
    % % ans = 
    % % 
    % %                RemoteName: 'guttke1HC-06'
    % %                  RemoteID: 'btspp://98D3319005AB'
    % %     ObjectConstructorName: {'Bluetooth('guttke1HC-06', 1);'}
    % %                  Channels: {'1'}
    if comments==1  disp('creating bluetooth object'); pause(1); end
    BT =Bluetooth('guttke1HC-06', 1); %lege BT-Objekt an
    BT.InputBufferSize=200E3; 

    if comments==1 disp('open serial Bluetooth connection'); pause(1); end
    fopen(BT) % ffne BT-Objekt , LED am HC-06 muss leuchten
        %fwrite(b, uint8([2,0,1,155]));
    if comments==1 disp('Bluetooth connection open when...'); end
    if comments==1 disp('LED on, not blinking');pause(1); end% 

%% FIFO - Routine for getting new data
while measure == 1 %Solange gemessen werden soll (f r Gui vorbereitet)
     
     bytes = BT.bytesavailable; %number of bytes in the inputbuffer
     if comments==1 disp(['newbytes: ',num2str(bytes)]); end 
     
     while bytes == 0 %Warte auf neue Daten im Inputbuffer
          if comments==1 disp(['waiting ',num2str(i),'s']); end %just if wanted 
          pause(1)
          bytes = BT.bytesavailable; %update bufferinfo
          if measure==0 , break, end %quit loop, if measure=0
          if i>5  %when more than 5 loops stop the waiting for data
              measure=0; 
          end %Wenn >10xWarten dann Abbruch
          i=i+1; %counter for waiting loops
    end
    i=0;
    %DataIn = fread(BT,BT.bytesavailable);
    %DataInChar = char(DataIn)';%All Ascii-numbers into Ascii-chars change 
    %DataInInt= str2num(DataInChar)
    %DataInChar=char(DataIn');
    %DataInfloat= sscanf(DataInChar,'%f');
    %DataInfloat= sscanf(BT,'%f');
    
    %% getdata from BT-object direct as float values
    if comments==1  disp(['get bytes ',num2str(bytes)]); end  
    Datanew= fscanf(BT,'%f')'; % getdata from BT as float values and 
    %transpose the vector into row
    %ASCII alternativ way: 
    %Datanew = char(fread(BT,BT.bytesavailable)');
    %DataIn= str2num(DataInChar); or DataInfloat= sscanf(DataInChar,'%f');
    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.
   
    if comments==1  disp('writing'); end 
    %dlmwrite('DataFile.txt',Data,'delimiter',' '); %direct form
    dlmwrite(filename,Datanew,'-append','delimiter',' ',...
        'coffset',1);
    %'coffset' is important to get 'space' between the data packages
    %type('myFile.txt') %Display contents of file could be used
     
    %% filling the FIFO-buffer 
    if comments==1  disp('FIFO'); end 
    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)]);
     
    
    drawnow; %make all changes valid and working
    
   
end

if comments==1 disp('Close Bluetooth connection!'); end
 fclose(BT)
 delete(BT)
 clear BT
 disp('End of reading!');
 
 %% code for a serial version
%serialInfo = instrhwinfo('serial'); 
%ports=serialInfo.AvailableSerialPorts
% instrfind
% %delete(instrfind)
% %s = serial('COM8','BaudRate',115200,'StopBits',1,'DataBits',8,'Parity','none','Terminator','CR/LF');
% s = serial('COM9','BaudRate',115200,'StopBits',1,'DataBits',8,'Parity','none');
% s.InputBufferSize = 1E5;
% %out = isvalid(s2)
% %out1 = get(s);
% %out2 = get(s,{'BaudRate','DataBits'});
% %get(s,'Parity')
% %s.BaudRate = 300
% 
% fopen(s)
% %fprintf(s,'*IDN?')
% % 
% % while  s.TransferStatus 
% numbernew = s.bytesavailable
% % end
% % 
% % settings = fgets(s)
% % settings =
% % 9600;0;0;NONE;LF
% % length(settings)
% % ans =
% %     17
% if measure == 1 %nur wenn gemeasure werden soll
%     while numbernew > 20
%     numbernew = s.bytesavailable     
%     numbersum = numbersum+numbernew;
%     DataIn = fread(s);
%     Data=[Data, DataIn]
%     end
% end
% fclose(s)
% delete(s)
% clear s