jl-iot/modbus/manage.go

54 lines
1.0 KiB
Go
Raw Normal View History

package modbus
import "sync"
// modbus客户端管理
type modbusManager struct {
lock sync.Mutex
clientMap map[string]MasterClient
}
var manager = modbusManager{
clientMap: make(map[string]MasterClient),
}
// 获取modbus客户端
func GetClient(url string) (MasterClient, bool) {
manager.lock.Lock()
defer manager.lock.Unlock()
client, ok := manager.clientMap[url]
return client, ok
}
// 新建客户端
func NewClient(conf *ClientConfig) (MasterClient, error) {
manager.lock.Lock()
defer manager.lock.Unlock()
client, err := newClient(conf)
if err != nil {
return nil, err
}
manager.clientMap[conf.Url] = client
return client, err
}
// 获取或新建客户端
func GetOrInitClient(conf *ClientConfig) (MasterClient, error) {
client, ok := GetClient(conf.Url)
if ok {
return client, nil
}
return NewClient(conf)
}
// 删除客户端
func DeleteClient(url string) {
manager.lock.Lock()
defer manager.lock.Unlock()
c := manager.clientMap[url]
if c != nil {
c.Close()
delete(manager.clientMap, url)
}
}