using Mirle.Component.MPLC.DataBlocks; using Mirle.Component.MPLC.Interfaces; using System.Collections.Generic; namespace Mirle.Component.MPLC.SharedMemory { /// /// 共享記憶體讀取 /// public class SMReadWriter : IMPLCProvider { /// /// 建構式 /// public SMReadWriter() { } /// /// 資料區塊 /// protected readonly List _dataBlocks = new List(); /// /// 是否連線 /// public bool IsConnected => true; /// /// 新增資料區塊 /// /// 共享記憶體資料區塊 public virtual void AddDataBlock(SMDataBlock newDataBlock) { _dataBlocks.Add(newDataBlock); } /// /// 取得位元 /// /// 位置 /// True/False public virtual bool GetBit(string address) { foreach (SMDataBlock block in _dataBlocks) { if (block.TryGetBit(address, out bool value)) return value; } return false; } /// /// 設置位元開啟 /// /// 位置 public virtual void SetBitOn(string address) { foreach (SMDataBlock block in _dataBlocks) { if (block.TrySetBitOn(address)) return; } } /// /// 設置位元關閉 /// /// 位置 public virtual void SetBitOff(string address) { foreach (SMDataBlock block in _dataBlocks) { if (block.TrySetBitOff(address)) return; } } /// /// 讀取字元 /// /// 位置 /// 字元 public virtual int ReadWord(string address) { foreach (SMDataBlock block in _dataBlocks) { if (block.TryGetWord(address, out int value)) return value; } return 0; } /// /// 寫入字元 /// /// 位置 /// 字元 public virtual void WriteWord(string address, int data) { foreach (SMDataBlock block in _dataBlocks) { if (block.TrySetWord(address, data)) return; } } /// /// 讀取多個字元 /// /// 起始位置 /// 長度 /// 字元陣列 public virtual int[] ReadWords(string startAddress, int length) { foreach (SMDataBlock block in _dataBlocks) { if (block.TryGetWords(startAddress, out int[] data, length)) return data; } return new int[length]; } /// /// 寫入多個字元 /// /// 起始位置 /// 字元陣列 public virtual void WriteWords(string startAddress, int[] data) { foreach (SMDataBlock block in _dataBlocks) { if (block.TrySetWords(startAddress, data)) return; } } } }