Manuel Opc 11
Manuel Opc 11
Manuel Opc 11
When an OPC server returns data from a read or logging operation, three pieces of
information make up the data. The Value, Quality, and Timestamp all contribute
information about the data point that is returned. As a result, you need to understand
how to deal with this information together, because one aspect of the data in isolation
will not provide a complete picture of the data returned by a read operation, data change
event, read async event, or toolbox logging task.
This chapter describes how OPC Toolbox software handles data returned by an OPC
server.
This section describes the OPC Value, Quality, and TimeStamp properties, and how
they should be used together to assess the information provided by an OPC server.
• Value — The Value of the server item is the last value that the OPC server stored
for that particular item. The value in the cache is updated whenever the server reads
from the device. The server reads values from the device at the update rate specified
by the dagroup object's UpdateRate property, and only when the item and group
are both active. You control the active status of an item or group using that object's
Active property.
In addition, for analog type data (data with the additional OPC Foundation
Recommended Properties 'High EU' and 'Low EU') the percentage change between
the cached value and the device value must exceed the DeadbandPercent property
specified for that item in order for the cached value to be updated.
• Quality — The Quality of the server item is a string that represents information
about how well the cache value matches the device value. The Quality is made up
8-3
OPC Data: Value, Quality, and TimeStamp
of two parts: a major quality, which can be 'Good', 'Bad', or 'Uncertain', and a
minor quality, which describes the reason for the major quality. For more information
on the Quality string, see “OPC Quality Strings” on page A-2.
The Quality of the server item can change without the Value changing. For
instance, if the OPC server attempts to obtain a Value from the device but that
operation fails, the Quality will be set to 'Bad'. Also, when you change the client's
Active property, the Quality will change.
You must always examine the Quality of an item before using the Value property of
that item.
• TimeStamp — The TimeStamp of a server item represents the most recent time that
the server assessed that the device set the Value and Quality properties of that
server item. The TimeStamp can change without the Value changing. For example, if
the OPC server obtains a value from the device that is the same as the current Value,
the TimeStamp property will still be updated, even if the Value property is not.
OPC Toolbox software provides access to the Value, Quality, and TimeStamp
properties of a server item through properties of the daitem object associated with that
server item.
The way OPC Toolbox software uses the three OPC Data Access mechanisms is described
in the following sections:
• “OPC Data Returned from Synchronous Read Operations” on page 8-4 describes
the synchronous read mechanism used by the read function.
• “OPC Data Returned in Asynchronous Read Operations” on page 8-4 describes
the asynchronous read mechanism used by the readasync function.
• “OPC Data Returned from a Data Change Event” on page 8-5 describes the data
change event notification mechanism used with subscribed, active groups, with the
refresh function, and by the toolbox logging process.
8-3
OPC Data: Value, Quality, and TimeStamp
You initiate a synchronous read operation by using the read function. When you read
from a dagroup object, all items in that group are read in one instruction.
You can specify the source of a synchronous read operation as 'cache' or 'device'.
If you read from the cache, the server simply returns the value in the cache. If you read
from the device, the server will get the value from the device and update the cache
before sending the Value, Quality, and TimeStamp information back as part of the read
operation.
OPC Toolbox software returns the data in the output structure from the read operation.
Each element of the structure array contains information about one of the items read.
Whenever you read values using the read function, the toolbox updates the daitem
object's Value, Quality, and TimeStamp properties with the values read from the
server.
You initiate an asynchronous read operation by using the readasync function. When
you read from a dagroup object, all items in that group are read in one instruction.
Asynchronous read operations always use the device as the source of the read. Whenever
you send an asynchronous read request, the server will read values from the devices
connected to the items. The server will then update that server item's Value, Quality,
and TimeStamp in the cache before sending an asynchronous read event back to the
toolbox.
OPC Toolbox software returns information from an asynchronous read operation via
the read async event structure. This event structure is stored in the opcda client
object's event log, which you can access using the EventLog property of the client. The
event structure is also passed to the callback function defined in the ReadAsyncFcn
property of the dagroup object that initiated the asynchronous read operation. For
more information on the format of the event structures, see “Event Structures” on page
9-9.
8-4
OPC Data: Value, Quality, and TimeStamp
The third mechanism for getting data from an OPC server involves the data change
event. The OPC server generates a data change event for a group at the period specified
by the UpdateRate property when the Value or Quality of an item in the group changes.
You do not have to specifically request a data change event, because the OPC server will
automatically generate a data change event. However, you can force a data change event
at any time using the refresh function.
An OPC server will generate a data change event only for an active, subscribed group
containing active items. You control the active status of dagroup objects and daitem
objects by setting their Active property. You control the subscribed status of a dagroup
object by setting the Subscription property of the dagroup object.
The following points describe how an OPC server generates a data change event:
• When you configure a group, you define the rate at which the server must scan items
in that group. This rate is controlled by the UpdateRate property for a dagroup
object. The server updates the Value, Quality, and TimeStamp values in the cache
for the items in that group at the required update rate. Note that if a device cannot
provide a value in that time, the server may reduce the rate at which it updates the
value in the server cache for that item.
• If you set an item's Active property to 'off', the server will stop scanning that
item. You must set the Active property to 'on' for the server to scan the item again.
• If you set the Active property of a dagroup object to 'off', the server will stop
scanning all items in that group. You can still perform asynchronous read operations,
and synchronous read operations from the 'device', but no operations involving the
server cache can be performed. You must set the Active property to 'on' to enable
operations involving the server cache.
• If the Subscription property for a dagroup object is set to 'on', then every time
the server updates cache values for the items in that group, the server will send a
data change event for that group, to the client object. The data change event contains
information about every item whose Value, Quality, or TimeStamp updated.
• If you set the Subscription property to 'off', then the OPC server will not
generate data change events. However, as long as the group is still active, the OPC
server will continue to scan all active items for that group, at the rate specified by the
UpdateRate property.
When the OPC server generates a data change event, OPC Toolbox software performs the
following tasks:
8-5
OPC Data: Value, Quality, and TimeStamp
1 The daitem object Value, Quality, and TimeStamp properties are updated for
each item that is included in the data change event.
2 The callback function defined by the DataChangeFcn property of the dagroup
object is called. For more information on callbacks, see “Create and Execute Callback
Functions” on page 9-15.
3 If the group is logging data, the data change event is stored in memory and/or on
disk. For more information on logging, see “Log OPC Server Data” on page 7-15.
4 If the group is logging, and the number of records acquired is a multiple of the
RecordsAcquiredFcnCount property of the dagroup object, then the callback
function defined by the RecordsAcquiredFcn property of the dagroup object
is called. For more information on callbacks, see “Create and Execute Callback
Functions” on page 9-15.
For more information on the structure of a data change event, see “Data Fields for Cancel
Async, Data Change, Error, Read Async, and Write Async Events” on page 9-9.
8-6
Work with Structure-Formatted Data
In all cases, the structure of the returned data is the same. This section describes that
structure, and how you can use the structure data to understand OPC operations.
This example creates a hierarchy of OPC Toolbox 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);
8-7
Work with Structure-Formatted Data
grp = addgroup(da,'StructExample');
itm1 = additem(grp,'Random.Real8');
itm2 = additem(grp,'Saw-toothed Waves.UInt2');
itm3 = additem(grp,'Random.Boolean');
This example reads values first from the device and then from the server cache. The data
is returned in structure format.
r1 = read(grp, 'device');
r2 = read(grp);
The data is returned in structure format. To interpret the data, you must extract the
relevant information from the structures. In this example, you compare the Value,
Quality, and TimeStamp to confirm that they are the same for both read operations.
disp({r1.ItemID;r1.Value;r2.Value})
disp({r1.ItemID;r1.Quality;r2.Quality})
disp({r1.ItemID;r1.TimeStamp;r2.TimeStamp})
By reading first from the cache and then from the device, you can compare the returned
data to see if any change has occurred. In this case, the data will not be the same.
r3 = read(grp);
r4 = read(grp, `device');
disp({r3.ItemID;r3.Value;r4.Value})
Step 5: Clean Up
Always remove toolbox objects from memory, and the variables that reference them,
when you no longer need them.
disconnect(da)
delete(da)
clear da grp itm1 itm2 itm3
8-8
Work with Structure-Formatted Data
underlying format. The format is best explained by starting with the output from the
read function, which provides the basic building block of structure-formatted data.
When you execute the read function with a single daitem object, the following structure
is returned.
rSingle = read(itm1)
rSingle =
ItemID: 'Random.Real8'
Value: 1.0440e+004
Quality: 'Good: Non-specific'
TimeStamp: [2004 3 10 14 46 9.5310]
Error: ''
All structure-formatted data for an item will contain the ItemID, Value, Quality, and
TimeStamp fields.
Note The Error field in this example is specific to the read function, and is used to
indicate any error message the server generated for that item.
If you execute the read function with a group object containing more than one item, a
structure array is returned.
rGroup = read(grp)
rGroup =
8-9
Work with Structure-Formatted Data
In this case, the structure array contains one element for each item that was read. The
ItemID field in each element identifies the item associated with that element of the
structure array.
Note When you perform asynchronous read operations, and for data change events, the
order of the items in the structure array is determined by the OPC server. The order may
not be the same as the order of the items passed to the read function.
Event structures contain information specifically about the event, as well as the data
associated with that event.
cleareventlog(da);
tid = readasync(itm);
% Wait for the read async event to occur
pause(1);
event = get(da, 'EventLog')
event =
Type: 'ReadAsync'
Data: [1x1 struct]
event.Data
ans =
event.Data.Items
ans =
8-10
Work with Structure-Formatted Data
ItemID: 'Random.Real8'
Value: 9.7471e+003
Quality: 'Good: Non-specific'
TimeStamp: [2004 3 11 10 59 57.6710]
From the example, you can see that the event structure embeds the structure-formatted
data in the Items field of the Data structure associated with the event. Additional fields
of the Data structure provide information on the event, such as the source of the event,
the time the event was received by the toolbox, and the transaction ID of that event.
OPC Toolbox software logs data to memory and/or disk using the data change event.
When you return structure-formatted data for a logging task using the opcread
or getdata function, the returned structure array contains the data change event
information arranged in a structure array. Each element of the structure array contains
a record, or data change event. The structure array has the LocalEventTime and Items
fields from the data change event. The Items field is in turn a structure array containing
the fields ItemID, Value, Quality, and TimeStamp.
For a logging task, you should use structure-formatted data when you are interested in
• The “raw” event information returned by the OPC server. The raw information may
help in diagnosing the OPC server configuration or the client configuration. For
example, if you see a data value that does not change frequently, yet you know that
the device should be changing frequently, you can examine the structure-formatted
data to determine when the OPC server notifies clients of a change in Value, Quality
and/or TimeStamp.
• Timing information rather than time series data. If you need to track when an
operator changed the state of a switch, structure-formatted data provides you with
event-based data rather than time series data.
For other tasks that involve time series data, such as visualization of the data, analysis,
modeling, and optimization operations, you should consider using the cell or numeric
8-11
Work with Structure-Formatted Data
array output format for getdata and opcread. For more information on array formats,
see “Array-Formatted Data” on page 8-13.
Note You should always retrieve data in numeric or cell array format whenever you only
want to manipulate the time series data. Although the opcstruct2array function has
been designed to use as little memory as possible, conversion in MATLAB software still
requires storage space for both the structure array and the resulting arrays.
8-12
Array-Formatted Data
Array-Formatted Data
In this section...
“Array Content” on page 8-13
“Conversion of Logged Data to Arrays” on page 8-14
Array Content
OPC Toolbox software can return arrays of Value, Quality, and TimeStamp information
from a logging task. You can retrieve arrays from memory using getdata, or from disk
using opcread, by specifying the data type as 'cell' or any MATLAB numeric array
data type, such as 'double' or 'uint32'. Consult the function reference pages for
details on how to specify the data type.
When you request array-formatted data, the toolbox returns arrays of each of the
following elements of the records in memory or on disk:
• ItemID — A 1-by-nItems list of all item IDs occurring in the structure array. Each
record is searched and all unique item IDs are returned in a cell array. The order
of the item IDs must be used to interpret any of the Value, Quality, or TimeStamp
arrays.
• Value — An nRecs-by-nItems array of values for each item ID defined in the
ItemID variable, at each time stamp defined by the TimeStamp array. Each column
of the Value array represents the history of values for the corresponding item in the
ItemID array. Each row corresponds to one record. See “Treatment of Missing Data”
on page 8-14 for information on how the Value array is populated.
• Quality — An nRecs-by-nItems cell array of quality strings. Each column
represents the history of qualities for the corresponding item in the ItemID array.
Each row corresponds to the qualities for a particular record. If a particular item ID
was not part of a record (because the item did not change during that period), the
corresponding column in that row is set to 'Repeat'.
• TimeStamp — An nRecs-by-nItems array of time stamps for each value in the Value
field. The time stamps are in MATLAB date number format. For more information on
MATLAB date numbers, see the datenum function help.
• EventTime — An nRecs-by-1 array of times that the record was received by OPC
Toolbox software (the LocalEventTime field of the record in structure format). The
times are in MATLAB date number format. For more information on MATLAB date
numbers, see the datenum function help.
8-13
Array-Formatted Data
When converting logged data to arrays, the toolbox must consider two factors when
populating the returned arrays:
• A record may not contain information for every item in the logging task. “Treatment
of Missing Data” on page 8-14 discusses how the toolbox deals with missing data.
• A record may contain an array value for a single item. Such values cannot easily be
converted to a single value of numeric data types. “Treatment of Array Data Values”
on page 8-14 discusses how the toolbox deals with this issue.
When OPC Toolbox software logs data, each logged record may not contain all items
in the logging task. When converting the data to array format, every item involved
in the logging task must be allocated a value, a quality, and a time stamp for each
record. Therefore, in a logging task there may be "missing" data for a particular item
in a particular record. The toolbox uses the following rules to determine how to fill the
missing entry in each array:
• Value — When you request the 'cell' array data type, the value used for the
missing entry is an empty double array ([]). When requesting a numeric data type,
the value used for the missing entry is the last value for that item. If no previous
value is known, the equivalent NaN (not a number) entry is used. For example, if
the very first record does not contain an entry for that item, NaN is used to fill in
the missing entry in the first row of the Value array. The equivalent NaN value for
integer and logical data types is 0.
• Quality — The missing entry is filled with the specific quality string 'Repeat'.
• TimeStamp — The time stamp used for the missing entry is the first time stamp
found in that particular record (row).
For each record stored in memory or on disk during a logging task, a single item may
return an array of values. When converting logged data to array format, each item in
each record has only one entry in the Value array allocated to that record and item.
8-14
Array-Formatted Data
For the 'cell' data type, OPC Toolbox software is able to store the array returned as
the Value for that element, because a MATLAB cell array is able to store any data type of
any size in each element of the cell array.
For numeric data types, such as 'double' or 'uint32', the resulting Value array
provides space for only a single value. Consequently, if an array value is found in
a logging task, and you have requested a numeric array data type, an error will be
generated. You must use the 'cell' data type or the structure format to return logged
data that contains arrays as values.
8-15
Array-Formatted Data
Conversion Between MATLAB Data Types and COM Variant Data Types
The OPC Data Access Standard uses the Microsoft COM Specification for communication
between the OPC server and OPC client. A significant amount of the data exchanged
between the OPC server and the client is the value from a server item or the value
that a client wants to write to a server item. The Microsoft COM Specification uses
Microsoft Variants to send different data types between the client and server. This
section discusses how OPC Toolbox software converts MATLAB data types to COM
Variants when writing values, and COM Variants to MATLAB data types when reading
values.
OPC servers require all values to be written to server items in COM Variant format. The
server also provides the toolbox with COM Variants when an item's Value property is
read or returned by the server. The toolbox automatically converts between the COM
Variant type and MATLAB data types according to the table shown below.
Table 8-1. Conversion from MATLAB Data Type to COM Variant Data Type
8-16
Work with Different Data Types
1 OPC Toolbox software converts the value into the equivalent COM Variant according
to Table 8-1. If any disallowed data type is encountered (for example, if you attempt
to write a MATLAB structure), an error will be generated.
2 The COM Variant is sent to the OPC server.
3 The OPC server will attempt to convert the COM Variant to the server item's
canonical data type, using COM Variant conversion rules. If the conversion fails, the
server will return an error.
8-17
Work with Different Data Types
daitem object's DataType property. If the conversion fails, an error message is returned
with the value. When OPC Toolbox software receives the value, the COM Variant is
converted to the equivalent MATLAB data type according to Table 8-1.
For all of the data types listed in Table 8-1 that can be converted between MATLAB and
a COM Variant, scalar and array data are permitted by the toolbox. However, the OPC
Specification supports only one-dimensional arrays of data. Higher dimension MATLAB
arrays are flattened into a one-dimensional vector when writing data to the OPC server.
8-18
9
You can enhance the power and flexibility of your OPC application by using event
callbacks. An event is a specific occurrence that can happen while an OPC Data Access
client object (opcda client object) is connected to an OPC server. The toolbox defines a
set of events that include starting, stopping, or acquiring records during a logging task,
as well as events for asynchronous reads and writes, data changes, and server shutdown
notification.
When a particular event occurs, the toolbox can execute a function that you specify.
This is called a callback. Certain events can result in one or more callbacks. You can use
callbacks to perform processing tasks while your client object is connected. For example,
you can display a message, analyze data, or perform other tasks. Callbacks are controlled
through OPC Toolbox object properties. Each event type has an associated property. You
specify the function that you want executed as the value of that property.
The example uses the default callback function provided with the toolbox, opccallback.
The default callback function displays the name of the object along with information
about the type of event that occurred and when it occurred. To learn how to create your
own callback functions, see “Create and Execute Callback Functions” on page 9-15.
9-3
Use the Default Callback Function
grp.RecordsToAcquire = 20;
grp.UpdateRate = 0.5;
For this example, specify how often to generate a records acquired event.
grp.RecordsAcquiredFcnCount = 5;
Step 5: Clean Up
Always remove toolbox objects from memory, and the variables that reference them,
when you no longer need them.
disconnect(da)
9-3
Use the Default Callback Function
delete(da)
clear da grp itm
9-4
Event Types
Event Types
OPC Toolbox software supports several different types of events. Each event type has an
associated toolbox object property that you can use to specify the function that executes
when the event occurs.
The following table lists the supported event types, the name of the object property
associated with the event, and a brief description of the event, including the object class
associated with the event. For detailed information about these callback properties, see
the reference information for the property.
The toolbox generates a specific set of information for each event and stores it in an event
structure. To learn more about the contents of these event structures and how to retrieve
this information, see “Retrieve Event Information” on page 9-9.
9-5
Event Types
9-6
Event Types
9-7
Event Types
9-8
Retrieve Event Information
Event Structures
Each event has a set of information associated with that event. The information is
generated by the OPC server or the OPC Toolbox software, and stored in an event
structure. This information includes the event type, the time the event occurred, and
other event-specific information. For some events, the toolbox records event information
in the opcda client object's EventLog property. You can also access the event structure
associated with an event in a callback function.
For information about accessing event information in a callback function, see “Create and
Execute Callback Functions” on page 9-15.
An event structure contains two fields: Type and Data. For example, this is an event
structure for a start event.
Type: 'Start'
Data: [1x1 struct]
The Type field is a text string that specifies the event type. For a start event, this field
contains the text string 'Start'.
The Data field is a structure that contains information about the event. The composition
of this structure varies, depending on which type of event occurred. For details about the
information associated with specific events, see the following sections:
• “Data Fields for Cancel Async, Data Change, Error, Read Async, and Write Async
Events” on page 9-9
• “Data Fields for Start, Stop, and Records Acquired Events” on page 9-10
• “Data Fields for Shutdown Events” on page 9-11
• “Data Fields for Timer Events” on page 9-12
Data Fields for Cancel Async, Data Change, Error, Read Async, and Write Async Events
For cancel async, data change, error, read async, and write async events, the Data
structure contains these fields.
9-9
Retrieve Event Information
The Items structure array for read async events contains the following fields.
The Items structure array for write async events contains one field: ItemID.
The Items structure array for error events contains the ItemID field and an Error field,
containing a string describing the error that occurred for that item.
For start, stop, and records acquired events, the Data structure contains these fields.
9-10
Retrieve Event Information
9-11
Retrieve Event Information
The toolbox adds event structures to the EventLog array in the order in which the
events occur. The first event structure reflects the first event recorded, the second event
structure reflects the second event recorded, and so on.
Note Data change events, records acquired events, and timer events are not included in
the EventLog. Event structures for these events (and all the other events) are available
to callback functions. For more information, see “Create and Execute Callback Functions”
on page 9-15.
To illustrate the event log, this example creates an OPC Toolbox object hierarchy,
executes a logging task, and then examines the object's EventLog property:
This example creates a hierarchy of OPC Toolbox 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');
9-12
Retrieve Event Information
connect(da);
grp = addgroup(da,'CallbackTest');
itm1 = additem(grp,'Triangle Waves.Real8');
Start the dagroup object. By default, the object acquires 120 records at 0.5-second
intervals, and then stops. Wait for the object to stop logging data.
start(grp)
wait(grp)
Access the EventLog property of the opcda client object. The execution of the group
logging task generated two events: start and stop. Thus the value of the EventLog
property is a 1-by-2 array of event structures.
events = da.EventLog
events =
To list the events that are recorded in the EventLog property, examine the contents of
the Type field.
{events.Type}
ans =
'Start' 'Stop'
To get information about a particular event, access the Data field in that event structure.
The example retrieves information about the stop event.
stopdata = events(2).Data
stopdata =
LocalEventTime: [2004 3 2 21 33 45.8750]
GroupName: 'CallbackTest'
RecordsAcquired: 120
9-13
Retrieve Event Information
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
9-14
Create and Execute Callback Functions
Note Callback function execution might be delayed if the callback involves a CPU-
intensive task, or if MATLAB software is processing another task.
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” on page 9-9.
In addition to these two required input arguments, you can also specify application-
specific arguments for your callback function.
9-15
Create and Execute Callback Functions
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” on page 9-17.
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 OPC Toolbox software 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)
To see how this function can be used as a callback, see “View Recently Logged Data” on
page 9-18.
9-16
Create and Execute Callback Functions
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.
You can specify the callback function as a string. 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';
You can specify the callback function as a text string 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 Toolbox
object (obj) and the event structure (event). Additional arguments follow these two
arguments.
9-17
Create and Execute Callback Functions
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.
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)
To enable a callback that has been disabled, set the value of the property associated with
the callback.
9-18
Create and Execute Callback Functions
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.
This example creates a hierarchy of OPC Toolbox 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');
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” on page 9-16. 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;
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.
9-19
Create and Execute Callback Functions
disconnect(da)
delete(da)
clear da grp itm1 itm2
9-20
10
The OPC Toolbox block library requires Simulink, a tool for simulating dynamic systems.
Simulink is a model definition environment. Use Simulink blocks to create a block
diagram that represents the computations of your system or application. Simulink is also
a model simulation environment in which you can see how your system behaves.
The best way to learn about the OPC Toolbox block library is to observe an example, such
as the one provided in “Read and Write Data from a Model” on page 10-3.
10-3
Read and Write Data from a Model
Example Overview
This section provides a step-by-step example to illustrate how to use the OPC Toolbox
block library. The example builds a simple model using the blocks in the OPC Toolbox
block library with blocks from other Simulink libraries.
This example writes a sine wave to the Matrikon OPC Simulation Server, and reads the
data back from the same server. You use the OPC Write block to send data to the OPC
server, and the OPC Read block to read that same data back into your model.
Note To run the code in the following examples, you must have the Matrikon OPC
Simulation Server available on your local machine. For information on installing this,
see “Install the Matrikon OPC Simulation Server” on page 1-19. The code used in this
example requires only minor changes to work with other servers.
simulink
10-3
Read and Write Data from a Model
at the MATLAB prompt. MATLAB opens the Simulink Library Browser. The left pane
contains a list of available block libraries in alphabetical order.
To open the OPC Toolbox block library, click its entry in the tree. When you open a
library, Simulink loads the library and displays its blocks.
Alternatively, you can open the OPC Toolbox block library by typing
opclib
1 To create a new model, select the Simulink Library Browser menu option File >
New > Model. An empty Simulink Editor window opens.
10-4
Read and Write Data from a Model
• OPC Configuration
• OPC Quality Parts
• OPC Read
• OPC Write
You can use these blocks to configure and manage connections to servers, to send and
receive live data between your OPC server and your simulation, and to analyze OPC
quality.
To use the blocks in a model, select each block in the library and, holding the mouse
button down, drag the block into the Simulink Editor. For this example, you need one
instance each of the OPC Configuration, OPC Write, and OPC Read block in your model.
10-5
Read and Write Data from a Model
10-6
Read and Write Data from a Model
To send a sine wave to the server, you can use the Sine Wave block. To access the Sine
Wave block, expand the Simulink node in the browser tree, and click the Sources library
entry. From the blocks displayed in the right pane, drag the Sine Wave block into the
Simulink Editor and place it to the left of the OPC Write block.
You can use the Scope block to show the value received from the server, and a Display
block to view the quality of the item. (You will remove the time stamp output port in
the next step.) To access the Scope block, click the Sinks library entry in the expanded
Simulink node in the browser tree. From the blocks displayed in the right pane, drag the
Scope block into the Simulink Editor and place it above and to the right of the OPC Read
block. Also drag a Display block into the Simulink Editor and place it below the Scope
block.
10-7
Read and Write Data from a Model
10-8
Read and Write Data from a Model
10-9
Read and Write Data from a Model
3 Click Add to open the OPC Server Properties dialog. Specify the ID of the server as
'Matrikon.OPC.Simulation.1' (or click Select and choose the server from the
list of available OPC servers).
10-10
Read and Write Data from a Model
The Matrikon OPC Simulation Server is now available throughout the model for
reading and writing.
5 Your model will use default values for all other settings in the OPC Configuration
block. Click OK in the OPC Configuration dialog to close that dialog.
10-11
Read and Write Data from a Model
1 Double-click the OPC Write block to open its parameters dialog. The Matrikon server
is automatically selected for you as the OPC client to use in this block. You need to
specify the items for writing.
2 Click Add Items to display a name space browser for the Matrikon OPC Simulation
Server.
3 Expand the Simulation Items node in the name space, then expand the Bucket
Brigade node. Select the Real8 node and click >> to add that item to the selected
items list.
10-12
Read and Write Data from a Model
4 Click OK to add the item Bucket Brigade.Real8 to the OPC Write block’s
ItemIDs list.
5 In the OPC Write parameters dialog, click OK to accept the changes and close the
dialog.
6 Double-click the OPC Read block to open its dialog. Add the same item to the OPC
Read block, repeating steps 2–5 that you followed for the OPC Write block in this
section.
7 Set the read mode to 'Synchronous (device)' and the sample time for the block
to 0.2.
8 Also uncheck the 'Show timestamp port' option. This step removes the time
stamp output port from the OPC Read block.
10-13
Read and Write Data from a Model
10-14
Read and Write Data from a Model
In the same way, make a connection between the first output port of the OPC Read block
(labeled V) and the input port of the Scope block. Then connect the other output port of
the OPC Read block (labeled Q) to the input port of the Display block.
Note that the OPC Write and OPC Read blocks do not directly connect together within
the model. The only communication between them is through an item on the server,
which you defined in “Step 5: Configure OPC Servers for the Model” on page 10-9.
10-15
Read and Write Data from a Model
To run the simulation, click Run in the Simulink Editor toolstrip. Alternatively, you can
select the Simulink Editor menu option Simulation > Run.
The model writes a sine wave to the OPC server, reads back from the server, and
displays the wave in the scope trace. In addition, the quality value is set to 192, which
indicates a good quality (see “OPC Quality Strings” on page A-2).
10-16
Read and Write Data from a Model
While the simulation is running, the status bar at the bottom of the model window
updates the progress of the simulation, and the sine wave is displayed in the Scope
window.
10-17
Read and Write Data from a Model
In this section...
“Introduction to the OPC Client Manager ” on page 10-18
“Add Clients to the OPC Client Manager” on page 10-19
“Remove Clients from the OPC Client Manager” on page 10-19
“Modify the Server Timeout Value for a Client” on page 10-20
“Control Client/Server Connections” on page 10-20
You access the OPC Client Manager from the parameters dialog of the OPC
Configuration, OPC Read, or OPC Write block, by clicking Configure OPC Clients. A
dialog similar to the following figure appears.
10-18
Use the OPC Client Manager
Specify the host in the Host edit box. You can then type the Server ID of the required
server, or use Select to query the host for a list of servers.
Specify the timeout (in seconds) to use when communicating with the server.
When you click OK, the client is added to the OPC Clients list in the OPC Client
Manager. You can now use that client in one or more OPC Read or OPC Write blocks
within that model.
If you attempt to remove a client that is referenced by one or more OPC Toolbox library
blocks, you see the following dialog.
Click Delete to remove all blocks that reference the client you want to delete.
10-19
Use the OPC Client Manager
Click Replace to replace the referenced client with another client in the OPC Client list
(this choice is available only if another client is available), and select the replacement
client from the resulting list. Click Cancel to cancel the delete operation.
You can control the client’s connection status by highlighting a client in the OPC Client
list and clicking Connect or Disconnect.
The OPC Toolbox block library automatically reconnects any disconnected client to its
server when you run a simulation.
10-20
11
Use the OPC Client Manager
10-21