@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(); } }
@Override public MqttConnectOptions getConnectionOptions() { MqttConnectOptions options = new MqttConnectOptions(); if (this.cleanSession != null) { options.setCleanSession(this.cleanSession); } if (this.connectionTimeout != null) { options.setConnectionTimeout(this.connectionTimeout); } if (this.keepAliveInterval != null) { options.setKeepAliveInterval(this.keepAliveInterval); } if (this.password != null) { options.setPassword(this.password.toCharArray()); } if (this.socketFactory != null) { options.setSocketFactory(this.socketFactory); } if (this.sslProperties != null) { options.setSSLProperties(this.sslProperties); } if (this.userName != null) { options.setUserName(this.userName); } if (this.will != null) { options.setWill( this.will.getTopic(), this.will.getPayload(), this.will.getQos(), this.will.isRetained()); } if (this.serverURIs != null) { options.setServerURIs(this.serverURIs); } return options; }
@Override public void onCreate() { super.onCreate(); vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); gameDatabase = new GameDatabase(this); // init game DB if (gameDatabase.getViruses().isEmpty()) { Virus v = VirusFactory.createMutation(null); Log.d(LOG_TAG, "new virus: " + v.getId()); gameDatabase.addVirus(v); EventBus.getDefault().post(new GameEvent(GameEvent.Type.NEW_VIRUS, v.getId(), 0)); } clientId = gameDatabase.getSetting("clientId", null); if (clientId == null) { clientId = UUID.randomUUID().toString(); gameDatabase.putSetting("clientId", clientId); Log.i(LOG_TAG, "persisted new clientId: " + clientId); } // MQTT mqttClient = new MqttAndroidClient(this, BROKER_URI, clientId); mqttClient.setCallback(this); // Location locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_LOCATION_UPDATE_INTERVAL_MS, MIN_LOCATION_UPDATE_DISTANCE_M, this); else locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_LOCATION_UPDATE_INTERVAL_MS, MIN_LOCATION_UPDATE_DISTANCE_M, this); findBestLastLocation(); try { MqttConnectOptions options = new MqttConnectOptions(); options.setKeepAliveInterval(0); // no keepalive pings mqttClient.connect(options, null, this); Log.d(LOG_TAG, "connected to MQTT broker as " + clientId); } catch (MqttException e) { Log.e(LOG_TAG, "could not connect to MQTT broker at " + BROKER_URI); } EventBus.getDefault().register(this); }
public MQTTAdaptorListener( MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration, String topic, String mqttClientId, InputEventAdaptorListener inputEventAdaptorListener, int tenantId) { this.mqttBrokerConnectionConfiguration = mqttBrokerConnectionConfiguration; this.mqttClientId = mqttClientId; this.cleanSession = mqttBrokerConnectionConfiguration.isCleanSession(); this.keepAlive = mqttBrokerConnectionConfiguration.getKeepAlive(); this.topic = topic; this.eventAdaptorListener = inputEventAdaptorListener; 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 { // Construct the connection options object that contains connection parameters // such as cleanSession and LWT connectionOptions = new MqttConnectOptions(); connectionOptions.setCleanSession(cleanSession); connectionOptions.setKeepAliveInterval(keepAlive); if (this.mqttBrokerConnectionConfiguration.getBrokerPassword() != null) { connectionOptions.setPassword( this.mqttBrokerConnectionConfiguration.getBrokerPassword().toCharArray()); } if (this.mqttBrokerConnectionConfiguration.getBrokerUsername() != null) { connectionOptions.setUserName(this.mqttBrokerConnectionConfiguration.getBrokerUsername()); } // Construct an MQTT blocking mode client mqttClient = new MqttClient( this.mqttBrokerConnectionConfiguration.getBrokerUrl(), this.mqttClientId, dataStore); // Set this wrapper as the callback handler mqttClient.setCallback(this); } catch (MqttException e) { log.error("Exception occurred while subscribing to MQTT broker" + e); throw new InputEventAdaptorEventProcessingException(e); } catch (Throwable e) { log.error("Exception occurred while subscribing to MQTT broker" + e); throw new InputEventAdaptorEventProcessingException(e); } }
public static MqttConnectOptions getOpts() { Properties pro = getOptsPro(); if (null != pro) { String uName = pro.getProperty("u", null); String pwd = pro.getProperty("p", null); String cid = pro.getProperty("c", null); if (!isEmpty(uName) && !isEmpty(pwd) && !isEmpty(cid)) { MqttConnectOptions opts = new MqttConnectOptions(); opts.setKeepAliveInterval(200); opts.setUserName(uName); opts.setPassword(pwd.toCharArray()); return opts; } } return null; }
public MQTTAdapterPublisher( MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration, String topic, String mqttClientId) { this.mqttBrokerConnectionConfiguration = mqttBrokerConnectionConfiguration; this.mqttClientId = mqttClientId; this.cleanSession = mqttBrokerConnectionConfiguration.isCleanSession(); this.keepAlive = mqttBrokerConnectionConfiguration.getKeepAlive(); this.topic = topic; // SORTING messages until the server fetches them String temp_directory = System.getProperty(MQTTEventAdapterConstants.ADAPTER_TEMP_DIRECTORY_NAME); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(temp_directory); try { // Construct the connection options object that contains connection parameters // such as cleanSession and LWT connectionOptions = new MqttConnectOptions(); connectionOptions.setCleanSession(cleanSession); connectionOptions.setKeepAliveInterval(keepAlive); if (this.mqttBrokerConnectionConfiguration.getBrokerPassword() != null) { connectionOptions.setPassword( this.mqttBrokerConnectionConfiguration.getBrokerPassword().toCharArray()); } if (this.mqttBrokerConnectionConfiguration.getBrokerUsername() != null) { connectionOptions.setUserName(this.mqttBrokerConnectionConfiguration.getBrokerUsername()); } // Construct an MQTT blocking mode client mqttClient = new MqttClient( this.mqttBrokerConnectionConfiguration.getBrokerUrl(), this.mqttClientId, dataStore); mqttClient.connect(connectionOptions); } catch (MqttException e) { log.error( "Error occurred when constructing MQTT client for broker url : " + mqttBrokerConnectionConfiguration.getBrokerUrl()); handleException(e); } }
public boolean connect(Properties props) { brokerUrl = props.getProperty("brokerurl", null); if (brokerUrl == null) { throw new RuntimeException("Could not find parameter brokerur"); } Random rnd = new Random(); clientId = props.getProperty( "clientid", System.getenv("mqtt.clientid") != null ? System.getenv("mqtt.clientid") : "mqtt.loadgen." + rnd.nextInt(100000)); if (clientId == null || clientId.length() == 0) { try { clientId = NetworkInterface.getNetworkInterfaces().hasMoreElements() ? NetworkInterface.getNetworkInterfaces() .nextElement() .getInetAddresses() .nextElement() .getHostName() : "noop"; } catch (Exception ex) { LOG.log(Level.SEVERE, "Could not retrieve hostname", ex); } } // This sample stores in a temporary directory... where messages temporarily // stored until the message has been delivered to the server. // ..a real application ought to store them somewhere // where they are not likely to get deleted or tampered with File tmpDir = createTempDir(); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir.getAbsolutePath()); LOG.log( Level.INFO, "Using directory {0} for temporary message storage", tmpDir.getAbsolutePath()); try { // Construct the connection options object that contains connection parameters // such as cleanSession and LWT conOpt = new MqttConnectOptions(); conOpt.setCleanSession(Boolean.parseBoolean(props.getProperty("cleansession", "true"))); conOpt.setConnectionTimeout(Integer.parseInt(props.getProperty("connectiontimeout", "100"))); conOpt.setKeepAliveInterval(Integer.parseInt(props.getProperty("keepaliveinterval", "100"))); conOpt.setSocketFactory( SslUtil.getSocketFactory( props.getProperty("cafile"), props.getProperty("cert"), props.getProperty("privkey"), props.getProperty("password", "dummy"))); // Construct an MQTT blocking mode client client = new MqttClient(this.brokerUrl, clientId, dataStore); // Wait max 10sec for a blocking call client.setTimeToWait(10000); // Set this wrapper as the callback handler client.setCallback(this); // Connect to the MQTT server LOG.log( Level.INFO, "Connecting to {0} with client ID {1}", new Object[] {brokerUrl, client.getClientId()}); client.connect(conOpt); LOG.info("Connected"); connected = true; return connected; } catch (MqttException e) { LOG.log(Level.WARNING, "Unable to set up client: " + e.toString(), e); } catch (Exception ex) { LOG.log(Level.SEVERE, "Could not create connection: " + ex.getLocalizedMessage(), ex); } return false; }
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); } }
/** * Process data from the connect action * * @param data the {@link Bundle} returned by the {@link NewConnection} Acitivty */ private void connectAction(Bundle data) { MqttConnectOptions conOpt = new MqttConnectOptions(); /* * Mutal Auth connections could do something like this * * * SSLContext context = SSLContext.getDefault(); * context.init({new CustomX509KeyManager()},null,null); //where CustomX509KeyManager proxies calls to keychain api * SSLSocketFactory factory = context.getSSLSocketFactory(); * * MqttConnectOptions options = new MqttConnectOptions(); * options.setSocketFactory(factory); * * client.connect(options); * */ // public Properties getSSLSettings() { // final Properties properties = new Properties(); // properties.setProperty("com.ibm.ssl.keyStore", // "C:/BKSKeystore/mqttclientkeystore.keystore"); // properties.setProperty("com.ibm.ssl.keyStoreType", "BKS"); // properties.setProperty("com.ibm.ssl.keyStorePassword", "passphrase"); // properties.setProperty("com.ibm.ssl.trustStore", // "C:/BKSKeystore/mqttclienttrust.keystore"); // properties.setProperty("com.ibm.ssl.trustStoreType", "BKS"); // properties.setProperty("com.ibm.ssl.trustStorePassword", "passphrase "); // // return properties; // } try { SSLContext context; KeyStore ts = KeyStore.getInstance("BKS"); ts.load(getResources().openRawResource(R.raw.test), "123456".toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); tmf.init(ts); TrustManager[] tm = tmf.getTrustManagers(); context = SSLContext.getInstance("TLS"); context.init(null, tm, null); // SocketFactory factory= SSLSocketFactory.getDefault(); // Socket socket =factory.createSocket("localhost", 10000); SocketFactory factory = context.getSocketFactory(); conOpt.setSocketFactory(factory); } catch (Exception e) { // TODO: handle exception } // The basic client information String server = (String) data.get(ActivityConstants.server); String clientId = (String) data.get(ActivityConstants.clientId); int port = Integer.parseInt((String) data.get(ActivityConstants.port)); boolean cleanSession = (Boolean) data.get(ActivityConstants.cleanSession); boolean ssl = (Boolean) data.get(ActivityConstants.ssl); String uri = null; if (ssl) { Log.e("SSLConnection", "Doing an SSL Connect"); uri = "ssl://"; } else { uri = "tcp://"; } uri = uri + server + ":" + port; MqttClientAndroidService client; client = Connections.getInstance(this).createClient(this, uri, clientId); // create a client handle String clientHandle = uri + clientId; // last will message String message = (String) data.get(ActivityConstants.message); String topic = (String) data.get(ActivityConstants.topic); Integer qos = (Integer) data.get(ActivityConstants.qos); Boolean retained = (Boolean) data.get(ActivityConstants.retained); // connection options String username = (String) data.get(ActivityConstants.username); String password = (String) data.get(ActivityConstants.password); int timeout = (Integer) data.get(ActivityConstants.timeout); int keepalive = (Integer) data.get(ActivityConstants.keepalive); Connection connection = new Connection(clientHandle, clientId, server, port, this, client, ssl); arrayAdapter.add(connection); connection.registerChangeListener(changeListener); // connect client String[] actionArgs = new String[1]; actionArgs[0] = clientId; connection.changeConnectionStatus(ConnectionStatus.CONNECTING); conOpt.setCleanSession(cleanSession); conOpt.setConnectionTimeout(timeout); conOpt.setKeepAliveInterval(keepalive); if (!username.equals(ActivityConstants.empty)) { conOpt.setUserName(username); } if (!password.equals(ActivityConstants.empty)) { conOpt.setPassword(password.toCharArray()); } final ActionListener callback = new ActionListener(this, ActionListener.Action.CONNECT, clientHandle, actionArgs); boolean doConnect = true; if ((!message.equals(ActivityConstants.empty)) || (!topic.equals(ActivityConstants.empty))) { // need to make a message since last will is set try { conOpt.setWill(topic, message.getBytes(), qos.intValue(), retained.booleanValue()); } catch (Exception e) { doConnect = false; callback.onFailure(null, e); } } client.setCallback(new MqttCallbackHandler(this, clientHandle)); connection.addConnectionOptions(conOpt); Connections.getInstance(this).addConnection(connection); if (doConnect) { try { client.connect(conOpt, null, callback); } catch (MqttException e) { Log.e(this.getClass().getCanonicalName(), "MqttException Occured", e); } } }