Ctrl K
ComunidadGuías…

tariff/tariffs.go

Rama master · réplica de lectura del repositorio original.

Archivo original ↗Preguntar a KiBot
package tariff

import (
	"time"

	"github.com/evcc-io/evcc/api"
	"golang.org/x/text/currency"
)

type Tariffs struct {
	Currency                                       currency.Unit
	Grid, FeedIn, Co2, Planner, Solar, Temperature api.Tariff
}

// At returns the rate at the given time
func At(t api.Tariff, ts time.Time) (api.Rate, error) {
	if t != nil {
		if rr, err := t.Rates(); err == nil {
			if r, err := rr.At(ts); err == nil {
				return r, nil
			}
		}
	}
	return api.Rate{}, api.ErrNotAvailable
}

// Now returns the price/cost/value at the given time
func Now(t api.Tariff) (float64, error) {
	r, err := At(t, time.Now())
	return r.Value, err
}

// Rates returns the tariffs rates if not nil
func Rates(t api.Tariff) api.Rates {
	if t == nil {
		return nil
	}

	rr, err := t.Rates()
	if err != nil {
		return nil
	}

	return rr
}

// AverageRate returns the arithmetic mean of rates in [now, now+d), or nil if unavailable.
func AverageRate(t api.Tariff, d time.Duration) *float64 {
	rr := Rates(t)
	if rr == nil {
		return nil
	}

	now := time.Now()
	end := now.Add(d)

	var sum float64
	var count int
	for _, r := range rr {
		if r.Start.Before(end) && r.End.After(now) {
			sum += r.Value
			count++
		}
	}

	if count == 0 {
		return nil
	}

	return new(sum / float64(count))
}

func (t *Tariffs) Get(u api.TariffUsage) api.Tariff {
	// ensure tariff is not a wrapper
	exists := func(t api.Tariff) bool {
		return t != nil && t.Type() != 0
	}

	switch u {
	case api.TariffUsageCo2:
		return t.Co2

	case api.TariffUsageFeedIn:
		return t.FeedIn

	case api.TariffUsageGrid:
		return t.Grid

	// TODO solar
	case api.TariffUsagePlanner:
		switch {
		case exists(t.Planner):
			// prio 0: manually set planner tariff
			return t.Planner

		case exists(t.Grid) && t.Grid.Type() == api.TariffTypePriceForecast:
			// prio 1: grid tariff with forecast
			return t.Grid

		case exists(t.Co2):
			// prio 2: co2 tariff
			return t.Co2

		default:
			// prio 3: static grid tariff
			return t.Grid
		}

	case api.TariffUsageSolar:
		return t.Solar

	case api.TariffUsageTemperature:
		return t.Temperature

	default:
		return nil
	}
}