SIM7600与ESP32-S3无法获取大体积HTTPS请求内容问题排查
问题分析与代码优化方案
针对SIM7600模块下载大文件时提前断开的问题,先梳理现有代码中的关键问题,再给出优化后的实现:
现有代码的核心问题
- 变量名笔误:串口打印时误用了WiFi函数中的
buff和len变量,实际应为当前函数的buffer和readSize,这会导致未定义行为,甚至干扰程序运行。 - 错误的终止逻辑:读取到0字节直接
break,但SIM模块的网络数据并非持续推送,0字节仅代表当前无可用数据,并非传输完成,这是导致提前中断下载的主要原因。 - 缺少超时机制:未设置HTTP请求的全局超时,也未在循环中处理长时间无数据的情况,容易导致连接异常断开。
- 无错误重试/状态检查:读取失败时直接终止,未尝试重新读取或检查连接状态。
优化后的SIM7600下载函数
bool FetchAndSaveJsonSIM() { HttpClient httpGetCards(secure_layer, mainServer, 443); // 设置全局超时,与WiFi保持一致 httpGetCards.setTimeout(30000); // 若服务器不支持长连接,可注释此行,避免连接超时 // httpGetCards.connectionKeepAlive(); httpGetCards.beginRequest(); httpGetCards.get(getAddressPath); httpGetCards.sendHeader("Authorization", String("Bearer ") + bearerToken); httpGetCards.endRequest(); int httpCode = httpGetCards.responseStatusCode(); int contentLength = httpGetCards.contentLength(); if (httpCode != 200) { Serial.printf("FetchAndSaveJsonSIM GET failed, error: %d\n", httpCode); httpGetCards.stop(); return false; } Serial.print("FetchAndSaveJsonSIM http response: "); Serial.print(httpCode); Serial.print(", content size: "); Serial.println(contentLength); if (contentLength <= 0) { Serial.printf("FetchAndSaveJsonSIM invalid content length: %d.\n", contentLength); httpGetCards.stop(); return false; } File file = SPIFFS.open(filePath, FILE_WRITE); if (!file) { Serial.println("FetchAndSaveJsonSIM SPIFFS file couldn't open."); httpGetCards.stop(); return false; } const int bufferSize = 256; uint8_t buffer[bufferSize]; int bytesRead = 0; // 超时计数:连续无数据的次数,每次间隔10ms,300次即3秒超时 int timeoutCount = 0; const int maxTimeoutCount = 300; while (httpGetCards.connected() && bytesRead < contentLength) { int readSize = httpGetCards.read(buffer, bufferSize); if (readSize > 0) { file.write(buffer, readSize); // 修复变量名笔误 Serial.write(buffer, readSize); Serial.println(); bytesRead += readSize; // 有数据读取到,重置超时计数 timeoutCount = 0; } else { // 无数据时,增加超时计数,达到阈值再终止 timeoutCount++; if (timeoutCount >= maxTimeoutCount) { Serial.println("FetchAndSaveJsonSIM: Data timeout, aborting."); break; } } // 短延时,给模块时间接收数据 delay(10); } file.close(); httpGetCards.stop(); Serial.print("bytesRead: "); Serial.println(bytesRead); if (bytesRead == 0 || bytesRead != contentLength) { Serial.println("Could not get new JSON completely. Operation failed."); return false; } Serial.printf("New JSON successfully written to memory. Total written bytes: %d\n", bytesRead); return true; }
额外优化建议
- 调整SIM7600模块设置:通过AT命令优化模块的网络参数,例如:
- 设置HTTP接收缓冲区大小:
AT+HTTPSSRC=2(具体值参考模块手册,部分型号支持调整缓冲区) - 开启HTTP分块传输支持:
AT+HTTPCHUNK=1(若服务器支持分块传输)
- 设置HTTP接收缓冲区大小:
- 降低缓冲区大小:若模块串口缓冲区较小,可将
bufferSize调整为128,避免数据溢出。 - 检查供电稳定性:SIM7600在传输大文件时功耗较高,确保模块供电充足(建议使用5V/2A以上电源),供电不足也会导致连接中断。
内容的提问来源于stack exchange,提问作者Barkın Sarıkartal
相关产品推荐
相关产品推荐

