profile

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package profile holds the declarative device profiles (spec 4): schema, loader for built-in and local profiles, validation, decoder and status maps. Everything vendor-specific lives in the YAML; this package only interprets it.

Index

Constants

View Source
const (
	TransportModbus = "modbus"
	TransportHTTP   = "http"
)

Transports.

View Source
const (
	ReadRange  = "range"
	ReadDirect = "direct"
)

Read modes (spec 4.3).

View Source
const (
	RolePV       = "pv"
	RoleGrid     = "grid"
	RoleBattery  = "battery"
	RoleConsumer = "consumer"
	RoleBackup   = "backup"
	RoleInverter = "inverter"
	RolePhase    = "phase"
)

Roles of blocks (spec 2 and the follow-up table of 4.2).

View Source
const (
	CounterNone       = ""
	CounterLifetime   = "lifetime"
	CounterDailyReset = "daily_reset"
)

Counter kinds (spec 5.3).

View Source
const (
	LevelOK     = "ok"
	LevelNotice = "notice"
	LevelFault  = "fault"
)

Status levels.

View Source
const DefaultMaxRegisters = 125

DefaultMaxRegisters is the Modbus limit per request unless the profile lowers it.

Variables

View Source
var ErrMissing = errors.New("value missing")

ErrMissing marks a value absent from the raw data.

View Source
var ErrUnknownProfile = errors.New("unknown profile")

ErrUnknownProfile is returned for a reference that is neither a path nor a built-in ID.

View Source
var IDPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*/[a-z0-9][a-z0-9-]*$`)

IDPattern is the pattern of built-in profile IDs (<vendor>/<model>, lower case).

Functions

func Categories

func Categories() []string

Categories returns the consumer categories (spec 2).

func ChannelRef

func ChannelRef(ref string) (block, channel string, ok bool)

ChannelRef splits "block.channel".

func IsPath

func IsPath(ref string) bool

IsPath reports whether a profile reference names a local file (ends in .yaml/.yml).

func Languages

func Languages() []string

Languages every text must provide.

func Lookup

func Lookup(doc any, path string) (any, bool)

Lookup evaluates a JSONPath of the supported subset ($.a.b[0].c) on decoded JSON.

func NormalUnit

func NormalUnit(u string) string

energyUnits maps energy units to their factor in Wh. NormalUnit is the unit of a channel after decoding: energy in Wh, power in W.

func Roles

func Roles() []string

Roles returns every block role.

func ValidPath

func ValidPath(s string) bool

ValidPath reports whether s is in the supported JSONPath subset ($.a.b[0].c).

func Validate

func Validate(p *Profile) []string

Validate checks a profile completely and returns every problem with its path.

Types

type Addrs

type Addrs []int

Addrs is one register address or a list of them (status bitfields over several words).

func (*Addrs) UnmarshalYAML

func (a *Addrs) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML accepts a scalar or a sequence of addresses.

type Block

type Block struct {
	Role         string             `yaml:"role"`
	RolesAllowed []string           `yaml:"roles_allowed"`
	Category     string             `yaml:"category"`
	Channels     map[string]Channel `yaml:"channels"`
}

Block is one meter the device can provide.

func (Block) Allows

func (b Block) Allows(role string) bool

Allows reports whether the block may be used with role.

type Channel

type Channel struct {
	Field       `yaml:",inline"`
	Sum         []string       `yaml:"sum"`
	Product     []string       `yaml:"product"`
	ValueID     *ValueID       `yaml:"value_id"`
	Derive      string         `yaml:"derive"`
	Of          string         `yaml:"of"`
	By          string         `yaml:"by"`
	Scale       *float64       `yaml:"scale"`
	Offset      float64        `yaml:"offset"`
	Invert      bool           `yaml:"invert"`
	SignFrom    *SignFrom      `yaml:"sign_from"`
	Unit        string         `yaml:"unit"`
	Counter     string         `yaml:"counter"`
	ResetGroup  string         `yaml:"reset_group"`
	Resolution  float64        `yaml:"resolution"`
	History     *bool          `yaml:"history"`
	Values      map[int]string `yaml:"values"` // type enum: code → state name
	RenamedFrom string         `yaml:"renamed_from"`
}

Channel is one normalised quantity of a block.

func (Channel) Historised

func (c Channel) Historised(name string) bool

Historised reports whether the channel is stored by default (spec 7.2): power, soc and energy channels unless history: false; others only with history: true.

func (Channel) IsEnergy

func (c Channel) IsEnergy() bool

IsEnergy reports whether the channel is an energy counter, an integrated energy channel or a share of one.

func (Channel) ScaleOr1

func (c Channel) ScaleOr1() float64

ScaleOr1 returns the scale, 1 when unset.

type Endpoint

type Endpoint struct {
	ID       string   `yaml:"id"`
	URL      string   `yaml:"url"`
	Interval Interval `yaml:"interval"`
}

Endpoint is one GET URL; Interval > 0 polls it less often than the device.

type Field

type Field struct {
	Endpoint string `yaml:"endpoint"`
	Path     string `yaml:"path"`
	Addr     Addrs  `yaml:"addr"`
	Type     string `yaml:"type"`
	Length   int    `yaml:"length"` // registers of a string
}

Field locates one raw value: a Modbus address or a JSON path, plus its type.

func (Field) Width

func (f Field) Width() int

Width returns the number of registers a Modbus field spans per address.

type Fixture

type Fixture struct {
	Profile  string    `json:"profile"`
	Version  int       `json:"version"`            // profile version the fixture was made with
	Source   string    `json:"source"`             // dump | documentation
	Interval string    `json:"interval,omitempty"` // poll interval of a dump
	Samples  []Sample  `json:"samples"`
	Created  time.Time `json:"created,omitzero"`
}

Fixture is a recorded or documentation-based sequence of raw polls of one device. It is the output format of "pvmon dump" and the input of golden and replay tests.

type Golden

type Golden struct {
	Samples []GoldenSample `json:"samples"`
}

Golden holds the expected normalised values per sample of a fixture: channels as "block.channel" → value (numbers, or strings for enum/string channels) and status as name → level.

type GoldenSample

type GoldenSample struct {
	Channels map[string]any    `json:"channels"`
	Status   map[string]string `json:"status"`
}

GoldenSample is the expectation for one sample.

type HTTPOptions

type HTTPOptions struct {
	Auth      string     `yaml:"auth"` // "" | basic | digest
	Endpoints []Endpoint `yaml:"endpoints"`
}

HTTPOptions lists the endpoints of an HTTP device.

type Interval

type Interval time.Duration

Interval is a Go duration string in a profile ("1h").

func (*Interval) UnmarshalYAML

func (i *Interval) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML parses a duration string.

type Loaded

type Loaded struct {
	*Profile
	Path      string
	Overrides bool // a local file replacing the built-in profile with the same ID
}

Loaded is a profile resolved for a device. Path is empty for built-in profiles.

type Loader

type Loader struct {
	// contains filtered or unexported fields
}

Loader resolves profile references: built-in IDs from the embedded set, or local files by path (spec 4.5). It holds no cache of local files; they are read on every Load.

func NewLoader

func NewLoader(builtin fs.FS, readFile func(string) ([]byte, error)) (*Loader, error)

NewLoader parses every built-in profile; any invalid or duplicate one is an error.

func (*Loader) IDs

func (l *Loader) IDs() []string

IDs returns the sorted built-in profile IDs.

func (*Loader) Load

func (l *Loader) Load(ref, baseDir string) (*Loaded, error)

Load resolves ref; relative paths are resolved against baseDir. An unreadable or invalid local file is an error, never a fallback to the built-in profile.

func (*Loader) LoadFile

func (l *Loader) LoadFile(path string) (*Profile, error)

LoadFile reads and validates one local profile file.

type Map

type Map struct {
	Default *MapEntry
	Codes   map[uint64]MapEntry
	Bits    map[int]MapEntry
}

Map is a status map: codes (or bits for bitfields) plus an optional default.

func (*Map) UnmarshalYAML

func (m *Map) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML reads "default", "bits" and numeric code keys (decimal or 0x hex).

type MapEntry

type MapEntry struct {
	Level string `yaml:"level"`
	Text  Text   `yaml:"text"`
}

MapEntry is one code or bit of a status map.

type ModbusOptions

type ModbusOptions struct {
	Function  string `yaml:"function"`   // input (04) | holding (03)
	ByteOrder string `yaml:"byte_order"` // big | little
	WordOrder string `yaml:"word_order"` // big | little
}

ModbusOptions selects function code and byte/word order.

type Needs

type Needs map[string]map[string]bool

Needs is the set of channels one poll of a device has to decode: block → channel names. A nil Needs means everything the profile describes (dumps, fixtures).

func (Needs) Blocks

func (n Needs) Blocks() []string

Blocks returns the blocks with at least one needed channel, sorted.

func (Needs) Has

func (n Needs) Has(block, channel string) bool

Has reports whether the channel is needed; a nil Needs needs every channel.

type ProblemsError

type ProblemsError struct {
	Profile  string
	Problems []string
}

ProblemsError lists every problem of a profile, each prefixed with its path.

func (*ProblemsError) Error

func (e *ProblemsError) Error() string

type Profile

type Profile struct {
	Schema    int               `yaml:"schema"`
	ID        string            `yaml:"profile"`
	Version   int               `yaml:"version"`
	Vendor    string            `yaml:"vendor"`
	Models    []string          `yaml:"models"`
	Transport string            `yaml:"transport"`
	Verified  bool              `yaml:"verified"`
	Modbus    *ModbusOptions    `yaml:"modbus"`
	Read      *ReadOptions      `yaml:"read"`
	HTTP      *HTTPOptions      `yaml:"http"`
	MaxPower  float64           `yaml:"max_power"`
	Netting   string            `yaml:"netting"`
	Blocks    map[string]Block  `yaml:"blocks"`
	Status    map[string]Status `yaml:"status"`
	Maps      map[string]Map    `yaml:"maps"`
}

Profile is one parsed device profile (spec 4.2).

func Parse

func Parse(data []byte) (*Profile, error)

Parse decodes a profile strictly (unknown keys are errors) and validates it.

func (*Profile) Channels

func (p *Profile) Channels(block string, raw Raw) map[string]Value

Channels decodes and normalises every channel of a block. Derive (share) channels are left out: they are computed from energy deltas by the collector.

func (*Profile) DescribeStatus

func (p *Profile) DescribeStatus(name string, code uint64) StatusValue

DescribeStatus evaluates a stored code of the status entry name (level and texts); an unknown name is invalid.

func (*Profile) Encode

func (p *Profile) Encode(values map[string]float64) (Sample, error)

Encode builds raw poll data from normalised channel values keyed "block.channel"; it is the inverse of the decoder for simulations and tests. Only channels with a value are written (blocks may share registers, e.g. one meter seen as grid or as pv); registers of the profile without a value stay 0. Composite channels (product, derive) are skipped, a sum is written to its first path and value_id channels get matching ID and value arrays.

func (*Profile) Endpoints

func (p *Profile) Endpoints(n Needs, due func(Endpoint) bool) []Endpoint

Endpoints returns the HTTP endpoints a poll with the given needs (nil: everything) reads; slow endpoints (Interval > 0) are included only when due reports true for them.

func (*Profile) NeedsFor

func (p *Profile) NeedsFor(blocks []string) Needs

NeedsFor returns the channels the given blocks need: all their channels, the inputs of product channels and, for a share channel, the shared counter and the weight channel of every block sharing it (a split is only right with all weights).

func (*Profile) Requests

func (p *Profile) Requests(mode string, n Needs) []Request

Requests returns the Modbus reads of one poll for the given read mode and needs. Range mode reads, within each profile range, only the spans holding needed registers, joining spans less than mergeGap apart; direct mode reads each needed field on its own (spec 4.3). Nil needs read everything the profile describes (whole ranges), as for dumps.

func (*Profile) Sharers

func (p *Profile) Sharers(of string) [][2]string

Sharers returns block and weight channel of every share channel that splits the counter "of" (block.channel), sorted by block.

func (*Profile) Statuses

func (p *Profile) Statuses(raw Raw) map[string]StatusValue

Statuses evaluates every status entry of the profile.

type Raw

type Raw struct {
	Words map[int]uint16
	JSON  map[string]any
}

Raw is the raw data of one poll: Modbus words by address or decoded JSON by endpoint.

type ReadOptions

type ReadOptions struct {
	Mode         string   `yaml:"mode"`
	MaxRegisters int      `yaml:"max_registers"`
	Ranges       [][2]int `yaml:"ranges"`
}

ReadOptions describes how registers are fetched.

func (*ReadOptions) Limit

func (r *ReadOptions) Limit() int

Limit returns the effective max registers per request.

type Request

type Request struct {
	Start int
	Count int
}

Request is one Modbus read: Count registers from Start.

type Sample

type Sample struct {
	At    time.Time                  `json:"at"`
	Words map[int]uint16             `json:"words,omitempty"`
	JSON  map[string]json.RawMessage `json:"json,omitempty"`
	Err   string                     `json:"err,omitempty"`
}

Sample is one poll: Modbus words by address or JSON bodies by endpoint ID. Err is set for a failed poll so replays see gaps.

func (Sample) Raw

func (s Sample) Raw() (Raw, error)

Raw decodes the sample into the decoder input.

type SignFrom

type SignFrom struct {
	Field         `yaml:",inline"`
	DischargeWhen int `yaml:"discharge_when"`
}

SignFrom gives a magnitude its sign from a direction register or path.

type Status

type Status struct {
	Field    `yaml:",inline"`
	Map      string `yaml:"map"`
	Level    string `yaml:"level"`    // bitfield without map: any set bit has this level
	NonEmpty string `yaml:"nonempty"` // type list: non-empty → level
	False    string `yaml:"false"`    // type bool: false → level
	NonZero  string `yaml:"nonzero"`  // any number: non-zero → level
	Text     Text   `yaml:"text"`
	Label    Text   `yaml:"label"` // display name on the device page; default the key
}

Status is one status register or JSON value mapped to ok / notice / fault.

type StatusValue

type StatusValue struct {
	Code  uint64
	Level string
	Texts []Text // texts of the code or of every set bit
	Valid bool
}

StatusValue is the evaluated state of one status entry.

type Text

type Text map[string]string

Text is a translated text keyed by language.

type Value

type Value struct {
	Num   float64
	Text  string // string and enum channels
	Valid bool
}

Value is one decoded channel value. Valid is false when the data is missing; a missing value is never 0.

type ValueID

type ValueID struct {
	IDs string `yaml:"ids"` // endpoint returning the ID array
	ID  int    `yaml:"id"`
}

ValueID looks a value up by ID in a parallel ID array (WARP).

Jump to

Keyboard shortcuts

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