basyair7

main.py

Aug 1st, 2025
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.99 KB | None | 0 0
  1. import asyncio
  2. import os
  3. import threading
  4. import time
  5. import pygame
  6.  
  7. import paho.mqtt.client as mqtt
  8. from bot.telegram import TelegramBot
  9.  
  10. # Mosquitto MQTT Config
  11. MQTT_BROKER = "localhost"
  12. MQTT_PORT = 1883
  13. CLIENT_ID = "raspberry_monyet"
  14. TOPIC = "esp8266/pub"
  15.  
  16. # Try to initialize pygame.mixer with retries
  17. def init_audio_with_retry(retries=5, delay=5):
  18.     for i in range(retries):
  19.         try:
  20.             pygame.mixer.init()
  21.             print("🔊 Audio initialized successfully")
  22.             return True
  23.         except pygame.error as e:
  24.             print(f"⚠️ Audio init failed (attempt {i+1}/{retries}): {e}")
  25.             time.sleep(delay)
  26.     print("❌ Audio init failed after all retries")
  27.     return False
  28.  
  29. audio_ready = init_audio_with_retry()
  30.  
  31. # Telegram Bot
  32. bot = TelegramBot()
  33.  
  34. # Play sound one time
  35. def play_sound_once():
  36.     if not audio_ready:
  37.         print("🔇 Skipping sound playback, audio device not ready")
  38.         return
  39.  
  40.     try:
  41.         # Check for various alarm file formats
  42.         alarm_files = ["alarm/alarm.wav", "alarm/alarm.mp3", "alarm/alarm.ogg", "alarm/alarm.flac"]
  43.         sound_file = "example.mp3"  # Default fallback
  44.        
  45.         for file in alarm_files:
  46.             if os.path.exists(file):
  47.                 sound_file = file
  48.                 break
  49.        
  50.         pygame.mixer.music.load(sound_file)
  51.         pygame.mixer.music.play()
  52.         print("🔊 Alarm playing once")
  53.         while pygame.mixer.music.get_busy():
  54.             time.sleep(0.1)
  55.         print("🔇 Alarm finished")
  56.     except Exception as e:
  57.         print(f"⚠️ Error playing sound: {e}")
  58.  
  59. # MQTT callbacks
  60. def on_connect(client, userdata, flags, rc):
  61.     if rc == 0:
  62.         print("✅ Connected to MQTT broker!")
  63.         client.subscribe(TOPIC)
  64.         print(f"📡 Subscribed to topic '{TOPIC}'")
  65.     else:
  66.         print(f"❌ Failed to connect, return code {rc}")
  67.  
  68. def on_message(client, userdata, msg):
  69.     message = msg.payload.decode()
  70.     print(f"📩 Received MQTT message from '{msg.topic}': {message}")
  71.  
  72.     threading.Thread(target=play_sound_once, daemon=True).start()
  73.     asyncio.run(bot.send_message("🐒 MQTT message received", sensor_active=True))
  74.  
  75. # MQTT Client Setup
  76. client = mqtt.Client(CLIENT_ID)
  77. client.on_connect = on_connect
  78. client.on_message = on_message
  79.  
  80. # Async main
  81. async def main():
  82.     print(f"🔌 Connecting to Mosquitto broker at {MQTT_BROKER}:{MQTT_PORT}...")
  83.     client.connect(MQTT_BROKER, MQTT_PORT, 60)
  84.     client.loop_start()
  85.  
  86.     try:
  87.         while True:
  88.             await asyncio.sleep(1)
  89.     except KeyboardInterrupt:
  90.         print("🔌 Disconnecting...")
  91.         client.loop_stop()
  92.         client.disconnect()
  93.         print("🚫 Disconnected.")
  94.  
  95. if __name__ == "__main__":
  96.     #try:
  97.      #   asyncio.run(main())
  98.     #except KeyboardInterrupt:
  99.         #print("🔌 Disconnecting...")
  100.         #client.loop_stop()
  101.         #client.disconnect()
  102.         #print("🚫 Disconnected.")
  103.     bot.run()
  104.  
Advertisement
Add Comment
Please, Sign In to add comment