Advertisement
Guest User

Untitled

a guest
Mar 29th, 2016
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 28.43 KB | None | 0 0
  1. package mqes;
  2.  
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.content.SharedPreferences;
  6. import android.content.pm.PackageManager;
  7. import android.preference.PreferenceManager;
  8. import android.util.Log;
  9.  
  10. import org.eclipse.paho.client.mqttv3.IMqttActionListener;
  11. import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
  12. import org.eclipse.paho.client.mqttv3.IMqttToken;
  13. import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
  14. import org.eclipse.paho.client.mqttv3.MqttCallback;
  15. import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
  16. import org.eclipse.paho.client.mqttv3.MqttException;
  17. import org.eclipse.paho.client.mqttv3.MqttMessage;
  18. import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
  19.  
  20. import java.sql.Timestamp;
  21. import java.util.List;
  22.  
  23. import Mpock.Globals;
  24. import Mpock.Vars;
  25. import de.greenrobot.event.EventBus;
  26. import eventBusClasses.MqConnected;
  27. import eventBusClasses.MqDisonnected;
  28.  
  29.  
  30.  
  31. public class MpockMqClient implements MqttCallback {
  32.  
  33. int state = BEGIN;
  34. static final int BEGIN = 0;
  35. public static final int CONNECTED = 1;
  36. static final int PUBLISHED = 2;
  37. static final int SUBSCRIBED = 3;
  38. static final int DISCONNECTED = 4;
  39. static final int FINISH = 5;
  40. static final int ERROR = 6;
  41. static final int DISCONNECT = 7;
  42.  
  43. // PREFS
  44. SharedPreferences prefs;
  45. String userName;
  46.  
  47. // Private instance variables
  48. MqttAsyncClient client;
  49. String brokerUrl;
  50. private boolean log = true;
  51. private MqttConnectOptions conOpt;
  52. // private boolean clean;
  53. Throwable ex = null;
  54. Object waiter = new Object();
  55. boolean donext = false;
  56. private String password;
  57. private String userNameMqtt;
  58. // String clientId = "testerhope";
  59. String clientId;
  60. MpockMqClient sampleClient;
  61.  
  62. // ANDROID INSERTS
  63. Context context;
  64.  
  65. String tag = "MpockMqClient";
  66.  
  67. Vars vars;
  68.  
  69. // BROADCAST CONSTANTS
  70. // PINGER
  71. public static final String MQTT_PING_ACTION = "com.dalelane.mqtt.PING";
  72. // DELIVERY COMPLETE
  73. public static final String MQTT_DEL_COMPLETE = "MQTT_DEL_COMPLETE";
  74. // CONNECTED
  75. public static final String MQTT_CONNECTED = "MQTT_CONNECTED";
  76. // DIS - CONNECTED
  77. public static final String MQTT_DISCONNECTED = "MQTT_DISCONNECTED";
  78.  
  79. //NOTIFICAITON COUNTER
  80. private int numMessages = 0;
  81.  
  82.  
  83. public MpockMqClient(String userNameL, Context contextL)
  84. throws MqttException, PackageManager.NameNotFoundException {
  85. // public SampleAsyncCallBack(String userNameL) throws MqttException {
  86. log("creating SampleAsyncCallBack object");
  87. this.brokerUrl = "tcp://" + Globals.mqRoot + ":" + Globals.MQ_ROOT_PORT;
  88.  
  89. // this.quietMode = false;
  90. // this.clean = true;
  91. this.password = null;
  92. this.userNameMqtt = null;
  93. this.userName = userNameL;
  94. this.context = contextL;
  95. prefs = PreferenceManager.getDefaultSharedPreferences(context);
  96.  
  97. MemoryPersistence persistence = new MemoryPersistence();
  98. // MqttDefaultFilePersistence dataStore = new
  99. // MqttDefaultFilePersistence(tmpDir);
  100.  
  101. vars = new Vars(contextL);
  102.  
  103. try {
  104. log("creating object, username is:" + userName);
  105. // Construct the object that contains connection parameters
  106. // such as cleansession and LWAT
  107. conOpt = new MqttConnectOptions();
  108. // String shit = "gcmtest";
  109. conOpt.setWill(Globals.appName + "death", userName.getBytes(), 2, false);
  110. conOpt.setCleanSession(Globals.clean);
  111. // conOpt.setCleanSession(vars.mqClean);
  112. if (password != null) {
  113. conOpt.setPassword(this.password.toCharArray());
  114. }
  115. if (userName != null) {
  116. conOpt.setUserName(this.userName);
  117. }
  118.  
  119. // Construct the MqttClient instance
  120. // client = new MqttAsyncClient(this.brokerUrl, clientId,
  121. // persistence);
  122. log("creating MqttAsyncClient username is:" + this.userName);
  123. client = new MqttAsyncClient(this.brokerUrl, this.userName,
  124. persistence);
  125.  
  126. // Set this wrapper as the callback handler
  127. client.setCallback(this);
  128.  
  129. } catch (MqttException e) {
  130. e.printStackTrace();
  131. log("Unable to set up client: " + e.toString());
  132. }
  133.  
  134. }
  135.  
  136.  
  137. public void publish(String topicName, int qos, byte[] payload,
  138. String userContext) throws Throwable {
  139. log("MQTT CLIENT...PUBLSIHING FUNCTION....:");
  140. printState();
  141. // Use a state machine to decide which step to do next. State change
  142. // occurs
  143. // when a notification is received that an MQTT action has completed
  144. while (state != FINISH) {
  145. switch (state) {
  146. case BEGIN:
  147. log("PUBLSIHING FUNCTION: CASE BEGIN");
  148. // Connect using a non blocking connect
  149. MqttConnector con = new MqttConnector();
  150. con.doConnect();
  151. break;
  152. case CONNECTED:
  153. log("PUBLSIHING FUNCTION: CASE CONNECTED");
  154.  
  155. // CREAT PUBLISHER OBJECT
  156. Publisher pub = new Publisher();
  157. pub.doPublish(topicName, qos, payload, userContext);
  158.  
  159. Subscriber sub = new Subscriber();
  160.  
  161. if (userName != null) {
  162. // sub.doSubscribe(Globals.appName + "/"+vars.clientId+"/#", 2);
  163. // sub.doSubscribe(Globals.appName + "/" + userName + "/#", 2);
  164.  
  165. sub.doSubscribe(Globals.appName + "/" + userName + "/#", 2);
  166.  
  167.  
  168. log("username was NOT NULL we suscribed");
  169. } else {
  170. log("uername == null OR CLIENT ID IS ZERO");
  171. }
  172.  
  173. //clientId = prefs.getString("clientId", "000");
  174. // String clientId = prefs.getString("clientId", "000");
  175. // if(vars.clientId != null && clientId != "000"){
  176. // sub.doSubscribe(Globals.appName + "/"+vars.clientId+"/#", 2);
  177. // log("vars.clientId was NOT NULL we suscribed");
  178. // }else{
  179. // log("vars.clientId == null OR CLIENT ID IS ZERO");
  180. // }
  181.  
  182. //sub.doSubscribe(Globals.appName+"/everyone/#", 2);
  183.  
  184.  
  185. // SUBSCRIBE STUFF
  186. // log("starting Subscriber");
  187. /*Subscriber sub = new Subscriber();
  188. // SUB TO EVERYONE
  189. sub.doSubscribe(Globals.appName+"/everyone/#", 2);
  190. // SUB TO USER NAME
  191. sub.doSubscribe(Globals.appName+"/" + vars.prefs.getString("userId", null)+ "/#", 2);
  192. // SUB TO GROUP CHAT
  193. sub.doSubscribe(Globals.appName+"/groups/1", 2);
  194. //NEW CONTACT
  195. sub.doSubscribe(Globals.appName+"/newContact", 2);
  196. //REMOVE CONTACT
  197. sub.doSubscribe(Globals.appName+"/removeContact",2);*/
  198.  
  199. state = FINISH;
  200. log(">>>>>>>>>>>>>>>: STATE CHANGED TO:"
  201. + MqUtilz.getState(state));
  202. // log("state IS:" + state);
  203. donext = true;
  204. break;
  205. case PUBLISHED:
  206. // state = FINISH;
  207. // donext = true;
  208. // break;
  209. state = FINISH;
  210. log(">>>>>>>>>>>>>>>: STATE CHANGED TO:" + getState(state));
  211. donext = true;
  212. break;
  213. case DISCONNECT:
  214. Disconnector disc = new Disconnector();
  215. disc.doDisconnect();
  216. break;
  217. case ERROR:
  218. throw ex;
  219. case DISCONNECTED:
  220. // state = FINISH;
  221. state = FINISH;
  222. log(">>>>>>>>>>>>>>>: STATE CHANGED TO:" + getState(state));
  223. donext = true;
  224. break;
  225. }
  226.  
  227. waitForStateChange(3000);
  228. // }
  229. }
  230. }
  231.  
  232. public void publishMultiple(int qos,
  233. String[][] pubArray) throws Throwable {
  234. log("30.0 MQTT CLIENT...publishMultiple FUNCTION....:");
  235. printState();
  236.  
  237. while (state != FINISH) {
  238. log("starting while (state != FINISH)");
  239. switch (state) {
  240. case BEGIN:
  241. log("PUBLSIHING FUNCTION: CASE BEGIN");
  242. // Connect using a non blocking connect
  243.  
  244. MqttConnector con = new MqttConnector();
  245. con.doConnect();
  246. break;
  247. case CONNECTED:
  248. log("PUBLSIHING FUNCTION: CASE CONNECTED");
  249.  
  250. // TWO DEMO ARRAY THAT CONTAINS TOPIC TO PUBLISH TO, WHAT TO
  251. // PUBLISH AND CONTEXT TO USE
  252. log("two dem array size:" + pubArray.length);
  253.  
  254. for (int i = 0; i < pubArray.length; i++) {
  255. log("iiiiiiiiiiiiiiii, i:" + i);
  256.  
  257. log("pubArray[i][0]" + pubArray[i][0]);
  258. log("pubArray[i][1]" + pubArray[i][1]);
  259. log("pubArray[i][2]" + pubArray[i][2]);
  260.  
  261. Publisher pub = new Publisher();
  262. pub.doPublish(pubArray[i][0], qos,
  263. pubArray[i][1].getBytes(), pubArray[i][2]);
  264. log("PUBLISHED STREAM:" + pubArray[i][0] + ":" + qos + ":"
  265. + pubArray[i][1].getBytes() + ":" + pubArray[i][2]);
  266. log("-----------------------------------------");
  267. }
  268.  
  269.  
  270. // DIRECT CREATION
  271. log("calling single publishhhhhhhhhhhhhh");
  272.  
  273. state = FINISH;
  274. log(">>>>>>>>>>>>>>>: STATE CHANGED TO:" + getState(state));
  275. // log("state IS:" + state);
  276. donext = true;
  277. break;
  278. case PUBLISHED:
  279. log("PUBLSIHING FUNCTION: CASE PUBLISHED");
  280. // state = DISCONNECT;
  281. state = FINISH;
  282. log(">>>>>>>>>>>>>>>: STATE CHANGED TO:" + getState(state));
  283. donext = true;
  284. break;
  285. case DISCONNECT:
  286. log("PUBLSIHING FUNCTION: CASE DISCONNECT");
  287. Disconnector disc = new Disconnector();
  288. disc.doDisconnect();
  289. break;
  290. case ERROR:
  291. throw ex;
  292. case DISCONNECTED:
  293. state = FINISH;
  294. log(">>>>>>>>>>>>>>>: STATE CHANGED TO:" + getState(state));
  295. donext = true;
  296. break;
  297. }
  298.  
  299. // if (state != FINISH) {
  300. // Wait until notified about a state change and then perform next
  301. // action
  302. waitForStateChange(3000);
  303. // }
  304. }
  305. }
  306.  
  307. private void waitForStateChange(int maxTTW) throws MqttException {
  308. synchronized (waiter) {
  309. if (!donext) {
  310. try {
  311. waiter.wait(maxTTW);
  312. } catch (InterruptedException e) {
  313. log("timed out");
  314. e.printStackTrace();
  315. }
  316.  
  317. if (ex != null) {
  318. throw (MqttException) ex;
  319. }
  320. }
  321. donext = false;
  322. }
  323. }
  324.  
  325. public void subscribe(String topicName, int qos) throws Throwable {
  326. //utils.Logg.logFunc("MQTT: - SUBSCRIBE FUNCTION");
  327. log("MQTT: - SUBSCRIBE FUNCTION");
  328. log("-- topic:" + topicName);
  329. printState();
  330. while (state != FINISH) {
  331. switch (state) {
  332. case BEGIN:
  333. // Connect using a non blocking connect
  334. MqttConnector con = new MqttConnector();// DIFFERENCE ONE
  335. con.doConnect();
  336. break;
  337. case CONNECTED:
  338. // Subscribe using a non blocking subscribe
  339. Subscriber sub = new Subscriber();
  340. sub.doSubscribe(topicName, qos);
  341.  
  342. //IMPORTED FROM PUBLISH FUNCTION
  343. state = FINISH;
  344. log(">>>>>>>>>>>>>>>: STATE CHANGED TO:"
  345. + MqUtilz.getState(state));
  346. // log("state IS:" + state);
  347. donext = true;
  348. break;
  349.  
  350. //break;
  351. case SUBSCRIBED:
  352. log("MQTT: INSIDE SUBSCRIBE FUNCTION");
  353. log("SATE IS DISCONNECT");
  354. state = DISCONNECT;
  355. donext = true;
  356. break;
  357. case DISCONNECT:
  358. Disconnector disc = new Disconnector();
  359. disc.doDisconnect();
  360. break;
  361. case ERROR:
  362. throw ex;
  363. case DISCONNECTED:
  364. state = FINISH;
  365. log(">>>>>>>>>>>>>>>: STATE CHANGED TO:" + getState(state));
  366. donext = true;
  367. break;
  368. }
  369.  
  370. // if (state != FINISH && state != DISCONNECT) {
  371. waitForStateChange(10000);
  372. }
  373. // }
  374. }
  375.  
  376. //SUB TO MANY THINGS.
  377.  
  378. public void subscribe(List<String> topics, int qos) throws Throwable {
  379. log("MQTT: - SUBSCRIBE FUNCTION");
  380. log("-- num topics:" + topics.size());
  381. printState();
  382. while (state != FINISH) {
  383. switch (state) {
  384. case BEGIN:
  385. // Connect using a non blocking connect
  386. MqttConnector con = new MqttConnector();// DIFFERENCE ONE
  387. con.doConnect();
  388. break;
  389. case CONNECTED:
  390. // Subscribe using a non blocking subscribe
  391. Subscriber sub = new Subscriber();
  392.  
  393. //LOOP THROUGH EACH TOPIC AND SUB
  394. for (String t : topics) {
  395. log("subscribing to:" + t);
  396. sub.doSubscribe(t, qos);
  397. }
  398.  
  399.  
  400. //IMPORTED FROM PUBLISH FUNCTION
  401. state = FINISH;
  402. log(">>>>>>>>>>>>>>>: STATE CHANGED TO:"
  403. + MqUtilz.getState(state));
  404. // log("state IS:" + state);
  405. donext = true;
  406. break;
  407.  
  408. //break;
  409. case SUBSCRIBED:
  410. log("MQTT: INSIDE SUBSCRIBE FUNCTION");
  411. log("SATE IS DISCONNECT");
  412. state = DISCONNECT;
  413. donext = true;
  414. break;
  415. case DISCONNECT:
  416. /*Disconnector disc = new Disconnector();
  417. disc.doDisconnect();*/
  418. break;
  419. case ERROR:
  420. throw ex;
  421. case DISCONNECTED:
  422. state = FINISH;
  423. log(">>>>>>>>>>>>>>>: STATE CHANGED TO:" + getState(state));
  424. donext = true;
  425. break;
  426. }
  427.  
  428. // if (state != FINISH && state != DISCONNECT) {
  429. waitForStateChange(10000);
  430. }
  431. // }
  432. }
  433.  
  434. void log(String message) {
  435. if (log && Globals.log) {
  436. Log.v(tag, message);
  437. }
  438. }
  439.  
  440. /**
  441. * *************************************************************
  442. */
  443. /* Methods to implement the MqttCallback interface */
  444. /**
  445. * *************************************************************
  446. */
  447. /**
  448. * @see MqttCallback#connectionLost(Throwable)
  449. */
  450. public void connectionLost(Throwable cause) {
  451. // Called when the connection to the server has been lost.
  452. // An application may choose to implement reconnection
  453. // logic at this point. This sample simply exits.
  454. log("Connection to " + brokerUrl + " lost!" + cause);
  455. log("attempty to REEONNNECT");
  456.  
  457.  
  458. // SEND connectionLost BROADCAST
  459. Intent broadcastIntent = new Intent();
  460. broadcastIntent.setAction(MQTT_DISCONNECTED);
  461. broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
  462. log("sending sent to server broadcast......................");
  463. context.sendBroadcast(broadcastIntent);
  464.  
  465. //SEND EVENTBUS ABOUT DIS
  466. MqDisonnected mqDisonnected = new MqDisonnected("disconnected");
  467. EventBus.getDefault().postSticky(mqDisonnected);
  468.  
  469. }
  470.  
  471.  
  472. public void deliveryComplete(IMqttDeliveryToken token) {
  473. log("44.0 dddddddddddddddd: MQTT DELIVERY CALL BACK: ddddddddddddddd");
  474. log("44.1 IMqttToken USER CONTEXT:" + (String) token.getUserContext());
  475.  
  476. String messageContext = (String) token.getUserContext();
  477.  
  478. // SEND MESSAGE RECEIVED BROADCAST
  479. Intent broadcastIntent = new Intent();
  480. broadcastIntent.setAction(Globals.DEL_TO_SERV);
  481. broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
  482. broadcastIntent.putExtra("message", messageContext);
  483. log("44.2 sending broadcast with extra:" + messageContext);
  484. log("44.3 sending sent to server broadcast......................");
  485. context.sendBroadcast(broadcastIntent);
  486.  
  487. //SEND EVENTBUS ABOUT DISCONNECTED
  488. MqConnected mqConnected = new MqConnected("connected");
  489. EventBus.getDefault().postSticky(mqConnected);
  490.  
  491.  
  492.  
  493. }
  494.  
  495. /**
  496. * @throws org.json.JSONException
  497. * @see MqttCallback#messageArrived(String, MqttMessage)
  498. */
  499. public void messageArrived(String topic, MqttMessage message) throws Exception {
  500. // Called when a message arrives from the server that matches any
  501. // subscription made by the client
  502. String time = new Timestamp(System.currentTimeMillis()).toString();
  503. log("Time:\t" + time + " Topic:\t" + topic
  504. + " Message:\t" + new String(message.getPayload())
  505. + " QoS:\t" + message.getQos());
  506.  
  507. try {
  508. //PROCESS MESSAGE...
  509. if (topic.endsWith("/testing")) {
  510. log("topic.endsWith Globals.NEW_STUDENT_CHARGE");
  511.  
  512. // EventBus.getDefault().post(studentCharge);
  513.  
  514. } else {
  515. //NotifyServant.oneOff(vars, "Message from the Server", Globals.NOTI_TYPE_UPDATE);
  516. }
  517.  
  518.  
  519. // }
  520. } catch (Exception e) {
  521. if (e instanceof NullPointerException) {
  522.  
  523. log("SHIT NPE!!");
  524. } else if (e instanceof com.google.gson.JsonSyntaxException) {
  525. //handle this one
  526. } else {
  527. // We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy.
  528. throw e;
  529. }
  530. }
  531.  
  532. }
  533.  
  534. // PRINT STATE
  535. void printState() {
  536. log("PRINT STATE:" + MqUtilz.getState(state));
  537. }
  538.  
  539. // GET THE NOTIFIER STATE
  540. String getState(int state) {
  541. String stateF = "NO STATE FOUND";
  542. // log("getState: sent state:"+state);
  543.  
  544. if (state == 0) {
  545. stateF = "BEGIN";
  546. } else if (state == 1) {
  547. stateF = "CONNECTED";
  548. } else if (state == 2) {
  549. stateF = "PUBLISHED";
  550. } else if (state == 3) {
  551. stateF = "SUBSCRIBED";
  552. } else if (state == 4) {
  553. stateF = "DISCONNECTED";
  554. } else if (state == 5) {
  555. stateF = "FINISH";
  556. } else if (state == 6) {
  557. stateF = "ERROR";
  558. } else if (state == 6) {
  559. stateF = "DISCONNECT";
  560. }
  561. return stateF;
  562. }
  563.  
  564. /**
  565. * Connect in a non blocking way and then sit back and wait to be notified
  566. * that the action has completed.
  567. */
  568. public class MqttConnector {
  569.  
  570. public MqttConnector() {
  571. log("MqttConnector() CONSTRUCTOR");
  572. }
  573.  
  574.  
  575. public void doConnect() {
  576. // Connect to the server
  577. // Get a token and setup an asynchronous listener on the token which
  578. // will be notified once the connect completes
  579. // log("Connecting to " + brokerUrl + " with client ID "
  580. // + client.getClientId());
  581. log("MQTT: MqttConnector: Connecting to " + brokerUrl
  582. + " with client ID " + client.getClientId());
  583.  
  584. IMqttActionListener conListener = new IMqttActionListener() {
  585. public void onSuccess(IMqttToken asyncActionToken) {
  586. log("MQTT: CONNECTOR IMqttActionListener -- CONNECT SUCCESSFULL!");
  587. log("MQTT: CONNECTOR IMqttActionListener -- context:"
  588. + asyncActionToken.getUserContext());
  589. state = CONNECTED;
  590.  
  591. MqConnected mqConnected = new MqConnected("connected");
  592. EventBus.getDefault().postSticky(mqConnected);
  593.  
  594. //MySingleton.getInstance(vars.context).brokerConnected = true;
  595. // log("MQCONN:set singletone broker conected to:"+MySingleton.getInstance(vars.context).brokerConnected);
  596. carryOn();
  597. }
  598.  
  599. public void onFailure(IMqttToken asyncActionToken,
  600. Throwable exception) {
  601. ex = exception;
  602. state = ERROR;
  603. log("connect failed" + exception);
  604. // CHECK IF ITS A MESSAGE ID
  605. String messageContext = (String) asyncActionToken
  606. .getUserContext();
  607. // SEND MESSAGE RECEIVED BROADCAST
  608. Intent broadcastIntent = new Intent();
  609. broadcastIntent.setAction(MQTT_CONNECTED);
  610. broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
  611. broadcastIntent.putExtra("message", messageContext);
  612. log("sending sent to server broadcast......................");
  613. context.sendBroadcast(broadcastIntent);
  614. carryOn();
  615. }
  616.  
  617. public void carryOn() {
  618. synchronized (waiter) {
  619. donext = true;
  620. waiter.notifyAll();
  621. }
  622. }
  623. };
  624.  
  625. try {
  626. // Connect using a non blocking connect
  627. client.connect(conOpt, "Connect sample context", conListener);
  628. } catch (MqttException e) {
  629. state = ERROR;
  630. log(">>>>>>>>>>>>>>>: STATE CHANGED TO:" + getState(state));
  631. donext = true;
  632. ex = e;
  633. }
  634. }
  635. }
  636.  
  637. public class Publisher {
  638.  
  639. // public void doPublish(String topicName, int qos, byte[] payload) {
  640. public void doPublish(String topicName, int qos, byte[] payload,
  641. String userContext) {
  642.  
  643. log("ASYNCALLBACK:PULISHER CLASS: doPublish");
  644.  
  645.  
  646. MqttMessage message = new MqttMessage(payload);
  647. message.setQos(qos);
  648.  
  649. String time = new Timestamp(System.currentTimeMillis()).toString();
  650. log("Publishing at: " + time + " to topic \"" + topicName
  651. + "\" qos " + qos);
  652.  
  653. // Setup a listener object to be notified when the publish
  654. // completes.
  655. // ASD
  656. IMqttActionListener pubListener = new IMqttActionListener() {
  657. public void onSuccess(IMqttToken asyncActionToken) {
  658. log("IMqttActionListener Publish Completed");
  659.  
  660. String test = "test";
  661. asyncActionToken.setUserContext(test);
  662.  
  663. // String context = (String) asyncActionToken.getUserContext();
  664.  
  665.  
  666. state = PUBLISHED;
  667. log("STATE SHOULD BE PUBLISHED:...........SSSSSSSSSSS."
  668. + state);
  669. log(">>>>>>>>>>>>>>>: STATE CHANGED TO:" + getState(state));
  670. carryOn();
  671. }
  672.  
  673. public void onFailure(IMqttToken asyncActionToken,
  674. Throwable exception) {
  675. ex = exception;
  676. state = ERROR;
  677. log("Publish failed" + exception);
  678. carryOn();
  679. }
  680.  
  681. public void carryOn() {
  682. log("ASYNCALLBACK:PULISHER CLASS: doPublish ||carryOn");
  683. printState();
  684. synchronized (waiter) {
  685. donext = true;
  686. waiter.notifyAll();
  687. }
  688. }
  689. };
  690.  
  691. try {
  692. // Publish the message
  693. // client.publish(topicName, message, "Pub sample context",
  694. // pubListener);
  695. // NEW WAY ADDING CONTEXT VAR
  696. client.publish(topicName, message, userContext, pubListener);
  697. // client.pu
  698.  
  699. // client.disconnect();
  700. // log("dddddddddddddddddddddddddd:DISONNECT CALLED");
  701.  
  702. } catch (MqttException e) {
  703. state = ERROR;
  704. donext = true;
  705. ex = e;
  706. }
  707. }
  708. }
  709.  
  710. /**
  711. * Subscribe in a non blocking way and then sit back and wait to be notified
  712. * that the action has completed.
  713. */
  714. public class Subscriber {
  715.  
  716. public void doSubscribe(final String topicName, int qos) {
  717. log("-------SUBSCRIBER CLASS");
  718. // Make a subscription
  719. // Get a token and setup an asynchronous listener on the token which
  720. // will be notified once the subscription is in place.
  721. log("Subscribing to topic \"" + topicName + "\" qos " + qos);
  722.  
  723. IMqttActionListener subListener = new IMqttActionListener() {
  724. public void onSuccess(IMqttToken asyncActionToken) {
  725. log("Subscribe Completed to:"+topicName);
  726. state = SUBSCRIBED;
  727. // MySingleton.getInstance(vars.context).brokerConnected = true;
  728.  
  729. EventBus.getDefault().postSticky(new MqConnected("connected"));
  730.  
  731. carryOn();
  732. }
  733.  
  734. public void onFailure(IMqttToken asyncActionToken,
  735. Throwable exception) {
  736. ex = exception;
  737. state = ERROR;
  738. log("Subscribe failed" + exception);
  739. carryOn();
  740. }
  741.  
  742. public void carryOn() {
  743. synchronized (waiter) {
  744. donext = true;
  745. waiter.notifyAll();
  746. }
  747. }
  748. };
  749.  
  750. try {
  751. client.subscribe(topicName, qos, "Subscribe sample context",
  752. subListener);
  753. } catch (MqttException e) {
  754. state = ERROR;
  755. donext = true;
  756. ex = e;
  757. }
  758. }
  759. }
  760.  
  761. /**
  762. * Disconnect in a non blocking way and then sit back and wait to be
  763. * notified that the action has completed.
  764. */
  765. public class Disconnector {
  766.  
  767. public void doDisconnect() {
  768. // Disconnect the client
  769. log("Disconnecting");
  770.  
  771. IMqttActionListener discListener = new IMqttActionListener() {
  772. public void onSuccess(IMqttToken asyncActionToken) {
  773. log("Disconnect Completed");
  774. state = DISCONNECTED;
  775. carryOn();
  776. }
  777.  
  778. public void onFailure(IMqttToken asyncActionToken,
  779. Throwable exception) {
  780. ex = exception;
  781. state = ERROR;
  782. log("Disconnect failed" + exception);
  783. carryOn();
  784. }
  785.  
  786. public void carryOn() {
  787. synchronized (waiter) {
  788. donext = true;
  789. waiter.notifyAll();
  790. }
  791. }
  792. };
  793.  
  794. try {
  795. client.disconnect("Disconnect sample context", discListener);
  796. } catch (MqttException e) {
  797. state = ERROR;
  798. donext = true;
  799. ex = e;
  800. }
  801. }
  802. }
  803.  
  804. // @Override
  805. // public IBinder onBind(Intent arg0) {
  806. // // TODO Auto-generated method stub
  807. // return null;
  808. // }
  809. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement