diff values

This commit is contained in:
Wolfgang Hottgenroth 2024-01-25 14:22:12 +01:00
parent 0f89fcf325
commit 1c19117170
Signed by: wn
GPG Key ID: 836E9E1192A6B132
2 changed files with 55 additions and 0 deletions

Binary file not shown.

View File

@ -5,6 +5,8 @@ import (
"log" "log"
"time" "time"
"encoding/json" "encoding/json"
"strconv"
"math"
"smq/config" "smq/config"
"smq/mqtt" "smq/mqtt"
@ -16,6 +18,7 @@ type variable_t struct {
Label string `json:"label"` Label string `json:"label"`
Variable string `json:"variable"` Variable string `json:"variable"`
Value string `json:"value"` Value string `json:"value"`
DiffValue string `json:"diffValue"`
} }
type message_t struct { type message_t struct {
@ -24,6 +27,45 @@ type message_t struct {
Variables map[string]variable_t `json:"variables"` Variables map[string]variable_t `json:"variables"`
} }
type lastValue_t struct {
Timestamp time.Time
Value string
}
var lastValues map[string]lastValue_t = make(map[string]lastValue_t)
func calculateDifference(key string, newValue string) (string, error) {
currentTime := time.Now()
lvv, ok := lastValues[key]
if ok {
log.Printf("lvv for %s exists: %s", key, lvv.Value)
oldValueI, err1 := strconv.Atoi(lvv.Value)
if err1 != nil {
return "", fmt.Errorf("failed to convert lastValue: %s, %v", lvv.Value, err1)
}
newValueI, err2 := strconv.Atoi(newValue)
if err2 != nil {
return "", fmt.Errorf("failed to convert newValue: %s, %v", newValue, err2)
}
diffValueI := newValueI - oldValueI
diffTime := int(math.Round(currentTime.Sub(lvv.Timestamp).Seconds()))
diffValuePerSecond := diffValueI / diffTime
log.Printf("Diff: %d, Duration: %d, Diff per second: %d", diffValueI, diffTime, diffValuePerSecond)
lastValues[key] = lastValue_t {
Timestamp: currentTime,
Value: newValue,
}
return strconv.Itoa(diffValuePerSecond), nil
} else {
log.Printf("create lvv for %s", key)
lastValues[key] = lastValue_t {
Timestamp: currentTime,
Value: newValue,
}
return "0", nil
}
return "0", nil
}
func Start() { func Start() {
for { for {
@ -72,11 +114,24 @@ func Start() {
convertedValue = fmt.Sprintf("%d", gosnmp.ToBigInt(variable.Value)) convertedValue = fmt.Sprintf("%d", gosnmp.ToBigInt(variable.Value))
} }
diffValue := "0"
if oidTopic.Diff == "true" {
log.Println("Calculate difference to last value")
key := endpoint.Endpoint + ":" + oidTopic.OID
diff, err := calculateDifference(key, convertedValue)
if err != nil {
log.Printf("Error when building difference: %v", err)
} else {
diffValue = diff
}
}
log.Printf("%s = %s", oidTopic.OID, convertedValue) log.Printf("%s = %s", oidTopic.OID, convertedValue)
v := variable_t { v := variable_t {
Label: oidTopic.Label, Label: oidTopic.Label,
Variable: oidTopic.OID, Variable: oidTopic.OID,
Value: convertedValue, Value: convertedValue,
DiffValue: diffValue,
} }
message.Variables[oidTopic.Label] = v message.Variables[oidTopic.Label] = v