using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; namespace NModbus.Data { /// /// Collection of discrete values. /// public class DiscreteCollection : Collection, IModbusMessageDataCollection { /// /// Number of bits per byte. /// private const int BitsPerByte = 8; private readonly List _discretes; /// /// Initializes a new instance of the class. /// public DiscreteCollection() : this(new List()) { } /// /// Initializes a new instance of the class. /// /// Array for discrete collection. public DiscreteCollection(params bool[] bits) : this((IList)bits) { } /// /// Initializes a new instance of the class. /// /// Array for discrete collection. public DiscreteCollection(params byte[] bytes) : this() { if (bytes == null) { throw new ArgumentNullException(nameof(bytes)); } _discretes.Capacity = bytes.Length * BitsPerByte; foreach (byte b in bytes) { _discretes.Add((b & 1) == 1); _discretes.Add((b & 2) == 2); _discretes.Add((b & 4) == 4); _discretes.Add((b & 8) == 8); _discretes.Add((b & 16) == 16); _discretes.Add((b & 32) == 32); _discretes.Add((b & 64) == 64); _discretes.Add((b & 128) == 128); } } /// /// Initializes a new instance of the class. /// /// List for discrete collection. public DiscreteCollection(IList bits) : this(new List(bits)) { } /// /// Initializes a new instance of the class. /// /// List for discrete collection. internal DiscreteCollection(List bits) : base(bits) { Debug.Assert(bits != null, "Discrete bits is null."); _discretes = bits; } /// /// Gets the network bytes. /// public byte[] NetworkBytes { get { byte[] bytes = new byte[ByteCount]; for (int index = 0; index < _discretes.Count; index++) { if (_discretes[index]) { bytes[index / BitsPerByte] |= (byte)(1 << (index % BitsPerByte)); } } return bytes; } } /// /// Gets the byte count. /// public byte ByteCount => (byte)((Count + 7) / 8); /// /// Returns a that represents the current . /// /// /// A that represents the current . /// public override string ToString() { return string.Concat("{", string.Join(", ", this.Select(discrete => discrete ? "1" : "0").ToArray()), "}"); } } }