How can I publish to an MQTT topic using a URL.
i.e. "http://127.0.0.1/cmnd/power/on" will send "on" to "power" topic.
Ps: I am using HiveMQ
First you need make mqtt Connection and once the connection is successful you could send any payload to desired topic. This is how you need to initiate connection.
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();
}