Read and Write Data

Introduction to Reading and Writing

Using OPC Toolbox™ software, you can exchange data with the OPC server using individual items, or using the dagroup object to perform the operation on multiple items. The reading and writing operation can be performed synchronously, so that your MATLAB® session will wait for the operation to complete, or asynchronously, allowing your MATLAB session to continue processing while the operation takes place in the background.

Read Data from an Item

You can read data from any item that is associated with a connected client. When you perform the read operation on an item, the server will return information about the server item associated with that item ID. The read operation can be performed synchronously or asynchronously:

Use Synchronous Read Operations

A synchronous read operation means that MATLAB will wait for the server to return data from a read request before continuing processing. The data returned by the server can come from the server's cache, or you can request that the server read values from the device that the server item refers to.

You use the read function to perform synchronous read operations, passing the daitem object associated with the server item you want to read. If the read operation is successful, the data is returned in a structure containing information about the read operation, including the value of the server item, the quality of that value, and the time that the server obtained that value. The item's Value, Quality and Timestamp properties are also updated to reflect the values obtained from the read operation.

The following example creates an opcda client object and configures a group with one item, 'Random.Real8'. A synchronous read operation is then performed on the item.

da = opcda('localhost','Matrikon.OPC.Simulation.1');
connect(da);
grp = addgroup(da);
itm1 = additem(grp,'Random.Real8');
r = read(itm1)
r = 

       ItemID: 'Random.Real8'
        Value: 4.3252e+003
      Quality: 'Good: Non-specific'
    TimeStamp: [2004 3 2 9 50 26.6710]
        Error: ''

Specify the Source of the Read Operation.  By default, a synchronous read operation will return data from the OPC server's cache. By reading from the cache, you do not have to wait for a possibly slow device to provide data to the server. You can specify the source of the synchronous read operation as the second parameter to the read function. If the source is specified as 'device', the server will read a value from the device, and return that value to you (as well as updating the server cache with that value).

    Note   Reading from the device may be slow. If the read operation generates a time-out error, you may need to increase the value of the Timeout property of the opcda client object associated with the group or item in order to support synchronous reads from the device.

The following example reads data from the device associated with itm1.

r = read(itm1,'device')
r = 

       ItemID: 'Random.Real8'
        Value: 9.1297e+003
      Quality: 'Good: Non-specific'
    TimeStamp: [2004 3 2 10 8 20.2650]
        Error: ''

Read from the Cache with Inactive Items.  In order to reduce communication traffic and speed up data access, OPC servers do not store all server item values in their cache. Only those server items that are active will be stored in the server cache. Therefore, synchronous read operations from the cache on an inactive item will return data that may not correspond to the current device value. If you attempt to read data from an inactive item using the read function, and do not specify 'device' as the source, the Quality will be set to 'Bad: Out of Service'.

You control the active status of an item using the Active property.

The following example sets the Active property of the item to 'off' and attempts to read from the cache.

itm1.Active = 'off';
r = read(itm1)
Warning: One or more items is inactive.
(Type "warning off opc:read:iteminactive" to suppress this 
warning.)

r = 

       ItemID: 'Random.Real8'
        Value: 8.4278e+003
      Quality: 'Bad: Out of Service'
    TimeStamp: [2004 3 2 10 17 19.9370]
        Error: ''

Use Asynchronous Read Operations

An asynchronous read operation creates a request to read data, and then sends that request to the server. Once the request has been accepted, MATLAB continues processing the next instruction without waiting to receive any values from the server. When the data is ready to be returned, the server sends the data back to MATLAB by generating a read async event. MATLAB will handle that event as soon as it is able to perform that task.

Asynchronous read operations always return data from the device.

By using an asynchronous read operation, you can continue performing tasks in MATLAB while the value is being read from the device, and then process the returned value when the server is able to provide it back to MATLAB.

You perform asynchronous read operations using the readasync function, passing the daitem object that you want to read from. If successful, the function will return a transaction ID, a unique identifier for that asynchronous transaction. You can use that transaction ID to identify the read operation when it is returned through the read async event.

When an asynchronous read operation is processed in MATLAB, the item's Value, Quality and Timestamp properties are also updated to reflect the values obtained from the asyncrhonous read operation.

The following example of using an asynchronous read operation uses the default callback for a read async event. The default callback is set to the opccallback function, which displays information about the event in the command line.

tid = readasync(itm1)
tid =

     3

The transaction ID for this operation is 3. A little while later, the default callback function displays the following information at the command line.

OPC ReadAsync event occurred at local time 10:44:49
    Transaction ID: 3
    Group Name: Group0
    1 items read.

You can change the read async event callback function by setting the ReadAsyncFcn property of the dagroup object.

Write Data to an Item

You can write data to individual items, or to groups of items. This section describes how to write data to individual items. See Read and Write Multiple Values for information on using dagroup objects to write data to multiple items.

You can write data to an OPC server using a synchronous write operation, in which case MATLAB will wait for the server to acknowledge that the write operation succeeds, or using an asynchronous write operation, in which case MATLAB is free to continue performing other tasks while the write operation takes place. Because write operations always apply directly to the device, a synchronous write operation may take a significant amount of time, particularly if the device that you are writing to has a slow connection to the OPC server.

Use Synchronous Write Operations

You use the write function to perform synchronous write operations. The first argument is the daitem object that represents the server item you want to write to. The second argument is the value that you want to write to that server item. The write function does not return any results, but will generate an error if the write operation is not successful.

The following example creates an item with item ID 'Bucket Brigade.Real8' and writes the value 10.34 to the item. The value is then read using a synchronous read operation.

itm2 = additem(grp,'Bucket Brigade.Real8');
write(itm2, 10.34)
r = read(itm2,'device')

You do not need to ensure that the data type of the value you are writing, and the data type of the daitem object, are the same. OPC Toolbox software relies on the server to perform the conversion from the data type you provide, to the data type required for that server item. For information on how the toolbox handles different data types, see Work with Different Data Types.

Use Asynchronous Write Operations

An asynchronous write operation creates a request to write data, and then sends that request to the server. Once the request has been accepted, MATLAB continues processing the next instruction without waiting for the data to be written. When the write operation completes on the server, the server notifies MATLAB that the operation completed by generating a write async event containing information on whether the write operation succeeded, and an error message if applicable. MATLAB will handle that event as soon as it is able to perform that task.

You use the writeasync function to write values to the server asynchronously. The first argument is the daitem object that represents the server item you want to write to. The second argument is the value you want to write to that server item. The return value is the transaction ID of the operation. You can use the transaction ID to identify the write operation when it is returned through the write async event.

The following example uses asynchronous operations to write the value 57.8 to the item 'Bucket Brigade.Real8' created earlier.

tid = writeasync(itm2, 57.8)
tid =

     4

A while later, the standard callback (opccallback) will display the results of the write operation to the command line.

OPC WriteAsync event occurred at local time 11:15:27
   Transaction ID: 4
   Group Name: Group0
   1 items written.

You can change the write async event callback function by setting the WriteAsyncFcn property of the dagroup object.

Read and Write Multiple Values

When you use the read and write operation on a single daitem object, you read or write a single value per transaction. OPC Toolbox software allows you to perform one operation to read multiple item values, or to write multiple values. You can also use a dagroup object to read and write values using all items in the group, or you can perform read and write operations on item object vectors.

A daitem object vector is a single variable in the MATLAB workspace containing more than one daitem object. You can construct item vectors using any of the standard concatenation techniques available in MATLAB. See Create OPC Toolbox Data Access Object Vectors for information on creating and working with toolbox object vectors.

When you perform any read or write operation on a dagroup object, it is the equivalent of performing the operation on the Item property of that group, which is a daitem object vector representing all items that are contained within the dagroup object.

The following sections describe how to perform read and write operations on multiple items:

Read Multiple Values

The following sections describe how synchronous read operations and asynchronous read operations behave for multiple items.

Synchronous Read Operations.  When you read multiple values using the read function, the returned value will be a structure array. Each element of the structure will contain the same fields. One of the fields is the item ID that the information in that element of the structure refers to.

The following example performs a synchronous read operation on the dagroup object created in the previous examples in this section.

r = read(grp)
r = 

2x1 struct array with fields:
    ItemID
    Value
    Quality
    TimeStamp
    Error

To display the first record in the structure array, use indexing into the structure.

r(1)
ans = 

       ItemID: 'Random.Real8'
        Value: 3.7068e+003
      Quality: 'Good: Non-specific'
    TimeStamp: [2004 3 2 11 49 52.5460]
        Error: ''

To display all values of a particular field, you can use the list generation syntax in MATLAB. Enclosing that list in a cell array groups the values into one variable.

{r.Value}
ans =

  {3.7068e+003    10}

Asynchronous Read Operations.  When you read multiple values using the readasync function, the return value is still a single transaction ID. The multiple values will be returned in the read async event structure passed to the ReadAsyncFcn callback. For information on the structure of the read async event, see Event Types.

Write Multiple Values

When you perform a write operation on multiple items you need to specify multiple values, one for each item you are writing to. OPC Toolbox software requires these multiple values to be in a cell array, since the data types for each value may be different. For information on constructing cell arrays, see MATLAB Programming.

    Note   Even if you are using the same data type for every value being written to the dagroup object or daitem object vector, you must still use a cell array to specify the individual values. Use the num2cell function to convert numeric arrays to cell arrays.

The following example writes values to a dagroup object containing two items.

write(grp, {1.234, 5.43})

Error Handling for Multiple Item Read and Write Operations

When reading and writing with multiple items, an error generated by performing the operation on one item will not automatically generate an error in MATLAB. The following rules apply to reading and writing with multiple items:

  • If all items fail the operation, an error will be generated. The error message will contain specific information for each item about why the item failed.

  • If some items fail but some succeed, the operation does not error, but generates a warning, listing which items failed and the reason for failure.

Note that for asynchronous read and write operations, items may fail early (during the request for the operation) or late (when the information is returned from the server). If any items fail late, an error event will be generated in addition to the read async event or write async event.

Was this topic helpful?