import pygame # for audio stuff import time import os from mfrc522 import SimpleMFRC522 #nfc reader import pygame.mixer # audio stuff import logging # instead of print statements, they are now logging.debug statements import random # for our joker card # Set up logging log_file = '/home/pi/programme/nfc/log.txt' logging.basicConfig(filename=log_file, level=logging.DEBUG, format='%(asctime)s %(message)s') id_old = None # having this as an empty ID # Initialize the NFC reader reader = SimpleMFRC522() # Dictionary mapping NFC tag IDs to names and corresponding audio files amiibo_dictionary = { 584185729648: ("Tom Nook", "tomnook.mp3"), 584198456190: ("Piranha Plant", "piranhaplant.mp3"), 584183817022: ("Boo", "boo.mp3"), 584186227665: ("Kirby", "kirby.mp3"), 584185554052: ("KK Slider", "kkslider.mp3"), 584196387116: ("Pikachu", "pikachu.mp3"), 584198271315: ("Samus", "samus.mp3"), 584191021155: ("Sheik", "songofstorms.mp3"), 584190129161: ("Corrin", "CorrinFire Emblem Fates OST Disc 1 09 Dusk Falls.mp3"), 584187759629: ("Inkling Boy", "Splatoonboy.mp3"), 584192111150: ("Timmy and Tommy", "Animal Crossing Gamecube Full Theme Song (High Quality).mp3"), 584195698087: ("Yarn Yoshi", "Yoshi's Story - Yoshi's Song.mp3"), 584190157978: ("Kapp'n", "KappnAnimal Crossing New Leaf- Kapp'n's Song.mp3"), 584193791472: ("Mario", "MarioSuper Mario Bros. Theme Song.mp3"), 584192980838: ("Lucina", "Lucina1-02-omen-main-theme.mp3"), 584192280790: ("Inkling Squid", "SplatoonSquidling.mp3"), 584185388089: ("Inkling Girl", "Splatoongirl.mp3"), 584189277469: ("Little Mac", "littlemac.mp3"), 584184792618: ("Zelda", "Zeldaballadgoddess.mp3"), 398965564655: ("Fob", "Ghost Trick - Cabanela - A White Lovely Lanky Man.mp3"), 776166726524: ("NFC Card", "random") # random is for our joker card } # Get the absolute path to the directory containing the script script_dir = os.path.dirname(os.path.abspath(__file__)) # Directory where audio files are stored audio_directory = os.path.join(script_dir, "audio") # Initialize pygame mixer pygame.mixer.init() # Getting the play count def get_play_count(file_path, filename): if os.path.exists(file_path): with open(file_path, 'r') as f: for line in f: if line.startswith(filename): return int(line.split(' = ')[1]) return 0 # Update play count def update_play_count(file_path, filename): play_counts = {} # Read the existing play counts into a dictionary if os.path.exists(file_path): with open(file_path, 'r') as f: for line in f: name, count = line.strip().split(' = ') play_counts[name] = int(count) # Update the play count for the specified filename if filename in play_counts: play_counts[filename] += 1 else: play_counts[filename] = 1 # Write the updated play counts back to the file with open(file_path, 'w') as f: for name, count in play_counts.items(): f.write(f"{name} = {count}\n") # Path to the play counts file play_counts_file = "/home/pi/programme/nfc/playcount.txt" # Function to play audio based on NFC tag ID def play_audio(id): global id_old if (id in amiibo_dictionary and id != id_old) or id == 776166726524: # making exception for joker card pygame.mixer.music.stop() #stop currently playing music because I got an error after using joker too often character_name, audio_file = amiibo_dictionary[id] logging.debug(f"Scanned ID: {id}, Character: {character_name}") id_old = id if audio_file == "random": # Get a list of all mp3 files in the audio directory audio_files = [f for f in os.listdir(audio_directory) if f.endswith('.mp3')] if audio_files: audio_file = random.choice(audio_files) else: logging.error("No MP3 files found in the audio directory.") return # Create full path for the audio file audio_file_path = os.path.join(audio_directory, audio_file) logging.debug(f"Audio file path: {audio_file_path}") # Check if audio file exists before loading if os.path.exists(audio_file_path): # Stop any currently playing music pygame.mixer.music.stop() # Load and play the corresponding audio file pygame.mixer.music.load(audio_file_path) # Set the volume (0.5 is half of the maximum volume) pygame.mixer.music.set_volume(0.1) pygame.mixer.music.play() # Wait briefly for playback to start time.sleep(0.1) # Update play count when the song is played update_play_count(play_counts_file, audio_file) # Verify the update count = get_play_count(play_counts_file, audio_file) # print(f"Play count for {audio_file}: {count}") # Wait until music playback finishes or a new tag is scanned start_time = time.time() while pygame.mixer.music.get_busy() and time.time() - start_time < 10: # Timeout after 10 seconds if reader.read_id() != id: pygame.mixer.music.stop() break time.sleep(0.1) else: logging.debug(f"Error: Audio file '{audio_file}' not found.") play_not_found_audio() elif id == id_old: logging.debug(f"ID is already being played, not retriggering.") pass else: logging.debug(f"No character found for ID: {id}") play_not_found_audio() def play_not_found_audio(): not_found_file = os.path.join(audio_directory, "notfound.mp3") if os.path.exists(not_found_file): # Stop any currently playing music pygame.mixer.music.stop() # Load and play the not found audio file pygame.mixer.music.load(not_found_file) pygame.mixer.music.play() # Wait briefly for playback to start time.sleep(0.1) # Wait until music playback finishes or a new tag is scanned start_time = time.time() while pygame.mixer.music.get_busy() and time.time() - start_time < 10: # Timeout after 10 seconds if reader.read_id() is not None: pygame.mixer.music.stop() break time.sleep(0.1) else: logging.debug(f"Error: Audio file '{not_found_file}' not found.") pass # Main program loop try: while True: print("Hold a tag near the reader") id = reader.read_id() # Read only the UID logging.debug(f"This amiibo is called: {id}") play_audio(id) except KeyboardInterrupt: print("Program interrupted") finally: pygame.mixer.quit() print("pygame.mixer cleanup completed")