Remove the modbus connection cache and improve handling configuration errors (#315)

This commit is contained in:
andig 2020-08-26 15:51:52 +02:00 • committed by GitHub
parent f2d5984696
commit 6b622b7df7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 18 deletions

View file

@ -45,6 +45,10 @@ func NewModbusFromConfig(other map[string]interface{}) (api.Meter, error) {
log := util.NewLogger("modbus")
conn, err := modbus.NewConnection(cc.URI, cc.Device, cc.Comset, cc.Baudrate, *cc.RTU)
if err != nil {
return nil, err
}
conn.Logger(log.TRACE)
// prepare device

View file

@ -26,32 +26,20 @@ type Connection struct {
RTU *bool // indicates RTU over TCP if true
}
var connections map[string]meters.Connection
func registeredConnection(key string, newConn meters.Connection) meters.Connection {
if connections == nil {
connections = make(map[string]meters.Connection)
}
if conn, ok := connections[key]; ok {
return conn
}
connections[key] = newConn
return newConn
}
// NewConnection creates physical modbus device from config
func NewConnection(uri, device, comset string, baudrate int, rtu bool) (conn meters.Connection, err error) {
if device != "" {
conn = registeredConnection(device, meters.NewRTU(device, baudrate, comset))
if baudrate == 0 || comset == "" {
return nil, errors.New("invalid modbus configuration: need baudrate and comset")
}
conn = meters.NewRTU(device, baudrate, comset)
}
if uri != "" {
if rtu {
conn = registeredConnection(uri, meters.NewRTUOverTCP(uri))
conn = meters.NewRTUOverTCP(uri)
} else {
conn = registeredConnection(uri, meters.NewTCP(uri))
conn = meters.NewTCP(uri)
}
}