import serial
import time
import glob
import binascii
import sys

# Gridseed Befehle (Hex Strings)
# Scrypt Reset: 55AA1F2816000000 + 55AA1F2817000000
# SHA256 Reset (Vermutung/Standard): 55AA1F2800000000
# Init: 55AAC000C0C0C0C00500000001000000

CMDS = {
    "1": ("SHA256 Force (00)", "55AA1F2800000000"),
    "2": ("Scrypt Force (16)", "55AA1F2816000000"),
    "3": ("Dual/Unkown (04)", "55AA1F2804000000"),
    "4": ("Reset Chip", "55AAC000808080800000000001000000"),
    "5": ("Full Init", "55AAC000C0C0C0C00500000001000000")
}

def send_command(port, hex_cmd):
    try:
        ser = serial.Serial(port, 115200, timeout=1)
        cmd_bytes = binascii.unhexlify(hex_cmd)
        print(f"Sending to {port}: {hex_cmd}")
        ser.write(cmd_bytes)
        time.sleep(0.1)
        ser.close()
        return True
    except Exception as e:
        print(f"Error on {port}: {e}")
        return False

def main():
    print("=== Gridseed Mode Switcher ===")
    print("Miner MUSS gestoppt sein!")
    
    ports = glob.glob('/dev/ttyACM*')
    if not ports:
        print("Keine Gridseeds gefunden (/dev/ttyACM*)")
        return

    print(f"Gefundene Geräte: {ports}")
    
    print("\nWähle Befehl:")
    for k, v in CMDS.items():
        print(f"{k}: {v[0]}")
        
    choice = input("Auswahl (1-5): ")
    
    if choice in CMDS:
        desc, cmd = CMDS[choice]
        print(f"Sende {desc}...")
        for port in ports:
            send_command(port, cmd)
    else:
        print("Ungültige Auswahl")

if __name__ == "__main__":
    main()