Java Code Examples for org.eclipse.paho.client.mqttv3.MqttException

The following are top voted examples for showing how to use org.eclipse.paho.client.mqttv3.MqttException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: iot-edge-greengrass   File: MqttBrokerMonitor.java   View source code 6 votes vote down vote up
public void connect() {
    try {
        client = new MqttAsyncClient((configuration.isSsl() ? "ssl" : "tcp") + "://" + configuration.getHost() + ":" + configuration.getPort(),
                getClientId(), new MemoryPersistence());
        client.setCallback(this);
        clientOptions = new MqttConnectOptions();
        clientOptions.setCleanSession(true);
        if (configuration.isSsl() && !StringUtils.isEmpty(configuration.getTruststore())) {
            Properties sslProperties = new Properties();
            sslProperties.put(SSLSocketFactoryFactory.TRUSTSTORE, configuration.getTruststore());
            sslProperties.put(SSLSocketFactoryFactory.TRUSTSTOREPWD, configuration.getTruststorePassword());
            sslProperties.put(SSLSocketFactoryFactory.TRUSTSTORETYPE, "JKS");
            sslProperties.put(SSLSocketFactoryFactory.CLIENTAUTH, false);
            clientOptions.setSSLProperties(sslProperties);
        }
        configuration.getCredentials().configure(clientOptions);
        checkConnection();
        if (configuration.getAttributeUpdates() != null) {
            configuration.getAttributeUpdates().forEach(mapping ->
                    gateway.subscribe(new AttributesUpdateSubscription(mapping.getDeviceNameFilter(), this))
            );
        }
        if (configuration.getServerSideRpc() != null) {
            configuration.getServerSideRpc().forEach(mapping ->
                    gateway.subscribe(new RpcCommandSubscription(mapping.getDeviceNameFilter(), this))
            );
        }
    } catch (MqttException e) {
        log.error("[{}:{}] MQTT broker connection failed!", configuration.getHost(), configuration.getPort(), e);
        throw new RuntimeException("MQTT broker connection failed!", e);
    }
}
 
Example 2
Project: summer-mqtt   File: ConnectionStatusTest.java   View source code 6 votes vote down vote up
@Test
public void testWithDefaultStatusPublisher() throws MqttException, InterruptedException
{
    StaticApplicationContext applicationContext = getStaticApplicationContext();
    PahoAsyncMqttClientService service = new PahoAsyncMqttClientService(
        BrokerHelper.getBrokerUri(), BrokerHelper.getClientId(),
        MqttClientConnectionType.PUBSUB, null);
    service.setApplicationEventPublisher(applicationContext);
    service.start();
    Assert.assertTrue(service.isConnected());
    Assert.assertTrue(service.isStarted());
    Thread.sleep(1100);
    Assert.assertEquals(0, messageDeliveredCount.get());
    Assert.assertEquals(0, messagePublishedCount.get());
    service.stop();
    service.close();
}
 
Example 3
Project: SensorThingsProcessor   File: ProcessorBatchAggregate.java   View source code 6 votes vote down vote up
@Override
public void stopListening() {
    try {
        if (orderExecutorService != null) {
            ProcessorHelper.shutdownProcessors(orderExecutorService, orderQueue, 5, TimeUnit.SECONDS);
        }
        if (mqttClient.isConnected()) {
            LOGGER.info("Stopping MQTT client.");
            String[] paths = comboBySource.keySet().toArray(new String[comboBySource.size()]);
            mqttClient.unsubscribe(paths);
            mqttClient.disconnect();
        } else {
            LOGGER.info("MQTT client already stopped.");
        }
    } catch (MqttException ex) {
        LOGGER.error("Problem while disconnecting!", ex);
    }
}
 
Example 4
Project: sensorhub-cloud-iot   File: MQTTPublisher.java   View source code 6 votes vote down vote up
private void initializeMqttClient()
    throws MqttException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    mqttClient = new MqttClient(cloudIotOptions.getBrokerUrl(),
        cloudIotOptions.getClientId(), new MemoryPersistence());

    MqttConnectOptions options = new MqttConnectOptions();
    // Note that the the Google Cloud IoT only supports MQTT 3.1.1, and Paho requires that we
    // explicitly set this. If you don't set MQTT version, the server will immediately close its
    // connection to your device.
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    options.setUserName(CloudIotOptions.UNUSED_ACCOUNT_NAME);

    // generate the jwt password
    options.setPassword(mqttAuth.createJwt(cloudIotOptions.getProjectId()));

    mqttClient.connect(options);
    mReady.set(true);
}
 
