Exemplo n.º 1
0
  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
    }
  }
  @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;
 }
  public static void main(String[] args) {
    // The quality of service for the sent message.
    int qualityOfService = 1;

    // Memory persistence for client message deliver. Store it in a file in case
    // lose connections to the broker.
    MqttClientPersistence persistence = new MqttDefaultFilePersistence();

    try {
      Properties credentials = new Properties();
      credentials.load(new FileInputStream(new File("/Users/keith/mqtt.properties")));

      MqttClient client =
          new MqttClient(
              "ssl://smartspaces.io:8883", "/mqtt/publisher/credentialed/ssl", persistence);

      client.setCallback(
          new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
              System.out.println("Lost connection");
              cause.printStackTrace();
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
              System.out.println("Got delivery token " + token.getResponse());
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
              // Not needed since not subscribing.
            }
          });

      MqttConnectOptions options = new MqttConnectOptions();
      options.setCleanSession(true);
      options.setUserName(credentials.getProperty("mqtt.username"));
      options.setPassword(credentials.getProperty("mqtt.password").toCharArray());
      options.setSocketFactory(configureSSLSocketFactory(credentials));

      System.out.println("Connecting to broker: " + client.getServerURI());
      client.connect(options);
      System.out.println("Connected");

      byte[] content = "Hello, world!".getBytes();
      MqttMessage message = new MqttMessage(content);
      message.setQos(qualityOfService);
      client.publish("/greeting", message);
      System.out.println("Message published");

      client.disconnect();
      System.out.println("Disconnected");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 5
0
  @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);
  }
  @Test
  public void checkSupportSSL() throws Exception {
    LOG.info("*** checkSupportSSL ***");
    SSLSocketFactory ssf = configureSSLSocketFactory();

    MqttConnectOptions options = new MqttConnectOptions();
    options.setSocketFactory(ssf);
    m_client.connect(options);
    m_client.subscribe("/topic", 0);
    m_client.disconnect();
  }
Exemplo n.º 7
0
  public static void main(String[] args) {
    String topic = "/group/1ffb66a0-304e-11e5-a2cb-0800200c9a66/send_data";
    String contentStr = "Message from KC";
    int qos = 2;
    String broker = "tcp://isplanet.dyndns-office.com:1883";
    String clientId = "JavaSample";
    MemoryPersistence persistence = new MemoryPersistence();

    Content content = new Content();
    content.setDevID("80:C1:6E:F3:E7:6B");
    content.setDevName("KC");
    content.setGroupID("1ffb66a0-304e-11e5-a2cb-0800200c9a66");
    content.setSendTimestamp(String.valueOf(System.currentTimeMillis()));

    Shot shot = new Shot();
    shot.setMessage("Test");
    shot.setImageUrl("http://ab.unayung.cc/uploads/photo/file/000/000/030/LN07_005.jpg");
    shot.setPosition(new GeoPoint(25.042299, 121.507695));

    content.setShot(shot);
    contentStr = JsonDataFactory.getJson(content);

    // System.exit(0);

    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: " + contentStr);

      MqttMessage message = new MqttMessage(contentStr.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();
    }
  }
 public void start() throws MqttException {
   MqttConnectOptions options = new MqttConnectOptions();
   options.setUserName(brokerUser);
   options.setPassword(brokerPass.toCharArray());
   client.connect(options);
   // PrintOutCallback printOutCallback = new PrintOutCallback();
   DatabaseCallback databaseCallback =
       new DatabaseCallback(
           databaseIP, databasePort, dataBaseUser, dataBasePass, defultDataBase, client);
   client.setCallback(databaseCallback);
   subscribeToTopics();
 }
Exemplo n.º 9
0
 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);
   }
 }
  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);
    }
  }
Exemplo n.º 11
0
  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;
  }
Exemplo n.º 12
0
 private void createClient() {
   Log.d(TAG, "Creating client");
   client = new MqttAndroidClient(context, serverURI, clientId);
   client.setCallback(this);
   client.setTraceCallback(this);
   MqttConnectOptions options = new MqttConnectOptions();
   options.setCleanSession(false);
   try {
     client.connect(options);
   } catch (MqttException e) {
     e.printStackTrace();
   }
   //        MqttMessage message = new MqttMessage();
   //        message.setQos(qos);
   //        message.setPayload(new String("Bjorn").getBytes());
   //        client.publish("message);
 }
Exemplo n.º 13
0
  /**
   * Constructs an instance of the sample client wrapper
   *
   * @param brokerUrl the url to connect to
   * @param clientId the client id to connect with
   * @param cleanSession clear state at end of connection or not (durable or non-durable
   *     subscriptions)
   * @param quietMode whether debug should be printed to standard out
   * @param userName the username to connect with
   * @param password the password for the user
   * @throws MqttException
   */
  public SampleAsyncWait(
      String brokerUrl,
      String clientId,
      boolean cleanSession,
      boolean quietMode,
      String userName,
      String password)
      throws MqttException {
    this.brokerUrl = brokerUrl;
    this.quietMode = quietMode;
    this.clean = cleanSession;
    this.userName = userName;
    this.password = password;
    // 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
    String tmpDir = System.getProperty("java.io.tmpdir");
    MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);

    try {
      // Construct the connection options object that contains connection parameters
      // such as cleanSession and LWT
      conOpt = new MqttConnectOptions();
      conOpt.setCleanSession(clean);
      if (password != null) {
        conOpt.setPassword(this.password.toCharArray());
      }
      if (userName != null) {
        conOpt.setUserName(this.userName);
      }

      // Construct a non-blocking MQTT client instance
      client = new MqttAsyncClient(this.brokerUrl, clientId, dataStore);

      // Set this wrapper as the callback handler
      client.setCallback(this);

    } catch (MqttException e) {
      e.printStackTrace();
      log("Unable to set up client: " + e.toString());
      System.exit(1);
    }
  }
  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);
    }
  }
Exemplo n.º 15
0
 void connectAndSub() {
   String methodName = Utility.getMethodName();
   try {
     mqttClient = clientFactory.createMqttClient(serverURI, ClientId);
     mqttV3Receiver = new MqttV3Receiver(mqttClient, LoggingUtilities.getPrintStream());
     mqttV3Receiver.setReportConnectionLoss(false);
     mqttClient.setCallback(mqttV3Receiver);
     MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
     mqttConnectOptions.setCleanSession(false);
     mqttConnectOptions.setWill("WillTopic", "payload".getBytes(), 2, true);
     log.info("Connecting...(serverURI:" + serverURI + ", ClientId:" + ClientId);
     mqttClient.connect(mqttConnectOptions);
     log.info("Subscribing to..." + FirstSubTopicString);
     mqttClient.subscribe(FirstSubTopicString, 2);
   } catch (Exception exception) {
     log.log(Level.SEVERE, "caugh exception:" + exception);
     setState(FirstClientState.ERROR);
     Assert.fail("Failed ConnectAndSub exception=" + exception);
   }
 }
  @Test
  public void checkSupportSSLForMultipleClient() throws Exception {
    LOG.info("*** checkSupportSSLForMultipleClient ***");
    SSLSocketFactory ssf = configureSSLSocketFactory();

    MqttConnectOptions options = new MqttConnectOptions();
    options.setSocketFactory(ssf);
    m_client.connect(options);
    m_client.subscribe("/topic", 0);

    MqttClient secondClient =
        new MqttClient("ssl://localhost:8883", "secondTestClient", new MemoryPersistence());
    MqttConnectOptions secondClientOptions = new MqttConnectOptions();
    secondClientOptions.setSocketFactory(ssf);
    secondClient.connect(secondClientOptions);
    secondClient.publish("/topic", new MqttMessage("message".getBytes()));
    secondClient.disconnect();

    m_client.disconnect();
  }
Exemplo n.º 17
0
  public void initializeAndConnect(Context ctx, int qos, InitCallback callback) {

    connectCallback = callback;
    context = ctx;
    qualityOfService = qos;
    deviceId = "ad" + Secure.getString(ctx.getContentResolver(), Secure.ANDROID_ID);

    opts = new MqttConnectOptions();
    opts.setCleanSession(true);

    User curUser = ClearBlade.getCurrentUser();

    if (curUser.getAuthToken() == null) {
      Log.i(DEBUG_TAG, "Auth token is null, cannot start messaging service");
      return;
    } else {
      Log.i(DEBUG_TAG, "Received Authenticated user details");
      opts.setUserName(curUser.getAuthToken());
      opts.setPassword(Util.getSystemKey().toCharArray());
    }

    connect(ctx, callback);
  }
Exemplo n.º 18
0
  public void doDemo() {
    try {
      client = new MqttClient("tcp://115.28.225.5:1883", "pahomqttpublish1");
      client.connect();
      MqttMessage message = new MqttMessage();
      message.setPayload("A single message".getBytes());
      client.publish("pahodemo", message);
      client.disconnect();

      MqttConnectOptions options = new MqttConnectOptions();
      options.setCleanSession(true);

      //      client = new MqttClient("tcp://115.28.225.5:1883", "pahomqtt2");
      //      client.setCallback(new MqttCallback() {
      //
      //        public void messageArrived(String topic, MqttMessage msg) throws Exception {
      //          System.out.println("get topic : " + topic + " , msg: " + msg);
      //        }
      //
      //        public void deliveryComplete(IMqttDeliveryToken arg0) {
      //          // TODO Auto-generated method stub
      //
      //        }
      //
      //        public void connectionLost(Throwable arg0) {
      //          // TODO Auto-generated method stub
      //
      //        }
      //      });
      //      client.connect(options);
      //      client.subscribe(new String[]{"pahodemo"});
      //      Thread.sleep(3000);
      //      client.disconnect();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public static void main(String[] args) {
    MqttClient client = null;
    MemoryPersistence persistence = new MemoryPersistence();
    try {
      client =
          new MqttClient("tcp://mqtt.phelicks.net:1883", "PointOfNoReturnService", persistence);
      MqttConnectOptions options = new MqttConnectOptions();
      options.setUserName("cab");
      options.setPassword("sjuttongubbar".toCharArray());
      client.connect(options);
    } catch (MqttException e) {
      e.printStackTrace();
    }

    PointOfNoReturnCallback pointOfNoReturnCallback = new PointOfNoReturnCallback(client);
    client.setCallback(pointOfNoReturnCallback);

    try {
      client.subscribe("telemetry/snapshot");
      client.subscribe("set/config");
    } catch (MqttException e) {
      e.printStackTrace();
    }
  }
  private MqttConnectOptions getConnectOptions(
      String userName,
      String password,
      Boolean clearSession,
      Integer connectionTimeout,
      String lwtTopic,
      String lwtMessage,
      Integer lwtQos,
      Boolean lwtRetained) {
    MqttConnectOptions connectOpts = new MqttConnectOptions();

    if (!StringUtility.isNullOrEmpty(userName)) {
      connectOpts.setUserName(userName);

      if (!StringUtility.isNullOrEmpty(password)) {
        connectOpts.setPassword(password.toCharArray());
      }
    }

    if (clearSession != null) {
      connectOpts.setCleanSession(clearSession);
    }

    if (connectionTimeout != null) {
      connectOpts.setConnectionTimeout(connectionTimeout);
    }

    if (!StringUtility.isNullOrEmpty(lwtTopic) && !StringUtility.isNullOrEmpty(lwtMessage)) {
      connectOpts.setWill(
          lwtTopic,
          lwtMessage.getBytes(),
          NumberUtility.nvl(lwtQos, 1),
          BooleanUtility.nvl(lwtRetained, false));
    }

    return connectOpts;
  }
  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;
  }
Exemplo n.º 22
0
  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'");
    }
  }
  /**
   * 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);
      }
    }
  }
  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);
 }
Exemplo n.º 26
0
  /**
   * Test that a client actively doing work can be taken over
   *
   * @throws Exception
   */
  @Test
  public void testLiveTakeOver() throws Exception {
    String methodName = Utility.getMethodName();
    LoggingUtilities.banner(log, cclass, methodName);
    log.entering(className, methodName);

    IMqttClient mqttClient = null;
    try {
      FirstClient firstClient = new FirstClient();
      Thread firstClientThread = new Thread(firstClient);
      log.info("Starting the firstClient thread");
      firstClientThread.start();
      log.info("firstClientThread Started");

      firstClient.waitForState(FirstClientState.READY);

      log.fine("telling the 1st client to go and let it publish for 2 seconds");
      // Tell the first client to go and let it publish for a couple of seconds
      firstClient.setState(FirstClientState.RUNNING);
      Thread.sleep(2000);

      log.fine("Client has been run for 2 seconds, now taking over connection");

      // Now lets take over the connection
      // Create a second MQTT client connection with the same clientid. The
      // server should spot this and kick the first client connection off.
      // To do this from the same box the 2nd client needs to use either
      // a different form of persistent store or a different locaiton for
      // the store to the first client.
      // MqttClientPersistence persist = new MemoryPersistence();
      mqttClient = clientFactory.createMqttClient(serverURI, ClientId, null);

      MqttV3Receiver mqttV3Receiver =
          new MqttV3Receiver(mqttClient, LoggingUtilities.getPrintStream());
      mqttClient.setCallback(mqttV3Receiver);
      MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
      mqttConnectOptions.setCleanSession(false);
      mqttConnectOptions.setWill("WillTopic", "payload".getBytes(), 2, true);
      log.info("Connecting...(serverURI:" + serverURI + ", ClientId:" + ClientId);
      mqttClient.connect(mqttConnectOptions);

      // We should have taken over the first Client's subscription...we may have some
      // of his publishes arrive.
      // NOTE: as a different persistence is used for the second client any inflight
      // publications from the client will not be recovered / restarted. This will
      // leave debris on the server.
      log.fine(
          "We should have taken over the first Client's subscription...we may have some of his publishes arrive.");
      // Ignore his publishes that arrive...
      ReceivedMessage oldMsg;
      do {
        oldMsg = mqttV3Receiver.receiveNext(1000);
      } while (oldMsg != null);

      log.fine("Now check we have grabbed his subscription by publishing..");
      // Now check we have grabbed his subscription by publishing..
      byte[] payload =
          ("Message payload from second client " + getClass().getName() + "." + methodName)
              .getBytes();
      MqttTopic mqttTopic = mqttClient.getTopic(FirstSubTopicString);
      log.info("Publishing to..." + FirstSubTopicString);
      mqttTopic.publish(payload, 1, false);
      log.info("Publish sent, checking for receipt...");

      boolean ok = mqttV3Receiver.validateReceipt(FirstSubTopicString, 1, payload);
      if (!ok) {
        throw new Exception("Receive failed");
      }
    } catch (Exception exception) {
      log.throwing(className, methodName, exception);
      throw exception;
    } finally {
      try {
        mqttClient.disconnect();
        log.info("Disconnecting...");
        mqttClient.close();
        log.info("Close...");
      } catch (Exception exception) {
        log.throwing(className, methodName, exception);
        throw exception;
      }
    }

    log.exiting(className, methodName);
  }