Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MqttConnection {
- private static final String BROKER_ADDRESS = Preferences.getProperty("mqtt-address");
- private static final String BROKER_PORT = Preferences.getProperty("mqtt-port");
- private static final String BROKER_URI = "tcp://" + BROKER_ADDRESS + ":" + BROKER_PORT;
- private static final String VHOST = Preferences.getProperty("mqtt-vhost");
- private static final String USERNAME = Preferences.getProperty("mqtt-username");
- private static final String PASSWORD = Preferences.getProperty("mqtt-password");
- private static MqttClient client;
- private static final Logger logger = LogManager.getLogger(MqttConnection.class);
- static {
- try {
- client = new MqttClient(BROKER_URI, MqttClient.generateClientId());
- } catch (MqttException ex) {
- logger.fatal(ex);
- }
- client.setCallback(new MqttCallback() {
- @Override
- public void connectionLost(Throwable thrwbl) {
- logger.info("MQTT : Perte de connexion...");
- MqttConnection.start();
- }
- @Override
- public void messageArrived(String topic, MqttMessage message) throws Exception {
- // CODE HERE
- }
- @Override
- public void deliveryComplete(IMqttDeliveryToken imdt) { }
- });
- }
- public static void start() {
- connect();
- }
- private static void connect() {
- if (!client.isConnected()) {
- try {
- if (Preferences.getProperty("mqtt-isauth").equalsIgnoreCase("true")) {
- MqttConnectOptions options = new MqttConnectOptions();
- String username = (VHOST.equals("")) ? USERNAME : VHOST + ":" + USERNAME;
- options.setUserName(username);
- options.setPassword(PASSWORD.toCharArray());
- client.connect(options);
- } else {
- client.connect();
- }
- logger.info("MQTT : Connecté au broker.");
- } catch (MqttException ex) {
- logger.fatal(ex);
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- logger.fatal(e);
- }
- connect();
- }
- }
- }
- private static void subscribe() {
- if (client.isConnected()) {
- try {
- client.subscribe("+/SWI1");
- } catch (MqttException e) {
- logger.fatal(e);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement