fix: resolve bot hanging issues with improved architecture
- 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.
This commit is contained in:
1 parent
92b0ac4eb8
commit
a08ee1b0d8
4 files changed
+1129
-116
No files matched your search
+356
-116
@@ -1,18 +1,20 @@
|
||||
import logging
|
||||
from telegram import Update
|
||||
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
|
||||
import config
|
||||
import os
|
||||
import threading
|
||||
import paho.mqtt.client as mqtt
|
||||
import base64
|
||||
from Crypto.Cipher import AES
|
||||
import datetime
|
||||
import queue
|
||||
import asyncio
|
||||
from collections import OrderedDict
|
||||
import re
|
||||
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:
|
||||
@@ -22,45 +24,106 @@ except ImportError:
|
||||
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] %(message)s',
|
||||
format='%(asctime)s [%(levelname)s] [%(threadName)s] %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
|
||||
# Suppress verbose Telegram HTTP logs and hide token
|
||||
# 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
|
||||
|
||||
# Queue for passing messages between MQTT and Telegram
|
||||
message_queue = queue.Queue()
|
||||
|
||||
# Cache for recent message ids to prevent duplicates
|
||||
recent_ids = OrderedDict()
|
||||
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
|
||||
|
||||
# Initialize node database
|
||||
# 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():
|
||||
if not os.path.exists(SUBSCRIBERS_FILE):
|
||||
return set()
|
||||
with open(SUBSCRIBERS_FILE, "r") as f:
|
||||
return set(int(line.strip()) for line in f if line.strip())
|
||||
"""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):
|
||||
with open(SUBSCRIBERS_FILE, "w") as f:
|
||||
for chat_id in subscribers:
|
||||
f.write(f"{chat_id}\n")
|
||||
"""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)
|
||||
@@ -70,8 +133,32 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
else:
|
||||
await update.message.reply_text("You are already subscribed.")
|
||||
|
||||
# --- MQTT and Meshtastic message handling ---
|
||||
|
||||
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)
|
||||
@@ -81,19 +168,31 @@ def decrypt_payload_ctr(encrypted, packet_id, from_id, key=BROADCAST_KEY):
|
||||
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 to update database
|
||||
# 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')
|
||||
|
||||
# Update node database
|
||||
node_db.update_node(
|
||||
node_id=from_id,
|
||||
short_name=node_info.short_name if node_info.short_name else None,
|
||||
@@ -111,64 +210,91 @@ def format_meshtastic_message(packet):
|
||||
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 database
|
||||
# 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): {hop_start}"
|
||||
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
|
||||
|
||||
# Cache for recent message ids to prevent duplicates
|
||||
def is_duplicate(packet_id, max_size=RECENT_IDS_MAX):
|
||||
if packet_id in recent_ids:
|
||||
return True
|
||||
recent_ids[packet_id] = True
|
||||
if len(recent_ids) > max_size:
|
||||
recent_ids.popitem(last=False)
|
||||
return False
|
||||
|
||||
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):
|
||||
service_envelope = mqtt_pb2.ServiceEnvelope()
|
||||
"""Handle incoming MQTT messages"""
|
||||
try:
|
||||
health_monitor.update_mqtt()
|
||||
|
||||
service_envelope = mqtt_pb2.ServiceEnvelope()
|
||||
service_envelope.ParseFromString(msg.payload)
|
||||
packet = service_envelope.packet
|
||||
# Log every received MQTT message (id, from, to, portnum, length)
|
||||
try:
|
||||
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)}")
|
||||
except Exception as e:
|
||||
logging.warning(f"Failed to log MQTT message meta: {e}")
|
||||
# Check for duplicate by id
|
||||
|
||||
# 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.")
|
||||
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()
|
||||
@@ -176,90 +302,204 @@ def on_mqtt_message(client, userdata, msg):
|
||||
packet.decoded.CopyFrom(decoded)
|
||||
except Exception as e:
|
||||
logging.warning(f"Error parsing decrypted payload: {e}")
|
||||
logging.info(f"MQTT message id={packet_id} not sent: failed to parse decrypted payload.")
|
||||
return
|
||||
else:
|
||||
logging.info("Failed to decrypt payload.")
|
||||
logging.info(f"MQTT message id={packet_id} not sent: failed to decrypt payload.")
|
||||
logging.info("Failed to decrypt payload")
|
||||
return
|
||||
# Format text for Telegram
|
||||
|
||||
# Format and queue message
|
||||
text, parse_mode = format_meshtastic_message(packet)
|
||||
if text:
|
||||
message_queue.put((text, parse_mode))
|
||||
else:
|
||||
logging.info(f"MQTT message id={packet_id} not sent: not a text message or failed to format.")
|
||||
except Exception as e:
|
||||
logging.warning(f"ServiceEnvelope parsing error: {e}")
|
||||
logging.info(f"MQTT message not sent: ServiceEnvelope parsing error.")
|
||||
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
|
||||
|
||||
def on_mqtt_disconnect(client, userdata, rc):
|
||||
if rc != 0:
|
||||
logging.warning(f"MQTT disconnected (rc={rc}). Will attempt to reconnect...")
|
||||
else:
|
||||
logging.info("MQTT disconnected cleanly.")
|
||||
delay = config.MQTT_RECONNECT_DELAY
|
||||
while True:
|
||||
try:
|
||||
client.reconnect()
|
||||
logging.info("MQTT reconnected successfully.")
|
||||
client.subscribe(config.MQTT_TOPIC)
|
||||
logging.info(f"Resubscribed to topic: {config.MQTT_TOPIC}")
|
||||
break
|
||||
except Exception as e:
|
||||
logging.error(f"MQTT reconnect failed: {e}. Next attempt in {delay} seconds.")
|
||||
time.sleep(delay)
|
||||
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():
|
||||
client = mqtt.Client()
|
||||
client.username_pw_set(config.MQTT_USERNAME, config.MQTT_PASSWORD)
|
||||
client.on_message = on_mqtt_message
|
||||
client.on_disconnect = on_mqtt_disconnect
|
||||
try:
|
||||
client.connect(config.MQTT_BROKER, config.MQTT_PORT, 60)
|
||||
except Exception as e:
|
||||
logging.error(f"Initial MQTT connect failed: {e}")
|
||||
# Reconnection attempts will be handled by on_disconnect
|
||||
topic = config.MQTT_TOPIC
|
||||
client.subscribe(topic)
|
||||
logging.info(f"Subscribed to binary topic: {topic}")
|
||||
logging.info("Started Meshtastic binary message forwarder (MQTT thread).")
|
||||
client.loop_forever()
|
||||
"""Main MQTT thread"""
|
||||
global mqtt_client
|
||||
|
||||
async def telegram_forwarder(app):
|
||||
while True:
|
||||
try:
|
||||
text, parse_mode = None, None
|
||||
# Wait for a new message from the queue (blocking, but with timeout for graceful shutdown)
|
||||
msg = await asyncio.get_event_loop().run_in_executor(None, message_queue.get)
|
||||
if isinstance(msg, tuple):
|
||||
text, parse_mode = msg
|
||||
else:
|
||||
text = msg
|
||||
sent = False
|
||||
for chat_id in load_subscribers():
|
||||
try:
|
||||
await app.bot.send_message(chat_id=chat_id, text=text, parse_mode=parse_mode)
|
||||
logging.info(f"Sent to {chat_id}: {text}")
|
||||
sent = True
|
||||
except Exception as e:
|
||||
logging.warning(f"Failed to send message to {chat_id}: {e}")
|
||||
if not sent:
|
||||
logging.info(f"Message was not sent to any subscriber: {text}")
|
||||
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.warning(f"Error in telegram_forwarder: {e}")
|
||||
await asyncio.sleep(0.1)
|
||||
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():
|
||||
# Start MQTT in a separate thread
|
||||
threading.Thread(target=mqtt_thread, daemon=True).start()
|
||||
app = ApplicationBuilder().token(config.TELEGRAM_BOT_TOKEN).post_init(post_init).build()
|
||||
app.add_handler(CommandHandler("start", start))
|
||||
logging.info("Telegram bot started.")
|
||||
app.run_polling()
|
||||
"""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()
|
||||
@@ -0,0 +1,268 @@
|
||||
import logging
|
||||
from telegram import Update
|
||||
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
|
||||
import config
|
||||
import os
|
||||
import threading
|
||||
import paho.mqtt.client as mqtt
|
||||
import base64
|
||||
from Crypto.Cipher import AES
|
||||
import datetime
|
||||
import queue
|
||||
import asyncio
|
||||
from collections import OrderedDict
|
||||
import re
|
||||
import time
|
||||
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
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s [%(levelname)s] %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
|
||||
# Suppress verbose Telegram HTTP logs and hide token
|
||||
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)
|
||||
|
||||
SUBSCRIBERS_FILE = "subscribers.txt"
|
||||
BROADCAST_KEY = b'\x01' * 16
|
||||
|
||||
# Queue for passing messages between MQTT and Telegram
|
||||
message_queue = queue.Queue()
|
||||
|
||||
# Cache for recent message ids to prevent duplicates
|
||||
recent_ids = OrderedDict()
|
||||
RECENT_IDS_MAX = 500
|
||||
|
||||
# Initialize node database
|
||||
node_db = NodeDatabase("nodes.db")
|
||||
|
||||
def load_subscribers():
|
||||
if not os.path.exists(SUBSCRIBERS_FILE):
|
||||
return set()
|
||||
with open(SUBSCRIBERS_FILE, "r") as f:
|
||||
return set(int(line.strip()) for line in f if line.strip())
|
||||
|
||||
def save_subscribers(subscribers):
|
||||
with open(SUBSCRIBERS_FILE, "w") as f:
|
||||
for chat_id in subscribers:
|
||||
f.write(f"{chat_id}\n")
|
||||
|
||||
subscribers = load_subscribers()
|
||||
|
||||
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
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.")
|
||||
|
||||
# --- MQTT and Meshtastic message handling ---
|
||||
def decrypt_payload_ctr(encrypted, packet_id, from_id, key=BROADCAST_KEY):
|
||||
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 format_meshtastic_message(packet):
|
||||
try:
|
||||
if packet.HasField("decoded"):
|
||||
decoded = packet.decoded
|
||||
|
||||
# Handle NodeInfo messages to update database
|
||||
if decoded.portnum == portnums_pb2.NODEINFO_APP:
|
||||
try:
|
||||
node_info = mesh_pb2.User()
|
||||
node_info.ParseFromString(decoded.payload)
|
||||
from_id = getattr(packet, 'from')
|
||||
|
||||
# Update node database
|
||||
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 database
|
||||
from_name = node_db.get_node_name(from_id)
|
||||
to_name = "broadcast" if to_id == 4294967295 else node_db.get_node_name(to_id)
|
||||
|
||||
# Calculate actual hops used (fallback to hop_start if hops_away not available)
|
||||
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
|
||||
|
||||
# Cache for recent message ids to prevent duplicates
|
||||
def is_duplicate(packet_id, max_size=RECENT_IDS_MAX):
|
||||
if packet_id in recent_ids:
|
||||
return True
|
||||
recent_ids[packet_id] = True
|
||||
if len(recent_ids) > max_size:
|
||||
recent_ids.popitem(last=False)
|
||||
return False
|
||||
|
||||
def on_mqtt_message(client, userdata, msg):
|
||||
service_envelope = mqtt_pb2.ServiceEnvelope()
|
||||
try:
|
||||
service_envelope.ParseFromString(msg.payload)
|
||||
packet = service_envelope.packet
|
||||
# Log every received MQTT message (id, from, to, portnum, length)
|
||||
try:
|
||||
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)}")
|
||||
except Exception as e:
|
||||
logging.warning(f"Failed to log MQTT message meta: {e}")
|
||||
# Check for duplicate by id
|
||||
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
|
||||
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}")
|
||||
logging.info(f"MQTT message id={packet_id} not sent: failed to parse decrypted payload.")
|
||||
return
|
||||
else:
|
||||
logging.info("Failed to decrypt payload.")
|
||||
logging.info(f"MQTT message id={packet_id} not sent: failed to decrypt payload.")
|
||||
return
|
||||
# Format text for Telegram
|
||||
text, parse_mode = format_meshtastic_message(packet)
|
||||
if text:
|
||||
message_queue.put((text, parse_mode))
|
||||
else:
|
||||
logging.info(f"MQTT message id={packet_id} not sent: not a text message or failed to format.")
|
||||
except Exception as e:
|
||||
logging.warning(f"ServiceEnvelope parsing error: {e}")
|
||||
logging.info(f"MQTT message not sent: ServiceEnvelope parsing error.")
|
||||
|
||||
def on_mqtt_disconnect(client, userdata, rc):
|
||||
if rc != 0:
|
||||
logging.warning(f"MQTT disconnected (rc={rc}). Will attempt to reconnect...")
|
||||
else:
|
||||
logging.info("MQTT disconnected cleanly.")
|
||||
delay = config.MQTT_RECONNECT_DELAY
|
||||
while True:
|
||||
try:
|
||||
client.reconnect()
|
||||
logging.info("MQTT reconnected successfully.")
|
||||
client.subscribe(config.MQTT_TOPIC)
|
||||
logging.info(f"Resubscribed to topic: {config.MQTT_TOPIC}")
|
||||
break
|
||||
except Exception as e:
|
||||
logging.error(f"MQTT reconnect failed: {e}. Next attempt in {delay} seconds.")
|
||||
time.sleep(delay)
|
||||
|
||||
def mqtt_thread():
|
||||
client = mqtt.Client()
|
||||
client.username_pw_set(config.MQTT_USERNAME, config.MQTT_PASSWORD)
|
||||
client.on_message = on_mqtt_message
|
||||
client.on_disconnect = on_mqtt_disconnect
|
||||
try:
|
||||
client.connect(config.MQTT_BROKER, config.MQTT_PORT, 60)
|
||||
except Exception as e:
|
||||
logging.error(f"Initial MQTT connect failed: {e}")
|
||||
# Reconnection attempts will be handled by on_disconnect
|
||||
topic = config.MQTT_TOPIC
|
||||
client.subscribe(topic)
|
||||
logging.info(f"Subscribed to binary topic: {topic}")
|
||||
logging.info("Started Meshtastic binary message forwarder (MQTT thread).")
|
||||
client.loop_forever()
|
||||
|
||||
async def telegram_forwarder(app):
|
||||
while True:
|
||||
try:
|
||||
text, parse_mode = None, None
|
||||
# Wait for a new message from the queue (blocking, but with timeout for graceful shutdown)
|
||||
msg = await asyncio.get_event_loop().run_in_executor(None, message_queue.get)
|
||||
if isinstance(msg, tuple):
|
||||
text, parse_mode = msg
|
||||
else:
|
||||
text = msg
|
||||
sent = False
|
||||
for chat_id in load_subscribers():
|
||||
try:
|
||||
await app.bot.send_message(chat_id=chat_id, text=text, parse_mode=parse_mode)
|
||||
logging.info(f"Sent to {chat_id}: {text}")
|
||||
sent = True
|
||||
except Exception as e:
|
||||
logging.warning(f"Failed to send message to {chat_id}: {e}")
|
||||
if not sent:
|
||||
logging.info(f"Message was not sent to any subscriber: {text}")
|
||||
except Exception as e:
|
||||
logging.warning(f"Error in telegram_forwarder: {e}")
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
async def post_init(app):
|
||||
app.create_task(telegram_forwarder(app))
|
||||
|
||||
|
||||
def main():
|
||||
# Start MQTT in a separate thread
|
||||
threading.Thread(target=mqtt_thread, daemon=True).start()
|
||||
app = ApplicationBuilder().token(config.TELEGRAM_BOT_TOKEN).post_init(post_init).build()
|
||||
app.add_handler(CommandHandler("start", start))
|
||||
logging.info("Telegram bot started.")
|
||||
app.run_polling()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,505 @@
|
||||
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()
|
||||
Reference in new issue
Block a user