% Direct-to-Disk logging example with Matlab

% Configuration options as defined in the DAPL script
nchan = 16;                 % number of channels in DAP board input configuration
nvalues = 1024;             % how many sample per block from each channel
nblocks = 10;               % how many blocks to collect from each channel
nbytes = nchan*nvalues*2;   % size of each block transfer in bytes

% open handle to DAP 'command input channel'
disp('opening handles to message and data channels')
texthandle = dapopen('\\.\dap0\$sysin', 'write');
if texthandle == -1
    error('Error opening DAP command text handle')
end

% open handle to DAP 'message text output channel'
msghandle = dapopen('\\.\dap0\$sysout', 'read');
if msghandle == -1
    error('Error opening DAP message text handle')
end

% open handle to DAP 'binary data output channel' in disk logging mode
iohandle = dapopen('\\.\Dap0\$BinOut', 'diskio');
if iohandle == -1
    error('Error opening DAP IO handle')
end

% Configure DAP board using DAPL command file 'MLogCfg.dap'
disp('configuring DAP board')
cnfg = dapcnfig(texthandle, 'MLogCfg.dap');
if cnfg < 1
    % Print error message
    error('Error configuring DAP')
end

% Sanity check: any error messages from parsing the script?
dappstr(texthandle,'DISPLAY EMSG');
pause(0.2)
iavail = dapgavl(msghandle);
if iavail  > 2
    msg = dapgstr(msghandle,2.0);
    disp(msg)
end

% Start the logging, flushing any stale previously received
disp('Log data until file size is:'); disp(nbytes*nblocks)
status = daplogpd(iohandle,'FlushBefore','h:\tmp\logfile.log', ...
    'read', 'CreateAlways', 'normal', nbytes*nblocks, nbytes);
disp('daplogpd reported operating status '); disp(status)

% Ready to start the sampling and data transfers
disp('starting the data capture now')
dappstr(texthandle,'START')

% Do various other things while waiting for data
runtime = 10.25;
disp('allowing plenty of time to collect the data:'); disp(runtime);
pause(runtime);

% Don't leave anything running on DAP after logging data
disp('stopping the DAP processing now')
dappstr(texthandle,'RESET')

% Terminate the logging process by closing data stream handle
disp('closing DAP handles')
close = dapclose (iohandle);
if close==-1
    error('Error closing DAP binary data stream handle to terminate logging')
end

% close handles to DAP communication channels
close = dapclose(texthandle);
if close==-1
    error('Error closing DAP command text handle')
end

close = dapclose(msghandle);
if close==-1
    error('Error closing DAP message return handle')
end
