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: echo   File: MQTTPublisher.java   Source Code and License 10 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 2
Project: jim   File: MqttClientFactory.java   Source Code and License 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 3
Project: iotplatform   File: MqttPlugin.java   Source Code and License 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 4
Project: mqtt-listener-example   File: Ingestion.java   Source Code and License 7 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 5
Project: iot-edge-greengrass   File: MqttBrokerMonitor.java   Source Code and License 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 6
Project: EMQ-Android-Toolkit   File: Connection.java   Source Code and License 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 7
Project: SerialMqttBridge   File: MqttHandler.java   Source Code and License 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 8
Project: Taxi-Datalogger   File: MQTTPublisher.java   Source Code and License 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 9
Project: device-mqtt   File: OutgoingSender.java   Source Code and License 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 10
Project: device-mqtt   File: CommandResponseListener.java   Source Code and License 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 11
Project: device-mqtt   File: IncomingListener.java   Source Code and License 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 12
Project: sensorhub-cloud-iot   File: MQTTPublisher.java   Source Code and License 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 13
Project: tetrad   File: TetradMQTT.java   Source Code and License 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 14
Project: SerialMqttBridge   File: MqttHandler.java   Source Code and License 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 15
Project: aws-iot-device-sdk-java   File: AwsIotMqttConnection.java   Source Code and License 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 16
Project: vertx-mqtt   File: MqttServerConnectionTest.java   Source Code and License 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 17
Project: vertx-mqtt   File: MqttServerConnectionTest.java   Source Code and License 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
Project: vertx-mqtt   File: MqttServerConnectionTest.java   Source Code and License 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 19
Project: vertx-mqtt   File: MqttServerClientIdentifierTest.java   Source Code and License 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 20
Project: vertx-mqtt   File: MqttServerClientIdentifierTest.java   Source Code and License 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 21
Project: HelloMQTT   File: MQService.java   Source Code and License 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 22
Project: diozero   File: ProtobufMqttProtocolHandler.java   Source Code and 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 23
Project: diozero   File: MqttTestClient.java   Source Code and 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 24
Project: IoT   File: MyMqttCloudClient.java   Source Code and License 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 25
Project: IoT   File: CopyOfMyMqttCloudClient.java   Source Code and License 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 26
Project: android-app   File: MQTTClient.java   Source Code and License 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 27
Project: Sparkplug   File: MainActivity.java   Source Code and License 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 28
Project: Sparkplug   File: MainActivity.java   Source Code and License 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 29
Project: Sparkplug   File: SparkplugListener.java   Source Code and License 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 30
Project: product-ei   File: MQTTTestClient.java   Source Code and License 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 31
Project: ActiveMQ-MQTT-Android   File: MainActivity.java   Source Code and License 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 32
Project: AppInventorRaspberryPiCompanion   File: InputPinHandler.java   Source Code and License 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 33
Project: iot-edge-greengrass   File: MqttGatewayService.java   Source Code and License 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 34
Project: iot-edge-greengrass   File: BasicCredentials.java   Source Code and License 5 votes vote down vote up
@Override
public void configure(MqttConnectOptions clientOptions) {
  clientOptions.setUserName(username);
  if (!StringUtils.isEmpty(password)) {
    clientOptions.setPassword(password.toCharArray());
  }
}
 
Example 35
Project: export-distro   File: IotCoreMQTTSender.java   Source Code and License 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 36
Project: echo   File: NifiDeployer.java   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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();
}
 
Example 41
Project: iotgateway   File: MqttGatewayService.java   Source Code and License 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 42
Project: iotgateway   File: MqttBrokerMonitor.java   Source Code and License 5 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);
    SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
    sslContext.init(null, null, null);
    clientOptions.setSocketFactory(sslContext.getSocketFactory());

    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 | NoSuchAlgorithmException | KeyManagementException e) {
    log.error("[{}:{}] MQTT broker connection failed!", configuration.getHost(), configuration.getPort(), e);
    throw new RuntimeException("MQTT broker connection failed!", e);
  }
}
 
Example 43
Project: iotgateway   File: BasicCredentials.java   Source Code and License 5 votes vote down vote up
@Override
public void configure(MqttConnectOptions clientOptions) {
  clientOptions.setUserName(username);
  if (!StringUtils.isEmpty(password)) {
    clientOptions.setPassword(password.toCharArray());
  }
}
 
Example 44
Project: Sense-Hub-Android-Things   File: MqttIoTPublisher.java   Source Code and License 5 votes vote down vote up
private void initializeMqttClient()
    throws MqttException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    mqttClient = new MqttClient(mMqttOptions.getBrokerUrl(),
            mMqttOptions.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(CloudIotCoreOptions.UNUSED_ACCOUNT_NAME);
    options.setAutomaticReconnect(true);

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

    mqttClient.setCallback(this);
    mqttClient.connect(options);

    if(mqttClient.isConnected()) {
        try{
            mSubTopic = "/devices/sense_hub_2.0_android_things/config";// + NetworkUtils.getMACAddress(mContext);
            Log.i(TAG, "initializeMqttClient subscribe topic=" + mSubTopic);
            mqttClient.subscribe(mSubTopic, 1);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    mReady.set(true);
}
 
Example 45
Project: Sense-Hub-Android-Things   File: MqttPublisher.java   Source Code and License 5 votes vote down vote up
private void initializeMqttClient()
        throws MqttException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    Log.d(TAG, "initializeMqttClient broker=" + mMqttOptions.getBrokerUrl() +
            " clientID=" + mMqttOptions.getClientId() +
            " username=" + mMqttOptions.getUsername() +
            " password=" + mMqttOptions.getPassword());
    mqttClient = new MqttClient(mMqttOptions.getBrokerUrl(),
            mMqttOptions.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(mMqttOptions.getUsername());
    options.setPassword(mMqttOptions.getPassword().toCharArray());

    options.setAutomaticReconnect(true);

    mqttClient.setCallback(this);
    mqttClient.connect(options);

    if(mqttClient.isConnected()) {
        try{
            Log.i(TAG, "initializeMqttClient subscribe topic=" + mMqttOptions.getSubscribeTopicName());
            mqttClient.subscribe(mMqttOptions.getSubscribeTopicName(), 1);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    else{
        Log.e(TAG, "Can't connect to " + mMqttOptions.getBrokerUrl());
    }
    mReady.set(true);
}
 
Example 46
Project: kalinka   File: MqttClient.java   Source Code and License 5 votes vote down vote up
private boolean doConnectBroker() {
	try {
		LOG.debug("{} > connect..", url);

		final MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
		mqttConnectOptions.setUserName("admin");
		mqttConnectOptions.setPassword("admin".toCharArray());
		mqttConnectOptions.setCleanSession(true);
		mqttConnectOptions.setWill(pubTopic2Mqtt, "Bye, bye Baby!".getBytes(), 0, false);

		// client
		final String tmpDir = System.getProperty("java.io.tmpdir");
		final MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
		LOG.info("creating MqttAsyncClient for {} and {}", url, clientId);
		mqttAsyncClient = new MqttAsyncClient(url, clientId, dataStore);

		// callback
		mqttAsyncClient.setCallback(this);

		// connect
		mqttAsyncClient.connect(mqttConnectOptions).waitForCompletion();

		// subscriptions
		for (final String subTopic : subTopics) {
			LOG.info("client {} subscribing to {}", clientId, subTopic);
			mqttAsyncClient.subscribe(subTopic, 0);
		}

		LOG.info("{} > mqtt connection established for {}.", url, clientId);
		return true;
	} catch (final Throwable throwable) {
		LOG.error("{} > connection failed. ({})", url, throwable.getMessage());
		close();
		return false;
	}
}
 
Example 47
Project: iot-device-samples   File: SampleRasPiDMAgentWithCustomMqttAsyncClient.java   Source Code and License 5 votes vote down vote up
private void createMqttAsyncClient(Properties deviceProps) throws MqttException, 
NoSuchAlgorithmException, 
KeyManagementException {
	
	StringBuilder serverURI = new StringBuilder();
	StringBuilder clientId = new StringBuilder();
	
	serverURI.append("ssl://")
			 .append(trimedValue(deviceProps.getProperty("Organization-ID")))
			 .append(".messaging.internetofthings.ibmcloud.com:8883");
	
	clientId.append("d:")
	         .append(trimedValue(deviceProps.getProperty("Organization-ID")))
	         .append(":")
	         .append(trimedValue(deviceProps.getProperty("Device-Type")))
	         .append(":")
	         .append(trimedValue(deviceProps.getProperty("Device-ID")));
	
	MqttConnectOptions conOpt = new MqttConnectOptions();
	conOpt.setCleanSession(false);
	conOpt.setUserName("use-token-auth");
	conOpt.setPassword(trimedValue(deviceProps.getProperty("Authentication-Token")).toCharArray());
	SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
	sslContext.init(null, null, null);
	conOpt.setSocketFactory(sslContext.getSocketFactory());
	
	
	mqttAsyncClient = new MqttAsyncClient(serverURI.toString(), clientId.toString());
	System.out.println("Trying to connect to URI -> "+serverURI.toString() +" ClientID: "+clientId.toString());
	System.out.println("Username : "+conOpt.getUserName());
	System.out.println("password : "+new String(conOpt.getPassword()));
	mqttAsyncClient.connect(conOpt);
}
 
Example 48
Project: iot-device-samples   File: SampleRasPiDMAgentWithCustomMqttClient.java   Source Code and License 5 votes vote down vote up
private void createMqttClient(Properties deviceProps) throws MqttException, 
NoSuchAlgorithmException, 
KeyManagementException {
	
	StringBuilder serverURI = new StringBuilder();
	StringBuilder clientId = new StringBuilder();
	
	serverURI.append("ssl://")
			 .append(trimedValue(deviceProps.getProperty("Organization-ID")))
			 .append(".messaging.internetofthings.ibmcloud.com:8883");
	
	clientId.append("d:")
	         .append(trimedValue(deviceProps.getProperty("Organization-ID")))
	         .append(":")
	         .append(trimedValue(deviceProps.getProperty("Device-Type")))
	         .append(":")
	         .append(trimedValue(deviceProps.getProperty("Device-ID")));
	
	MqttConnectOptions conOpt = new MqttConnectOptions();
	conOpt.setCleanSession(false);
	conOpt.setUserName("use-token-auth");
	conOpt.setPassword(trimedValue(deviceProps.getProperty("Authentication-Token")).toCharArray());
	SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
	sslContext.init(null, null, null);
	conOpt.setSocketFactory(sslContext.getSocketFactory());
	
	
	mqttClient = new MqttClient(serverURI.toString(), clientId.toString());
	System.out.println("Trying to connect to URI -> "+serverURI.toString() +" ClientID: "+clientId.toString());
	System.out.println("Username : "+conOpt.getUserName());
	System.out.println("password : "+new String(conOpt.getPassword()));
	mqttClient.connect(conOpt);
}
 
Example 49
Project: modbus-mqtt   File: MqttConnector.java   Source Code and License 5 votes vote down vote up
@Override
public void run() {
    try {
        mqtt = new MqttClient(broker, service.getName(), new MemoryPersistence());
        MqttConnectOptions opts = new MqttConnectOptions();
        opts.setCleanSession(true);
        mqtt.connect(opts);
        mqtt.setCallback(this);
    } catch (MqttException ex) {
        ModbusMqttService.error(ex.getMessage(), ex);
    }

}
 
Example 50
Project: artikcloud-java   File: MqttSession.java   Source Code and License 5 votes vote down vote up
public void connect() throws ArtikCloudMqttException {
        try {
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            connOpts.setUserName(deviceId);
            connOpts.setPassword(deviceToken.toCharArray());
//            System.out.println("****** Thread: " + Thread.currentThread().getName()+ "; MqttSession connecting to : "+ brokerUri);
            
            mqttClient.connect(connOpts, String.valueOf(OperationMode.CONNECT), operationListener);
        } catch (Exception e) {
            throw new ArtikCloudMqttException(e);
        }
        
    }
 
Example 51
Project: rxmqtt   File: PahoObservableMqttClient.java   Source Code and License 5 votes vote down vote up
public Builder(final IMqttAsyncClient client) {
    this.client = client;
    this.connectOptions = new MqttConnectOptions();
    this.closeFactory = new CloseFactory(client);
    this.connectFactory = new ConnectFactory(this.client, this.connectOptions);
    this.disconnectFactory = new DisconnectFactory(client);
    this.publishFactory = new PublishFactory(client);
    this.subscribeFactory = new SubscribeFactory(client);
    this.unsubscribeFactory = new UnsubscribeFactory(client);
    this.backpressureStrategy = BackpressureStrategy.BUFFER;
}
 
Example 52
Project: rxmqtt   File: ConnectFactoryTest.java   Source Code and License 5 votes vote down vote up
@Test
public void whenCreateIsCalledAndAnErrorOccursThenObserverOnErrorIsCalled() throws Throwable {
    expectedException.expectCause(isA(MqttException.class));
    final MqttConnectOptions options = Mockito.mock(MqttConnectOptions.class);
    final IMqttAsyncClient client = Mockito.mock(IMqttAsyncClient.class);
    Mockito.when(client.connect(Mockito.same(options), Mockito.isNull(),
            Mockito.any(ConnectFactory.ConnectActionListener.class)))
            .thenThrow(new MqttException(MqttException.REASON_CODE_CLIENT_CONNECTED));
    final ConnectFactory factory = new ConnectFactory(client, options);
    final Completable obs = factory.create();
    obs.blockingAwait();
}
 
Example 53
Project: aws-iot-device-sdk-java   File: AwsIotMqttConnection.java   Source Code and License 5 votes vote down vote up
public void openConnection(AwsIotMessageCallback callback) throws AWSIotException {
    try {
        AwsIotMqttConnectionListener connectionListener = new AwsIotMqttConnectionListener(client, true, callback);
        MqttConnectOptions options = buildMqttConnectOptions(client, socketFactory);
        mqttClient.connect(options, null, connectionListener);
    } catch (MqttException e) {
        throw new AWSIotException(e);
    }
}
 
Example 54
Project: circular   File: MQTTconect.java   Source Code and License 5 votes vote down vote up
public void doConnect(IMqttActionListener listener) {

        try {
            //realiza a conexão com o broker
            MqttConnectOptions options = new MqttConnectOptions();
            options.setConnectionTimeout(5);
            IMqttToken token = mqttAndroidClient.connect();
            token.setActionCallback(listener);

        } catch (MqttException e) {

            e.printStackTrace();
        }

    }
 
Example 55
Project: vertx-mqtt   File: MqttServerConnectionTest.java   Source Code and License 5 votes vote down vote up
@Override
protected void endpointHandler(MqttEndpoint endpoint) {

  MqttConnectReturnCode returnCode = this.expectedReturnCode;

  switch (this.expectedReturnCode) {

    case CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD:

      returnCode =
        (endpoint.auth().userName().equals(MQTT_USERNAME) &&
          endpoint.auth().password().equals(MQTT_PASSWORD)) ?
          MqttConnectReturnCode.CONNECTION_ACCEPTED :
          MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD;
      break;

    case CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION:

      returnCode = endpoint.protocolVersion() == MqttConnectOptions.MQTT_VERSION_3_1_1 ?
        MqttConnectReturnCode.CONNECTION_ACCEPTED :
        MqttConnectReturnCode.CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION;
      break;
  }

  log.info("return code = " + returnCode);

  if (returnCode == MqttConnectReturnCode.CONNECTION_ACCEPTED) {
    log.info("client id = " + endpoint.clientIdentifier());
    endpoint.accept(false);
  } else {
    endpoint.reject(returnCode);
  }

  this.endpoint = endpoint;
}
 
Example 56
Project: diozero   File: MqttListener.java   Source Code and 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 57
Project: diozero   File: MqttTestApp.java   Source Code and License 5 votes vote down vote up
public MqttTestApp() throws UnknownHostException, MqttException {
	mqttClient = new MqttClient(mqttUrl, CLIENT_ID_PREFIX + InetAddress.getLocalHost().getHostName(),
			new MemoryPersistence());
	mqttClient.setCallback(this);
	MqttConnectOptions con_opts = new MqttConnectOptions();
	con_opts.setAutomaticReconnect(true);
	con_opts.setCleanSession(true);
	Logger.debug("Connecting to {}...", mqttUrl);
	mqttClient.connect(con_opts);
	Logger.debug("Connected to {}", mqttUrl);

	mqttClient.subscribe("outTopic");
	mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC);
}
 
Example 58
Project: diozero   File: MqttJsonServer.java   Source Code and License 5 votes vote down vote up
public MqttJsonServer(String mqttUrl) throws UnknownHostException, MqttException {
	mqttClient = new MqttClient(mqttUrl, CLIENT_ID_PREFIX + InetAddress.getLocalHost().getHostName(),
			new MemoryPersistence());
	mqttClient.setCallback(this);
	MqttConnectOptions con_opts = new MqttConnectOptions();
	con_opts.setAutomaticReconnect(true);
	con_opts.setCleanSession(true);
	Logger.debug("Connecting to {}...", mqttUrl);
	mqttClient.connect(con_opts);
	Logger.debug("Connected to {}", mqttUrl);
}
 
Example 59
Project: diozero   File: MqttProtobufServer.java   Source Code and License 5 votes vote down vote up
public MqttProtobufServer(String mqttUrl) throws UnknownHostException, MqttException {
	mqttClient = new MqttClient(mqttUrl, CLIENT_ID_PREFIX + InetAddress.getLocalHost().getHostName(),
			new MemoryPersistence());
	mqttClient.setCallback(this);
	MqttConnectOptions con_opts = new MqttConnectOptions();
	con_opts.setAutomaticReconnect(true);
	con_opts.setCleanSession(true);
	Logger.debug("Connecting to {}...", mqttUrl);
	mqttClient.connect(con_opts);
	Logger.debug("Connected to {}", mqttUrl);
}
 
Example 60
Project: moonlight-mqtt   File: Client.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {

        String topic = "MQTT Examples";
        String content = "Message from MqttPublishSample";
        int qos = 0;
        String broker = "tcp://localhost:8080";
        String clientId = "JavaSample";
        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: " + broker);
            sampleClient.connect(connOpts);
            System.out.println("Connected");
            System.out.println("Publishing message: " + 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 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();
        }
    }