# mPy - developing df_player command station on FSK0001
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-01-26  initial release

import	time
from	machine	import	UART

# =========================== Serial ================================

class Serial:

    # Open serial port through UART. Esp32s2 has two UARTS 0..1
    # eSP32S3 : uart0 not usable
    def __init__(self, id=1, baud=115200, rx=27, tx=26):
        self.uart = UART(id, baudrate=baud, rx=rx, tx=tx, stop=2)
        self.b_rx = None
        self.uart.irq(self.onRx, trigger=UART.IRQ_RXIDLE)


    # close the serial port
    def close(self):
        if self.uart:
            self.uart.deinit()
            self.uart = None


    # Write bytes or bytearray
    def write(self, obj):
        self.uart.write(obj)


    # Irq on data receive gap, using timer 0
    def onRx(self, sender):
        self.b_rx = self.uart.read()

# ======================== main =================================

# DF-Player commands
SET_VOLUME   = 0x06
PLAY_FIRST   = 0x03
PLAY_FILE    = 0x0F
PAUSE		 = 0x0E


# send command and data to DF-Player
def dfCmd(cmd=0x00, dh=0x00, dl=0x00):
    res = bytearray(b'\x7E\xFF\x06\x00\x00\x00\x00\xEF')
    res[3] = cmd
    res[5] = dh
    res[6] = dl
    return res


# play first track
def test1():
    serial = Serial(baud=9600, tx=26, rx=27)
    try:
        time.sleep_ms(500)
        serial.write(dfCmd(SET_VOLUME, 0x00, 0x1F))
        serial.write(dfCmd(PLAY_FIRST))
        time.sleep_ms(50)
    finally: serial.close()
    
    
# play first track for 20 seconds
def test2():
    serial = Serial(baud=9600, tx=26, rx=27)
    try:
        time.sleep_ms(500)
        serial.write(dfCmd(SET_VOLUME, 0x00, 0x1F))
        serial.write(dfCmd(PLAY_FIRST))
        time.sleep(20)
        serial.write(dfCmd(PAUSE))
        time.sleep_ms(50)
    finally: serial.close()
    

# play flle #3 from directory 0
def test3():
    serial = Serial(baud=9600, tx=26, rx=27)
    try:
        time.sleep_ms(500)
        serial.write(dfCmd(SET_VOLUME, 0x00, 0x1F))
        serial.write(dfCmd(PLAY_FILE, 0x01, 0x03))
        time.sleep_ms(50)
    finally: serial.close()


test3()

# ============================ end ===============================
