-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Add Modbus service for dynamic parameter reading #25908
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 33 commits
Commits
Show all changes
61 commits
Select commit
Hold shift + click to select a range
b02335b
initial modbus service
iseeberg79 63ce90a
remove usage filter
iseeberg79 48466c8
fix ui
iseeberg79 b8b44ad
fix tests
iseeberg79 c32a0bc
fix integration, restore
iseeberg79 0c5ced8
fix, reduce
iseeberg79 6071b9f
simplify
iseeberg79 0de806d
cache
iseeberg79 a648282
refactor
iseeberg79 884ff34
Merge branch 'master' into feature/service
iseeberg79 a085515
fix
iseeberg79 d152738
cleanup
iseeberg79 35a1ea7
simplify UI
iseeberg79 0c4a96a
linter
iseeberg79 e9039d4
remove obsolete
iseeberg79 2094942
Revert UI simplification
iseeberg79 d47c424
fix linter
iseeberg79 2d601b1
mapstructure squash pattern
iseeberg79 700fdb1
use uri
iseeberg79 70038f7
remove constants
iseeberg79 e7bd763
fix test
iseeberg79 6b00d11
simplify
iseeberg79 3518ad8
fix
iseeberg79 1e185c2
dynamic getters
iseeberg79 6c9ede3
validate
iseeberg79 75df7fd
simplify
andig b7bd656
wip
andig 927cda2
fix
iseeberg79 de1d13e
revert test
iseeberg79 9119f1a
Delete .project
iseeberg79 fdf24fc
refactor
iseeberg79 9871ebf
add serial
iseeberg79 f4df4a7
lint
iseeberg79 8e5bf35
applyCast tests
iseeberg79 3a94c54
logging
iseeberg79 8d6181b
use mapstructure
iseeberg79 fabcbc7
simplify pluginGetter
iseeberg79 86bf70b
wip
iseeberg79 6573a87
Apply suggestion from @andig
andig bc4462e
Merge branch 'master' into feature/service
naltatis 6e3336b
feature service dependency groups and yaml defintion
iseeberg79 7e15216
simplify
iseeberg79 c1f2c5a
fix linter
iseeberg79 828332d
simplify, fix
iseeberg79 632be00
revert changes to types
iseeberg79 6985b2f
refactor
iseeberg79 a57b344
Merge branch 'master' into feature/service
iseeberg79 8dfff46
fix early expand
iseeberg79 9cfd23b
simplify
iseeberg79 59a3d98
refactor propertyfield
naltatis 0ced775
Merge branch 'master' into feature/service
naltatis 0dc5f54
fix modbus default handling; add e2e tests
naltatis 27d4dc8
added comment
naltatis e711ece
cleanup
naltatis 347c9ad
fix test
naltatis 82b5a8b
remove redundant modbus defaults
iseeberg79 555a065
Merge branch 'master' into feature/service
naltatis 202ee51
Merge branch 'master' into feature/service
naltatis 1072c80
update template docs; add service, auth, missing props
naltatis cece1cb
rename
naltatis 47b165d
Merge branch 'master' into feature/service
naltatis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,189 @@ | ||
| package service | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "net/http" | ||
| "strings" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/evcc-io/evcc/plugin" | ||
| "github.com/evcc-io/evcc/server/service" | ||
| "github.com/evcc-io/evcc/util" | ||
| "github.com/evcc-io/evcc/util/modbus" | ||
| "github.com/spf13/cast" | ||
| ) | ||
|
|
||
| // Simple cache for service responses | ||
| type cacheEntry struct { | ||
| value any | ||
| timestamp time.Time | ||
| } | ||
|
|
||
| var ( | ||
| cache = make(map[string]cacheEntry) | ||
| mu sync.RWMutex | ||
| cacheTTL = 1 * time.Minute // Cache for 1 minute | ||
iseeberg79 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ) | ||
|
|
||
| // Query combines modbus settings, register config, and additional parameters | ||
| type Query struct { | ||
| modbus.Settings `mapstructure:",squash"` | ||
| modbus.Register `mapstructure:",squash"` | ||
| Scale float64 // scaling factor | ||
| ResultType string // type cast (int, float, string) | ||
| } | ||
|
|
||
| func init() { | ||
| mux := http.NewServeMux() | ||
| mux.HandleFunc("GET /params", getParams) | ||
iseeberg79 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| service.Register("modbus", mux) | ||
| } | ||
|
|
||
| // getParams reads a parameter value from a device based on URL parameters | ||
| // Returns single value as array (for UI compatibility) | ||
| func getParams(w http.ResponseWriter, req *http.Request) { | ||
iseeberg79 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| // Convert URL query parameters to map for decoding | ||
| cc := make(map[string]any) | ||
| for k := range req.URL.Query() { | ||
| cc[k] = req.URL.Query().Get(k) | ||
| } | ||
|
|
||
| // Decode query parameters into Query struct using mapstructure | ||
| query := Query{ | ||
| Scale: 1.0, | ||
| } | ||
|
|
||
| if err := util.DecodeOther(cc, &query); err != nil { | ||
| jsonError(w, http.StatusBadRequest, err) | ||
| return | ||
| } | ||
|
|
||
| // Validate required parameters | ||
| if (query.URI == "" && query.Device == "") || query.Address == 0 { | ||
iseeberg79 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| jsonError(w, http.StatusBadRequest, fmt.Errorf("uri or device and address parameters are required")) | ||
| return | ||
| } | ||
|
|
||
| // Create cache key from connection string and register address | ||
| connStr := query.URI | ||
| if connStr == "" { | ||
| connStr = query.Device | ||
| } | ||
| cacheKey := fmt.Sprintf("%s:%d", connStr, query.Address) | ||
sourcery-ai[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
iseeberg79 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| // Check cache first | ||
| mu.RLock() | ||
| if entry, ok := cache[cacheKey]; ok && time.Since(entry.timestamp) < cacheTTL { | ||
| mu.RUnlock() | ||
| jsonWrite(w, []string{cast.ToString(entry.value)}) | ||
| return | ||
| } | ||
| mu.RUnlock() | ||
|
|
||
| // Read value from modbus using plugin | ||
| // Use background context so connection isn't tied to HTTP request lifecycle | ||
| value, err := readRegisterValue(context.TODO(), query) | ||
iseeberg79 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if err != nil { | ||
| jsonWrite(w, []string{}) // Return empty array on error | ||
| return | ||
| } | ||
|
|
||
| // Apply optional cast | ||
| if query.ResultType != "" { | ||
| value = applyCast(value, query.ResultType) | ||
| } | ||
|
|
||
| // Store in cache | ||
| mu.Lock() | ||
| cache[cacheKey] = cacheEntry{ | ||
| value: value, | ||
| timestamp: time.Now(), | ||
| } | ||
| mu.Unlock() | ||
|
|
||
| jsonWrite(w, []string{cast.ToString(value)}) | ||
| } | ||
|
|
||
| // readRegisterValue reads a modbus register value by reusing the modbus plugin | ||
| func readRegisterValue(ctx context.Context, query Query) (res any, err error) { | ||
| // Build config map for plugin - need to flatten embedded structs manually | ||
| cfg := map[string]any{ | ||
iseeberg79 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| "uri": query.URI, | ||
| "id": query.ID, | ||
| "register": query.Register, | ||
| "scale": query.Scale, | ||
| } | ||
|
|
||
| // Add optional settings | ||
| if query.Device != "" { | ||
| cfg["device"] = query.Device | ||
| } | ||
| if query.Comset != "" { | ||
| cfg["comset"] = query.Comset | ||
| } | ||
| if query.Baudrate != 0 { | ||
| cfg["baudrate"] = query.Baudrate | ||
| } | ||
|
|
||
| p, err := plugin.NewModbusFromConfig(ctx, cfg) | ||
| if err != nil { | ||
| return 0, fmt.Errorf("failed to create modbus plugin: %w", err) | ||
| } | ||
|
|
||
| defer func() { | ||
| if r := recover(); r != nil { | ||
| res = nil | ||
iseeberg79 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
andig marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| err = fmt.Errorf("read failed: %v", r) | ||
| } | ||
| }() | ||
|
|
||
| // Choose getter based on encoding type | ||
| encoding := strings.ToLower(query.Encoding) | ||
|
|
||
| // String encodings need special handling | ||
| if encoding == "string" || encoding == "bytes" { | ||
| return callGetter(p.(plugin.StringGetter).StringGetter()) | ||
| } | ||
|
|
||
| // For all numeric encodings (int*, uint*, float*, bool*), use FloatGetter | ||
iseeberg79 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| // This is the base implementation in modbus plugin | ||
| return callGetter(p.(plugin.FloatGetter).FloatGetter()) | ||
iseeberg79 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| // callGetter calls a getter function and returns the result | ||
| func callGetter[T any](getterFn func() (T, error), err error) (any, error) { | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return getterFn() | ||
| } | ||
|
|
||
| // applyCast applies optional type casting | ||
| func applyCast(value any, castType string) any { | ||
| switch strings.ToLower(castType) { | ||
| case "int": | ||
| return cast.ToInt64(value) | ||
| case "float": | ||
| return cast.ToFloat64(value) | ||
| case "string": | ||
| return cast.ToString(value) | ||
| default: | ||
| return value | ||
| } | ||
| } | ||
|
|
||
| // jsonWrite writes a JSON response | ||
| func jsonWrite(w http.ResponseWriter, data any) { | ||
| w.Header().Set("Content-Type", "application/json") | ||
| json.NewEncoder(w).Encode(data) | ||
| } | ||
|
|
||
| // jsonError writes an error response | ||
| func jsonError(w http.ResponseWriter, status int, err error) { | ||
| w.WriteHeader(status) | ||
| jsonWrite(w, util.ErrorAsJson(err)) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.