%% Create and Use J1939 Channels
% This example shows you how to use Vehicle Network Toolbox(TM) with 
% J1939 to create and use J1939 channels to transmit and receive 
% parameter groups on a network. This example uses the CAN database 
% file, |J1939.dbc|. It also uses MathWorks Virtual CAN channels connected 
% in a loopback configuration
%
% Copyright 2015-2016 The MathWorks, Inc.

%% Open the Database File 
% Open the database file to access the definitions.
db = canDatabase('J1939.dbc');

%% Create the J1939 Channels
% Create J1939 channels on which you can send and receive information.
txCh = j1939Channel(db, 'MathWorks', 'Virtual 1', 1)
rxCh = j1939Channel(db, 'MathWorks', 'Virtual 1', 2)

%% Create the J1939 Parameter Groups
% You can create J1939 parameter groups to send on the network.
pgSingleFrame = j1939ParameterGroup(db, 'VehicleDataSingle')
pgSingleFrame.SourceAddress = 30;
pgSingleFrame.DestinationAddress = 50;
pgMultiFrame = j1939ParameterGroup(db, 'VehicleDataMulti')
pgMultiFrame.SourceAddress = 30;
pgMultiFrame.DestinationAddress = 255;

%% Start the J1939 Channels
% To begin using channels for transmit and receive operations, place
% them online.
start(rxCh);
start(txCh);

%% Send J1939 Parameter Groups
% The |transmit| function sends parameter groups onto the network.
% The J1939 channel automatically sends parameter groups requiring 
% multiframe messaging via its transport protocol.
transmit(txCh, pgSingleFrame)
transmit(txCh, pgSingleFrame)
transmit(txCh, pgMultiFrame)
transmit(txCh, pgSingleFrame)
transmit(txCh, pgSingleFrame)
pause(1);

%% Receive the Parameter Groups
% The |receive| function retrieves information from the channel which
% represents messaging that occurred on the network.
pgRx = receive(rxCh, Inf)

%% Inspect Received Parameter Groups
% View details of the received information.
pgRx(1)

%% Note Multiframe Reception
% Parameter groups sent using the transport protocol are reconstructed 
% in full detail by the channel.
pgRx(3)

%% Stop the J1939 Channels
% To stop receiving data from the network, stop the J1939 channels.
stop(rxCh);
stop(txCh);
