Yocto-Meteo : Application mobile sous Android

02 mai 2017 rdorigny 0 commentaires

Un article pour réaliser une application mobile assez simple qui affichera les données de la sonde Yocto-Meteo. Elle vous permettra de prendre connaissance à distance de la température de votre maison.

La principale difficulté consiste à récupérer les données stockées dans la base de données. Pour cela nous allons réaliser un petit web service en REST/JSON avec un script php.






Pour mĂ©moire, nous avons rĂ©alisĂ© un script qui enregistre tous les quarts d'heure les donnĂ©es d'une sonde mĂ©tĂ©o de chez Yoctopuce. Notre objectif est d'afficher les valeurs de la derniĂšre mesure. Pour cela nous allons crĂ©er un script qui reçoit une requĂȘte web et qui retourne les donnĂ©es dans une rĂ©ponse en JSON.

Voici le script, n'oubliez pas d'initialiser la variable de connexion à la base de données:
<?php // ************************************************************************************************************* // // Ceci est l'API du web service restfull/json du serveur domotique // // DORIGNY Robert - rdorigny@free.fr - 25/08/2014 // // ************************************************************************************************************* //**************************Ici vous devrez gérer la connexion à la base de données ....c'est à vous d'initialiser la variable $Connection if ((isset($_GET["action"]))&&(isset($_GET["var"]))) { switch ($_GET["action"]) { case ("get") : api_get($_GET["var"]); break; default: print("L'action appelée n'existe pas."); } } else print("Erreur lors de l'utilisation de l'API"); function api_get($var) { global $Connection; switch ($var) { case ("temp") : //Récupération des données $requete="select tempp,pres,humidite,date from masonde BY num DESC LIMIT 1 "; $resultat=mysql_query($requete,$Connection); if ($resultat) { $t=mysql_fetch_row($resultat); $temp=$t[0]; } else $temp="Impossible d'obtenir la température."; $tab = array(); $tab["context"] = array("id"=>"441618","owner"=>"DORIGNY Robert","local"=>"fr,Saint Remy les chevreuse"); $tab["pht"] = array("pres"=>$t[1],"hum"=>$t[2],"temp"=>$t[0],"date"=>$t[3]); print(json_encode($tab)); break; default: print("La variable appelée n'existe pas."); } } ?>



Si on envoie la requĂȘte sur http://www.lesite.fr/api.php?action=get&var=temp, vous obtiendrez la rĂ©ponse json avec les donnĂ©es:

{"context":{"id":"441618","owner":"DORIGNY Robert","local":"fr,Saint Remy les chevreuse"},"pht":{"pres":"1015.00", "hum":"48.40","temp":"22.94","date":"08 05 2017 18:45:32"}}

Ensuite, il suffit de transmettre cette requĂȘte via l'application mobile, et afficher les donnĂ©es extraites. L'Ă©lĂ©ment important Ă  prendre en compte, c'est que la rĂ©ception d'un web service est considĂ©rĂ© dans le framework Android comme une opĂ©ration lente et risquĂ©. Donc le traitement de cette opĂ©ration sera rĂ©alisĂ©e via une tĂąche asynchrone (AsyncTask).

Le layout de notre application:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="wrap_content" android:layout_height="wrap_content" tools:context="fr.doritique.maison.MainActivity" tools:layout_editor_absoluteY="81dp" tools:layout_editor_absoluteX="0dp"> <RelativeLayout android:layout_width="368dp" android:layout_height="495dp" tools:layout_editor_absoluteX="8dp" tools:layout_editor_absoluteY="8dp"> <TableLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true"> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="30dp" android:layout_weight="1" android:text="Pour le bureau " tools:text="Pour le bureau " /> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/textView9" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Date - Heure" tools:text="Date - Heure" /> <TextView android:id="@+id/textView10" android:layout_width="25dp" android:layout_height="15dp" android:layout_weight="1" android:text=":" tools:text=":" /> <TextView android:id="@+id/ladate" android:layout_column="3" android:gravity="left" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" "/> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/textView3" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Temperature" tools:text="Temperature" /> <TextView android:id="@+id/textView8" android:layout_width="25dp" android:layout_height="15dp" android:layout_weight="1" android:text=":" tools:text=":" /> <TextView android:id="@+id/latemperature" android:layout_column="3" android:gravity="left" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" "/> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/textView4" android:layout_width="70dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Humidité" tools:text="Humidité" /> <TextView android:id="@+id/textView6" android:layout_width="25dp" android:layout_height="15dp" android:layout_weight="1" android:text=":" tools:text=":" /> <TextView android:id="@+id/lhumidite" android:layout_column="3" android:gravity="left" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Pression" tools:text="Pression" /> <TextView android:id="@+id/textView7" android:layout_width="25dp" android:layout_height="15dp" android:layout_weight="1" android:text=":" tools:text=":" /> <TextView android:id="@+id/lapression" android:layout_column="3" android:gravity="left" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </TableRow> </TableLayout> <Button android:id="@+id/MyBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="rafraichir" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" /> </RelativeLayout> </android.support.constraint.ConstraintLayout>


Le code de l'application:
package fr.doritique.maison; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class MainActivity extends AppCompatActivity { public Toast toast; public static final String TAG ="Mon_TAG"; public TextView latemperature, lapression, lhumidite, ladate; public String t; //température public String p; //pression public String h; //humidité public String d; //date @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); latemperature=(TextView) findViewById(R.id.latemperature); lapression=(TextView) findViewById(R.id.lapression); lhumidite=(TextView) findViewById(R.id.lhumidite); ladate=(TextView) findViewById(R.id.ladate); Button btn = (Button) findViewById(R.id.MyBtn); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Affiche(); } }); } public void Affiche(){ //toast=Toast.makeText(this,"test",Toast.LENGTH_LONG); //toast.show(); new RequestTask().execute("http://www.monsite.fr/api.php?action=get&var=temp"); } private class RequestTask extends AsyncTask<String, Void, String> { private String response = ""; @Override protected String doInBackground(String... urls) { Recup_WS_domo(); response=p; return response; } public void Recup_WS_domo(){ h="Ca ne marche pas..."; t="Ca ne marche pas..."; p="Ca ne marche pas..."; d="Ca ne marche pas..."; HttpURLConnection urlConnection = null; BufferedReader reader = null; String forecastJsonStr = null; try { URL url = new URL("http://www.monsite.fr/api.php?action=get&var=temp"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); BufferedReader bufferedreader=new BufferedReader(new InputStreamReader(inputStream)); StringBuilder strinbulder=new StringBuilder(); String ligne=bufferedreader.readLine(); while (ligne!=null){ strinbulder.append(ligne+"n"); ligne=bufferedreader.readLine(); } bufferedreader.close(); JSONObject jso=new JSONObject(strinbulder.toString()); JSONObject jsomain=jso.getJSONObject("pht"); h=jsomain.getString("hum"); t=jsomain.getString("temp"); p=jsomain.getString("pres"); d=jsomain.getString("date"); StringBuffer buffer = new StringBuffer(); forecastJsonStr = buffer.toString(); } catch (IOException e) { Log.e("PlaceholderFragment", "Error ", e); } catch (JSONException e) { e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } } @Override protected void onPostExecute(String result) { latemperature.setText(t+" °C"); lapression.setText(p+" Pa"); lhumidite.setText(h+" %"); ladate.setText(d); } } }


Sans oublier d'autoriser les échanges de données Internet dans le fichier manifest:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fr.doritique.maison"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>


Ce qui donne une fois le fichier apk installé sur votre téléphone:


Voilà, le début d'une application domotique qui affiche les données de la sonde Yocto-Meteo. Je vous laisse reprendre le code et l'adapter à votre guise. Bon code!





Pseudonyme (obligatoire) :
Adresse mail (obligatoire) :
Site web :




© 2024 www.doritique.fr par Robert DORIGNY