package modbusx
|
|
import (
|
"apsClient/conf"
|
"github.com/goburrow/modbus"
|
"sync"
|
"time"
|
)
|
|
type ConnectionManager struct {
|
connections map[string]modbus.Client
|
mu sync.Mutex
|
}
|
|
var handler *modbus.TCPClientHandler
|
|
func newPlcConnectionManager() *ConnectionManager {
|
return &ConnectionManager{
|
connections: make(map[string]modbus.Client),
|
}
|
}
|
|
func (cm *ConnectionManager) GetConnection(address string) (modbus.Client, bool) {
|
cm.mu.Lock()
|
defer cm.mu.Unlock()
|
|
conn, ok := cm.connections[address]
|
if !ok {
|
return nil, false
|
}
|
return conn, true
|
}
|
|
var connectionManager = newPlcConnectionManager()
|
|
func (cm *ConnectionManager) AddConnection(address string, connection modbus.Client) {
|
cm.mu.Lock()
|
defer cm.mu.Unlock()
|
|
cm.connections[address] = connection
|
}
|
|
func (cm *ConnectionManager) RemoveConnection(address string) {
|
cm.mu.Lock()
|
defer cm.mu.Unlock()
|
delete(cm.connections, address)
|
}
|
func getModbusConnection(ipAddr string) modbus.Client {
|
if conn, ok := connectionManager.GetConnection(ipAddr); ok {
|
return conn
|
}
|
conn := newGetModbusConnection(ipAddr)
|
connectionManager.AddConnection(ipAddr, conn)
|
return conn
|
}
|
|
func unsetModbusConnection(ipAddr string) {
|
_, ok := connectionManager.GetConnection(ipAddr)
|
if !ok {
|
return
|
}
|
connectionManager.RemoveConnection(ipAddr)
|
if handler != nil {
|
handler.Close()
|
}
|
}
|
|
func newGetModbusConnection(ipAddr string) modbus.Client {
|
handler = modbus.NewTCPClientHandler(ipAddr)
|
handler.Timeout = 10 * time.Second
|
handler.SlaveId = byte(conf.Conf.PLC.SlaveId)
|
return modbus.NewClient(handler)
|
}
|