Page 1 of 1
[SOLVED] Help with sending .txt file over HTTP formatted as a .json file
Posted: Tue Dec 13, 2022 7:00 pm
by zydizz
Hi everyone,
Hello! This is my first time in this forum. I am developing a device that takes measurements from a microphone and stores these measurements into a txt file, logging each second. The end goal is then sending the contents of this .txt file in a .JSON object over HTTP to a server to make datalogging and analysing easy. A minute of calculation data creates a file about 20kb.<br/>
The json object will look like this:
{
"DeviceId": "123456",
"Data": "THE MULTI-LINE DATA READ FROM THE SD CARD AS A VARIABLE"
}
The steps in my head was like such;
- Read the file into a character array with the size of the file
- Format said array into a string like json
But the main issue occurs at the second part, I am not able to format the array without any heap overflows. Will address my previous ideas after code snippet.
What may be the ideal form of sending the data in json form? Using streams and just the WifiClient?
(Libraries used:
WiFi.h, HTTPClient.h, ArduinoJson.h, FS.h, SD.h)
void readPost(fs::FS &fs, const char * path, const char * httpUrl) {
Serial.printf("Reading file: %s\n", path);
File file = fs.open(path);
if(!file) {
Serial.println("Failed to open file for reading");
return;
}
const size_t fLen = file.size();
char * fileBuffer = new char[fLen + 1];
while(file.available()){
fileBuffer[file.position() - 1] = file.read();
}
file.close();
char * fileData = new char[fLen + 33];
sprintf(fileData, "{\"DeviceId\":\"%s\",\"Data\":\"%s\"}", deviceId, fileBuffer);
delete [] fileBuffer;
if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status
HTTPClient http;
http.begin(String(httpUrl)); //Specify the URL and certificate
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST((uint8_t *)fileData, sizeof(fileData));
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
http.end(); //Free the resources
}
delete [] fileData;
}
Re: Help with sending .txt file over HTTP formatted as a .json file
Posted: Wed Dec 14, 2022 7:17 pm
by lbernstone
I don't think the HTTPClient will do what you want. Rather than shoehorning that library to do something out of scope, just use WiFiClientSecure. Read in 4096 bytes at a time from the file, and write it out to the socket as you parse that. This will give you full control over what the output looks like.
Re: Help with sending .txt file over HTTP formatted as a .json file
Posted: Thu Dec 15, 2022 6:33 am
by zydizz
lbernstone wrote: ↑Wed Dec 14, 2022 7:17 pm
just use WiFiClientSecure. Read in 4096 bytes at a time from the file, and write it out to the socket as you parse that. This will give you full control over what the output looks like.
Thanks, I thought so. Can you provide an example how should i do that? Will newline operators be problematic or will they stil stay in the https request?
Is my current "read to a array then send" method problematic? Should I send the data in 4096 byte partitions as I read? Because I want the whole data in a single json formatted https request.
Re: Help with sending .txt file over HTTP formatted as a .json file
Posted: Thu Dec 15, 2022 5:28 pm
by lbernstone
Sorry, I am not going to do your homework for you, mostly because I think your http flow is not correct. The more compliant way to send data like this to a server would be as an argument to the request string. That means your URL would be something like "
https://server.example.com/postdata?json={data1:.....}". This is much easier to construct, will work just fine with HTTPClient, and is guaranteed to be accepted by any server.
If you don't have control of the backend, then you will have to fit to what it expects. You need to use a tool like curl/wireshark or postman to generate a transaction that works properly with your server before you try to build it on the esp32. Once you know what the request should look like, it should be fairly easy to use the WiFiClientSecure example (
https://github.com/espressif/arduino-es ... Secure.ino) as a template to generate the necessary text. As far as newlines go, it is standard http. A single CR is a line break, two CRs is an EOM marker. WiFiClient::write posts just the string, WiFiClient::print puts a CR at the end.
Re: Help with sending .txt file over HTTP formatted as a .json file
Posted: Fri Dec 16, 2022 7:15 am
by zydizz
Thank you so much for your detailed answer.
lbernstone wrote: ↑Thu Dec 15, 2022 5:28 pm
Sorry, I am not going to do your homework for you, mostly because I think your http flow is not correct.
Sorry if i made it sound that way, that was not my intention. Since I'm fairly new to http (literally a week) I'm kind of lost between many different methods. And I'm still trying to grasp the concepts of the http request headers, body, etc...
lbernstone wrote: ↑Thu Dec 15, 2022 5:28 pm
If you don't have control of the backend, then you will have to fit to what it expects. You need to use a tool like curl/wireshark or postman to generate a transaction that works properly with your server before you try to build it on the esp32.
The server expects a string in the form of a serialized json file as such. I will try generating a transaction in postman, thanks.
{"DeviceId": "123456", "Data": "DATA FROM THE SD CARD"}
I am now trying to work with WifiClient.h and at least I got a response from the server that my request was invalid. Good so far. Will a 20kb array be too big for client.print() to send in a single line? Because I cannot see any errors/etc. on the server AND code side.
Re: Help with sending .txt file over HTTP formatted as a .json file
Posted: Sat Dec 17, 2022 7:53 pm
by lbernstone
WiFiClient::print will only be limited by your available memory. That said, as your initial issue was about memory consumption, why not keep it as low as possible. json doesn't care about whitespace (you can use \n if you really need it for readability), and you can let the IP stack do the buffering for you, so just printf directly to the client object (and the socket underneath) as you parse the file. Read in 4096 bytes (the size of a "disk" sector), and have the client.printf the string in a for loop. That way you will never be using much more than that 4k, and can keep everything in stack space, and you minimize the processing.
Re: Help with sending .txt file over HTTP formatted as a .json file
Posted: Thu Dec 22, 2022 11:47 am
by zydizz
@lbernstone,
Before trying to implement the sequential read I tried to port my code over to WifiClient.h but after 3 days of trying everything there still is no content in the body of the request. Can you see where my issue lies (im highly suspecting the \n's and \r's)?
(The first part hasn't changed at all, just the part after "WiFiClient client")
WiFiClient client;
Serial.println("\nStarting connection to server...");
if (!client.connect(httpHost, 80))
Serial.println("Connection failed!");
else {
Serial.println("Connected to server!");
client.println();
client.println();
client.println("POST " + String(httpPath) + " HTTP/1.1");
// Make a HTTP request
client.println("Host: " + String(httpHost));
client.println("Connection: close");
client.println("Content-Type: application/json");
client.println();
client.print("{\"DeviceId\":\"");
client.print(deviceId);
client.print("\",\"Data\":\"");
client.print("lorem ipsum");
client.print("\"}");
client.print("\r\n");
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
Serial.println("headers received");
break;
}
}
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
Serial.println();
}
client.stop();
delete [] fileBuffer;
}
Esp32 serial readout:
- esp.png (21.58 KiB) Viewed 4422 times
Request recieved by Postman's mock server (internally created post requests are successfully transferred):
- postman.png (23.9 KiB) Viewed 4422 times
Re: Help with sending .txt file over HTTP formatted as a .json file
Posted: Thu Dec 22, 2022 1:58 pm
by zydizz
ISSUE IS SOLVED, the request just needed a Content-Length header haha. A 1 week brain melting session finally resulted in something.
Thanks a lot for your advices @lbernstone, hope you have a nice day.