| | |
| | | "encoding/binary" |
| | | "errors" |
| | | "fmt" |
| | | "sync" |
| | | ) |
| | | |
| | | func PlcRead(plcConfig *model.DevicePlc, fieldType constvar.PlcStartAddressType) (val interface{}, err error) { |
| | |
| | | |
| | | 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 { |
| | |
| | | |
| | | conn, err := plc.GetModbusConnection(ipAddr) |
| | | if err != nil { |
| | | logx.Errorf("GetProductProgress 连接plc失败: %v", err.Error()) |
| | | logx.Errorf("PlcWrite 连接plc失败: %v", err.Error()) |
| | | return |
| | | } |
| | | |
| | |
| | | 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) |
| | | } |