%% Event Triggered CAN Message Transmission
% This example shows you how to use the automated CAN message transmit
% features of Vehicle Network Toolbox(TM) to send messages on event. It 
% uses MathWorks Virtual CAN channels connected in a loopback configuration.
% As this example is based on sending and receiving CAN messages
% on a virtual network, running Vehicle CAN Bus Monitor in conjunction may
% provide a more complete understanding of what the code is doing. To
% run Vehicle CAN Bus Monitor, open and configure it to use the same 
% interface as the receiving channel of the example. Make sure to start 
% Vehicle CAN Bus Monitor before beginning to run the example in order to 
% see all of the messages as they occur.
%
% Copyright 2010-2016 The MathWorks, Inc.


%% Create the CAN Channels
% Create CAN channels on which to use the automated message transmit
% commands.
txCh = canChannel('MathWorks', 'Virtual 1', 1);
rxCh = canChannel('MathWorks', 'Virtual 1', 2);

%%
% In this example, you will use a CAN database file to define and decode
% messages. Open the database and attach it to the CAN channels.
db = canDatabase('demoVNT_CANdbFiles.dbc');
txCh.Database = db;
rxCh.Database = db;

%% Create the CAN Message
% You can create a CAN message to register for event transmit using the
% database information.
msgEngineMsg = canMessage(db, 'EngineMsg')

%% Configure the Message for Event Transmit
% To configure a message for event transmit, use the |transmitEvent|
% command to specify the channel, the message to register on the channel,
% and a mode value.
transmitEvent(txCh, msgEngineMsg, 'On');

%% Start the Event Message Transmit
% Start the channels and write the new values to either the Data property 
% or directly to the signals to trigger automatic event-based transmission
% of the message onto the CAN bus.
start(rxCh);
start(txCh);
msgEngineMsg.Data = [250 100 0 0 20 0 0 0];
pause(1);
msgEngineMsg.Signals.VehicleSpeed = 60;
pause(1);
stop(txCh);
stop(rxCh);

%% Analyze the Event Transmit Behavior
% The receiving channel now has two messages available, corresponding to
% the two updates that resulted in two transmits. 
rxCh

%%
% Receive and inspect each message to see that each has the data values 
% previously set.
msgRx = receive(rxCh, Inf, 'OutputFormat', 'timetable')
signals = canSignalTimetable(msgRx)

%% View Messages Configured for Event Transmit
% To see messages configured on a channel for event transmit, use the
% |transmitConfiguration| command.
transmitConfiguration(txCh)