Example 5
Project: neoscada   File: MqttExporter.java   View source code 6 votes vote down vote up
private void unRealizeSubscriptions ( final Hive hive, final ObjectPool<MqttItemToTopic> pool ) throws InvalidSessionException, MqttException
{
    if ( this.poolListener != null )
    {
        pool.removeListener ( this.poolListener );
    }
    if ( this.session != null )
    {
        this.session.setListener ( (ItemChangeListener)null );
        hive.closeSession ( this.session );
    }
    if ( this.client != null )
    {
        this.client.setCallback ( null );
    }
}
 
Example 6
Project: neoscada   File: MqttExporter.java   View source code 6 votes vote down vote up
private void unsubscribe ( final Session session, final MqttItemToTopic itemToTopic ) throws InvalidSessionException, InvalidItemException, MqttException
{
    this.executor.submit ( new Callable<Void> () {
        @Override
        public Void call () throws Exception
        {
            logger.trace ( "unsubscribe () called with '{}'", itemToTopic );
            if ( itemToTopic.isReadable () )
            {
                MqttExporter.this.itemsToReadTopics.remove ( itemToTopic.getItemId () );
                MqttExporter.this.hive.unsubscribeItem ( session, itemToTopic.getItemId () );
            }
            if ( itemToTopic.isWritable () )
            {
                logger.trace ( "unsubscribe () called on topic '{}'", makeWriteTopicName ( itemToTopic ) );
                MqttExporter.this.itemsToWriteTopics.remove ( itemToTopic.getItemId () );
                MqttExporter.this.client.unsubscribe ( makeWriteTopicName ( itemToTopic ) );
            }
            return null;
        }
    } );
}
 
Example 7
Project: neoscada   File: MqttExporter.java   View source code 6 votes vote down vote up
/**
 * convert received mqtt message and write it to item
 *
 * @param hive
 * @param session
 * @param itemId
 * @param message
 * @throws InvalidSessionException
 * @throws PermissionDeniedException
 * @throws InvalidItemException
 * @throws MqttException
 */
private void writeMessageToItem ( final Hive hive, final Session session, final String itemId, final MqttMessage message ) throws InvalidSessionException, PermissionDeniedException, InvalidItemException, MqttException
{
    final DataItemValue div = messageToValue ( itemId, message );
    if ( div != null )
    {
        if ( div.getValue () != null )
        {
            hive.startWrite ( session, itemId, div.getValue (), null, null );
        }
        if ( div.getAttributes () != null && !div.getAttributes ().isEmpty () )
        {
            hive.startWriteAttributes ( session, itemId, div.getAttributes (), null, null );
        }
    }
}
 
Example 8
Project: neoscada   File: MqttExporter.java   View source code 6 votes vote down vote up
/**
 * @param itemId
 * @param message
 *            from MQTT topic
 * @return converted value
 * @throws MqttException
 */
private DataItemValue messageToValue ( final String itemId, final MqttMessage message ) throws MqttException
{
    final DataItemValue div;
    try
    {
        div = gson.fromJson ( new String ( message.getPayload (), "UTF-8" ), DataItemValue.class );
        if ( message.isRetained () || message.isDuplicate () )
        {
            logger.info ( "message is retained/duplicate, will not write" );
            return null;
        }
        return div;
    }
    catch ( JsonSyntaxException | UnsupportedEncodingException e1 )
    {
        logger.warn ( "could not parse message {}", message );
        return null;
    }
}
 
Example 9
Project: nCube-Thyme-Java   File: MqttClientKetiSub.java   View source code 6 votes vote down vote up
public MqttClientKetiSub(String serverUrl) {
	
	this.mqttServerUrl = serverUrl;
	
	System.out.println("[KETI MQTT Client] Client Initialize");
	
	try {
		mqc = new MqttClient(mqttServerUrl, mqttClientId, persistence);
		
		while(!mqc.isConnected()){
			mqc.connect();
			System.out.println("[KETI MQTT Client] Connection try");
		}
		
		System.out.println("[KETI MQTT Client] Connected to Server - " + mqttServerUrl);
	} catch (MqttException e) {
		e.printStackTrace();
	}
}
 
Example 10
Project: nCube-Thyme-Java   File: MqttClientKetiSub.java   View source code 6 votes vote down vote up
public MqttClientKetiSub(String serverUrl, String aeId) {
	
	this.mqttServerUrl = serverUrl;
	this.aeId = aeId;
	this.mqttClientId = MqttClient.generateClientId()+"K";
	
	System.out.println("[KETI MQTT Client] Client Initialize");
	
	try {
		mqc = new MqttClient(mqttServerUrl, mqttClientId, persistence);
		
		while(!mqc.isConnected()){
			mqc.connect();
			System.out.println("[KETI MQTT Client] Connection try");
		}
		
		System.out.println("[KETI MQTT Client] Connected to Server - " + mqttServerUrl);
	} catch (MqttException e) {
		e.printStackTrace();
	}
}
 
Example 11
Project: nCube-Thyme-Java   File: MqttClientKetiPub.java   View source code 6 votes vote down vote up
public MqttClientKetiPub(String serverUrl) {
	
	this.mqttServerUrl = serverUrl;
	
	System.out.println("[KETI MQTT Client] Client Initialize");
	
	try {
		mqc = new MqttClient(mqttServerUrl, mqttClientId, persistence);
		
		while(!mqc.isConnected()){
			mqc.connect();
			System.out.println("[KETI MQTT Client] Connection try");
		}
		
		System.out.println("[KETI MQTT Client] Connected to Server - " + mqttServerUrl);
	} catch (MqttException e) {
		e.printStackTrace();
	}
}
 
Example 12
Project: nCube-Thyme-Java   File: MqttClientKetiPub.java   View source code 6 votes vote down vote up
public MqttClientKetiPub(String serverUrl, String aeId) {
	
	this.mqttServerUrl = serverUrl;
	this.aeId = aeId;
	this.mqttClientId = MqttClient.generateClientId()+"K";
	
	System.out.println("[KETI MQTT Client] Client Initialize");
	
	try {
		mqc = new MqttClient(mqttServerUrl, mqttClientId, persistence);
		
		while(!mqc.isConnected()){
			mqc.connect();
			System.out.println("[KETI MQTT Client] Connection try");
		}
		
		System.out.println("[KETI MQTT Client] Connected to Server - " + mqttServerUrl);
	} catch (MqttException e) {
		e.printStackTrace();
	}
}
 
Example 13
Project: Taxi-Datalogger   File: MQTTPublisher.java   View source code 6 votes vote down vote up
private void initializeMqttClient()
    throws MqttException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    mqttClient = new MqttClient(cloudIotOptions.getBrokerUrl(),
        cloudIotOptions.getClientId(), new MemoryPersistence());

    MqttConnectOptions options = new MqttConnectOptions();
    // Note that the the Google Cloud IoT only supports MQTT 3.1.1, and Paho requires that we
    // explicitly set this. If you don't set MQTT version, the server will immediately close its
    // connection to your device.
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    options.setUserName(CloudIotOptions.UNUSED_ACCOUNT_NAME);

    // generate the jwt password
    options.setPassword(mqttAuth.createJwt(cloudIotOptions.getProjectId()));

    mqttClient.connect(options);
    mReady.set(true);
}
 
Example 14
Project: android-mqtt-service   File: MQTTService.java   View source code 6 votes vote down vote up
private void onPublish(final String requestId, final String topic, final byte[] payload) {
    if (!clientIsConnected()) {
        broadcastException(BROADCAST_EXCEPTION, requestId,
                           new Exception("Can't publish to topic: " + topic + ", client not connected!"));
        return;
    }

    try {
        MQTTServiceLogger.debug("onPublish", "Publishing to topic: " + topic + ", payload with size " + payload.length);
        MqttMessage message = new MqttMessage(payload);
        message.setQos(0);
        mClient.publish(topic, message);
        MQTTServiceLogger.debug("onPublish", "Successfully published to topic: " + topic + ", payload: " + payload);

        broadcast(BROADCAST_PUBLISH_SUCCESS, requestId,
                PARAM_TOPIC, topic
        );

    } catch (Exception exc) {
        broadcastException(BROADCAST_EXCEPTION, requestId, new MqttException(exc));
    }
}
 
Example 15
Project: device-mqtt   File: OutgoingSender.java   View source code 6 votes vote down vote up
private void connectClient() {
  try {
    client = new MqttClient(broker, clientId);
    client.setCallback(this);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(user);
    connOpts.setPassword(password.toCharArray());
    connOpts.setCleanSession(true);
    connOpts.setKeepAliveInterval(OUTGOING_MQTT_KEEP_ALIVE);
    logger.debug("Connecting to broker:  " + broker);
    client.connect(connOpts);
    logger.debug("Connected");
  } catch (MqttException e) {
    logger.error("Failed to connect to MQTT client ( " + broker + "/" + clientId
        + ") for outbound messages");
    logger.error(e.getLocalizedMessage());
    e.printStackTrace();
  }
}
 
Example 16
Project: device-mqtt   File: CommandResponseListener.java   View source code 6 votes vote down vote up
private void startListening() {
  logger.debug("Starting listening for response traffic");
  try {
    String url =
        cmdrespMqttBrokerProtocol + "://" + cmdrespMqttBroker + ":" + cmdrespMqttBrokerPort;
    client = new MqttClient(url, cmdrespMqttClientId);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(cmdrespMqttUser);
    connOpts.setPassword(cmdrespMqttPassword.toCharArray());
    connOpts.setCleanSession(true);
    connOpts.setKeepAliveInterval(cmdrespMqttKeepAlive);
    logger.debug("Connecting to response message broker:  " + cmdrespMqttBroker);
    client.connect(connOpts);
    logger.debug("Connected to response message broker");
    client.setCallback(this);
    client.subscribe(cmdrespMqttTopic, cmdrespMqttQos);
  } catch (MqttException e) {
    logger.error("Unable to connect to response message queue.  "
        + "Unable to respond to command requests.");
    e.printStackTrace();
    client = null;
  }
}
 
Example 17
Project: device-mqtt   File: IncomingListener.java   View source code 6 votes vote down vote up
private void startListening() {
  logger.debug("Starting listening for incoming traffic");
  try {
    String url =
        incomingMqttBrokerProtocol + "://" + incomingMqttBroker + ":" + incomingMqttBrokerPort;
    client = new MqttClient(url, incomingMqttClientId);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(incomingMqttUser);
    connOpts.setPassword(incomingMqttPassword.toCharArray());
    connOpts.setCleanSession(true);
    connOpts.setKeepAliveInterval(incomingMqttKeepAlive);
    logger.debug("Connecting to incoming message broker:  " + incomingMqttBroker);
    client.connect(connOpts);
    logger.debug("Connected to incoming message broker");
    client.setCallback(this);
    client.subscribe(incomingMqttTopic, incomingMqttQos);
  } catch (MqttException e) {
    logger.error("Unable to connect to incoming message queue.");
    e.printStackTrace();
    client = null;
  }
}
 
Example 18
Project: summer-mqtt   File: PahoAsyncMqttClientService.java   View source code 6 votes vote down vote up
@Override
public void close()
{
    reentrantLock.lock();
    try
    {
        stop();
        mqttClient.close();
        LOG.info(
            String.format("Client ID %s is closed and cannot be restarted.", getClientId()));
    }
    catch (MqttException ex)
    {
        LOG.error(
            String.format("Client ID %s encountered an error while closing.", getClientId()),
            ex);
    }
    finally
    {
        reentrantLock.unlock();
    }
}
 
Example 19
Project: summer-mqtt   File: AutomaticReconnectTest.java   View source code 6 votes vote down vote up
@Test
public void testGoodConnection() throws MqttException
{
    StaticApplicationContext applicationContext = getStaticApplicationContext();
    MessageChannel inboundMessageChannel = new ExecutorSubscribableChannel();
    PahoAsyncMqttClientService service = new PahoAsyncMqttClientService(
        BrokerHelper.getProxyUri(), BrokerHelper.getClientId(), MqttClientConnectionType.PUBSUB,
        null);
    service.setApplicationEventPublisher(applicationContext);
    service.setInboundMessageChannel(inboundMessageChannel);
    service.subscribe(String.format("client/%s", BrokerHelper.getClientId()),
        MqttQualityOfService.QOS_0);
    service.getMqttConnectOptions().setCleanSession(true);
    Assert.assertTrue(service.start());
    Assert.assertTrue(service.isConnected());
    Assert.assertTrue(service.isStarted());
    Assert.assertEquals(1, clientConnectedCount.get());
    Assert.assertEquals(0, clientDisconnectedCount.get());
    Assert.assertEquals(0, clientLostConnectionCount.get());
    Assert.assertEquals(0, clientFailedConnectionCount.get());
    service.stop();
    service.close();
    applicationContext.close();
}
 
Example 20
Project: summer-mqtt   File: SubscribeUnsubscribeTest.java   View source code 6 votes vote down vote up
@Test
public void testSubscribeDuplicateTopicNameDifferentQualityOfServiceBeforeStart()
    throws MqttException
{
    PahoAsyncMqttClientService service = new PahoAsyncMqttClientService(
        BrokerHelper.getBrokerUri(), BrokerHelper.getClientId(),
        MqttClientConnectionType.PUBSUB, null);
    Assert.assertEquals(0, service.getTopicSubscriptions().size());
    service.subscribe(String.format("client/%s", BrokerHelper.getClientId()),
        MqttQualityOfService.QOS_0);
    Assert.assertEquals(1, service.getTopicSubscriptions().size());
    Assert.assertEquals(MqttQualityOfService.QOS_0,
        service.getTopicSubscriptions().get(0).getQualityOfService());
    service.subscribe(String.format("client/%s", BrokerHelper.getClientId()),
        MqttQualityOfService.QOS_1);
    Assert.assertEquals(1, service.getTopicSubscriptions().size());
    Assert.assertEquals(MqttQualityOfService.QOS_1,
        service.getTopicSubscriptions().get(0).getQualityOfService());
}
 
Example 21
Project: iot-edge-greengrass   File: WiotpMqttBrokerMonitor.java   View source code 5 votes vote down vote up
@Override
public void onRpcCommand(String deviceName, RpcCommandData command) {
    int requestId = command.getRequestId();

    List<ServerSideRpcMapping> mappings = configuration.getServerSideRpc().stream()
            .filter(mapping -> deviceName.matches(mapping.getDeviceNameFilter()))
            .filter(mapping -> command.getMethod().matches(mapping.getMethodFilter())).collect(Collectors.toList());

    mappings.forEach(mapping -> {
        String requestTopic = replace(mapping.getRequestTopicExpression(), deviceName, command);
        String body = replace(mapping.getValueExpression(), deviceName, command);

        boolean oneway = StringUtils.isEmpty(mapping.getResponseTopicExpression());
        if (oneway) {
            publish(deviceName, requestTopic, new MqttMessage(body.getBytes(StandardCharsets.UTF_8)));
        } else {
            String responseTopic = replace(mapping.getResponseTopicExpression(), deviceName, command);
            try {
                log.info("[{}] Temporary subscribe to RPC response topic [{}]", deviceName, responseTopic);
                client.subscribe(responseTopic, 1,
                        new MqttRpcResponseMessageListener(requestId, deviceName, this::onRpcCommandResponse)
                ).waitForCompletion();
                scheduler.schedule(() -> {
                    unsubscribe(deviceName, requestId, responseTopic);
                }, mapping.getResponseTimeout(), TimeUnit.MILLISECONDS);
                publish(deviceName, requestTopic, new MqttMessage(body.getBytes(StandardCharsets.UTF_8)));
            } catch (MqttException e) {
                log.warn("[{}] Failed to subscribe to response topic and push RPC command [{}]", deviceName, requestId, e);
            }
        }
    });
}
 
