How to Integrate MQTT-Telegram Alarm

How to Integrate MQTT-Telegram Alarm

This guide explains how to set up a system where your ROS PRO device acts as an MQTT broker and forwards alarm messages to Telegram.

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"
}




    • 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 ...
    • 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 Integrate RCMS API with Python

      Project Setup 1. Create project directory: mkdir rcms_api cd rcms_api 2. Install required dependencies with pip for e.x.: python -m pip install requests 3. Create main client file rcms_client.py: import hashlib import hmac import json import time ...
    • How to Convert LoRa to Modbus

      ? Executive Summary Our gateway solution seamlessly connects LoRaWAN sensor networks with industrial Modbus systems by leveraging Chirpstack's IoT stack. This middleware enables long-range IoT sensors to integrate directly with industrial control ...