collector

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 21 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 collector polls the devices of one connection, normalises their values, turns counters into energy deltas, nets grid energy and books everything into 15-minute buckets (spec 5, 6). One collector instance serves one connection.

Index

Constants

View Source
const (
	EventReplaced = "replaced" // clear decrease: meter replaced, new base
	EventJump     = "jump"     // implausible jump confirmed by the next reading: new base
	EventOverflow = "overflow" // u32 wrap-around
)

Counter events.

View Source
const (
	// ResetConfirm is how long a drop must persist before it is booked as a reset.
	ResetConfirm = 15 * time.Minute
	// ResetOverdue is how long after the last reset a missing reset is reported.
	ResetOverdue = 25 * time.Hour
)

Reset detection (spec 5.3). A reset is a data event, never triggered by time: device clocks drift and often lack NTP and DST. A drop counts once it persisted for ResetConfirm; the counter itself buffers the energy meanwhile, so nothing is lost by waiting.

View Source
const (
	EventResetPartial = "reset of only part of the reset group (register stuck?)"
	EventResetMissing = "no reset for more than 25 h"
)

Reset events, logged once per occurrence.

View Source
const FlushInterval = time.Minute

FlushInterval is the upsert interval of open buckets (spec 5.1).

View Source
const GapAfter = 5 * time.Minute

GapAfter: a poll more than the interval plus this after the last successful one is a gap poll (app not running, clock jump > 5 min; spec 5.2, 5.3).

Variables

View Source
var ErrNotJSON = errors.New("collector: response is not JSON")

ErrNotJSON is returned for a response body that is not valid JSON.

Functions

func Slot

func Slot(t time.Time) int64

Slot returns the 15-minute UTC slot of t (spec 5.2).

func SlotStart

func SlotStart(slot int64) time.Time

SlotStart returns the start time of a slot.

Types

type Accumulator

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

Accumulator collects the open buckets of one collector between flushes. Gauges are partial aggregates, energy is the Wh added since the last flush; storage merges both. It is owned by the collector goroutine.

func NewAccumulator

func NewAccumulator() *Accumulator

NewAccumulator returns an empty accumulator.

func (*Accumulator) AddEnergy

func (a *Accumulator) AddEnergy(series int64, e Energy)

AddEnergy books e proportionally to the time each slot overlaps (From, To]; From == To books everything into the slot of To.

func (*Accumulator) AddGauge

func (a *Accumulator) AddGauge(series int64, v float64, at time.Time, weight time.Duration)

AddGauge adds a sample valid for weight (the device interval) to the slot of at.

func (*Accumulator) AddShaped added in v0.3.0

func (a *Accumulator) AddShaped(series int64, e Energy, w map[int64]float64)

AddShaped books e over the slots of (From, To] in proportion to their weight w (energy integrated from power). Without weight in the span it books like AddEnergy. Every slot of the span gets a row, also with 0 Wh, so the slots are complete as with AddEnergy.

func (*Accumulator) Batch

func (a *Accumulator) Batch(todayStart int64) storage.Batch

Batch drains everything pending into one storage batch, sorted for stable writes.

func (*Accumulator) Empty

func (a *Accumulator) Empty() bool

Empty reports whether nothing is pending.

func (*Accumulator) Restore

func (a *Accumulator) Restore(b storage.Batch)

Restore puts a batch that failed to write back, so no energy is lost; newer pending values are kept on top of it.

func (*Accumulator) SetCounter

func (a *Accumulator) SetCounter(st storage.CounterState)

SetCounter records the counter state to persist with the next flush.

type Collector

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

Collector polls the devices of one connection (health.Component).

func New

func New(s Settings, d Deps) (*Collector, error)

New builds a collector; nothing is read or written before Start.

func (*Collector) LastBeat

func (c *Collector) LastBeat() time.Time

LastBeat implements health.Component.

func (*Collector) Start

func (c *Collector) Start(ctx context.Context) error

Start restores state and starts the polling loop.

func (*Collector) State

func (c *Collector) State() health.State

State implements health.Component.

func (*Collector) Stop

func (c *Collector) Stop() error

Stop ends the loop, flushes open buckets and stops the transport. It is idempotent.

type CounterConfig

type CounterConfig struct {
	Resolution float64 // profile resolution in Wh (0 = none)
	Step       float64 // Wh of one raw count of an integer register (0 = none)
	MaxPower   float64 // W; 0 disables the glitch guard
	Wrap       float64 // Wh value at which the raw counter wraps (u32); 0 = never
	Float32    bool    // raw value is an f32 in Unit; precision limits the resolution
	UnitFactor float64 // Wh per raw unit (kWh: 1000)
}

CounterConfig describes one counter input.

func (CounterConfig) EffectiveResolution

func (c CounterConfig) EffectiveResolution(v float64) float64

EffectiveResolution = max(profile resolution, type precision at v) (spec 5.3).

type Daily

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

Daily is one daily_reset counter of a reset group.

func NewDaily

func NewDaily(cfg CounterConfig, base *float64, at time.Time) *Daily

NewDaily returns a member; base restores the persisted raw value (nil = none).

func (*Daily) Base

func (d *Daily) Base() (*float64, time.Time)

Base returns the current base value and its time (nil before the first reading).

type Delta

type Delta struct {
	Wh        float64
	Gap       bool      // the poll followed a gap; spread over the gap's buckets
	ResetSeen bool      // a daily reset was booked
	Held      bool      // the reading was held (glitch guard or waiting for the reset group)
	Event     string    // one-time events for the log: replaced, jump, overflow
	From      time.Time // a confirmed reset: book from the poll before the drop
}

Delta is the energy a counter or integrator books for one poll.

type Deps

type Deps struct {
	Store     storage.CollectorStore
	Cache     LiveCache
	Bus       Publisher
	Reporter  health.Reporter
	Transport Transport
	Clock     util.Clock
	Log       zerolog.Logger
}

Deps are the collector's dependencies.

type Energy

type Energy struct {
	Wh       float64
	From, To time.Time
	Flags    int
	Counter  *float64
}

Energy is energy produced in (From, To] with its bucket flags and the raw counter at To.

type Fetcher

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

Fetcher reads the raw data of one device per poll: the Modbus requests or due HTTP endpoints its configured meters need, nothing else (keeps the bus load low). Slow endpoints (interval > 0) are cached between fetches.

func NewHTTPFetcher

func NewHTTPFetcher(dev *site.Device, clock util.Clock, r HTTPReader) (*Fetcher, error)

NewHTTPFetcher builds a fetcher for an HTTP device.

func NewModbusFetcher

func NewModbusFetcher(dev *site.Device, clock util.Clock, r ModbusReader) (*Fetcher, error)

NewModbusFetcher builds a fetcher for a Modbus device.

func (*Fetcher) Fetch

func (f *Fetcher) Fetch(ctx context.Context) (profile.Sample, error)

Fetch performs one poll. The poll instant is captured once at its start. Any failed request fails the whole poll, so the counters see a gap instead of partial data.

func (*Fetcher) FetchAll

func (f *Fetcher) FetchAll(ctx context.Context) (profile.Sample, error)

FetchAll reads everything the profile describes, every HTTP endpoint regardless of its interval (dumps and fixtures).

func (*Fetcher) Invalidate

func (f *Fetcher) Invalidate()

Invalidate drops cached slow endpoints, e.g. after an ID/value length mismatch.

type Group

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

Group is a reset group: all its counters reset together once per device day.

func NewGroup

func NewGroup(members []*Daily, rollover time.Duration, loc *time.Location,
	last, lastReset time.Time,
) *Group

NewGroup builds a group. last is the last poll and lastReset the last confirmed reset as persisted (zero if unknown); rollover is the configured local reset time.

func (*Group) LastReset

func (g *Group) LastReset() time.Time

LastReset returns the instant of the last confirmed reset (zero if none).

func (*Group) PeriodStart

func (g *Group) PeriodStart(at time.Time) time.Time

PeriodStart returns the start of the device day containing at: the last confirmed reset, or before the first one the configured rollover. Energy shown by a daily register belongs to the period since then and is never booked before it.

func (*Group) Update

func (g *Group) Update(at time.Time, gap bool, readings []Reading) []Delta

Update books one poll of all members (same order as members).

type HTTPReader

type HTTPReader interface {
	Get(ctx context.Context, path string) ([]byte, error)
}

HTTPReader fetches a device path (transport/http.Client).

type Integrator

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

Integrator integrates power between two consecutive successful polls (trapezoid).

func (*Integrator) Reset

func (i *Integrator) Reset()

Reset forgets the previous poll (after a failed poll).

func (*Integrator) Update

func (i *Integrator) Update(p float64, at time.Time, gap bool) (wh float64, ok bool)

Update returns the signed energy in Wh since the previous poll; ok is false when there is no previous poll or the poll followed a gap (the gap stays a gap).

type Lifetime

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

Lifetime tracks a monotonic counter (spec 5.3).

func NewLifetime

func NewLifetime(cfg CounterConfig, base *float64, at time.Time) *Lifetime

NewLifetime returns a tracker; base restores the persisted raw value (nil = none).

func (*Lifetime) Base

func (l *Lifetime) Base() (*float64, time.Time)

Base returns the current base value and its time (nil before the first reading).

func (*Lifetime) Update

func (l *Lifetime) Update(v float64, at time.Time, gap bool) Delta

Update books the reading v at at.

type LiveCache

type LiveCache interface {
	Set(key string, v livecache.Value, interval time.Duration)
}

LiveCache receives live values.

type ModbusReader

type ModbusReader interface {
	Read(ctx context.Context, unit uint8, fn modbus.Function, start, count uint16) ([]uint16, error)
}

ModbusReader reads registers over the shared connection (transport/modbus.Conn).

type Publisher

type Publisher interface {
	Publish(e eventbus.Event)
}

Publisher receives status events.

type Reading

type Reading struct {
	Value float64
	Valid bool
}

Reading is one member value of a poll; Valid is false when the value is missing.

type Settings

type Settings struct {
	Site       *site.Site
	Connection string            // connection address key
	Sources    map[string]Source // per device ID
	Location   *time.Location    // site time zone (TZ)
}

Settings selects the connection and its devices.

type Shape added in v0.3.0

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

Shape integrates the power of a meter in one direction per slot since the last base of a counter. A coarse counter step is then spread like the power flowed instead of evenly (spec 5.3). The time between two readings is bridged linearly, also over failed polls and outages; the slots of an outage are flagged estimated by the caller.

func NewShape added in v0.3.0

func NewShape(sign float64) *Shape

NewShape returns an empty shape for power of sign.

func (*Shape) Add added in v0.3.0

func (s *Shape) Add(p float64, at time.Time)

Add integrates the power p read at at (trapezoid of the part in the shape's direction).

func (*Shape) Cut added in v0.3.0

func (s *Shape) Cut(at time.Time)

Cut starts a new span at at: the counter took a new base there.

func (*Shape) Weights added in v0.3.0

func (s *Shape) Weights(from time.Time) map[int64]float64

Weights returns the weight per slot when the shape covers everything since from, else nil.

type Source

type Source interface {
	Fetch(ctx context.Context) (profile.Sample, error)
}

Source reads one raw poll of a device (Fetcher).

type Transport

type Transport interface {
	Start()
	Stop()
}

Transport is the connection lifecycle owned by the collector (Modbus connection; a no-op for HTTP devices, whose clients need none).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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