Domotique

Récupération JSON pour WT32

Pour permettre à un ESP32 (comme le WT32) de récupérer le JSON des thermostats via l'URL spécifiée et de l'enregistrer dans le SPIFFS pour alimenter la structure, voici comment vous pourriez structurer votre code côté microcontrôleur.

Étapes générales :

  1. Effectuer une requête HTTP GET à l'URL API Jeedom.
  2. Télécharger et stocker la réponse JSON dans le SPIFFS.
  3. Lire le fichier JSON depuis le SPIFFS et l'analyser pour remplir une structure en mémoire.

Voici un exemple de code pour le WT32/ESP32 en utilisant l'Arduino framework :

Code ESP32 côté Arduino

#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <SPIFFS.h>

// Configuration WiFi
const char* ssid = "Votre_SSID";
const char* password = "Votre_MotDePasse";

// URL de l'API Jeedom
const char* api_url = "http://xxxxxxxxxxxxxxxxxxxx/core/api/jeeApi.php?apikey=xxxxxxxxxxxxxxxxxxxxxxxxxxxi&type=cmd&id=44474";

// Fichier JSON dans le SPIFFS
const char* spiffs_file = "/thermostats.json";

// Structure du thermostat
struct Mode {
    String name;
    int cmd;
};

struct Thermostat {
    int id;
    String name;
    int order_max;
    int order_min;
    Mode modes[10];  // Adapter selon le nombre maximum de modes
    int modeCmdId;
    int statutCmdId;
    int tempCmdId;
    int getConsigneCmdId;
    int putConsigneCmdId;
};

void setup() {
    Serial.begin(115200);

    // Initialiser le SPIFFS
    if (!SPIFFS.begin(true)) {
        Serial.println("Erreur SPIFFS !");
        return;
    }

    // Connexion WiFi
    WiFi.begin(ssid, password);
    Serial.println("Connexion WiFi...");
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.print(".");
    }
    Serial.println("\nConnecté au WiFi");

    // Récupérer le JSON
    if (downloadThermostatJson()) {
        Serial.println("JSON récupéré et stocké !");
        parseThermostatJson(); // Lire et analyser le JSON
    } else {
        Serial.println("Erreur lors de la récupération du JSON.");
    }
}

void loop() {
    // Votre logique principale
}

// Télécharger le JSON depuis l'API Jeedom et le stocker dans le SPIFFS
bool downloadThermostatJson() {
    if (WiFi.status() == WL_CONNECTED) {
        HTTPClient http;
        http.begin(api_url);
        int httpCode = http.GET();

        if (httpCode == 200) { // Succès
            String payload = http.getString();

            // Écrire dans le SPIFFS
            File file = SPIFFS.open(spiffs_file, FILE_WRITE);
            if (!file) {
                Serial.println("Erreur d'ouverture du fichier pour écrire.");
                return false;
            }
            file.print(payload);
            file.close();
            return true;
        } else {
            Serial.printf("Erreur HTTP: %d\n", httpCode);
        }
        http.end();
    }
    return false;
}

// Lire le fichier JSON depuis le SPIFFS et l'analyser
void parseThermostatJson() {
    File file = SPIFFS.open(spiffs_file, FILE_READ);
    if (!file) {
        Serial.println("Erreur d'ouverture du fichier JSON.");
        return;
    }

    // Charger le JSON dans un objet ArduinoJson
    StaticJsonDocument<4096> doc; // Adapter la taille au besoin
    DeserializationError error = deserializeJson(doc, file);
    file.close();

    if (error) {
        Serial.printf("Erreur d'analyse JSON: %s\n", error.c_str());
        return;
    }

    // Exemple : parcourir et afficher les thermostats
    JsonArray thermostats = doc.as<JsonArray>();
    for (JsonObject thermostat : thermostats) {
        Serial.printf("Thermostat ID: %d, Name: %s\n", thermostat["id"].as<int>(), thermostat["name"].as<const char*>());
        JsonArray modes = thermostat["modes"];
        for (JsonObject mode : modes) {
            Serial.printf("  Mode: %s, Cmd: %d\n", mode["name"].as<const char*>(), mode["cmd"].as<int>());
        }
    }
}

Points Clés :

  1. SPIFFS : Utilisé pour stocker le JSON localement afin de le réutiliser sans refaire une requête.
  2. ArduinoJson : Permet de traiter et d'analyser les données JSON facilement.
  3. Gestion des erreurs : Vérifiez toujours les retours des fonctions SPIFFS, HTTP et JSON.

Étapes Suivantes :

  1. Adapter les tailles et structures pour s'assurer que tout le contenu est pris en charge.
  2. Optimiser la mémoire si le JSON est très volumineux, en utilisant un parsing par streaming.
  3. Ajouter une logique d'actualisation pour mettre à jour le JSON périodiquement ou sur demande.


