org.eclipse.paho.client.mqttv3.persist.MemoryPersistence Java Examples

The following examples show how to use org.eclipse.paho.client.mqttv3.persist.MemoryPersistence. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MqttService.java    From PresencePublisher with MIT License 6 votes vote down vote up
public void sendMessages(List<Message> messages) throws MqttException {
    HyperLog.i(TAG, "Sending " + messages.size() + " messages to server");
    boolean tls = sharedPreferences.getBoolean(USE_TLS, false);
    String clientCertAlias = sharedPreferences.getString(CLIENT_CERTIFICATE, null);
    String login = sharedPreferences.getString(USERNAME, "");
    String password = securePreferences.getString(PASSWORD, "");

    MqttClient mqttClient = new MqttClient(getMqttUrl(tls), Settings.Secure.ANDROID_ID, new MemoryPersistence());
    MqttConnectOptions options = new MqttConnectOptions();
    options.setConnectionTimeout(5);
    if (!login.isEmpty() && !password.isEmpty()) {
        options.setUserName(login);
        options.setPassword(password.toCharArray());
    }
    if (tls) {
        options.setSocketFactory(factory.getSslSocketFactory(clientCertAlias));
    }
    mqttClient.connect(options);
    for (Message message : messages) {
        mqttClient.publish(message.getTopic(), message.getContent().getBytes(Charset.forName("UTF-8")), 1, false);
    }
    mqttClient.disconnect(5);
    mqttClient.close(true);
    HyperLog.i(TAG, "Sending messages was successful");
}
 
Example #2
Source File: ProtobufMqttProtocolHandler.java    From diozero with MIT License 6 votes vote down vote up
public ProtobufMqttProtocolHandler(NativeDeviceFactoryInterface deviceFactory) {
	super(deviceFactory);

	String mqtt_url = PropertyUtil.getProperty(MQTT_URL_PROP, null);
	if (mqtt_url == null) {
		throw new RuntimeIOException("Property '" + MQTT_URL_PROP + "' must be set");
	}

	try {
		mqttClient = new MqttClient(mqtt_url, MqttClient.generateClientId(), new MemoryPersistence());
		mqttClient.setCallback(this);
		MqttConnectOptions con_opts = new MqttConnectOptions();
		con_opts.setAutomaticReconnect(true);
		con_opts.setCleanSession(true);
		mqttClient.connect(con_opts);
		Logger.debug("Connected to {}", mqtt_url);

		// Subscribe
		Logger.debug("Subscribing to response and notification topics...");
		mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC);
		mqttClient.subscribe(MqttProviderConstants.GPIO_NOTIFICATION_TOPIC);
		Logger.debug("Subscribed");
	} catch (MqttException e) {
		throw new RuntimeIOException(e);
	}
}
 
Example #3
Source File: SocketProxyTest.java    From rxmqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void whenPahoConnectToBrokerViaProxyThenItWorks() throws Throwable {
    
    // Wait a second
    Thread.sleep(1000);
    
    // Create the client
    MqttConnectOptions options = new MqttConnectOptions();
    options.setAutomaticReconnect(false);
    options.setCleanSession(false);
    options.setKeepAliveInterval(1);
    options.setConnectionTimeout(1);
    
    String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT;
    MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence());
    
    // Connect, publish, disconnect
    AsyncPahoUtils.connect(asyncClient);
    AsyncPahoUtils.publish(asyncClient, "topical", "Test message".getBytes());
    AsyncPahoUtils.disconnect(asyncClient);
    
    // Check we received a message
    Assert.assertEquals(1, broker.getMessages().size());
    
}
 
Example #4
Source File: AwsIotMqttConnection.java    From aws-iot-device-sdk-java with Apache License 2.0 6 votes vote down vote up
public AwsIotMqttConnection(AbstractAwsIotClient client, SocketFactory socketFactory, String serverUri)
        throws AWSIotException {
    super(client);

    this.socketFactory = socketFactory;

    messageListener = new AwsIotMqttMessageListener(client);
    clientListener = new AwsIotMqttClientListener(client);

    try {
        mqttClient = new MqttAsyncClient(serverUri, client.getClientId(), new MemoryPersistence());
        mqttClient.setCallback(clientListener);
    } catch (MqttException e) {
        throw new AWSIotException(e);
    }
}
 
Example #5
Source File: MqttTestClient.java    From diozero with MIT License 6 votes vote down vote up
public MqttTestClient(String mqttUrl) throws MqttException {
	mqttClient = new MqttClient(mqttUrl, MqttClient.generateClientId(), new MemoryPersistence());
	mqttClient.setCallback(this);
	MqttConnectOptions con_opts = new MqttConnectOptions();
	con_opts.setAutomaticReconnect(true);
	con_opts.setCleanSession(true);
	mqttClient.connect(con_opts);
	Logger.debug("Connected to {}", mqttUrl);

	lock = new ReentrantLock();
	conditions = new HashMap<>();
	responses = new HashMap<>();

	// Subscribe
	Logger.debug("Subscribing to {}...", MqttProviderConstants.RESPONSE_TOPIC);
	mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC);
	Logger.debug("Subscribed");
}
 
Example #6
Source File: MQService.java    From HelloMQTT with Apache License 2.0 6 votes vote down vote up
/**
 * 服务初始化回调函数
 */
@Override
public void onCreate() {
    super.onCreate();

    /**创建一个Handler*/
    mConnHandler = new Handler();
    try {
        /**新建一个本地临时存储数据的目录,该目录存储将要发送到服务器的数据,直到数据被发送到服务器*/
        mDataStore = new MqttDefaultFilePersistence(getCacheDir().getAbsolutePath());
    } catch(Exception e) {
        e.printStackTrace();
        /**新建一个内存临时存储数据的目录*/
        mDataStore = null;
        mMemStore = new MemoryPersistence();
    }
    /**连接的参数选项*/
    mOpts = new MqttConnectOptions();
    /**删除以前的Session*/
    mOpts.setCleanSession(MQTT_CLEAN_SESSION);
    // Do not set keep alive interval on mOpts we keep track of it with alarm's
    /**定时器用来实现心跳*/
    mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    /**管理网络连接*/
    mConnectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
}
 
Example #7
Source File: MqttServerEndpointStatusTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void disconnectedByClient(TestContext context) {

  Async async = context.async();

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect();
    client.disconnect();

    // give more time to the MqttClient to update its connection state
    this.vertx.setTimer(1000, t1 -> {
      async.complete();
    });

    async.await();

    context.assertTrue(!client.isConnected() && !this.endpoint.isConnected());

  } catch (MqttException e) {
    context.assertTrue(false);
    e.printStackTrace();
  }
}
 
Example #8
Source File: MqttServerSubscribeTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
private void subscribe(TestContext context, String topic, int expectedQos) {

    this.async = context.async();

    try {
      MemoryPersistence persistence = new MemoryPersistence();
      MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
      client.connect();

      String[] topics = new String[]{topic};
      int[] qos = new int[]{expectedQos};
      // after calling subscribe, the qos is replaced with granted QoS that should be the same
      client.subscribe(topics, qos);

      this.async.await();

      context.assertTrue(qos[0] == expectedQos);

    } catch (MqttException e) {

      context.assertTrue(!topic.equals(MQTT_TOPIC_FAILURE) ? false : true);
      e.printStackTrace();
    }
  }
 
Example #9
Source File: MqttServerClientIdentifierTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidClientIdentifier(TestContext context) throws Exception {

  MemoryPersistence persistence = new MemoryPersistence();
  MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "id-madeof-23-characters", persistence);
  MqttConnectOptions options = new MqttConnectOptions();
  options.setMqttVersion(MQTT_VERSION_3_1);

  try {

    client.connect(options);
    context.assertTrue(true);

  } catch (MqttException ignore) {
    context.assertTrue(false);
  }
}
 
Example #10
Source File: MQTTWrapper.java    From lwm2m_over_mqtt with Eclipse Public License 1.0 6 votes vote down vote up
public void start() {
	MemoryPersistence persistence = new MemoryPersistence();
	try {
		String serverURI = "tcp://"+brokerAddress.getHostString()+":"+brokerAddress.getPort();
		mqttClient = new MqttClient(serverURI, endpointID, persistence);
           MqttConnectOptions connOpts = new MqttConnectOptions();
           connOpts.setCleanSession(true);
           LOG.info("Connecting endpoint "+ endpointID + " to broker: "+serverURI);
           mqttClient.connect(connOpts);
           LOG.info("Connected");
	} catch(MqttException me) {
           LOG.error("reason "+me.getReasonCode());
           LOG.error("msg "+me.getMessage());
           LOG.error("loc "+me.getLocalizedMessage());
           LOG.error("cause "+me.getCause());
           LOG.error("excep "+me);
           me.printStackTrace();
       }
}
 
Example #11
Source File: MqttConfiguration.java    From mqtt with Apache License 2.0 6 votes vote down vote up
@Bean
public MqttPahoClientFactory mqttClientFactory() {
	DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
	factory.setServerURIs(mqttProperties.getUrl());
	factory.setUserName(mqttProperties.getUsername());
	factory.setPassword(mqttProperties.getPassword());
	factory.setCleanSession(mqttProperties.isCleanSession());
	factory.setConnectionTimeout(mqttProperties.getConnectionTimeout());
	factory.setKeepAliveInterval(mqttProperties.getKeepAliveInterval());
	if (ObjectUtils.nullSafeEquals(mqttProperties.getPersistence(), "file")) {
		factory.setPersistence(new MqttDefaultFilePersistence(mqttProperties.getPersistenceDirectory()));
	}
	else if (ObjectUtils.nullSafeEquals(mqttProperties.getPersistence(), "memory")) {
		factory.setPersistence(new MemoryPersistence());
	}
	return factory;
}
 
Example #12
Source File: MqttServerClientIdentifierTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidClientIdentifier(TestContext context) throws Exception {

  MemoryPersistence persistence = new MemoryPersistence();
  MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "invalid-id-with-24-chars", persistence);
  MqttConnectOptions options = new MqttConnectOptions();
  options.setMqttVersion(MQTT_VERSION_3_1);

  try {

    client.connect(options);
    context.assertTrue(false);

  } catch (MqttException ignore) {
    context.assertTrue(true);
  }
}
 
Example #13
Source File: MqttServerConnectionTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void refusedClientIdZeroBytes(TestContext context) {

  this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED;

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttConnectOptions options = new MqttConnectOptions();
    options.setCleanSession(false);
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "", persistence);
    client.connect(options);
    context.fail();
  } catch (MqttException e) {
    context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_INVALID_CLIENT_ID);
    context.assertNotNull(rejection);
  }
}
 
Example #14
Source File: MqttServerConnectionTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void refusedBadUsernamePassword(TestContext context) {

  this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD;

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttConnectOptions options = new MqttConnectOptions();
    options.setUserName("wrong_username");
    options.setPassword("wrong_password".toCharArray());
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect(options);
    context.fail();
  } catch (MqttException e) {
    context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_FAILED_AUTHENTICATION);
  }
}
 
Example #15
Source File: MqttTopicConnector.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * Create MQTT client object with required configuration.
 */
@Override
public void create() {

    try {
        String mqttUrl = System.getProperty("mqtturl");
        if (StringUtils.isBlank(mqttUrl)) {
            mqttUrl = MessagingConstants.MQTT_PROPERTIES.getProperty("mqtturl", MessagingConstants.MQTT_URL_DEFAULT);
        }
        MemoryPersistence memoryPersistence = new MemoryPersistence();
        String clientId = MessagingUtil.getRandomString(23);
        mqttClient = new MqttClient(mqttUrl, clientId, memoryPersistence);
        if (log.isDebugEnabled()) {
            log.debug("MQTT client created: [client-id] " + clientId);
        }
    } catch (Exception e) {
        String message = "Could not create MQTT client";
        log.error(message, e);
        throw new MessagingException(message, e);
    }
}
 
Example #16
Source File: MqttAppender.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
public void activate(Dictionary<String, Object> config) throws Exception {
    this.config = config;
    client = new MqttClient(
            getValue(config, SERVER_PROPERTY, SERVER_DEFAULT),
            getValue(config, CLIENT_ID_PROPERTY, CLIENT_ID_DEFAULT),
            new MemoryPersistence());
    MqttConnectOptions options = new MqttConnectOptions();
    options.setCleanSession(true);
    String username = getValue(config, "username", null);
    String password = getValue(config, "password", null);
    if (username != null) {
        options.setUserName(username);
    }
    if (password != null) {
        options.setPassword(password.toCharArray());
    }
    client.connect(options);
}
 
Example #17
Source File: MqttServerConnectionTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void refusedUnacceptableProtocolVersion(TestContext context) {

  this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION;

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttConnectOptions options = new MqttConnectOptions();
    // trying the old 3.1
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect(options);
    context.fail();
  } catch (MqttException e) {
    context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_INVALID_PROTOCOL_VERSION);
  }
}
 
Example #18
Source File: MqttServerConnectionTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void connectionAlreadyAccepted(TestContext context) throws Exception {

  this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_ACCEPTED;

  MemoryPersistence persistence = new MemoryPersistence();
  MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
  client.connect();

  try {
    // try to accept a connection already accepted
    this.endpoint.accept(false);
    context.fail();
  } catch (IllegalStateException e) {
    // Ok
  }
}
 
Example #19
Source File: MqttClientInstance.java    From maestro-java with Apache License 2.0 6 votes vote down vote up
private MqttClientInstance(final String url) {
    final String adjustedUrl = URLUtils.sanitizeURL(url);

    final UUID uuid = UUID.randomUUID();
    final String clientId = uuid.toString();
    final MemoryPersistence memoryPersistence = new MemoryPersistence();

    this.id = clientId;
    try {
        client = new MqttClient(adjustedUrl, "maestro.exchange." + clientId, memoryPersistence);

        Runtime.getRuntime().addShutdownHook(new Thread(this::terminate));
    }
    catch (MqttException e) {
        throw new MaestroConnectionException("Unable create a MQTT client instance : " + e.getMessage(),
                e);
    }

}
 
Example #20
Source File: MQTTManager.java    From EMQ-Android-Toolkit with Apache License 2.0 6 votes vote down vote up
public MqttAndroidClient createClient(String id, String serverURI, String clientId) {
    MqttClientPersistence mqttClientPersistence = new MemoryPersistence();
    MqttAndroidClient client = new MqttAndroidClient(MyApplication.getContext(), serverURI, clientId, mqttClientPersistence);
    client.setCallback(new MqttCallback() {
        @Override
        public void connectionLost(Throwable cause) {
            LogUtil.e("connectionLost");
            EventBus.getDefault().post(new MQTTActionEvent(Constant.MQTTStatusConstant.CONNECTION_LOST, null, cause));

        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            LogUtil.d("topic is " + topic + ",message is " + message.toString() + ", qos is " + message.getQos());
            EventBus.getDefault().postSticky(new MessageEvent(new EmqMessage(topic, message)));

        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
            LogUtil.d("deliveryComplete");


        }
    });

    mClients.put(id, client);

    return client;

}
 
Example #21
Source File: MqttServerConnectionTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void refusedNotAuthorized(TestContext context) {

  this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED;

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect();
    context.fail();
  } catch (MqttException e) {
    context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_NOT_AUTHORIZED);
  }
}
 
Example #22
Source File: MqttListener.java    From diozero with MIT License 5 votes vote down vote up
public MqttListener() {
	try {
		mqttClient = new MqttClient(mqttServer, MqttClient.generateClientId(), new MemoryPersistence());
		mqttClient.setCallback(this);
		MqttConnectOptions con_opts = new MqttConnectOptions();
		con_opts.setCleanSession(true);
		mqttClient.connect(con_opts);
		System.out.println("Connected to '" + mqttServer + "'");
	} catch (MqttException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example #23
Source File: PushListActivity.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void configureMqttClient() {
    try {
        mqttClient = new MqttAsyncClient("tcp://test-io.Pushfish.api.push.fish:1883", "android", new MemoryPersistence());
        mqttClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
                Log.i(PushListActivity.class.getName(), "MQTT Connection successful!");
            }

            @Override
            public void connectionLost(Throwable cause) {
                Log.w(PushListActivity.class.getName(), "MQTT Connection was lost!");
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) {
                handleMessage(topic, message);
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {

            }
        });
    } catch (MqttException e) {
        e.printStackTrace();
    }
}
 
Example #24
Source File: MqttServerConnectionTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void refusedServerUnavailable(TestContext context) {

  this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE;

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect();
    context.fail();
  } catch (MqttException e) {
    context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_BROKER_UNAVAILABLE);
  }
}
 
Example #25
Source File: MqttConnection.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
public MqttConnection(String serverURI, String clientId, String userName, String
        password, SocketFactory socketFactory, MqttCallback mqttCallbackListener,
                      IMqttActionListener mqttMessageListener) throws MqttException {

    if (serverURI == null || mqttCallbackListener == null || mqttMessageListener == null) {
        throw new IllegalArgumentException("serverURI, mqttCallbackListener, mqttMessageListener can't be null!");
    }
    this.mqttAsyncClient = new MqttAsyncClient(serverURI, clientId, new MemoryPersistence());
    this.mqttAsyncClient.setManualAcks(true);
    this.connectionOptions = new MqttConnectOptions();
    this.initOptions(userName, password, socketFactory);
    this.mqttMessageListener = mqttMessageListener;
    this.mqttAsyncClient.setCallback(mqttCallbackListener);
}
 
Example #26
Source File: MqttSubscriberClient.java    From product-iots with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param serverAddress Mqtt broker address
 * @param clientId Client ID
 * @param topicName Topic Name
 * @throws MqttException Mqtt Exception
 */
public MqttSubscriberClient(String serverAddress, String clientId, String topicName, String accessToken) throws
        MqttException {
    mqttMessages = new ArrayList<>();
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(serverAddress, clientId, persistence);
    MqttConnectOptions connectOptions = new MqttConnectOptions();
    client.setCallback(this);
    connectOptions.setUserName(accessToken);
    connectOptions.setPassword("".toCharArray());
    connectOptions.setCleanSession(true);
    connectOptions.setKeepAliveInterval(300);
    client.connect(connectOptions);
    client.subscribe(topicName);
}
 
Example #27
Source File: MqttAcknowledgementTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private MqttClient createMqttClient(String clientId) throws MqttException {
   MqttClient client = new MqttClient("tcp://localhost:" + getPort(), clientId, new MemoryPersistence());
   client.setCallback(createCallback());
   client.setManualAcks(true);
   MqttConnectOptions options = new MqttConnectOptions();
   options.setCleanSession(false);
   client.connect(options);
   return client;
}
 
Example #28
Source File: CustomAction.java    From itracing2 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    final Matcher matcher = pattern.matcher(this.domain);
    if (matcher.matches()) {
        String login = matcher.group(2);
        String password = matcher.group(3);
        String host = matcher.group(4);
        String port = matcher.group(5);
        String topic = matcher.group(6);

        if (port == null) {
            port = "1883";
        }

        try {
            final MqttClient client = new MqttClient("tcp://" + host + ":" + port,
                    MqttClient.generateClientId(),
                    new MemoryPersistence()
            );
            final MqttConnectOptions options = new MqttConnectOptions();

            if (login != null && password != null) {
                options.setUserName(login);
                options.setPassword(password.toCharArray());
            }

            client.connect(options);
            if (client.isConnected()) {
                client.publish(topic, payload.getBytes(), 0, false);
                client.disconnect();

            }
        } catch (MqttException e) {
            Log.d(TAG, "exception", e);
        }
    }
}
 
Example #29
Source File: MessagingModule.java    From winthing with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    bind(MqttClientPersistence.class).to(MemoryPersistence.class).in(Singleton.class);

    bind(Registry.class).to(SimpleRegistry.class).in(Singleton.class);

    bind(Engine.class).in(Singleton.class);
    bind(MessagePublisher.class).to(Engine.class);

    expose(Registry.class);
    expose(MessagePublisher.class);
    expose(Engine.class);
}
 
Example #30
Source File: TesterAsync.java    From vertx-mqtt-broker with Apache License 2.0 5 votes vote down vote up
public TesterAsync(int numClients, String clientIDPrefix, String serverURL) throws MqttException {
    for(int i=1; i<=numClients; i++) {
        String clientID = clientIDPrefix+"_" + i;

        MqttAsyncClient client = new MqttAsyncClient(serverURL, clientID, new MemoryPersistence());
        MQTTClientHandler h = new MQTTClientHandler(clientID);
        client.setCallback(h);

        clients.add(client);
        clientHandlers.add(h);
    }
}