From 7335d19846ad4f5b0a61541a992d61763c5cf35b Mon Sep 17 00:00:00 2001
From: zhangqian <zhangqian@123.com>
Date: 星期五, 03 十一月 2023 17:17:44 +0800
Subject: [PATCH] 串口支持大数读写

---
 pkg/plccom/plccom.go |   32 ++++++++++++++++++++++++++++----
 1 files changed, 28 insertions(+), 4 deletions(-)

diff --git a/pkg/plccom/plccom.go b/pkg/plccom/plccom.go
index eca7403..43e2b9b 100644
--- a/pkg/plccom/plccom.go
+++ b/pkg/plccom/plccom.go
@@ -19,11 +19,18 @@
 	// MakeReadProtocol 鍒涘缓璇诲彇鏁版嵁鐨勫崗璁�
 	MakeReadProtocol(addr string) []byte
 
+	// MakeReadProtocolBits 鍒涘缓璇诲彇鏁版嵁鐨勫崗璁�
+	MakeReadProtocolBits(bits int, addr string) []byte
+
 	// MakeWriteProtocol 鍒涘缓鍐欏叆鏁版嵁鐨勫崗璁�
 	MakeWriteProtocol(addr string, value int) []byte
 
+	MakeWriteProtocolBits(bits int, addr string, ival int) []byte
+
 	// ParseReadValue 瑙f瀽浠庤澶囪鍙栫殑鍊�
 	ParseReadValue(data []byte) int
+
+	ParseReadValueBits(data []byte) int
 
 	// ParseWriteValue 瑙f瀽鍐欏叆璁惧鐨勭粨鏋滐紝骞惰繑鍥炵粨鏋滃拰鏄惁鎴愬姛
 	ParseWriteValue(data []byte) (int, bool)
@@ -49,13 +56,19 @@
 	return protocol, nil
 }
 
-func ReadPLC(deviceType, url, label string) (val int, err error) {
+func ReadPLC(deviceType, url, label string, length int) (val int, err error) {
 	protocol, err := LoadProtocol(deviceType)
 	if err != nil {
 		return 0, err
 	}
 	addr := protocol.ConvertLabelToAddress(label)
-	proto := protocol.MakeReadProtocol(addr)
+	var proto []byte
+	if length == 1 {
+		proto = protocol.MakeReadProtocol(addr)
+	} else {
+		proto = protocol.MakeReadProtocolBits(length*16, addr)
+	}
+
 	bp := base64.StdEncoding.EncodeToString(proto)
 	fullUrl := fmt.Sprintf("%v?proto=%v", url, bp)
 	resp, err := http.Get(fullUrl)
@@ -69,7 +82,12 @@
 		logx.Errorf("ReadPLC base64.StdEncoding.DecodeString failed: %v, data: %v", err, string(body))
 		return 0, err
 	}
-	val = protocol.ParseReadValue(data)
+	if length == 1 {
+		val = protocol.ParseReadValue(data)
+	} else {
+		val = protocol.ParseReadValueBits(data)
+	}
+
 	fmt.Println("read PLC:", val)
 	return val, nil
 
@@ -91,7 +109,13 @@
 		return err
 	}
 	addr := protocol.ConvertLabelToAddress(label)
-	proto := protocol.MakeWriteProtocol(addr, val)
+	var proto []byte
+	if val < 65536 {
+		proto = protocol.MakeWriteProtocol(addr, val)
+	} else {
+		proto = protocol.MakeWriteProtocolBits(32, addr, val)
+	}
+
 	bp := base64.StdEncoding.EncodeToString(proto)
 	resp, err := http.Post(url, "text/plain", strings.NewReader(bp))
 	if err != nil {

--
Gitblit v1.8.0