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
- Variables
- func BoolToFloat(v bool) float64
- func CheckPassword(stored, candidate string) (ok, needsRehash bool)
- func Decode(input NodeEdgeChildren, outputStruct any) error
- func DecodeSerialHrPayload(payload []byte, callback func(Point)) error
- func EncodeNodes(nodes Nodes, err error) []byte
- func FindNodeInStruct(outputStruct interface{}, nodeID string, parentID string) reflect.Value
- func FloatToBool(v float64) bool
- func HashPassword(plain string) (string, error)
- func MQTTFilterToSubject(filter string) (string, error)
- func MQTTSubjectToTopic(subject string) string
- func MQTTTopicToSubject(topic string) (string, error)
- func MergeEdgePoints(id, parent string, points []Point, outputStruct interface{}) error
- func MergePoints(id string, points []Point, outputStruct interface{}) error
- func NodeTypeIsPrimary(typ string) bool
- func NodeTypeOwner(typ string) string
- func PasswordIsHashed(stored string) bool
- func SameValue(a, b Point) bool
- func SubjectSafeToken(s string) string
- func ToCamelCase(s string) string
- type Auth
- type ByEdgeID
- type ByTypeKey
- type Edge
- type EdgeRole
- type Event
- type EventLevel
- type EventType
- type GpsPos
- type GroupedPoints
- type Message
- type Node
- type NodeCmd
- type NodeEdge
- type NodeEdgeChildren
- type NodeFile
- type NodeVersion
- type NodeYAML
- type Nodes
- type Notification
- type Point
- func (p *Point) Bool() bool
- func (p Point) CRC() uint32
- func (p Point) CheckSubjectTokens() error
- func (p Point) Encode(buf *bytes.Buffer)
- func (p Point) IsMatch(typ, key string) bool
- func (p Point) MarshalJSON() ([]byte, error)
- func (p Point) MarshalYAML() (interface{}, error)
- func (p Point) Numeric() bool
- func (p *Point) PutFloat(v float64)
- func (p *Point) PutInt(v int64)
- func (p *Point) PutString(v string)
- func (p Point) String() string
- func (p Point) Txt() string
- func (p *Point) UnmarshalJSON(b []byte) error
- func (p *Point) UnmarshalYAML(unmarshal func(interface{}) error) error
- func (p Point) Val() float64
- func (p *Point) ValueFloat() (float64, error)
- func (p *Point) ValueInt() (int64, error)
- func (p *Point) ValueString() (string, error)
- type PointAverager
- type PointDataType
- type PointFilter
- type PointOld
- type Points
- func (ps *Points) Add(pIn Point)
- func (ps *Points) Collapse()
- func (ps Points) Desc() string
- func (ps *Points) Encode() []byte
- func (ps Points) Find(typ, key string) (Point, bool)
- func (ps *Points) Hash() uint32
- func (ps *Points) LatestTime() time.Time
- func (ps Points) Len() int
- func (ps Points) Less(i, j int) bool
- func (ps Points) MatchKey() string
- func (ps *Points) Merge(in Points, maxTime time.Duration) Points
- func (ps Points) String() string
- func (ps Points) Swap(i, j int)
- func (ps *Points) Text(typ, key string) (string, bool)
- func (ps *Points) Value(typ, key string) (float64, bool)
- func (ps *Points) ValueBool(typ, key string) (bool, bool)
- func (ps *Points) ValueInt(typ, key string) (int, bool)
- type StandardResponse
- type SwUpdateState
- type TimeWindowAverager
- type User
Constants ¶
const ( CmdUpdateApp = "updateApp" CmdPoll = "poll" CmdFieldMode = "fieldMode" )
define valid commands
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" // Edge points that say what an edge means for the node below it. // A node that owns something outside the tree -- a bus, a line, a // socket -- has one primary edge that runs its client, and any // number of mirror edges that exist for organization and access // control and run nothing. Edges for nodes with no primary location, // such as a user or a group, carry neither point. See // docs/ref/data.md#primary-and-mirror-edges. PointTypePrimary = "primary" PointTypeMirror = "mirror" 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" PointTypeTimeout = "timeout" 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" // PointTypeExpandKeyLabels writes each label in a point key that was // written as a label set -- name=value pairs joined by commas, which is // what a Prometheus scrape produces -- as its own database label, so a // scraped series queries the way the Prometheus series it came from did. // The parse is strict, so keys from every other client are left alone. PointTypeExpandKeyLabels = "expandKeyLabels" // PointTypeDbType selects which time series database the db client // writes to. An empty value is treated as InfluxDB for backwards // compatibility. PointTypeDbType = "dbType" PointValueInfluxDb = "influxdb" PointValueVictoriaMetrics = "victoriaMetrics" // 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" PointTypeMinInactive = "minInactive" NodeTypeAction = "action" NodeTypeActionInactive = "actionInactive" PointTypeAction = "action" PointValueNotify = "notify" PointValueSetValue = "setValue" PointValuePlayAudio = "playAudio" PointTypeRepeatInterval = "repeatInterval" // Notifications and messages travel as points carrying a JSON payload // (see data/notification.go and data/message.go). A notification says // what happened; a message says what happened and who to send it to. // Both use a fixed key so a node carries only its most recent one -- // history lives in the JetStream stream. PointTypeNotification = "notification" PointTypeMessage = "message" NodeTypeMsgService = "msgService" PointTypeService = "service" PointValueTwilio = "twilio" PointValueSMTP = "smtp" PointValueNtfy = "ntfy" PointTypeSID = "sid" PointTypeAuthToken = "authToken" PointTypeFrom = "from" PointTypeUsername = "username" PointTypeTopic = "topic" // MQTT clients. An mqtt node holds the connection -- a blank uri means the // broker built into this instance -- and its mqttSub children map topics // into points. NodeTypeMqtt = "mqtt" NodeTypeMqttSub = "mqttSub" // NodeTypeMqttDevice is created automatically from a topic schema and // holds the points extracted from the topics below it. NodeTypeMqttDevice = "mqttDevice" // PointTypeTopicSchema names the levels of a topic, such as // "{site}/{gateway}/{device}", so nodes can be created from topics as they // arrive. Plain MQTT says nothing about which level is which, and this // supplies exactly that. PointTypeTopicSchema = "topicSchema" // PointTypeMaxNodes bounds how many nodes a topic schema creates, so a // topic level carrying an unbounded value cannot grow the tree without // limit. PointTypeMaxNodes = "maxNodes" // PointTypePath locates the value inside a JSON payload, written in dot // notation such as $.a.b[0]. A blank path maps the whole payload. PointTypePath = "path" // PointTypeSparkplug enables Sparkplug B handling on an mqtt node. Birth // certificates describe every metric, so the nodes below are created from // the data rather than configured. PointTypeSparkplug = "sparkplug" NodeTypeSparkplugGroup = "sparkplugGroup" NodeTypeSparkplugNode = "sparkplugNode" NodeTypeSparkplugDevice = "sparkplugDevice" // PointTypeSparkplugAlias holds the alias assignments from an edge node's // birth certificates as a JSON object of alias to metric name. Keeping it // on the sparkplugNode node means data that arrives after a restart // resolves straight away rather than waiting for a rebirth. PointTypeSparkplugAlias = "sparkplugAlias" NodeTypeVariable = "variable" PointTypeVariableType = "variableType" NodeTypeSync = "sync" // NodeTypeDeviceCred is a credential for one device. It sits under the // device node on the upstream and holds only the public key; the // authorizer scopes a connection presenting the matching seed to that // device's data. The seed stays in a file on the device (never a point, // since a device's points replicate upstream) and the device's sync // nodes carry the public key so it can be read off the device. See // docs/ref/security.md. NodeTypeDeviceCred = "deviceCred" PointTypePubKey = "pubKey" PointTypeLastConnect = "lastConnect" // PointTypePending marks a credential a device enrolled itself with // that an operator has not approved yet. It authorizes nothing until // cleared. PointTypePending = "pending" // NodeTypeEnrollToken is a fleet-wide token, kept under the upstream // root, that lets a device with no credential ask for one. It holds // only a hash of the token. A sync node carries the token itself as // enrollToken. NodeTypeEnrollToken = "enrollToken" PointTypeTokenHash = "tokenHash" PointTypeAutoApprove = "autoApprove" PointTypeExpires = "expires" PointTypeEnrollToken = "enrollToken" PointTypeMetricNatsCycleNodePoint = "metricNatsCycleNodePoint" PointTypeMetricNatsCycleNodeEdgePoint = "metricNatsCycleNodeEdgePoint" PointTypeMetricNatsCycleNode = "metricNatsCycleNode" PointTypeMetricNatsCycleNodeChildren = "metricNatsCycleNodeChildren" PointTypeMetricNatsPendingNodePoint = "metricNatsPendingNodePoint" PointTypeMetricNatsPendingNodeEdgePoint = "metricNatsPendingNodeEdgePoint" PointTypeMetricNatsThroughputNodePoint = "metricNatsThroughputNodePoint" PointTypeMetricNatsThroughputNodeEdgePoint = "metricNatsThroughputNodeEdgePoint" // serial MCU clients NodeTypeSerialDev = "serialDev" // PointTypeProtocol on a serialDev node selects the wire protocol. // An empty value means PointValueProtocolBinary so existing nodes // keep working with no migration. PointValueProtocolBinary = "binary" // COBS framed binary packets PointValueProtocolShell = "shell" // Zephyr console shell, ASCII // PointTypeLogConsole mirrors the MCU console to the SIOT server log. // Shell protocol only. PointTypeLogConsole = "logConsole" 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" // Browser PointTypeURL = "url" PointTypeRotate = "rotate" PointTypeKeyboardScale = "keyboardscale" PointTypeFullscreen = "fullscreen" PointTypeDefaultDialogs = "defaultdialogs" PointTypeDialogColor = "dialogcolor" PointTypeTouchQuirk = "touchquirk" PointTypeRetryInterval = "retryinterval" PointTypeExceptionURL = "exceptionurl" PointTypeIgnoreCertErr = "ignorecerterr" PointTypeDisableSandbox = "disablesandbox" PointTypeDebugPort = "debugport" PointTypeScreenResolution = "screenresolution" PointTypeDisplayCard = "displaycard" 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" // PointTypeCreated is when a node came into existence, written once and // never rewritten, which is what orders provisioning files uploaded // through the UI. PointTypeCreated = "created" // provisioning reads files from a directory and from file nodes under the // provisioning node, applying each one the way siot import does NodeTypeProvisioning = "provisioning" NodeTypeProvisioningFile = "provisioningFile" // PointTypeProvisionHash is the SHA-256 of the contents provisioning last // applied from a source. It is distinct from PointTypeHash, which the file // client maintains to describe the contents themselves. PointTypeProvisionHash = "provisionHash" PointTypeRate = "rate" PointTypeRateHR = "rateHR" NodeTypeMetrics = "metrics" PointTypeType = "type" PointValueApp = "app" PointValueProcess = "process" PointValueAllProcesses = "allProcesses" PointValueSystem = "system" PointValuePrometheus = "prometheus" // PointTypeCounterDelta enables publishing a per-period delta alongside // the raw value of each counter a Prometheus endpoint reports. A counter // is monotonic, so the raw value answers "how many since start" while the // delta answers "how many this period", which is the reading a rule can // act on. PointTypeCounterDelta = "counterDelta" // PointTypeMaxSeries bounds how many samples a single scrape publishes, // so an endpoint with more series than expected cannot grow one node out // of proportion to the rest of the tree. PointTypeMaxSeries = "maxSeries" // CounterDeltaSuffix is appended to a counter's metric name to form the // point type its per-period delta is published under. Prometheus reserves // _total, _sum, _count, and _bucket, so this cannot be mistaken for one // of its conventions. CounterDeltaSuffix = "_delta" PointTypeCount = "count" // Sys Metrics PointTypeMetricSysLoad = "metricSysLoad" PointTypeMetricSysCPUPercent = "metricSysCPUPercent" PointTypeMetricSysMem = "metricSysMem" PointTypeMetricSysMemUsedPercent = "metricSysMemUsedPercent" PointTypeMetricSysDiskUsedPercent = "metricSysDiskUsedPercent" PointTypeMetricSysNetBytesRecv = "metricSysNetBytesRecv" PointTypeMetricSysNetBytesSent = "metricSysNetBytesSent" PointTypeMetricSysUptime = "metricSysUptime" // current clock of a CPU in MHz, keyed by cpu0, cpu1, and so on PointTypeMetricSysCPUFreq = "metricSysCPUFreq" // fan tachometer reading in RPM PointTypeMetricSysFanSpeed = "metricSysFanSpeed" // fan drive level, 0-255, as reported by the hwmon pwm interface PointTypeMetricSysFanPWM = "metricSysFanPWM" // current state of a thermal cooling device. Anything above zero means // the thermal governor is limiting the system, so a rising cpufreq or // devfreq state is the system giving up performance to stay cool. PointTypeMetricSysCoolingState = "metricSysCoolingState" // highest state a cooling device supports, which gives the scale the // current state is measured against PointTypeMetricSysCoolingStateMax = "metricSysCoolingStateMax" // 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" // Points a Shelly device reports beyond the on/off state of its outputs. // Which ones appear depends on the components the device reports, not on // its model. See the shelly client. PointTypeGeneration = "gen" PointTypeModel = "model" PointTypeEnergy = "energy" PointTypeHumidity = "humidity" PointTypePosition = "position" PointTypePositionSet = "positionSet" PointTypeCoverState = "coverState" PointTypeBattery = "battery" PointTypeBatteryLevel = "batteryLevel" PointTypeExternalPower = "externalPower" PointTypePowerFactor = "powerFactor" PointTypeApparentPower = "apparentPower" PointTypeAlarm = "alarm" 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" // GPS client NodeTypeGPS = "gps" PointTypeGPSSource = "gpsSource" PointValueGPSSourceSerial = "serial" PointValueGPSSourceGpsd = "gpsd" PointValueGPSSourceSim = "sim" // GPS output points PointTypeLatitude = "latitude" // degrees, +N PointTypeLongitude = "longitude" // degrees, +E PointTypeAltitude = "altitude" // meters above mean sea level PointTypeSpeed = "speed" // meters/second over ground PointTypeHeading = "heading" // degrees true, 0-360 PointTypeNumSat = "numSat" // satellites used in fix PointTypeHDOP = "hdop" // horizontal dilution of precision PointTypeGPSTime = "gpsTime" // Unix epoch seconds reported by the source // Normalized GPS fix dimensionality, following gpsd's TPV mode encoding. // Numeric rather than a string enum so it can be stored in metrics-only // databases such as Victoria Metrics, which store strings as 0. PointTypeFixType = "fixType" PointValueFixNone = 0 // no fix, or fix status unknown PointValueFix2D = 2 PointValueFix3D = 3 // Normalized GPS fix augmentation quality, following the NMEA GGA fix // quality encoding, which covers every case the three sources report. PointTypeFixQuality = "fixQuality" PointValueFixQualityNone = 0 PointValueFixQualityGPS = 1 PointValueFixQualityDGPS = 2 PointValueFixQualityPPS = 3 PointValueFixQualityRTKFixed = 4 PointValueFixQualityRTKFloat = 5 PointValueFixQualityEstimated = 6 PointValueFixQualityManual = 7 PointValueFixQualitySimulated = 8 // GPS gpsd source config PointTypeGpsdAddress = "gpsdAddress" // host:port, default localhost:2947 // GPS simulation config PointTypeSimLatitude = "simLatitude" // starting latitude PointTypeSimLongitude = "simLongitude" // starting longitude PointTypeSimSpeed = "simSpeed" // meters/second PointTypeSimHeading = "simHeading" // starting heading, degrees true PointTypeSimHeadingRate = "simHeadingRate" // max heading change, degrees/second PointTypeSimReset = "simReset" // move the track back to the start // GPIO client. A gpio node is one line on a Linux GPIO character device. NodeTypeGPIO = "gpio" // Line selection. Chip is a chip name ("gpiochip0"), a chip label, a full // device path, or "sim" for a line with no hardware behind it. Line is a // line offset ("17") or the kernel's name for the line ("FLOAT_SW"). PointTypeChip = "chip" PointTypeLine = "line" // Resolved line identity, published by the client PointTypeLineOffset = "lineOffset" PointTypeLineName = "lineName" PointTypeDirection = "direction" PointValueInput = "input" PointValueOutput = "output" // Internal bias, inputs mainly. An empty value leaves the bias as-is. PointTypeBias = "bias" PointValuePullUp = "pullUp" PointValuePullDown = "pullDown" PointValueBiasDisabled = "biasDisabled" // Output drive. An empty value is push-pull. PointTypeDrive = "drive" PointValuePushPull = "pushPull" PointValueOpenDrain = "openDrain" PointValueOpenSource = "openSource" // ActiveLow inverts the line: a low line reads and drives as active PointTypeActiveLow = "activeLow" // Debounce is the kernel debounce period in ms, inputs only PointTypeDebounce = "debounce" // PointValueSim selects a simulated resource rather than a real one PointValueSim = "sim" // The Particle client connects to the Particle cloud and turns the // events it publishes into points. NodeTypeParticle = "particle" // The Browser client drives a browser on this host's display. NodeTypeBrowser = "browser" // IIO client. An iio node is one Linux Industrial I/O device -- an ADC, // a DAC, or a sensor the kernel presents through the same interface -- // and an iioChannel node is one channel on that device. NodeTypeIIO = "iio" NodeTypeIIOChannel = "iioChannel" // Resolved device identity, published by the IIO client PointTypeDeviceName = "deviceName" PointTypeDevicePath = "devicePath" // Device level IIO settings, written to sysfs when set PointTypeSampleFrequency = "sampleFrequency" PointTypeOversampling = "oversampling" // ChannelType is the measured quantity an IIO channel reports: // "voltage", "current", "temp", "accel", and so on. PointTypeChannelType = "channelType" // MinChange is how far a value must move from the last published one // before it is sent again, which keeps ADC noise out of the store. PointTypeMinChange = "minChange" )
define common node and point types that have special meaning in the system.
const NodeFileAPIVersion = 1
NodeFileAPIVersion is the format version this build writes and understands.
Variables ¶
var ErrDocumentNotFound = errors.New("document not found")
ErrDocumentNotFound is returned in APIs if document is not found
Functions ¶
func BoolToFloat ¶ added in v0.0.16
BoolToFloat converts bool to float
func CheckPassword ¶ added in v0.25.1
CheckPassword verifies a candidate password against the stored value, which may be a bcrypt hash or a legacy plaintext password. needsRehash is true when the check succeeded against a legacy value, meaning the stored password should be rewritten as a hash.
func Decode ¶ added in v0.3.0
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 ¶ added in v0.10.0
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 EncodeNodes ¶ added in v0.27.0
EncodeNodes serializes a node reply. The frame is: a version byte, an error string (empty on success), a uint32 node count, then each node as id, type, parent, points, and edge points, using the point encoding. The hash is not carried.
func FindNodeInStruct ¶ added in v0.12.4
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 ¶ added in v0.0.16
FloatToBool converts a float to bool
func HashPassword ¶ added in v0.25.1
HashPassword hashes a plaintext password for storage. bcrypt limits passwords to 72 bytes and returns an error for longer values.
func MQTTFilterToSubject ¶ added in v0.25.0
MQTTFilterToSubject converts an MQTT topic filter to a NATS subject, mapping the MQTT wildcards + and # onto the NATS wildcards * and >.
func MQTTSubjectToTopic ¶ added in v0.25.0
MQTTSubjectToTopic converts a NATS subject back to the MQTT topic it came from. It is the inverse of MQTTTopicToSubject and is how a client recovers the topic of a message delivered over NATS.
func MQTTTopicToSubject ¶ added in v0.25.0
MQTTTopicToSubject converts an MQTT topic name to the NATS subject the embedded broker publishes it on. Wildcards are not allowed in a topic name, so they are rejected here.
func MergeEdgePoints ¶ added in v0.3.0
MergeEdgePoints takes edge points and updates a type that matching edgepoint tags. See Decode for an example type.
func MergePoints ¶ added in v0.3.0
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 NodeTypeIsPrimary ¶ added in v0.26.1
NodeTypeIsPrimary reports whether a node of this type owns something outside the tree, so that exactly one of its edges may run a client. A type the system does not know -- one a user invents -- reports false and keeps behaving as it always has.
func NodeTypeOwner ¶ added in v0.26.1
NodeTypeOwner returns the parent type a node of this type must live under, or "" when the type may live anywhere. A modbusIo is found through its modbus bus, so moving it elsewhere leaves it inert.
func PasswordIsHashed ¶ added in v0.25.1
PasswordIsHashed reports whether a stored password value is a bcrypt hash.
func SameValue ¶ added in v0.22.0
SameValue reports whether two points say the same thing. Numbers are compared by value and text by string, rather than by their stored bytes, so that an integer 5 and a float 5 are one value and a file does not fight a client that writes its points with PutInt.
func SubjectSafeToken ¶ added in v0.23.2
SubjectSafeToken replaces every character that is not allowed in a point type or key with an underscore. It is for callers that generate keys from names they do not control, such as sysfs device names or network interface names. Data a device sends is never rewritten -- that is rejected instead, so the sender can be fixed.
func ToCamelCase ¶ added in v0.10.0
ToCamelCase naively converts a string to camelCase. This function does not consider common initialisms.
Types ¶
type ByEdgeID ¶ added in v0.0.30
type ByEdgeID []*Edge
ByEdgeID implements sort interface for NodeEdge by ID
type ByTypeKey ¶ added in v0.14.0
type ByTypeKey []Point
ByTypeKey can be used to sort points by type then key
type Edge ¶ added in v0.0.15
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 ¶ added in v0.0.30
IsTombstone returns true of edge points to a deleted node
type EdgeRole ¶ added in v0.26.1
type EdgeRole int
EdgeRole describes what an edge means for the node below it.
const ( // EdgeRoleNone is an edge for a node with no primary location -- a // user, a group, a rule. Several such edges are meaningful and each // one runs a client. Edges created before primary and mirror edge // points existed also read as EdgeRoleNone. EdgeRoleNone EdgeRole = iota // EdgeRolePrimary is the one edge that owns the node. The client runs // here. EdgeRolePrimary // EdgeRoleMirror is an edge that exists for organization or access // control. No client runs here. EdgeRoleMirror )
func EdgeRoleOf ¶ added in v0.26.1
EdgeRoleOf reads the role from a set of edge points. An edge carrying both points is treated as a mirror, because declining to run a client is the safe direction to fail.
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
type GroupedPoints ¶ added in v0.10.0
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)
type Message ¶ added in v0.0.23
type Message struct {
// NotificationID is carried through unchanged from the notification
// that generated this message, so a service can recognize two messages
// generated from one notification by different instances of a mirrored
// user node.
NotificationID string `json:"notificationID"`
UserID string `json:"userID"`
Phone string `json:"phone"`
Email string `json:"email"`
Subject string `json:"subject"`
Message string `json:"message"`
}
Message is a notification addressed to a particular user. It travels as a JSON payload in a point of type PointTypeMessage on the user node that generated it. Like notifications, the point uses a fixed (empty) key, so the user node carries only its most recent message.
func PointToMessage ¶ added in v0.24.0
PointToMessage decodes a message from a point.
type Node ¶ added in v0.0.12
Node represents the state of a device. UUID is recommended for ID to prevent collisions is distributed instances.
func (*Node) GetState ¶ added in v0.0.30
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) ToNodeEdge ¶ added in v0.0.15
ToNodeEdge converts to data structure used in API requests
type NodeCmd ¶ added in v0.0.12
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 ¶ added in v0.0.15
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 DecodeNodes ¶ added in v0.27.0
DecodeNodes deserializes a node reply made by EncodeNodes. An error the sender put in the frame is returned as the error; ErrDocumentNotFound is returned as that value so callers can compare against it. An empty payload decodes to no nodes.
func Encode ¶ added in v0.3.0
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 RemoveDuplicateNodesID ¶ added in v0.0.23
RemoveDuplicateNodesID removes duplicate nodes in list with the same ID (can have different parents)
func RemoveDuplicateNodesIDParent ¶ added in v0.0.23
RemoveDuplicateNodesIDParent removes duplicate nodes in list with the same ID and parent
func (*NodeEdge) AddPoint ¶ added in v0.0.44
AddPoint takes a point for a device and adds/updates its array of points
func (NodeEdge) EdgeRole ¶ added in v0.26.1
EdgeRole returns the role this edge plays for the node below it.
func (NodeEdge) IsTombstone ¶ added in v0.0.30
IsTombstone returns Tombstone value and timestamp
type NodeEdgeChildren ¶ added in v0.5.0
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 ¶ added in v0.14.0
func (ne NodeEdgeChildren) String() string
type NodeFile ¶ added in v0.22.0
type NodeFile struct {
APIVersion int `yaml:"apiVersion,omitempty"`
Nodes []NodeYAML `yaml:"nodes,omitempty"`
Delete []NodeYAML `yaml:"delete,omitempty"`
}
NodeFile is a file of nodes: what siot export writes, and what siot import and provisioning read.
type NodeVersion ¶ added in v0.0.12
NodeVersion represents the device SW version
type NodeYAML ¶ added in v0.22.0
type NodeYAML struct {
// Type is the node type, which is the key the rest of the body hangs from.
Type string
// Parent is the match key of the node this one attaches to, and is only
// meaningful on a top level entry.
Parent string
Points Points
EdgePoints Points
Children []NodeYAML
}
NodeYAML is one node in a node file. The node type is the key and each point type is a key of its own:
nodes:
- modbus:
description: Modbus sensors
port: /dev/ttyS1
baud: 9600
A file carries configuration and nothing else: no node IDs, no origins, and no points that carry no value.
func (NodeYAML) MarshalYAML ¶ added in v0.22.0
MarshalYAML implements the goccy/go-yaml InterfaceMarshaler.
func (NodeYAML) ToNodeEdge ¶ added in v0.22.0
ToNodeEdge converts to the structure the rest of the system passes around.
func (*NodeYAML) UnmarshalYAML ¶ added in v0.22.0
UnmarshalYAML implements the goccy/go-yaml BytesUnmarshaler. It works from the AST rather than decoding into Go values so that how a value is written decides what it becomes: 9600 is a numeric point, "9600" is a text one, and 1 and 1.5 are an integer and a float.
type Notification ¶ added in v0.0.23
type Notification struct {
// ID is a UUID assigned when the notification is raised. It is carried
// through to messages and used to deduplicate delivery.
ID string `json:"id"`
// SourceNode is the node that triggered the notification (for a rule,
// the node that satisfied the condition).
SourceNode string `json:"sourceNode"`
Subject string `json:"subject"`
Message string `json:"message"`
}
Notification describes something that happened that users may want to know about. It travels as a JSON payload in a point of type PointTypeNotification on the node that raised it, so it is persisted, synchronized between instances, and visible to clients like any other point. The point uses a fixed (empty) key, so a node carries only its most recent notification -- history lives in the JetStream stream.
func PointToNotification ¶ added in v0.24.0
func PointToNotification(p Point) (Notification, error)
PointToNotification decodes a notification from a point.
func (Notification) Point ¶ added in v0.24.0
func (n Notification) Point() (Point, error)
Point encodes the notification as a point ready to send to a node.
type Point ¶ added in v0.0.11
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:"-"`
// DataType describes what type of data we have
DataType PointDataType `json:"dataType,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 DecodePoint ¶ added in v0.19.0
DecodePoint deserializes a Point from binary data at offset.
func NewPointFloat ¶ added in v0.19.0
NewPointFloat creates a new Point with a float64 value
func NewPointInt ¶ added in v0.19.0
NewPointInt creates a new Point with an int value
func NewPointString ¶ added in v0.19.0
NewPointString creates a new Point with a string value
func (Point) CheckSubjectTokens ¶ added in v0.23.2
CheckSubjectTokens returns an error if the point type or key contains a character that is not allowed in a NATS subject token.
Points travel on subjects built from their type and key -- see client.SendPoints -- and listeners read the node ID and other routing information from fixed positions in the subject. A period in a type or key adds a token and shifts everything after it, so the point is delivered to the wrong handler. The store rejects such points on the way in, which keeps every subject the system publishes well formed.
func (Point) IsMatch ¶ added in v0.0.30
IsMatch returns true if the point matches the params passed in
func (Point) MarshalJSON ¶ added in v0.19.0
MarshalJSON encodes Point to JSON, including legacy value/text fields for backward compatibility.
func (Point) MarshalYAML ¶ added in v0.19.0
MarshalYAML encodes Point to YAML with legacy value/text fields for human readability. Implements goccy/go-yaml InterfaceMarshaler.
func (Point) Numeric ¶ added in v0.23.0
Numeric returns true if the point carries a numeric value. Points that hold strings or JSON return false, as does a point with an unknown data type.
func (Point) Txt ¶ added in v0.19.0
Txt returns the string value of the point. Returns "" for non-string types. This is a convenience method that mirrors the old Point.Text field access semantics.
func (*Point) UnmarshalJSON ¶ added in v0.19.0
UnmarshalJSON decodes Point from JSON, supporting both new (dataType/data) and legacy (value/text) fields.
func (*Point) UnmarshalYAML ¶ added in v0.19.0
UnmarshalYAML decodes Point from YAML, supporting both new (dataType/data) and legacy (value/text) fields. Implements goccy/go-yaml InterfaceUnmarshaler.
func (Point) Val ¶ added in v0.19.0
Val returns the float64 value of the point, converting from int if needed. Returns 0 for non-numeric types. This is a convenience method that mirrors the old Point.Value field access semantics.
func (*Point) ValueFloat ¶ added in v0.19.0
ValueFloat decodes a float value from the point
func (*Point) ValueString ¶ added in v0.19.0
ValueString returns a string value from the point
type PointAverager ¶ added in v0.0.23
type PointAverager struct {
// contains filtered or unexported fields
}
PointAverager accumulates points, and averages them. The average can be reset.
func NewPointAverager ¶ added in v0.0.23
func NewPointAverager(pointType string) *PointAverager
NewPointAverager initializes and returns an averager
func (*PointAverager) AddPoint ¶ added in v0.0.23
func (pa *PointAverager) AddPoint(s Point)
AddPoint takes a point, and adds it to the total
func (*PointAverager) GetAverage ¶ added in v0.0.23
func (pa *PointAverager) GetAverage() Point
GetAverage returns the average of the accumulated points
func (*PointAverager) ResetAverage ¶ added in v0.0.23
func (pa *PointAverager) ResetAverage()
ResetAverage sets the accumulated total to zero
type PointDataType ¶ added in v0.19.0
type PointDataType byte
PointDataType is the data sent over the wire
const ( PointDataTypeUnknown PointDataType = 0 PointDataTypeFloat PointDataType = 1 PointDataTypeInt PointDataType = 2 PointDataTypeString PointDataType = 3 PointDataTypeJSON PointDataType = 4 )
PointDataType defines
type PointFilter ¶ added in v0.0.11
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 ¶ added in v0.0.11
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 ¶ added in v0.0.11
func (sf *PointFilter) Add(points []Point) []Point
Add adds points and returns points that meet the filter criteria
type PointOld ¶ added in v0.19.0
type PointOld 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"`
}
PointOld old point struct
type Points ¶ added in v0.0.11
type Points []Point
Points is an array of Point
func DecodePoints ¶ added in v0.19.0
DecodePoints deserializes a Points array from binary data.
func DiffPoints ¶ added in v0.12.6
DiffPoints compares a before and after struct and generates the set of Points that represent their differences.
func (*Points) Add ¶ added in v0.0.44
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 ¶ added in v0.14.0
func (ps *Points) Collapse()
Collapse is used to merge any common points and keep the latest
func (*Points) Encode ¶ added in v0.19.0
Encode serializes a Points array to binary format: uint32 count + repeated Point.
func (Points) Find ¶ added in v0.0.30
Find fetches a point given ID, Type, and Index and true of found, or false if not found
func (*Points) LatestTime ¶ added in v0.0.11
LatestTime returns the latest timestamp of a devices points
func (Points) MatchKey ¶ added in v0.22.0
MatchKey returns the value that identifies a node when a file describes it by name rather than by ID, used by siot import and provisioning. Most nodes are identified by their description; a user has none, so an email address is used, and a name if there is no email.
This is deliberately separate from Desc, which prefers a name over a description for display.
func (*Points) Merge ¶ added in v0.10.0
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) Text ¶ added in v0.0.11
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) Value ¶ added in v0.0.11
Value fetches a value from an array of points given ID, Type, and Index. If ID or Type are set to "", they are ignored.
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 ¶ added in v0.0.9
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 ¶ added in v0.0.30
func (sws *SwUpdateState) Points() Points
Points converts SW update state to node points
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 ¶ added in v0.0.23
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 ¶ added in v0.0.23
NodeToUser converts a node to a user