I think I finally got it:
void callback(const char* topic, byte* payload, unsigned int length) {
// create array large enough to hold null terminated payload
char nullTermedPayload[length+2];
// prep by clearing
memset(nullTermedPayload, 0, sizeof(nullTermedPayload));
// copy payload to nullTermPayload, this adds null terminator automatically
memcpy(nullTermedPayload, payload, length);
// NOTE: cannot do if(topic == "hydro1"), and in strcmp, 0 is a match. 1 is not a match.
if (strcmp(topic, "hydro1") == 0) {
Serial.print("payload received in callback from MQTT server: ");
Serial.println((const char*) payload);
Serial.print("length of the message payload: ");
Serial.println(length);
Serial.print("nullTermedPayload: ");
Serial.println((const char*) nullTermedPayload);
Serial.print("length of the nullTermedPayload: ");
Serial.println(sizeof(nullTermedPayload));
char *firstToken, *secondToken, tempBuffer[25];
// strtok mutates the char array given it!!!
strcpy(tempBuffer, (const char *)nullTermedPayload);
firstToken = strtok(tempBuffer, ":");
Serial.print("First Token = ");
Serial.println(firstToken);
secondToken = strtok(NULL, ":");
Serial.print("Second Token = ");
Serial.println(secondToken);
}
}
But I'm still getting that weird trailing numbers and "vag" from if (client.connect("ajxfcvag", MQTT_USER, MQTT_PASS)) { when I directly println the payload. But when I output payload as HEX the trailing numbers and vag don't show up.
payload (receivedChars) on the Arduino to be published to MQTT: T1:20.25
payload received in callback from MQTT server: T1:20.25.250vag
length of the message payload: 8
nullTermedPayload: T1:20.25
length of the nullTermedPayload: 10
First Token = T1
Second Token = 20.25
payload (receivedChars) on the Arduino to be published to MQTT: A0:93.00
payload received in callback from MQTT server: A0:93.00.000vag
length of the message payload: 8
nullTermedPayload: A0:93.00
length of the nullTermedPayload: 10
First Token = A0
Second Token = 93.00