Java Code Examples for org.eclipse.paho.client.mqttv3.MqttClient#generateClientId()

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttClient#generateClientId() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProtobufMqttProtocolHandler.java    From diozero with MIT License 6 votes vote down vote up
public ProtobufMqttProtocolHandler(NativeDeviceFactoryInterface deviceFactory) {
	super(deviceFactory);

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

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

		// Subscribe
		Logger.debug("Subscribing to response and notification topics...");
		mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC);
		mqttClient.subscribe(MqttProviderConstants.GPIO_NOTIFICATION_TOPIC);
		Logger.debug("Subscribed");
	} catch (MqttException e) {
		throw new RuntimeIOException(e);
	}
}
 
Example 2
Source File: MqttTestClient.java    From diozero with MIT License 6 votes vote down vote up
public MqttTestClient(String mqttUrl) throws MqttException {
	mqttClient = new MqttClient(mqttUrl, MqttClient.generateClientId(), new MemoryPersistence());
	mqttClient.setCallback(this);
	MqttConnectOptions con_opts = new MqttConnectOptions();
	con_opts.setAutomaticReconnect(true);
	con_opts.setCleanSession(true);
	mqttClient.connect(con_opts);
	Logger.debug("Connected to {}", mqttUrl);

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

	// Subscribe
	Logger.debug("Subscribing to {}...", MqttProviderConstants.RESPONSE_TOPIC);
	mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC);
	Logger.debug("Subscribed");
}
 
Example 3
Source File: MqttBrokerConnection.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Create a new MQTT client connection to a server with the given protocol, host and port.
 *
 * @param protocol The transport protocol
 * @param host A host name or address
 * @param port A port or null to select the default port for a secure or insecure connection
 * @param secure A secure connection
 * @param clientId Client id. Each client on a MQTT server has a unique client id. Sometimes client ids are
 *            used for access restriction implementations.
 *            If none is specified, a default is generated. The client id cannot be longer than 65535
 *            characters.
 * @throws IllegalArgumentException If the client id or port is not valid.
 */
public MqttBrokerConnection(Protocol protocol, String host, @Nullable Integer port, boolean secure,
        @Nullable String clientId) {
    this.protocol = protocol;
    this.host = host;
    this.secure = secure;
    String newClientID = clientId;
    if (newClientID == null) {
        newClientID = MqttClient.generateClientId();
    } else if (newClientID.length() > 65535) {
        throw new IllegalArgumentException("Client ID cannot be longer than 65535 characters");
    }
    if (port != null && (port <= 0 || port > 65535)) {
        throw new IllegalArgumentException("Port is not within a valid range");
    }
    this.port = port != null ? port : (secure ? 8883 : 1883);
    this.clientId = newClientID;
    setReconnectStrategy(new PeriodicReconnectStrategy());
    connectionCallback = new ConnectionCallback(this);
}
 
Example 4
Source File: WildcardSubscriber.java    From paho-wildcard-subscriber with Apache License 2.0 6 votes vote down vote up
public void start() {
    log.info("Starting Wilcard subscriber");
    try {
        final String clientId = MqttClient.generateClientId();
        final MqttClient mqttClient = new MqttClient(BROKER_URL, clientId, new MemoryPersistence());

        mqttClient.setCallback(new SubscribeCallback(mqttClient));

        log.info("Connecting to {} with clientID {}", BROKER_URL, clientId);
        mqttClient.connect();

        //We subscribe to wildcard
        log.info("Subscribing to {}", TOPIC_SUBSCRIPTION);
        mqttClient.subscribe(TOPIC_SUBSCRIPTION, QUALITY_OF_SERVICE_LEVEL);

    } catch (MqttException e) {
        log.error("An unexpected error occured. Exiting", e);
        System.exit(1);
    }
}
 
Example 5
Source File: MqttListener.java    From diozero with MIT License 5 votes vote down vote up
public MqttListener() {
	try {
		mqttClient = new MqttClient(mqttServer, MqttClient.generateClientId(), new MemoryPersistence());
		mqttClient.setCallback(this);
		MqttConnectOptions con_opts = new MqttConnectOptions();
		con_opts.setCleanSession(true);
		mqttClient.connect(con_opts);
		System.out.println("Connected to '" + mqttServer + "'");
	} catch (MqttException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 6
Source File: MqttConnector.java    From quarks with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new connector.
 * 
 * @param config connector configuration.
 */
public MqttConnector(Supplier<MqttConfig> config) {
    this.configFn = config;
    
    String cid = configFn.get().getClientId();
    if (cid == null)
        cid = MqttClient.generateClientId();
    clientId = cid;
}
 
Example 7
Source File: CustomAction.java    From itracing2 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    final Matcher matcher = pattern.matcher(this.domain);
    if (matcher.matches()) {
        String login = matcher.group(2);
        String password = matcher.group(3);
        String host = matcher.group(4);
        String port = matcher.group(5);
        String topic = matcher.group(6);

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

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

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

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

            }
        } catch (MqttException e) {
            Log.d(TAG, "exception", e);
        }
    }
}
 
Example 8
Source File: MQTTExporterVS.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean initialize() {
	
	TreeMap<String, String> params = getVirtualSensorConfiguration().getMainClassInitialParams();

       serverURI = params.get("uri");
       if (serverURI == null) {
           logger.error("Parameter uri not provided in Virtual Sensor file.");
           return false;
       }
       clientID = params.get("client_id");
       if (clientID == null) {
           logger.warn("Parameter client_id not provided in Virtual Sensor file, using random one.");
           clientID = MqttClient.generateClientId();
       }
       topic = params.get("topic");
       if (topic == null) {
           logger.warn("Parameter topic not provided in Virtual Sensor file, using virtual sensor name.");
           topic = getVirtualSensorConfiguration().getName();
       }
	
	try{
	    client = new MqttClient(serverURI, clientID);
	    options.setAutomaticReconnect(true);
	    client.connect(options);
	}catch (Exception e){
		logger.error("Unable to connect to MQTT server.", e);
		return false;
	}
	return true;
}
 
Example 9
Source File: Publisher.java    From mqtt-sample-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws MqttException {

    String messageString = "Hello World from Java!";

    if (args.length == 2 ) {
      messageString = args[1];
    }


    System.out.println("== START PUBLISHER ==");


    MqttClient client = new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
    client.connect();
    MqttMessage message = new MqttMessage();
    message.setPayload(messageString.getBytes());
    client.publish("iot_data", message);

    System.out.println("\tMessage '"+ messageString +"' to 'iot_data'");

    client.disconnect();

    System.out.println("== END PUBLISHER ==");

  }
 
Example 10
Source File: Subscriber.java    From mqtt-sample-java with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) throws MqttException {

    System.out.println("== START SUBSCRIBER ==");

    MqttClient client=new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
    client.setCallback( new SimpleMqttCallBack() );
    client.connect();

    client.subscribe("iot_data");

  }