%% XCP Direct Data Acquisition
% This example shows how to use XCP connections to directly acquire
% measurement values from a slave. It uses a freely available XCP slave 
% simulator from Vector and Vector virtual CAN channels. For access to virtual 
% channels, Vector device drivers must be installed. It is also
% recommended to run Vehicle CAN Bus Monitor in conjunction with this example.
%
% Copyright 2012-2018 The MathWorks, Inc.

%% Run a Slave Simulator
% This example requires installing a free, third-party XCP implementation 
% from Vector. The package includes an XCP slave simulator and A2L file. To
% install this driver, please follow these instructions:
%
% # Go to www.vector.com and navigate to the "DOWNLOADS" page.
% # Search for "Demos" under "Categories" and "XCP" under "Standards".
% # Download and install the available version of "XCP Sample 
%   Implementation".
% # In MATLAB, navigate to where you installed the sample package, and
%   then go to .\Samples\XCPSim\CANape.
% # The MATLAB XCP examples will use the XCPSIM.a2l file and the
%   XCPsim.exe slave simulator. Run XCPsim.exe.

%% Open the A2L File
% Establishing a connection to an XCP slave requires using the A2L file that
% describes the slave module.
a2lObj = xcpA2L('XCPSIM.a2l')

%% Create an XCP Channel
% Create an XCP channel to prepare a connection to the slave.
xcpCh = xcpChannel(a2lObj, 'CAN', 'Vector', 'Virtual 1', 1)

%% Connect to the Slave
% To make communication with the slave active, connect to it.
connect(xcpCh)

%% Directly Acquire Measurement Samples
% Acquire some samples of a measurement from the slave.
readSingleValue(xcpCh, 'channel3')
readSingleValue(xcpCh, 'channel3')
readSingleValue(xcpCh, 'channel3')

%% Directly Acquire a Series of Measurement Samples
% Using a loop, acquire and plot many measurement samples from the slave.
allSamples = [];
for ii = 1:50
    newSample = readSingleValue(xcpCh, 'channel3');
    allSamples = [allSamples newSample];
end
plot(allSamples)

%% Disconnect from the Slave
% To make communication with the slave inactive, disconnect from it.
disconnect(xcpCh)
