Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ import ballerina/mqtt;

public function main() returns error? {
do {
mqtt:DeliveryToken mqttDeliverytoken = check mqttClient->publish(mqttTopic, {payload: "Hello World".toBytes()});
mqtt:DeliveryToken _ = check mqttClient->publish(mqttTopic, {
payload: "25.5".toBytes(),
qos: 2,
retained: true
});
log:printInfo("Temperature published to MQTT broker", topic = mqttTopic, value = "25.5");

} on fail error e {
log:printError("Error occurred", 'error = e);
return e;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import ballerina/mqtt;

configurable string mqttServerUri = ?;
configurable string mqttClientId = ?;
configurable string mqttTopic = "test/topic";
configurable string mqttServerUri = mqtt:DEFAULT_URL;
configurable string mqttClientId = "ballerina-mqtt-client";
configurable string mqttTopic = "sensors/temperature";
36 changes: 27 additions & 9 deletions integrator-default-profile/connectors/mqtt_trigger_sample/main.bal
Original file line number Diff line number Diff line change
@@ -1,16 +1,34 @@
import ballerina/log;
import ballerina/mqtt;
import ballerina/uuid;

listener mqtt:Listener mqttListener = new (string `${mqttBrokerUrl}mqtt://localhost:1883`, string `${mqttClientId}unique_client_001`, string `${mqttTopic}topic1`);
configurable string broker = mqtt:DEFAULT_URL;
const TOPIC = "sensors/temperature";

service mqtt:Service on mqttListener {
remote function onMessage(mqtt:Message message) returns error? {
do {
log:printInfo(message.toJsonString());
} on fail error err {
// handle error
return error("unhandled error", err);
listener mqtt:Listener mqttListener = new (
broker,
uuid:createType1AsString(),
TOPIC,
{manualAcks: true}
);

service on mqttListener {
remote function onMessage(mqtt:Message message, mqtt:Caller caller) returns error? {
string payload = check string:fromBytes(message.payload);
log:printInfo("Temperature message received from MQTT broker", topic = message.topic, payload = payload);
float temperature = check float:fromString(payload);

if temperature > 30.0 {
log:printWarn("High temperature alert!", temp = temperature);
} else {
log:printInfo("Temperature normal", temp = temperature);
}

// Acknowledge the message
check caller->complete();
}

}
remote function onError(mqtt:Error err) returns error? {
log:printError("Error processing message", 'error = err);
}
}