- Fix blocking MQTT reconnect in callback thread that caused complete bot freeze - Replace blocking queue.get() with non-blocking approach in asyncio context - Add message queue size limit to prevent memory exhaustion - Implement health monitoring system for MQTT and Telegram components - Add retry logic with exponential backoff for Telegram API calls - Add /status command for real-time bot health diagnostics - Improve thread safety with proper locks for shared resources - Add periodic health check task with automatic recovery triggers - Enhance logging with thread names and better error tracking This fixes the silent hanging issue where bot would stop processing messages without any error logs and required manual restart.
506 lines
18 KiB
Python
506 lines
18 KiB
Python
import logging
|
|
import os
|
|
import threading
|
|
import asyncio
|
|
import queue
|
|
import time
|
|
import datetime
|
|
import base64
|
|
from collections import OrderedDict
|
|
from contextlib import contextmanager
|
|
|
|
import paho.mqtt.client as mqtt
|
|
from telegram import Update
|
|
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
|
|
from Crypto.Cipher import AES
|
|
|
|
import config
|
|
from node_db import NodeDatabase
|
|
|
|
try:
|
|
from meshtastic import mesh_pb2, portnums_pb2, mqtt_pb2
|
|
except ImportError:
|
|
import meshtastic.mesh_pb2 as mesh_pb2
|
|
import meshtastic.portnums_pb2 as portnums_pb2
|
|
import meshtastic.mqtt_pb2 as mqtt_pb2
|
|
|
|
# Configure logging
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format='%(asctime)s [%(levelname)s] [%(threadName)s] %(message)s',
|
|
datefmt='%Y-%m-%d %H:%M:%S'
|
|
)
|
|
|
|
# Suppress verbose Telegram HTTP logs
|
|
logging.getLogger("httpx").setLevel(logging.WARNING)
|
|
logging.getLogger("telegram.vendor.ptb_urllib3.urllib3.connectionpool").setLevel(logging.WARNING)
|
|
logging.getLogger("telegram.request").setLevel(logging.WARNING)
|
|
logging.getLogger("telegram.bot").setLevel(logging.WARNING)
|
|
|
|
# Constants
|
|
SUBSCRIBERS_FILE = "subscribers.txt"
|
|
BROADCAST_KEY = b'\x01' * 16
|
|
RECENT_IDS_MAX = 500
|
|
MESSAGE_QUEUE_MAX = 1000
|
|
HEALTH_CHECK_INTERVAL = 60 # seconds
|
|
MQTT_KEEPALIVE = 60
|
|
MQTT_RECONNECT_MAX_DELAY = 60
|
|
MQTT_RECONNECT_MIN_DELAY = 5
|
|
TELEGRAM_RETRY_DELAY = 5
|
|
TELEGRAM_MAX_RETRIES = 3
|
|
|
|
# Global state
|
|
message_queue = queue.Queue(maxsize=MESSAGE_QUEUE_MAX)
|
|
recent_ids = OrderedDict()
|
|
recent_ids_lock = threading.Lock()
|
|
node_db = NodeDatabase("nodes.db")
|
|
subscribers_lock = threading.Lock()
|
|
last_mqtt_message_time = time.time()
|
|
last_mqtt_message_lock = threading.Lock()
|
|
mqtt_client = None
|
|
mqtt_connected = False
|
|
mqtt_reconnect_event = threading.Event()
|
|
|
|
|
|
class HealthMonitor:
|
|
"""Monitor the health of different components"""
|
|
|
|
def __init__(self):
|
|
self.last_mqtt_activity = time.time()
|
|
self.last_telegram_activity = time.time()
|
|
self.lock = threading.Lock()
|
|
|
|
def update_mqtt(self):
|
|
with self.lock:
|
|
self.last_mqtt_activity = time.time()
|
|
|
|
def update_telegram(self):
|
|
with self.lock:
|
|
self.last_telegram_activity = time.time()
|
|
|
|
def check_health(self, timeout=300):
|
|
"""Check if components are healthy (active within timeout seconds)"""
|
|
with self.lock:
|
|
now = time.time()
|
|
mqtt_healthy = (now - self.last_mqtt_activity) < timeout
|
|
telegram_healthy = (now - self.last_telegram_activity) < timeout
|
|
return {
|
|
'mqtt_healthy': mqtt_healthy,
|
|
'telegram_healthy': telegram_healthy,
|
|
'mqtt_last_seen': int(now - self.last_mqtt_activity),
|
|
'telegram_last_seen': int(now - self.last_telegram_activity)
|
|
}
|
|
|
|
|
|
health_monitor = HealthMonitor()
|
|
|
|
|
|
def load_subscribers():
|
|
"""Load subscriber list from file"""
|
|
with subscribers_lock:
|
|
if not os.path.exists(SUBSCRIBERS_FILE):
|
|
return set()
|
|
try:
|
|
with open(SUBSCRIBERS_FILE, "r") as f:
|
|
return set(int(line.strip()) for line in f if line.strip())
|
|
except Exception as e:
|
|
logging.error(f"Failed to load subscribers: {e}")
|
|
return set()
|
|
|
|
|
|
def save_subscribers(subscribers):
|
|
"""Save subscriber list to file"""
|
|
with subscribers_lock:
|
|
try:
|
|
with open(SUBSCRIBERS_FILE, "w") as f:
|
|
for chat_id in subscribers:
|
|
f.write(f"{chat_id}\n")
|
|
except Exception as e:
|
|
logging.error(f"Failed to save subscribers: {e}")
|
|
|
|
|
|
subscribers = load_subscribers()
|
|
|
|
|
|
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
"""Handle /start command"""
|
|
chat_id = update.effective_chat.id
|
|
if chat_id not in subscribers:
|
|
subscribers.add(chat_id)
|
|
save_subscribers(subscribers)
|
|
await update.message.reply_text("You are now subscribed to Meshtastic messages!")
|
|
logging.info(f"User {chat_id} subscribed.")
|
|
else:
|
|
await update.message.reply_text("You are already subscribed.")
|
|
|
|
|
|
async def status(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
"""Handle /status command to check bot health"""
|
|
try:
|
|
health = health_monitor.check_health()
|
|
queue_size = message_queue.qsize()
|
|
current_subscribers = load_subscribers()
|
|
|
|
status_msg = (
|
|
f"📊 Bot Status:\n"
|
|
f"MQTT: {'✅' if health['mqtt_healthy'] else '❌'} (last: {health['mqtt_last_seen']}s ago)\n"
|
|
f"Telegram: {'✅' if health['telegram_healthy'] else '❌'} (last: {health['telegram_last_seen']}s ago)\n"
|
|
f"Queue: {queue_size}/{MESSAGE_QUEUE_MAX} messages\n"
|
|
f"MQTT Connected: {'✅' if mqtt_connected else '❌'}\n"
|
|
f"Subscribers: {len(current_subscribers)}"
|
|
)
|
|
|
|
await update.message.reply_text(status_msg)
|
|
logging.info(f"Status command executed by {update.effective_chat.id}")
|
|
except Exception as e:
|
|
logging.error(f"Error in status command: {e}")
|
|
await update.message.reply_text(f"❌ Error getting status: {str(e)}")
|
|
|
|
|
|
def decrypt_payload_ctr(encrypted, packet_id, from_id, key=BROADCAST_KEY):
|
|
"""Decrypt Meshtastic payload using AES CTR mode"""
|
|
try:
|
|
nonce = packet_id.to_bytes(8, 'little') + from_id.to_bytes(8, 'little')
|
|
cipher = AES.new(key, AES.MODE_CTR, nonce=nonce)
|
|
decrypted = cipher.decrypt(encrypted)
|
|
return decrypted
|
|
except Exception as e:
|
|
logging.warning(f"Decryption error (CTR): {e}")
|
|
return None
|
|
|
|
|
|
def is_duplicate(packet_id):
|
|
"""Check if packet_id is a duplicate"""
|
|
with recent_ids_lock:
|
|
if packet_id in recent_ids:
|
|
return True
|
|
recent_ids[packet_id] = True
|
|
if len(recent_ids) > RECENT_IDS_MAX:
|
|
recent_ids.popitem(last=False)
|
|
return False
|
|
|
|
|
|
def format_meshtastic_message(packet):
|
|
"""Format Meshtastic packet for Telegram"""
|
|
try:
|
|
if packet.HasField("decoded"):
|
|
decoded = packet.decoded
|
|
|
|
# Handle NodeInfo messages
|
|
if decoded.portnum == portnums_pb2.NODEINFO_APP:
|
|
try:
|
|
node_info = mesh_pb2.User()
|
|
node_info.ParseFromString(decoded.payload)
|
|
from_id = getattr(packet, 'from')
|
|
|
|
node_db.update_node(
|
|
node_id=from_id,
|
|
short_name=node_info.short_name if node_info.short_name else None,
|
|
long_name=node_info.long_name if node_info.long_name else None,
|
|
hw_model=str(node_info.hw_model) if hasattr(node_info, 'hw_model') else None,
|
|
role=str(node_info.role) if hasattr(node_info, 'role') else None
|
|
)
|
|
logging.info(f"Updated NodeInfo for {from_id}: {node_info.short_name}/{node_info.long_name}")
|
|
except Exception as e:
|
|
logging.warning(f"Failed to parse NodeInfo: {e}")
|
|
return None, None
|
|
|
|
# Handle text messages
|
|
elif decoded.portnum == portnums_pb2.TEXT_MESSAGE_APP:
|
|
text = decoded.payload.decode(errors='replace')
|
|
from_id = getattr(packet, 'from')
|
|
to_id = packet.to
|
|
|
|
# Filter: only forward broadcast messages
|
|
if to_id != 4294967295:
|
|
logging.info(f"Message to {to_id} ignored (not broadcast)")
|
|
return None, None
|
|
|
|
rssi = packet.rx_rssi
|
|
hop_start = packet.hop_start
|
|
hops_away = getattr(packet, 'hops_away', None)
|
|
timestamp = packet.rx_time
|
|
|
|
if timestamp:
|
|
ts_str = datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
|
|
else:
|
|
ts_str = "N/A"
|
|
|
|
# Get human-readable names
|
|
from_name = node_db.get_node_name(from_id)
|
|
to_name = "broadcast" if to_id == 4294967295 else node_db.get_node_name(to_id)
|
|
actual_hops = hops_away if hops_away is not None else hop_start
|
|
|
|
# Format message for Telegram (HTML)
|
|
text_html = f"<b>{text}</b>"
|
|
msg = f"{ts_str}\n{text_html}\n{from_name} to {to_name}\nRSSI: {rssi}\nHop(s): {actual_hops}"
|
|
return msg, 'HTML'
|
|
except Exception as e:
|
|
logging.warning(f"Protobuf parsing error: {e}")
|
|
return None, None
|
|
|
|
|
|
def on_mqtt_connect(client, userdata, flags, rc):
|
|
"""Handle MQTT connection"""
|
|
global mqtt_connected
|
|
if rc == 0:
|
|
mqtt_connected = True
|
|
client.subscribe(config.MQTT_TOPIC)
|
|
logging.info(f"MQTT connected and subscribed to: {config.MQTT_TOPIC}")
|
|
health_monitor.update_mqtt()
|
|
else:
|
|
mqtt_connected = False
|
|
logging.error(f"MQTT connection failed with code: {rc}")
|
|
|
|
|
|
def on_mqtt_disconnect(client, userdata, rc):
|
|
"""Handle MQTT disconnection"""
|
|
global mqtt_connected
|
|
mqtt_connected = False
|
|
|
|
if rc != 0:
|
|
logging.warning(f"MQTT disconnected unexpectedly (rc={rc})")
|
|
# Set event to trigger reconnection in separate thread
|
|
mqtt_reconnect_event.set()
|
|
else:
|
|
logging.info("MQTT disconnected cleanly")
|
|
|
|
|
|
def on_mqtt_message(client, userdata, msg):
|
|
"""Handle incoming MQTT messages"""
|
|
try:
|
|
health_monitor.update_mqtt()
|
|
|
|
service_envelope = mqtt_pb2.ServiceEnvelope()
|
|
service_envelope.ParseFromString(msg.payload)
|
|
packet = service_envelope.packet
|
|
|
|
# Log received message
|
|
log_id = getattr(packet, 'id', None)
|
|
log_from = getattr(packet, 'from', None)
|
|
log_to = getattr(packet, 'to', None)
|
|
log_portnum = packet.decoded.portnum if packet.HasField('decoded') else None
|
|
logging.info(f"MQTT received: id={log_id}, from={log_from}, to={log_to}, portnum={log_portnum}, len={len(msg.payload)}")
|
|
|
|
# Check for duplicate
|
|
packet_id = packet.id if hasattr(packet, 'id') else None
|
|
if packet_id is not None and is_duplicate(packet_id):
|
|
logging.info(f"Duplicate message id {packet_id}, skipping")
|
|
return
|
|
|
|
# Decrypt if needed
|
|
if packet.HasField("encrypted") and not packet.HasField("decoded"):
|
|
encrypted = packet.encrypted
|
|
packet_id = getattr(packet, 'id', 0)
|
|
from_id = getattr(packet, 'from') if packet.HasField("from") else 0
|
|
decrypted_payload = decrypt_payload_ctr(encrypted, packet_id, from_id)
|
|
|
|
if decrypted_payload:
|
|
try:
|
|
decoded = mesh_pb2.DecodedPacket()
|
|
decoded.ParseFromString(decrypted_payload)
|
|
packet.decoded.CopyFrom(decoded)
|
|
except Exception as e:
|
|
logging.warning(f"Error parsing decrypted payload: {e}")
|
|
return
|
|
else:
|
|
logging.info("Failed to decrypt payload")
|
|
return
|
|
|
|
# Format and queue message
|
|
text, parse_mode = format_meshtastic_message(packet)
|
|
if text:
|
|
try:
|
|
message_queue.put_nowait((text, parse_mode))
|
|
logging.debug(f"Message queued, queue size: {message_queue.qsize()}")
|
|
except queue.Full:
|
|
logging.warning("Message queue is full, dropping oldest message")
|
|
try:
|
|
message_queue.get_nowait()
|
|
message_queue.put_nowait((text, parse_mode))
|
|
except:
|
|
pass
|
|
|
|
# Update last message time
|
|
with last_mqtt_message_lock:
|
|
global last_mqtt_message_time
|
|
last_mqtt_message_time = time.time()
|
|
|
|
except Exception as e:
|
|
logging.error(f"Error processing MQTT message: {e}", exc_info=True)
|
|
|
|
|
|
def mqtt_reconnect_thread():
|
|
"""Handle MQTT reconnection in a separate thread"""
|
|
global mqtt_client, mqtt_connected
|
|
|
|
while True:
|
|
mqtt_reconnect_event.wait()
|
|
mqtt_reconnect_event.clear()
|
|
|
|
if mqtt_connected:
|
|
continue
|
|
|
|
delay = MQTT_RECONNECT_MIN_DELAY
|
|
attempt = 0
|
|
|
|
while not mqtt_connected:
|
|
attempt += 1
|
|
try:
|
|
logging.info(f"Attempting MQTT reconnection (attempt {attempt})")
|
|
if mqtt_client:
|
|
mqtt_client.reconnect()
|
|
logging.info("MQTT reconnected successfully")
|
|
break
|
|
except Exception as e:
|
|
logging.error(f"MQTT reconnection failed: {e}")
|
|
time.sleep(delay)
|
|
delay = min(delay * 2, MQTT_RECONNECT_MAX_DELAY)
|
|
|
|
|
|
def mqtt_thread():
|
|
"""Main MQTT thread"""
|
|
global mqtt_client
|
|
|
|
while True:
|
|
try:
|
|
mqtt_client = mqtt.Client()
|
|
mqtt_client.username_pw_set(config.MQTT_USERNAME, config.MQTT_PASSWORD)
|
|
mqtt_client.on_connect = on_mqtt_connect
|
|
mqtt_client.on_disconnect = on_mqtt_disconnect
|
|
mqtt_client.on_message = on_mqtt_message
|
|
|
|
logging.info(f"Connecting to MQTT broker at {config.MQTT_BROKER}:{config.MQTT_PORT}")
|
|
mqtt_client.connect(config.MQTT_BROKER, config.MQTT_PORT, MQTT_KEEPALIVE)
|
|
|
|
logging.info("Starting MQTT loop")
|
|
mqtt_client.loop_forever()
|
|
|
|
except Exception as e:
|
|
logging.error(f"MQTT thread error: {e}", exc_info=True)
|
|
time.sleep(MQTT_RECONNECT_MIN_DELAY)
|
|
|
|
|
|
async def telegram_forwarder(app):
|
|
"""Forward messages from queue to Telegram subscribers"""
|
|
logging.info("Starting Telegram forwarder")
|
|
|
|
while True:
|
|
try:
|
|
# Non-blocking get with asyncio sleep
|
|
text, parse_mode = None, None
|
|
|
|
if not message_queue.empty():
|
|
msg = message_queue.get_nowait()
|
|
if isinstance(msg, tuple):
|
|
text, parse_mode = msg
|
|
else:
|
|
text = msg
|
|
|
|
# Update health monitor
|
|
health_monitor.update_telegram()
|
|
|
|
# Get current subscribers
|
|
current_subscribers = load_subscribers()
|
|
|
|
if not current_subscribers:
|
|
logging.warning("No subscribers to send message to")
|
|
else:
|
|
sent_count = 0
|
|
failed_count = 0
|
|
|
|
for chat_id in current_subscribers:
|
|
retry_count = 0
|
|
while retry_count < TELEGRAM_MAX_RETRIES:
|
|
try:
|
|
await app.bot.send_message(
|
|
chat_id=chat_id,
|
|
text=text,
|
|
parse_mode=parse_mode
|
|
)
|
|
logging.info(f"Sent to {chat_id}")
|
|
sent_count += 1
|
|
break
|
|
except Exception as e:
|
|
retry_count += 1
|
|
if retry_count >= TELEGRAM_MAX_RETRIES:
|
|
logging.error(f"Failed to send to {chat_id} after {TELEGRAM_MAX_RETRIES} retries: {e}")
|
|
failed_count += 1
|
|
else:
|
|
logging.warning(f"Retry {retry_count} for {chat_id}: {e}")
|
|
await asyncio.sleep(TELEGRAM_RETRY_DELAY)
|
|
|
|
logging.info(f"Message sent to {sent_count} subscribers, {failed_count} failed")
|
|
else:
|
|
# No messages, just sleep
|
|
await asyncio.sleep(0.5)
|
|
|
|
except Exception as e:
|
|
logging.error(f"Error in telegram_forwarder: {e}", exc_info=True)
|
|
await asyncio.sleep(1)
|
|
|
|
|
|
async def health_check_task(app):
|
|
"""Periodic health check task"""
|
|
logging.info("Starting health check task")
|
|
|
|
while True:
|
|
try:
|
|
await asyncio.sleep(HEALTH_CHECK_INTERVAL)
|
|
|
|
health = health_monitor.check_health()
|
|
queue_size = message_queue.qsize()
|
|
|
|
# Log health status
|
|
logging.info(
|
|
f"Health check - MQTT: {health['mqtt_healthy']} ({health['mqtt_last_seen']}s), "
|
|
f"Telegram: {health['telegram_healthy']} ({health['telegram_last_seen']}s), "
|
|
f"Queue: {queue_size}/{MESSAGE_QUEUE_MAX}, "
|
|
f"Connected: {mqtt_connected}"
|
|
)
|
|
|
|
# Trigger MQTT reconnect if unhealthy
|
|
if not health['mqtt_healthy'] and not mqtt_connected:
|
|
logging.warning("MQTT appears unhealthy, triggering reconnection")
|
|
mqtt_reconnect_event.set()
|
|
|
|
except Exception as e:
|
|
logging.error(f"Error in health check: {e}", exc_info=True)
|
|
|
|
|
|
async def post_init(app):
|
|
"""Post-initialization tasks"""
|
|
app.create_task(telegram_forwarder(app))
|
|
app.create_task(health_check_task(app))
|
|
|
|
|
|
def main():
|
|
"""Main entry point"""
|
|
logging.info("Starting Meshtastic to Telegram forwarder")
|
|
|
|
# Start MQTT reconnection thread
|
|
reconnect_thread = threading.Thread(target=mqtt_reconnect_thread, daemon=True, name="MQTT-Reconnect")
|
|
reconnect_thread.start()
|
|
|
|
# Start MQTT thread
|
|
mqtt_thread_handle = threading.Thread(target=mqtt_thread, daemon=True, name="MQTT-Main")
|
|
mqtt_thread_handle.start()
|
|
|
|
# Start Telegram bot
|
|
try:
|
|
app = ApplicationBuilder().token(config.TELEGRAM_BOT_TOKEN).post_init(post_init).build()
|
|
app.add_handler(CommandHandler("start", start))
|
|
app.add_handler(CommandHandler("status", status))
|
|
|
|
logging.info("Starting Telegram bot polling")
|
|
app.run_polling()
|
|
|
|
except KeyboardInterrupt:
|
|
logging.info("Shutting down gracefully")
|
|
except Exception as e:
|
|
logging.error(f"Fatal error: {e}", exc_info=True)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|