diff values
This commit is contained in:
parent
0f89fcf325
commit
1c19117170
BIN
src/smq/smq
BIN
src/smq/smq
Binary file not shown.
@ -5,6 +5,8 @@ import (
|
||||
"log"
|
||||
"time"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"math"
|
||||
|
||||
"smq/config"
|
||||
"smq/mqtt"
|
||||
@ -16,6 +18,7 @@ type variable_t struct {
|
||||
Label string `json:"label"`
|
||||
Variable string `json:"variable"`
|
||||
Value string `json:"value"`
|
||||
DiffValue string `json:"diffValue"`
|
||||
}
|
||||
|
||||
type message_t struct {
|
||||
@ -24,6 +27,45 @@ type message_t struct {
|
||||
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() {
|
||||
for {
|
||||
@ -72,11 +114,24 @@ func Start() {
|
||||
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)
|
||||
v := variable_t {
|
||||
Label: oidTopic.Label,
|
||||
Variable: oidTopic.OID,
|
||||
Value: convertedValue,
|
||||
DiffValue: diffValue,
|
||||
}
|
||||
message.Variables[oidTopic.Label] = v
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user