@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); mapView.addLayer( new ArcGISTiledMapServiceLayer( "http://cache1.arcgisonline.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer")); layer = new GraphicsLayer(); mapView.addLayer(layer); mapView.getLocationDisplayManager().start(); mapView.getLocationDisplayManager().setLocationListener(this); try { client = new MqttAndroidClient( this, "tcp://broker.mqttdashboard.com:1883", "Likaci/MqttMap/" + id); client.setCallback(this); MqttConnectOptions options = new MqttConnectOptions(); options.setKeepAliveInterval(10); options.setConnectionTimeout(1000); options.setCleanSession(false); client.connect(options, null, this); } catch (Exception e) { e.printStackTrace(); } }
private void doConnect() { L.info( "Connecting to MQTT broker " + mqttc.getServerURI() + " with CLIENTID=" + mqttc.getClientId() + " and TOPIC PREFIX=" + topicPrefix); MqttConnectOptions copts = new MqttConnectOptions(); copts.setWill(topicPrefix + "connected", "0".getBytes(), 1, true); copts.setCleanSession(true); copts.setUserName("emonpi"); copts.setPassword("emonpimqtt2016".toCharArray()); try { mqttc.connect(copts); sendConnectionState(); L.info("Successfully connected to broker, subscribing to " + topicPrefix + "(set|get)/#"); try { mqttc.subscribe(topicPrefix + "set/#", 1); mqttc.subscribe(topicPrefix + "get/#", 1); shouldBeConnected = true; } catch (MqttException mqe) { L.log(Level.WARNING, "Error subscribing to topic hierarchy, check your configuration", mqe); throw mqe; } } catch (MqttException mqe) { L.log( Level.WARNING, "Error while connecting to MQTT broker, will retry: " + mqe.getMessage(), mqe); queueConnect(); // Attempt reconnect } }
private void initMQTT() { getLogger().info("Init MQTT"); try { MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(true); this.mqttClient = new MqttClient("tcp://elab.kr:1883", String.valueOf(this.getServiceId()), persistence); this.mqttClient.setCallback(this.mqttCallback); this.mqttClient.connect(connOpts); } catch (MqttException e) { getLogger().fatal("Not Connected MQTT broker", e); } }
protected NetworkModule[] createNetworkModules(String address, MqttConnectOptions options) throws MqttException, MqttSecurityException { final String methodName = "createNetworkModules"; // @TRACE 116=URI={0} log.fine(CLASS_NAME, methodName, "116", new Object[] {address}); NetworkModule[] networkModules = null; String[] serverURIs = options.getServerURIs(); String[] array = null; if (serverURIs == null) { array = new String[] {address}; } else if (serverURIs.length == 0) { array = new String[] {address}; } else { array = serverURIs; } networkModules = new NetworkModule[array.length]; for (int i = 0; i < array.length; i++) { networkModules[i] = createNetworkModule(array[i], options); } log.fine(CLASS_NAME, methodName, "108"); return networkModules; }
/** * Create an MqttAsyncClient that is used to communicate with an MQTT server. * * <p>The address of a server can be specified on the constructor. Alternatively a list containing * one or more servers can be specified using the {@link * MqttConnectOptions#setServerURIs(String[]) setServerURIs} method on MqttConnectOptions. * * <p>The <code>serverURI</code> parameter is typically used with the the <code>clientId</code> * parameter to form a key. The key is used to store and reference messages while they are being * delivered. Hence the serverURI specified on the constructor must still be specified even if a * list of servers is specified on an MqttConnectOptions object. The serverURI on the constructor * must remain the same across restarts of the client for delivery of messages to be maintained * from a given client to a given server or set of servers. * * <p>The address of the server to connect to is specified as a URI. Two types of connection are * supported <code>tcp://</code> for a TCP connection and <code>ssl://</code> for a TCP connection * secured by SSL/TLS. For example: * * <ul> * <li><code>tcp://localhost:1883</code> * <li><code>ssl://localhost:8883</code> * </ul> * * If the port is not specified, it will default to 1883 for <code>tcp://</code>" URIs, and 8883 * for <code>ssl://</code> URIs. * * <p>A client identifier <code>clientId</code> must be specified and be less that 65535 * characters. It must be unique across all clients connecting to the same server. The clientId is * used by the server to store data related to the client, hence it is important that the clientId * remain the same when connecting to a server if durable subscriptions or reliable messaging are * required. * * <p>A convenience method is provided to generate a random client id that should satisfy this * criteria - {@link #generateClientId()}. As the client identifier is used by the server to * identify a client when it reconnects, the client must use the same identifier between * connections if durable subscriptions or reliable delivery of messages is required. * * <p>In Java SE, SSL can be configured in one of several ways, which the client will use in the * following order: * * <ul> * <li><strong>Supplying an <code>SSLSocketFactory</code></strong> - applications can use {@link * MqttConnectOptions#setSocketFactory(SocketFactory)} to supply a factory with the * appropriate SSL settings. * <li><strong>SSL Properties</strong> - applications can supply SSL settings as a simple Java * Properties using {@link MqttConnectOptions#setSSLProperties(Properties)}. * <li><strong>Use JVM settings</strong> - There are a number of standard Java system properties * that can be used to configure key and trust stores. * </ul> * * <p>In Java ME, the platform settings are used for SSL connections. * * <p>A persistence mechanism is used to enable reliable messaging. For messages sent at qualities * of service (QoS) 1 or 2 to be reliably delivered, messages must be stored (on both the client * and server) until the delivery of the message is complete. If messages are not safely stored * when being delivered then a failure in the client or server can result in lost messages. A * pluggable persistence mechanism is supported via the {@link MqttClientPersistence} interface. * An implementer of this interface that safely stores messages must be specified in order for * delivery of messages to be reliable. In addition {@link * MqttConnectOptions#setCleanSession(boolean)} must be set to false. In the event that only QoS 0 * messages are sent or received or cleanSession is set to true then a safe store is not needed. * * <p>An implementation of file-based persistence is provided in class {@link * MqttDefaultFilePersistence} which will work in all Java SE based systems. If no persistence is * needed, the persistence parameter can be explicitly set to <code>null</code>. * * @param serverURI the address of the server to connect to, specified as a URI. Can be overridden * using {@link MqttConnectOptions#setServerURIs(String[])} * @param clientId a client identifier that is unique on the server being connected to * @param persistence the persistence class to use to store in-flight message. If null then the * default persistence mechanism is used * @throws IllegalArgumentException if the URI does not start with "tcp://", "ssl://" or * "local://" * @throws IllegalArgumentException if the clientId is null or is greater than 65535 characters in * length * @throws MqttException if any other problem was encountered */ public MqttAsyncClient( String serverURI, String clientId, MqttClientPersistence persistence, MqttPingSender pingSender) throws MqttException { final String methodName = "MqttAsyncClient"; log.setResourceName(clientId); if (clientId == null) { // Support empty client Id, 3.1.1 standard throw new IllegalArgumentException("Null clientId"); } // Count characters, surrogate pairs count as one character. int clientIdLength = 0; for (int i = 0; i < clientId.length() - 1; i++) { if (Character_isHighSurrogate(clientId.charAt(i))) i++; clientIdLength++; } if (clientIdLength > 65535) { throw new IllegalArgumentException("ClientId longer than 65535 characters"); } MqttConnectOptions.validateURI(serverURI); this.serverURI = serverURI; this.clientId = clientId; this.persistence = persistence; if (this.persistence == null) { this.persistence = new MemoryPersistence(); } // @TRACE 101=<init> ClientID={0} ServerURI={1} PersistenceType={2} log.fine(CLASS_NAME, methodName, "101", new Object[] {clientId, serverURI, persistence}); this.persistence.open(clientId, serverURI); this.comms = new ClientComms(this, this.persistence, pingSender); this.persistence.close(); this.topics = new Hashtable(); }
/* (non-Javadoc) * @see org.eclipse.paho.client.mqttv3.IMqttAsyncClient#connect(org.eclipse.paho.client.mqttv3.MqttConnectOptions, java.lang.Object, org.eclipse.paho.client.mqttv3.IMqttActionListener) */ public IMqttToken connect( MqttConnectOptions options, Object userContext, IMqttActionListener callback) throws MqttException, MqttSecurityException { final String methodName = "connect"; if (comms.isConnected()) { throw ExceptionHelper.createMqttException(MqttException.REASON_CODE_CLIENT_CONNECTED); } if (comms.isConnecting()) { throw new MqttException(MqttException.REASON_CODE_CONNECT_IN_PROGRESS); } if (comms.isDisconnecting()) { throw new MqttException(MqttException.REASON_CODE_CLIENT_DISCONNECTING); } if (comms.isClosed()) { throw new MqttException(MqttException.REASON_CODE_CLIENT_CLOSED); } this.connOpts = options; this.userContext = userContext; final boolean automaticReconnect = options.isAutomaticReconnect(); // @TRACE 103=cleanSession={0} connectionTimeout={1} TimekeepAlive={2} userName={3} password={4} // will={5} userContext={6} callback={7} log.fine( CLASS_NAME, methodName, "103", new Object[] { Boolean.valueOf(options.isCleanSession()), new Integer(options.getConnectionTimeout()), new Integer(options.getKeepAliveInterval()), options.getUserName(), ((null == options.getPassword()) ? "[null]" : "[notnull]"), ((null == options.getWillMessage()) ? "[null]" : "[notnull]"), userContext, callback }); comms.setNetworkModules(createNetworkModules(serverURI, options)); comms.setReconnectCallback( new MqttCallbackExtended() { public void messageArrived(String topic, MqttMessage message) throws Exception {} public void deliveryComplete(IMqttDeliveryToken token) {} public void connectComplete(boolean reconnect, String serverURI) {} public void connectionLost(Throwable cause) { if (automaticReconnect) { // Automatic reconnect is set so make sure comms is in resting state comms.setRestingState(true); reconnecting = true; startReconnectCycle(); } } }); // Insert our own callback to iterate through the URIs till the connect succeeds MqttToken userToken = new MqttToken(getClientId()); ConnectActionListener connectActionListener = new ConnectActionListener( this, persistence, comms, options, userToken, userContext, callback, reconnecting); userToken.setActionCallback(connectActionListener); userToken.setUserContext(this); // If we are using the MqttCallbackExtended, set it on the connectActionListener if (this.mqttCallback instanceof MqttCallbackExtended) { connectActionListener.setMqttCallbackExtended((MqttCallbackExtended) this.mqttCallback); } comms.setNetworkModuleIndex(0); connectActionListener.connect(); return userToken; }
/** * Factory method to create the correct network module, based on the supplied address URI. * * @param address the URI for the server. * @param Connect options * @return a network module appropriate to the specified address. */ private NetworkModule createNetworkModule(String address, MqttConnectOptions options) throws MqttException, MqttSecurityException { final String methodName = "createNetworkModule"; // @TRACE 115=URI={0} log.fine(CLASS_NAME, methodName, "115", new Object[] {address}); NetworkModule netModule; String shortAddress; String host; int port; SocketFactory factory = options.getSocketFactory(); int serverURIType = MqttConnectOptions.validateURI(address); switch (serverURIType) { case MqttConnectOptions.URI_TYPE_TCP: shortAddress = address.substring(6); host = getHostName(shortAddress); port = getPort(shortAddress, 1883); if (factory == null) { factory = SocketFactory.getDefault(); } else if (factory instanceof SSLSocketFactory) { throw ExceptionHelper.createMqttException( MqttException.REASON_CODE_SOCKET_FACTORY_MISMATCH); } netModule = new TCPNetworkModule(factory, host, port, clientId); ((TCPNetworkModule) netModule).setConnectTimeout(options.getConnectionTimeout()); break; case MqttConnectOptions.URI_TYPE_SSL: shortAddress = address.substring(6); host = getHostName(shortAddress); port = getPort(shortAddress, 8883); SSLSocketFactoryFactory factoryFactory = null; if (factory == null) { // try { factoryFactory = new SSLSocketFactoryFactory(); Properties sslClientProps = options.getSSLProperties(); if (null != sslClientProps) factoryFactory.initialize(sslClientProps, null); factory = factoryFactory.createSocketFactory(null); // } // catch (MqttDirectException ex) { // throw ExceptionHelper.createMqttException(ex.getCause()); // } } else if ((factory instanceof SSLSocketFactory) == false) { throw ExceptionHelper.createMqttException( MqttException.REASON_CODE_SOCKET_FACTORY_MISMATCH); } // Create the network module... netModule = new SSLNetworkModule((SSLSocketFactory) factory, host, port, clientId); ((SSLNetworkModule) netModule).setSSLhandshakeTimeout(options.getConnectionTimeout()); // Ciphers suites need to be set, if they are available if (factoryFactory != null) { String[] enabledCiphers = factoryFactory.getEnabledCipherSuites(null); if (enabledCiphers != null) { ((SSLNetworkModule) netModule).setEnabledCiphers(enabledCiphers); } } break; case MqttConnectOptions.URI_TYPE_WS: shortAddress = address.substring(5); host = getHostName(shortAddress); port = getPort(shortAddress, 80); if (factory == null) { factory = SocketFactory.getDefault(); } else if (factory instanceof SSLSocketFactory) { throw ExceptionHelper.createMqttException( MqttException.REASON_CODE_SOCKET_FACTORY_MISMATCH); } netModule = new WebSocketNetworkModule(factory, address, host, port, clientId); ((WebSocketNetworkModule) netModule).setConnectTimeout(options.getConnectionTimeout()); break; case MqttConnectOptions.URI_TYPE_WSS: shortAddress = address.substring(6); host = getHostName(shortAddress); port = getPort(shortAddress, 443); SSLSocketFactoryFactory wSSFactoryFactory = null; if (factory == null) { wSSFactoryFactory = new SSLSocketFactoryFactory(); Properties sslClientProps = options.getSSLProperties(); if (null != sslClientProps) wSSFactoryFactory.initialize(sslClientProps, null); factory = wSSFactoryFactory.createSocketFactory(null); } else if ((factory instanceof SSLSocketFactory) == false) { throw ExceptionHelper.createMqttException( MqttException.REASON_CODE_SOCKET_FACTORY_MISMATCH); } // Create the network module... netModule = new WebSocketSecureNetworkModule( (SSLSocketFactory) factory, address, host, port, clientId); ((WebSocketSecureNetworkModule) netModule) .setSSLhandshakeTimeout(options.getConnectionTimeout()); // Ciphers suites need to be set, if they are available if (wSSFactoryFactory != null) { String[] enabledCiphers = wSSFactoryFactory.getEnabledCipherSuites(null); if (enabledCiphers != null) { ((SSLNetworkModule) netModule).setEnabledCiphers(enabledCiphers); } } break; case MqttConnectOptions.URI_TYPE_LOCAL: netModule = new LocalNetworkModule(address.substring(8)); break; default: // This shouldn't happen, as long as validateURI() has been called. netModule = null; } return netModule; }
public MQTTAdapterListener( MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration, String topic, String mqttClientId, InputEventAdapterListener inputEventAdapterListener, int tenantId) { if (mqttClientId == null || mqttClientId.trim().isEmpty()) { mqttClientId = MqttClient.generateClientId(); } this.mqttBrokerConnectionConfiguration = mqttBrokerConnectionConfiguration; this.cleanSession = mqttBrokerConnectionConfiguration.isCleanSession(); int keepAlive = mqttBrokerConnectionConfiguration.getKeepAlive(); this.topic = topic; this.eventAdapterListener = inputEventAdapterListener; this.tenantId = tenantId; // SORTING messages until the server fetches them String temp_directory = System.getProperty("java.io.tmpdir"); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(temp_directory); try { connectionOptions = new MqttConnectOptions(); connectionOptions.setCleanSession(cleanSession); connectionOptions.setKeepAliveInterval(keepAlive); // Construct an MQTT blocking mode client mqttClient = new MqttClient( this.mqttBrokerConnectionConfiguration.getBrokerUrl(), mqttClientId, dataStore); // Set this wrapper as the callback handler mqttClient.setCallback(this); String contentValidatorClassName = this.mqttBrokerConnectionConfiguration.getContentValidatorClassName(); if (contentValidatorClassName != null && contentValidatorClassName.equals(MQTTEventAdapterConstants.DEFAULT)) { contentValidator = new DefaultContentValidator(); } else if (contentValidatorClassName != null && !contentValidatorClassName.isEmpty()) { try { Class<? extends ContentValidator> contentValidatorClass = Class.forName(contentValidatorClassName).asSubclass(ContentValidator.class); contentValidator = contentValidatorClass.newInstance(); } catch (ClassNotFoundException e) { throw new MQTTContentInitializationException( "Unable to find the class validator: " + contentValidatorClassName, e); } catch (InstantiationException e) { throw new MQTTContentInitializationException( "Unable to create an instance of :" + contentValidatorClassName, e); } catch (IllegalAccessException e) { throw new MQTTContentInitializationException("Access of the instance in not allowed.", e); } } String contentTransformerClassName = this.mqttBrokerConnectionConfiguration.getContentTransformerClassName(); if (contentTransformerClassName != null && contentTransformerClassName.equals(MQTTEventAdapterConstants.DEFAULT)) { contentTransformer = new DefaultContentTransformer(); } else if (contentTransformerClassName != null && !contentTransformerClassName.isEmpty()) { try { Class<? extends ContentTransformer> contentTransformerClass = Class.forName(contentTransformerClassName).asSubclass(ContentTransformer.class); contentTransformer = contentTransformerClass.newInstance(); } catch (ClassNotFoundException e) { throw new MQTTContentInitializationException( "Unable to find the class transfoer: " + contentTransformerClassName, e); } catch (InstantiationException e) { throw new MQTTContentInitializationException( "Unable to create an instance of :" + contentTransformerClassName, e); } catch (IllegalAccessException e) { throw new MQTTContentInitializationException("Access of the instance in not allowed.", e); } } } catch (MqttException e) { log.error( "Exception occurred while subscribing to MQTT broker at " + mqttBrokerConnectionConfiguration.getBrokerUrl()); throw new InputEventAdapterRuntimeException(e); } }
public void startListener() throws MqttException { if (this.mqttBrokerConnectionConfiguration.getBrokerUsername() != null && this.mqttBrokerConnectionConfiguration.getDcrUrl() != null) { String username = this.mqttBrokerConnectionConfiguration.getBrokerUsername(); String dcrUrlString = this.mqttBrokerConnectionConfiguration.getDcrUrl(); String scopes = this.mqttBrokerConnectionConfiguration.getBrokerScopes(); // getJWT Client Parameters. if (dcrUrlString != null && !dcrUrlString.isEmpty()) { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username); try { URL dcrUrl = new URL(dcrUrlString); HttpClient httpClient = MQTTUtil.getHttpClient(dcrUrl.getProtocol()); HttpPost postMethod = new HttpPost(dcrUrlString); RegistrationProfile registrationProfile = new RegistrationProfile(); registrationProfile.setCallbackUrl(MQTTEventAdapterConstants.EMPTY_STRING); registrationProfile.setGrantType(MQTTEventAdapterConstants.GRANT_TYPE); registrationProfile.setOwner(username); registrationProfile.setTokenScope(MQTTEventAdapterConstants.TOKEN_SCOPE); registrationProfile.setApplicationType(MQTTEventAdapterConstants.APPLICATION_TYPE); registrationProfile.setClientName(username + "_" + tenantId); String jsonString = registrationProfile.toJSON(); StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); postMethod.setEntity(requestEntity); HttpResponse httpResponse = httpClient.execute(postMethod); if (httpResponse != null) { String response = MQTTUtil.getResponseString(httpResponse); try { if (response != null) { JSONParser jsonParser = new JSONParser(); JSONObject jsonPayload = (JSONObject) jsonParser.parse(response); String clientId = (String) jsonPayload.get(MQTTEventAdapterConstants.CLIENT_ID); String clientSecret = (String) jsonPayload.get(MQTTEventAdapterConstants.CLIENT_SECRET); JWTClientManagerService jwtClientManagerService = MQTTUtil.getJWTClientManagerService(); AccessTokenInfo accessTokenInfo = jwtClientManagerService .getJWTClient() .getAccessToken(clientId, clientSecret, username, scopes); connectionOptions.setUserName(accessTokenInfo.getAccessToken()); } } catch (ParseException e) { String msg = "error occurred while parsing client credential payload"; log.error(msg, e); } catch (JWTClientException e) { String msg = "error occurred while parsing the response from JWT Client"; log.error(msg, e); } } } catch (MalformedURLException e) { log.error("Invalid dcrUrl : " + dcrUrlString); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | IOException e) { log.error("Failed to create an https connection.", e); } finally { PrivilegedCarbonContext.endTenantFlow(); } } } mqttClient.connect(connectionOptions); mqttClient.subscribe(topic); }
public void publish(String publishClientId, String publishTopic, byte[] payload) throws DeviceControllerException { if (mqttEnabled) { MqttClient client; MqttConnectOptions options; if (publishClientId.length() > 24) { String errorString = "No of characters '" + publishClientId.length() + "' for ClientID: '" + publishClientId + "' is invalid (should be less than 24, hence please provide a " + "simple " + "'owner' tag)"; log.error(errorString); throw new DeviceControllerException(errorString); } else { log.info( "No of Characters " + publishClientId.length() + " for ClientID : '" + publishClientId + "' is acceptable"); } try { client = new MqttClient(mqttEndpoint, publishClientId); options = new MqttConnectOptions(); options.setWill("device/clienterrors", "crashed".getBytes(UTF_8), 2, true); client.setCallback(this); client.connect(options); client.publish(publishTopic, payload, 0, true); if (log.isDebugEnabled()) { log.debug( "MQTT Client successfully published to topic: " + publishTopic + ", with payload - " + payload); } client.disconnect(); } catch (MqttException ex) { String errorMsg = "MQTT Client Error" + "\n\tReason: " + ex.getReasonCode() + "\n\tMessage: " + ex.getMessage() + "\n\tLocalMsg: " + ex.getLocalizedMessage() + "\n\tCause: " + ex.getCause() + "\n\tException: " + ex; log.error(errorMsg, ex); throw new DeviceControllerException(errorMsg, ex); } } else { log.warn("MQTT <Enabled> set to false in 'device-mgt-config.xml'"); } }