Search code examples
c++jsonhttpsimulinks-function

Manage HTTP response (uint_8 decimal vector) and use http parser to read JSON values


I am working in Simulink on a TCP connection between client (my computer) and server. Through standard Ethernet blocks, I send an HTTP request like the following:

GET /status HTTP/1.1
Host:...
Accept: application/json

To send it, I convert it with the uint8('GET /status...') command. The server responds, always with a uint8 array (decimal bytes) like this :

resp=[72 84 80 47 49 32 50 48...] //(HTTP/1.1 200 OK... ).

In the reply "resp" content, always in decimal characters, there is a text in JSON format like {"VarA":1000, "VarB":2000,...}.

My purpose is to create an S-function (but more generally a code in C++) that taking in input the vector "resp" returns the values of VarA and VarB (1000 and 2000).

I know that there are a lot of single-header source code like nlohmann/json or PicoHTTPParser but I don't know how to use them in the specific case.

  1. My idea is to convert "resp" into a string and then pass it to the functions already written in the .h files for JSON/HTTP management. Is this correct? Can it be done? I ask myself this question because I don't know what format the parse functions of those .h files take in input.

  2. I also wonder if it is right to convert it into a string and then work on it...does anyone know if there is something that works directly on the uint_8 vector?

  3. Should I extract the body message from "resp" before I work on it?

Sorry for these questions but I'm little bit confused. I don't even know how to search this problem on Google! Actually, I'm looking for the easiest way to get to the final goal.

Thank you everyone!


Solution

  • I used https://github.com/nlohmann/json. Very easy to use library. Please note that the capacity of the message body in boost library is limited to 8k. I had to write my own handlers (which in the end came out faster and more reliable). Yes, a little presumptuous, but I threw out all the extra checks and other heavy things. When you expect only json and only a specific format, you can ignore the universality and just return an exception if the input data is incorrect.