From 583142e22b647955082ea61f8ee6b3641aaa903c Mon Sep 17 00:00:00 2001
From: zhangqian <zhangqian@123.com>
Date: 星期二, 19 九月 2023 14:16:55 +0800
Subject: [PATCH] 写plc fix

---
 pkg/plc/modbusx/modbus.go |   35 +++++++++++------------------------
 1 files changed, 11 insertions(+), 24 deletions(-)

diff --git a/pkg/plc/modbusx/modbus.go b/pkg/plc/modbusx/modbus.go
index e1af28c..2d323ec 100644
--- a/pkg/plc/modbusx/modbus.go
+++ b/pkg/plc/modbusx/modbus.go
@@ -19,37 +19,24 @@
 }
 
 func Write(ipAddr string, address uint16, value int) (err error) {
+	address--
 	var bytesVal []byte
-	if value <= 1<<16 {
-		uint16ToBytes(uint16(value))
-	} else {
-		bytesVal = intToBytes(value)
-	}
+	bytesVal = intToBytes(value)
 	cli := getModbusConnection(ipAddr)
 	_, err = cli.WriteMultipleRegisters(address, uint16(len(bytesVal)), bytesVal)
 	dealErr(err, ipAddr)
 	return err
 }
 
-func uint16ToBytes(value uint16) []byte {
-	// 鍒涘缓涓�涓暱搴︿负2鐨勫瓧鑺傚垏鐗�
-	bytes := make([]byte, 2)
-
-	// 灏� uint16 鐨勫�煎啓鍏ュ瓧鑺傚垏鐗囷紝鍙互閫夋嫨浣跨敤澶х鎴栧皬绔瓧鑺傚簭
-	bytes[0] = byte(value >> 8) // 鑾峰彇楂�8浣�
-	bytes[1] = byte(value)      // 鑾峰彇浣�8浣�
-
-	return bytes
-}
-
-func intToBytes(value int) []byte {
-	// 鍒涘缓涓�涓暱搴︿负4鐨勫瓧鑺傚垏鐗囷紝鐢ㄤ簬瀛樺偍 int 鍊�
-	bytes := make([]byte, 4)
-
-	// 浣跨敤 binary 鍖呭皢 int 鍊艰浆鎹负瀛楄妭鍒囩墖
-	binary.BigEndian.PutUint32(bytes, uint32(value))
-
-	return bytes
+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) {

--
Gitblit v1.8.0