service

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 17 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 service holds the read services behind the HTTP handlers.

Index

Constants

View Source
const (
	StatusOK       = "ok"
	StatusDegraded = "degraded"
	StatusFailed   = "failed"
)

Health statuses.

View Source
const (
	LevelOffline = "offline" // the device does not answer
	LevelNone    = "none"    // pvmon did not run: no data
)

Levels of the generic device status (spec 12): the profile levels plus the connection.

Variables

View Source
var (
	ErrInvalidLevel = derive.ErrInvalidLevel
	ErrInvalidRange = derive.ErrInvalidRange
	ErrRangeTooLong = derive.ErrRangeTooLong
)

Request errors of the energy endpoint; the handler maps them to error codes.

View Source
var ErrInvalidReport = report.ErrInvalidRange

ErrInvalidReport wraps every bad report parameter (400, code invalid_range).

View Source
var ErrNotFound = errors.New("service: not found")

ErrNotFound reports an unknown device.

Functions

This section is empty.

Types

type BucketModel

type BucketModel struct {
	Key             string    `json:"key"`
	From            string    `json:"from"`
	To              string    `json:"to"`
	Partial         bool      `json:"partial"`
	Days            int       `json:"days"`
	CompleteDays    int       `json:"complete_days"`
	Total           EnergyKWh `json:"total"`
	SelfSufficiency *float64  `json:"self_sufficiency_pct"`
}

BucketModel is one day, month or year of the range.

type CapabilitiesModel

type CapabilitiesModel struct {
	PV         int            `json:"pv"`
	Battery    int            `json:"battery"`
	Grid       bool           `json:"grid"`
	Backup     bool           `json:"backup"`
	Loadpoints map[string]int `json:"loadpoints"`
}

CapabilitiesModel is what the site has; the UI builds its layout from it.

type ComparisonModel

type ComparisonModel struct {
	Mode         string `json:"mode"`
	From         string `json:"from"`
	To           string `json:"to"`
	Days         int    `json:"days"`
	CompleteDays int    `json:"complete_days"`
	Matched      bool   `json:"matched"`
	MatchedDays  int    `json:"matched_days"`
}

ComparisonModel is the comparison period.

type DayValueModel

type DayValueModel struct {
	Date string  `json:"date"`
	KWh  float64 `json:"kwh"`
}

DayValueModel is a day and its energy.

type DeviceBlock

type DeviceBlock struct {
	Meter    string          `json:"meter"`
	Label    string          `json:"label"`
	Role     string          `json:"role"`
	Block    string          `json:"block"`
	Channels []DeviceChannel `json:"channels"`
}

DeviceBlock is a meter of the device with its channels.

type DeviceChannel

type DeviceChannel struct {
	Name string `json:"name"`
	Key  string `json:"key"`
	Unit string `json:"unit,omitempty"`
}

DeviceChannel is one live channel: its key for the WebSocket and its unit.

type DeviceDetail

type DeviceDetail struct {
	DeviceInfo
	Netting string           `json:"netting,omitempty"`
	Read    string           `json:"read,omitempty"`
	Blocks  []DeviceBlock    `json:"blocks"`
	Status  []StatusRegister `json:"status"`
}

DeviceDetail is GET /api/v1/devices/{id}: the device, the meters it provides with their live channels, its status registers and the netting of its grid meter.

type DeviceInfo

type DeviceInfo struct {
	ID        string   `json:"id"`
	Profile   string   `json:"profile"`
	Vendor    string   `json:"vendor"`
	Models    []string `json:"models"`
	Transport string   `json:"transport"`
	Verified  bool     `json:"verified"`
	State     string   `json:"state"`
	IntervalS float64  `json:"interval_s"`
	Meters    []string `json:"meters"`
	// LastPoll is the newest poll since start, nil before the first one.
	LastPoll *LastPoll `json:"last_poll"`
}

DeviceInfo is one device of GET /api/v1/devices; addresses and credentials are never exposed.

type DeviceModel

type DeviceModel struct {
	ID       string `json:"id"`
	Profile  string `json:"profile"`
	Verified bool   `json:"verified"`
	State    string `json:"state"`
}

DeviceModel is one device; addresses and credentials are never exposed.

type DeviceStatus

type DeviceStatus struct {
	ID      string        `json:"id"`
	Changes []LevelChange `json:"changes"`
}

DeviceStatus is one device of GET /api/v1/status: the generic level over time, oldest first; the first change is the level active at the start of the range.

type Devices

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

Devices answers the device endpoints.

func NewDevices

func NewDevices(s *site.Site, snap SnapshotSource, status StatusReader, loc *time.Location,
) (*Devices, error)

NewDevices builds the service.

func (*Devices) Get

func (s *Devices) Get(id string) (DeviceDetail, error)

Get returns one device with its meters and channels.

func (*Devices) List

func (s *Devices) List() []DeviceInfo

List returns every device, sorted by ID.

func (*Devices) Overview

func (s *Devices) Overview(ctx context.Context, from, to time.Time) ([]DeviceStatus, error)

Overview returns the generic level of every device in [from, to), sorted by ID.

func (*Devices) Status

func (s *Devices) Status(ctx context.Context, id string, from, to time.Time,
) ([]StatusEventModel, error)

Status returns the status changes of a device in [from, to), newest first, followed by the change of each register active at from. Levels and texts come from the profile; the connection register has the levels ok, offline and none.

type Energy

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

Energy answers energy requests.

func NewEnergy

func NewEnergy(d EnergyDeriver) (*Energy, error)

NewEnergy builds the service.

func (*Energy) Series

func (s *Energy) Series(ctx context.Context, names []string, level string, from, to time.Time,
) (EnergyModel, error)

Series returns the periods of level for the local days from..to.

type EnergyDeriver

type EnergyDeriver interface {
	Energy(ctx context.Context, names []string, level derive.Level, from, to time.Time,
	) ([]derive.Result, error)
	Names() []string
}

EnergyDeriver is the part of derive.Service the energy service needs.

type EnergyKWh

type EnergyKWh struct {
	PV          *float64 `json:"pv_kwh"`
	Consumption float64  `json:"consumption_kwh"`
	Import      float64  `json:"import_kwh"`
	Export      float64  `json:"export_kwh"`
	Charge      *float64 `json:"charge_kwh"`
	Discharge   *float64 `json:"discharge_kwh"`
}

EnergyKWh are the site quantities in kWh; absent quantities are null.

type EnergyModel

type EnergyModel struct {
	Series []EnergySeries `json:"series"`
}

EnergyModel is the body of GET /api/v1/energy (spec 9.1).

type EnergySeries

type EnergySeries struct {
	Name   string        `json:"name"`
	Unit   string        `json:"unit"`
	Values []EnergyValue `json:"values"`
}

EnergySeries is one series over the requested periods.

type EnergyValue

type EnergyValue struct {
	Period      string
	Value       *float64
	Ratio       bool
	Complete    bool
	Estimated   bool
	MissingDays int
}

EnergyValue is one period. Value is Wh for energy series and percent for ratios; it is marshalled as "wh" or "pct" and is null when there is no data, never 0.

func (EnergyValue) MarshalJSON

func (v EnergyValue) MarshalJSON() ([]byte, error)

MarshalJSON writes the number as "wh" or, for ratios, as "pct".

type FigureModel

type FigureModel struct {
	ID        string   `json:"id"`
	Kind      string   `json:"kind"`
	Better    string   `json:"better"`
	Value     *float64 `json:"value"`
	Compared  *float64 `json:"compared"`
	Base      *float64 `json:"base"`
	Change    *float64 `json:"change"`
	ChangePct *float64 `json:"change_pct"`
}

FigureModel is a key figure: energy in kWh (change in kWh and %), ratios in percent (change in points).

type FirstSlotSource

type FirstSlotSource interface {
	FirstSlot(ctx context.Context) (slot int64, ok bool, err error)
}

FirstSlotSource tells where the stored data starts.

type Gauge

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

Gauge answers gauge requests.

func NewGauge

func NewGauge(d GaugeDeriver, loc *time.Location) (*Gauge, error)

NewGauge builds the service; loc is the site's location for the slot times.

func (*Gauge) Series

func (s *Gauge) Series(ctx context.Context, names []string, from, to time.Time,
) (GaugeModel, error)

Series returns the 15-minute gauges of names for the local days from..to.

type GaugeDeriver

type GaugeDeriver interface {
	Gauge(ctx context.Context, names []string, from, to time.Time) ([]derive.GaugeResult, error)
}

GaugeDeriver is the part of derive.Service the gauge service needs.

type GaugeModel

type GaugeModel struct {
	Series []GaugeSeries `json:"series"`
}

GaugeModel is the body of GET /api/v1/gauge (spec 9.1).

type GaugePoint

type GaugePoint struct {
	At    time.Time `json:"at"`
	Avg   float64   `json:"avg"`
	Min   float64   `json:"min"`
	Max   float64   `json:"max"`
	Cover int       `json:"cover"`
}

GaugePoint is one 15-minute slot: its start, avg/min/max and covered seconds.

type GaugeSeries

type GaugeSeries struct {
	Name   string       `json:"name"`
	Unit   string       `json:"unit"`
	Points []GaugePoint `json:"points"`
}

GaugeSeries is one series; slots without data are left out.

type Health

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

Health evaluates the supervisor snapshot; it never blocks on a component.

func NewHealth

func NewHealth(src SnapshotSource, clock util.Clock, s HealthSettings) (*Health, error)

NewHealth builds the service.

func (*Health) Report

func (h *Health) Report() (HealthReport, int)

Report returns the health report and its HTTP status code.

type HealthReport

type HealthReport struct {
	Status     string                   `json:"status"`
	Components []health.ComponentStatus `json:"components"`
	Devices    map[string]string        `json:"devices"`
}

HealthReport is the body of GET /health.

type HealthSettings

type HealthSettings struct {
	Sweep        time.Duration
	OfflineAfter time.Duration   // status.offline_after
	Critical     map[string]bool // devices that provide a critical meter
}

HealthSettings configures the /health semantics (spec 8.2).

type LastPoll

type LastPoll struct {
	At     time.Time `json:"at"`
	TookMS int64     `json:"took_ms"`
	OK     bool      `json:"ok"`
}

LastPoll is the newest poll of a device: start, duration from the first request to the decoded sample, and whether it succeeded.

type LevelChange

type LevelChange struct {
	At    time.Time `json:"at"`
	Level string    `json:"level"`
}

LevelChange is a change of the generic level of a device.

type LoadpointsModel

type LoadpointsModel struct {
	Meters     []ReportMeter `json:"meters"`
	Categories []ReportMeter `json:"categories"`
}

LoadpointsModel lists loadpoints and their categories.

type MeterModel

type MeterModel struct {
	ID         string   `json:"id"`
	Role       string   `json:"role"`
	Category   string   `json:"category,omitempty"`
	Label      string   `json:"label"`
	Device     string   `json:"device"`
	Parent     string   `json:"parent,omitempty"`
	CapacityWh float64  `json:"capacity_wh,omitempty"`
	KWp        float64  `json:"kwp,omitempty"`
	Series     []string `json:"series"`
}

MeterModel is one meter; it carries no connection details.

type PatternsModel

type PatternsModel struct {
	BestPV             *DayValueModel `json:"best_pv"`
	LowestPV           *DayValueModel `json:"lowest_pv"`
	MaxConsumption     *DayValueModel `json:"max_consumption"`
	MaxImport          *DayValueModel `json:"max_import"`
	WeekdayConsumption *float64       `json:"weekday_consumption_kwh"`
	WeekendConsumption *float64       `json:"weekend_consumption_kwh"`
	LowImportDays      int            `json:"low_import_days"`
}

PatternsModel are the day-level observations.

type ProbeBlock

type ProbeBlock struct {
	Name         string         `json:"name"`
	Role         string         `json:"role"`
	RolesAllowed []string       `json:"roles_allowed"`
	Category     string         `json:"category,omitempty"`
	Channels     []ProbeChannel `json:"channels"`
}

ProbeBlock is one meter block of the profile with its decoded channels.

func ProbeBlocks

func ProbeBlocks(p *profile.Profile, raw *profile.Raw) []ProbeBlock

ProbeBlocks decodes every meter block of the profile from one raw sample, sorted by name. Without raw data (a failed read) the channels have no values.

type ProbeChannel

type ProbeChannel struct {
	Name  string   `json:"name"`
	Value *float64 `json:"value"`
	Text  string   `json:"text,omitempty"`
	Unit  string   `json:"unit,omitempty"`
}

ProbeChannel is one normalised value; Value is null when the device did not deliver it.

type ProbeResult

type ProbeResult struct {
	Device   string       `json:"device"`
	Profile  string       `json:"profile"`
	Verified bool         `json:"verified"`
	At       time.Time    `json:"at"`
	TookMS   int64        `json:"took_ms"`
	Error    string       `json:"error,omitempty"`
	Blocks   []ProbeBlock `json:"blocks"`
}

ProbeResult is one read of a device with a draft configuration (POST /api/v1/config/probe, spec 11.14). A device that does not answer is a result with Error, not a failed request.

type ProfileBlock

type ProfileBlock struct {
	Name         string   `json:"name"`
	Role         string   `json:"role"`
	RolesAllowed []string `json:"roles_allowed"`
	Category     string   `json:"category,omitempty"`
	Channels     []string `json:"channels"`
}

ProfileBlock is one meter block of a profile with the roles it may take.

type ProfileInfo

type ProfileInfo struct {
	ID        string         `json:"id"`
	Vendor    string         `json:"vendor"`
	Models    []string       `json:"models"`
	Transport string         `json:"transport"`
	Verified  bool           `json:"verified"`
	Netting   string         `json:"netting,omitempty"`
	Blocks    []ProfileBlock `json:"blocks"`
}

ProfileInfo is one built-in profile for the setup wizard (GET /api/v1/profiles).

type ProfileModel

type ProfileModel struct {
	MeanW  []*float64 `json:"mean_w"`
	PeakW  *float64   `json:"peak_w"`
	PeakAt *string    `json:"peak_at"`
}

ProfileModel is the load profile: mean W per 15-minute slot of day, peak 15-min mean.

type ProfileSource

type ProfileSource interface {
	IDs() []string
	Load(ref, baseDir string) (*profile.Loaded, error)
}

ProfileSource lists and resolves the built-in profiles (*profile.Loader).

type Profiles

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

Profiles answers GET /api/v1/profiles.

func NewProfiles

func NewProfiles(src ProfileSource) *Profiles

NewProfiles builds the service.

func (*Profiles) List

func (p *Profiles) List() []ProfileInfo

List returns every built-in profile, sorted by ID.

type ReportMeter

type ReportMeter struct {
	ID            string   `json:"id"`
	Label         string   `json:"label"`
	Category      string   `json:"category,omitempty"`
	CompleteDays  int      `json:"complete_days"`
	InKWh         *float64 `json:"in_kwh"`
	OutKWh        *float64 `json:"out_kwh"`
	SharePct      *float64 `json:"share_pct,omitempty"`
	SpecificYield *float64 `json:"specific_yield,omitempty"`
	Ratio         *float64 `json:"ratio,omitempty"`
	SolarKWh      *float64 `json:"solar_est_kwh,omitempty"`
	SolarPct      *float64 `json:"solar_pct,omitempty"`
}

ReportMeter is one PV source, battery or loadpoint.

type ReportModel

type ReportModel struct {
	From          string           `json:"from"`
	To            string           `json:"to"`
	Granularity   string           `json:"granularity"`
	TodayExcluded bool             `json:"today_excluded"`
	Summary       SummaryModel     `json:"summary"`
	Figures       []FigureModel    `json:"figures"`
	Comparison    *ComparisonModel `json:"comparison"`
	Buckets       []BucketModel    `json:"buckets"`
	PVSources     []ReportMeter    `json:"pv_sources"`
	Batteries     []ReportMeter    `json:"batteries"`
	Loadpoints    *LoadpointsModel `json:"loadpoints"`
	Profile       ProfileModel     `json:"profile"`
	Patterns      PatternsModel    `json:"patterns"`
	MissingDays   []string         `json:"missing_days"`
	Quality       []ReportQuality  `json:"quality"`
}

ReportModel is the body of GET /api/v1/report?format=json.

func NewReportModel

func NewReportModel(r report.Report) ReportModel

NewReportModel turns a report into its JSON body.

type ReportQuality

type ReportQuality struct {
	ID            string `json:"id"`
	Label         string `json:"label"`
	MissingDays   int    `json:"missing_days"`
	EstimatedDays int    `json:"estimated_days"`
}

ReportQuality is one meter's data quality.

type ReportQuery

type ReportQuery struct {
	From, To, Granularity, Compare string
}

ReportQuery are the parameters of GET /api/v1/report (spec 9.1, 12).

type Reports

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

Reports builds energy reports from derived site quantities.

func NewReports

func NewReports(s *site.Site, energy EnergyDeriver, clock util.Clock, loc *time.Location,
) (*Reports, error)

NewReports builds the service for site s.

func (*Reports) Build

func (r *Reports) Build(ctx context.Context, q ReportQuery) (report.Report, error)

Build computes the report of q.

type Site

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

Site builds the site model from the effective site model.

func NewSite

func NewSite(s *site.Site, loc *time.Location, first FirstSlotSource,
	snap SnapshotSource,
) (*Site, error)

NewSite builds the service.

func (*Site) Model

func (s *Site) Model(ctx context.Context) (SiteModel, error)

Model returns the current site model.

type SiteModel

type SiteModel struct {
	Name         string            `json:"name"`
	TZ           string            `json:"tz"`
	ConfigRev    int64             `json:"config_rev"`
	DataSince    *string           `json:"data_since"`
	Capabilities CapabilitiesModel `json:"capabilities"`
	Meters       []MeterModel      `json:"meters"`
	Devices      []DeviceModel     `json:"devices"`
	SiteSeries   []string          `json:"site_series"`
}

SiteModel is the body of GET /api/v1/site (spec 9.1).

type SnapshotSource

type SnapshotSource interface {
	Snapshot() health.Snapshot
}

SnapshotSource is the supervisor's health snapshot.

type SplitModel

type SplitModel struct {
	SolarKWh   float64  `json:"solar_est_kwh"`
	BatteryKWh float64  `json:"battery_est_kwh"`
	GridKWh    float64  `json:"grid_est_kwh"`
	SolarPct   *float64 `json:"solar_pct"`
	BatteryPct *float64 `json:"battery_pct"`
	GridPct    *float64 `json:"grid_pct"`
}

SplitModel is a split into solar, battery and grid (≈).

type StatusEventModel

type StatusEventModel struct {
	Register string         `json:"register"`
	At       time.Time      `json:"at"`
	Code     int64          `json:"code"`
	Level    string         `json:"level"`
	Texts    []profile.Text `json:"texts"`
}

StatusEventModel is one status change with its level and texts.

type StatusReader

type StatusReader interface {
	StatusEvents(ctx context.Context, device string, from, to int64, limit int,
	) ([]storage.StatusEvent, error)
}

StatusReader reads stored status changes.

type StatusRegister

type StatusRegister struct {
	Name  string       `json:"name"`
	Label profile.Text `json:"label,omitempty"`
}

StatusRegister is a status register of the profile with its display name.

type SummaryModel

type SummaryModel struct {
	Days            int         `json:"days"`
	CompleteDays    int         `json:"complete_days"`
	Total           EnergyKWh   `json:"total"`
	PerDay          *EnergyKWh  `json:"per_day"`
	SelfSufficiency *float64    `json:"self_sufficiency_pct"`
	SelfConsumption *float64    `json:"self_consumption_pct"`
	GridCharge      *float64    `json:"grid_charge_est_kwh"`
	Sources         SplitModel  `json:"sources"`
	PVSplit         *SplitModel `json:"pv_split"`
	BatteryRatio    *float64    `json:"battery_ratio"`
	BalanceDiff     *float64    `json:"balance_diff_kwh"`
	BalanceDiffPct  *float64    `json:"balance_diff_pct"`
	FallbackDays    int         `json:"fallback_days"`
}

SummaryModel is the summary of the complete days.

type UnknownSeriesError

type UnknownSeriesError = derive.UnknownSeriesError

UnknownSeriesError lists requested series names that do not exist.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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