From 83b652cd2f1be2375d33a67366a7c359cf6e22c0 Mon Sep 17 00:00:00 2001
From: zhangqian <zhangqian@123.com>
Date: 星期一, 18 九月 2023 14:56:09 +0800
Subject: [PATCH] 支持几个配置,支持按配置选择plc驱动包

---
 pkg/plc/modbusx/modbus.go |   33 ++++++++++++++++++++++++++++-----
 1 files changed, 28 insertions(+), 5 deletions(-)

diff --git a/pkg/plc/modbusx/modbus.go b/pkg/plc/modbusx/modbus.go
index 4bb3b64..edcea6f 100644
--- a/pkg/plc/modbusx/modbus.go
+++ b/pkg/plc/modbusx/modbus.go
@@ -1,7 +1,7 @@
 package modbusx
 
 import (
-	"encoding/json"
+	"encoding/binary"
 	"sync/atomic"
 )
 
@@ -12,10 +12,12 @@
 	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) {
+	var bytesVal []byte
+	if value <= 1<<16 {
+		uint16ToBytes(uint16(value))
+	} else {
+		bytesVal = intToBytes(value)
 	}
 	cli := getModbusConnection(ipAddr)
 	_, err = cli.WriteMultipleRegisters(address, uint16(len(bytesVal)), bytesVal)
@@ -23,6 +25,27 @@
 	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 dealErr(err error, ipAddr string) {
 	if err != nil {
 		unsetModbusConnection(ipAddr)       //澶辫触鍒欏垹闄ょ紦瀛樼殑杩炴帴

--
Gitblit v1.8.0