Désolé @hbachetti, de ne t’avoir pas remercié de ta réponse aussitôt.
Une petite mise à jour concernant mon projet :
J’ai réalisé un shield équivalent à l’EmonTX d’openEnergyMonitor regroupant les 8 capteurs cités dans le premier message de ce fil et les 2 relais. 2 régulateurs de tension 5 V alimentent la carte, un spécialement pour le capteur de gaz MQ-8 et l’autre pour le reste dshield. Les relais sortent du 12 V.
Cette carte est en sandwich entre une Mega et un shield Ethernet/SD.
Il y a 3 câbles pour récupérer les données des appareils Victron avec connecteurs JST à chaque extrémités, le câble du BMV 700 étant relié à un convertisseur TTL 3,3V/5V.
Le code fonctionne bien pour la réception des données, leur traitement et l’envoi par requête HTTP format JSON sur mon site EMONCMS.
N’ayant pas de connexion internet permanente pour des raison d’économie d’électricité, les données sont stockées sur une carte SD en attendant la reconnexion.
Mon problème du moment est d’envoyer toutes les données inscrites dans un fichier sur la carte SD via client.print().
Elles passent par une chaîne String en mémoire vive avant l’envoi.
J’ai constaté sur Wireshark, le sniffeur de paquets ethernet, que client.print() n’envoie que la première requête alors qu’un Serial.print() de la chaîne affiche bien tout le contenu du fichier. J’ai horodaté les requêtes en temps Unix.
Comment faire lire toute la chaîne à client.print() ? Comment afficher en temps réel ce que client.print() envoie vraiment?
Ou bien me faut-il passer par de multiples fichiers contenant une seule requête par fichier ? Et donc une boucle d’écriture puis de lecture.
Ci-joint le code de test pour la lecture sur la carte et l’envoi des données sur mon serveur.
#include <Arduino.h>
#include "SdFat.h"
#include <SPI.h>
#include <RTClib.h>
#include <Wire.h>
#include <Ethernet.h>
RTC_DS1307 rtc;
SdFat sd;
File logFile;
const uint8_t chipSelect = 4;
const char fileName[] = "datalog.txt";
// Error messages stored in flash.
#define error(msg) sd.errorHalt(F(msg))
// this must be unique
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x59, 0x67 };
// change to your network settings
byte ip[] = { 192, 168, 5, 53 };
byte gateway[] = { 192, 168, 5, 1 };
byte subnet[] = { 255, 255, 255, 0 };
char server[] = "192.168.5.50";
EthernetClient client;
String apikey = "aaaaabbbbbbccccccddddddddeeeee"; //localhost api key
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
boolean lastConnected = false; // state of the connection last time through the main loop
const unsigned long postingInterval = 10 * 1000; // delay between updates, in milliseconds
//============================================================
int value1[17] = {25341, 440, 5879, 222478, 15, 48, 65, 95, 99, 75, 32, 147, 258, 963, 5789, 11, 28};
int value2[11] = {25341, 440, 5879, 222478, 15, 48, 65, 95, 99, 75, 32};
//=============================================================
void dateTime(uint16_t* date, uint16_t* time) {
DateTime now = rtc.now();
// return date using FAT_DATE macro to format fields
*date = FAT_DATE(now.year(), now.month(), now.day());
// return time using FAT_TIME macro to format fields
*time = FAT_TIME(now.hour(), now.minute(), now.second());
}
//============================================================
void writeSD() {
DateTime now = rtc.now();
unsigned long currentTime = now.unixtime();
SdFile::dateTimeCallback(dateTime);
if (!logFile.open(fileName, O_CREAT | O_APPEND | O_WRITE )) {
error("write_logFile.open");
}
logFile.print("GET /emoncms/input/bulk?data=[[");
//(...)
logFile.print(value1[12]);
logFile.print("},{\"H22\":");
logFile.print(value1[13]);
logFile.print("},{\"H23\":");
logFile.print(value1[14]);
logFile.print("},{\"HSDS\":");
logFile.print(value1[15]);
logFile.print("}],[36,5,{\"MODE\":");
//(...)
logFile.print("},{\"H12\":");
logFile.print(value3[24]);
logFile.print("},{\"H17\":");
logFile.print(value3[25]);
logFile.print("},{\"H18\":");
logFile.print(value3[26]); */
logFile.print("}]]&time=");
logFile.print(currentTime - 7200);
logFile.print("&apikey=");
logFile.println(apikey);
logFile.println("HTTP/1.1");
logFile.println("Host:localhost");
logFile.println("User-Agent: Arduino-ethernet");
logFile.println("Connection: close");
logFile.println();
// Force data to SD and update the directory entry to avoid data loss.
if (!logFile.sync() || logFile.getWriteError()) {
error("logFile write error");
}
logFile.close();
Serial.println(F("Data writed"));
}
//============================================================
void readSD() {
if (!logFile.open(fileName, O_READ)) {
error("read_logFile.open");
}
if (logFile.available()) {
while (logFile.position() < logFile.size()) {
String dataBuff = logFile.readStringUntil('\0');
client.print(dataBuff);
//client.println();
//debug
//Serial.println(dataBuff);
}
}
else {
Serial.println(F("Nothing to send from SD card"));
}
logFile.close();
}
//============================================================
void fileTruncate() {
if (!logFile.open(fileName, O_WRITE)) {
error("trunc_file.open");
}
if (logFile.size() > 0) {
if (!logFile.truncate(0) == 0) {
Serial.println(F("Effacement OK"));
}
else {
error("echec effacement");
}
}
logFile.close();
}
//============================================================
void sendData() {
DateTime now = rtc.now();
unsigned long currentTime = now.unixtime();
//Serial.println(currentTime);
client.print("GET /emoncms/input/bulk?data=[[");
client.print("32,4"); // node MPPT-150_35
client.print(",{\"V\":");
client.print(value1[3]);
//(....)
client.print("},{\"AR\":");
client.print(value2[8]);
client.print("},{\"WARN\":");
client.print(value2[9]);
client.print("}]]&time=");
client.print(currentTime - 7200);
client.print("&apikey=");
client.print(apikey);
client.println(" HTTP/1.1");
//client.println("Host:genatfab.ovh");
client.println("Host:localhost");
client.println("User-Agent: Arduino-ethernet");
client.println("Connection: close");
client.println();
}
//============================================================
void doHTTP() {
if (client.available()) {
char c = client.read();
Serial.print(c);
}
if (!client.connected() && (lastConnected && (millis() - lastConnectionTime >= (postingInterval + 5000)))) {
Serial.println(F("\r\n"));
Serial.println(F("Disconnecting..."));
client.stop();
}
if (!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
if (client.connect(server, 80)) {
Serial.println(F("\r\n"));
Serial.println(F("Connected"));
//readSD();
sendData();
//fileTruncate();
lastConnectionTime = millis();
}
// if the server's disconnected more than 2 min, stop the client and write data on sd card:
if (!client.connected() && (millis() - (lastConnectionTime >= (postingInterval * 12)))) {
Serial.print(F("\r\n"));
Serial.println(F("disconnecting from server."));
client.stop();
writeSD();
Serial.println(F("Writing on SD card"));
Serial.println(F("\r\n"));
delay(30000);
}
}
lastConnected = client.connected();
}
//============================================================
void setup() {
Serial.begin(115200);
// Mega
pinMode(53, OUTPUT);
// disable w5100 SPI while setting up SD
pinMode(10, OUTPUT);
digitalWrite(10, HIGH);
// enable SD SPI
pinMode(4, OUTPUT);
digitalWrite(4, LOW);
rtc.begin();
if (! rtc.isrunning()) {
Serial.println("RTC ne fonctionne PAS!");
// La ligne qui suit ajuste le RTC à la date et time du moment de compilation
rtc.adjust(DateTime(__DATE__, __TIME__));
}
if (!sd.begin(chipSelect, SD_SCK_MHZ(50)))
{
sd.initErrorHalt();
}
Ethernet.begin(mac, ip, gateway, gateway, subnet);
digitalWrite(10, HIGH);
Serial.println(Ethernet.localIP());
//readSD();
//fileTruncate();
//writeSD();
}
//============================================================
void loop() {
doHTTP();
}
Emoncms_SD_test.ino (9.74 KB)