Tag Archives: mqtt

Modify Socket parameters of Mqtt Client

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import javax.net.SocketFactory;

public class MySocketFactory extends SocketFactory {

    private SocketFactory socketFactory;
    private Socket socket;

    public MySocketFactory() {
        this.socketFactory = SocketFactory.getDefault();
    }

    public MySocketFactory(SocketFactory socketFactory) {
        this.socketFactory = socketFactory;
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException {
        socket = this.socketFactory.createSocket(host, port);
        modifySocket();
        return socket;
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
        socket = socketFactory.createSocket(host, port, localHost, localPort);
        modifySocket();
        return socket;
    }

    @Override
    public Socket createSocket(InetAddress host, int port) throws IOException {
        socket = socketFactory.createSocket(host, port);
        modifySocket();
        return socket;
    }

    @Override
    public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
        socket = socketFactory.createSocket(address, port, localAddress, localPort);
        modifySocket();
        return socket;
    }

    @Override
    public Socket createSocket() throws IOException {
        socket = socketFactory.createSocket();
        modifySocket();
        return socket;
    }

    private void modifySocket() throws IOException {
        socket.setKeepAlive(true);
        socket.setSoTimeout(10 * 1000);
        socket.setSoLinger(true, 0);
        socket.setTcpNoDelay(true);
    }
}
String broker = Statics.broker;
// mqtt paho client id
clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(MyMqttService.this, broker,
                        clientId, new MemoryPersistence());

MqttConnectOptions options = new MqttConnectOptions();
options.setAutomaticReconnect(false);
options.setCleanSession(true);
options.setUserName(""test");
options.setPassword("test".toCharArray());
options.setConnectionTimeout(20);
options.setKeepAliveInterval(0);

MySocketFactory mySocketFactory=new MySocketFactory();
options.setSocketFactory(mySocketFactory);

Maximum simultaneous connections on a mosquitto broker

nano /etc/sysctl.conf
fs.file-max = 999999
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 4096 16777216
net.ipv4.tcp_wmem = 4096 4096 16777216
net.ipv4.tcp_syncookies = 1
# this gives the kernel more memory for tcp
# which you need with many (100k+) open socket connections
net.ipv4.tcp_mem = 50576   64768   98152
net.core.netdev_max_backlog = 2500
nano /etc/security/limits.conf
*       soft    nofile  262144
*       hard    nofile  262144
*       soft    nproc  262144
*       hard    nproc  262144
cat /proc/sys/net/ipv4/ip_local_port_range
cat /proc/sys/kernel/threads-max
nano .bashrc
ulimit -t unlimited
ulimit -c unlimited
ulimit -a

References
https://lists.launchpad.net/mosquitto-users/msg00163.html

How to Install and Secure the Mosquitto MQTT Messaging Broker on Ubuntu 16.04

Installing Mosquitto

sudo add-apt-repository ppa:mosquitto-dev/mosquitto-ppa
sudo apt-get update
sudo apt-get install mosquitto mosquitto-clients

Installing Certbot for Let’s Encrypt Certificates

sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install certbot

Running Certbot

sudo ufw allow 80
sudo ufw allow 443
sudo certbot certonly --standalone

Enter your domain : mqtt.example.com

Setting up Certbot Automatic Renewals

sudo crontab -e
. . .
15 3 * * * certbot renew --noninteractive --post-hook "systemctl restart mosquitto"

Configuring MQTT Passwords

sudo mosquitto_passwd -c /etc/mosquitto/passwd sammy
sudo nano /etc/mosquitto/conf.d/default.conf
allow_anonymous false
password_file /etc/mosquitto/passwd
sudo systemctl restart mosquitto

Configuring MQTT SSL

sudo nano /etc/mosquitto/conf.d/default.conf
. . .
listener 1883 localhost

listener 8883
certfile /etc/letsencrypt/live/mqtt.example.com/cert.pem
cafile /etc/letsencrypt/live/mqtt.example.com/chain.pem
keyfile /etc/letsencrypt/live/mqtt.example.com/privkey.pem
sudo systemctl restart mosquitto
sudo ufw allow 8883

References
https://www.digitalocean.com/community/tutorials/how-to-install-and-secure-the-mosquitto-mqtt-messaging-broker-on-ubuntu-16-04

Publish a Message From Android on MQTT

AndroidManifest.xml

    <!-- Permissions the Application Requires -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <!--<uses-permission android:name="android.permission.READ_PHONE_STATE" />-->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />

And register our MQTT Android Service in our app before the closing tag by adding this line:

 <service android:name="org.eclipse.paho.android.service.MqttService" />

Java

public class MqttManager {

    MqttAndroidClient mqtt=null;

    public void publishTest() throws MqttException {

        try
        {
            String clientId= MqttClient.generateClientId();
            mqtt=new MqttAndroidClient(CachePupli.context,"tcp://192.168.1.2:1883",clientId);
            MqttConnectOptions connectOptions=new MqttConnectOptions();
            connectOptions.setAutomaticReconnect(true);
            connectOptions.setCleanSession(true);
            IMqttToken token= mqtt.connect(connectOptions);
            token.setActionCallback(onConnect);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }


    private IMqttActionListener onConnect=new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken asyncActionToken) {

            MqttMessage message=new MqttMessage("Hello World".getBytes());
            try {
                mqtt.publish("test",message);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {

        }
    };
}

References
https://www.eclipse.org/paho/clients/android/
https://wildanmsyah.wordpress.com/2017/05/11/mqtt-android-client-tutorial/

Install Mosquitto MQTT Messaging Broker on Ubuntu 16.04

sudo apt-get install mosquitto mosquitto-clients

Test

mosquitto_sub -h localhost -t test
mosquitto_pub -h localhost -t test -m "hello world"

Configuring MQTT Passwords

sudo mosquitto_passwd -c /etc/mosquitto/passwd sammy
sudo nano /etc/mosquitto/conf.d/default.conf
allow_anonymous false
password_file /etc/mosquitto/passwd
sudo systemctl restart mosquitto

References
https://www.digitalocean.com/community/tutorials/how-to-install-and-secure-the-mosquitto-mqtt-messaging-broker-on-ubuntu-16-04