piwebapi

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

README

piwebapi

A client for the AVEVA PI Web API (formerly OSIsoft) in pure Go, with Kerberos login that works from settings alone; not affiliated with AVEVA.

Go Reference test Go

It reads and writes time-series data in a PI System through the PI Web API: points and Asset Framework objects (servers, databases, elements, attributes, event frames), every stream read (value, end, recorded with paging and backfill, interpolated, at times, plot, summary), value and values updates with partial failures reported per item, stream sets of many streams in one call, stream updates (polling by marker), batch requests, and WebID 2.0 helpers. Logins are Basic, Bearer, or Kerberos (HTTP Negotiate) through gokrb5, configured from krb5.conf text and a keytab or password, with nothing read from disk. The root package uses the Go standard library only; no cgo. It was written for SigmaM2M, a oneM2M platform, whose historian adapter is built on it.

Why it exists: the Go PI Web API clients found (gowebapi and its forks, generated from a 2018 API description) are unmaintained and have no Kerberos login, which many PI Web API servers require.

Support matrix

Every PI Web API action this module calls, by controller. "Not yet" rows say why. Other GET actions can be made with Client.Get, and any other action with Client.Do (which sends the CSRF header for writes).

Controller and action Method Status
Home, System: system, system/userinfo (login and delegation check), system/versions, system/status System, UserInfo, Versions, Status yes
DataServer: list, by name, by path, by WebId DataServers, DataServerByName, DataServerByPath, DataServer yes
DataServer: points by name filter, paged by startIndex and maxCount Points, PointPages yes
Point: by path, by WebId, several by path (points/multiple), point attributes PointByPath, Point, PointsByPath, PointAttributes yes
AssetServer: list, by name, by path, by WebId, its databases AssetServers, AssetServerByName, AssetServerByPath, AssetServer, AssetDatabases yes
AssetDatabase: by path, by WebId, elements (filters, full hierarchy, paging, sort), event frames AssetDatabaseByPath, AssetDatabase, Elements, EventFrames yes
Element: by path, by WebId, several by path, child elements, attributes, event frames that reference it ElementByPath, Element, ElementsByPath, ChildElements, Attributes, ElementEventFrames yes
Attribute: by path, by WebId, several by path, child attributes, value (GET; PUT for static values) AttributeByPath, Attribute, AttributesByPath, ChildAttributes, AttributeValue, SetAttributeValue yes
EventFrame: search (every search mode, time range, name, referenced element, template, category, severity, acknowledgement, paging), by path, by WebId, children, attributes EventFrames, EventFrameByPath, EventFrame, ChildEventFrames, EventFrameAttributes yes
Stream: value (snapshot or at a time), end Value, End yes
Stream: recorded (boundary type, maxCount, filter expression, filtered values), with backfill paging Recorded, RecordedWith, RecordedPages yes
Stream: interpolated (interval as PI time span, sync time), interpolated at times, plot Interpolated, InterpolatedWith, InterpolatedAtTimes, Plot yes
Stream: recorded at time and at times (every retrieval mode) RecordedAtTime, RecordedAtTimes yes
Stream: summary (every summary type, time- or event-weighted, per duration, sampling) Summary yes
Stream: update value, update values (update and buffer options; 202, 204, 207 with per-item substatus) UpdateValue, UpdateValues yes
Stream updates: register, read by marker; for one stream and for a stream set RegisterUpdates, Updates, RegisterStreamSetUpdates, StreamSetUpdates yes
StreamSet, ad hoc (webId= list) and of an element or event frame (streamsets/{webId}): value, end, recorded, interpolated, interpolated at times, plot, summary, recorded at time and times; per-stream failures (WebException) StreamSet* with Streams yes
StreamSet: update value and values, ad hoc (207 per stream and per value) StreamSetUpdateValue, StreamSetUpdateValues yes
StreamSet: update value and values of an element (POST streamsets/{webId}/...) Not yet: the ad hoc writes take the attributes' WebIds and do the same
Batch: requests with parent IDs, JSONPath parameters, request templates; 207 Batch, BatchGet, BatchPost, BatchResponse yes
Common parameters: selectedFields, webIdType, timeZone, desiredUnits, any other through Extra Common yes
WebID 2.0: read a WebId's type, marker, owner and path; build path-only WebIds ParseWebID, PathWebID, PointWebID, AttributeWebID yes (header and path-only payloads; full WebIds' GUIDs are not decoded)
Values: numbers, text, booleans, digital and system states; Good, Questionable, Substituted, Annotated, per-value Errors Value.Decode, State, Float, IsGood yes
Errors: {"Errors": [...]} bodies, 401/403 (AuthError, with the offered schemes and an NTLM hint), 404 (IsNotFound), 408/429/5xx (Temporary, RetryAfter), timeouts through the context Error, AuthError, PartialError yes
Logins: Basic, Bearer, Kerberos with a password or keytab (negotiate) Basic, Bearer, negotiate.Service yes
CSRF defence: X-Requested-With on POST, PUT, PATCH, DELETE (batch included) Client.RequestedWith yes
Channels (streams/{webId}/channel, streamsets/channel) Not yet: they are WebSockets; the standard library has no WebSocket client and this module keeps its dependencies to gokrb5. Stream updates give the same changes by polling
Calculation (calculation/...), indexed Search (search/query), elements/search and attribute searches Not yet: not needed by the module's first user; reachable with Get
Configuration changes: create, update or delete points, elements, attributes, event frames, databases; security entries; tables; enumeration sets; analyses; notifications; OMF Not yet: this module reads and writes data, not configuration; reachable with Do
NTLM No: it is not a login method the PI Web API documents. When a Windows host answers Negotiate with NTLM (no service principal for the name asked), AuthError.NTLM says so
Paging links (Links.Next) Not read: list reads page by startIndex and maxCount; recorded reads have no next link and page by timestamp

Limits worth knowing:

  • Recorded, Interpolated and RecordedPages keep their v0 signatures (absolute times; the interval in whole seconds). The ...With forms take PI time expressions and time spans as text.
  • RecordedPages resumes at the last timestamp of a full page and drops the values already read there. When page or more values share one instant, the values beyond the page at that instant are skipped.
  • Times are sent in UTC with seven fractional digits (100 ns); a time without a zone would be read in the server's own zone.
  • The PI Web API caps one call's items (MaxReturnedItemsPerCall); a read above the cap fails with 400. Page or narrow such reads.

Install

go get github.com/cB-Sigma/piwebapi@latest

Requires Go 1.26 or later.

Quick start

import (
	"github.com/cB-Sigma/piwebapi"
	"github.com/cB-Sigma/piwebapi/negotiate"
)

k, err := negotiate.New(negotiate.Config{Realm: "PLANT.EXAMPLE", KDCs: []string{"dc1.plant.example"},
	Username: "svc-reader", Password: password})
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`)
err = c.RecordedPages(ctx, pt.WebID, since, time.Now(), 1000, func(v piwebapi.Values) error {
	for _, x := range v.Items {
		val, quality := x.Decode() // quality: "", or bad, questionable, substituted, system
		_ = val
	}
	return nil
})

// Many attributes in one call, and a write.
el, err := c.ElementByPath(ctx, `\\PIAF01\Plant\Area1\Boiler1`)
vals, err := c.StreamSetValue(ctx, piwebapi.Streams{Of: el.WebID}, piwebapi.ValueOptions{})
err = c.UpdateValue(ctx, pt.WebID, piwebapi.TimedValue{Value: 181.5}, piwebapi.UpdateOptions{})

Example in example_test.go shows the Kerberos flow (it needs a server, so it is not run); ExampleValue_Decode and ExamplePointWebID run. piwebapi-sim runs the same calls against a simulated PI Web API and a test KDC.

Documentation

API reference: https://pkg.go.dev/github.com/cB-Sigma/piwebapi

Package What it does
piwebapi (module root) Client (Get, Do, URL, and the methods in the matrix above), the value, object and option types, Time, Tick, Authorizer with Basic and Bearer, ErrAuth, AuthError, Error, PartialError, IsNotFound, WebID 2.0 helpers. Standard library only
negotiate Kerberos V5 login and SPNEGO Authorization: Negotiate headers through gokrb5: krb5.conf text parsed in memory, keytab bytes or base64, AES and TCP by default, ErrLogin for a refused login, Problem naming the bad setting, re-login when a session fails; hooks CheckKDC (egress rules) and WeakEtype (crypto policy); SPNFor, Client.For(spn)

Changes per version are in CHANGELOG.md.

Testing

go test -race ./...

The tests here check the requests the client sends for every action (method, path, query, headers, body) and how it reads canned answers: 207 partial failures, batch responses, per-stream exceptions, refusals, server errors with Retry-After, timeouts, WebIds, paging. The tests that drive a PI Web API, against the simulator and the test KDC, are in piwebapi-sim.

Interop tested against
  • Not yet: a real PI Web API. None was available; the request shapes come from AVEVA's public PI Web API reference and from the public client generated from its 2018 API description (OSIsoft's PI-Web-API-Client-Python, read for parameter and field names only). Stream updates and the Annotated flag are newer than that client and come from the reference alone.
  • The simulator in piwebapi-sim and this client have the same author, so their agreement is not independent evidence.
  • Kerberos: the login and SPNEGO tokens are gokrb5's. They are tested against piwebapi-sim's test KDC (written from RFC 4120 on gokrb5's message types) and a service that checks tickets with gokrb5's acceptor; not yet against Active Directory or an IIS-hosted PI Web API.
  • piwebapi-sim: a simulated PI Web API and a test Kerberos KDC, as Go packages and a command.

Status

v0.x: the API may change before v1.

Contributing

See CONTRIBUTING.md.

Security

See SECURITY.md to report a vulnerability privately.

Licence

Apache-2.0 (see LICENSE and NOTICE). Copyright 2026 Abhinav Gautam. AVEVA, OSIsoft, PI System and PI Web API are trademarks of their owners; the names are used only to say which product this module talks to.

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)
	}
}

Index

Examples

Constants

View Source
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.

View Source
const (
	BoundaryInside       = "Inside"
	BoundaryOutside      = "Outside"
	BoundaryInterpolated = "Interpolated"
)

Boundary types of a recorded read.

View Source
const (
	RetrieveAuto       = "Auto"
	RetrieveAtOrBefore = "AtOrBefore"
	RetrieveBefore     = "Before"
	RetrieveAtOrAfter  = "AtOrAfter"
	RetrieveAfter      = "After"
	RetrieveExact      = "Exact"
)

Retrieval modes of a recorded-at-time read.

View Source
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.

View Source
const (
	BufferDoNotBuffer      = "DoNotBuffer"
	BufferBufferIfPossible = "BufferIfPossible"
	BufferBuffer           = "Buffer"
)

Buffer options of a write.

View Source
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.

View Source
const (
	WebIDFull          = 'F'
	WebIDIDOnly        = 'I'
	WebIDPathOnly      = 'P'
	WebIDLocalIDOnly   = 'L'
	WebIDDefaultIDOnly = 'D'
)

WebID types (the first letter).

View Source
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.

View Source
const (
	OwnerElement    = "E"
	OwnerEventFrame = "F"
)

Owner markers of an attribute's WebId.

View Source
const Tick = 100 * time.Nanosecond

Tick is the PI time resolution.

Variables

View Source
var ErrAuth = errors.New("the PI Web API refused the login")

ErrAuth is a login the PI Web API refused; an *AuthError matches it.

View Source
var ErrWebID = errors.New("piwebapi: not a WebID 2.0")

ErrWebID is a WebId this client cannot read.

Functions

func AttributeWebID

func AttributeWebID(path string) string

AttributeWebID is the path-only WebId of an element's attribute (\\AFSERVER\DB\Element|Attribute).

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is a 404 answer.

func PathWebID

func PathWebID(marker, owner, path string) string

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

func PointWebID(path string) string

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

func Time

func Time(t time.Time) string

Time is the absolute time form the client sends: UTC with seven fractional digits, the PI time resolution of 100 ns. A time without a zone would be read in the server's own time zone, so the zone is always sent.

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).

func (*AuthError) Error

func (e *AuthError) Error() string

func (*AuthError) Is

func (e *AuthError) Is(target error) bool

Is makes errors.Is(err, ErrAuth) true.

type Authorizer

type Authorizer interface {
	Authorize(ctx context.Context, r *http.Request) error
}

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 Basic

type Basic struct{ User, Password string }

Basic is HTTP basic authentication.

func (Basic) Authorize

func (b Basic) Authorize(_ context.Context, r *http.Request) error

Authorize sets r's basic authentication.

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 Bearer

type Bearer string

Bearer is a bearer token (OpenID Connect).

func (Bearer) Authorize

func (b Bearer) Authorize(_ context.Context, r *http.Request) error

Authorize sets r's Authorization: Bearer header.

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

func (c *Client) AssetDatabase(ctx context.Context, webID string) (AssetDatabase, error)

AssetDatabase reads an AF database by WebId. GET assetdatabases/{webId}.

func (*Client) AssetDatabaseByPath

func (c *Client) AssetDatabaseByPath(ctx context.Context, path string) (AssetDatabase, error)

AssetDatabaseByPath finds an AF database by path (\\AFSERVER\DB). GET assetdatabases?path=.

func (*Client) AssetDatabases

func (c *Client) AssetDatabases(ctx context.Context, serverWebID string) ([]AssetDatabase, error)

AssetDatabases lists an AF server's databases. GET assetservers/{webId}/assetdatabases.

func (*Client) AssetServer

func (c *Client) AssetServer(ctx context.Context, webID string) (AssetServer, error)

AssetServer reads an AF server by WebId. GET assetservers/{webId}.

func (*Client) AssetServerByName

func (c *Client) AssetServerByName(ctx context.Context, name string) (AssetServer, error)

AssetServerByName finds an AF server by name. GET assetservers?name=.

func (*Client) AssetServerByPath

func (c *Client) AssetServerByPath(ctx context.Context, path string) (AssetServer, error)

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) Attribute

func (c *Client) Attribute(ctx context.Context, webID string) (Attribute, error)

Attribute reads an attribute by WebId. GET attributes/{webId}.

func (*Client) AttributeByPath

func (c *Client) AttributeByPath(ctx context.Context, path string) (Attribute, error)

AttributeByPath finds an attribute by path (\\AFSERVER\DB\Plant\Boiler1|Temperature). GET attributes?path=.

func (*Client) AttributeValue

func (c *Client) AttributeValue(ctx context.Context, webID string) (Value, error)

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

func (c *Client) AttributesByPath(ctx context.Context, paths []string) ([]Found[Attribute], error)

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) BatchGet

func (c *Client) BatchGet(path string, q url.Values, parents ...string) BatchRequest

BatchGet is a GET request of a batch for path with query q.

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

func (c *Client) DataServer(ctx context.Context, webID string) (DataServer, error)

DataServer reads a Data Archive by WebId. GET dataservers/{webId}.

func (*Client) DataServerByName

func (c *Client) DataServerByName(ctx context.Context, name string) (DataServer, error)

DataServerByName finds a Data Archive by name. GET dataservers?name=.

func (*Client) DataServerByPath

func (c *Client) DataServerByPath(ctx context.Context, path string) (DataServer, error)

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

func (c *Client) Do(ctx context.Context, method, path string, q url.Values, body, out any) error

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) Element

func (c *Client) Element(ctx context.Context, webID string) (Element, error)

Element reads an element by WebId. GET elements/{webId}.

func (*Client) ElementByPath

func (c *Client) ElementByPath(ctx context.Context, path string) (Element, error)

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

func (c *Client) ElementsByPath(ctx context.Context, paths []string) ([]Found[Element], error)

ElementsByPath looks up several elements by path in one request. GET elements/multiple.

func (*Client) End

func (c *Client) End(ctx context.Context, webID string, o Common) (Value, error)

End reads a stream's last archived value. streams/{webId}/end.

func (*Client) EventFrame

func (c *Client) EventFrame(ctx context.Context, webID string) (EventFrame, error)

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

func (c *Client) EventFrameByPath(ctx context.Context, path string) (EventFrame, error)

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

func (c *Client) Get(ctx context.Context, path string, q url.Values, out any) error

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) Plot

func (c *Client) Plot(ctx context.Context, webID string, o PlotOptions) (Values, error)

Plot reads the values that draw a stream. streams/{webId}/plot.

func (*Client) Point

func (c *Client) Point(ctx context.Context, webID string) (Point, error)

Point reads a PI point by WebId. GET points/{webId}.

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

func (c *Client) PointByPath(ctx context.Context, path string) (Point, error)

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

func (c *Client) PointsByPath(ctx context.Context, paths []string) ([]Found[Point], error)

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

func (c *Client) RecordedWith(ctx context.Context, webID string, o RecordedOptions) (Values, error)

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

func (c *Client) RegisterUpdates(ctx context.Context, webID string) (StreamUpdates, error)

RegisterUpdates registers for a stream's changes and returns the first marker. POST streams/{webId}/updates.

func (*Client) SetAttributeValue

func (c *Client) SetAttributeValue(ctx context.Context, webID string, v TimedValue) error

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

func (c *Client) StreamSetEnd(ctx context.Context, s Streams, o Common) ([]StreamValue, error)

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

func (c *Client) Summary(ctx context.Context, webID string, o SummaryOptions) ([]Summary, error)

Summary reads a stream's summaries (totals, averages...). streams/{webId}/summary.

func (*Client) System

func (c *Client) System(ctx context.Context) (System, error)

System reads the PI Web API's product name and version. GET system.

func (*Client) URL

func (c *Client) URL(path string, q url.Values) string

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

func (c *Client) Updates(ctx context.Context, marker string, o Common) (StreamUpdates, error)

Updates reads the changes since marker and the next marker. GET streams/updates/{marker}.

func (*Client) UserInfo

func (c *Client) UserInfo(ctx context.Context) (UserInfo, error)

UserInfo reads who the PI Web API takes the caller to be. GET system/userinfo.

func (*Client) Value

func (c *Client) Value(ctx context.Context, webID string, o ValueOptions) (Value, error)

Value reads a stream's current value (the snapshot), or its value at o.Time (interpolated, or the value before for step points). streams/{webId}/value.

func (*Client) Versions

func (c *Client) Versions(ctx context.Context) (map[string]any, error)

Versions reads the versions of the PI Web API's components, by name. GET system/versions.

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

type Error struct {
	Status     int
	Path       string
	Message    string
	RetryAfter time.Duration
}

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.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Temporary

func (e *Error) Temporary() bool

Temporary reports whether the request may succeed when repeated: a timeout (408), throttling (429) or a server-side failure (5xx).

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

type Found[T any] struct {
	Identifier     string
	IdentifierType string
	Object         T
	Err            error
}

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

type ItemError struct {
	Index   int
	Sub     int
	WebID   string
	Status  int
	Message string
}

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

type PlotOptions struct {
	StartTime, EndTime string
	Intervals          int
	Common
}

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

type PointAttribute struct {
	Name  string `json:"Name"`
	Value any    `json:"Value"`
}

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 Summary

type Summary struct {
	Type  string `json:"Type"`
	Value Value  `json:"Value"`
}

Summary is one summary value of a stream.

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

type UpdateEvent struct {
	Value
	Action string `json:"Action"`
}

UpdateEvent is one change of a stream: a value and its action (Add, Update, Remove...).

type UpdateOptions

type UpdateOptions struct {
	UpdateOption string
	BufferOption string
}

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

func (v Value) Decode() (any, string)

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) Float

func (v Value) Float() (float64, bool)

Float reads the value as a number; ok is false for other values.

func (Value) IsGood

func (v Value) IsGood() bool

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

type ValueOptions struct {
	Time string
	Common
}

ValueOptions is a value read: the current value, or the value at Time.

type Values

type Values struct {
	Items []Value `json:"Items"`
	Units string  `json:"UnitsAbbreviation"`
}

Values is a stream read's answer.

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

func ParseWebID(id string) (WebIDInfo, error)

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL