Search in sources :

Example 11 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project nifi by apache.

the class AbstractMQTTProcessor method buildClient.

protected void buildClient(ProcessContext context) {
    try {
        broker = context.getProperty(PROP_BROKER_URI).getValue();
        clientID = context.getProperty(PROP_CLIENTID).getValue();
        connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(context.getProperty(PROP_CLEAN_SESSION).asBoolean());
        connOpts.setKeepAliveInterval(context.getProperty(PROP_KEEP_ALIVE_INTERVAL).asInteger());
        connOpts.setMqttVersion(context.getProperty(PROP_MQTT_VERSION).asInteger());
        connOpts.setConnectionTimeout(context.getProperty(PROP_CONN_TIMEOUT).asInteger());
        PropertyValue sslProp = context.getProperty(PROP_SSL_CONTEXT_SERVICE);
        if (sslProp.isSet()) {
            Properties sslProps = transformSSLContextService((SSLContextService) sslProp.asControllerService());
            connOpts.setSSLProperties(sslProps);
        }
        PropertyValue lastWillTopicProp = context.getProperty(PROP_LAST_WILL_TOPIC);
        if (lastWillTopicProp.isSet()) {
            String lastWillMessage = context.getProperty(PROP_LAST_WILL_MESSAGE).getValue();
            PropertyValue lastWillRetain = context.getProperty(PROP_LAST_WILL_RETAIN);
            Integer lastWillQOS = context.getProperty(PROP_LAST_WILL_QOS).asInteger();
            connOpts.setWill(lastWillTopicProp.getValue(), lastWillMessage.getBytes(), lastWillQOS, lastWillRetain.isSet() ? lastWillRetain.asBoolean() : false);
        }
        PropertyValue usernameProp = context.getProperty(PROP_USERNAME);
        if (usernameProp.isSet()) {
            connOpts.setUserName(usernameProp.getValue());
            connOpts.setPassword(context.getProperty(PROP_PASSWORD).getValue().toCharArray());
        }
        mqttClientConnectLock.writeLock().lock();
        try {
            mqttClient = getMqttClient(broker, clientID, persistence);
        } finally {
            mqttClientConnectLock.writeLock().unlock();
        }
    } catch (MqttException me) {
        logger.error("Failed to initialize the connection to the  " + me.getMessage());
    }
}
Also used : MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttException(org.eclipse.paho.client.mqttv3.MqttException) PropertyValue(org.apache.nifi.components.PropertyValue) Properties(java.util.Properties)

Example 12 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project nifi by apache.

the class TestConsumeMqttCommon method isConnected.

private static boolean isConnected(AbstractMQTTProcessor processor) throws NoSuchFieldException, IllegalAccessException {
    Field f = AbstractMQTTProcessor.class.getDeclaredField("mqttClient");
    f.setAccessible(true);
    IMqttClient mqttClient = (IMqttClient) f.get(processor);
    return mqttClient.isConnected();
}
Also used : Field(java.lang.reflect.Field) IMqttClient(org.eclipse.paho.client.mqttv3.IMqttClient)

Example 13 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project aware-client by denzilferreira.

the class Mqtt method initializeMQTT.

