-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
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
Open
iseeberg79
wants to merge
38
commits into
evcc-io:master
Choose a base branch
from
iseeberg79:feature/service
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+427
−25
Open
Changes from all commits
Commits
Show all changes
38 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 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,183 @@ | ||
| 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/fatih/structs" | ||
| "github.com/spf13/cast" | ||
| ) | ||
|
|
||
| // Simple cache for service responses | ||
| type cacheEntry struct { | ||
| value any | ||
| timestamp time.Time | ||
| } | ||
|
|
||
| var ( | ||
| log = util.NewLogger("modbus") | ||
| cache = make(map[string]cacheEntry) | ||
| mu sync.RWMutex | ||
| cacheTTL = 1 * time.Minute // Cache for 1 minute | ||
| ) | ||
|
|
||
| // 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) | ||
|
|
||
| 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) { | ||
| // 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 == "") || cc["address"] == nil { | ||
| 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.
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 { | ||
| log.TRACE.Printf("failed to read register %d from %s: %v", query.Address, cacheKey, err) | ||
| jsonError(w, http.StatusInternalServerError, err) | ||
| return | ||
| } | ||
|
|
||
| // Apply optional cast | ||
| if query.ResultType != "" { | ||
| value = applyCast(value, query.ResultType) | ||
| } | ||
|
|
||
| log.TRACE.Printf("read register %d from %s: %v", query.Address, cacheKey, value) | ||
|
|
||
| // 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) { | ||
| // Convert Settings to map (plugin expects Settings fields at top level) | ||
| cfg := structs.Map(query.Settings) | ||
|
|
||
| // Plugin expects Register as nested object, not flattened | ||
| cfg["register"] = query.Register | ||
| cfg["scale"] = query.Scale | ||
|
|
||
| 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 | ||
| 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" { | ||
| g, err := p.(plugin.StringGetter).StringGetter() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return g() | ||
| } | ||
|
|
||
| // For all numeric encodings (int*, float*, bool*), use FloatGetter | ||
| g, err := p.(plugin.FloatGetter).FloatGetter() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return g() | ||
| } | ||
|
|
||
| // 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 "bool": | ||
| return cast.ToBool(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.