From 49f56cee1e2285fd32c43f35e3622d2ed6c5fec3 Mon Sep 17 00:00:00 2001
From: zhangqian <zhangqian@123.com>
Date: 星期六, 26 八月 2023 20:09:07 +0800
Subject: [PATCH] plc tag

---
 service/plc.go |   55 ++++++++++++++++++++++++++++++++++++++++++++++---------
 1 files changed, 46 insertions(+), 9 deletions(-)

diff --git a/service/plc.go b/service/plc.go
index 00fa70f..73e8f33 100644
--- a/service/plc.go
+++ b/service/plc.go
@@ -8,6 +8,7 @@
 	"encoding/binary"
 	"errors"
 	"fmt"
+	"sync"
 )
 
 func PlcRead(plcConfig *model.DevicePlc, fieldType constvar.PlcStartAddressType) (val interface{}, err error) {
@@ -24,19 +25,18 @@
 			valueType = pc.Type
 			dataLength = pc.Length
 		}
-		ipAddr = fmt.Sprintf("%s:%v", plcConfig.Address, plcConfig.Port)
 	}
+	ipAddr = fmt.Sprintf("%s:%v", plcConfig.Address, plcConfig.Port)
 
-	conn, err := plc.NewModbusConnection(ipAddr)
+	conn, err := plc.GetModbusConnection(ipAddr)
 	if err != nil {
-		logx.Errorf("GetProductProgress 杩炴帴plc澶辫触: %v", err.Error())
+		logx.Errorf("PlcRead 杩炴帴plc澶辫触: %v", err.Error())
 		return
 	}
-	defer conn.Close()
 
 	rawData, err := plc.ReadHoldingRegister(conn, startAddress, dataLength)
 	if err != nil {
-		logx.Errorf("GetProductProgress 鑾峰彇plc鏁版嵁澶辫触: %v", err.Error())
+		logx.Errorf("PlcRead 鑾峰彇plc鏁版嵁澶辫触: %v", err.Error())
 		return
 	}
 	switch valueType {
@@ -58,15 +58,14 @@
 		if pc.FieldName == fieldType {
 			startAddress = pc.StartAddress
 		}
-		ipAddr = fmt.Sprintf("%s:%v", plcConfig.Address, plcConfig.Port)
 	}
+	ipAddr = fmt.Sprintf("%s:%v", plcConfig.Address, plcConfig.Port)
 
-	conn, err := plc.NewModbusConnection(ipAddr)
+	conn, err := plc.GetModbusConnection(ipAddr)
 	if err != nil {
-		logx.Errorf("GetProductProgress 杩炴帴plc澶辫触: %v", err.Error())
+		logx.Errorf("PlcWrite 杩炴帴plc澶辫触: %v", err.Error())
 		return
 	}
-	defer conn.Close()
 
 	result, err := plc.WriteHoldingRegister(conn, startAddress, value)
 	if err != nil {
@@ -76,3 +75,41 @@
 	logx.Infof("plc write ok, address: %v, value: %v, result: %v", startAddress, value, result)
 	return
 }
+
+type CacheStore struct {
+	cache map[string]interface{}
+	mu    sync.Mutex
+}
+
+var defaultCacheStore *CacheStore
+
+func init() {
+	defaultCacheStore = newCacheManager()
+}
+func newCacheManager() *CacheStore {
+	return &CacheStore{
+		cache: make(map[string]interface{}),
+	}
+}
+
+func (cm *CacheStore) Get(key string) (interface{}, bool) {
+	cm.mu.Lock()
+	defer cm.mu.Unlock()
+
+	conn, ok := cm.cache[key]
+	return conn, ok
+}
+
+func (cm *CacheStore) Add(key string, value interface{}) {
+	cm.mu.Lock()
+	defer cm.mu.Unlock()
+	cm.cache[key] = value
+}
+
+func PlcCacheGet(key string) (interface{}, bool) {
+	return defaultCacheStore.Get(key)
+}
+
+func PlcCacheSet(key string, value interface{}) {
+	defaultCacheStore.Add(key, value)
+}

--
Gitblit v1.8.0