Created
July 3, 2018 14:04
-
-
Save rapha-dev/f3cd66f69e6d141d2842008335db912c to your computer and use it in GitHub Desktop.
ReadString
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Read known string from PLC | |
/// </summary> | |
/// <param name="startAddr">start byte in format DBx.DBBy</param> | |
/// <returns>known string</returns> | |
public string ReadString(string startAddr) | |
{ | |
if (_plc.IsConnected) | |
{ | |
_plc.ClearLastError(); | |
// decode db and start byte | |
int db = int.Parse(startAddr.Substring(2, startAddr.IndexOf('.') - 2)); | |
int startByte = int.Parse(startAddr.Substring(startAddr.IndexOf('.') + 4)); | |
// read string header | |
var header = (byte[])_plc.Read(DataType.DataBlock, db, startByte, VarType.Byte, 2); | |
// read used bytes as string | |
var bytes = new List<byte>(); | |
if (header[0] != header[1]) | |
{ | |
if (header[1] > 1) | |
{ | |
bytes.AddRange((byte[])_plc.Read(DataType.DataBlock, db, startByte + 2, VarType.Byte, header[1] > header[0] ? header[0] : header[1])); | |
} | |
else | |
{ | |
if (header[1] > 0) | |
{ | |
bytes.Add((byte)_plc.Read(DataType.DataBlock, db, startByte + 2, VarType.Byte, header[1] > header[0] ? header[0] : header[1])); | |
} | |
} | |
} | |
return System.Text.Encoding.ASCII.GetString(bytes.ToArray(), 0, bytes.Count).Replace("\0", ""); | |
} | |
return default(string); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment