【问题标题】:MQTT publish using URL HIVEMQMQTT 使用 URL HIVEMQ 发布
【发布时间】:2018-10-12 06:33:10
【问题描述】:

如何使用 URL 发布到 MQTT 主题。

即“http://127.0.0.1/cmnd/power/on”会将“on”发送到“power”主题。

Ps:我正在使用 HiveMQ

【问题讨论】:

  • 以后你需要在提问时展示你实际尝试过的内容

标签: mqtt hivemq


【解决方案1】:

MQTT 通常使用 TCP 作为底层协议,(HTTP 仅在 websocket 上下文中)。

使用 paho mqtt 客户端库连接 mqtt 客户端的 Java 示例:

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
...

final MqttClient mqttClient = new MqttClient("tcp://localhost:1883", 
      MqttClient.generateClientId(), 
      new MemoryPersistence());  
opt.setUserName("User");
...
mqttClient.connect(opt);
...

//subscribe to all topics 
mqttClient.subscribe("#");

//publish your status ON with a QoS 1 message that is retained 
mqttClient.publish("cmnd/power, ("on").getBytes(), 1, true);

【讨论】:

    【解决方案2】:

    首先,您需要建立 mqtt 连接,一旦连接成功,您就可以将任何有效负载发送到所需的主题。 这就是您需要启动连接的方式。

     String clientId = MqttClient.generateClientId();
     MqttConnectOptions options = new MqttConnectOptions();
     options.setUserName("USERNAME");
     options.setPassword("PASSWORD".toCharArray());
     MqttAndroidClient client =
        new MqttAndroidClient(this.getApplicationContext(), "tcp://broker.hivemq.com:1883",
                              clientId);
    
      try {
           IMqttToken token = client.connect(options);
           token.setActionCallback(new IMqttActionListener() {
           @Override
            public void onSuccess(IMqttToken asyncActionToken) {
            // We are connected
            Log.d(TAG, "onSuccess");
           }
    
          @Override
          public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            // Something went wrong e.g. connection timeout or firewall problems
            Log.d(TAG, "onFailure");
           }
          });
         } catch (MqttException e) {
        e.printStackTrace();
     }
    
    You can publish message to topic power 
    
    
         String topic = "power";
         String payload = "ON";
         byte[] encodedPayload = new byte[0];
    
       try {
           encodedPayload = payload.getBytes("UTF-8");
           MqttMessage message = new MqttMessage(encodedPayload);
           client.publish(topic, message);
         }  catch (UnsupportedEncodingException | MqttException e) {
          e.printStackTrace();
       }
    

    【讨论】:

      猜你喜欢
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多