Hello,
I have been facing the same issue.
I have an ESP32 and I am trying to download an Arduino-compiled file - sketch.ino.bin from my nodeJS server.
Here is the NodeJS code -
Code: Select all
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/download') {
const filePath = './sketch.ino.bin'; // Change to your file's path
const fileName = 'sketch.ino'; // Change to your desired file name
res.setHeader('Content-Disposition', `attachment; filename=${fileName}`);
res.setHeader('Content-Type', 'application/octet-stream');
const fileStream = fs.createReadStream(filePath);
fileStream.pipe(res);
} else {
res.statusCode = 404;
res.end('Not Found');
}
});
const port = 3000; // Change to your desired port
server.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
On the ESP-side, I have this -
Code: Select all
#include <WiFi.h>
#include <HTTPClient.h>
#include <Update.h>
const char* ssid = "khushal";
const char* password = "123456789";
const char* serverAddress = "192.168.29.81";
const int serverPort = 3000; // Change to your server's port
const String firmwareFileName = "sketch.bin"; // The name of the firmware file to be downloaded and flashed
void setup() {
Serial.begin(115200);
delay(100);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Specify the URL for the firmware file you want to download
String url = "http://" + String(serverAddress) + ":" + String(serverPort) + "/download";
HTTPClient http;
http.begin(url);
int httpCode = http.GET();
if (httpCode == HTTP_CODE_OK) {
Serial.println("Downloading firmware...");
if (Update.begin(UPDATE_SIZE_UNKNOWN)) {
int len = http.getSize();
uint8_t buff[4096] = { 0 };
// get tcp stream
WiFiClient * stream = http.getStreamPtr();
// read all data from server
while(http.connected() && (len > 0 || len == -1)) {
// get available data size
size_t size = stream->available();
if(size) {
int act_size = ((size > sizeof(buff)) ? sizeof(buff) : size);
int c = stream->readBytes(buff, act_size);
// write it to Serial
int writtenCount = Update.write(buff, c);
Serial.println((String)"written:"+writtenCount+" act_size:"+act_size);
if (writtenCount != act_size) {
Serial.println("Error updating firmware here");
break;
}
if(len > 0) {
len -= c;
}
}
delay(1);
}
if (Update.end()) {
Serial.println("Firmware update successful!");
delay(10000);
ESP.restart();
} else {
Serial.println("Error updating firmware");
}
} else {
Serial.println("Error starting update");
}
} else {
Serial.println("Firmware download failed");
}
http.end();
}
void loop() {
}
When I try to run this code, I see that the ESP32 was able to write 4096 bytes, but after that, the Update.write() returns 0 and my code exits the loop.
What may be the possible cause of this?
Possibly any issue from the server-side code ?