Beispiel #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
    }
  }
 // region MqttActionCallBack -- connection success or fail
 @Override
 public void onSuccess(IMqttToken iMqttToken) {
   isConnected = true;
   ShowToast("连接成功");
   try {
     client.subscribe("Likaci/MqttMap", 0);
   } catch (MqttException e) {
     e.printStackTrace();
   }
 }
  @Override
  protected void init(VaadinRequest request) {
    System.out.println("request = " + request);
    final VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    setContent(layout);
    layout.addComponent(chart);

    try {
      empf = new MqttClient("tcp://192.168.0.106:1883", "MyfirstMQTTEmpf", new MemoryPersistence());
      empf.setCallback(
          new MqttCallback() {
            @Override
            public void connectionLost(Throwable throwable) {}

            @Override
            public void messageArrived(String str, MqttMessage mqttMessage) throws Exception {
              byte[] payload = mqttMessage.getPayload();
              lastMessage = new String(payload);
              System.out.println("s = " + str + " msg " + lastMessage);
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {}
          });

      Button button = new Button("refresh");
      button.addClickListener(
          event ->
              access(
                  () ->
                      chart
                          .getConfiguration()
                          .getSeries()
                          .forEach(
                              s ->
                                  ((ListSeries) s)
                                      .updatePoint(0, Double.valueOf(lastMessage.split(":")[3])))));
      layout.addComponent(button);
      empf.connect();
      empf.subscribe(TOPIC, 1);

      mqqtThread.start();
    } catch (MqttException e) {
      e.printStackTrace();
    }
  }
  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'");
    }
  }