1

I'm experiencing an issue with sending AT commands through a serial port in my code. The problem is that when I send the following commands:

while (true) {
    thread_sleep_for(5000);

    sendATCommand("AT+CIPSENDEX=0,64");
    sendATCommand("test\\0");
}

The TCP receiver ends up receiving the string AT+CIPSENDEX=0,64 along with test.

To make it more clear: The expected behavior on TCP receiver is:

test

However, current behavior is:

AT+CIPSENDEX=0,64
test

When I did some further testing, I noticed some strange behaviour; when I uncomment a printf statement in sendATCommand, the issue seems to be resolved, and the TCP receiver only gets test:

Here's the relevant code for the sendATCommand function:

void sendATCommand(const char* command, ...) {
    char fullCommand[256] = {0};
    va_list args;
    va_start(args, command);

    vsnprintf(fullCommand, 256, command, args);
    va_end(args);

    // Uncommenting the following line magically fixes the issue:
    // printf("the command is: %s\n", fullCommand);

    strcat(fullCommand, "\r\n"); // Append carriage return and newline
    serial_port.write(fullCommand, strlen(fullCommand));
}

Questions:

  • Why does the TCP receiver receive the AT+CIPSENDEX=0,64 command along with test?
  • What could be causing this behavior where the problem is fixed just by including a printf statement?
  • How can I resolve this issue so that only the intended message (test) is sent and received correctly?

Thank you for your help!

3
  • Why do you believe the optional arguments are relevant to the problem? Does the problem disappear if you remove all the vararg stuff? Commented Aug 13, 2024 at 8:59
  • 2
    When this question was in the staging ground several comments regarding possible timing issues were made. Did you investigate those? Commented Aug 13, 2024 at 9:38
  • Side-note: NB, regarding vsnprintf notice that it does not nul-terminate the string if it would have overflown, so you really really should make it a habit to always handle such cases correctly, although that is unrelated to the question you are asking here. Commented Aug 13, 2024 at 16:05

0