private void initializeMQTT() {
    String server = Aware.getSetting(getApplicationContext(), Aware_Preferences.MQTT_SERVER);
    if (server == null || server.length() == 0)
        return;
    if (server.contains("http") || server.contains("https")) {
        Uri serverUri = Uri.parse(server);
        server = serverUri.getHost();
    }
    MQTT_SERVER = server;
    MQTT_PORT = Aware.getSetting(getApplicationContext(), Aware_Preferences.MQTT_PORT);
    MQTT_USERNAME = Aware.getSetting(getApplicationContext(), Aware_Preferences.MQTT_USERNAME);
    MQTT_PASSWORD = Aware.getSetting(getApplicationContext(), Aware_Preferences.MQTT_PASSWORD);
    MQTT_KEEPALIVE = (Aware.getSetting(getApplicationContext(), Aware_Preferences.MQTT_KEEP_ALIVE).length() > 0 ? Aware.getSetting(getApplicationContext(), Aware_Preferences.MQTT_KEEP_ALIVE) : "600");
    MQTT_QoS = Aware.getSetting(getApplicationContext(), Aware_Preferences.MQTT_QOS);
    if (Integer.parseInt(MQTT_PORT) == 1883)
        MQTT_PROTOCOL = "tcp";
    if (Integer.parseInt(MQTT_PORT) == 8883)
        MQTT_PROTOCOL = "ssl";
    String MQTT_URL = MQTT_PROTOCOL + "://" + MQTT_SERVER + ":" + MQTT_PORT;
    if (MQTT_MESSAGES_PERSISTENCE == null)
        MQTT_MESSAGES_PERSISTENCE = new MemoryPersistence();
    MqttConnectOptions MQTT_OPTIONS = new MqttConnectOptions();
    // resume pending messages from server
    MQTT_OPTIONS.setCleanSession(false);
    // add 10 seconds to keep alive as options timeout
    MQTT_OPTIONS.setConnectionTimeout(Integer.parseInt(MQTT_KEEPALIVE) + 10);
    MQTT_OPTIONS.setKeepAliveInterval(Integer.parseInt(MQTT_KEEPALIVE));
    MQTT_OPTIONS.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    MQTT_OPTIONS.setAutomaticReconnect(true);
    if (MQTT_USERNAME.length() > 0)
        MQTT_OPTIONS.setUserName(MQTT_USERNAME);
    if (MQTT_PASSWORD.length() > 0)
        MQTT_OPTIONS.setPassword(MQTT_PASSWORD.toCharArray());
    if (MQTT_PROTOCOL.equalsIgnoreCase("ssl")) {
        try {
            SocketFactory factory = new SSLUtils(this).getSocketFactory(MQTT_SERVER);
            MQTT_OPTIONS.setSocketFactory(factory);
            MQTT_CLIENT = new MqttClient(MQTT_URL, String.valueOf(Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID).hashCode()), MQTT_MESSAGES_PERSISTENCE);
            MQTT_CLIENT.setCallback(this);
            new MQTTAsync().execute(MQTT_OPTIONS);
        } catch (NullPointerException e) {
            Log.e(Mqtt.TAG, "Unable to create SSL factory. Certificate missing?");
        } catch (MqttException | IllegalArgumentException e) {
            if (Aware.DEBUG)
                Log.e(TAG, "Failed: " + e.getMessage());
        }
    }
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) SocketFactory(javax.net.SocketFactory) MqttException(org.eclipse.paho.client.mqttv3.MqttException) Uri(android.net.Uri) SSLUtils(com.aware.utils.SSLUtils)

Example 14 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project wso2-axis2-transports by wso2.

the class MqttEndpoint method subscribeToTopic.

public void subscribeToTopic() {
    mqttClient = mqttConnectionFactory.getMqttClient(hostName, port, sslEnabled, clientId, qos, tempStore);
    mqttClient.setCallback(new MqttListenerCallback(this, contentType));
    MqttConnectOptions options = new MqttConnectOptions();
    options.setCleanSession(cleanSession);
    try {
        mqttClient.connect(options);
        if (topic != null) {
            mqttClient.subscribe(topic, qos);
            log.info("Connected to the remote server.");
        }
    } catch (MqttException e) {
        if (!mqttClient.isConnected()) {
            int retryC = 0;
            while ((retryC < retryCount)) {
                retryC++;
                log.info("Attempting to reconnect" + " in " + retryInterval * (retryC + 1) + " ms");
                try {
                    Thread.sleep(retryInterval * (retryC + 1));
                } catch (InterruptedException ignore) {
                }
                try {
                    mqttClient.connect(options);
                    if (mqttClient.isConnected()) {
                        if (topic != null) {
                            mqttClient.subscribe(topic, qos);
                        }
                        break;
                    }
                    log.info("Re-connected to the remote server.");
                } catch (MqttException e1) {
                    log.error("Error while trying to retry", e1);
                }
            }
        }
    }
}
Also used : MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Example 15 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project anki-battle-showcase by adessoAG.

the class MqttService method connect.

public void connect() {
    try {
        // test.mosquitto.org   broker.hivemq.com
        mqttClient = new MqttClient("tcp://localhost:1883", "anki-battle", new MemoryPersistence());
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(false);
        log.info("Connecting to MQTT broker: localhost:1883");
        mqttClient.connect(connOpts);
        log.info("Connected to MQTT broker");
        mqttClient.setCallback(new MqttCallback() {

            @Override
            public void connectionLost(Throwable throwable) {
                log.info("MQTT connection lost");
            }

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage) {
                try {
                    log.debug("MQTT message arrived: topic=" + s + "; message=" + mqttMessage.toString());
                    String temp = mqttMessage.toString();
                    byte[] hm = mqttMessage.getPayload();
                    JSONObject json = new JSONObject(mqttMessage.toString());
                    // get topic, where topic is identifier for vehicle
                    // get corresponding vehicle v
                    // v.exexute command
                    String topic = s.split("_")[0];
                    List<DynamicBody> vehicles = world.getDynamicBodies();
                    Vehicle wantedVehicle = null;
                    for (int i = 0; i < vehicles.size(); i++) {
                        Vehicle currentVehicle = ((Vehicle) vehicles.get(i));
                        if (topic.equals(currentVehicle.getName())) {
                            wantedVehicle = currentVehicle;
                            break;
                        }
                    }
                    String commandType = (String) json.get("type");
                    int speed;
                    Command command = null;
                    int track;
                    switch(commandType) {
                        case ("accelerate"):
                            speed = Integer.parseInt((String) json.get("velocity"));
                            command = new AccelerateCommand(speed);
                            break;
                        case ("brake"):
                            speed = Integer.parseInt((String) json.get("velocity"));
                            command = new BrakeCommand(speed);
                            break;
                        case ("change track"):
                            val lane = Double.parseDouble((String) json.get("track"));
                            command = new ChangeLaneCommand(lane);
                            break;
                        case ("uTurn"):
                            command = new UTurnCommand();
                            break;
                        case ("fireRocket"):
                            command = new FireRocketCommand("");
                            break;
                        case ("putMine"):
                            command = new PutMineCommand();
                            break;
                    }
                    if (command != null) {
                        command.execute(wantedVehicle);
                    } else {
                        log.debug("No Command");
                    }
                } catch (Exception e) {
                    log.error("Error while parsing MQTT message", e);
                }
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
            }
        });
    } catch (MqttException e) {
        log.debug("exception during initialising service");
        e.printStackTrace();
    }
}
Also used : lombok.val(lombok.val) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) Vehicle(de.adesso.anki.battle.world.bodies.Vehicle) JSONObject(org.json.JSONObject) List(java.util.List)

Aggregations

MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)46 MqttException (org.eclipse.paho.client.mqttv3.MqttException)37 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)23 MemoryPersistence (org.eclipse.paho.client.mqttv3.persist.MemoryPersistence)23 MqttMessage (org.eclipse.paho.client.mqttv3.MqttMessage)18 Test (org.junit.Test)12 Properties (java.util.Properties)6 IMqttClient (org.eclipse.paho.client.mqttv3.IMqttClient)6 MqttDefaultFilePersistence (org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence)5 IOException (java.io.IOException)4 IMqttDeliveryToken (org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)4 MqttCallback (org.eclipse.paho.client.mqttv3.MqttCallback)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 JsonArray (com.google.gson.JsonArray)3 JsonElement (com.google.gson.JsonElement)3 JsonObject (com.google.gson.JsonObject)3 SSLSecurityManager (it.unibo.arces.wot.sepa.commons.protocol.SSLSecurityManager)3 KeyManagementException (java.security.KeyManagementException)3 KeyStoreException (java.security.KeyStoreException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3