Parsing data received by Gateway


#1

I am not much of a C programmer and have completed a big program except for one remaining step, namely parsing a string delimited by a comma “,”.

I am following the example in the docs:

void handle_custom_data(uint8_t data, uint16_t length) {
Particle.publish(“Data Capture”, String((char)data));
}

I know I am receiving the correct string because I can see it on the web but how do I go about parsing it?

Here is a sample string: “@@,9,1235,5634,9234,|” I want to store the 9, 1235, 5634 and 9234 in int variables.

Any help is appreciated.


#2

I am not an expert either and there are many ways to do this, some more efficient than others. However it is a tedious process, unlike other languages.
First browse the String functions in the docs: Strings
Take a look at lastIndexOf(), which lets you find where the comma is. Then copy the characters between the commas into another string.
Once you have all the sections, use toInt() (also in the docs) to convert them to integers.

Another link to keep around is the Arduino Reference
Look at this tutorial: String Tutorial
Also, search the web for “parse comma delimited string”, or review this reference: http://www.cplusplus.com/reference/cstring/

I have to admit that given this is probably a common task, I am surprised I did not find a ready made example on the web. If you find one, please post it.


#3

Here is a solution:

//Assume String is                              "@@,8,7111,0,42,0,6,42,1,|"           
  int a, b, c, d, e, f, g, h
  //------------------------------------------------
sscanf((const char*)data, "@@,%d,%d,%d,%d,%d,%d,%d,%d,|", &a, &b, &c, &d, &e, &f, &g, &h);

#4

Thanks for responding. I was intrigued by this function, so I went to look up how it works.
This example was the most useful I found.