Example 22
Project: iot-edge-greengrass   File: WiotpMqttBrokerMonitor.java   View source code 5 votes vote down vote up
private void unsubscribe(String deviceName, int requestId, String topic) {
    try {
        client.unsubscribe(topic);
    } catch (MqttException e) {
        log.warn("[{}][{}] Failed to unsubscribe from RPC reply topic [{}]", deviceName, requestId, topic, e);
    }
}
 
Example 23
Project: iot-edge-greengrass   File: MqttBrokerMonitor.java   View source code 5 votes vote down vote up
@Override
public void onRpcCommand(String deviceName, RpcCommandData command) {
    int requestId = command.getRequestId();

    List<ServerSideRpcMapping> mappings = configuration.getServerSideRpc().stream()
            .filter(mapping -> deviceName.matches(mapping.getDeviceNameFilter()))
            .filter(mapping -> command.getMethod().matches(mapping.getMethodFilter())).collect(Collectors.toList());

    mappings.forEach(mapping -> {
        String requestTopic = replace(mapping.getRequestTopicExpression(), deviceName, command);
        String body = replace(mapping.getValueExpression(), deviceName, command);

        boolean oneway = StringUtils.isEmpty(mapping.getResponseTopicExpression());
        if (oneway) {
            publish(deviceName, requestTopic, new MqttMessage(body.getBytes(StandardCharsets.UTF_8)));
        } else {
            String responseTopic = replace(mapping.getResponseTopicExpression(), deviceName, command);
            try {
                log.info("[{}] Temporary subscribe to RPC response topic [{}]", deviceName, responseTopic);
                client.subscribe(responseTopic, 1,
                        new MqttRpcResponseMessageListener(requestId, deviceName, this::onRpcCommandResponse)
                ).waitForCompletion();
                scheduler.schedule(() -> {
                    unsubscribe(deviceName, requestId, responseTopic);
                }, mapping.getResponseTimeout(), TimeUnit.MILLISECONDS);
                publish(deviceName, requestTopic, new MqttMessage(body.getBytes(StandardCharsets.UTF_8)));
            } catch (MqttException e) {
                log.warn("[{}] Failed to subscribe to response topic and push RPC command [{}]", deviceName, requestId, e);
            }
        }
    });
}
 
Example 24
Project: iot-edge-greengrass   File: MqttBrokerMonitor.java   View source code 5 votes vote down vote up
private void unsubscribe(String deviceName, int requestId, String topic) {
    try {
        client.unsubscribe(topic);
    } catch (MqttException e) {
        log.warn("[{}][{}] Failed to unsubscribe from RPC reply topic [{}]", deviceName, requestId, topic, e);
    }
}
 
Example 25
Project: export-distro   File: MQTTSender.java   View source code 5 votes vote down vote up
public void closeClient() {
	try {
		if (client != null) {
			client.disconnect();
			client.close();
		}
	} catch (MqttException e) {
		logger.error("Problems disconnecting and closing the client.");
		e.printStackTrace();
	}
}
 
Example 26
Project: reactive-components   File: MqttComponent.java   View source code 5 votes vote down vote up
@Deactivate
public void deactivate() throws MqttException {
    for (MqttDestination<?> destination : destinations) {
        try {
            destination.close(); 
        } catch (Exception e) {
        }
    }
    client.disconnect();
    client.close();
}
 
Example 27
Project: echo   File: MQTTPublisher.java   View source code 5 votes vote down vote up
public static void main(String args[]) {
    String topic = "iot/iot";
    String content = "Hello ith";
    int qos = 2;
    String broker = "tcp://127.0.0.1:1883";
    String clientId = "sample";
    MemoryPersistence persistence = new MemoryPersistence();

    try {
        MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        System.out.println("Connecting to broker");
        sampleClient.connect(connOpts);
        System.out.println("connected");
        System.out.println("Publishing meessage: " + content);
        MqttMessage message = new MqttMessage(content.getBytes());
        message.setQos(qos);
        sampleClient.publish(topic, message);
        System.out.println("Message published");
        sampleClient.disconnect();
        System.out.println("Disconnected");
        System.exit(0);
    } catch (MqttException e){
        System.out.println("reason " + e.getReasonCode());
        System.out.println("msg " + e.getMessage());
        System.out.println("loc " + e.getLocalizedMessage());
        System.out.println("cause " + e.getCause());
        System.out.println("exxcep " + e);
    }

}
 
