Documentation
¶
Overview ¶
Package mdqmodels holds the hand-written data models of the canonical meter-reading schema: Messwert (one value per quarter hour) and Zaehlerstand (a meter reading).
The contract is the JSON form of the types in this package, pinned by the shared fixtures in testdata/, which the Go and the Python models both parse and round-trip. The gRPC contract lives in proto/mdq/v1.
Reading is strict on purpose: unknown and duplicate keys are rejected, so a typo fails loudly and two parsers can never read different data from the same bytes. Every rejection is a *ValidationError naming the field and the rule.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func HerkunftMatchesStatus ¶
HerkunftMatchesStatus reports whether a herkunft is allowed for a status. A nil herkunft means "not set" (null in JSON); a non-nil pointer to the empty string is not "not set" but an unknown value and never matches (Python's herkunft_passt_zu_status treats "" the same way). The rules: fehlend if and only if herkunft is nil (a missing value has no origin); wahr requires fremd (the agent only forms provisional and substitute values, so a true value is always fremd); vorlaeufig and ersatzwert may have either. An unknown status or herkunft never matches.
func IsValidMaLoID ¶
IsValidMaLoID reports whether id is 11 ASCII digits, does not start with 0, and ends in the correct check digit.
func MaLoCheckDigit ¶
MaLoCheckDigit computes the check digit of a MaLo ID (BDEW algorithm) from its first ten digits: the digits at odd positions (1st, 3rd, ...) are summed once, those at even positions twice, and the check digit is (10 - sum % 10) % 10. It returns an error unless first10 is exactly ten ASCII digits (a leading zero is fine here; the ID rule in IsValidMaLoID is stricter).
Types ¶
type Decimal ¶
type Decimal string
Decimal is a decimal number in its shortest canonical string form with at most 12 integer digits (|value| < 10^12) and at most 6 decimal places, for example "0", "160", "0.000001", "25.25" or "-3.5".
It is a string on the wire so that no consumer loses precision by parsing it as a float. The accepted syntax is ^-?(0|[1-9][0-9]*)(\.[0-9]{0,5}[1-9])?$: no exponent, no plus sign, no leading zeros, no trailing zeros after the point ("1.0" is rejected), no negative zero ("-0"), no "NaN" or "Infinity", no separators. A value with more than 6 decimals ("0.1234567") is rejected, never rounded, and so is a value of 10^12 or more (the storage column is numeric(18,6)): producers that compute in floating point round to 6 decimals first. Negative values are allowed; the consumer flags them.
Converting a string directly (Decimal("1.50")) does not normalise: Validate then rejects it. Use NewDecimal to get the canonical form from "1.50" or "1.5000000". To build one from a float64, round to 6 decimals first and format the shortest representation:
d, err := NewDecimal(strconv.FormatFloat(math.Round(x*1e6)/1e6, 'f', -1, 64))
NaN and the infinities fail in NewDecimal.
func NewDecimal ¶
NewDecimal builds a canonical Decimal from s (at most 12 integer digits, see Decimal), which may carry trailing zeros: "1.5000000" becomes "1.5", "2.0" becomes "2" and "-0.00" becomes "0". Why: the Python models normalise a decimal built in code the same way, so both languages accept and write the same values. Decimals are counted after the trailing zeros are removed, so "1.0000001" (7 decimals) is rejected, never rounded. Anything else non-canonical (exponent, plus sign, leading zeros, ".5", "5.", NaN, separators) is rejected.
func (Decimal) MarshalJSON ¶
MarshalJSON writes d as a JSON string after validating it.
func (*Decimal) UnmarshalJSON ¶
UnmarshalJSON reads a JSON string and validates it. JSON numbers and null are rejected: a number would be parsed as a float by most consumers and lose precision.
type Herkunft ¶
type Herkunft string
Herkunft says where a Messwert comes from.
const ( // HerkunftFremd is a value that was not formed by the meter data quality agent (MQA), for example // one delivered from the source system. HerkunftFremd Herkunft = "fremd" // HerkunftMqa is a value formed by the meter data quality agent (MQA, German "Messdatenqualitaetsagent"), // the software that forms provisional and substitute values, in an earlier run. HerkunftMqa Herkunft = "mqa" )
The values of Herkunft.
func (Herkunft) MarshalJSON ¶
MarshalJSON writes h as a JSON string after validating it.
func (*Herkunft) UnmarshalJSON ¶
UnmarshalJSON reads a JSON string and validates it; null is rejected (a nullable herkunft is a *Herkunft, and the null is handled by the owning struct).
type Messwert ¶
type Messwert struct {
// Malo is the market location ID: 11 ASCII digits, no leading 0, valid check digit.
Malo string
// Timestamp is the START of the quarter hour: 00:00 is the first quarter hour of a day and 23:45
// the last, and the value equals the start of a [from, to) interval, so intervals never overlap
// and never leave a gap. In code any time zone is accepted and written in UTC.
Timestamp time.Time
// Resolution is the raster; only PT15M in v1.
Resolution Resolution
// Value is the quantity, or nil if and only if Status is StatusFehlend. Negative values are
// allowed: the consumer flags them, the schema does not reject them.
Value *Decimal
// Status says how trustworthy the value is.
Status Status
// Herkunft is the origin of the value, or nil if and only if Status is StatusFehlend;
// StatusWahr requires HerkunftFremd.
Herkunft *Herkunft
// Profiltyp is the load profile kind.
Profiltyp Profiltyp
// Richtung is the flow direction.
Richtung Richtung
}
Messwert is one row of the canonical meter-reading schema: the quantity of one MaLo for one quarter hour.
All eight JSON keys are required. Value and Herkunft are required-nullable: they are always written, as null when unset (nil here), and a missing key is rejected on read even though null would be fine. Parsing is strict on purpose: unknown and duplicate keys are rejected.
func ParseMesswert ¶
ParseMesswert reads one Messwert from JSON bytes. It is the recommended entry point: every failure, including null, a non-object, a syntax error, trailing data, a byte order mark and invalid UTF-8, is a *ValidationError. The strictness is that of UnmarshalJSON.
Example ¶
ExampleParseMesswert is the Go snippet of the README; TestReadmeGoSnippet keeps the two identical.
package main
import (
"errors"
"fmt"
"log"
"time"
mdq "github.com/hochfrequenz/mdq-models"
)
func main() {
raw := []byte(`{"malo":"68283561554","timestamp":"2026-03-29T00:45:00Z","resolution":"PT15M",` +
`"value":"1.5","status":"wahr","herkunft":"fremd","profiltyp":"haushalt","richtung":"bezug"}`)
m, err := mdq.ParseMesswert(raw) // every failure is a *mdq.ValidationError
if err != nil {
log.Fatal(err)
}
fmt.Println(m.Malo, m.Timestamp.Format(time.RFC3339), *m.Value, m.Status)
// Build a row in code. NewDecimal drops trailing zeros: "2.50" becomes "2.5".
value, err := mdq.NewDecimal("2.50")
if err != nil {
log.Fatal(err)
}
mqa := mdq.HerkunftMqa
built := mdq.Messwert{
Malo: "68283561554",
Timestamp: time.Date(2026, 3, 29, 3, 0, 0, 0, time.FixedZone("CEST", 2*3600)), // written as UTC
Resolution: mdq.PT15M,
Value: &value,
Status: mdq.StatusErsatzwert,
Herkunft: &mqa,
Profiltyp: mdq.ProfiltypHaushalt,
Richtung: mdq.RichtungBezug,
}
out, err := built.MarshalJSON() // validates; an invalid row does not marshal
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
// Reading is strict: duplicate (and unknown) keys are rejected.
_, err = mdq.ParseMesswert([]byte(`{"malo":"68283561554","malo":"68283561554"}`))
var invalid *mdq.ValidationError
fmt.Println(errors.As(err, &invalid))
}
Output: 68283561554 2026-03-29T00:45:00Z 1.5 wahr {"malo":"68283561554","timestamp":"2026-03-29T01:00:00Z","resolution":"PT15M","value":"2.5","status":"ersatzwert","herkunft":"mqa","profiltyp":"haushalt","richtung":"bezug"} true
func (Messwert) MarshalJSON ¶
MarshalJSON validates m and writes it with the keys in contract order and the timestamp in UTC with a literal Z; unset Value and Herkunft are written as null. It has a value receiver so that both Messwert and *Messwert marshal the same way.
func (*Messwert) UnmarshalJSON ¶
UnmarshalJSON reads one Messwert strictly: all eight keys required (in any order), no unknown or duplicate keys, timestamps exactly in the form YYYY-MM-DDTHH:MM:SSZ, and every rule of Validate. On error the receiver is left unchanged.
Called through json.Unmarshal, syntax errors surface as *json.SyntaxError (not a *ValidationError), and a top-level null into a *Messwert pointer (var p *Messwert) sets the pointer to nil without any error, because encoding/json never calls UnmarshalJSON for it; plan 0.1 rejects top-level null. Use ParseMesswert for untrusted input.
type Profiltyp ¶
type Profiltyp string
Profiltyp is the kind of load profile of a Messwert's MaLo.
const ( // ProfiltypHaushalt is a household profile. ProfiltypHaushalt Profiltyp = "haushalt" // ProfiltypGewerbe is a commercial profile. ProfiltypGewerbe Profiltyp = "gewerbe" // ProfiltypIndustrie is an industrial profile. ProfiltypIndustrie Profiltyp = "industrie" // ProfiltypUnbekannt is an unknown profile. ProfiltypUnbekannt Profiltyp = "unbekannt" )
The values of Profiltyp.
func (Profiltyp) MarshalJSON ¶
MarshalJSON writes p as a JSON string after validating it.
func (*Profiltyp) UnmarshalJSON ¶
UnmarshalJSON reads a JSON string and validates it; null is rejected.
type Resolution ¶
type Resolution string
Resolution is the time raster of a Messwert, written as an ISO 8601 duration.
const PT15M Resolution = "PT15M"
PT15M is the only resolution in v1: one value per quarter hour. It is a field of its own (and not implied) so that another raster can be added later without changing the shape of the data.
func (Resolution) MarshalJSON ¶
func (r Resolution) MarshalJSON() ([]byte, error)
MarshalJSON writes r as a JSON string after validating it.
func (*Resolution) UnmarshalJSON ¶
func (r *Resolution) UnmarshalJSON(b []byte) error
UnmarshalJSON reads a JSON string and validates it; null is rejected.
func (Resolution) Validate ¶
func (r Resolution) Validate() error
Validate checks that r is a resolution known to v1.
type Richtung ¶
type Richtung string
Richtung is the flow direction of a Messwert.
const ( // RichtungBezug is consumption from the grid. RichtungBezug Richtung = "bezug" // RichtungEinspeisung is feed-in to the grid. RichtungEinspeisung Richtung = "einspeisung" )
The values of Richtung.
func (Richtung) MarshalJSON ¶
MarshalJSON writes r as a JSON string after validating it.
func (*Richtung) UnmarshalJSON ¶
UnmarshalJSON reads a JSON string and validates it; null is rejected.
type Status ¶
type Status string
Status says how trustworthy a Messwert is.
const ( // StatusWahr is a measured value. StatusWahr Status = "wahr" // StatusVorlaeufig is a provisional value that may still change. StatusVorlaeufig Status = "vorlaeufig" // StatusErsatzwert is a substitute value that replaces a missing or implausible measurement. StatusErsatzwert Status = "ersatzwert" // StatusFehlend marks a missing value; value and herkunft are null. StatusFehlend Status = "fehlend" )
The values of Status. The JSON value is the constant's name without the prefix, lower-case, and matches the proto enum constants (STATUS_WAHR and so on).
func (Status) MarshalJSON ¶
MarshalJSON writes s as a JSON string after validating it.
func (*Status) UnmarshalJSON ¶
UnmarshalJSON reads a JSON string and validates it; null is rejected.
type ValidationError ¶
type ValidationError struct {
// Field is the JSON key the rule belongs to ("malo", "value", ...). It is empty when the rule
// concerns the document as a whole (for example "must be a JSON object").
Field string
// Rule is a short human-readable statement of the rule that was broken.
Rule string
}
ValidationError says which field broke which rule. Every error returned by this package when it rejects data is a *ValidationError, so callers can use errors.As to find the field and the rule instead of matching text. That holds for Validate, MarshalJSON, ParseMesswert and ParseZaehlerstand; it does NOT hold for json.Unmarshal, which reports syntax errors (including trailing data) as *json.SyntaxError before this package sees the input. Use the Parse functions to read untrusted bytes.
type Zaehlerstand ¶
type Zaehlerstand struct {
// Malo is the market location ID: 11 ASCII digits, no leading 0, valid check digit.
Malo string
// Timestamp is the instant of the reading, a whole second. In code any time zone is accepted and
// written in UTC.
Timestamp time.Time
// Value is the register value; required, never null.
Value Decimal
}
Zaehlerstand is a meter reading: the cumulative register value of one MaLo at one point in time. It is the second input of the schema, next to Messwert.
All three JSON keys are required and parsing is strict like for Messwert (unknown and duplicate keys are rejected). Unlike Messwert there is no raster: Timestamp is a point in time with any whole second, not the start of a quarter hour, and Value is never null.
func ParseZaehlerstand ¶
func ParseZaehlerstand(b []byte) (Zaehlerstand, error)
ParseZaehlerstand reads one Zaehlerstand from JSON bytes. It is the recommended entry point: every failure, including null, a non-object, a syntax error, trailing data, a byte order mark and invalid UTF-8, is a *ValidationError. The strictness is that of UnmarshalJSON.
func (Zaehlerstand) MarshalJSON ¶
func (z Zaehlerstand) MarshalJSON() ([]byte, error)
MarshalJSON validates z and writes it with the keys in contract order and the timestamp in UTC with a literal Z.
func (*Zaehlerstand) UnmarshalJSON ¶
func (z *Zaehlerstand) UnmarshalJSON(b []byte) error
UnmarshalJSON reads one Zaehlerstand strictly: all three keys required (in any order), no unknown or duplicate keys, and every rule of Validate. On error the receiver is left unchanged.
Called through json.Unmarshal, syntax errors surface as *json.SyntaxError (not a *ValidationError), and a top-level null into a *Zaehlerstand pointer (var p *Zaehlerstand) sets the pointer to nil without any error, because encoding/json never calls UnmarshalJSON for it. Use ParseZaehlerstand for untrusted input.
func (Zaehlerstand) Validate ¶
func (z Zaehlerstand) Validate() error
Validate checks every rule of the contract on a value built in code and returns a *ValidationError naming the first broken field.