Main Content

Create and Execute Callback Functions

Create Callback Functions

The power of using event callbacks is that you can perform processing in response to events. You decide which events with which you want to associate callbacks, and which functions these callbacks execute.

Note

Callback function execution might be delayed if the callback involves a CPU-intensive task, or if MATLAB® software is processing another task.

Callback functions require at least two input arguments:

  • The OPC object

  • The event structure associated with the event

The function header for this callback function illustrates this basic syntax.

function mycallback(obj,event)

The first argument, obj, is the toolbox object itself. Because the object is available, you can use in your callback function any of the toolbox functions, such as getdata, that require the object as an argument. You can also access all object properties, including the parent and children of the object.

The second argument, event, is the event structure associated with the event. This event information pertains only to the event that caused the callback function to execute. For a complete list of supported event types and their associated event structures, see Event Structures.

In addition to these two required input arguments, you can also specify application-specific arguments for your callback function.

Note

If you specify input arguments in addition to the object and event arguments, you must use a cell array when specifying the name of the function as the value of a callback property. For more information, see Specify Callback Functions.

Write a Callback Function

This example implements a callback function for a records acquired event. This callback function enables you to monitor the records being acquired by viewing the most recently acquired records in a plot window.

To implement this function, the callback function acquires the last 60 records of data (or fewer if not enough data is available in the toolbox engine) and displays the data in a MATLAB figure window. The function also accesses the event structure passed as an argument to display the time stamp of the event. The drawnow command in the callback function forces MATLAB to update the display.

function display_opcdata(obj,event)

numRecords = min(obj.RecordsAvailable, 100);
lastRecords = peekdata(obj,numRecords);
[i, v, q, t] = opcstruct2array(lastRecords);
plot(t, v);
isBad = strncmp('Bad', q, 3);
isRep = strncmp('Repeat', q, 6);
hold on
for k=1:length(i)
  h = plot(t(isBad(:,k),k), v(isBad(:,k),k), 'o');
  set(h,'MarkerEdgeColor','k', 'MarkerFaceColor','r')
  h = plot(t(isRep(:,k),k), v(isRep(:,k),k), '*');
  set(h,'MarkerEdgeColor',[0.75, 0.75, 0]);
end
axis tight;
ylim([0, 200]);
datetick('x','keeplimits');
eventTime = event.Data.LocalEventTime;
title(sprintf('Event occurred at %s', ...
  datestr(eventTime, 13)));
drawnow; % force an update of the figure window
hold off;

To see how this function can be used as a callback, see View Recently Logged Data.

Specify Callback Functions

You associate a callback function with a specific event by setting the value of the OPC object property associated with that event. You can specify the callback function as the value of the property in one of three ways:

The following sections provide more information about each of these options.

Note

To access the object or event structure passed to the callback function, you must specify the function as a cell array or as a function handle.

Use a Character Vector to Specify Callback Functions

You can specify the callback function as a character vector. For example, this code specifies the callback function mycallback as the value of the start event callback property StartFcn for the group object grp.

grp.StartFcn = 'mycallback';

In this case, the callback is evaluated in the MATLAB workspace.

Use a Cell Array to Specify Callback Functions

You can specify the callback function as a character vector inside a cell array.

For example, this code specifies the callback function mycallback as the value of the start event callback property StartFcn for the group object grp.

grp.StartFcn = {'mycallback'};

To specify additional parameters, include them as additional elements in the cell array.

time = datestr(now,0);
grp.StartFcn = {'mycallback',time};

The first two arguments passed to the callback function are still the OPC object (obj) and the event structure (event). Additional arguments follow these two arguments.

Use Function Handles to Specify Callback Functions

You can specify the callback function as a function handle.

For example, this code specifies the callback function mycallback as the value of the start event callback property StartFcn for the group object grp.

grp.StartFcn = @mycallback;

To specify additional parameters, include the function handle and the parameters as elements in the cell array.

time = datestr(now,0);
grp.StartFcn = {@mycallback,time};

If you are executing a local callback function from within a file, you must specify the callback as a function handle.

Specify a Toolbox Function as a Callback

In addition to specifying callback functions of your own creation, you can also specify toolbox functions as callbacks. For example, this code sets the value of the stop event callback to the start function.

grp.StopFcn = @start;

Disable Callbacks

If an error occurs in the execution of the callback function, the toolbox disables the callback and displays a message similar to the following.

start(grp)
??? Error using ==> myrecords_cb
Too many input arguments.

Warning: The RecordsAcquiredFcn callback is being disabled.

To enable a callback that has been disabled, set the value of the property associated with the callback.

View Recently Logged Data

This example configures an OPC object hierarchy and sets the records acquired event callback function property to the display_opcdata function, created in Write a Callback Function.

When run, the example displays the last 60 records of acquired data every time 5 records have been acquired. Repeat values are highlighted with magenta circles, and bad values are highlighted with red circles.

Step 1: Create the OPC Object Hierarchy

This example creates a hierarchy of OPC objects for the Matrikon™ Simulation Server. To run this example on your system, you must have the Matrikon Simulation Server installed. Alternatively, you can replace the values used in the creation of the objects with values for a server you can access.

da = opcda('localhost','Matrikon.OPC.Simulation.1');
connect(da)
grp = addgroup(da,'CallbackTest');
itm1 = additem(grp,'Triangle Waves.Real8');
itm2 = additem(grp,'Saw-toothed Waves.UInt2');

Step 2: Configure Property Values

This example sets the UpdateRate value to 0.2 seconds, and the RecordsToAcquire property to 200. The example also specifies as the value of the RecordsAcquiredFcn callback the event callback function display_opcdata, created in Write a Callback Function. The object will execute the RecordsAcquiredFcn every 5 records, as specified by the value of the RecordsAcquiredFcnCount property.

grp.UpdateRate = 0.2;
grp.RecordsToAcquire = 200;
grp.RecordsAcquiredFcnCount = 5;
grp.RecordsAcquiredFcn = @display_opcdata;

Step 3: Acquire Data

Start the dagroup object. Every time 5 records are acquired, the object executes the display_opcdata callback function. This callback function displays the most recently acquired records logged to the memory buffer.

start(grp)
wait(grp)

Step 4: Clean Up

Always remove toolbox objects from memory, and the variables that reference them, when you no longer need them. Deleting the opcda client object also deletes the group and item objects.

disconnect(da)
delete(da)
clear da grp itm1 itm2