How to Connect With MQTT Broker & Publish Test Message to MQTT Topic from A9G Board & Python via Cellular Connectivity

Introduction:

In the realm of IoT, connectivity is key. But what if you find yourself in a scenario where conventional internet options like Wi-Fi or Ethernet are unavailable? Enter the A9G module, a versatile solution that leverages 2G cellular connectivity to bridge the gap. In this guide, we’ll explore how to harness the power of the A9G module to establish a connection with an MQTT broker and enable remote monitoring using Python.

Prerequisites:

Before diving into the implementation, ensure you have the following:

  • A9G module.

  • Airtel SIM card or any compatible SIM for cellular connectivity especially 2G.

  • USB to Serial Converter (CP2102) for interfacing with the A9G module.

  • Basic understanding of Python and AT commands.

Connection Diagram:

To get started, set up your hardware as follows:

  1. Connect the A9G module to your computer using the USB to Serial Converter.
  2. Insert your SIM card into the A9G module.
  3. Ensure proper power supply to the A9G module.

Coding:

Now, let’s dive into the coding part. We’ll use Python to send AT commands to the A9G module and establish an MQTT connection. Here’s a basic outline of the steps involved:

  1. Initialize serial communication with the A9G module.
  2. Send AT commands to enable GPRS connectivity and configure APN settings.
  3. Connect to the MQTT broker using AT commands.
  4. Publish data to the desired MQTT topic.

 

Here’s a snippet of Python code to illustrate the process:

				
					import serial
import time

# MQTT broker details
mqtt_host = ""
mqtt_port = ""
mqtt_user = ""
mqtt_password = ""
mqtt_topic = ""  # Topic to publish messages

# Function to send AT command
def send_command(command):
    ser.write((command + '\r\n').encode())
    time.sleep(1)
    response = ser.read(ser.inWaiting()).decode()
    return response


# Function to connect to MQTT broker
def connect_to_mqtt(host, port, user, password):
    send_command('AT+CGATT=1')
    send_command('AT+CGDCONT=1,"IP","CMNET"')
    send_command('AT+CGACT=1,1')
    command = 'AT+MQTTCONN="{}",{},12345,120,0,"{}","{}"'.format(host, port, user, password)
    send_command(command)

# Function to publish message to MQTT broker
def publish_message(topic, message):
    command = 'AT+MQTTPUB="{}","{}",0,0,0'.format(topic, message)
    send_command(command)

# Function to disconnect from MQTT broker
def disconnect_mqtt():
    send_command('AT+MQTTDISCONN')

# Main code
if __name__ == "__main__":
    # Open serial connection to the A9G module
    ser = serial.Serial('COMX', 115200, timeout=1)

    # Wait for the module to initialize
    time.sleep(2)

    try:
        # Connect to MQTT broker
        print("Connecting to MQTT broker...")
        connect_to_mqtt(mqtt_host, mqtt_port, mqtt_user, mqtt_password)
        print("Connected to MQTT broker")

        # Publish test message
        print("Publishing test message...")
        publish_message(mqtt_topic, "This is a test message - 3")
        print("Test message published")

        # Disconnect from MQTT broker
        print("Disconnecting from MQTT broker...")
        disconnect_mqtt()
        print("Disconnected from MQTT broker")

    except Exception as e:
        print("An error occurred:", e)

    # Close serial connection
    ser.close()
				
			

Testing:

After coding, it’s time to test our setup. Execute the Python script and monitor the output for any errors or successful connections. Verify data transmission by checking the MQTT broker for published messages.

Conclusion:

In conclusion, we’ve demonstrated how to utilize the A9G module and Python to establish a cellular IoT gateway. By leveraging 2G connectivity and AT commands, we’ve enabled remote monitoring and data transmission to an MQTT broker. This solution provides flexibility in scenarios where traditional internet options are unavailable, making it a valuable tool for IoT applications.