using S7.Net.Protocol.S7;
using System;
namespace S7.Net.Types
{
///
/// Create an instance of a memory block that can be read by using ReadMultipleVars
///
public class DataItem
{
///
/// Memory area to read
///
public DataType DataType { get; set; }
///
/// Type of data to be read (default is bytes)
///
public VarType VarType { get; set; }
///
/// Address of memory area to read (example: for DB1 this value is 1, for T45 this value is 45)
///
public int DB { get; set; }
///
/// Address of the first byte to read
///
public int StartByteAdr { get; set; }
///
/// Addess of bit to read from StartByteAdr
///
public byte BitAdr { get; set; }
///
/// Number of variables to read
///
public int Count { get; set; }
///
/// Contains the value of the memory area after the read has been executed
///
public object? Value { get; set; }
///
/// Create an instance of DataItem
///
public DataItem()
{
VarType = VarType.Byte;
Count = 1;
}
///
/// Create an instance of from the supplied address.
///
/// The address to create the DataItem for.
/// A new instance with properties parsed from .
/// The property is not parsed from the address.
public static DataItem FromAddress(string address)
{
PLCAddress.Parse(address, out var dataType, out var dbNumber, out var varType, out var startByte,
out var bitNumber);
return new DataItem
{
DataType = dataType,
DB = dbNumber,
VarType = varType,
StartByteAdr = startByte,
BitAdr = (byte) (bitNumber == -1 ? 0 : bitNumber)
};
}
///
/// Create an instance of from the supplied address and value.
///
/// The address to create the DataItem for.
/// The value to be applied to the DataItem.
/// A new instance with properties parsed from and the supplied value set.
public static DataItem FromAddressAndValue(string address, T value)
{
var dataItem = FromAddress(address);
dataItem.Value = value;
if (typeof(T).IsArray)
{
var array = ((Array?)dataItem.Value);
if ( array != null)
{
dataItem.Count = array.Length;
}
}
return dataItem;
}
internal static DataItemAddress GetDataItemAddress(DataItem dataItem)
{
return new DataItemAddress(dataItem.DataType, dataItem.DB, dataItem.StartByteAdr, Plc.VarTypeToByteLength(dataItem.VarType, dataItem.Count));
}
}
}