@echo off

:: check if com port number input
if "%~1"=="" (
    echo Error: No COM port provided. Usage: download.bat [COM port number]
    exit /b 1
)

:: get COM port number
set COM_PORT=COM%~1

:: define necessary files
set FILES=ChipLoad.exe minidriver.hex mtb-example-threadx-le-wifi-onboarding.btp MbtP.exe

:: check if necessary files exist.
for %%F in (%FILES%) do (
    if not exist "%%F" (
        echo Error: Missing file %%F. Please ensure all required files are in the same folder.
        exit /b 1
    )
)


echo Starting download process...

ChipLoad.exe -BLUETOOLMODE -ENTERDOWNLOADMODE -PORT %COM_PORT% -LAUNCHADDRESS 0x00300400 -BAUDRATE 115200 -NOVERIFY -BTP mtb-example-threadx-le-wifi-onboarding.btp -FIRMWARE minidriver.hex -LOGTOX download_minidriver.log -DL_TIMEOUT_MULTIPLIER 16
MbtP.exe update_baudrate %COM_PORT% 115200 3000000

IF EXIST mtb-example-threadx-le-wifi-onboarding_download.hex (
    :: Execute download for HCD file
    ChipLoad.exe -BLUETOOLMODE -PORT %COM_PORT% -LAUNCHADDRESS 0x00000000 -NOHCIRESET -NODLMINIDRIVER -BAUDRATE 3000000 -NOVERIFY -BTP mtb-example-threadx-le-wifi-onboarding.btp -CONFIG mtb-example-threadx-le-wifi-onboarding_download.hex -LOGTOX download_image.log -DL_TIMEOUT_MULTIPLIER 16
) ELSE IF EXIST mtb-example-threadx-le-wifi-onboarding_download.hcd (
    :: Execute download for HEX file
    ChipLoad.exe -BLUETOOLMODE -PORT %COM_PORT% -LAUNCHADDRESS 0x00000000 -NOHCIRESET -NODLMINIDRIVER -BAUDRATE 3000000 -NOVERIFY -BTP mtb-example-threadx-le-wifi-onboarding.btp -CONFIG mtb-example-threadx-le-wifi-onboarding_download.hcd -LOGTOX download_image.log -DL_TIMEOUT_MULTIPLIER 16
) ELSE (
    echo Error: Both mtb-example-threadx-le-wifi-onboarding_download.hcd and mtb-example-threadx-le-wifi-onboarding_download.hex are missing.
    exit /b 1
)

:: finished
if errorlevel 1 (
    echo Error: ChipLoad.exe fail.
    exit /b 1
)

