Advertisement
vitareinforce

Android MQTT

Sep 26th, 2018
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.09 KB | None | 0 0
  1. package id.pptik.vitra.homeautomation.helpers;
  2.  
  3. import android.content.Context;
  4. import android.util.Log;
  5.  
  6. import org.eclipse.paho.android.service.MqttAndroidClient;
  7. import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
  8. import org.eclipse.paho.client.mqttv3.IMqttActionListener;
  9. import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
  10. import org.eclipse.paho.client.mqttv3.IMqttToken;
  11. import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
  12. import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
  13. import org.eclipse.paho.client.mqttv3.MqttException;
  14. import org.eclipse.paho.client.mqttv3.MqttMessage;
  15.  
  16. public class MQTTHelper {
  17.  
  18.     //define mqtt android client
  19.     public MqttAndroidClient mqttAndroidClient;
  20.  
  21.     /**
  22.      * Connection Parameter
  23.      */
  24.     final String serverUri = "tcp://192.168.0.254:1883";
  25.     final String clientId = "Android_Client_" + android.os.Build.MODEL;
  26.     final String subscriptionTopic = "/hello";
  27.     final String username = "/homeauto:homeauto";
  28.     final String password = "homeauto12345!";
  29.  
  30.     /**
  31.      * Constructor for MQTT Helper
  32.      * @param context android context
  33.      */
  34.     public MQTTHelper(Context context){
  35.  
  36.         /**
  37.          * Define new MQTT Connection with callback
  38.          */
  39.         mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
  40.         mqttAndroidClient.setCallback(new MqttCallbackExtended() {
  41.  
  42.             /**
  43.              * Connection Complete Callback
  44.              * @param b
  45.              * @param s
  46.              */
  47.             @Override
  48.             public void connectComplete(boolean b, String s) {
  49.                 Log.w("mqtt", s);
  50.             }
  51.  
  52.             /**
  53.              * Connection Lost Callback
  54.              * @param throwable throwable exception
  55.              */
  56.             @Override
  57.             public void connectionLost(Throwable throwable) {
  58.  
  59.             }
  60.  
  61.             /**
  62.              * Message Arrived callback
  63.              * @param topic mqtt topic
  64.              * @param mqttMessage mqtt message content
  65.              * @throws Exception
  66.              */
  67.             @Override
  68.             public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
  69.                 Log.w("Mqtt", mqttMessage.toString());
  70.             }
  71.  
  72.             /**
  73.              * Delivery Complete callback
  74.              * @param iMqttDeliveryToken
  75.              */
  76.             @Override
  77.             public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
  78.  
  79.             }
  80.         });
  81.  
  82.         //connect now
  83.         connect();
  84.     }
  85.  
  86.     /**
  87.      * Setup MQTT Callback
  88.      * @param callback
  89.      */
  90.     public void setCallback(MqttCallbackExtended callback) {
  91.         mqttAndroidClient.setCallback(callback);
  92.     }
  93.  
  94.     /**
  95.      * MQTT Connection function
  96.      */
  97.     private void connect(){
  98.         MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
  99.         mqttConnectOptions.setAutomaticReconnect(true);
  100.         mqttConnectOptions.setCleanSession(false);
  101. //        mqttConnectOptions.setUserName(username);
  102. //        mqttConnectOptions.setPassword(password.toCharArray());
  103.  
  104.         try {
  105.  
  106.             /**
  107.              * mqtt android client connection function
  108.              */
  109.             mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
  110.  
  111.                 /**
  112.                  * if connection success run this
  113.                  * @param asyncActionToken MQTT Token connection
  114.                  */
  115.                 @Override
  116.                 public void onSuccess(IMqttToken asyncActionToken) {
  117.  
  118.                     DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
  119.                     disconnectedBufferOptions.setBufferEnabled(true);
  120.                     disconnectedBufferOptions.setBufferSize(100);
  121.                     disconnectedBufferOptions.setPersistBuffer(false);
  122.                     disconnectedBufferOptions.setDeleteOldestMessages(false);
  123.                     mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
  124.                     subscribeToTopic();
  125.                 }
  126.  
  127.                 /**
  128.                  * if connection failed run this
  129.                  * @param asyncActionToken MQTT Token Connection
  130.                  * @param exception Throwable exception
  131.                  */
  132.                 @Override
  133.                 public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
  134.                     Log.w("Mqtt", "Failed to connect to: " + serverUri + exception.toString());
  135.                 }
  136.             });
  137.  
  138.         } catch (MqttException ex){
  139.             ex.printStackTrace();
  140.         }
  141.     }
  142.  
  143.  
  144.     /**
  145.      * Subscribe to Topic
  146.      */
  147.     private void subscribeToTopic() {
  148.         try {
  149.  
  150.             /**
  151.              * mqtt android client subscribe function
  152.              */
  153.             mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
  154.  
  155.  
  156.                 /**
  157.                  * if subscribtion success run this
  158.                  * @param asyncActionToken MQTT Token connection
  159.                  */
  160.                 @Override
  161.                 public void onSuccess(IMqttToken asyncActionToken) {
  162.                     Log.w("Mqtt","Subscribed!");
  163.                 }
  164.  
  165.                 /**
  166.                  * if subscribtion failed run this
  167.                  * @param asyncActionToken MQTT Token Connection
  168.                  * @param exception Throwable exception
  169.                  */
  170.                 @Override
  171.                 public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
  172.                     Log.w("Mqtt", "Subscribed fail!");
  173.                 }
  174.             });
  175.  
  176.         } catch (MqttException ex) {
  177.             System.err.println("Exceptionst subscribing");
  178.             ex.printStackTrace();
  179.         }
  180.     }
  181.  
  182.     public void publish(String topic_pub, String message) {
  183.         try {
  184.             mqttAndroidClient.publish(topic_pub, message.getBytes(),0,false);
  185.         } catch (MqttException e) {
  186.             e.printStackTrace();
  187.  
  188.         }
  189.     }
  190. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement