Home About us Support Partners

MQTT Client Connectivity via Mobile App

Text Copied
Introduction

This documentation offers a comprehensive guide to integrating our CrystalMQ broker or any MQTT broker of your choice with mobile applications on Android and iOS. It covers fundamental tasks such as establishing connections, subscribing to topics, unsubscribing, and exchanging messages. By following these steps, you can seamlessly implement MQTT communication within your mobile applications.

Pre-requisites

Before proceeding, ensure you have

  • Any working MQTT broker instance accessible over the network.
  • Android Studio or Xcode installed for Android or iOS development respectively.
  • Basic familiarity with Android and iOS development environments.
Setting up development environment

1. Android environment setup

  • Open Android Studio and create a new project.
  • Add the MQTT Paho library to your project by including the following dependency in your build.gradle file:
  • python -m venv myenv
    source myenv/bin/activate # On Windows use `myenv\Scripts\activate`

  • Ensure your app has appropriate permissions for internet access by adding the following line to your AndroidManifest.xml:
  • python -m venv myenv
    source myenv/bin/activate # On Windows use `myenv\Scripts\activate`

2. iOS environment setup

  • Launch Xcode and create a new project.
  • Integrate the MQTT client library using CocoaPods. Add the following to your Podfile:
  • python -m venv myenv
    source myenv/bin/activate # On Windows use `myenv\Scripts\activate`

  • Install the dependencies by running 'pod install' in your project directory.
  • python -m venv myenv
    source myenv/bin/activate # On Windows use `myenv\Scripts\activate`

MQTT over TCP

To connect your mobile app to the chosen MQTT broker over TCP:

1. Android

code

2.iOS

code

MQTT over Secure Port

Connecting securely via SSL/TLS to the MQTT broker.

1. Android

code

2.iOS

code

MQTT over Websocket

Establishing MQTT connection over websocket for scenarios where direct MQTT connections are blocked :

1. Android

code

iOS

code

Configuring MQTT authentication

Configure authentication credentials to securely connect your app to the MQTT broker:

1. Authentication Parameters:

  • username
  • password
  • Client ID (optional but recommended for unique identification)

2. Setting Credentials:

To secure your connection with authentication, use :

code

Ensure to handle authentication securely by storing credentials in a safe manner, such as using encrypted storage on mobile devices.

Advanced MQTT Features

1. Last Will & Testament

Implement the Last Will and Testament feature to have the broker publish a predefined message if the client unexpectedly disconnects. This ensures subscribers are informed about the client’s status.

code

2. Retain messages

Enable the retain flag when publishing a message to instruct the broker to store the last message for each topic. This allows new subscribers to receive the most recent message immediately upon connection.

code

3. Keep Alive

MQTT uses a keep-alive mechanism to maintain client-broker connections. Adjust the keepalive parameter to control how frequently the client sends PINGREQ messages to the broker.

code

4. QoS Levels

MQTT offers three QoS levels for message delivery:

  • QoS 0 (At most once)
  • QoS 1 (At least once)
  • QoS 2 (Exactly once)

Specify the desired QoS level when publishing MQTT messages to ensure the appropriate delivery guarantee.

code

5. Persistent Sessions

MQTT sessions can be configured as:

  • Clean Session: Start fresh with no stored state on the broker (`clean: true`).
  • Persistent Session: Retain subscriptions and queued messages (`clean: false`).

Configure MQTT session persistence as needed using the provided code snippet.

code

Data Receiving & Sending

These sections provide essential functionalities for managing data flow in your MQTT-connected Android application, facilitating both publishing and subscribing operations effectively.

Publish

Efficiently distribute data to multiple subscribers by sending it to specific topics using the provided code snippet:

code

Subscribe

Receive real-time updates from subscribed topics to handle information flow responsively using the following code snippet:

code

Unsubscribe Topics

To stop receiving updates from specific topics with a designated Quality of Service (QoS) level, use the provided code snippet:

code

Building Your Business Logic

You have the opportunity to develop and customize your own intricate business logic within this environment, tailoring it precisely to your specific needs and objectives.

Write your own code!

For a more comprehensive understanding of the origins and methods of acquiring data for monitoring purposes, be sure to explore our detailed data acquisition page.

MQTT 5 Property Setup

Our CrystalMQ broker fully complies with MQTT 5, introducing new features that enhance protocol functionality and flexibility. These properties provide detailed control over client-broker interactions, improving session management and message handling. Below, we detail essential configurations for CONNECT and PUBLISH operations.

CONNECT Properties

MQTT CONNECT properties encompass additional metadata or settings included during client-broker connection establishment. These configurations, such as session expiry intervals and maximum packet sizes, optimize the initial setup for secure and reliable communication.

1. Session Expiry Interval

The 'Session expiry interval' property defines how long session information persists after client disconnection, maintaining continuity across reconnects.

code

2. Maximum Packet Size

The 'Maximum packet size' property specifies the largest MQTT packet a client can handle, controlling data transmission effectively.

code

PUBLISH Properties

MQTT PUBLISH properties enhance message handling with additional attributes or instructions for brokers and clients. These properties, including message expiry intervals and topic aliases, ensure precise message delivery and network optimization.

1. Message Expiry Interval

The 'Message expiry interval' property sets a message's lifespan in seconds; if undelivered within this time, the broker discards it.

code

2. Topic Alias

The 'Topic Alias' property enables clients to use a compact alias instead of the full topic name, reducing message size and optimizing network bandwidth.

code

Disconnecting from the MQTT Broker

Ensure a proper disconnection from the connected broker by invoking client.end() when communication is no longer required. This action frees up resources and facilitates a smooth termination of the MQTT session.

To disconnect from the MQTT broker, use the following code snippet:

code

Best Practices for MQTT Integration

1. Effective Error Handling

Implement strong error handling to effectively manage MQTT connection failures, subscription issues, and message publishing errors.

2. Securing Access Credentials

Protect sensitive information such as usernames, passwords, and client IDs by avoiding their inclusion in your source code. Instead, utilize environment variables or secure configuration files.

3. Continuous Testing & Monitoring

Regularly test MQTT communication and monitor critical client metrics such as connection status, message throughput, and error rates. This proactive approach helps in detecting and resolving issues promptly.

4. Managing Session Persistence

Choose between clean and persistent MQTT sessions (`clean: true` or `clean: false`) based on your requirements to either start fresh or retain subscriptions and queued messages across client connections.

Download Code

Download the complete Mobile app MQTT client code to connect your client with our CrystalMQ broker or any broker of your choice.

code

Create Executable Bundle

Begin by downloading and installing the compiler directly from the official website. Once you've set up the compiler, seamlessly connect your client to our state-of-the-art CrystalMQ broker or any broker of your choice. This powerful combination will ensure optimal performance and reliability for all your messaging needs, paving the way for a robust and efficient system integration.