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(url string) (MasterClient, error) { manager.lock.Lock() defer manager.lock.Unlock() client, err := newClient(url) if err != nil { return nil, err } manager.clientMap[url] = client return client, err } // 获取或新建客户端 func GetOrInitClient(url string) (MasterClient, error) { client, ok := GetClient(url) if ok { return client, nil } return NewClient(url) } // 删除客户端 func DeleteClient(url string) { manager.lock.Lock() defer manager.lock.Unlock() c := manager.clientMap[url] if c != nil { c.Close() delete(manager.clientMap, url) } }