From 8324f872ef3a4d0c978a9b1d062800c6a1701c12 Mon Sep 17 00:00:00 2001 From: zhangqian <zhangqian@123.com> Date: 星期五, 01 十二月 2023 09:58:17 +0800 Subject: [PATCH] fix --- pkg/plc/modbusx/modbus.go | 60 +++++++++++++++++++++++------------------------------------- 1 files changed, 23 insertions(+), 37 deletions(-) diff --git a/pkg/plc/modbusx/modbus.go b/pkg/plc/modbusx/modbus.go index 796aa17..1a779c3 100644 --- a/pkg/plc/modbusx/modbus.go +++ b/pkg/plc/modbusx/modbus.go @@ -1,59 +1,45 @@ package modbusx import ( - "encoding/json" - "sync/atomic" + "encoding/binary" ) func Read(ipAddr string, address uint16, quantity uint16) (data []byte, err error) { + address-- cli := getModbusConnection(ipAddr) data, err = cli.ReadHoldingRegisters(address, quantity) dealErr(err, ipAddr) + if err != nil { + cli = getModbusConnection(ipAddr) + data, err = cli.ReadHoldingRegisters(address, quantity) + dealErr(err, ipAddr) + } return } -func Write(ipAddr string, address uint16, value interface{}) (err error) { - bytesVal, err := json.Marshal(value) - if err != nil { - return err - } +func Write(ipAddr string, address uint16, value int) (err error) { + address-- + var bytesVal []byte + bytesVal = intToBytes(value) cli := getModbusConnection(ipAddr) _, err = cli.WriteMultipleRegisters(address, uint16(len(bytesVal)), bytesVal) dealErr(err, ipAddr) return err } +func intToBytes(value int) (data []byte) { + if value <= 1<<16 { + data = make([]byte, 2) + binary.BigEndian.PutUint16(data, uint16(value)) + } else { + data = make([]byte, 4) + binary.BigEndian.PutUint32(data, uint32(value)) + } + return +} + func dealErr(err error, ipAddr string) { if err != nil { - unsetModbusConnection(ipAddr) //澶辫触鍒欏垹闄ょ紦瀛樼殑杩炴帴 - FailureRemainingOpportunitiesDecr() //鍑忓皯澶辫触鍓╀綑鏈轰細 - } else { - FailureRemainingOpportunitiesReset() //閲嶇疆澶辫触鍓╀綑鏈轰細 + unsetModbusConnection(ipAddr) //澶辫触鍒欏垹闄ょ紦瀛樼殑杩炴帴 } -} - -var connectionStatus atomic.Bool - -var failureRemainingOpportunities atomic.Int64 - -const ( - defaultFailureRemainingOpportunities = 20 -) - -func IsConnect() bool { - return connectionStatus.Load() -} - -func FailureRemainingOpportunitiesDecr() { - newValue := failureRemainingOpportunities.Add(-1) - if newValue <= 0 { - connectionStatus.Store(false) - } - return -} - -func FailureRemainingOpportunitiesReset() { - failureRemainingOpportunities.Store(defaultFailureRemainingOpportunities) - connectionStatus.Store(true) - return } -- Gitblit v1.8.0