From 1d60aa005fd1640362975abe21e37d39d0da3ea9 Mon Sep 17 00:00:00 2001 From: andig Date: Sun, 18 Jan 2026 10:48:34 +0100 Subject: [PATCH] Modbus: ensure service result is rounded (#26756) --- util/service/helper.go | 19 +++++++++---------- util/service/modbus.go | 12 +++++------- util/service/modbus_test.go | 5 +++-- 3 files changed, 17 insertions(+), 19 deletions(-) diff --git a/util/service/helper.go b/util/service/helper.go index d5f82e590..e3cc9f635 100644 --- a/util/service/helper.go +++ b/util/service/helper.go @@ -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 diff --git a/util/service/modbus.go b/util/service/modbus.go index 826e50de1..213ce7f17 100644 --- a/util/service/modbus.go +++ b/util/service/modbus.go @@ -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 diff --git a/util/service/modbus_test.go b/util/service/modbus_test.go index 53cab99af..b9939e3a2 100644 --- a/util/service/modbus_test.go +++ b/util/service/modbus_test.go @@ -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) }) } }