Advertisement
Guest User

Untitled

a guest
Jan 18th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.89 KB | None | 0 0
  1. import org.fusesource.mqtt.client.*;
  2. import org.json.JSONArray;
  3. import org.json.JSONException;
  4. import org.json.JSONObject;
  5.  
  6. import java.nio.charset.StandardCharsets;
  7. import java.util.ArrayList;
  8.  
  9. /**
  10. * Created by Kalaman on 09.01.18.
  11. */
  12. public class MQTTClient {
  13. private MQTT mqtt;
  14. private static BlockingConnection connection;
  15. private Topic [] topic;
  16.  
  17. private ArrayList<MQTTListener> mqttListener;
  18. private static final String SERVER_IP = "192.168.43.197";
  19. private static final int SERVER_PORT = 1883;
  20.  
  21. public static final String TOPIC_LOG = "log";
  22. public static final String TOPIC_NODE = "node";
  23. public static final String TOPIC_DRIVE = "drive";
  24. public static final String TOPIC_SONIC_DISTANCE = "distance";
  25.  
  26. public MQTTClient() {
  27. mqtt = new MQTT();
  28. mqttListener = new ArrayList<MQTTListener>();
  29. topic = new Topic[] {new Topic(TOPIC_DRIVE, QoS.EXACTLY_ONCE)};
  30.  
  31. try {
  32. mqtt.setHost(SERVER_IP, SERVER_PORT);
  33. connection = mqtt.blockingConnection();
  34. connection.connect();
  35. publish("Robot is connected [" + SERVER_IP + ":" + SERVER_PORT + "] ...",TOPIC_LOG);
  36. connection.subscribe(topic);
  37.  
  38. }
  39. catch (Exception e){
  40. e.printStackTrace();
  41. }
  42. }
  43.  
  44. public interface MQTTListener {
  45. public void onDriveReceived(float distanceInCM);
  46. }
  47.  
  48. public boolean addMQTTListener(MQTTListener listener) {
  49. return mqttListener.add(listener);
  50. }
  51.  
  52. public boolean removeMQTTListener(MQTTListener listener) {
  53. return mqttListener.remove(listener);
  54. }
  55.  
  56. public void startListeningThread () {
  57. new Thread() {
  58. @Override
  59. public void run() {
  60. try {
  61. while(true) {
  62. Message message = connection.receive();
  63. String payload = new String(message.getPayload(), StandardCharsets.UTF_8);
  64.  
  65. if (message.getTopic().equals(TOPIC_DRIVE))
  66. {
  67. float distance = Float.parseFloat(payload) * (float)10;
  68.  
  69. for (MQTTListener listener : mqttListener)
  70. listener.onDriveReceived(distance);
  71. }
  72.  
  73. message.ack();
  74. }
  75. }
  76. catch (Exception e) {
  77. e.printStackTrace();
  78. }
  79. }
  80.  
  81. }.start();
  82. }
  83.  
  84. public static void publish (String message, String topic) {
  85. try {
  86. connection.publish(topic, message.getBytes() ,QoS.EXACTLY_ONCE, false);
  87. } catch (Exception e) {
  88. e.printStackTrace();
  89. }
  90. }
  91.  
  92. public void publishLog (String msg) {
  93. publish(msg,TOPIC_LOG);
  94. }
  95.  
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement