codesysstructured-textiec61131-3

I need to concatenate several strings


I am new to stuctured text and I would like to know how to concatenate several string. The cleanest way possible. I this instance I only need to change one variable when creating the string. I have another where I need to do 2. That number will probably grow. The purpose of this is so I can send XML message to an HTTP server. This is for logging data.

In this instance it is the reader variable which is a word.

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IService/receiveHeartbeat</Action>
  </s:Header>
  <s:Body>
    <receiveHeartbeat xmlns="http://tempuri.org/">
      <reader>**Word Variable**</reader>
    </receiveHeartbeat>
  </s:Body>
</s:Envelope>

Solution

  • You can chain CONCAT functions like so:
    concat3: STRING := CONCAT(CONCAT(str1, str2), str3);

    However, beware that by default STRING is only 80 characters (81 bytes) long.

    If a size is not defined, then CODESYS allocates 80 characters by default.

    You can specify the size using parenthesis:
    concat3: STRING(255) := CONCAT(CONCAT(str1, str2), str3);
    But again, the standard CONCAT function (and others) only accepts and returns strings of up to 255 in length!

    If you need strings longer than 255, then check Working with Strings More Than 255 Characters in the codesys documentation.

    If you often work with strings, it might be useful to create your own Concat3, Concat4, etc.. functions for future use.

    If your codesys version supports default values for function inputs, and you don't mind wasting a few CPU cycles, you may do something like this:

    FUNCTION StringConcat : STRING(255)
    VAR_INPUT
        STR1: STRING(255);
        STR2: STRING(255);
        STR3: STRING(255):= '';
        STR4: STRING(255):= '';
        // etc up to a large number
    END_VAR
    
    StringConcat := CONCAT(STR1 := StringConcat, STR2 := STR1);
    StringConcat := CONCAT(STR1 := StringConcat, STR2 := STR2);
    StringConcat := CONCAT(STR1 := StringConcat, STR2 := STR3);
    StringConcat := CONCAT(STR1 := StringConcat, STR2 := STR4);
    // etc up to all defined inputs
    

    With the function above, you can use the same function to concatenate as many strings as you want (well, up to the number of inputs you defined), for example:

    str1: STRING(255);
    str2: STRING(255);
    
    // implementation:
    str1 := StringConcat('Hello', ' ', 'World', '!');
    str2 := StringConcat('Hell', 'o', ' ', 'World', '!', '!', '!');
    

    Result:

    result

    Although, beware that using StringConcat during declaration produces garbage (seems to be a bug in codesys with default values in the declaration), for example:

    str1: STRING(255) := StringConcat('Hello', ' ', 'World', '!');
    

    Results is:

    result