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

The following are top voted examples for showing how to use org.eclipse.paho.client.mqttv3.MqttConnectOptions. 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: jim   File: MqttClientFactory.java   View source code 8 votes vote down vote up
/**
 * get MqttClient by clientKey
 * @param clientKey
 * @return
 * @throws MqttException
 */
public static MqttClient getMqttClient(String serverURI, String clientId,StringRedisTemplate redisTemplate) 
                throws MqttException{
	 String clientKey=serverURI.concat(clientId);
     if(clientMap.get(clientKey)==null){
         lock.lock();
             if(clientMap.get(clientKey)==null){
            	 MqttClientPersistence persistence = new MemoryPersistence();
            	
                 MqttClient client = new MqttClient(serverURI, clientId, persistence);
                 MqttConnectOptions connOpts = new MqttConnectOptions();
                 
                 MqttCallback callback = new IMMqttCallBack(client,redisTemplate);
                 client.setCallback(callback);
                 
                 connOpts.setCleanSession(true);
                 client.connect(connOpts);
                 clientMap.put(clientKey, client);
             }
          lock.unlock();
     }
      return clientMap.get(clientKey);
}
 
Example 2
Project: iotplatform   File: MqttPlugin.java   View source code 7 votes vote down vote up
@Override
public void init(MqttPluginConfiguration configuration) {
  retryInterval = configuration.getRetryInterval();

  mqttClientOptions = new MqttConnectOptions();
  mqttClientOptions.setCleanSession(false);
  mqttClientOptions.setMaxInflight(configuration.getMaxInFlight());
  mqttClientOptions.setAutomaticReconnect(true);
  String clientId = configuration.getClientId();
  if (StringUtils.isEmpty(clientId)) {
    clientId = UUID.randomUUID().toString();
  }
  if (!StringUtils.isEmpty(configuration.getAccessToken())) {
    mqttClientOptions.setUserName(configuration.getAccessToken());
  }
  try {
    mqttClient = new MqttAsyncClient("tcp://" + configuration.getHost() + ":" + configuration.getPort(), clientId);
  } catch (Exception e) {
    log.error("Failed to create mqtt client", e);
    throw new RuntimeException(e);
  }
  // connect();
}
 
Example 3
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 4
Project: EMQ-Android-Toolkit   File: Connection.java   View source code 6 votes vote down vote up
public MqttConnectOptions getMqttConnectOptions() {
    MqttConnectOptions options = new MqttConnectOptions();
    options.setCleanSession(isCleanSession());
    options.setConnectionTimeout(getTimeout());
    options.setKeepAliveInterval(getKeepAlive());

    if (!getUsername().isEmpty()) {
        options.setUserName(getUsername());
    }

    if (!getPassword().isEmpty()) {
        options.setPassword(getPassword().toCharArray());
    }

    if (!getLwtTopic().isEmpty() && !getLwtPayload().isEmpty()) {
        options.setWill(getLwtTopic(), getLwtPayload().getBytes(), getLwtQos(), isLwtRetained());
    }

    return options;
}
 
Example 5
Project: SerialMqttBridge   File: MqttHandler.java   View source code 6 votes vote down vote up
/*********************************************************************************************************************************************************************
 *
 */
private void connectAndSubscribe() throws Exception {

  ConfigHandler configHandler = serialMqttBridge.getConfigHandler();

  mqttClient = new MqttClient(configHandler.getMqttBrokerUrl(), configHandler.getMqttClientId(), null);
  MqttConnectOptions connOpts = new MqttConnectOptions();
  connOpts.setCleanSession(true);
  connOpts.setAutomaticReconnect(true);

  // Authentication
  if (configHandler.getMqttBrokerUsername() != null && configHandler.getMqttBrokerPassword() != null) {
    connOpts.setUserName(configHandler.getMqttBrokerUsername());
    connOpts.setPassword(configHandler.getMqttBrokerPassword().toCharArray());
  }

  // MqttCallback
  mqttCallback = new MqttSubscriptionCallback(this);
  mqttClient.setCallback(mqttCallback);

  mqttClient.connect(connOpts);

  // Subscribe to defined inbound topic
  mqttClient.subscribe(configHandler.getMqttTopicSubscribe(), configHandler.getMqttQosSubscribe());
}
 
Example 6
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 7
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 8
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 9
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 10
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 11
Project: tetrad   File: TetradMQTT.java   View source code 6 votes vote down vote up
private void connect() {
    logger.debug(MessageFormat.format("Connecting to {0} as {1}", mqttConfig.getBroker(), mqttConfig.getClientid()));
    try {
        mqttSession = new MqttAsyncClient(mqttConfig.getBroker(),
                mqttConfig.getClientid(),
                new MemoryPersistence());
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);

        mqttSession.connect(connOpts, new TetradMQTTConnectionListener(this));
    } catch (MqttException e) {
        logger.error(MessageFormat.format("Error connecting to {0} as {1}. Message: {2}, ReasonCode: {3}",
                mqttConfig.getBroker(),
                mqttConfig.getClientid(),
                e.getMessage(),
                e.getReasonCode()
        ));
        e.printStackTrace();
    }

}
 
Example 12
Project: SerialMqttBridge   File: MqttHandler.java   View source code 6 votes vote down vote up
/*********************************************************************************************************************************************************************
 *
 */
private void connectAndSubscribe() throws Exception {

  ConfigHandler configHandler = serialMqttBridge.getConfigHandler();

  mqttClient = new MqttClient(configHandler.getMqttBrokerUrl(), configHandler.getMqttClientId(), null);
  MqttConnectOptions connOpts = new MqttConnectOptions();
  connOpts.setCleanSession(true);
  connOpts.setAutomaticReconnect(true);

  // Authentication
  if (configHandler.getMqttBrokerUsername() != null && configHandler.getMqttBrokerPassword() != null) {
    connOpts.setUserName(configHandler.getMqttBrokerUsername());
    connOpts.setPassword(configHandler.getMqttBrokerPassword().toCharArray());
  }

  // MqttCallback
  mqttCallback = new MqttSubscriptionCallback(this);
  mqttClient.setCallback(mqttCallback);

  mqttClient.connect(connOpts);

  // Subscribe to defined inbound topic
  mqttClient.subscribe(configHandler.getMqttTopicSubscribe(), configHandler.getMqttQosSubscribe());
}
 
Example 13
Project: aws-iot-device-sdk-java   File: AwsIotMqttConnection.java   View source code 6 votes vote down vote up
private MqttConnectOptions buildMqttConnectOptions(AbstractAwsIotClient client, SocketFactory socketFactory) {
    MqttConnectOptions options = new MqttConnectOptions();

    options.setSocketFactory(socketFactory);
    options.setCleanSession(true);
    options.setConnectionTimeout(client.getConnectionTimeout() / 1000);
    options.setKeepAliveInterval(client.getKeepAliveInterval() / 1000);

    Set<String> serverUris = getServerUris();
    if (serverUris != null && !serverUris.isEmpty()) {
        String[] uriArray = new String[serverUris.size()];
        serverUris.toArray(uriArray);
        options.setServerURIs(uriArray);
    }

    if (client.getWillMessage() != null) {
        AWSIotMessage message = client.getWillMessage();

        options.setWill(message.getTopic(), message.getPayload(), message.getQos().getValue(), false);
    }

    return options;
}
 
Example 14
Project: vertx-mqtt   File: MqttServerConnectionTest.java   View source code 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
Project: vertx-mqtt   File: MqttServerConnectionTest.java   View source code 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 16
Project: vertx-mqtt   File: MqttServerConnectionTest.java   View source code 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 17
Project: vertx-mqtt   File: MqttServerClientIdentifierTest.java   View source code 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 18
Project: vertx-mqtt   File: MqttServerClientIdentifierTest.java   View source code 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 19
Project: HelloMQTT   File: MQService.java   View source code 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 20
Project: diozero   File: ProtobufMqttProtocolHandler.java   View source code 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 21
Project: diozero   File: MqttTestClient.java   View source code 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 22
Project: IoT   File: MyMqttCloudClient.java   View source code 6 votes vote down vote up
public MyMqttCloudClient(String cloudBrokerAddress, String clientId) {
//		this._cloudTopic = cloudTopic;
		this._cloudBrokerAddress = cloudBrokerAddress;
		this._clientId = clientId;
		MemoryPersistence persistence = new MemoryPersistence();
		try {
			this._mqCloudClient = new MqttClient(this._cloudBrokerAddress,
					this._clientId, persistence);
			this._mqCloudClient.setCallback(this);
			MqttConnectOptions connOpts = new MqttConnectOptions();
//			connOpts.setCleanSession(true);
			connOpts.setConnectionTimeout(0);
			connOpts.setKeepAliveInterval(30);
			connOpts.setAutomaticReconnect(true);
			System.out.println("Connecting to cloud broker: " + this._cloudBrokerAddress);
			this._mqCloudClient.connect(connOpts);
			System.out.println("Connected");			
		} catch (MqttException me) {
			System.out.println("reason " + me.getReasonCode());
			System.out.println("msg " + me.getMessage());
			System.out.println("loc " + me.getLocalizedMessage());
			System.out.println("cause " + me.getCause());
			System.out.println("excep " + me);
			me.printStackTrace();
		}
	}
 
Example 23
Project: IoT   File: CopyOfMyMqttCloudClient.java   View source code 6 votes vote down vote up
public CopyOfMyMqttCloudClient(String cloudTopic, String cloudBrokerAddress, String clientId) {
		this._cloudTopic = cloudTopic;
		this._cloudBrokerAddress = cloudBrokerAddress;
		this._clientId = clientId;
		MemoryPersistence persistence = new MemoryPersistence();
		try {
			this._mqCloudClient = new MqttClient(this._cloudBrokerAddress,
					"sfdf", persistence);
			this._mqCloudClient.setCallback(this);
			MqttConnectOptions connOpts = new MqttConnectOptions();
//			connOpts.setCleanSession(true);
			connOpts.setKeepAliveInterval(30);
			System.out.println("Connecting to cloud broker: " + this._cloudBrokerAddress);
			this._mqCloudClient.connect(connOpts);
			System.out.println("Connected");			
		} catch (MqttException me) {
			System.out.println("reason " + me.getReasonCode());
			System.out.println("msg " + me.getMessage());
			System.out.println("loc " + me.getLocalizedMessage());
			System.out.println("cause " + me.getCause());
			System.out.println("excep " + me);
			me.printStackTrace();
		}
	}
 
Example 24
Project: android-app   File: MQTTClient.java   View source code 6 votes vote down vote up
/**
 *
 *
 */
private void connect() throws MqttException {
    connOpt = new MqttConnectOptions();

    connOpt.setCleanSession(true);
    connOpt.setKeepAliveInterval(3600);
    connOpt.setConnectionTimeout(3600);
    connOpt.setUserName(sharedPref.getString("pref_username", ""));
    connOpt.setPassword(sharedPref.getString("pref_password", "").toCharArray());

    String tmpDir = createTempDir().getPath(); //System.getProperty("java.io.tmpdir");
    Log.i(TAG, "Persistence will be done in " + tmpDir);

    MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);

    // Connect to Broker
    mClient = new MqttClient(sharedPref.getString("pref_url", "") + ":" + sharedPref.getString("pref_port", "1883"), android_id + "_client", dataStore);
    mClient.setCallback(this);
    mClient.connect(connOpt);
    Log.i(TAG, "Connected to " + sharedPref.getString("pref_url", ""));

}
 
Example 25
Project: Sparkplug   File: MainActivity.java   View source code 6 votes vote down vote up
private MqttConnectOptions optionsFromModel(ConnectionModel model){

        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(model.isCleanSession());
        connOpts.setConnectionTimeout(model.getTimeout());
        connOpts.setKeepAliveInterval(model.getKeepAlive());
        if(!model.getUsername().equals(ActivityConstants.empty)){
            connOpts.setUserName(model.getUsername());
        }

        if(!model.getPassword().equals(ActivityConstants.empty)){
            connOpts.setPassword(model.getPassword().toCharArray());
        }
        /*
        if(!model.getLwtTopic().equals(ActivityConstants.empty) && !model.getLwtMessage().equals(ActivityConstants.empty)){
            connOpts.setWill(model.getLwtTopic(), model.getLwtMessage().getBytes(), model.getLwtQos(), model.isLwtRetain());
        }*/
        //   if(tlsConnection){
        //       // TODO Add Keys to conOpts here
        //       //connOpts.setSocketFactory();
        //   }
        return connOpts;
    }
 
Example 26
Project: Sparkplug   File: MainActivity.java   View source code 6 votes vote down vote up
public void connect(Connection connection) {
    String[] actionArgs = new String[1];
    actionArgs[0] = connection.getId();
    final ActionListener callback = new ActionListener(this,
            ActionListener.Action.CONNECT, connection, actionArgs);
    connection.getClient().setCallback(new MqttCallbackHandler(this, connection.handle()));
    try {
        MqttConnectOptions mqttConnectOptions = connection.getConnectionOptions();
        SparkplugBPayloadBuilder deathPayload = new SparkplugBPayloadBuilder().setTimestamp(new Date());
        deathPayload = connection.addBdSeqNum(deathPayload);
        byte [] deathBytes = new SparkplugBPayloadEncoder().getBytes(deathPayload.createPayload());
        String lwtTopic = "spBv1.0/" + connection.getGroupId() + "/NDEATH/" + connection.getEdgeNodeId();
        Log.d(TAG, "1. Setting up LWT: " + lwtTopic);
        mqttConnectOptions.setWill(lwtTopic, deathBytes, 0, false);

        connection.getClient().connect(mqttConnectOptions, null, callback);
    }
    catch (Exception e) {
        Log.e(this.getClass().getCanonicalName(),
                "Exception occurred", e);
    }
}
 
Example 27
Project: Sparkplug   File: SparkplugListener.java   View source code 6 votes vote down vote up
public void run() {
	try {
		// Connect to the MQTT Server
		MqttConnectOptions options = new MqttConnectOptions();
		options.setAutomaticReconnect(true);
		options.setCleanSession(true);
		options.setConnectionTimeout(30);
		options.setKeepAliveInterval(30);
		options.setUserName(username);
		options.setPassword(password.toCharArray());
		client = new MqttClient(serverUrl, clientId);
		client.setTimeToWait(5000);						// short timeout on failure to connect
		client.connect(options);
		client.setCallback(this);
		
		// Just listen to all DDATA messages on spAv1.0 topics and wait for inbound messages
		client.subscribe("spBv1.0/#", 0);
	} catch(Exception e) {
		e.printStackTrace();
	}
}
 
Example 28
Project: product-ei   File: MQTTTestClient.java   View source code 6 votes vote down vote up
/**
 * Generate a MQTT client with given parameters
 *
 * @param brokerURL url of MQTT provider
 * @param userName username to connect to MQTT provider
 * @param password password to connect to MQTT provider
 * @param clientId unique id for the publisher/subscriber client
 * @throws MqttException in case of issue of connect/publish/consume
 */
public MQTTTestClient(String brokerURL, String userName, char[] password, String clientId) throws MqttException {
    this.brokerURL = brokerURL;
    //Store messages until server fetches them
    MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(JAVA_TMP_DIR + "/" + clientId);
    mqttClient = new MqttClient(brokerURL, clientId, dataStore);
    SimpleMQTTCallback callback = new SimpleMQTTCallback();
    mqttClient.setCallback(callback);
    MqttConnectOptions connectOptions = new MqttConnectOptions();
    connectOptions.setUserName(userName);
    connectOptions.setPassword(password);
    connectOptions.setCleanSession(true);
    mqttClient.connect(connectOptions);

    log.info("MQTTTestClient successfully connected to broker at " + this.brokerURL);
}
 
Example 29
Project: ActiveMQ-MQTT-Android   File: MainActivity.java   View source code 6 votes vote down vote up
private void startConnect(String clientID, String serverIP, String port) {
    //服务器地址
    String  uri ="tcp://";
    uri=uri+serverIP+":"+port;
    Log.d("MainActivity",uri+"  "+clientID);
    /**
     * 连接的选项
     */
    MqttConnectOptions conOpt = new MqttConnectOptions();
    /**设计连接超时时间*/
    conOpt.setConnectionTimeout(3000);
    /**设计心跳间隔时间300秒*/
    conOpt.setKeepAliveInterval(300);
    /**
     * 创建连接对象
     */
     client = new MqttAndroidClient(this,uri, clientID);
    /**
     * 连接后设计一个回调
     */
    client.setCallback(new MqttCallbackHandler(this, clientID));
    /**
     * 开始连接服务器,参数:ConnectionOptions,  IMqttActionListener
     */
    try {
        client.connect(conOpt, null, new ConnectCallBackHandler(this));
    } catch (MqttException e) {
        e.printStackTrace();
    }

}
 
Example 30
Project: AppInventorRaspberryPiCompanion   File: InputPinHandler.java   View source code 6 votes vote down vote up
public InputPinHandler() {
  MqttConnectOptions connOpts = new MqttConnectOptions();
  connOpts.setCleanSession(true);
  try {
    mClient = new MqttClient(PropertyUtil.getMqttAddress(), MqttClient.generateClientId(), new MemoryPersistence());
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Connecting to broker " + PropertyUtil.getMqttAddress() + "...");
    }
    mClient.connect(connOpts);
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Connected to broker " + PropertyUtil.getMqttAddress() + ".");
    }
  } catch (MqttException e) {
    LOGGER.error(e.getMessage(), e);
  }
}
 
Example 31
Project: mqtt-listener-example   File: Ingestion.java   View source code 6 votes vote down vote up
public void init() throws MqttException {
    try {
        String url = mqttProperties.getHostname() + ":" + mqttProperties.getPort();
        LOGGER.info("Opening MQTT connection: '{}'", url);
        LOGGER.info("properties: {}", mqttProperties);
        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setUserName(mqttProperties.getUsername());
        connectOptions.setPassword(mqttProperties.getPassword().toCharArray());
        connectOptions.setCleanSession(false);
        client = new MqttClient(url, mqttProperties.getClientName(), new MemoryPersistence());
        client.setCallback(onMessageArrived);
        client.connect(connectOptions);
        client.subscribe(mqttProperties.getTopic());
    } catch (MqttException e) {
        LOGGER.error(e.getMessage(), e);
        throw e;
    }
}
 
Example 32
Project: iot-edge-greengrass   File: MqttGatewayService.java   View source code 5 votes vote down vote up
@PostConstruct
public void init() throws Exception {
    scheduler = Executors.newSingleThreadScheduledExecutor();

    tbClientOptions = new MqttConnectOptions();
    tbClientOptions.setCleanSession(false);
    tbClientOptions.setMaxInflight(connection.getMaxInFlight());
    tbClientOptions.setAutomaticReconnect(true);

    MqttGatewaySecurityConfiguration security = connection.getSecurity();
    security.setupSecurityOptions(tbClientOptions);

    tbClient = new MqttAsyncClient((security.isSsl() ? "ssl" : "tcp") + "://" + connection.getHost() + ":" + connection.getPort(),
            security.getClientId(), persistence.getPersistence());
    tbClient.setCallback(this);

    if (persistence.getBufferSize() > 0) {
        DisconnectedBufferOptions options = new DisconnectedBufferOptions();
        options.setBufferSize(persistence.getBufferSize());
        options.setBufferEnabled(true);
        options.setPersistBuffer(true);
        tbClient.setBufferOpts(options);
    }
    connect();

    scheduler.scheduleAtFixedRate(this::reportStats, 0, reporting.getInterval(), TimeUnit.MILLISECONDS);
}
 
Example 33
Project: iot-edge-greengrass   File: BasicCredentials.java   View source code 5 votes vote down vote up
@Override
public void configure(MqttConnectOptions clientOptions) {
  clientOptions.setUserName(username);
  if (!StringUtils.isEmpty(password)) {
    clientOptions.setPassword(password.toCharArray());
  }
}
 
Example 34
Project: export-distro   File: IotCoreMQTTSender.java   View source code 5 votes vote down vote up
private void connectClient() throws Exception {
	try {
	    String mqttServerAddress = String.format("ssl://%s:%s", mqttBridgeHostname, mqttBridgePort);

		MqttConnectOptions connectOptions = new MqttConnectOptions();
	    connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
	    connectOptions.setUserName(username);
	    password = createJwt(projectId, privateKeyFile, algorithm);
	    connectOptions.setPassword(password.toCharArray());

		connectOptions.setCleanSession(true);
		connectOptions.setKeepAliveInterval(keepAlive);

	    client = new MqttClient(mqttServerAddress, clientId, new MemoryPersistence());
		client.setCallback(this);

		logger.debug("Connecting to broker:  " + mqttServerAddress);
		client.connect(connectOptions);
		logger.debug("Connected");
		
	} catch (Exception e) {
		logger.error("Failed to connect to MQTT client ( " + mqttBridgeHostname + ":" + mqttBridgePort + "/" + clientId + ") for outbound messages");
		throw e;
	}
}
 
Example 35
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 36
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 37
Project: thingsboard-gateway   File: BasicCredentials.java   View source code 5 votes vote down vote up
@Override
public void configure(MqttConnectOptions clientOptions) {
    clientOptions.setUserName(username);
    if (!StringUtils.isEmpty(password)) {
        clientOptions.setPassword(password.toCharArray());
    }
}
 
Example 38
Project: mqttserver   File: PubWebMessage.java   View source code 5 votes vote down vote up
public static void pubMsg(String tcpUrl, String clientId, String topicName,
			String message) throws MqttException, UnsupportedEncodingException {
		MqttClient client = new MqttClient(tcpUrl, clientId);
		MqttConnectOptions mqcConf = new MqttConnectOptions();
		mqcConf.setConnectionTimeout(300);
		mqcConf.setKeepAliveInterval(1200);
		client.connect(mqcConf);

		MqttTopic topic = client.getTopic(topicName);
		topic.publish(message.getBytes("utf8"), 1, false);

//		client.close();
	}
 
Example 39
Project: mqttserver   File: SubscribeMessage.java   View source code 5 votes vote down vote up
public void doDemo(String tcpUrl, String clientId, String topicName) {
	try {
	  MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
	  mqttConnectOptions.setMqttVersion(4);
		client = new MqttClient(tcpUrl, clientId);
		client.connect(mqttConnectOptions);
		client.setCallback(this);
		client.subscribe(topicName);
	} catch (MqttException e) {
		e.printStackTrace();
	}
}
 
Example 40
Project: mqttserver   File: PubMessage.java   View source code 5 votes vote down vote up
public static void pubMsg(String tcpUrl, String clientId, String topicName)
    throws MqttException, UnsupportedEncodingException {
  MqttClient client = new MqttClient(tcpUrl, clientId);
  MqttConnectOptions mqcConf = new MqttConnectOptions();
  mqcConf.setConnectionTimeout(300);
  mqcConf.setKeepAliveInterval(1200);
  client.connect(mqcConf);

  MqttTopic topic = client.getTopic(topicName);
  for (int i = 0; i < 10; i++) {
    String message = "{\"id\":" + (i+1) + ",\"temp\":12}";
    topic.publish(message.getBytes("utf8"), 1, false);
  }
  client.disconnect();
}