getpost27
Bac STI2D

TP n°35 : Application hybride  <- Json -> objets connectés

Noms :  
Centre d'intérêt : CI 5 Communication entre systèmes
Classe : Term Sti2d Sin
Id programme : sin15, sin31  
Conditions : binôme , durée  3 heures.
Matériel : - un ordinateur;
- un Esp32 ou Esp8266;
- une smartphone ou une tablette;

Logiciel : - l'ide Netbeans;
- l'ide arduino;
- Utiliser le navigateur chrome;
Document :  

I. Objectifs

II. Introduction

Nous avons vu que les données peuvent être structurées sous différents formats.

XML et JSON sont les plus répandus.

Exemple de données au format xml :

<data>
  <temp>19.07</temp>
  <humi>27</humi>
  <led1>OFF</led1>
</data>

Exemple de données au format json :

{
  "temp":19.07,
  "humi":27,
  "led1":"OFF"
}

Nous voyons que le format Json est plus avantageux que le Xml. En effet, il est plus :

Légé (donc vitesse de traitement réduite),
Simple à mettre en oeuvre par les développeurs,
Lisible aussi bien par l'Homme que par la machine.

III. Traitement json sur Esp

En mode serveur

//Charger la librairie Wifi pour l'Esp
#include <ESP8266WiFi.h>

//declaration des parametres wifi
const char* ssid = "EspSin";
const char* password = "12345678";

WiFiServer server(80); //Utilise le port http

void setup() {
Serial.begin(115200);
delay(10);
Serial.println(WiFi.localIP());
// prepare GPIO2
//Declare la sortie BUILTIN_LED
pinMode(BUILTIN_LED, OUTPUT);
digitalWrite(BUILTIN_LED, LOW);

// Connection au Wifi de la salle
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

//Déclaration du point d'accès
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, password);

//Demarrage du serveur
server.begin();
Serial.println("Serveur Esp Ok");

//Affiche l'adresse IP de l'Esp
Serial.println(WiFi.localIP());
}

void loop() {
//Teste si un client est connecté

WiFiClient client = server.available();
if (!client) {
return;
}

// Attend que le client envoie des données
while (!client.available()) {
delay(1);
}

//Récupère la 1ère ligne de la requète
String req = client.readStringUntil('\r');
client.flush();

//Traite la requète
if (req.indexOf("") != -10) { //Vérifie si c'est la page principale

if (req.indexOf("/OFF") != -1) { //Vérifie si OFF
digitalWrite(BUILTIN_LED, LOW);
Serial.println("Led OFF");
}
if (req.indexOf("/ON") != -1) { //Vérifie si ON
digitalWrite(BUILTIN_LED, HIGH);
Serial.println("Led ON");
}
}
else {
Serial.println("invalid request");
client.stop();
return;
}

//Créer la réponse Json
String s = "HTTP/1.1 200 OK\r\n";
s += "Content-Type: application/json\r\n\r\n";
s += "{";
s += "'temp':";
s += analogRead(A0);
s += ",'humi':";
s += analogRead(A0);
s += ",'led1':";
s += digitalRead(3);
s += "}";

client.flush(); //initialise le client.print


//Envoie le json au client
client.print(s);
delay(1);
}

 

Envoyer sur un serveur (mode client)

#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>

void setup() {

Serial.begin(115200); //Serial connection
WiFi.begin("YourNetworkName", "YourPassword"); //WiFi connection

while (WiFi.status() != WL_CONNECTED) { //Wait for the WiFI connection completion

delay(500);
Serial.println("Waiting for connection");

}

}

void loop() {

if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

StaticJsonBuffer<300> JSONbuffer; //Declaring static JSON buffer
JsonObject& JSONencoder = JSONbuffer.createObject();

JSONencoder["temp"] = analogRead(A0);
JSONencoder["humi"] = analogRead(A0);
JSONencoder["led1"] = digitalRead(3);

char JSONmessageBuffer[300];
JSONencoder.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
Serial.println(JSONmessageBuffer);

HTTPClient http; //Declare object of class HTTPClient

http.begin("http://sciencesappliquees.com/postjson"); //Specify request destination
http.addHeader("Content-Type", "application/json"); //Specify content-type header

int httpCode = http.POST(JSONmessageBuffer); //Send the request
String payload = http.getString(); //Get the response payload

Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload

http.end(); //Close connection

} else {

Serial.println("Error in WiFi connection");

}

delay(30000); //Send a request every 30 seconds

IV.Application hybride

Ouvrir le l'invité de commande :

cordova create monApp monapp.com monApp

cd monApp

cordova platform add android

cordova platform add windows

Aller dans le répertoire monapp\www

modifier index.php comme ci-dessous :

<!DOCTYPE html>

<html>
<head>
<title>Hello World</title>
<script src="https://www.rgraph.net/libraries/RGraph.common.core.js" ></script>
<script src="https://www.rgraph.net/libraries/RGraph.thermometer.js" ></script>
</head>
<body>
<div>temp=<spam id='temp'></spam>°C</div>
<div id='humi'></div>
<div id='led1'></div>


<script>

function lancerRequete(){
var maRequete = null; //initialiser l'objet

//déclare l'objet requete
if(window.XMLHttpRequest){
maRequete = new XMLHttpRequest();
}

//url du serveur
var url = "http://sciencesappliquees.com/templates/php/json.php";

//Choisir le type de requete
maRequete.open("GET", url, true);

//gestion de la reponse du serveur
maRequete.onreadystatechange = function(){
if(maRequete.readyState == 4){
//affiche la réponse du serveur
//alert(maRequete.responseText);
var data = JSON.parse(maRequete.responseText);
document.getElementById('temp').innerHTML = data.temp;
document.getElementById('humi').innerHTML = data.humi;
document.getElementById('led1').innerHTML = data.led1;

 

}
}

//envoyer la requete au serveur
maRequete.send();

//relance la fonction au bout de 2 secondes
setTimeout('lancerRequete()', 1000);
}
//lance la fonction 
lancerRequete();
</script>
</body>
</html>

 

 

Source : https://techtutorialsx.com/2017/01/08/esp8266-posting-json-data-to-a-flask-server-on-the-cloud/

 

Affichages : 5221