Lesson 3: Reading and writing data
- Last UpdatedMay 16, 2023
- 2 minute read
- PI System
- AF SDK 2.10
- PI Server
After completing this lesson you will be able to:
-
Use AF SDK to read data from PI AF
-
Use AF SDK to write data to PI AF
-
Use bulk calls to retrieve data within a specified time range for many attributes
-
Use the AFValue object to store time-series information
Help for methods and data types used in this lesson
Bulk calls
To retrieve data within a specified time range for many attributes, it is time-consuming to issue a data call for each attribute, because many round trips over the network to the PI Data Archive are required. In networked systems, latency delays can be costly.
You can reduce network latency (the number of network round trips) by using list calls in AF SDK. First, you create a list of attributes to retrieve and store them in an AFAttributeList. You then access the Data property on the AFAttributeList, which exposes data retrieval methods for the entire attribute list. Now, you can make a single call to the server to retrieve data for all of the attributes, as shown in the following code:
AFAttributeList attrList = AFAttribute.FindElementAttributes(
// argument list omitted for brevity
);
// Bulk call to get value at specified time for all found attributes
IList<AFValue> vals = attrList.Data.RecordedValue(time);
You might be wondering why the above example used AFAttributeList instead of AFAttributes. The reason in that AFAttributes returns a list of attributes for an element, whereas AFAttributeList returns a list of unrelated AFAttributes. For more information, see AFAttributes and AFAttributeList.
The AFValue object contains two important properties:
-
AFValue.Timestamp: An AFTime object that represents the event's timestamp
-
AFValue.Value: A .NET object representing the event's value that can be cast to the appropriate type
AFTime is similar to a .NET DateTime object; however, AFTime objects can be constructed using PI Time syntax (for example: "t" or "*-10m").
Example
To read time-series data, you first obtain a reference to the AFAttribute, and then access its Data property. The data property is an AFData object that exposes methods to retrieve time-series data. In the example here, all of the archived values of an attribute for the last 10 minutes are retrieved.
AFTime startTime = new AFTime("*-10m");
AFTime endTime = new AFTime("*");
AFTimeRange timeRange = new AFTimeRange(startTime, endTime);
AFValues vals = attr.Data.RecordedValues(
timeRange: timeRange,
boundaryType: AFBoundaryType.Inside,
desiredUOM: null,
filterExpression: null,
includeFilteredValues: false);