| | |
| | | |
| | | import ( |
| | | "apsClient/conf" |
| | | "apsClient/model/common" |
| | | "apsClient/pkg/logx" |
| | | "github.com/goburrow/modbus" |
| | | "sync" |
| | | "time" |
| | |
| | | if conn, ok := connectionManager.GetConnection(ipAddr); ok { |
| | | return conn |
| | | } |
| | | conn := newGetModbusConnection(ipAddr) |
| | | conn := newModbusConnection(ipAddr) |
| | | connectionManager.AddConnection(ipAddr, conn) |
| | | return conn |
| | | } |
| | |
| | | } |
| | | } |
| | | |
| | | func newGetModbusConnection(ipAddr string) modbus.Client { |
| | | func newModbusConnection(ipAddr string) modbus.Client { |
| | | handler = modbus.NewTCPClientHandler(ipAddr) |
| | | handler.Timeout = 10 * time.Second |
| | | handler.SlaveId = byte(conf.Conf.PLC.SlaveId) |
| | | return modbus.NewClient(handler) |
| | | } |
| | | |
| | | var rtuHandler *modbus.RTUClientHandler |
| | | |
| | | func getModbusRTUConnection(c *common.RTUConfig) modbus.Client { |
| | | if conn, ok := connectionManager.GetConnection(c.SerialName); ok { |
| | | return conn |
| | | } |
| | | conn := newModbusRTUConnection(c) |
| | | connectionManager.AddConnection(c.SerialName, conn) |
| | | return conn |
| | | } |
| | | |
| | | func unsetModbusRTUConnection(serialName string) { |
| | | _, ok := connectionManager.GetConnection(serialName) |
| | | if !ok { |
| | | return |
| | | } |
| | | connectionManager.RemoveConnection(serialName) |
| | | if handler != nil { |
| | | handler.Close() |
| | | } |
| | | } |
| | | |
| | | func newModbusRTUConnection(c *common.RTUConfig) modbus.Client { |
| | | // Modbus RTU/ASCII |
| | | rtuHandler = modbus.NewRTUClientHandler(c.SerialName) |
| | | rtuHandler.BaudRate = c.BaudRate |
| | | rtuHandler.DataBits = c.DataBit |
| | | rtuHandler.Parity = c.Parity.String() |
| | | rtuHandler.StopBits = c.StopBit |
| | | rtuHandler.SlaveId = 1 |
| | | rtuHandler.Timeout = 5 * time.Second |
| | | |
| | | err := rtuHandler.Connect() |
| | | if err != nil { |
| | | logx.Errorf("getModbusRTUConnection Connect err:%v, config: %+v", err, c) |
| | | return nil |
| | | } |
| | | return modbus.NewClient(rtuHandler) |
| | | } |