Example 28
Project: echo   File: AppManager.java   View source code 5 votes vote down vote up
public AppManager() {
	super();
	resourceDirectory = new ResourceDirectory("13.71.125.147", 8080);
	mqttBroker = "tcp://10.24.24.222:1883";
	mapper = new ObjectMapper();
	try {
		MemoryPersistence persistence = new MemoryPersistence();
		mqttClient = new MqttClient(mqttBroker, "master", persistence);
	} catch (MqttException e) {
		e.printStackTrace();
	}
}
 
Example 29
Project: echo   File: NifiDeployer.java   View source code 5 votes vote down vote up
public boolean stopDag() {
    try {
        mqttClient.connect();
        stopArtifactsAndPurgeConnections();
        removeArtifacts();
        mqttClient.disconnect();
    } catch(MqttException e ) {
        e.printStackTrace();
    }
    // stop all processors and ports and rpgs, purge all connections.
    // remove all connections.
    // remove all processors and ports and rpgs.
    return true;
}
 
Example 30
Project: echo   File: NifiDeployer.java   View source code 5 votes vote down vote up
public DataflowInput deployDag(Map<Processor, Device> placementMap,
                               DataflowInput input) {

    this.processorMapping = placementMap;
    for (Map.Entry<Processor, Device> entry : this.processorMapping.entrySet()) {
        System.out.println(entry.getValue().getDeviceIP());
    }

    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setCleanSession(true);
    try {
        mqttClient.connect();

        populateMaps(input.getWiring(), placementMap);

        createProcessorsPortsAndRPGs();
        createConnections();
        startAllPorts();
        createRemoteConnections();
        startAllProcessors();

        mqttClient.disconnect();
    } catch (MqttException e) {
        e.printStackTrace();
    }
    return input;
}
 
Example 31
Project: WebRTC-VideoCall-Anrdoid   File: MqttClientHelper.java   View source code 5 votes vote down vote up
public void release() {
    try {
        mqttAndroidClient.unregisterResources();
        mqttAndroidClient.close();
        mqttAndroidClient.disconnect();
        mqttAndroidClient = null;

        mqttClientListeners.clear();
        mqttClientListeners = null;
    } catch (MqttException e) {
        e.printStackTrace();
    }
}
 
