Modbus: ensure service result is rounded (#26756)
This commit is contained in:
parent
dbd298445b
commit
1d60aa005f
3 changed files with 17 additions and 19 deletions
|
|
@ -3,26 +3,25 @@ package service
|
|||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/evcc-io/evcc/util"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
// applyCast applies optional type casting
|
||||
func applyCast(value any, castType string) any {
|
||||
// toString converts to canonical string representation
|
||||
func toString(value any, castType string) string {
|
||||
res := value
|
||||
switch strings.ToLower(castType) {
|
||||
case "int":
|
||||
return cast.ToInt64(value)
|
||||
case "float":
|
||||
return cast.ToFloat64(value)
|
||||
res = cast.ToInt64(value)
|
||||
case "bool":
|
||||
return cast.ToBool(value)
|
||||
case "string":
|
||||
return cast.ToString(value)
|
||||
default:
|
||||
return value
|
||||
res = cast.ToBool(value)
|
||||
case "float":
|
||||
return strconv.FormatFloat(cast.ToFloat64(value), 'g', 3, 64)
|
||||
}
|
||||
return cast.ToString(res)
|
||||
}
|
||||
|
||||
// jsonWrite writes a JSON response
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ import (
|
|||
|
||||
// Simple cache for service responses
|
||||
type cacheEntry struct {
|
||||
value any
|
||||
value string
|
||||
timestamp time.Time
|
||||
}
|
||||
|
||||
|
|
@ -88,20 +88,18 @@ func modbusRead(w http.ResponseWriter, req *http.Request) {
|
|||
return
|
||||
}
|
||||
|
||||
// Apply optional cast
|
||||
if query.ResultType != "" {
|
||||
value = applyCast(value, query.ResultType)
|
||||
}
|
||||
// Convert to string
|
||||
res := toString(value, query.ResultType)
|
||||
|
||||
// Store in cache
|
||||
mu.Lock()
|
||||
cache[cacheKey] = cacheEntry{
|
||||
value: value,
|
||||
value: res,
|
||||
timestamp: time.Now(),
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
jsonWrite(w, []string{cast.ToString(value)})
|
||||
jsonWrite(w, []string{res})
|
||||
}
|
||||
|
||||
// readRegisterValue reads a modbus register value by reusing the modbus plugin
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cast"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
|
|
@ -139,8 +140,8 @@ func TestApplyCast(t *testing.T) {
|
|||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := applyCast(tt.value, tt.castType)
|
||||
assert.Equal(t, tt.expected, result)
|
||||
result := toString(tt.value, tt.castType)
|
||||
assert.Equal(t, cast.ToString(tt.expected), result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue