Connecting to VerneMQ MQTT Broker Tutorial
Here You find some way, Connecting to VerneMQ. VerneMQ is most popular MQTT broker.
What is VerneMQ ?
VerneMQ is an enterprise ready, high-performance, distributed MQTT message broker. It scales horizontally and vertically on commodity hardware to support a high number of concurrent publishers and consumers while maintaining low and predictable latency and fault tolerance. It plugins can be developed in Erlang, Elixir, Lua, and any programming language that can implement HTTP WebHooks. It uses modern broadcast protocols and LevelDB for state replication in a cluster. It is Open Source and Apache2 licensed.
It is first and foremost a MQTT publish/subscribe message broker which implements the OASIS industry standard MQTT protocol. But VerneMQ is also built to take messaging and IoT applications to the next level by providing a unique set of features related to scalability, reliability and high-performance as well as operational simplicity.
To achieve these goals VerneMQ is designed from the ground up to work as a distributed message broker, ensuring continued operation in the event of node or network failures and easy horizontal scalability. The underlying technology is a proven telecom grade technology stack providing a rock solid foundation for systems that must be in continuous operation around the clock. It’s also able to make efficient use of all available resources as a basis for easy vertical scalability.
It uses a master-less clustering technology. There are no special nodes like masters or slaves to consider when the inevitable infrastructure changes or maintenance windows require adding or removing nodes. This makes operating the cluster safe and simple. MQTT 5.0 support now available.
If you know more about VerneMQ , Visit this link VerneMQ: A Distributed MQTT Broker (Overview)
Recommended : How To Install VerneMQ on UbunTu, RHEL, Docker, Debian and CentOS
Connecting to VerneMQ
As MQTT is the main application protocol spoken by VerneMQ, you could use any protocol compliant MQTT client library. Here you find some overview of the different options you have.
C
Use Mosquitto C library. A simple example looks like the following:
#include <stdio.h>
#include <mosquitto.h>
/* Compile with: cc -o sub sub.c -lmosquitto */
void on_connect(struct mosquitto *mosq, void *userdata, int rc)
{
mosquitto_subscribe(mosq, NULL, "$SYS/#", 0);
}
void on_message(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *m)
{
printf("%s %s\n", m->topic, m->payload);
}
int main(int argc, char **argv)
{
struct mosquitto *mosq;
int rc;
mosquitto_lib_init();
mosq = mosquitto_new(NULL, true, (void *)NULL);
if (!mosq) {
fprintf(stderr, "Error: Out of memory.\n");
mosquitto_lib_cleanup();
return (1);
}
mosquitto_connect_callback_set(mosq, on_connect);
mosquitto_message_callback_set(mosq, on_message);
rc = mosquitto_connect(mosq, "127.0.0.1", 1883, 60);
if (rc) {
fprintf(stderr, "Unable to connect (%d).\n", rc);
mosquitto_lib_cleanup();
return (rc);
}
mosquitto_loop_forever(mosq, -1, 1);
/* Unreached */
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
return (0);
}
C++
Use the official Paho MQTT client library. A simple example looks like the following:
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
int rc = 0;
char buf[200];
MQTTString topicString = MQTTString_initializer;
char* payload = "mypayload";
int payloadlen = strlen(payload);int buflen = sizeof(buf);
data.clientID.cstring = "me";
data.keepAliveInterval = 20;
data.cleansession = 1;
len = MQTTSerialize_connect(buf, buflen, &data);
topicString.cstring = "mytopic";
len += MQTTSerialize_publish(buf + len, buflen - len, 0, 0, 0, 0, topicString, payload, payloadlen);
len += MQTTSerialize_disconnect(buf + len, buflen - len);
rc = Socket_new("127.0.0.1", 1883, &mysock);
rc = write(mysock, buf, len);
rc = close(mysock);
Java
use the official Paho MQTT client library. A simple example looks like the following:
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MqttPublishSample {
public static void main(String[] args) {
String topic = "MQTT Examples";
String content = "Message from MqttPublishSample";
int qos = 2;
String broker = "tcp://iot.eclipse.org:1883";
String clientId = "JavaSample";
MemoryPersistence persistence = new MemoryPersistence();
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: "+content);
MqttMessage message = new MqttMessage(content.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();
}
}
}
Lua
use the mqtt_lua client library. The library requires A simple example looks like the following:
-- Define a function which is called by mqtt_client:handler(),
-- whenever messages are received on the subscribed topics
function callback(topic, message)
print("Received: " .. topic .. ": " .. message)
if (message == "quit") then running = false end
end
-- Create an MQTT client instance, connect to the MQTT server and
-- subscribe to the topic called "test/2"
MQTT = require("mqtt_library")
MQTT.Utility.set_debug(true)
mqtt_client = MQTT.client.create("localhost", nil, callback)
mqtt_client:connect("lua mqtt client"))
mqtt_client:subscribe({"test/2"})
-- Continously invoke mqtt_client:handler() to process the MQTT protocol and
-- handle any received messages. Also, publish a message on topic "test/1"
running = true
while (running) do
mqtt_client:handler()
mqtt_client:publish("test/1", "test message")
socket.sleep(1.0) -- seconds
end
Python
Use the official Paho MQTT client library. A simple example looks like the following:
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("$SYS/#")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("iot.eclipse.org", 1883, 60)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
Javascript
Use the official Paho MQTT client library. This library is meant to be used in the web browser. It requires that VerneMQ has a websocket listener configured. A simple example for using the client on a webpage could look like the following:
// Create a client instance
client = new Paho.MQTT.Client(location.hostname, Number(location.port), "clientId");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
client.connect({onSuccess:onConnect});
// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
client.subscribe("/World");
message = new Paho.MQTT.Message("Hello");
message.destinationName = "/World";
client.send(message);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
console.log("onMessageArrived:"+message.payloadString);
}
Android
In principle it is possible to use the Paho Java library directly for this, but a much better option is to use Paho Android Client and Service which wraps the java library in an Android Service which makes it easy to send and receive messages on behalf of Android applications, even when they are not currently running.
iOS
In principle it is possible to wrap a C library and get it to work on iOS, but since Apple does not permit third party networking stacks access to the mobile antenna we recommend the native Objective-C MQTT-Client-Framework.
Arduino
Use the knolleary MQTT client library. The library requires the Arduino Ethernet Shield. A simple example looks like the following:
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
byte server[] = { 172, 16, 0, 2 };
byte ip[] = { 172, 16, 0, 100 };
void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
}
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void setup()
{
Ethernet.begin(mac, ip);
if (client.connect("arduinoClient")) {
client.publish("outTopic","hello world");
client.subscribe("inTopic");
}
}
void loop()
{
client.loop();
}
Above mentioned Libraries based on recommendation according to official VerneMQ Docs. Sometimes I used with different Libraries but use recommended libreries for better experience and seamless output.
I hope you like this post “ Connecting to VerneMQ ”. Do you have any questions? Leave a comment down below!
Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog.