Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. public class MqttConnection {
  2.  
  3. private static final String BROKER_ADDRESS = Preferences.getProperty("mqtt-address");
  4. private static final String BROKER_PORT = Preferences.getProperty("mqtt-port");
  5. private static final String BROKER_URI = "tcp://" + BROKER_ADDRESS + ":" + BROKER_PORT;
  6.  
  7. private static final String VHOST = Preferences.getProperty("mqtt-vhost");
  8. private static final String USERNAME = Preferences.getProperty("mqtt-username");
  9. private static final String PASSWORD = Preferences.getProperty("mqtt-password");
  10.  
  11. private static MqttClient client;
  12.  
  13. private static final Logger logger = LogManager.getLogger(MqttConnection.class);
  14.  
  15. static {
  16. try {
  17. client = new MqttClient(BROKER_URI, MqttClient.generateClientId());
  18. } catch (MqttException ex) {
  19. logger.fatal(ex);
  20. }
  21. client.setCallback(new MqttCallback() {
  22. @Override
  23. public void connectionLost(Throwable thrwbl) {
  24. logger.info("MQTT : Perte de connexion...");
  25. MqttConnection.start();
  26. }
  27.  
  28. @Override
  29. public void messageArrived(String topic, MqttMessage message) throws Exception {
  30. // CODE HERE
  31. }
  32.  
  33. @Override
  34. public void deliveryComplete(IMqttDeliveryToken imdt) { }
  35. });
  36. }
  37.  
  38. public static void start() {
  39. connect();
  40. }
  41.  
  42. private static void connect() {
  43. if (!client.isConnected()) {
  44. try {
  45. if (Preferences.getProperty("mqtt-isauth").equalsIgnoreCase("true")) {
  46. MqttConnectOptions options = new MqttConnectOptions();
  47. String username = (VHOST.equals("")) ? USERNAME : VHOST + ":" + USERNAME;
  48. options.setUserName(username);
  49. options.setPassword(PASSWORD.toCharArray());
  50. client.connect(options);
  51. } else {
  52. client.connect();
  53. }
  54. logger.info("MQTT : Connecté au broker.");
  55. } catch (MqttException ex) {
  56. logger.fatal(ex);
  57. try {
  58. Thread.sleep(5000);
  59. } catch (InterruptedException e) {
  60. logger.fatal(e);
  61. }
  62. connect();
  63. }
  64. }
  65. }
  66.  
  67. private static void subscribe() {
  68. if (client.isConnected()) {
  69. try {
  70. client.subscribe("+/SWI1");
  71. } catch (MqttException e) {
  72. logger.fatal(e);
  73. }
  74. }
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement