data

package
v0.0.0-...-94bc3c9 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2025 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package data contains common data structures that are used throughout the project.

Encode, Decode, MergePoints, and MergeEdgePoints can be used to convert your custom types to/from the NodeEdge type that SIOT uses for its wire and storage format.

Index

Constants

View Source
const (
	CmdUpdateApp = "updateApp"
	CmdPoll      = "poll"
	CmdFieldMode = "fieldMode"
)

define valid commands

View Source
const (
	// general point types
	PointTypeChannel      = "channel"
	PointTypeDevice       = "device"
	PointTypeDescription  = "description"
	PointTypeFilePath     = "filePath"
	PointTypeNodeType     = "nodeType"
	PointTypeTombstone    = "tombstone"
	PointTypeScale        = "scale"
	PointTypeOffset       = "offset"
	PointTypeUnits        = "units"
	PointTypeValue        = "value"
	PointTypeValueSet     = "valueSet"
	PointTypeIndex        = "index"
	PointTypeTagPointType = "tagPointType"
	PointTypeTag          = "tag"
	// PointTypeID typically refers to Node ID
	PointTypeID                 = "id"
	PointTypeDebug              = "debug"
	PointTypeInitialized        = "initialized"
	PointTypePollPeriod         = "pollPeriod"
	PointTypeError              = "error"
	PointTypeErrorCount         = "errorCount"
	PointTypeErrorCountReset    = "errorCountReset"
	PointTypeErrorCountEOF      = "errorCountEOF"
	PointTypeErrorCountEOFReset = "errorCountEOFReset"
	PointTypeErrorCountCRC      = "errorCountCRC"
	PointTypeErrorCountCRCReset = "errorCountCRCReset"
	PointTypeErrorCountHR       = "errorCountHR"
	PointTypeErrorCountResetHR  = "errorCountResetHR"
	PointTypeSyncCount          = "syncCount"
	PointTypeSyncCountReset     = "syncCountReset"
	PointTypeReadOnly           = "readOnly"
	PointTypeURI                = "uri"
	PointTypeDisabled           = "disabled"
	PointTypeControlled         = "controlled"

	PointTypePeriod = "period"

	// An device node describes an phyical device -- it may be the
	// cloud server, gateway, etc
	NodeTypeDevice         = "device"
	PointTypeCmdPending    = "cmdPending"
	PointTypeSwUpdateState = "swUpdateState"
	PointTypeStartApp      = "startApp"
	PointTypeStartSystem   = "startSystem"
	PointTypeUpdateOS      = "updateOS"
	PointTypeUpdateApp     = "updateApp"
	PointTypeSysState      = "sysState"

	PointValueSysStateUnknown  = "unknown"
	PointValueSysStatePowerOff = "powerOff"
	PointValueSysStateOffline  = "offline"
	PointValueSysStateOnline   = "online"

	PointTypeSwUpdateRunning      = "swUpdateRunning"
	PointTypeSwUpdateError        = "swUpdateError"
	PointTypeSwUpdatePercComplete = "swUpdatePercComplete"
	PointTypeVersionOS            = "versionOS"
	PointTypeVersionApp           = "versionApp"
	PointTypeVersionHW            = "versionHW"

	// user node describes a system user and is used to control
	// access to the system (typically through web UI)
	NodeTypeUser       = "user"
	PointTypeFirstName = "firstName"
	PointTypeLastName  = "lastName"
	PointTypePhone     = "phone"
	PointTypeEmail     = "email"
	PointTypePass      = "pass"

	// user edge points
	PointTypeRole       = "role"
	PointValueRoleAdmin = "admin"
	PointValueRoleUser  = "user"

	// User Authentication
	NodeTypeJWT    = "jwt"
	PointTypeToken = "token"

	// modbus nodes
	// in modbus land, terminology is a big backwards, client is master,
	// and server is slave.
	NodeTypeModbus = "modbus"

	PointTypeClientServer = "clientServer"
	PointValueClient      = "client"
	PointValueServer      = "server"

	PointTypePort   = "port"
	PointTypeBaud   = "baud"
	PointTypeHRDest = "hrDest"

	PointTypeProtocol = "protocol"
	PointValueRTU     = "RTU"
	PointValueTCP     = "TCP"

	NodeTypeModbusIO = "modbusIo"

	// FIXME, should we change modbusIoType to ioType?
	PointTypeModbusIOType           = "modbusIoType"
	PointValueModbusDiscreteInput   = "modbusDiscreteInput"
	PointValueModbusCoil            = "modbusCoil"
	PointValueModbusInputRegister   = "modbusInputRegister"
	PointValueModbusHoldingRegister = "modbusHoldingRegister"

	PointTypeDataFormat = "dataFormat"
	PointValueUINT16    = "uint16"
	PointValueINT16     = "int16"
	PointValueUINT32    = "uint32"
	PointValueINT32     = "int32"
	PointValueFLOAT32   = "float32"

	NodeTypeOneWire   = "oneWire"
	NodeTypeOneWireIO = "oneWireIO"

	// A group node is used to group users and devices
	// or generally to add structure to the node graph.
	NodeTypeGroup = "group"

	NodeTypeDb = "db"

	PointTypeBucket = "bucket"
	PointTypeOrg    = "org"

	// a rule node describes a rule that may run on the system
	NodeTypeRule = "rule"

	PointTypeActive = "active"

	NodeTypeCondition = "condition"

	PointTypeConditionType = "conditionType"
	PointValuePointValue   = "pointValue"
	PointValueSchedule     = "schedule"

	PointTypeNodeID = "nodeID"

	PointTypeTrigger = "trigger"

	PointTypeStart   = "start"
	PointTypeEnd     = "end"
	PointTypeWeekday = "weekday"
	PointTypeDate    = "date"

	PointTypePointID    = "pointID"
	PointTypePointKey   = "pointKey"
	PointTypePointType  = "pointType"
	PointTypePointIndex = "pointIndex"
	PointTypeValueType  = "valueType"
	PointValueNumber    = "number"
	PointValueOnOff     = "onOff"
	PointValueText      = "text"

	PointTypeOperator     = "operator"
	PointValueGreaterThan = ">"
	PointValueLessThan    = "<"
	PointValueEqual       = "="
	PointValueNotEqual    = "!="
	PointValueOn          = "on"
	PointValueOff         = "off"
	PointValueContains    = "contains"

	PointTypeValueText = "valueText"

	PointTypeMinActive = "minActive"

	NodeTypeAction         = "action"
	NodeTypeActionInactive = "actionInactive"

	PointTypeAction = "action"

	PointValueNotify    = "notify"
	PointValueSetValue  = "setValue"
	PointValuePlayAudio = "playAudio"

	// Transient points that are used for notifications, etc.
	// These points are not stored in the state of any node,
	// but are recorded in the time series database to record history.
	PointMsgAll  = "msgAll"
	PointMsgUser = "msgUser"

	NodeTypeMsgService = "msgService"

	PointTypeService = "service"

	PointValueTwilio = "twilio"
	PointValueSMTP   = "smtp"

	PointTypeSID       = "sid"
	PointTypeAuthToken = "authToken"
	PointTypeFrom      = "from"

	NodeTypeVariable      = "variable"
	PointTypeVariableType = "variableType"

	NodeTypeSync = "sync"

	PointTypeMetricNatsCycleNodePoint          = "metricNatsCycleNodePoint"
	PointTypeMetricNatsCycleNodeEdgePoint      = "metricNatsCycleNodeEdgePoint"
	PointTypeMetricNatsCycleNode               = "metricNatsCycleNode"
	PointTypeMetricNatsCycleNodeChildren       = "metricNatsCycleNodeChildren"
	PointTypeMetricNatsPendingNodePoint        = "metricNatsPendingNodePoint"
	PointTypeMetricNatsPendingNodeEdgePoint    = "metricNatsPendingNodeEdgePoint"
	PointTypeMetricNatsThroughputNodePoint     = "metricNatsThroughputNodePoint"
	PointTypeMetricNatsThroughputNodeEdgePoint = "metricNatsThroughputNodeEdgePoint"

	// serial MCU clients
	NodeTypeSerialDev         = "serialDev"
	PointTypeRx               = "rx"
	PointTypeTx               = "tx"
	PointTypeHrRx             = "hrRx"
	PointTypeRxReset          = "rxReset"
	PointTypeTxReset          = "txReset"
	PointTypeHrRxReset        = "hrRxReset"
	PointTypeLog              = "log"
	PointTypeUptime           = "uptime"
	PointTypeMaxMessageLength = "maxMessageLength"
	PointTypeSyncParent       = "syncParent"

	// CAN bus clients
	NodeTypeCanBus               = "canBus"
	PointTypeBitRate             = "bitRate"
	PointTypeMsgsInDb            = "msgsInDb"
	PointTypeSignalsInDb         = "signalsInDb"
	PointTypeMsgsRecvdDb         = "msgsRecvdDb"
	PointTypeMsgsRecvdDbReset    = "msgsRecvdDbReset"
	PointTypeMsgsRecvdOther      = "msgsRecvdOther"
	PointTypeMsgsRecvdOtherReset = "msgsRecvdOtherReset"

	NodeTypeSignalGenerator = "signalGenerator"

	PointTypeSignalType   = "signalType"
	PointTypeMinValue     = "minValue"
	PointTypeMaxValue     = "maxValue"
	PointTypeInitialValue = "initialValue"
	PointTypeRoundTo      = "roundTo"
	PointTypeSampleRate   = "sampleRate"
	PointTypeDestination  = "destination"
	PointTypeBatchPeriod  = "batchPeriod"
	PointTypeFrequency    = "frequency"
	PointTypeMinIncrement = "minIncrement"
	PointTypeMaxIncrement = "maxIncrement"

	NodeTypeFile      = "file"
	PointTypeName     = "name"
	PointTypeData     = "data"
	PointTypeBinary   = "binary"
	PointTypeSize     = "size"
	PointTypeHash     = "hash"
	PointTypeDownload = "download"
	PointTypeProgress = "progress"

	PointTypeRate   = "rate"
	PointTypeRateHR = "rateHR"
	NodeTypeMetrics = "metrics"

	PointTypeType          = "type"
	PointValueApp          = "app"
	PointValueProcess      = "process"
	PointValueAllProcesses = "allProcesses"
	PointValueSystem       = "system"

	PointTypeCount = "count"

	// Sys Metrics
	PointTypeMetricSysLoad            = "metricSysLoad"
	PointTypeMetricSysCPUPercent      = "metricSysCPUPercent"
	PointTypeMetricSysMem             = "metricSysMem"
	PointTypeMetricSysMemUsedPercent  = "metricSysMemUsedPercent"
	PointTypeMetricSysDiskUsedPercent = "metricSysDiskUsedPercent"
	PointTypeMetricSysNetBytesRecv    = "metricSysNetBytesRecv"
	PointTypeMetricSysNetBytesSent    = "metricSysNetBytesSent"
	PointTypeMetricSysUptime          = "metricSysUptime"

	// App Metrics
	PointTypeMetricAppAlloc        = "metricAppAlloc"
	PointTypeMetricAppNumGoroutine = "metricAppNumGoroutine"

	// process metrics
	PointTypeMetricProcCPUPercent = "metricProcCPUPercent"
	PointTypeMetricProcMemPercent = "metricProcMemPercent"
	PointTypeMetricProcMemRSS     = "metricProcMemRSS"

	PointTypeHost                = "host"
	PointTypeHostBootTime        = "hostBootTime"
	PointKeyHostname             = "hostname"
	PointKeyOS                   = "os"
	PointKeyPlatform             = "platform"
	PointKeyPlatformFamily       = "platformFamily"
	PointKeyPlatformVersion      = "platformVersion"
	PointKeyKernelVersion        = "kernelVersion"
	PointKeyKernelArch           = "kernelArch"
	PointKeyVirtualizationSystem = "virtualizationSystem"
	PointKeyVirtualizationRole   = "virtualizationRole"

	PointKeyUsedPercent = "usedPercent"
	PointKeyTotal       = "total"
	PointKeyAvailable   = "available"
	PointKeyUsed        = "used"
	PointKeyFree        = "free"

	NodeTypeShelly   = "shelly"
	NodeTypeShellyIo = "shellyIo"

	PointTypeSwitch      = "switch"
	PointTypeSwitchSet   = "switchSet"
	PointTypeInput       = "input"
	PointTypeLight       = "light"
	PointTypeLightSet    = "lightSet"
	PointTypeDeviceID    = "deviceID"
	PointTypeIP          = "ip"
	PointTypeVoltage     = "voltage"
	PointTypeCurrent     = "current"
	PointTypePower       = "power"
	PointTypeTemperature = "temp"
	PointTypeBrightness  = "brightness"
	PointTypeWhite       = "white"
	PointTypeLightTemp   = "lightTemp"
	PointTypeTransition  = "transition"
	PointTypeOffline     = "offline"

	PointValueShellyTypeBulbDuo = "BulbDuo"
	PointValueShellyTypeRGBW2   = "rgbw2"
	PointValueShellyType1PM     = "1pm"
	PointValueShellyTypePlugUS  = "PlugUS"
	PointValueShellyTypePlugUK  = "PlugUK"
	PointValueShellyTypePlugIT  = "PlugIT"
	PointValueShellyTypePlugS   = "PlugS"
	PointValueShellyTypeI4      = "PlusI4"
	PointValueShellyTypePlus1   = "Plus1"
	PointValueShellyTypePlus2PM = "Plus2PM"

	PointTypeTimeSync  = "timeSync"
	PointTypeConnected = "connected"

	NodeTypeNetworkManager       = "networkManager"
	NodeTypeNetworkManagerDevice = "networkManagerDevice"
	NodeTypeNetworkManagerConn   = "networkManagerConn"

	NodeTypeNTP             = "ntp"
	PointTypeServer         = "server"
	PointTypeFallbackServer = "fallbackServer"

	NodeTypeUpdate           = "update"
	PointTypeOSUpdate        = "osUpdate"
	PointTypeAppUpdate       = "appUpdate"
	PointTypePrefix          = "prefix"
	PointTypeDownloadOS      = "downloadOS"
	PointTypeOSDownloaded    = "osDownloaded"
	PointTypeDiscardDownload = "discardDownload"
	PointTypeReboot          = "reboot"
	PointTypeAutoReboot      = "autoReboot"
	PointTypeAutoDownload    = "autoDownload"
	PointTypeDirectory       = "directory"
	PointTypeRefresh         = "refresh"

	// points for networking config
	PointTypeStaticIP = "staticIP"
	PointTypeAddress  = "address"
	PointTypeNetmask  = "netmask"
	PointTypeGateway  = "gateway"
)

define common node and point types that have special meaning in the system.

Variables

View Source
var ErrDocumentNotFound = errors.New("document not found")

ErrDocumentNotFound is returned in APIs if document is not found

Functions

func BoolToFloat

func BoolToFloat(v bool) float64

BoolToFloat converts bool to float

func Decode

func Decode(input NodeEdgeChildren, outputStruct any) error

Decode converts a Node to custom struct. output can be a struct type that contains node, point, and edgepoint tags as shown below. It is recommended that id and parent node tags always be included.

   type exType struct {
	ID          string      `node:"id"`
	Parent      string      `node:"parent"`
	Description string      `point:"description"`
	Count       int         `point:"count"`
	Role        string      `edgepoint:"role"`
	Tombstone   bool        `edgepoint:"tombstone"`
	Conditions  []Condition `child:"condition"`
   }

outputStruct can also be a *reflect.Value

Some consideration is needed when using Decode and MergePoints to decode points into Go slices. Slices are never allocated / copied unless they are being expanded. Instead, deleted points are written to the slice as the zero value. However, for a given Decode call, if points are deleted from the end of the slice, Decode will re-slice it to remove those values from the slice. Thus, there is an important consideration for clients: if they wish to rely on slices being truncated when points are deleted, points must be batched in order such that Decode sees the trailing deleted points first. Put another way, Decode does not care about points deleted from prior calls to Decode, so "holes" of zero values may still appear at the end of a slice under certain circumstances. Consider points with integer values [0, 1, 2, 3, 4]. If tombstone is set on point with Key 3 followed by a point tombstone set on point with Key 4, the resulting slice will be [0, 1, 2] if these points are batched together, but if they are sent separately (thus resulting in multiple Decode calls), the resulting slice will be [0, 1, 2, 0].

func DecodeSerialHrPayload

func DecodeSerialHrPayload(payload []byte, callback func(Point)) error

DecodeSerialHrPayload decodes a serial high-rate payload. Payload format.

  • type (off:0, 16 bytes) point type
  • key (off:16, 16 bytes) point key
  • starttime (off:32, uint64) starting time of samples in ns since Unix Epoch
  • sampleperiod (off:40, uint32) time between samples in ns
  • data (off:44) packed 32-bit floating point samples

func FindNodeInStruct

func FindNodeInStruct(outputStruct interface{}, nodeID string, parentID string) reflect.Value

FindNodeInStruct recursively scans the `outputStruct` for a struct with a field having a `node:"id"` tag and whose value matches `nodeID`. If `parentID` is provided, the struct must also have a field with a `node:"parent"` tag whose value matches `parentID`. If such a struct is found, the struct is returned as a reflect.Value; otherwise, an invalid reflect.Value is returned whose IsValid method returns false.

func FloatToBool

func FloatToBool(v float64) bool

FloatToBool converts a float to bool

func MergeEdgePoints

func MergeEdgePoints(id, parent string, points []Point, outputStruct interface{}) error

MergeEdgePoints takes edge points and updates a type that matching edgepoint tags. See Decode for an example type.

func MergePoints

func MergePoints(id string, points []Point, outputStruct interface{}) error

MergePoints takes points and updates fields in a type that have matching point tags. See Decode for an example type. When deleting points from arrays, the point key (index) is ignored and the last entry from the array is removed. Normally, it is recommended to send all points for an array when doing complex modifications to an array.

func ToCamelCase

func ToCamelCase(s string) string

ToCamelCase naively converts a string to camelCase. This function does not consider common initialisms.

Types

type Auth

type Auth struct {
	Token string `json:"token"`
	Email string `json:"email"`
}

Auth is an authentication response.

type ByEdgeID

type ByEdgeID []*Edge

ByEdgeID implements sort interface for NodeEdge by ID

func (ByEdgeID) Len

func (a ByEdgeID) Len() int

func (ByEdgeID) Less

func (a ByEdgeID) Less(i, j int) bool

func (ByEdgeID) Swap

func (a ByEdgeID) Swap(i, j int)

type ByHash

type ByHash []*Edge

ByHash implements sort interface for NodeEdge by Hash

func (ByHash) Len

func (a ByHash) Len() int

func (ByHash) Less

func (a ByHash) Less(i, j int) bool

func (ByHash) Swap

func (a ByHash) Swap(i, j int)

type ByTypeKey

type ByTypeKey []Point

ByTypeKey can be used to sort points by type then key

func (ByTypeKey) Len

func (b ByTypeKey) Len() int

func (ByTypeKey) Less

func (b ByTypeKey) Less(i, j int) bool

func (ByTypeKey) Swap

func (b ByTypeKey) Swap(i, j int)

type Edge

type Edge struct {
	ID     string `json:"id"`
	Up     string `json:"up"`
	Down   string `json:"down"`
	Points Points `json:"points"`
	Hash   uint32 `json:"hash"`
	Type   string `json:"type"`
}

Edge is used to describe the relationship between two nodes

func (*Edge) IsTombstone

func (e *Edge) IsTombstone() bool

IsTombstone returns true of edge points to a deleted node

func (Edge) String

func (e Edge) String() string

type Event

type Event struct {
	Time    time.Time
	Type    EventType
	Level   EventLevel
	Message string
}

Event describes something that happened and might be displayed to user in a a sequential log format.

type EventLevel

type EventLevel int

EventLevel is used to describe the "severity" of the event and can be used to quickly filter the type of events

const (
	EventLevelFault EventLevel = 3
	EventLevelInfo
	EventLevelDebug
)

define valid events

type EventType

type EventType int

EventType describes an event. Custom applications that build on top of Simple IoT should custom event types at high number above 10,000 to ensure there is not a collision between type IDs. Note, these enums should never change.

const (
	EventTypeStartSystem EventType = 10
	EventTypeStartApp
	EventTypeSystemUpdate
	EventTypeAppUpdate
)

define valid events

type GpsPos

type GpsPos struct {
	Lat    float64 `json:"lat"`
	Long   float64 `json:"long"`
	Fix    string  `json:"fix"`
	NumSat int64   `json:"numSat"`
}

GpsPos describes location and fix information from a GPS

func (*GpsPos) FromGPGGA

func (p *GpsPos) FromGPGGA(gpgga nmea.GPGGA)

FromGPGGA converts a GPGGA string to a position/fix

type GroupedPoints

type GroupedPoints struct {
	// KeyNotIndex is set to a Point's `Key` field if it *cannot* be parsed as a
	// positive integer
	// Note: If `Key` is empty string (""), it is treated as "0"
	KeyNotIndex string
	// KeyMaxInt is the largest `Point.Key` value in Points
	KeyMaxInt int
	// Points is the list of Points for this group
	Points []Point
}

GroupedPoints are Points grouped by their `Point.Type`. While scanning through the list of points, we also keep track of whether or not the points are keyed with positive integer values (for decoding into arrays)

func (GroupedPoints) SetValue

func (g GroupedPoints) SetValue(v reflect.Value) error

SetValue populates v with the Points in the group

type HistoryAggregatedPoint

type HistoryAggregatedPoint struct {
	Time time.Time `json:"time"`

	// NodeTags (i.e. "id", "description", "type", and others)
	NodeTags map[string]string `json:"nodeTags"`

	// Type of point (voltage, current, key, etc)
	Type string `json:"type,omitempty"`

	// Key is used to allow a group of points to represent a map or array
	Key string `json:"key,omitempty"`

	// Arithmetic mean of the point values in the aggregated window
	Mean float64 `json:"mean"`

	// Minimum point value in the aggregated window
	Min float64 `json:"min"`

	// Maximum point value in the aggregated window
	Max float64 `json:"max"`

	// Count is the number of points in the aggregated window
	Count int64 `json:"count"`
}

HistoryAggregatedPoint is a group of aggregated points of a history query

type HistoryPoint

type HistoryPoint struct {
	Time time.Time `json:"time"`

	// NodeTags (i.e. "id", "description", "type", and others)
	NodeTags map[string]string `json:"nodeTags"`

	// Type of point (voltage, current, key, etc)
	Type string `json:"type,omitempty"`

	// Key is used to allow a group of points to represent a map or array
	Key string `json:"key,omitempty"`

	// Instantaneous analog or digital value of the point.
	// 0 and 1 are used to represent digital values
	Value float64 `json:"value,omitempty"`

	// Optional text value of the point for data that is best represented
	// as a string rather than a number.
	Text string `json:"text,omitempty"`
}

HistoryPoint is a point returned by a non-aggregated history query

type HistoryQuery

type HistoryQuery struct {
	Start           time.Time      `json:"start"`
	Stop            time.Time      `json:"stop"`
	TagFilters      TagFilters     `json:"tagFilters"`
	AggregateWindow *time.Duration `json:"aggregateWindow"`
}

HistoryQuery is a query that is sent to an Influx DB client to request historical points

func (HistoryQuery) Execute

func (qry HistoryQuery) Execute(
	ctx context.Context,
	api api.QueryAPI,
	bucket, measurement string,
	results *HistoryResults,
)

Execute generates the Flux query and executes it, populating the specified HistoryResults

func (HistoryQuery) Flux

func (qry HistoryQuery) Flux(bucket, measurement string) (string, error)

Flux generates a Flux query for the HistoryQuery. Returns an error if tag filters could not be sanitized.

type HistoryResults

type HistoryResults struct {
	ErrorMessage     string                   `json:"error,omitempty"`
	Points           []HistoryPoint           `json:"points,omitempty"`
	AggregatedPoints []HistoryAggregatedPoint `json:"aggregatedPoints,omitempty"`
}

HistoryResults is the result of a history query. The result includes an optional error string along with a slice of either points or aggregated points.

type Message

type Message struct {
	ID             string
	UserID         string
	ParentID       string
	NotificationID string
	Email          string
	Phone          string
	Subject        string
	Message        string
}

Message describes a notification that is sent to a particular user

func PbDecodeMessage

func PbDecodeMessage(data []byte) (Message, error)

PbDecodeMessage converts a protobuf to a message data structure

func (*Message) ToPb

func (m *Message) ToPb() ([]byte, error)

ToPb converts to protobuf data

type MsgService

type MsgService struct {
	ID        string
	Service   string
	SID       string
	AuthToken string
	From      string
}

MsgService is used to represent message services such as Twilio, SMTP, etc

func NodeToMsgService

func NodeToMsgService(node Node) (MsgService, error)

NodeToMsgService converts a node to message service

type Node

type Node struct {
	ID     string `json:"id"`
	Type   string `json:"type"`
	Points Points `json:"points"`
}

Node represents the state of a device. UUID is recommended for ID to prevent collisions is distributed instances.

func (*Node) Desc

func (n *Node) Desc() string

Desc returns Description if set, otherwise ID

func (*Node) GetState

func (n *Node) GetState() (string, bool)

GetState checks state of node and returns true if state was updated. We originally considered offline to be when we did not receive data from a remote device for X minutes. However, with points that could represent a config change as well. Eventually we may want to improve this to look at point types (perhaps Sample).

func (*Node) State

func (n *Node) State() string

State returns the current state of a device

func (Node) String

func (n Node) String() string

func (*Node) ToNodeEdge

func (n *Node) ToNodeEdge(edge Edge) NodeEdge

ToNodeEdge converts to data structure used in API requests

func (*Node) ToUser

func (n *Node) ToUser() User

ToUser converts a node to user struct

type NodeCmd

type NodeCmd struct {
	ID     string `json:"id,omitempty"`
	Cmd    string `json:"cmd"`
	Detail string `json:"detail,omitempty"`
}

NodeCmd represents a command to be sent to a device

type NodeEdge

type NodeEdge struct {
	ID         string `json:"id"`
	Type       string `json:"type"`
	Hash       uint32 `json:"hash" yaml:"-"`
	Parent     string `json:"parent"`
	Points     Points `json:"points,omitempty"`
	EdgePoints Points `json:"edgePoints,omitempty"`
}

NodeEdge combines node and edge data, used for APIs

func Encode

func Encode(in any) (NodeEdge, error)

Encode is used to convert a user struct to a node. in must be a struct type that contains node, point, and edgepoint tags as shown below. It is recommended that id and parent node tags always be included.

   type exType struct {
	ID          string  `node:"id"`
	Parent      string  `node:"parent"`
	Description string  `point:"description"`
	Count       int     `point:"count"`
	Role        string  `edgepoint:"role"`
	Tombstone   bool    `edgepoint:"tombstone"`
   }

func PbDecodeNode

func PbDecodeNode(data []byte) (NodeEdge, error)

PbDecodeNode converts a protobuf to node data structure

func PbDecodeNodeRequest

func PbDecodeNodeRequest(buf []byte) (NodeEdge, error)

PbDecodeNodeRequest converts a protobuf to node data structure

func PbDecodeNodes

func PbDecodeNodes(data []byte) ([]NodeEdge, error)

PbDecodeNodes decode probuf encoded nodes

func PbDecodeNodesRequest

func PbDecodeNodesRequest(data []byte) ([]NodeEdge, error)

PbDecodeNodesRequest decode probuf encoded nodes

func PbToNode

func PbToNode(pbNode *pb.Node) (NodeEdge, error)

PbToNode converts pb node to node

func RemoveDuplicateNodesID

func RemoveDuplicateNodesID(nodes []NodeEdge) []NodeEdge

RemoveDuplicateNodesID removes duplicate nodes in list with the same ID (can have different parents)

func RemoveDuplicateNodesIDParent

func RemoveDuplicateNodesIDParent(nodes []NodeEdge) []NodeEdge

RemoveDuplicateNodesIDParent removes duplicate nodes in list with the same ID and parent

func (*NodeEdge) AddPoint

func (n *NodeEdge) AddPoint(pIn Point)

AddPoint takes a point for a device and adds/updates its array of points

func (NodeEdge) CalcHash

func (n NodeEdge) CalcHash(children []NodeEdge) uint32

CalcHash calculates the hash for a node

func (NodeEdge) Desc

func (n NodeEdge) Desc() string

Desc returns Description if set, otherwise ID

func (NodeEdge) IsTombstone

func (n NodeEdge) IsTombstone() (bool, time.Time)

IsTombstone returns Tombstone value and timestamp

func (NodeEdge) String

func (n NodeEdge) String() string

func (*NodeEdge) ToNode

func (n *NodeEdge) ToNode() Node

ToNode converts to structure stored in db

func (*NodeEdge) ToPb

func (n *NodeEdge) ToPb() ([]byte, error)

ToPb encodes a node to a protobuf

func (*NodeEdge) ToPbNode

func (n *NodeEdge) ToPbNode() (*pb.Node, error)

ToPbNode converts a node to pb.Node type

type NodeEdgeChildren

type NodeEdgeChildren struct {
	NodeEdge `yaml:",inline"`
	Children []NodeEdgeChildren `yaml:",omitempty"`
}

NodeEdgeChildren is used to pass a tree node structure into the decoder

func (NodeEdgeChildren) String

func (ne NodeEdgeChildren) String() string

type NodeVersion

type NodeVersion struct {
	OS  string `json:"os"`
	App string `json:"app"`
	HW  string `json:"hw"`
}

NodeVersion represents the device SW version

type Nodes

type Nodes []NodeEdge

Nodes defines a list of nodes

func (*Nodes) ToPb

func (nodes *Nodes) ToPb() ([]byte, error)

ToPb converts a list of nodes to protobuf

func (*Nodes) ToPbNodes

func (nodes *Nodes) ToPbNodes() ([]*pb.Node, error)

ToPbNodes converts a list of nodes to protobuf nodes

type Notification

type Notification struct {
	ID         string `json:"id"`
	Parent     string `json:"parent"`
	SourceNode string `json:"sourceNode"`
	Subject    string `json:"subject"`
	Message    string `json:"message"`
}

Notification represents a message sent by a node

func PbDecodeNotification

func PbDecodeNotification(data []byte) (Notification, error)

PbDecodeNotification converts a protobuf to notification data structure

func (*Notification) ToPb

func (n *Notification) ToPb() ([]byte, error)

ToPb converts to protobuf data

type Point

type Point struct {

	// Type of point (voltage, current, key, etc)
	Type string `json:"type,omitempty"`

	// Key is used to allow a group of points to represent a map or array
	Key string `json:"key,omitempty"`

	// Time the point was taken
	Time time.Time `json:"time,omitempty" yaml:"-"`

	// Instantaneous analog or digital value of the point.
	// 0 and 1 are used to represent digital values
	Value float64 `json:"value,omitempty"`

	// Optional text value of the point for data that is best represented
	// as a string rather than a number.
	Text string `json:"text,omitempty"`

	// catchall field for data that does not fit into float or string --
	// should be used sparingly
	Data []byte `json:"data,omitempty"`

	// Used to indicate a point has been deleted. This value is only
	// ever incremented. Odd values mean point is deleted.
	Tombstone int `json:"tombstone,omitempty"`

	// Where did this point come from. If from the owning node, it may be blank.
	Origin string `json:"origin,omitempty"`
}

Point is a flexible data structure that can be used to represent a sensor value or a configuration parameter. Type, and Key uniquely identify a point in a node. Using the Key field, maps and arrays can be represented. Array would have key values like: "0", "1", "2", "3", ... A map might have key values like "min", "max", "average", etc.

func PbToPoint

func PbToPoint(sPb *pb.Point) (Point, error)

PbToPoint converts pb point to point

func SerialToPoint

func SerialToPoint(sPb *pb.SerialPoint) (Point, error)

SerialToPoint converts serial pb point to point

func (*Point) Bool

func (p *Point) Bool() bool

Bool returns a bool representation of value

func (Point) CRC

func (p Point) CRC() uint32

CRC returns a CRC for the point

func (Point) IsMatch

func (p Point) IsMatch(typ, key string) bool

IsMatch returns true if the point matches the params passed in

func (Point) String

func (p Point) String() string

func (Point) ToPb

func (p Point) ToPb() (pb.Point, error)

ToPb encodes point in protobuf format

func (Point) ToSerial

func (p Point) ToSerial() (pb.SerialPoint, error)

ToSerial encodes point in serial protobuf format

type PointAverager

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

PointAverager accumulates points, and averages them. The average can be reset.

func NewPointAverager

func NewPointAverager(pointType string) *PointAverager

NewPointAverager initializes and returns an averager

func (*PointAverager) AddPoint

func (pa *PointAverager) AddPoint(s Point)

AddPoint takes a point, and adds it to the total

func (*PointAverager) GetAverage

func (pa *PointAverager) GetAverage() Point

GetAverage returns the average of the accumulated points

func (*PointAverager) ResetAverage

func (pa *PointAverager) ResetAverage()

ResetAverage sets the accumulated total to zero

type PointFilter

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

PointFilter is used to send points upstream. It only sends the data has changed, and at a max frequency

func NewPointFilter

func NewPointFilter(minSend, periodicSend time.Duration) *PointFilter

NewPointFilter is used to creat a new point filter If points have changed that get sent out at a minSend interval frequency of minSend. All points are periodically sent at lastPeriodicSend interval. Set minSend to 0 for things like config settings where you want them to be sent whenever anything changes.

func (*PointFilter) Add

func (sf *PointFilter) Add(points []Point) []Point

Add adds points and returns points that meet the filter criteria

type Points

type Points []Point

Points is an array of Point

func DiffPoints

func DiffPoints[T any](before, after T) (Points, error)

DiffPoints compares a before and after struct and generates the set of Points that represent their differences.

func PbDecodePoints

func PbDecodePoints(data []byte) (Points, error)

PbDecodePoints decode protobuf encoded points

func PbDecodeSerialPoints

func PbDecodeSerialPoints(d []byte) (Points, error)

PbDecodeSerialPoints can be used to decode serial points

func (*Points) Add

func (ps *Points) Add(pIn Point)

Add takes a point and updates an existing array of points. Existing points are replaced if the Timestamp in pIn is > than the existing timestamp. If the pIn timestamp is zero, the current time is used.

func (*Points) Collapse

func (ps *Points) Collapse()

Collapse is used to merge any common points and keep the latest

func (Points) Desc

func (ps Points) Desc() string

Desc returns a Description of a set of points

func (Points) Find

func (ps Points) Find(typ, key string) (Point, bool)

Find fetches a point given ID, Type, and Index and true of found, or false if not found

func (*Points) Hash

func (ps *Points) Hash() uint32

Hash returns the hash of points

func (*Points) LatestTime

func (ps *Points) LatestTime() time.Time

LatestTime returns the latest timestamp of a devices points

func (Points) Len

func (ps Points) Len() int

Len returns the number of points

func (Points) Less

func (ps Points) Less(i, j int) bool

Less is required by sort.Interface

func (*Points) Merge

func (ps *Points) Merge(in Points, maxTime time.Duration) Points

Merge is used to update points. Any points that are changed are returned. maxDuration can be used to return points if they have not been updated in maxDuration -- this can be used to send out points every X duration even if they are not changing which is useful for making graphs look nice. Set maxTime to zero to disable.

func (Points) String

func (ps Points) String() string

func (Points) Swap

func (ps Points) Swap(i, j int)

Swap is required by sort.Interface

func (*Points) Text

func (ps *Points) Text(typ, key string) (string, bool)

Text fetches a text value from an array of points given Type and Key. If ID or Type are set to "", they are ignored.

func (*Points) ToPb

func (ps *Points) ToPb() ([]byte, error)

ToPb encodes an array of points into protobuf

func (*Points) Value

func (ps *Points) Value(typ, key string) (float64, bool)

Value fetches a value from an array of points given ID, Type, and Index. If ID or Type are set to "", they are ignored.

func (*Points) ValueBool

func (ps *Points) ValueBool(typ, key string) (bool, bool)

ValueBool returns value as bool

func (*Points) ValueInt

func (ps *Points) ValueInt(typ, key string) (int, bool)

ValueInt returns value as integer

type StandardResponse

type StandardResponse struct {
	Success bool   `json:"success"`
	Error   string `json:"error,omitempty"`
	ID      string `json:"id,omitempty"`
}

StandardResponse is the standard response to any request

type SwUpdateState

type SwUpdateState struct {
	Running     bool   `json:"running"`
	Error       string `json:"error"`
	PercentDone int    `json:"percentDone"`
}

SwUpdateState represents the state of an update

func (*SwUpdateState) Points

func (sws *SwUpdateState) Points() Points

Points converts SW update state to node points

type TagFilters

type TagFilters map[string]any

TagFilters further reduces Influx query results by tag Map values may be strings or a slice of strings

func (TagFilters) Flux

func (t TagFilters) Flux(sb *strings.Builder) error

Flux writes a clause for a Flux query (to be added to the filter function body) to the specified string.Builder. Returns an error if a tag filter could not be sanitized.

type TimeWindowAverager

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

TimeWindowAverager accumulates points, and averages them on a fixed time period and outputs the average/min/max, etc as a point

func NewTimeWindowAverager

func NewTimeWindowAverager(windowLen time.Duration, callBack func(Point), pointType string) *TimeWindowAverager

NewTimeWindowAverager initializes and returns an averager

func (*TimeWindowAverager) NewPoint

func (twa *TimeWindowAverager) NewPoint(s Point)

NewPoint takes a point, and if the time window expired, it calls the callback function with the a new point which is avg of all points since start time.

type User

type User struct {
	ID        string `json:"id"`
	FirstName string `json:"firstName"`
	LastName  string `json:"lastName"`
	Phone     string `json:"phone"`
	Email     string `json:"email"`
	Pass      string `json:"pass"`
}

User represents a user of the system

func NodeToUser

func NodeToUser(node Node) (User, error)

NodeToUser converts a node to a user

func (*User) ToNode

func (u *User) ToNode() Node

ToNode converts a user structure into a node

func (*User) ToPoints

func (u *User) ToPoints() Points

ToPoints converts a user structure into points

Jump to

Keyboard shortcuts

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