How to Integrate MQTT Telegram Alarm on Robustel's RobustOS Pro Devices

How to Integrate MQTT-Telegram Alarm

Overview

This guide explains how to integrate MQTT alarm messages with Telegram on Robustel's RobustOS Pro. It applies to users who need a basic notification workflow where the gateway acts as an MQTT broker and forwards alarm messages to a Telegram chat through a bot. By following the article, users will create a Telegram bot, obtain the chat ID, install the required packages, create the integration script, and test whether MQTT alarm messages can trigger Telegram notifications.

Prerequisites

  1. ROS PRO device with network connection
  2. Telegram account

Step 1: Create Telegram Bot

  1. Open Telegram app
  2. Search for "@BotFather"
  3. Start chat and send /newbot command
  4. Choose a name for your bot
  5. Save the API token you receive (looks like 123456789:ABCdefGHIjklMNOpqrsTUVwxyz)

Step 2: Get Your Chat ID

  1. Start a chat with your new bot
  2. Send any message to the bot
  3. Open in browser: https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates
  4. Find your chat ID in the response (it's a number like 271084513)

Step 3: Install Required Packages

sudo apt-get update
sudo apt-get install python3-requests mosquitto python3-paho-mqtt mosquitto-clients

Step 4: Create Integration Script

Create a new file mqtt_telegram.py:
#!/usr/bin/env python3
import paho.mqtt.client as mqtt
import requests
import json
import sys
from typing import Optional

class AlarmMonitor:
def __init__(self):
# Telegram settings
self.token = "YOUR_BOT_TOKEN" # Replace with your bot token
self.chat_id = "YOUR_CHAT_ID" # Replace with your chat ID

# MQTT settings
self.mqtt_host = "localhost"
self.mqtt_port = 1883
self.mqtt_topic = "alarms/#" # Subscribe to all alarm topics

# Initialize MQTT client
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message

print("Alarm Monitor starting...")

def on_connect(self, client, userdata, flags, rc):
"""Callback when connected to MQTT broker"""
if rc == 0:
print("Connected to MQTT broker")
# Subscribe to alarm topics
self.client.subscribe(self.mqtt_topic)
print(f"Subscribed to topic: {self.mqtt_topic}")
else:
print(f"Failed to connect to MQTT broker with code: {rc}")

def on_message(self, client, userdata, msg):
"""Callback when message is received"""
try:
# Try to parse message as JSON
payload = msg.payload.decode()
try:
alarm_data = json.loads(payload)
message = self.format_alarm_message(msg.topic, alarm_data)
except json.JSONDecodeError:
# If not JSON, treat as plain text
message = self.format_alarm_message(msg.topic, payload)

# Send to Telegram
self.send_telegram_message(message)

except Exception as e:
print(f"Error processing message: {str(e)}", file=sys.stderr)
sys.stderr.flush()

def format_alarm_message(self, topic: str, data: dict) -> str:
"""Format alarm data into readable message"""
message = f"🚨 ALARM NOTIFICATION 🚨\n"
message += f"Topic: {topic}\n"

if isinstance(data, dict):
for key, value in data.items():
message += f"{key}: {value}\n"
else:
message += f"Message: {data}\n"

return message

def send_telegram_message(self, message: str) -> None:
"""Send message to Telegram"""
url = f"https://api.telegram.org/bot{self.token}/sendMessage"
data = {'chat_id': self.chat_id, 'text': message}
try:
response = requests.post(url, data=data)
if not response.ok:
print(f"Failed to send Telegram message: {response.text}")
except Exception as e:
print(f"Error sending to Telegram: {str(e)}")

def run(self):
"""Start the monitor"""
try:
# Connect to MQTT broker
self.client.connect(self.mqtt_host, self.mqtt_port, 60)

# Start the loop
self.client.loop_forever()
except KeyboardInterrupt:
print("\nMonitoring stopped")
self.client.disconnect()
sys.exit(0)
except Exception as e:
print(f"Error running monitor: {str(e)}")
sys.exit(1)

if __name__ == '__main__':
monitor = AlarmMonitor()
monitor.run()

Step 5: Configure MQTT Broker

Create/edit the Mosquitto configuration:
sudo nano /etc/mosquitto/mosquitto.conf

Add this content:

listener 1883
allow_anonymous true

Step 6: Create System Services

1. Create MQTT broker service:
sudo nano /etc/systemd/system/mqtt_broker.service

Add content:

[Unit]
Description=Mosquitto MQTT Broker
After=network.target

[Service]
Type=simple
ExecStart=/usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf
Restart=always

[Install]
WantedBy=multi-user.target

2. Create integration service:
sudo nano /etc/systemd/system/mqtt_telegram.service

Add content:

[Unit]
Description=MQTT-Telegram Alarm Integration
After=network.target mosquitto.service

[Service]
ExecStart=/full/path/to/mqtt_telegram.py
Restart=always
User=your_username

[Install]
WantedBy=multi-user.target

Step 7: Start Services

sudo systemctl enable mosquitto
sudo systemctl start mosquitto
sudo systemctl enable mqtt_telegram
sudo systemctl start mqtt_telegram

Testing

To test if everything works:
1. Subscribe to alarms in a terminal window:
mosquitto_sub -t "alarms/#"
2. In another terminal, publish a test alarm:
mosquitto_pub -t "alarms/test" -m "{'type': 'test_alarm', 'severity': 'high'}"
You should see:
  1. The message appear in your subscription terminal
  2. A notification in your Telegram chat

Troubleshooting

Check service status:
sudo systemctl status mosquitto
sudo systemctl status mqtt_telegram

View logs:

journalctl -u mqtt_telegram -f

Integration

Other applications can publish alarms using:
  1. Host: localhost (or device IP)
  2. Port: 1883
  3. Topic: alarms/# (or any subtopic under alarms/)
Example message format:
{
"type": "temperature_alert",
"severity": "high",
"value": "35.5",
"unit": "C"
}



FAQs

Q1: What should I prepare before setting up MQTT Telegram alarm notifications?
A: Prepare a network connected RobustOS Pro device a Telegram account a bot token and the chat ID required by the script
Q2: What should I check if Telegram messages are not received?
A: Confirm the bot token chat ID MQTT broker connection and subscribed alarm topic used in the original script
Q3: Should the Python script be changed for different alarm topics?
A: Only change script variables when the target MQTT topics and alarm message format are confirmed

Conclusion

After completing this guide, the Robustel's RobustOS Pro should be able to receive MQTT alarm messages and forward them to Telegram through the configured bot. Users should verify that the MQTT broker connection is successful, the script subscribes to the alarm topic, and Telegram receives the expected notification. Avoid changing the script logic unless reviewed by a technical owner.
    • Related Articles

    • How to Integrate WhatsApp Alarm Systems on RobustOS Pro Gateways

      In today's interconnected industrial environments, timely notifications about critical events can prevent costly downtime and rapid response to potential issues. As a leading provider of industrial IoT solutions, Robustel continues to innovate with ...
    • Edge Gateway Main Page

      Edge Gateway Configuration & Development Your central hub for mastering Robustel Edge Gateways, tailored for developers and system integrators. From basic device configuration to advanced application development and third-party integration, find the ...
    • How to Set up Bidirectional SMS Integration with Telegram

      This guide describes how to set up bidirectional SMS integration with Telegram on a RobustOS Pro device. After setup, you'll be able to: Receive device SMS messages in your Telegram chat Send SMS from Telegram using simple commands Prerequisites ...
    • How to Configure LoRa to MQTT

      This guide provides a detailed walkthrough for using a Robustel R1520LG gateway to transmit data from LoRa nodes to a cloud-based MQTT broker. This setup leverages the built-in ChirpStack Network Server and the Edge2Cloud (E2C) framework to achieve a ...
    • How to Deploy Zabbix and SNMP Data Simulation via MQTT on RobustOS Pro

      Overview When using Robustel's edge computing gateways (such as the MG460) running RobustOS Pro, users may need to monitor end-device data using Zabbix via SNMP and MQTT protocols. This comprehensive deployment solution bridges end-devices to a ...