From 35d15855172bb559fc6817745dee672f5e9b8d80 Mon Sep 17 00:00:00 2001 From: zhangqian <zhangqian@123.com> Date: 星期五, 25 八月 2023 21:05:26 +0800 Subject: [PATCH] 2秒钟请求一次完成量并存储 --- service/plc.go | 45 ++++++++++++++++++++++++++++++++++++++++++--- 1 files changed, 42 insertions(+), 3 deletions(-) diff --git a/service/plc.go b/service/plc.go index 582f0f3..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) { @@ -29,13 +30,13 @@ conn, err := plc.GetModbusConnection(ipAddr) if err != nil { - logx.Errorf("GetProductProgress 杩炴帴plc澶辫触: %v", err.Error()) + logx.Errorf("PlcRead 杩炴帴plc澶辫触: %v", err.Error()) return } 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 { @@ -62,7 +63,7 @@ conn, err := plc.GetModbusConnection(ipAddr) if err != nil { - logx.Errorf("GetProductProgress 杩炴帴plc澶辫触: %v", err.Error()) + logx.Errorf("PlcWrite 杩炴帴plc澶辫触: %v", err.Error()) return } @@ -74,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