Projet Bee-Honey't (Mobile)  0.2
BTS SNIR LaSalle Avignon 2020
CommunicationMQTT.java
Aller à la documentation de ce fichier.
1 package com.lasalle.beehoneyt;
2 
9 import android.content.Context;
10 import android.os.Bundle;
11 import android.os.Handler;
12 import android.os.Message;
13 import android.util.Log;
14 import org.eclipse.paho.android.service.MqttAndroidClient;
15 import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
16 import org.eclipse.paho.client.mqttv3.IMqttActionListener;
17 import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
18 import org.eclipse.paho.client.mqttv3.IMqttToken;
19 import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
20 import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
21 import org.eclipse.paho.client.mqttv3.MqttException;
22 import org.eclipse.paho.client.mqttv3.MqttMessage;
23 import org.json.JSONObject;
24 import org.json.JSONArray;
25 import org.json.JSONException;
26 import java.util.Iterator;
27 
32 public class CommunicationMQTT
33 {
37  private static final String TAG = "CommunicationMQTT";
41  static public MqttAndroidClient mqttAndroidClient;
42  private Handler handler = null;
46  public static final int TTN_CONNECTE = 1;
47  public static final int TTN_DECONNECTE = 2;
48  public static final int TTN_MESSAGE = 3;
52  private String serverUri = "tcp://eu.thethings.network:1883";
53  static public String clientId = "mes_ruches";
54  private String username = "mes_ruches";
55  private String password = "ttn-account-v2.vC-aqMRnLLzGkNjODWgy81kLqzxBPAT8_mE-L7U2C_w";
56 
63  public CommunicationMQTT(Context context, final Handler handler)
64  {
65  Log.v(TAG, "CommunicationMQTT() clientId = " + clientId);
66  this.handler = handler;
67  mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
68  mqttAndroidClient.setCallback(new MqttCallbackExtended()
69  {
70  @Override
71  public void connectComplete(boolean b, String s)
72  {
73  Log.w(TAG, "connectComplete() serverUri = " + s + " connecte = " + mqttAndroidClient.isConnected());
74  Message msg = Message.obtain();
75  Bundle bundle = new Bundle();
76  bundle.putInt("etat", TTN_CONNECTE);
77  msg.setData(bundle);
78  handler.sendMessage(msg);
79  }
80 
81  @Override
82  public void connectionLost(Throwable throwable)
83  {
84  Log.w(TAG, "connectionLost()");
85  Message msg = Message.obtain();
86  Bundle b = new Bundle();
87  b.putInt("etat", TTN_DECONNECTE);
88  msg.setData(b);
89  handler.sendMessage(msg);
90  }
91 
92  @Override
93  public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception
94  {
95  Log.w(TAG, "messageArrived() topic = " + topic + " message = " + mqttMessage.toString());
96  Message msg = Message.obtain();
97  Bundle b = new Bundle();
98  b.putInt("etat", TTN_MESSAGE);
99  b.putString("topic", topic);
100  b.putString("message", mqttMessage.toString());
101  msg.setData(b);
102  handler.sendMessage(msg);
103  }
104 
105  @Override
106  public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken)
107  {
108  Log.w(TAG, "deliveryComplete()");
109  }
110  });
111 
112  connecter();
113  }
114 
121  static public void setCallback(MqttCallbackExtended callback)
122  {
123  mqttAndroidClient.setCallback(callback);
124  }
125 
131  private void connecter()
132  {
133  MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
134  mqttConnectOptions.setAutomaticReconnect(true);
135  mqttConnectOptions.setCleanSession(false);
136  mqttConnectOptions.setUserName(username);
137  mqttConnectOptions.setPassword(password.toCharArray());
138 
139  try
140  {
141  Log.d(TAG, "connecter() serverUri = " + serverUri + " clientId = " + clientId);
142  mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener()
143  {
144  @Override
145  public void onSuccess(IMqttToken asyncActionToken)
146  {
147  DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
148  disconnectedBufferOptions.setBufferEnabled(true);
149  disconnectedBufferOptions.setBufferSize(100);
150  disconnectedBufferOptions.setPersistBuffer(false);
151  disconnectedBufferOptions.setDeleteOldestMessages(false);
152  mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
153  Log.d(TAG, "onSuccess() serverUri = " + serverUri + " clientId = " + clientId);
154  }
155 
156  @Override
157  public void onFailure(IMqttToken asyncActionToken, Throwable exception)
158  {
159  Log.d(TAG, "onFailure() serverUri = " + serverUri + " clientId = " + clientId + " exception = " + exception.toString());
160  }
161  });
162  }
163  catch (MqttException ex)
164  {
165  ex.printStackTrace();
166  }
167  }
168 
174  public void reconnecter()
175  {
176  Log.w(TAG, "reconnecter ()");
177  if (estConnecte())
178  deconnecter();
179  connecter();
180  }
181 
187  public void deconnecter()
188  {
189  Log.d(TAG, "deconnecter() serverUri = " + serverUri + " clientId = " + clientId);
190  try
191  {
192  IMqttToken disconToken = mqttAndroidClient.disconnect();
193  disconToken.setActionCallback(new IMqttActionListener()
194  {
195  @Override
196  public void onSuccess(IMqttToken asyncActionToken)
197  {
198  Log.d(TAG, "onSuccess() serverUri = " + serverUri + " clientId = " + clientId);
199  }
200 
201  @Override
202  public void onFailure(IMqttToken asyncActionToken, Throwable exception)
203  {
204  Log.d(TAG, "onFailure() serverUri = " + serverUri + " clientId = " + clientId + " exception = " + exception.toString());
205  }
206  });
207  }
208  catch (MqttException e)
209  {
210  e.printStackTrace();
211  }
212  }
213 
219  static public boolean estConnecte()
220  {
221  Log.w(TAG, "estConnecte() " + mqttAndroidClient.isConnected());
222 
223  return mqttAndroidClient.isConnected();
224  }
225 
232  static public boolean souscrireTopic(String topic)
233  {
234  if(mqttAndroidClient == null && !mqttAndroidClient.isConnected())
235  {
236  return false;
237  }
238  final String subTopic = clientId + "/devices/" + topic + "/up";
239  Log.w(TAG, "souscrireTopic() topic = " + subTopic);
240  try
241  {
242  final boolean[] retour = {false};
243  mqttAndroidClient.subscribe(subTopic, 0, null, new IMqttActionListener()
244  {
245  @Override
246  public void onSuccess(IMqttToken asyncActionToken)
247  {
248  Log.w(TAG, "onSuccess() topic = " + subTopic);
249  retour[0] = true;
250  }
251 
252  @Override
253  public void onFailure(IMqttToken asyncActionToken, Throwable exception)
254  {
255  Log.w(TAG, "onFailure() topic = " + subTopic);
256  retour[0] = false;
257  }
258  });
259  return retour[0];
260  }
261  catch (MqttException ex)
262  {
263  Log.w(TAG, "Erreur topic = " + subTopic);
264  ex.printStackTrace();
265  return false;
266  }
267  }
268 
276  static public void decoderMessage(String message, Ruche ruche )
277  {
278  try
279  {
280  JSONObject json = null;
281  Iterator<String> it = null;
282 
283  json = new JSONObject(message);
284  int port = json.getInt("port");
285 
286  it = json.keys();
287  while (it.hasNext())
288  {
289  String cle = it.next();
290  Log.i(TAG, "decoderMessage() clé = " + cle);
291  Log.i(TAG, "decoderMessage() valeur = " + json.getString(cle));
292  //Log.i(TAG, "type = " + json.get(cle).getClass());
293 
294  if (cle.equals("payload_fields"))
295  {
296  decoderPayload(port, json.getString(cle), ruche);
297  }
298  }
299  }
300  catch (JSONException e)
301  {
302  e.printStackTrace();
303  }
304  }
305 
312  static public void decoderPayload(int port, String payload, Ruche ruche)
313  {
314 
315  Log.i(TAG, "decoderPayload() port = " + port );
316  if ( port == 3)
317  {
318  decoderDonneInterieure(payload, ruche);
319  }
320  else
321  {
322  decoderDonneExterieure(payload, ruche);
323  }
324  }
325 
331  static public void decoderDonneInterieure(String payload, Ruche ruche)
332  {
333  try
334  {
335  JSONObject json = null;
336  json = new JSONObject(payload);
337 
338  Iterator<String> it = null;
339  it = json.keys();
340  while (it.hasNext())
341  {
342  String cle = it.next();
343  if (cle.equals("temperature"))
344  {
345  Log.i(TAG, "decoderDonneInterieure() temperature = " + json.getString(cle));
346  RucheActivity.afficherTemperatureInterieure(json.getString(cle));
347  }
348  else if (cle.equals("humidite"))
349  {
350  Log.i(TAG, "decoderDonneInterieure() humidite = " + json.getString(cle));
351  RucheActivity.afficherHumiditeInterieure(json.getString(cle));
352  }
353  }
354  }
355  catch (JSONException e)
356  {
357  e.printStackTrace();
358  }
359  }
360 
366  static public void decoderDonneExterieure(String payload, Ruche ruche)
367  {
368  try {
369  JSONObject json = null;
370  json = new JSONObject(payload);
371 
372  Iterator<String> it = null;
373  it = json.keys();
374  while (it.hasNext()) {
375  String cle = it.next();
376  if (cle.equals("temperature"))
377  {
378  Log.i(TAG, "decoderDonneExterieure() temperature = " + json.getString(cle));
379  RucheActivity.afficherTemperatureExterieure(json.getString(cle));
380  }
381  else if (cle.equals("humidite"))
382  {
383  Log.i(TAG, "decoderDonneExterieure() humidite = " + json.getString(cle));
384  RucheActivity.afficherHumiditerExterieure(json.getString(cle));
385  }
386  else if (cle.equals("ensoleillement"))
387  {
388  Log.i(TAG, "decoderDonneExterieure() ensoleillement = " + json.getString(cle));
389  RucheActivity.afficherEnsoleillement(json.getString(cle));
390  }
391  else if (cle.equals("pression"))
392  {
393  Log.i(TAG, "decoderDonneExterieure() pression = " + json.getString(cle));
394  RucheActivity.afficherPression(json.getString(cle));
395  }
396  else if (cle.equals("poids"))
397  {
398  double poids = json.getDouble(cle);
399  poids = poids * 0.01;
400  Log.i(TAG, "decoderDonneExterieure() poids = " + json.getInt(cle));
401  ruche.setPoids(json.getInt(cle));
402  RucheActivity.afficherPoids(json.getInt(cle));
403  }
404  }
405  }
406  catch (JSONException e)
407  {
408  e.printStackTrace();
409  }
410  }
411 
416  static public String extraireHorodatage(String message)
417  {
418  String date = "";
419 
420  try
421  {
422  JSONObject json = null;
423  json = new JSONObject(message);
424 
425  date = json.getJSONObject("metadata").getString("time");
426  date = date.substring(0, 10) + " " + date.substring(11, 19);
427  Log.d(TAG, "extraireHorodatage() time = " + json.getJSONObject("metadata").getString("time"));
428  Log.d(TAG, "extraireHorodatage() horodatage = " + date);
429 
430  }
431  catch (JSONException e)
432  {
433  e.printStackTrace();
434  }
435 
436  return date;
437  }
438 }
static void afficherHumiditerExterieure(String message)
affichie l&#39;humiditer exterieure dans le layout
static void afficherTemperatureExterieure(String message)
affichie la Temperature exterieure dans le layout
static void decoderPayload(int port, String payload, Ruche ruche)
d&#39;ecode le payload
static void afficherTemperatureInterieure(String message)
affichie la Temperature interieure dans le layout
static void afficherPoids(int message)
affichie le poid dans le layout
static void afficherEnsoleillement(String message)
affichie l&#39;Ensoleillement dans le layout
static boolean souscrireTopic(String topic)
S&#39;abone a un device.
static void decoderMessage(String message, Ruche ruche)
decode le message recu
Déclaration de la classe CommunicationMQTT.
static void afficherHumiditeInterieure(String message)
affichie l&#39;humiditer interieure dans le layout
CommunicationMQTT(Context context, final Handler handler)
Constructeur de la classe CommunicationMQTT.
Déclaration de la classe Ruche.
Definition: Ruche.java:16
static void decoderDonneExterieure(String payload, Ruche ruche)
decode les donné de l&#39;exterieure de la ruche
static void afficherPression(String message)
affichie la pression dans le layout
static void decoderDonneInterieure(String payload, Ruche ruche)
decode les donné de l&#39;interieur de la ruche
static void setCallback(MqttCallbackExtended callback)
static String extraireHorodatage(String message)
extrait l&#39;horodatage
static String clientId
Application ID.
static boolean estConnecte()
boolaine retourne si le ttn est connecter
String username
nom d&#39;utilisateur
void setPoids(int Poids)
Mutateur set du poids de la ruche.
Definition: Ruche.java:82
Déclaration de la classe RucheActivity.