Example 32
Project: jmeter-bzm-plugins   File: MqttCallBackImpl.java   View source code 5 votes vote down vote up
public void close(){
	if (client.isConnected()){
		try {
			client.disconnect();
			log.info("CLIENT DISCONNECTION");
			messages.add("CLIENT DISCONNECTION");
			client.close();
			log.info("CLIENT CLOSING");
			messages.add("CLIENT CLOSING");
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}
}
 
Example 33
Project: reactive-components   File: MqttSource.java   View source code 5 votes vote down vote up
@Override
public void cancel() {
    try {
        if (subScribed.compareAndSet(true, false)) {
            client.unsubscribe(topic);
        }
    } catch (MqttException e) {
        subscriber.onError(e);
    }
}
 
Example 34
Project: ConAir   File: ACController.java   View source code 5 votes vote down vote up
protected void mqttSendMessage(String topic, String payload){
    byte[] encodedPayload = new byte[0];
    try {
        encodedPayload = payload.getBytes("UTF-8");
        MqttMessage message = new MqttMessage(encodedPayload);
        message.setRetained(true);
        message.setQos(1);
        client.publish(topic, message);
    } catch (UnsupportedEncodingException | MqttException e) {
        e.printStackTrace();
    }
}
 
Example 35
Project: neoscada   File: MqttInput.java   View source code 5 votes vote down vote up
@Override
public synchronized void stop ()
{
    logger.info ( "Request to stop component: {}", this );
    if ( !this.started )
    {
        logger.debug ( "Component already stopped" );
        return;
    }

    this.started = false;
    if ( this.client != null )
    {
        try
        {
            logger.debug ( "Disconnecting client" );
            this.client.disconnect ().waitForCompletion ();
        }
        catch ( final MqttException e )
        {
            logger.warn ( "Failed to close MQTT Client", e );
        }
        finally
        {
            this.client = null;
            fireDisposed ();
        }
    }
}
 
Example 36
Project: WebRTC-VideoCall-Anrdoid   File: MqttClientHelper.java   View source code 5 votes vote down vote up
public void unsubscribeToTopic(String topic) {
    try {
        mqttAndroidClient.unsubscribe(topic);
    } catch (MqttException ex) {
        System.err.println("Exception whilst subscribing");
        ex.printStackTrace();
    }
}
 
Example 37
Project: neoscada   File: MqttExporter.java   View source code 5 votes vote down vote up
private void setupMqtt ( final Hive hive, final Session session ) throws MqttException
{
    this.client.setCallback ( new MqttCallback () {

        @Override
        public void messageArrived ( final String topic, final MqttMessage message ) throws Exception
        {
            logger.trace ( "received message '{}' on topic '{}'", message, topic );
            MqttExporter.this.executor.submit ( new Callable<Void> () {
                @Override
                public Void call () throws Exception
                {
                    final String itemId = MqttExporter.this.itemsToWriteTopics.inverse ().get ( topic );
                    if ( itemId != null )
                    {
                        writeMessageToItem ( hive, session, itemId, message );
                    }
                    else
                    {
                        logger.warn ( "received message '{}' on topic '{}' but no corresponding item found", message, topic );
                    }
                    return null;
                }
            } );
        }

        @Override
        public void deliveryComplete ( final IMqttDeliveryToken token )
        {
        }

        @Override
        public void connectionLost ( final Throwable th )
        {
            // TODO: implement this
            logger.warn ( "connectionLost", th );
        }
    } );
}
 
Example 38
Project: neoscada   File: MqttExporter.java   View source code 5 votes vote down vote up
private void setupPoolListener ( final Hive hive, final Session session )
{
    this.poolListener = new ObjectPoolListener<MqttItemToTopic> () {
        @Override
        public void serviceRemoved ( final MqttItemToTopic itemToTopic, final Dictionary<?, ?> properties )
        {
            try
            {
                unsubscribe ( session, itemToTopic );
            }
            catch ( InvalidSessionException | InvalidItemException | MqttException e )
            {
                logger.error ( "unsubscribe failed", e );
            }
        }

        @Override
        public void serviceModified ( final MqttItemToTopic itemToTopic, final Dictionary<?, ?> properties )
        {
            throw new UnsupportedOperationException ( "serviceModified must not be called" );
        }

        @Override
        public void serviceAdded ( final MqttItemToTopic itemToTopic, final Dictionary<?, ?> properties )
        {
            try
            {
                subscribe ( session, itemToTopic );
            }
            catch ( InvalidSessionException | InvalidItemException | MqttException e )
            {
                logger.error ( "subscribe failed", e );
            }
        }
    };
    this.pool.addListener ( this.poolListener );
}
 
Example 39
Project: react-native-android-library-humaniq-api   File: MqttModule.java   View source code 5 votes vote down vote up
@ReactMethod public void sendMessage(String accountId, String messageBody) {

    try {
      MqttMessage message = new MqttMessage();
      message.setPayload(messageBody.getBytes());
      mqttAndroidClient.publish(accountId, message);
      if(!mqttAndroidClient.isConnected()) {
        Log.d(LOG_TAG, mqttAndroidClient.getBufferedMessageCount() + " messages in buffer.");
      }
    } catch (MqttException e) {
      Log.d(LOG_TAG, "Error Publishing: " + e.getMessage());
      e.printStackTrace();
    }
  }
 
Example 40
Project: neoscada   File: MqttExporter.java   View source code 5 votes vote down vote up
/**
 * send DataItemValue to topic
 *
 * @param topic
 * @param div
 */
private void publishValue ( final String topic, final DataItemValue div )
{
    logger.trace ( "publish dataItemValue {} on topic {}", div, topic );
    try
    {
        this.client.getTopic ( topic ).publish ( valueToMessage ( div ) );
    }
    catch ( final MqttException e )
    {
        logger.error ( "could not publish message {} on topic {}", div, topic, e );
    }
}