1 year ago
#312183

Feynman137
Extracting a variable value from a multi-line MQTT message with C++
My microcontroller is receiving an MQTT message through a UART connection to a cellular modem in response to an AT command, the response I am getting looks like:
21:25:42.224 -> AT+QMTPUBEX=1,0,0,0,"motorbeta/heartbeat","{"pulse":1,"secondary":2}"
21:25:42.224 -> OK
21:25:42.224 ->
21:25:42.224 -> +QMTPUB: 1,0,0
21:25:42.224 ->
21:25:42.224 -> +QMTRECV: 1,0,"motorbeta/shutdown","shutdown=1"
I am sending the command and recording the response on the serial monitor using some c++ which looks like:
//AT command sequences
void atsendbasic(String command, int fallout3, int fallout4){
unsigned long initialtime4 = millis();
Serial2.print(command);
Serial2.flush(); // Wait until it is all sent
while ((!Serial2.available() && millis() - initialtime4 <= fallout3) || millis() - initialtime4 <= fallout4) continue;
while ((Serial2.available()&& millis() - initialtime4 <= fallout3) || millis() - initialtime4 <= fallout4) {
char feedback = Serial2.read();
Serial.print(feedback);
}
}
But I need to store the value in the last line of the MQTT response in a global integer variable named shutdown. What I have so far should work for 1 line responses, like when I run with just +QMTRECV: 1,0,"motorbeta/shutdown","shutdown=1"
as the input, but doesn't work for multi line responses.
int shutdown;
int
getValue (char *s,const char *lbl,int *val ){
char fmt [40];
sprintf (fmt, "%s=", lbl);
char *q = strstr (s, fmt);
if (NULL == q)
return 0;
sprintf (fmt, "%s=%%d", lbl);
sscanf (q, fmt, val);
return 1;
}
void atreceivebasic(String command, int fallout3, int fallout4){
char feedback;
unsigned long initialtime5 = millis();
Serial2.print(command);
Serial2.flush(); // Wait until it is all sent
while ((!Serial2.available() && millis() - initialtime5 <= fallout3) || millis() - initialtime5 <= fallout4) continue;
while ((Serial2.available()&& millis() - initialtime5 <= fallout3) || millis() - initialtime5 <= fallout4) {
feedback = Serial2.read();
Serial.print(feedback);
}
getValue ((char*)feedback, "shutdown", &shutdown);
Serial.println(shutdown);
}
I am having trouble modifying this C++ to incorporate multi line responses, mostly because I don't fully understand how it works for the single line example. Can someone help me solve this problem.
c++
serial-port
mqtt
at-command
0 Answers
Your Answer