zhangqian
2023-08-25 35d15855172bb559fc6817745dee672f5e9b8d80
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)
}