senml

package module
v0.0.0-...-b6df6a0 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2021 License: EUPL-1.2 Imports: 8 Imported by: 17

README

Package senml

godoc cirrus ci goreportcard gocover

Package senml implements the SenML specification, used for sending simple sensor measurements encoded in JSON, CBOR or XML.

The goal of this package is to not only support the specification, but to also make it easy to work with within Go.

Examples

Encoding:

package main

import (
	"fmt"
	"time"

	"github.com/silkeh/senml"
)

func main() {
	now := time.Now()
	list := []senml.Measurement{
		senml.NewValue("sensor:temperature", 23.5, senml.Celsius, now, 0),
		senml.NewValue("sensor:humidity", 33.7, senml.RelativeHumidityPercent, now, 0),
	}

	data, err := senml.EncodeJSON(list)
	if err != nil {
		fmt.Print("Error encoding to JSON:", err)
	}

	fmt.Printf("%s\n", data)
}

Decoding:

package main

import (
	"fmt"

	"github.com/silkeh/senml"
)

func main() {
	json := []byte(`[{"bn":"sensor:","bt":1555487588,"bu":"Cel","n":"temperature","v":23.5},{"n":"humidity","u":"%RH","v":33.7}]`)

	list, err := senml.DecodeJSON(json)
	if err != nil {
		fmt.Print("Error encoding to JSON:", err)
	}

	for _, m := range list {
		fmt.Printf("%#v\n", m)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AutoTime = true

AutoTime toggles the automatic setting of zero timestamps to now. Disabling this option results in timestamps relative to zero time when no exact time is given.

Functions

func EncodeCBOR

func EncodeCBOR(list []Measurement) (b []byte, err error)

EncodeCBOR encodes a list of measurements into CBOR.

func EncodeJSON

func EncodeJSON(list []Measurement) ([]byte, error)

EncodeJSON encodes a list of measurements into JSON.

func EncodeXML

func EncodeXML(list []Measurement) (b []byte, err error)

EncodeXML encodes a list of measurements into XML.

Types

type Attributes

type Attributes struct {
	Name       string
	Unit       Unit
	Time       time.Time
	UpdateTime time.Duration
}

Attributes contains the properties common to a measurement.

func (*Attributes) Attrs

func (m *Attributes) Attrs() *Attributes

Attrs returns a pointer to the measurement of the Measurement value.

func (*Attributes) Equal

func (m *Attributes) Equal(s *Attributes) bool

Equal returns true if the given attribute values are equal.

func (*Attributes) Record

func (m *Attributes) Record() Record

Record returns a SenML record representing the value.

type Boolean

type Boolean struct {
	Attributes
	Value bool
}

Boolean represents a boolean measurement value. It implements Measurement.

func NewBoolean

func NewBoolean(name string, value bool, unit Unit, time time.Time, updateTime time.Duration) *Boolean

NewBoolean returns a new Boolean value with the corresponding value and attributes.

func (*Boolean) Equal

func (v *Boolean) Equal(ml Measurement) bool

Equal returns true if the given Measurement value is equal.

func (*Boolean) Record

func (v *Boolean) Record() Record

Record returns a SenML record representing the value.

type Data

type Data struct {
	Attributes
	Value []byte
}

Data represents a measurement value returning binary data. It implements Measurement.

func NewData

func NewData(name string, value []byte, unit Unit, time time.Time, updateTime time.Duration) *Data

NewData returns a new Data value with the corresponding value and attributes.

func (*Data) Equal

func (v *Data) Equal(ml Measurement) bool

Equal returns true if the given Measurement value is equal.

func (*Data) Record

func (v *Data) Record() Record

Record returns a SenML record representing the value.

type Decimal

type Decimal [2]int

Decimal represents a CBOR decimal type. See RFC8949 section 3.4.4.

func NewDecimal

func NewDecimal(exponent, value int) Decimal

NewDecimal creates a new Decimal value.

func (Decimal) Float

func (n Decimal) Float() float64

Float returns the floating point representation of the Decimal value. Some precision may be lost.

func (Decimal) Int

func (n Decimal) Int() int

Int returns the integer representation of the Decimal value. Any fractional part will be lost.

type Measurement

type Measurement interface {
	// Attrs returns a pointer to the measurement of the Measurement value.
	Attrs() *Attributes

	// Equal returns true if the given Measurement value is equal.
	Equal(Measurement) bool

	// Record returns a SenML record representing the value.
	Record() Record
}

Measurement represents a single SenML measurement value. This interface is meant to represent the various Measurement values, see: Value, Sum, String, Boolean and Data.

func Decode

func Decode(records []Record) (list []Measurement, err error)

Decode decodes a list of Measurement records into measurement values.

func DecodeCBOR

func DecodeCBOR(c []byte) ([]Measurement, error)

DecodeCBOR decodes a list of measurements from CBOR.

func DecodeJSON

func DecodeJSON(j []byte) ([]Measurement, error)

DecodeJSON decodes a list of measurements from JSON.

func DecodeXML

func DecodeXML(x []byte) ([]Measurement, error)

DecodeXML decodes a list of measurements from XML.

type Numeric

type Numeric interface{}

Numeric represents a numeric value. This can be any integer or floating point type, or a Decimal fraction. Numeric is equal to the empty interface, but using it for anything other than those types will result in a panic.

type Record

type Record struct {
	XMLName xml.Name `json:"-" xml:"senml" codec:"-"`

	BaseName     string  `json:"bn,omitempty" xml:"bn,attr,omitempty" codec:"-2"`
	BaseTime     Numeric `json:"bt,omitempty" xml:"bt,attr,omitempty" codec:"-3"`
	BaseUnit     string  `json:"bu,omitempty" xml:"bu,attr,omitempty" codec:"-4"`
	BaseValue    Numeric `json:"bv,omitempty" xml:"bv,attr,omitempty" codec:"-5"`
	BaseSum      Numeric `json:"bs,omitempty" xml:"bs,attr,omitempty" codec:"-6"`
	BaseVersion  int     `json:"bver,omitempty" xml:"bver,attr,omitempty" codec:"-1"`
	Name         string  `json:"n,omitempty" xml:"n,attr,omitempty" codec:"0"`
	Unit         string  `json:"u,omitempty" xml:"u,attr,omitempty" codec:"1"`
	Value        Numeric `json:"v,omitempty" xml:"v,attr,omitempty" codec:"2"`
	StringValue  string  `json:"vs,omitempty" xml:"vs,attr,omitempty" codec:"3"`
	BooleanValue *bool   `json:"vb,omitempty" xml:"vb,attr,omitempty" codec:"4"`
	DataValue    []byte  `json:"vd,omitempty" xml:"vd,attr,omitempty" codec:"8"`
	Sum          Numeric `json:"s,omitempty" xml:"s,attr,omitempty" codec:"5"`
	Time         Numeric `json:"t,omitempty" xml:"t,attr,omitempty" codec:"6"`
	UpdateTime   Numeric `json:"ut,omitempty" xml:"ut,attr,omitempty" codec:"7"`
	// contains filtered or unexported fields
}

Record represents a SenML record. This type is used as an intermediary between the Measurement values and the actual encoding. All SenML attributes are supported in this record.

func Encode

func Encode(list []Measurement) (records []Record)

Encode encodes a list of measurements to corresponding Measurement records.

type String

type String struct {
	Attributes
	Value string
}

String represents a string measurement value. It implements Measurement.

func NewString

func NewString(name string, value string, unit Unit, time time.Time, updateTime time.Duration) *String

NewString returns a new String value with the corresponding value and attributes.

func (*String) Equal

func (v *String) Equal(ml Measurement) bool

Equal returns true if the given Measurement value is equal.

func (*String) Record

func (v *String) Record() Record

Record returns a SenML record representing the value.

type Sum

type Sum struct {
	Attributes
	Value float64
}

Sum represents an integrated floating point measurement value. It implements Measurement.

func NewSum

func NewSum(name string, sum float64, unit Unit, time time.Time, updateTime time.Duration) *Sum

NewSum returns a new Sum value with the corresponding value and attributes.

func (*Sum) Equal

func (v *Sum) Equal(ml Measurement) bool

Equal returns true if the given Measurement value is equal.

func (*Sum) Record

func (v *Sum) Record() Record

Record returns a SenML record representing the value.

type Unit

type Unit string

Unit represents a SenML defined unit

const (
	// RFC8428
	None                    Unit = ""
	Meter                   Unit = "m"
	Kilogram                Unit = "kg"
	Gram                    Unit = "g" // not recommended
	Second                  Unit = "s"
	Ampere                  Unit = "A"
	Kelvin                  Unit = "K"
	Candela                 Unit = "cd"
	Mole                    Unit = "mol"
	Hertz                   Unit = "Hz"
	Radian                  Unit = "rad"
	Steradian               Unit = "sr"
	Newton                  Unit = "N"
	Pascal                  Unit = "Pa"
	Joule                   Unit = "J"
	Watt                    Unit = "W"
	Coulomb                 Unit = "C"
	Volt                    Unit = "V"
	Farad                   Unit = "F"
	Ohm                     Unit = "Ohm"
	Siemens                 Unit = "S"
	Weber                   Unit = "Wb"
	Tesla                   Unit = "T"
	Henry                   Unit = "H"
	Celsius                 Unit = "Cel"
	Lumen                   Unit = "lm"
	Lux                     Unit = "lx"
	Becquerel               Unit = "Bq"
	Gray                    Unit = "Gy"
	Sievert                 Unit = "Sv"
	Katal                   Unit = "kat"
	SquareMeter             Unit = "m2"
	CubicMeter              Unit = "m3"
	Liter                   Unit = "l" // not recommended
	MeterPerSecond          Unit = "m/s"
	MeterPerSquareSecond    Unit = "m/s2"
	CubicMeterPerSecond     Unit = "m3/s"
	LiterPerSecond          Unit = "l/s" // not recommended
	WattPerSquareMeter      Unit = "W/m2"
	CandelaPerSquareMeter   Unit = "cd/m2"
	Bit                     Unit = "bit"
	BitPerSecond            Unit = "bit/s"
	Latitude                Unit = "lat"
	Longitude               Unit = "lon"
	PH                      Unit = "pH"
	Decibel                 Unit = "dB"
	DBW                     Unit = "dBW"
	Bel                     Unit = "Bspl" // not recommended
	Count                   Unit = "count"
	Ratio                   Unit = "/"
	Ratio2                  Unit = "%" // not recommended
	RelativeHumidityPercent Unit = "%RH"
	RemainingBatteryPercent Unit = "%EL"
	RemainingBatterySeconds Unit = "EL"
	Rate                    Unit = "1/s"
	RPM                     Unit = "1/min"    // not recommended
	HeartRate               Unit = "beat/min" // not recommended
	HeartBeats              Unit = "beats"    // not recommended
	Conductivity            Unit = "S/m"

	// RFC8798
	Byte                     Unit = "B"
	VoltAmpere               Unit = "VA"
	VoltAmpereSecond         Unit = "VAs"
	VoltAmpereReactive       Unit = "var"
	VoltAmpereReactiveSecond Unit = "vars"
	JoulePerMeter            Unit = "J/m"
	KilogramPerCubicMeter    Unit = "kg/m3"
	Degree                   Unit = "deg" // not recommended

	// ISO 7027-1:2016
	NephelometricTurbidityUnit Unit = "NTU"

	// Secondary units (RFC8798)
	Millisecond            Unit = "ms"
	Minute                 Unit = "min"
	Hour                   Unit = "h"
	Megahertz              Unit = "MHz"
	Kilowatt               Unit = "kW"
	KilovoltAmpere         Unit = "kVA"
	Kilovar                Unit = "kvar"
	AmpereHour             Unit = "Ah"
	WattHour               Unit = "Wh"
	KilowattHour           Unit = "kWh"
	VarHour                Unit = "varh"
	KilovarHour            Unit = "kvarh"
	KilovoltAmpereHour     Unit = "kVAh"
	WattHourPerKilometer   Unit = "Wh/km"
	Kibibyte               Unit = "KiB"
	Gigabyte               Unit = "GB"
	MegabitPerSecond       Unit = "Mbit/s"
	BytePerSecond          Unit = "B/s"
	MegabytePerSecond      Unit = "MB/s"
	Millivolt              Unit = "mV"
	Milliampere            Unit = "mA"
	DecibelMilliwatt       Unit = "dBm"
	MicrogramPerCubicMeter Unit = "ug/m3"
	MillimeterPerHour      Unit = "mm/h"
	MeterPerHour           Unit = "m/h"
	PartsPerMillion        Unit = "ppm"
	Percent                Unit = "/100"
	Permille               Unit = "/1000"
	Hectopascal            Unit = "hPa"
	Millimeter             Unit = "mm"
	Centimeter             Unit = "cm"
	Kilometer              Unit = "km"
	KilometerPerHour       Unit = "km/h"

	// Secondary units (CoRE-1)
	PartsPerBillion  Unit = "ppb"
	PartsPerTrillion Unit = "ppt"
	VoltAmpereHour   Unit = "VAh"
	Milligram        Unit = "mg/l"
	Microgram        Unit = "ug/l"
	GramPerLiter     Unit = "g/l"
)

SenML unit definitions

func (Unit) String

func (u Unit) String() string

String returns the string value of a Unit

type Value

type Value struct {
	Attributes
	Value float64
}

Value represents a floating point measurement value. It implements Measurement.

func NewValue

func NewValue(name string, value float64, unit Unit, time time.Time, updateTime time.Duration) *Value

NewValue returns a new Value with the corresponding value and attributes.

func (*Value) Equal

func (v *Value) Equal(ml Measurement) bool

Equal returns true if the given Measurement value is equal.

func (*Value) Record

func (v *Value) Record() Record

Record returns a SenML record representing the value.

Jump to

Keyboard shortcuts

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