Search code examples
stringlazarusdelphi

String concatenation doesn't work


I created a simple class to store data receive from the serial port and split it following certain conditions. I realize it was not working as excepted, so I recode it step by step to see what was wrong. And I found that it was a string concatenation. Here is the code of the class. The line that fails is the buffer = buffer + tail;

unit InBuffer;

{$mode objfpc}{$H+}

interface

uses
    Classes, SysUtils;

type
    TInBuffer = class
        private
            buffer: String;
            messages: TStrings;
        public
            constructor Create;
            destructor Destroy;
            procedure Add(tail: string);
            function getBuffer: String;
            function getLast: String;
            function DataAvailable: boolean;
    end;

implementation

constructor TInBuffer.Create;
begin
    buffer := '';
    messages := TStringList.Create;
end;

destructor TInBuffer.Destroy;
begin
    messages.Free;
    inherited Destroy;
end;

procedure TInBuffer.Add(tail: string);
begin
    buffer := buffer + tail;
end;

function TInBuffer.GetBuffer: String;
begin
    Result := buffer;
end;

function TInBuffer.GetLast: String;
begin
    if DataAvailable then
        begin
        Result := messages[0];
        messages.Delete(0);
        end;
end;

function TInBuffer.DataAvailable: boolean;
begin
    Result := messages.Count > 0;
end;

end.

I use SdpoSerial for the communication stuff. In the OnRxData event I have this code.

procedure TfrmMain.serOnRxData(Sender: TObject);
var
    msg: string;
begin
    msg := ser.ReadData;
    buff.Add(msg);
    log('Stored buffer: ' + buff.getBuffer);
    log('Receive trace: ' + msg);
end;

In the log I see the correct data in "Receive trace", but the line in "Stored buffer" is always the same (the first message received in the communication). I've tried using functions like Copy or Concat to build the buffer, but nothing changes.

What may be I doing wrong?

Thanks.

EDIT: Following Abelisto's suggestion, I put this code inside a button's onClick event

buff.Add('111');
buff.Add('222');
ShowMessage(buff.getBuffer);

And the message shown is correct. So there is some problem with passing the data coming from the serial port. It's shown correctly in the log, but not in the buffer. Any ideas why?


Solution

  • While the external devices like RS232 or so on can post to the port anything you have to be ready for it. In the our case the device post the NULL character which is breaks the string in the C-written OS. The Pascal strings can handle it but not the OS wigets. However I was confused by console like app which is handle the NULL character fine. So be careful.