Documentation
¶
Overview ¶
Package piwebapi is a client for the AVEVA (formerly OSIsoft) PI Web API, written from its public reference (https://docs.aveva.com/bundle/pi-web-api-reference/). It reads and writes time-series data and looks up the objects that hold it:
- Data Archives and PI points: dataservers, points (by path, WebId, name filter with paging), point attributes.
- Asset Framework: asset servers, asset databases, elements, attributes, event frames, and attribute static values.
- Streams (one point or attribute): value, end, recorded (with paging and backfill), interpolated, interpolated at times, plot, summary, recorded at time(s), value and values updates, stream updates.
- Stream sets (several streams at once, ad hoc by WebId or the attributes of an element or event frame): the same reads and the value and values updates, with partial failures reported per item.
- Batch requests with parent dependencies and parameters.
- WebID 2.0 helpers: reading a WebId's header, building path-only WebIds without a round trip.
Values decode to numbers, text, booleans or digital state names with their quality (bad, questionable, substituted, system). Logins are pluggable: Basic, Bearer, or Kerberos through the negotiate package (HTTP Negotiate, RFC 4559). Requests that change data carry the X-Requested-With header the PI Web API's CSRF defence asks for.
Example ¶
Log in with Kerberos, find a point and backfill its archived values, then write a value. It needs a PI Web API, so it is not run; piwebapi-sim runs the same calls against a simulated one.
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/cB-Sigma/piwebapi"
"github.com/cB-Sigma/piwebapi/negotiate"
)
func main() {
ctx := context.Background()
k, err := negotiate.New(negotiate.Config{Realm: "PLANT.EXAMPLE", KDCs: []string{"dc1.plant.example"},
Username: "svc-reader", Password: "demo-password"})
if err != nil {
log.Fatal(err)
}
c := piwebapi.New("https://pi.plant.example/piwebapi", nil, k.For(negotiate.SPNFor("https://pi.plant.example")))
pt, err := c.PointByPath(ctx, `\\PISRV01\BLR1.STEAM.TEMP`)
if err != nil {
log.Fatal(err)
}
since := time.Now().Add(-24 * time.Hour)
err = c.RecordedPages(ctx, pt.WebID, since, time.Now(), 1000, func(v piwebapi.Values) error {
for _, x := range v.Items {
val, quality := x.Decode()
fmt.Println(x.Timestamp, val, quality)
}
return nil
})
if err != nil {
log.Fatal(err)
}
err = c.UpdateValue(ctx, pt.WebID, piwebapi.TimedValue{Timestamp: "*", Value: 181.5}, piwebapi.UpdateOptions{})
if err != nil {
log.Fatal(err)
}
}
Output:
Index ¶
- Constants
- Variables
- func AttributeWebID(path string) string
- func IsNotFound(err error) bool
- func PathWebID(marker, owner, path string) string
- func PointWebID(path string) string
- func Time(t time.Time) string
- type AssetDatabase
- type AssetServer
- type AtTimesOptions
- type Attribute
- type AttributeQuery
- type AuthError
- type Authorizer
- type Basic
- type BatchRequest
- type BatchResponse
- type BatchTemplate
- type Bearer
- type Client
- func (c *Client) AssetDatabase(ctx context.Context, webID string) (AssetDatabase, error)
- func (c *Client) AssetDatabaseByPath(ctx context.Context, path string) (AssetDatabase, error)
- func (c *Client) AssetDatabases(ctx context.Context, serverWebID string) ([]AssetDatabase, error)
- func (c *Client) AssetServer(ctx context.Context, webID string) (AssetServer, error)
- func (c *Client) AssetServerByName(ctx context.Context, name string) (AssetServer, error)
- func (c *Client) AssetServerByPath(ctx context.Context, path string) (AssetServer, error)
- func (c *Client) AssetServers(ctx context.Context) ([]AssetServer, error)
- func (c *Client) Attribute(ctx context.Context, webID string) (Attribute, error)
- func (c *Client) AttributeByPath(ctx context.Context, path string) (Attribute, error)
- func (c *Client) AttributeValue(ctx context.Context, webID string) (Value, error)
- func (c *Client) Attributes(ctx context.Context, elementWebID string, o AttributeQuery) ([]Attribute, error)
- func (c *Client) AttributesByPath(ctx context.Context, paths []string) ([]Found[Attribute], error)
- func (c *Client) Batch(ctx context.Context, reqs map[string]BatchRequest) (map[string]BatchResponse, error)
- func (c *Client) BatchGet(path string, q url.Values, parents ...string) BatchRequest
- func (c *Client) BatchPost(path string, q url.Values, body any, parents ...string) (BatchRequest, error)
- func (c *Client) ChildAttributes(ctx context.Context, attributeWebID string, o AttributeQuery) ([]Attribute, error)
- func (c *Client) ChildElements(ctx context.Context, elementWebID string, o ElementQuery) ([]Element, error)
- func (c *Client) ChildEventFrames(ctx context.Context, eventFrameWebID string, o EventFrameQuery) ([]EventFrame, error)
- func (c *Client) DataServer(ctx context.Context, webID string) (DataServer, error)
- func (c *Client) DataServerByName(ctx context.Context, name string) (DataServer, error)
- func (c *Client) DataServerByPath(ctx context.Context, path string) (DataServer, error)
- func (c *Client) DataServers(ctx context.Context) ([]DataServer, error)
- func (c *Client) Do(ctx context.Context, method, path string, q url.Values, body, out any) error
- func (c *Client) Element(ctx context.Context, webID string) (Element, error)
- func (c *Client) ElementByPath(ctx context.Context, path string) (Element, error)
- func (c *Client) ElementEventFrames(ctx context.Context, elementWebID string, o EventFrameQuery) ([]EventFrame, error)
- func (c *Client) Elements(ctx context.Context, databaseWebID string, o ElementQuery) ([]Element, error)
- func (c *Client) ElementsByPath(ctx context.Context, paths []string) ([]Found[Element], error)
- func (c *Client) End(ctx context.Context, webID string, o Common) (Value, error)
- func (c *Client) EventFrame(ctx context.Context, webID string) (EventFrame, error)
- func (c *Client) EventFrameAttributes(ctx context.Context, eventFrameWebID string, o AttributeQuery) ([]Attribute, error)
- func (c *Client) EventFrameByPath(ctx context.Context, path string) (EventFrame, error)
- func (c *Client) EventFrames(ctx context.Context, databaseWebID string, o EventFrameQuery) ([]EventFrame, error)
- func (c *Client) Get(ctx context.Context, path string, q url.Values, out any) error
- func (c *Client) Interpolated(ctx context.Context, webID string, start, end time.Time, ...) (Values, error)
- func (c *Client) InterpolatedAtTimes(ctx context.Context, webID string, times []string, o AtTimesOptions) (Values, error)
- func (c *Client) InterpolatedWith(ctx context.Context, webID string, o InterpolatedOptions) (Values, error)
- func (c *Client) Plot(ctx context.Context, webID string, o PlotOptions) (Values, error)
- func (c *Client) Point(ctx context.Context, webID string) (Point, error)
- func (c *Client) PointAttributes(ctx context.Context, webID, nameFilter string) ([]PointAttribute, error)
- func (c *Client) PointByPath(ctx context.Context, path string) (Point, error)
- func (c *Client) PointPages(ctx context.Context, dataServer, nameFilter string, page int, ...) error
- func (c *Client) Points(ctx context.Context, dataServer, nameFilter string, startIndex, maxCount int) ([]Point, error)
- func (c *Client) PointsByPath(ctx context.Context, paths []string) ([]Found[Point], error)
- func (c *Client) Recorded(ctx context.Context, webID string, start, end time.Time, maxCount int) (Values, error)
- func (c *Client) RecordedAtTime(ctx context.Context, webID, time, mode string, o Common) (Value, error)
- func (c *Client) RecordedAtTimes(ctx context.Context, webID string, times []string, o AtTimesOptions) (Values, error)
- func (c *Client) RecordedPages(ctx context.Context, webID string, start, end time.Time, page int, ...) error
- func (c *Client) RecordedWith(ctx context.Context, webID string, o RecordedOptions) (Values, error)
- func (c *Client) RegisterStreamSetUpdates(ctx context.Context, webIDs []string) ([]StreamUpdates, error)
- func (c *Client) RegisterUpdates(ctx context.Context, webID string) (StreamUpdates, error)
- func (c *Client) SetAttributeValue(ctx context.Context, webID string, v TimedValue) error
- func (c *Client) Status(ctx context.Context) (SystemStatus, error)
- func (c *Client) StreamSetEnd(ctx context.Context, s Streams, o Common) ([]StreamValue, error)
- func (c *Client) StreamSetInterpolated(ctx context.Context, s Streams, o InterpolatedOptions) ([]StreamValues, error)
- func (c *Client) StreamSetInterpolatedAtTimes(ctx context.Context, s Streams, times []string, o AtTimesOptions) ([]StreamValues, error)
- func (c *Client) StreamSetPlot(ctx context.Context, s Streams, o PlotOptions) ([]StreamValues, error)
- func (c *Client) StreamSetRecorded(ctx context.Context, s Streams, o RecordedOptions) ([]StreamValues, error)
- func (c *Client) StreamSetRecordedAtTime(ctx context.Context, s Streams, time, mode string, o Common) ([]StreamValue, error)
- func (c *Client) StreamSetRecordedAtTimes(ctx context.Context, s Streams, times []string, o AtTimesOptions) ([]StreamValues, error)
- func (c *Client) StreamSetSummary(ctx context.Context, s Streams, o SummaryOptions) ([]StreamSummaries, error)
- func (c *Client) StreamSetUpdateValue(ctx context.Context, vs []StreamUpdate, o UpdateOptions) error
- func (c *Client) StreamSetUpdateValues(ctx context.Context, vs []StreamValuesUpdate, o UpdateOptions) error
- func (c *Client) StreamSetUpdates(ctx context.Context, markers []string, o Common) ([]StreamUpdates, error)
- func (c *Client) StreamSetValue(ctx context.Context, s Streams, o ValueOptions) ([]StreamValue, error)
- func (c *Client) Summary(ctx context.Context, webID string, o SummaryOptions) ([]Summary, error)
- func (c *Client) System(ctx context.Context) (System, error)
- func (c *Client) URL(path string, q url.Values) string
- func (c *Client) UpdateValue(ctx context.Context, webID string, v TimedValue, o UpdateOptions) error
- func (c *Client) UpdateValues(ctx context.Context, webID string, vs []TimedValue, o UpdateOptions) error
- func (c *Client) Updates(ctx context.Context, marker string, o Common) (StreamUpdates, error)
- func (c *Client) UserInfo(ctx context.Context) (UserInfo, error)
- func (c *Client) Value(ctx context.Context, webID string, o ValueOptions) (Value, error)
- func (c *Client) Versions(ctx context.Context) (map[string]any, error)
- type Common
- type DataServer
- type DigitalState
- type Element
- type ElementQuery
- type Error
- type EventFrame
- type EventFrameQuery
- type Found
- type InterpolatedOptions
- type ItemError
- type Paging
- type PartialError
- type PlotOptions
- type Point
- type PointAttribute
- type RecordedOptions
- type StreamSummaries
- type StreamUpdate
- type StreamUpdates
- type StreamValue
- type StreamValues
- type StreamValuesUpdate
- type Streams
- type Summary
- type SummaryOptions
- type System
- type SystemStatus
- type TimedValue
- type UpdateEvent
- type UpdateOptions
- type UserInfo
- type Value
- type ValueOptions
- type Values
- type WebIDInfo
Examples ¶
Constants ¶
const ( SearchOverlapped = "Overlapped" SearchInclusive = "Inclusive" SearchStartInclusive = "StartInclusive" SearchEndInclusive = "EndInclusive" SearchBackwardFromStartTime = "BackwardFromStartTime" SearchForwardFromStartTime = "ForwardFromStartTime" SearchBackwardFromEndTime = "BackwardFromEndTime" SearchForwardFromEndTime = "ForwardFromEndTime" SearchBackwardInProgress = "BackwardInProgress" SearchForwardInProgress = "ForwardInProgress" )
Event frame search modes.
const ( BoundaryInside = "Inside" BoundaryOutside = "Outside" BoundaryInterpolated = "Interpolated" )
Boundary types of a recorded read.
const ( RetrieveAuto = "Auto" RetrieveAtOrBefore = "AtOrBefore" RetrieveBefore = "Before" RetrieveAtOrAfter = "AtOrAfter" RetrieveAfter = "After" RetrieveExact = "Exact" )
Retrieval modes of a recorded-at-time read.
const ( UpdateReplace = "Replace" UpdateInsert = "Insert" UpdateNoReplace = "NoReplace" UpdateReplaceOnly = "ReplaceOnly" UpdateInsertNoCompression = "InsertNoCompression" UpdateRemove = "Remove" )
Update options of a write: how a value meets one already archived at its timestamp.
const ( BufferDoNotBuffer = "DoNotBuffer" BufferBufferIfPossible = "BufferIfPossible" BufferBuffer = "Buffer" )
Buffer options of a write.
const ( SummaryTotal = "Total" SummaryAverage = "Average" SummaryMinimum = "Minimum" SummaryMaximum = "Maximum" SummaryRange = "Range" SummaryStdDev = "StdDev" SummaryPopulationStdDev = "PopulationStdDev" SummaryCount = "Count" SummaryPercentGood = "PercentGood" SummaryTotalWithUOM = "TotalWithUOM" SummaryAll = "All" SummaryAllForNonNumeric = "AllForNonNumeric" CalculationTimeWeighted = "TimeWeighted" CalculationEventWeighted = "EventWeighted" )
Summary types of a summary read.
const ( WebIDFull = 'F' WebIDIDOnly = 'I' WebIDPathOnly = 'P' WebIDLocalIDOnly = 'L' WebIDDefaultIDOnly = 'D' )
WebID types (the first letter).
const ( MarkerPoint = "DP" MarkerDataServer = "DS" MarkerAssetServer = "RS" MarkerAssetDatabase = "RD" MarkerElement = "Em" MarkerAttribute = "Ab" MarkerEventFrame = "Fm" MarkerEnumeration = "MS" )
WebID markers of the object kinds this client reads.
const ( OwnerElement = "E" OwnerEventFrame = "F" )
Owner markers of an attribute's WebId.
const Tick = 100 * time.Nanosecond
Tick is the PI time resolution.
Variables ¶
var ErrAuth = errors.New("the PI Web API refused the login")
ErrAuth is a login the PI Web API refused; an *AuthError matches it.
var ErrWebID = errors.New("piwebapi: not a WebID 2.0")
ErrWebID is a WebId this client cannot read.
Functions ¶
func AttributeWebID ¶
AttributeWebID is the path-only WebId of an element's attribute (\\AFSERVER\DB\Element|Attribute).
func PathWebID ¶
PathWebID is the path-only WebId of the object at path (\\SERVER\TAG, \\AFSERVER\DB\Element|Attribute), of kind marker; owner is the owner marker for an attribute (OwnerElement, OwnerEventFrame) and empty for the others. The PI Web API resolves such a WebId by its path, so it is found as long as the object keeps its name.
func PointWebID ¶
PointWebID is the path-only WebId of a PI point (\\SERVER\TAG).
Example ¶
Name a point without looking it up.
package main
import (
"fmt"
"github.com/cB-Sigma/piwebapi"
)
func main() {
id := piwebapi.PointWebID(`\\PISRV01\BLR1.STEAM.TEMP`)
info, _ := piwebapi.ParseWebID(id)
fmt.Println(id)
fmt.Println(info.Marker, info.Path)
}
Output: P1DPUElTUlYwMVxCTFIxLlNURUFNLlRFTVA DP \\PISRV01\BLR1.STEAM.TEMP
Types ¶
type AssetDatabase ¶
type AssetDatabase struct {
WebID string `json:"WebId"`
ID string `json:"Id,omitempty"`
Name string `json:"Name"`
Description string `json:"Description,omitempty"`
Path string `json:"Path,omitempty"`
}
AssetDatabase is an AF database.
type AssetServer ¶
type AssetServer struct {
WebID string `json:"WebId"`
ID string `json:"Id,omitempty"`
Name string `json:"Name"`
Description string `json:"Description,omitempty"`
Path string `json:"Path,omitempty"`
IsConnected bool `json:"IsConnected,omitempty"`
ServerVersion string `json:"ServerVersion,omitempty"`
}
AssetServer is a PI AF server (a PI System).
type AtTimesOptions ¶
type AtTimesOptions struct {
// SortOrder is Ascending (default) or Descending.
SortOrder string
// RetrievalMode applies to recorded reads (RetrieveAuto...).
RetrievalMode string
FilterExpression string
IncludeFilteredValues bool
Common
}
AtTimesOptions is a read at listed times.
type Attribute ¶
type Attribute struct {
WebID string `json:"WebId"`
ID string `json:"Id,omitempty"`
Name string `json:"Name"`
Description string `json:"Description,omitempty"`
Path string `json:"Path,omitempty"`
Type string `json:"Type,omitempty"`
TypeQualifier string `json:"TypeQualifier,omitempty"`
DefaultUnitsName string `json:"DefaultUnitsName,omitempty"`
DataReferencePlugIn string `json:"DataReferencePlugIn,omitempty"`
ConfigString string `json:"ConfigString,omitempty"`
IsConfigurationItem bool `json:"IsConfigurationItem,omitempty"`
IsExcluded bool `json:"IsExcluded,omitempty"`
IsHidden bool `json:"IsHidden,omitempty"`
IsManualDataEntry bool `json:"IsManualDataEntry,omitempty"`
HasChildren bool `json:"HasChildren,omitempty"`
Step bool `json:"Step,omitempty"`
CategoryNames []string `json:"CategoryNames,omitempty"`
}
Attribute is an AF attribute of an element or event frame.
type AttributeQuery ¶
type AttributeQuery struct {
NameFilter, CategoryName, TemplateName string
// ValueType is the attribute value type (Double, Int32, String...).
ValueType string
SearchFullHierarchy, ShowExcluded, ShowHidden bool
Paging
Common
}
AttributeQuery filters the attributes of an element, event frame or attribute.
type AuthError ¶
type AuthError struct {
Status int
Message string
// Offered are the login schemes of the answer's WWW-Authenticate
// headers (Negotiate, Basic, Bearer, NTLM).
Offered []string
// NTLM is set when the server offered NTLM and not Kerberos: NTLM
// alone, or a Negotiate answer carrying an NTLM token, which a
// Windows host sends when it has no service principal for the name
// the client asked for. This client does not speak NTLM; register
// the service principal HTTP/<host> for the PI Web API's account.
NTLM bool
}
AuthError is a 401 or 403 answer. Message is the answer's Errors list, when it has one (a 403 may be a missing permission rather than a bad login).
type Authorizer ¶
Authorizer adds a login to a request. An Authorizer that also has a Reset() method is reset when the PI Web API refuses a login (401 or 403), so that the next request logs in again; negotiate.Service is one.
type BatchRequest ¶
type BatchRequest struct {
Method string `json:"Method"`
Resource string `json:"Resource,omitempty"`
RequestTemplate *BatchTemplate `json:"RequestTemplate,omitempty"`
Parameters []string `json:"Parameters,omitempty"`
Headers map[string]string `json:"Headers,omitempty"`
Content string `json:"Content,omitempty"`
ParentIDs []string `json:"ParentIds,omitempty"`
}
BatchRequest is one request of a batch. Resource is an address on the PI Web API (Client.URL makes one), and may hold "{0}", "{1}"... placeholders that Parameters fill: each parameter is a JSONPath into an earlier response ("$.GetPoint.Content.WebId"), whose request must be listed in ParentIDs. RequestTemplate, instead of Resource, repeats the request once for each value a parameter selects ("$.Points.Content.Items[*].WebId"); its response then holds one response per value in Content.Items. Content is the request body as JSON text.
type BatchResponse ¶
type BatchResponse struct {
Status int `json:"Status"`
Headers map[string]string `json:"Headers,omitempty"`
Content json.RawMessage `json:"Content,omitempty"`
}
BatchResponse is the answer to one request of a batch.
func (BatchResponse) Decode ¶
func (r BatchResponse) Decode(out any) error
Decode reads a successful response's content into out, or returns Err.
func (BatchResponse) Err ¶
func (r BatchResponse) Err() error
Err is the request's failure as an *Error (an *AuthError for 401 and 403), nil when it succeeded.
func (BatchResponse) Items ¶
func (r BatchResponse) Items() ([]BatchResponse, error)
Items reads the responses of a RequestTemplate request (one per parameter value).
func (BatchResponse) OK ¶
func (r BatchResponse) OK() bool
OK reports whether the request succeeded (2xx).
type BatchTemplate ¶
type BatchTemplate struct {
Resource string `json:"Resource"`
}
BatchTemplate is the Resource of a request repeated for each value of its parameter.
type Client ¶
type Client struct {
Base string
HTTP *http.Client // nil: http.DefaultClient
Auth Authorizer // nil: no login
// RequestedWith is the X-Requested-With value sent with requests that
// change data (POST, PUT, PATCH, DELETE); empty: "XMLHttpRequest".
// The PI Web API refuses such requests without the header when its
// CSRF defence is on, which is its default.
RequestedWith string
}
Client is a PI Web API at Base (https://host/piwebapi).
func New ¶
func New(base string, hc *http.Client, auth Authorizer) *Client
New returns a client for base.
func (*Client) AssetDatabase ¶
AssetDatabase reads an AF database by WebId. GET assetdatabases/{webId}.
func (*Client) AssetDatabaseByPath ¶
AssetDatabaseByPath finds an AF database by path (\\AFSERVER\DB). GET assetdatabases?path=.
func (*Client) AssetDatabases ¶
AssetDatabases lists an AF server's databases. GET assetservers/{webId}/assetdatabases.
func (*Client) AssetServer ¶
AssetServer reads an AF server by WebId. GET assetservers/{webId}.
func (*Client) AssetServerByName ¶
AssetServerByName finds an AF server by name. GET assetservers?name=.
func (*Client) AssetServerByPath ¶
AssetServerByPath finds an AF server by path (\\AFSERVER). GET assetservers?path=.
func (*Client) AssetServers ¶
func (c *Client) AssetServers(ctx context.Context) ([]AssetServer, error)
AssetServers lists the AF servers. GET assetservers.
func (*Client) AttributeByPath ¶
AttributeByPath finds an attribute by path (\\AFSERVER\DB\Plant\Boiler1|Temperature). GET attributes?path=.
func (*Client) AttributeValue ¶
AttributeValue reads an attribute's value through the attribute controller (static attributes; streams work for both). GET attributes/{webId}/value.
func (*Client) Attributes ¶
func (c *Client) Attributes(ctx context.Context, elementWebID string, o AttributeQuery) ([]Attribute, error)
Attributes lists an element's attributes. GET elements/{webId}/attributes.
func (*Client) AttributesByPath ¶
AttributesByPath looks up several attributes by path in one request. GET attributes/multiple.
func (*Client) Batch ¶
func (c *Client) Batch(ctx context.Context, reqs map[string]BatchRequest) (map[string]BatchResponse, error)
Batch sends several requests in one (POST batch) and returns the response of each, by the IDs of reqs. The PI Web API answers 207 when some requests failed; each response's Err tells which. An error is returned only when the batch as a whole failed.
func (*Client) BatchPost ¶
func (c *Client) BatchPost(path string, q url.Values, body any, parents ...string) (BatchRequest, error)
BatchPost is a POST request of a batch for path with query q and body as JSON.
func (*Client) ChildAttributes ¶
func (c *Client) ChildAttributes(ctx context.Context, attributeWebID string, o AttributeQuery) ([]Attribute, error)
ChildAttributes lists an attribute's child attributes. GET attributes/{webId}/attributes.
func (*Client) ChildElements ¶
func (c *Client) ChildElements(ctx context.Context, elementWebID string, o ElementQuery) ([]Element, error)
ChildElements lists an element's child elements. GET elements/{webId}/elements.
func (*Client) ChildEventFrames ¶
func (c *Client) ChildEventFrames(ctx context.Context, eventFrameWebID string, o EventFrameQuery) ([]EventFrame, error)
ChildEventFrames searches an event frame's child event frames. GET eventframes/{webId}/eventframes.
func (*Client) DataServer ¶
DataServer reads a Data Archive by WebId. GET dataservers/{webId}.
func (*Client) DataServerByName ¶
DataServerByName finds a Data Archive by name. GET dataservers?name=.
func (*Client) DataServerByPath ¶
DataServerByPath finds a Data Archive by path (\\PIServers[NAME]). GET dataservers?path=.
func (*Client) DataServers ¶
func (c *Client) DataServers(ctx context.Context) ([]DataServer, error)
DataServers lists the Data Archives.
func (*Client) Do ¶
Do sends a request with method to path (relative to Base) with query q and, when body is not nil, body as JSON; a 2xx answer with a body is decoded into out (when out is not nil). A 207 answer to a write is a *PartialError listing the items that failed.
func (*Client) ElementByPath ¶
ElementByPath finds an element by path (\\AFSERVER\DB\Plant\Boiler1). GET elements?path=.
func (*Client) ElementEventFrames ¶
func (c *Client) ElementEventFrames(ctx context.Context, elementWebID string, o EventFrameQuery) ([]EventFrame, error)
ElementEventFrames searches the event frames that reference an element. GET elements/{webId}/eventframes.
func (*Client) Elements ¶
func (c *Client) Elements(ctx context.Context, databaseWebID string, o ElementQuery) ([]Element, error)
Elements lists a database's elements (its root elements, or with SearchFullHierarchy all of them). GET assetdatabases/{webId}/elements.
func (*Client) ElementsByPath ¶
ElementsByPath looks up several elements by path in one request. GET elements/multiple.
func (*Client) EventFrame ¶
EventFrame reads an event frame by WebId. GET eventframes/{webId}.
func (*Client) EventFrameAttributes ¶
func (c *Client) EventFrameAttributes(ctx context.Context, eventFrameWebID string, o AttributeQuery) ([]Attribute, error)
EventFrameAttributes lists an event frame's attributes. GET eventframes/{webId}/attributes.
func (*Client) EventFrameByPath ¶
EventFrameByPath finds an event frame by path. GET eventframes?path=.
func (*Client) EventFrames ¶
func (c *Client) EventFrames(ctx context.Context, databaseWebID string, o EventFrameQuery) ([]EventFrame, error)
EventFrames searches a database's event frames. GET assetdatabases/{webId}/eventframes.
func (*Client) Get ¶
Get reads path (relative to Base) with query q into out. Errors from the Authorizer are returned unchanged.
func (*Client) Interpolated ¶
func (c *Client) Interpolated(ctx context.Context, webID string, start, end time.Time, interval time.Duration) (Values, error)
Interpolated reads values every interval (whole seconds) from start to end.
func (*Client) InterpolatedAtTimes ¶
func (c *Client) InterpolatedAtTimes(ctx context.Context, webID string, times []string, o AtTimesOptions) (Values, error)
InterpolatedAtTimes reads a stream's values at the given times. streams/{webId}/interpolatedattimes.
func (*Client) InterpolatedWith ¶
func (c *Client) InterpolatedWith(ctx context.Context, webID string, o InterpolatedOptions) (Values, error)
InterpolatedWith reads a stream's values at even intervals. streams/{webId}/interpolated.
func (*Client) PointAttributes ¶
func (c *Client) PointAttributes(ctx context.Context, webID, nameFilter string) ([]PointAttribute, error)
PointAttributes reads a PI point's point attributes, those whose names match nameFilter (empty: all). GET points/{webId}/attributes.
func (*Client) PointByPath ¶
PointByPath finds a point by its path (\\server\tag).
func (*Client) PointPages ¶
func (c *Client) PointPages(ctx context.Context, dataServer, nameFilter string, page int, fn func([]Point) error) error
PointPages lists all of a Data Archive's points matching nameFilter, page points at a time, calling fn with each page; it stops at the first page that is not full or when fn returns an error.
func (*Client) Points ¶
func (c *Client) Points(ctx context.Context, dataServer, nameFilter string, startIndex, maxCount int) ([]Point, error)
Points lists a Data Archive's points matching nameFilter (PI wildcards: * and ?), from startIndex, at most maxCount.
func (*Client) PointsByPath ¶
PointsByPath looks up several points by path in one request. GET points/multiple.
func (*Client) Recorded ¶
func (c *Client) Recorded(ctx context.Context, webID string, start, end time.Time, maxCount int) (Values, error)
Recorded reads the archived values of a point between start and end (both included, boundaryType Inside), at most maxCount.
func (*Client) RecordedAtTime ¶
func (c *Client) RecordedAtTime(ctx context.Context, webID, time, mode string, o Common) (Value, error)
RecordedAtTime reads the archived value at or near time, as mode says (RetrieveAuto...; empty: the API's default, Auto). streams/{webId}/recordedattime.
func (*Client) RecordedAtTimes ¶
func (c *Client) RecordedAtTimes(ctx context.Context, webID string, times []string, o AtTimesOptions) (Values, error)
RecordedAtTimes reads the archived values at or near each time. streams/{webId}/recordedattimes.
func (*Client) RecordedPages ¶
func (c *Client) RecordedPages(ctx context.Context, webID string, start, end time.Time, page int, fn func(Values) error) error
RecordedPages backfills: it reads the archived values after start up to end, page values at a time, and calls fn with each page. The PI Web API gives recorded reads no next-page link; a full page means there may be more. The next read starts at the full page's last timestamp (included), and the values at that timestamp already passed to fn are dropped from it, so several values sharing one timestamp across a page boundary are each read once. When a whole page shares one timestamp (page or more values at the same instant), the read moves on to just after it (one Tick) and the values beyond the page at that instant are not read; use a larger page if that matters. It stops at the first page that is not full, or when fn returns an error.
func (*Client) RecordedWith ¶
RecordedWith reads a stream's archived values. streams/{webId}/recorded.
func (*Client) RegisterStreamSetUpdates ¶
func (c *Client) RegisterStreamSetUpdates(ctx context.Context, webIDs []string) ([]StreamUpdates, error)
RegisterStreamSetUpdates registers for the changes of several streams. POST streamsets/updates?webId=...
func (*Client) RegisterUpdates ¶
RegisterUpdates registers for a stream's changes and returns the first marker. POST streams/{webId}/updates.
func (*Client) SetAttributeValue ¶
SetAttributeValue sets the value of an attribute that has no data reference (a static value). PUT attributes/{webId}/value.
func (*Client) Status ¶
func (c *Client) Status(ctx context.Context) (SystemStatus, error)
Status reads the PI Web API's state. GET system/status.
func (*Client) StreamSetEnd ¶
StreamSetEnd reads each stream's last archived value. streamsets/end, streamsets/{webId}/end.
func (*Client) StreamSetInterpolated ¶
func (c *Client) StreamSetInterpolated(ctx context.Context, s Streams, o InterpolatedOptions) ([]StreamValues, error)
StreamSetInterpolated reads each stream's values at even intervals. streamsets/interpolated, streamsets/{webId}/interpolated.
func (*Client) StreamSetInterpolatedAtTimes ¶
func (c *Client) StreamSetInterpolatedAtTimes(ctx context.Context, s Streams, times []string, o AtTimesOptions) ([]StreamValues, error)
StreamSetInterpolatedAtTimes reads each stream's values at the given times. streamsets/interpolatedattimes, streamsets/{webId}/interpolatedattimes.
func (*Client) StreamSetPlot ¶
func (c *Client) StreamSetPlot(ctx context.Context, s Streams, o PlotOptions) ([]StreamValues, error)
StreamSetPlot reads the values that draw each stream. streamsets/plot, streamsets/{webId}/plot.
func (*Client) StreamSetRecorded ¶
func (c *Client) StreamSetRecorded(ctx context.Context, s Streams, o RecordedOptions) ([]StreamValues, error)
StreamSetRecorded reads each stream's archived values. streamsets/recorded, streamsets/{webId}/recorded.
func (*Client) StreamSetRecordedAtTime ¶
func (c *Client) StreamSetRecordedAtTime(ctx context.Context, s Streams, time, mode string, o Common) ([]StreamValue, error)
StreamSetRecordedAtTime reads each stream's archived value at or near time. streamsets/recordedattime, streamsets/{webId}/recordedattime.
func (*Client) StreamSetRecordedAtTimes ¶
func (c *Client) StreamSetRecordedAtTimes(ctx context.Context, s Streams, times []string, o AtTimesOptions) ([]StreamValues, error)
StreamSetRecordedAtTimes reads each stream's archived values at or near each time. streamsets/recordedattimes, streamsets/{webId}/recordedattimes.
func (*Client) StreamSetSummary ¶
func (c *Client) StreamSetSummary(ctx context.Context, s Streams, o SummaryOptions) ([]StreamSummaries, error)
StreamSetSummary reads each stream's summaries. streamsets/summary, streamsets/{webId}/summary.
func (*Client) StreamSetUpdateValue ¶
func (c *Client) StreamSetUpdateValue(ctx context.Context, vs []StreamUpdate, o UpdateOptions) error
StreamSetUpdateValue writes one value to each stream. POST streamsets/value. When some fail, the error is a *PartialError naming them by their index in vs.
func (*Client) StreamSetUpdateValues ¶
func (c *Client) StreamSetUpdateValues(ctx context.Context, vs []StreamValuesUpdate, o UpdateOptions) error
StreamSetUpdateValues writes values to each stream. POST streamsets/recorded. When some fail, the error is a *PartialError naming them by stream (Index) and value (Sub).
func (*Client) StreamSetUpdates ¶
func (c *Client) StreamSetUpdates(ctx context.Context, markers []string, o Common) ([]StreamUpdates, error)
StreamSetUpdates reads the changes since each marker. GET streamsets/updates?marker=...
func (*Client) StreamSetValue ¶
func (c *Client) StreamSetValue(ctx context.Context, s Streams, o ValueOptions) ([]StreamValue, error)
StreamSetValue reads each stream's current value, or its value at o.Time. streamsets/value, streamsets/{webId}/value.
func (*Client) Summary ¶
Summary reads a stream's summaries (totals, averages...). streams/{webId}/summary.
func (*Client) URL ¶
URL is the absolute address of path (relative to Base) with query q, as a Batch request's Resource takes it.
func (*Client) UpdateValue ¶
func (c *Client) UpdateValue(ctx context.Context, webID string, v TimedValue, o UpdateOptions) error
UpdateValue writes one value to a stream. POST streams/{webId}/value. The PI Web API answers 202 (accepted, maybe buffered) or 204 (written).
func (*Client) UpdateValues ¶
func (c *Client) UpdateValues(ctx context.Context, webID string, vs []TimedValue, o UpdateOptions) error
UpdateValues writes values to a stream. POST streams/{webId}/recorded. When some values fail, the error is a *PartialError naming them by their index in vs.
func (*Client) Updates ¶
Updates reads the changes since marker and the next marker. GET streams/updates/{marker}.
func (*Client) UserInfo ¶
UserInfo reads who the PI Web API takes the caller to be. GET system/userinfo.
type Common ¶
type Common struct {
// DesiredUnits converts values to these units (attributes only).
DesiredUnits string
// SelectedFields limits the answer's fields ("Items.Timestamp;Items.Value").
SelectedFields string
// TimeZone names the time zone of the answer's timestamps.
TimeZone string
// WebIDType asks for WebIds of this type (Full, IDOnly, PathOnly,
// LocalIDOnly, DefaultIDOnly).
WebIDType string
// Extra holds any other parameter, sent as given.
Extra url.Values
}
Common are the parameters most reads take.
type DataServer ¶
type DataServer struct {
WebID string `json:"WebId"`
Name string `json:"Name"`
ID string `json:"Id,omitempty"`
Path string `json:"Path,omitempty"`
IsConnected bool `json:"IsConnected,omitempty"`
ServerVersion string `json:"ServerVersion,omitempty"`
}
DataServer is a PI Data Archive.
type DigitalState ¶
type DigitalState struct {
Name string `json:"Name"`
Value int `json:"Value,omitempty"`
IsSystem bool `json:"IsSystem,omitempty"`
}
DigitalState is a digital state value: its name, its code in the state set, and whether it is a system state (No Data, I/O Timeout, Shutdown). Written as a TimedValue's Value, DigitalState{Name: "Running"} sends the name alone.
type Element ¶
type Element struct {
WebID string `json:"WebId"`
ID string `json:"Id,omitempty"`
Name string `json:"Name"`
Description string `json:"Description,omitempty"`
Path string `json:"Path,omitempty"`
TemplateName string `json:"TemplateName,omitempty"`
HasChildren bool `json:"HasChildren,omitempty"`
CategoryNames []string `json:"CategoryNames,omitempty"`
}
Element is an AF element.
type ElementQuery ¶
type ElementQuery struct {
NameFilter, DescriptionFilter string
CategoryName, TemplateName string
// ElementType is Any, Other, Node, Measurement, Flow...
ElementType string
SearchFullHierarchy bool
Paging
Common
}
ElementQuery filters the elements of a database or element.
type Error ¶
Error is any other answer outside 2xx, with the PI Web API's Errors list (or the start of the body) as Message. RetryAfter is the answer's Retry-After header, when it has one in seconds.
type EventFrame ¶
type EventFrame struct {
WebID string `json:"WebId"`
ID string `json:"Id,omitempty"`
Name string `json:"Name"`
Description string `json:"Description,omitempty"`
Path string `json:"Path,omitempty"`
TemplateName string `json:"TemplateName,omitempty"`
HasChildren bool `json:"HasChildren,omitempty"`
CategoryNames []string `json:"CategoryNames,omitempty"`
StartTime time.Time `json:"StartTime"`
EndTime time.Time `json:"EndTime"`
Severity string `json:"Severity,omitempty"`
CanBeAcknowledged bool `json:"CanBeAcknowledged,omitempty"`
IsAcknowledged bool `json:"IsAcknowledged,omitempty"`
IsAnnotated bool `json:"IsAnnotated,omitempty"`
IsLocked bool `json:"IsLocked,omitempty"`
AreValuesCaptured bool `json:"AreValuesCaptured,omitempty"`
RefElementWebIDs []string `json:"RefElementWebIds,omitempty"`
}
EventFrame is an AF event frame. An event frame still in progress has an EndTime far in the future (9999-12-31).
func (EventFrame) InProgress ¶
func (e EventFrame) InProgress() bool
InProgress reports whether the event frame has not ended.
type EventFrameQuery ¶
type EventFrameQuery struct {
SearchMode string
StartTime, EndTime string
NameFilter string
ReferencedElementNameFilter string
ReferencedElementTemplate string
CategoryName, TemplateName string
Severity []string
CanBeAcknowledged *bool
IsAcknowledged *bool
SearchFullHierarchy bool
Paging
Common
}
EventFrameQuery searches event frames. Empty times take the API's defaults (StartTime "*-8h", EndTime "*").
type Found ¶
Found is one item of a lookup of several objects by path or WebId: Object is decoded into T; Err is set when that one was not found.
type InterpolatedOptions ¶
type InterpolatedOptions struct {
StartTime, EndTime string
// Interval is a PI time span ("1h", "30m", "10s"; the API's default
// is 1h).
Interval string
// SyncTime aligns the intervals; SyncTimeBoundaryType is Inside or
// Outside.
SyncTime, SyncTimeBoundaryType string
FilterExpression string
IncludeFilteredValues bool
Common
}
InterpolatedOptions is an interpolated read.
type ItemError ¶
ItemError is one item of a write that failed: Index is its position in the request (Sub its position within that item's values, for stream set writes of several values; -1 otherwise), Status the item's substatus.
type Paging ¶
type Paging struct {
StartIndex int
MaxCount int
// SortField and SortOrder (Ascending, Descending) order the list.
SortField, SortOrder string
}
Paging is the start and size of a page of a list.
type PartialError ¶
type PartialError struct {
Items []ItemError
}
PartialError is a 207 answer to a write: some items were written and Items were not.
func (*PartialError) Error ¶
func (e *PartialError) Error() string
type PlotOptions ¶
PlotOptions is a plot read: values that draw the stream over Intervals pixels' worth of intervals (first, last, minimum, maximum and exceptional values of each).
type Point ¶
type Point struct {
WebID string `json:"WebId"`
Name string `json:"Name"`
Path string `json:"Path"`
Desc string `json:"Descriptor"`
Units string `json:"EngineeringUnits"`
Type string `json:"PointType"`
ID int64 `json:"Id,omitempty"`
PointClass string `json:"PointClass,omitempty"`
DigitalSetName string `json:"DigitalSetName,omitempty"`
Step bool `json:"Step,omitempty"`
Future bool `json:"Future,omitempty"`
}
Point is a PI point.
type PointAttribute ¶
PointAttribute is one attribute of a PI point (zero, span, compdev...).
type RecordedOptions ¶
type RecordedOptions struct {
StartTime, EndTime string
// BoundaryType is BoundaryInside (the API's default), Outside or
// Interpolated.
BoundaryType string
// MaxCount is the most values returned (the API's default is 1000).
MaxCount int
// FilterExpression keeps the values for which it is true; with
// IncludeFilteredValues the others are returned marked as filtered.
FilterExpression string
IncludeFilteredValues bool
Common
}
RecordedOptions is a recorded read.
type StreamSummaries ¶
type StreamSummaries struct {
WebID string `json:"WebId"`
Name string `json:"Name"`
Path string `json:"Path"`
Items []Summary `json:"Items"`
Exception *webException `json:"WebException,omitempty"`
}
StreamSummaries is one stream's summaries in a stream set answer.
func (StreamSummaries) Err ¶
func (s StreamSummaries) Err() error
Err is the stream's failure, nil when it was read.
type StreamUpdate ¶
type StreamUpdate struct {
WebID string `json:"WebId"`
Value TimedValue `json:"Value"`
}
StreamUpdate is one stream's value in a stream set write.
type StreamUpdates ¶
type StreamUpdates struct {
Source string `json:"Source"`
SourceName string `json:"SourceName,omitempty"`
SourcePath string `json:"SourcePath,omitempty"`
Status string `json:"Status,omitempty"`
Marker string `json:"LatestMarker"`
Events []UpdateEvent `json:"Events,omitempty"`
Exception *webException `json:"Exception,omitempty"`
// RequestedMarker is the marker the read was for.
RequestedMarker string `json:"RequestedMarker,omitempty"`
}
StreamUpdates is a registration for, or a read of, a stream's changes (stream updates, PI Web API 2019 SP1 and later): Marker is passed to the next read; Events are the values added, changed or removed since the last marker, with their Action.
func (StreamUpdates) Err ¶
func (u StreamUpdates) Err() error
Err is the registration's or read's failure, nil when it succeeded.
type StreamValue ¶
type StreamValue struct {
WebID string `json:"WebId"`
Name string `json:"Name"`
Path string `json:"Path"`
Value Value `json:"Value"`
Units string `json:"UnitsAbbreviation,omitempty"`
Exception *webException `json:"WebException,omitempty"`
}
StreamValue is one stream's value in a stream set answer. Err is set when that stream could not be read.
func (StreamValue) Err ¶
func (s StreamValue) Err() error
Err is the stream's failure, nil when it was read.
type StreamValues ¶
type StreamValues struct {
WebID string `json:"WebId"`
Name string `json:"Name"`
Path string `json:"Path"`
Items []Value `json:"Items"`
Units string `json:"UnitsAbbreviation,omitempty"`
Exception *webException `json:"WebException,omitempty"`
}
StreamValues is one stream's values in a stream set answer.
func (StreamValues) Err ¶
func (s StreamValues) Err() error
Err is the stream's failure, nil when it was read.
type StreamValuesUpdate ¶
type StreamValuesUpdate struct {
WebID string `json:"WebId"`
Items []TimedValue `json:"Items"`
}
StreamValuesUpdate is one stream's values in a stream set write.
type Streams ¶
type Streams struct {
WebIDs []string
Of string
NameFilter string
CategoryName string
TemplateName string
SearchFullHierarchy bool
ShowExcluded bool
ShowHidden bool
// SortField and SortOrder order the streams (Name; Ascending or
// Descending).
SortField, SortOrder string
}
Streams names the streams of a stream set read: WebIDs (an ad hoc set of points or attributes, streamsets/...?webId=) or Of, an element or event frame whose attributes are read (streamsets/{webId}/...), with the attribute filters that go with Of.
type SummaryOptions ¶
type SummaryOptions struct {
StartTime, EndTime string
// SummaryTypes are SummaryTotal... (the API's default is Total).
SummaryTypes []string
// CalculationBasis is CalculationTimeWeighted (default) or
// CalculationEventWeighted.
CalculationBasis string
// TimeType is Auto, EarliestTime, MostRecentTime.
TimeType string
// SummaryDuration splits the range into intervals ("1h").
SummaryDuration string
// SampleType is ExpressionRecordedValues or Interval; SampleInterval
// goes with Interval.
SampleType, SampleInterval string
FilterExpression string
Common
}
SummaryOptions is a summary read.
type System ¶
type System struct {
ProductTitle string `json:"ProductTitle"`
ProductVersion string `json:"ProductVersion"`
}
System is the PI Web API's own description (GET system).
type SystemStatus ¶
type SystemStatus struct {
UpTimeInMinutes float64 `json:"UpTimeInMinutes"`
State string `json:"State"`
CacheInstances int `json:"CacheInstances"`
ServerTime string `json:"ServerTime,omitempty"`
}
SystemStatus is the PI Web API's state (GET system/status).
type TimedValue ¶
type TimedValue struct {
Timestamp string `json:"Timestamp,omitempty"`
Value any `json:"Value"`
Units string `json:"UnitsAbbreviation,omitempty"`
Good *bool `json:"Good,omitempty"`
Questionable *bool `json:"Questionable,omitempty"`
}
TimedValue is a value to write. Timestamp is an absolute time or a PI time expression; empty means now (the server's clock). Value is a number, text, a boolean, or a digital state by name (DigitalState{Name: "Running"}) or by its code.
type UpdateEvent ¶
UpdateEvent is one change of a stream: a value and its action (Add, Update, Remove...).
type UpdateOptions ¶
UpdateOptions is a write's update and buffer options (empty: the API's defaults, Replace and BufferIfPossible).
type UserInfo ¶
type UserInfo struct {
IdentityType string `json:"IdentityType"`
Name string `json:"Name"`
IsAuthenticated bool `json:"IsAuthenticated"`
SID string `json:"SID,omitempty"`
ImpersonationLevel string `json:"ImpersonationLevel,omitempty"`
}
UserInfo is who the PI Web API takes the caller to be (GET system/userinfo): the way to check a login, and with Kerberos whether the server may act on the user's behalf (ImpersonationLevel Delegation is needed for a double hop to the Data Archive).
type Value ¶
type Value struct {
Timestamp time.Time `json:"Timestamp"`
Value json.RawMessage `json:"Value"`
Units string `json:"UnitsAbbreviation"`
Good *bool `json:"Good"`
Questionable bool `json:"Questionable"`
Substituted bool `json:"Substituted"`
Annotated bool `json:"Annotated,omitempty"`
// Errors is set on a value the PI Web API could not read.
Errors []string `json:"Errors,omitempty"`
}
Value is one value of a stream.
func (Value) Decode ¶
Decode reads a value: a number, text, a boolean, or a digital state {Name, Value, IsSystem} as its name. The quality is a comma-separated list of bad, questionable, substituted, system and unreadable; empty when good.
Example ¶
Decode a value as the PI Web API returns it.
package main
import (
"encoding/json"
"fmt"
"github.com/cB-Sigma/piwebapi"
)
func main() {
var v piwebapi.Value
_ = json.Unmarshal([]byte(`{"Timestamp":"2026-10-06T08:01:00Z","Value":{"Name":"I/O Timeout","Value":246,"IsSystem":true},"Good":false}`), &v)
x, quality := v.Decode()
fmt.Println(x, quality)
}
Output: I/O Timeout bad,system
func (Value) IsGood ¶
IsGood reports whether the value is good: Good is true or absent and it is not a system state.
func (Value) State ¶
func (v Value) State() (DigitalState, bool)
State reads the value as a digital state; ok is false for other values.
type ValueOptions ¶
ValueOptions is a value read: the current value, or the value at Time.
type WebIDInfo ¶
type WebIDInfo struct {
Type byte // WebIDFull...
Version int // 1 for WebID 2.0
Marker string // MarkerPoint...
Owner string // OwnerElement... for attributes, else empty
// Path is the object's path (with its leading \\) for a path-only
// WebId, else empty.
Path string
}
WebIDInfo is what a WebId's header says.
func ParseWebID ¶
ParseWebID reads a WebId's type, version, marker and owner, and the path of a path-only WebId.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package negotiate logs in to a Kerberos V5 realm (RFC 4120) and makes HTTP Negotiate (SPNEGO, RFC 4559) Authorization headers, for an HTTP service that wants Windows integrated login such as a PI Web API hosted in IIS.
|
Package negotiate logs in to a Kerberos V5 realm (RFC 4120) and makes HTTP Negotiate (SPNEGO, RFC 4559) Authorization headers, for an HTTP service that wants Windows integrated login such as a PI Web API hosted in IIS. |