아!두이노, 라즈베리, 코딩 노가다

레트로아크 실행되기전에 코드 삽입 하기 본문

오락실

레트로아크 실행되기전에 코드 삽입 하기

아이스뭐라카노 2026. 5. 19. 08:13
반응형
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
import sys
import os

# GPIO 핀 번호 설정 (BCM 방식)
GPIO.setmode(GPIO.BCM)
TILT_PIN = 17
GPIO.setup(TILT_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# cfg 파일 생성 위치
CFG_DIR = "/opt/retropie/configs/all/retroarch/configs"

# 0도(수평) cfg 내용
CFG_CONTENT_0 = """\
aspect_ratio_index            = "22"
input_overlay_enable          = "false"
input_overlay_opacity         = "1.000000"
video_integer_scale           = "false"
video_rotation                = "0"
menu_show_advanced_settings   = "true"
video_fullscreen              = "true"
video_window_show_decorations = "false"
video_viewport_bias_x         = "0.5"
video_viewport_bias_y         = "0.5"
"""

# 90도(수직) cfg 내용
CFG_CONTENT_90 = """\
aspect_ratio_index            = "22"
input_overlay_enable          = "false"
input_overlay_opacity         = "1.000000"
video_integer_scale           = "false"
video_rotation                = "3"
menu_show_advanced_settings   = "true"
video_fullscreen              = "true"
video_window_show_decorations = "false"
video_viewport_bias_x         = "0.5"
video_viewport_bias_y         = "0.5"
"""

def create_file_for_0_degree(emulator_type, rom_name):
    """ 0도(수평)일 때 실행할 파일 생성 로직 """
    print(f"[INFO] 0도 수평 감지 | 에뮬레이터: {emulator_type} | 롬파일명: {rom_name}")

    if emulator_type == "RetroArch":
        cfg_filename = f"{rom_name}.cfg"
        cfg_path = os.path.join(CFG_DIR, cfg_filename)

        with open(cfg_path, "w") as f:
            f.write(CFG_CONTENT_0)

        print(f"[INFO] 0도 cfg 파일 생성 완료: {cfg_path}")
    else:
        print(f"[INFO] RetroArch가 아니므로 파일 생성 생략 ({emulator_type})")

def create_file_for_90_degree(emulator_type, rom_name):
    """ 90도(수직)일 때 실행할 파일 생성 로직 """
    print(f"[INFO] 90도 수직 감지 | 에뮬레이터: {emulator_type} | 롬파일명: {rom_name}")

    if emulator_type == "RetroArch":
        cfg_filename = f"{rom_name}.cfg"
        cfg_path = os.path.join(CFG_DIR, cfg_filename)

        with open(cfg_path, "w") as f:
            f.write(CFG_CONTENT_90)

        print(f"[INFO] 90도 cfg 파일 생성 완료: {cfg_path}")
    else:
        print(f"[INFO] RetroArch가 아니므로 파일 생성 생략 ({emulator_type})")

def main():
    # runcommand로부터 인자가 정상적으로 넘어왔는지 확인
    # 인자가 없으면 기본값(Unknown) 지정
    system_arg = sys.argv[1] if len(sys.argv) > 1 else "unknown"
    rom_path_arg = sys.argv[2] if len(sys.argv) > 2 else "unknown.zip"

    # 1. 에뮬레이터 종류 판별 로직
    system_lower = system_arg.lower()
    if "libretro" in system_lower or system_lower in ["arcade", "fba", "neogeo"]:
        emulator_type = "RetroArch"
    elif "mame" in system_lower:
        emulator_type = "MAME"
    else:
        emulator_type = f"Other({system_arg})"

    # 2. 롬 파일 이름 추출 로직
    base_name = os.path.basename(rom_path_arg)   # 예: 'mslug.zip'
    rom_name, _ = os.path.splitext(base_name)    # 예: 'mslug'

    try:
        # 센서 값 샘플링 - 채터링 방지
        low_count = 0
        high_count = 0
        for _ in range(5):
            if GPIO.input(TILT_PIN) == GPIO.LOW:
                low_count += 1
            else:
                high_count += 1
            time.sleep(0.02)

        # 각도 판별 및 cfg 파일 생성
        if low_count > high_count:
            create_file_for_90_degree(emulator_type, rom_name)
        else:
            create_file_for_0_degree(emulator_type, rom_name)

    except Exception as e:
        print(f"[ERROR] 스크립트 실행 중 오류 발생: {e}", file=sys.stderr)

    finally:
        GPIO.cleanup(TILT_PIN)

if __name__ == "__main__":
    main()

 

nano /opt/retropie/configs/all/runcommand-onstart.sh

#!/bin/bash

# $1: 시스템 이름(예: arcade, mame-libretro)
# $3: 롬 파일의 전체 경로(예: /home/pi/RetroPie/roms/arcade/mslug.zip)
# 이 두 가지 정보를 파이썬 스크립트의 매개변수로 넘겨줍니다.
python3 /home/pi/check_tilt.py "$1" "$3"