Autre variante.

Parsing du JSON dans le code WT32-SC01

Pour alimenter la structure Thermostat, voici un exemple de code en C++ (Arduino) qui parse le JSON et charge les données dans une liste.

Exemple d'utilisation avec ArduinoJson

#include <ArduinoJson.h>
#include <SPIFFS.h>

#define JSON_SIZE 4096 // Ajustez selon la taille maximale de votre JSON

// Définition de la structure Thermostat
typedef struct {
    const char* label;
    int confortCmdId;
    int confort1CmdId;
    int confort2CmdId;
    int ecoCmdId;
    int horsGelCmdId;
    int offCmdId;
    int modeCmdId;
    int statutCmdId;
    int tempCmdId;
    int getConsigneCmdId;
    int putConsigneCmdId;
    int order_max;
    int order_min;
} Thermostat;

// Table de thermostats
Thermostat thermostats[10]; // Ajustez la taille selon vos besoins
int thermostatCount = 0;

void setup() {
    Serial.begin(115200);

    // Initialiser le SPIFFS
    if (!SPIFFS.begin(true)) {
        Serial.println("Erreur SPIFFS");
        return;
    }

    // Charger le JSON
    File file = SPIFFS.open("/thermostats.json", "r");
    if (!file) {
        Serial.println("Erreur lors de l'ouverture du fichier JSON");
        return;
    }

    // Lire le JSON
    StaticJsonDocument<JSON_SIZE> doc;
    DeserializationError error = deserializeJson(doc, file);
    if (error) {
        Serial.print("Erreur de parsing JSON: ");
        Serial.println(error.c_str());
        return;
    }

    // Parcourir les thermostats
    JsonArray array = doc.as<JsonArray>();
    thermostatCount = 0;
    for (JsonObject obj : array) {
        Thermostat& t = thermostats[thermostatCount++];
        t.label = obj["name"];
        t.confortCmdId = obj["modes"][0]["cmd"];
        t.confort1CmdId = obj["modes"][1]["cmd"];
        t.confort2CmdId = obj["modes"][2]["cmd"];
        t.horsGelCmdId = obj["modes"][3]["cmd"];
        t.ecoCmdId = obj["modes"][4]["cmd"];
        t.offCmdId = obj["modes"][5]["cmd"];
        t.modeCmdId = obj["modeCmdId"];
        t.statutCmdId = obj["statutCmdId"];
        t.tempCmdId = obj["tempCmdId"];
        t.getConsigneCmdId = obj["getConsigneCmdId"];
        t.putConsigneCmdId = obj["putConsigneCmdId"];
        t.order_max = obj["order_max"];
        t.order_min = obj["order_min"];
    }

    // Afficher les thermostats chargés
    for (int i = 0; i < thermostatCount; i++) {
        Serial.print("Thermostat ");
        Serial.println(thermostats[i].label);
    }
}

void loop() {
    // Boucle principale
}

Sauvegarde et Lecture dans SPIFFS

Enregistrez le JSON dans SPIFFS à l'aide de la commande suivante pour le tester :

Écriture initiale du JSON

void writeExampleJson() {
    const char* json = R"([
        {
            "id": 113,
            "name": "Salon",
            "order_max": 28,
            "order_min": 9,
            "modes": [
                { "name": "Confort", "cmd": 755 },
                { "name": "Confort -1", "cmd": 8404 },
                { "name": "Confort -2", "cmd": 8405 },
                { "name": "Hors Gel", "cmd": 44440 },
                { "name": "Eco", "cmd": 756 },
                { "name": "Off", "cmd": 752 }
            ],
            "modeCmdId": 10001,
            "statutCmdId": 10002,
            "tempCmdId": 10003,
            "getConsigneCmdId": 10004,
            "putConsigneCmdId": 10005
        }
    ])";

    File file = SPIFFS.open("/thermostats.json", "w");
    if (!file) {
        Serial.println("Erreur lors de la création du fichier JSON");
        return;
    }

    file.print(json);
    file.close();
}

Appelez cette fonction une fois dans le setup() pour initialiser le fichier JSON dans SPIFFS.

 

 

 

Related Articles

Information

Ce site est construit autour de Joomla 5, en utilisant le template Helix Ultimate et les composants : SP Builder Pro pour la construction de certaines pages, Smart Slider 3 Free pour les slideshows, Komento Free pour les commentaires sur les articles et Ignite Gallery pour les galeries de photos.

Mentions légales

Le site est édité par Christian Sammut
130, Avenue du Général Leclerc
45800 Saint Jean de Braye
Tél.: 06.01.74.90.33
E-mail: contact@sammut.fr

Ce site est hébergé par AMEN SASU
12-14, Rond Point des Champs Elysées
75008 Paris