::	@File Name: HEXBIN.bat
::	@Version : 1.0
::	@Author : Alex-XU
::	@Creat Date : 2023-03-30
::	@Brief : 
::			在keil中,生成hex、bin文件到 Out 文件夹中.
::			复制本文件到keil工程文件所在目录下（/Project目录下）
::			在keil 魔法棒USER里填写
::			.\Out.bat $K !P @P
::			$K hextobin转换工具位置 !P 工程名 @P 工程目录
::			.\HEXBIN.bat .\Objects\hex2bin_TP.exe mcu \Objects\

::关闭显示
@echo off
::获取时间
set year=%date:~0,4%
set month=%date:~5,2%
set day=%date:~8,2%
set hour=%time:~0,2%
set min=%time:~3,2%
set sec=%time:~6,2%
::创建输出文件夹 Out
if exist .\..\Out (
	echo Out file exist
) else (
	mkdir .\..\Out
)

::设置hex2bin_TP.exe位置 ,\Objects\hex2bin_TP.exe
set exe_location=%1
::获取工程名 mcu.hex
set project_name=%3
::设置.hex文件所在目录路径\Objects\
set crc_path=%2
::设置.hex文件所在目录路径\Objects\
set obj_path=%4
::设置输出后的文件名
set output_nameTmp=SY883X_EVB_%project_name%_%date:~0,4%_%date:~5,2%_%date:~8,2%_%time:~0,2%%time:~3,2%%time:~6,2%
::如果hour小于10，会有空格，下面这句话可以除去字符串中的空格，并用0代替。
set output_name=%output_nameTmp: =0%

::将bin文件生成到HEXBIN文件夹  >nul屏蔽成功命令    .\Objects\hex2bin_TP.exe .\Objects\mcu.hex  .\Objects\bin.bin 3 0
%exe_location% .%obj_path%%project_name%.hex .%obj_path%%output_name%.bin 3 0 >nul
::将hex文件重命名
ren .%obj_path%%project_name%.hex %output_name%.hex >nul

ECHO Add CRC16  At the end of the .bin file
ECHO -------------------------------------

::SET SREC_PATH=D:\Keil_v5\SREC
SET SREC_PATH=..\Tools\SREC

for /f %%i in ('dir /s /b .%obj_path%%output_name%.bin') do ( 
set indexdx=%%~zi
)

ECHO --- size= %indexdx% Bytes ---
::计算程序CRC16校验和，并加在.bin文件最后
ECHO %SREC_PATH%\srec_cat.exe .%obj_path%%output_name%.bin -Binary -crop 0 %indexdx% -CRC16_Big_Endian %indexdx% -XMODEM -o .%obj_path%%output_name%_crc.bin -Binary
%SREC_PATH%\srec_cat.exe .%obj_path%%output_name%.bin -Binary -crop 0 %indexdx% -CRC16_Big_Endian %indexdx% -XMODEM -o .%obj_path%%output_name%_crc.bin -Binary

::获取软件CRC校验和以及版本号
%crc_path% .%obj_path%%output_name%_crc.bin

del /q ..\Out\*.*
::将hex文件复制到HEXBIN文件夹
move .%obj_path%%output_name%.hex .\..\Out >nul
move .%obj_path%%output_name%.bin .\..\Out >nul
::del .%obj_path%%output_name%.hex
::del .%obj_path%%output_name%.bin
del .%obj_path%%output_name%_crc.bin
move .%obj_path%%output_name%_crc(*.bin .\..\Out >nul
