Working With OPC Data
Working With OPC Data
Working With OPC Data
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
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.
OPC Data Returned from Synchronous Read Operations
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.
When an asynchronous read operation succeeds, in addition to returning data via the event
structures, the toolbox also updates the Value, Quality, and TimeStamp properties of the
associated daitem object.
8-4
OPC Data Returned from a Data Change Event
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:
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.
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);
grp = addgroup(da,'StructExample');
itm1 = additem(grp,'Random.Real8');
itm2 = additem(grp,'Saw-toothed Waves.UInt2');
itm3 = additem(grp,'Random.Boolean');
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
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 =
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.
event =
Type: 'ReadAsync'
Data: [1x1 struct]
ans =
ans =
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
array output format for getdata and opcread. For more information on array formats, see “Array-
Formatted Data” on page 8-13.
The opcstruct2array function is particularly useful when you want to visualize or analyze
time series data without removing it from memory. Because peekdata only returns structure
arrays (due to speed considerations), you can use opcstruct2array to convert the contents of
the structure data into separate arrays for visualization and analysis purposes.
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.
For an example of using opcstruct2array, see “Write a Callback Function” on page 9-16.
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.
Conversion of Logged Data to Arrays
When you request array-formatted data from getdata or opcread, you must define the desired
data type for the returned Value array. OPC Toolbox software automatically converts each record
of logged data from the item's data type (defined by the DataType property of that item) to the
requested data type.
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.
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.
Work with Different Data Types
In this section...
“Conversion Between MATLAB Data Types and COM Variant Data Types” on page 8-16
“Conversion of Values Written to an OPC Server” on page 8-17
“Conversion of Values Read from an OPC Server” on page 8-17
“Handling Arrays for Item Values” on page 8-18
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
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.
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.
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
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)
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.
Data DataChangeFcn The toolbox generates a data change event when the server
Chan notifies the toolbox that data for a group has changed. The
ge server will notify the toolbox of data changes only if the
group's Active property is set to 'on' and the
Subscription property is set to 'on'. For more
information on controlling data change events, see “Data
Change Events and Subscription” on page 7-11.
Event Callback Property Description
When a data change event occurs, the toolbox executes
the function specified by the DataChangeFcn
property.
Read Async ReadAsyncFcn The toolbox generates a read async event when an
asynchronous read operation completes. You execute an
asynchronous read operation using the readasync
function.
Start StartFcn The toolbox generates a start event when an object is started.
You use the start function to start an object.
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.
Field Name Description
GroupName The name of the group associated with the event.
LocalEventTime Absolute time the event occurred, returned in MATLAB date
vector format:
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.
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');
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
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
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.
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.
Specify Callback Functions
You associate a callback function with a specific event by setting the value of the OPC Toolbox object
property associated with that event. You can specify the callback function as the value of the property
in one of three ways:
• “Use a Text String to Specify Callback Functions” on page 9-17
• “Use a Cell Array to Specify Callback Functions” on page 9-17
• “Use Function Handles to Specify Callback Functions” on page 9-18
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.
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.
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.
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.
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.
disconnect(da)
delete(da)
clear da grp itm1 itm2
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
In this section...
“Example Overview” on page 10-3
“Step 1: Open the OPC Toolbox Block Library” on page 10-3 “Step 2:
Create New Model in Simulink Editor” on page 10-4 “Step 3: Drag OPC
Toolbox Blocks into the Editor” on page 10-5 “Step 4: Drag Other Blocks
to Complete the Model” on page 10-7 “Step 5: Configure OPC Servers for
the Model” on page 10-9 “Step 6: Specify the Block Parameter Values”
on page 10-12 “Step 7: Connect the Blocks” on page 10-15
“Step 8: Run the Simulation” on page 10-16
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
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
Step 3: Drag OPC Toolbox Blocks into the Editor
The OPC Toolbox block library contains four blocks
• 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.
Step 4: Drag Other Blocks to Complete the Model
Your model requires three more blocks. One block provides the data sent to the server; the other two
blocks display the data received from the server.
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.
Step 5: Configure OPC Servers for the Model
To communicate with OPC servers from Simulink, you first need to configure those servers in the
model. The OPC Configuration block manages and configures OPC servers for a Simulink model. Each
OPC Read or OPC Write block uses one server from the configured servers, and defines the items to
read from or write to.
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.
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.
Step 7: Connect the Blocks
Make a connection between the Sine Wave block and the OPC Write block. When you move the
cursor near the output port of the Sine Wave block, the cursor becomes
crosshairs. Click the Sine Wave output port and hold the mouse button; drag to the input port of the
OPC Write block, and release the button.
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.
Step 8: Run the Simulation
Before you run the simulation, double-click the Scope block to open the scope view.
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).
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.
Use the OPC Client Manager
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.
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.
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.
11