IAP_YMODEM_STM32F1_ATY.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. /**
  2. * @file IAP_YMODEM_STM32F1_ATY.c
  3. *
  4. * @param Project DEVICE_GENERAL_ATY_LIB
  5. *
  6. * @author ATY
  7. *
  8. * @copyright
  9. * - Copyright 2017 - 2023 MZ-ATY
  10. * - This code follows:
  11. * - MZ-ATY Various Contents Joint Statement -
  12. * <a href="https://mengze.top/MZ-ATY_VCJS">
  13. * https://mengze.top/MZ-ATY_VCJS</a>
  14. * - CC 4.0 BY-NC-SA -
  15. * <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
  16. * https://creativecommons.org/licenses/by-nc-sa/4.0/</a>
  17. * - Your use will be deemed to have accepted the terms of this statement.
  18. *
  19. * @brief functions of IAP with YMODEM for STM32F1xx
  20. *
  21. * @version
  22. * - 1_01_240911 > ATY
  23. * -# Preliminary version, first Release
  24. * - 1_02_250701 > ATY
  25. * -# real fix to lib type
  26. * - 1_03_250704 > ATY
  27. * -# finish uart and ucdc IAP whole test
  28. * - 1_04_251016 > ATY
  29. * -# fix large bin 255 limit at 128 and 1K trans in USB CDC
  30. * @todo some IT not restart when jump to app some times
  31. ********************************************************************************
  32. */
  33. #ifndef __IAP_YMODEM_STM32F1_ATY_C
  34. #define __IAP_YMODEM_STM32F1_ATY_C
  35. #include "IAP_YMODEM_STM32F1_ATY.h"
  36. /******************************* For user *************************************/
  37. uint8_t EmptyBuf[1] = {0};
  38. #ifdef IAP_YMODEM_STM32F1_ATY_USB
  39. USBD_CDC_HandleTypeDef* hcdc;
  40. uint32_t ucdcRcvLength = 0;
  41. uint8_t ucdcRcvOverFlag = 1;
  42. uint32_t ucdcRcvLastTime = 0;
  43. uint8_t ucdcRcvBuffer[PACKET_1K_SIZE + PACKET_DATA_INDEX + PACKET_TRAILER_SIZE] = {0};
  44. #endif
  45. void JumpToAppWithReset(void){
  46. // ResetBeforeJumpToApp();
  47. #ifdef IAP_YMODEM_STM32F1_ATY_USB
  48. // Deinitialize USB
  49. USBD_DeInit(&hUsbDeviceFS);
  50. #endif
  51. Bootloader_DeInit();
  52. JumpToApp(APPLICATION_ADDRESS);
  53. }
  54. void Interface_Clean(void){
  55. #ifdef IAP_YMODEM_STM32F1_ATY_USB
  56. #warning "IAP_YMODEM_STM32F1_ATY_USB"
  57. ucdcRcvLength = 0;
  58. ucdcRcvOverFlag = 1;
  59. #else
  60. #warning "NOT IAP_YMODEM_STM32F1_ATY_USB"
  61. __HAL_UART_FLUSH_DRREGISTER(&Interface_UART);
  62. #endif
  63. }
  64. #ifdef IAP_YMODEM_STM32F1_ATY_USB
  65. void PUT_IN_CDC_Receive_FS(uint8_t* Buf, uint32_t* Len){
  66. if(ucdcRcvOverFlag == 1){ // new start
  67. ucdcRcvOverFlag = 0;
  68. ucdcRcvLength = *Len;
  69. memcpy(ucdcRcvBuffer, Buf, *Len);
  70. if(*Len < 64){
  71. ucdcRcvOverFlag = 1;
  72. }
  73. else{
  74. ucdcRcvLastTime = HAL_GetTick();
  75. }
  76. }
  77. else{ // pending to before
  78. memcpy(ucdcRcvBuffer + ucdcRcvLength, Buf, *Len);
  79. ucdcRcvLength += *Len;
  80. if(*Len < 64){
  81. ucdcRcvOverFlag = 1;
  82. }
  83. else{
  84. ucdcRcvLastTime = HAL_GetTick();
  85. }
  86. }
  87. // USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]);
  88. // USBD_CDC_ReceivePacket(&hUsbDeviceFS);
  89. // return (USBD_OK);
  90. }
  91. #endif
  92. uint32_t timeoutCount = 0;
  93. uint32_t timeoutFinal = 100;
  94. HAL_StatusTypeDef Interface_Receive(uint8_t* bytes, uint16_t size, uint32_t timeout){
  95. #ifdef IAP_YMODEM_STM32F1_ATY_USB
  96. hcdc = (USBD_CDC_HandleTypeDef*)hUsbDeviceFS.pClassData;
  97. if(hcdc->RxLength > APP_RX_DATA_SIZE)
  98. return HAL_ERROR;
  99. timeoutCount = 0;
  100. timeoutFinal = timeout;
  101. while(ucdcRcvLength == 0){
  102. timeoutCount++;
  103. if(timeoutCount > timeoutFinal){
  104. timeoutCount = 0;
  105. USBD_CDC_ReceivePacket(&hUsbDeviceFS);
  106. bytes[0] = 0;
  107. return HAL_TIMEOUT;
  108. }
  109. HAL_Delay(1);
  110. }
  111. if(ucdcRcvOverFlag == 0){
  112. while(HAL_GetTick() - ucdcRcvLastTime < 200){
  113. }
  114. ucdcRcvOverFlag = 1;
  115. }
  116. if(ucdcRcvLength > 0 && ucdcRcvLength <= PACKET_1K_SIZE + PACKET_DATA_INDEX + PACKET_TRAILER_SIZE){
  117. uint16_t copySize = (ucdcRcvLength > size) ? size : ucdcRcvLength;
  118. memcpy(bytes, ucdcRcvBuffer, copySize);
  119. ucdcRcvLength -= copySize;
  120. memcpy(ucdcRcvBuffer, ucdcRcvBuffer + copySize, ucdcRcvLength);
  121. }
  122. return HAL_OK;
  123. #else
  124. HAL_StatusTypeDef state = HAL_UART_Receive(&Interface_UART, bytes, size, timeout);
  125. return state;
  126. // return HAL_UART_Receive(&Interface_UART, bytes, size, timeout);
  127. #endif
  128. }
  129. HAL_StatusTypeDef Interface_Transmit(uint8_t* bytes, uint16_t size, uint32_t timeout){
  130. #ifdef IAP_YMODEM_STM32F1_ATY_USB
  131. Interface_Clean();
  132. ucdcRcvOverFlag = 1;
  133. timeoutCount = 0;
  134. timeoutFinal = timeout;
  135. while(CDC_Transmit_FS(bytes, size) != HAL_OK){
  136. timeoutCount++;
  137. if(timeoutCount > timeoutFinal)
  138. return HAL_TIMEOUT;
  139. HAL_Delay(1);
  140. }
  141. return HAL_OK;
  142. #else
  143. /* May be timeouted... */
  144. if(Interface_UART.gState == HAL_UART_STATE_TIMEOUT){
  145. Interface_UART.gState = HAL_UART_STATE_READY;
  146. }
  147. return HAL_UART_Transmit(&Interface_UART, bytes, size, timeout);
  148. #endif
  149. }
  150. /**
  151. * @brief Display the Main Menu on HyperTerminal
  152. */
  153. void Main_Menu(void){
  154. uint8_t key = 0;
  155. uint16_t errTimes = 0;
  156. uint32_t FlashProtection = 0;
  157. /* Initialise Flash */
  158. FLASH_If_Init();
  159. /* Test if any sector of Flash memory where user application will be loaded is write protected */
  160. FlashProtection = FLASH_If_GetWriteProtectionStatus();
  161. Interface_PutString("\r\n\r\n=================== Main Menu ============================\r\n\r\n");
  162. Interface_PutString(" Download image to the internal Flash ----------------- 1\r\n\r\n");
  163. Interface_PutString(" Upload image from the internal Flash ----------------- 2\r\n\r\n");
  164. Interface_PutString(" Execute the loaded application ----------------------- 3\r\n\r\n");
  165. if(FlashProtection != FLASHIF_PROTECTION_NONE){
  166. Interface_PutString(" Disable the write protection ------------------------- 4\r\n\r\n");
  167. }
  168. else{
  169. Interface_PutString(" Enable the write protection -------------------------- 4\r\n\r\n");
  170. }
  171. Interface_PutString("==========================================================\r\n\r\n");
  172. while(1){
  173. /* Clean the input path */
  174. Interface_Clean();
  175. /* Receive key */
  176. Interface_Receive(&key, 1, IAP_3_TIME);
  177. /* Auto jump to app */
  178. if(key == 0)
  179. key = 51;
  180. switch(key){
  181. case '*':
  182. /* Upload user application from the Flash */
  183. Interface_Upload();
  184. break;
  185. case '2':
  186. /* Upload user application from the Flash */
  187. Interface_PutString("\r\nAuthorize wrong!\r\n\r\n");
  188. break;
  189. case '1':
  190. /* Download user application in the Flash */
  191. if(Interface_Download() != COM_OK)
  192. break;
  193. case '3':
  194. Interface_PutString("\r\nStart program execution...\r\n");
  195. JumpToAppWithReset();
  196. break;
  197. case '4':
  198. if(FlashProtection != FLASHIF_PROTECTION_NONE){
  199. /* Disable the write protection */
  200. if(FLASH_If_WriteProtectionConfig(FLASHIF_WRP_DISABLE) == FLASHIF_OK){
  201. Interface_PutString("Write protection disabled...\r\n");
  202. Interface_PutString("System will now restart...\r\n");
  203. /* Launch the option byte loading */
  204. HAL_FLASH_OB_Launch();
  205. }
  206. else{
  207. Interface_PutString("Error: Flash write un-protection failed...\r\n");
  208. }
  209. }
  210. else{
  211. if(FLASH_If_WriteProtectionConfig(FLASHIF_WRP_ENABLE) == FLASHIF_OK){
  212. Interface_PutString("Write protection enabled...\r\n");
  213. Interface_PutString("System will now restart...\r\n");
  214. /* Launch the option byte loading */
  215. HAL_FLASH_OB_Launch();
  216. }
  217. else{
  218. Interface_PutString("Error: Flash write protection failed...\r\n");
  219. }
  220. }
  221. break;
  222. default:
  223. errTimes++;
  224. if(errTimes > 500){
  225. Interface_PutString("Start program execution for max err...\r\n\r\n");
  226. JumpToAppWithReset();
  227. }
  228. // Interface_PutString("Invalid Number ! ==> The number should be either 1, 2, 3 or 4\r\n");
  229. break;
  230. }
  231. key = 0;
  232. }
  233. }
  234. #include "rtc.h"
  235. void Main_Cycle(void){
  236. uint8_t sKey[2] = {0};
  237. HAL_RTCEx_BKUPWrite(&hrtc, RTC_BKP_DR1, IAP_VerA);
  238. HAL_RTCEx_BKUPWrite(&hrtc, RTC_BKP_DR2, IAP_VerB);
  239. HAL_RTCEx_BKUPWrite(&hrtc, RTC_BKP_DR3, IAP_VerC);
  240. Interface_PutString("\r\n\r\nS to start\r\n\r\n");
  241. while(1){
  242. #ifdef IAP_YMODEM_STM32F1_ATY_USB
  243. if(hcdc->RxLength > 1024){
  244. uint8_t t[1] = {0};
  245. Interface_Clean();
  246. Interface_PutByte(0x00);
  247. Interface_Receive(t, 1, 10);
  248. continue;
  249. }
  250. #endif
  251. if(1){
  252. if(Interface_Receive(sKey, 2, IAP_S_TIME) == HAL_OK){
  253. if(sKey[0] == 'S'){
  254. if(sKey[1] == '3'){
  255. Interface_Clean();
  256. Interface_PutString("\r\nStart program execution...\r\n");
  257. JumpToAppWithReset();
  258. }
  259. else if(sKey[1] == '1'){
  260. Interface_Clean();
  261. if(Interface_Download() != COM_OK){
  262. Interface_PutString("\r\nStart program execution...\r\n");
  263. JumpToAppWithReset();
  264. }
  265. }
  266. else{
  267. Interface_Clean();
  268. Main_Menu();
  269. }
  270. }
  271. else{
  272. Interface_Clean();
  273. }
  274. }
  275. else{
  276. Interface_Clean();
  277. Main_Menu();
  278. }
  279. }
  280. /* Keep the user application running */
  281. else{
  282. JumpToAppWithReset();
  283. }
  284. }
  285. }
  286. /* ****************************************************************************/
  287. /* interface realize **********************************************************/
  288. /**
  289. * @brief Print a string on the HyperTerminal
  290. * @param p_string: The string to be printed
  291. * @retval send state
  292. */
  293. HAL_StatusTypeDef Interface_PutString(uint8_t* p_string){
  294. #ifdef IAP_YMODEM_STM32F1_ATY_DBG
  295. uint16_t length = 0;
  296. while(p_string[length] != '\0'){
  297. length++;
  298. }
  299. return Interface_Transmit(p_string, length, TX_TIMEOUT);
  300. #else
  301. return Interface_Transmit("", 0, TX_TIMEOUT);;
  302. #endif
  303. }
  304. /**
  305. * @brief Transmit a byte to the HyperTerminal
  306. * @param bytes The byte to be sent
  307. * @retval send state
  308. */
  309. HAL_StatusTypeDef Interface_PutByte(uint8_t bytes){
  310. return Interface_Transmit(&bytes, 1, TX_TIMEOUT);
  311. }
  312. /**
  313. * @brief Download a file
  314. * @retval download state
  315. */
  316. COM_StatusTypeDef Interface_Download(void){
  317. uint8_t number[11] = {0};
  318. uint32_t size = 0;
  319. COM_StatusTypeDef result;
  320. Interface_PutString("\r\nWaiting for the file to be sent... (press 'a' to abort)\r\n");
  321. Interface_PutByte(CRC16);
  322. result = Ymodem_Receive(&size);
  323. if(result == COM_OK){
  324. Interface_PutString("\r\n\r\nProgramming Completed Successfully!\n\r--------------------------------\r\n Name: ");
  325. Interface_PutString(aFileName);
  326. Int2Str(number, size);
  327. Interface_PutString("\r\nSize: ");
  328. Interface_PutString(number);
  329. Interface_PutString(" Bytes\r\n");
  330. Interface_PutString("-------------------\r\n");
  331. }
  332. else if(result == COM_LIMIT){
  333. Interface_PutString("\r\nThe image size is higher than the allowed space memory!\n\r");
  334. }
  335. else if(result == COM_DATA){
  336. Interface_PutString("\r\nVerification failed!\n\r");
  337. }
  338. else if(result == COM_ABORT){
  339. Interface_PutString("\r\nAborted by user.\n\r");
  340. }
  341. else{
  342. Interface_PutString("\r\nFailed to receive the file!\r\n");
  343. }
  344. return result;
  345. }
  346. /**
  347. * @brief Upload a file
  348. */
  349. void Interface_Upload(void){
  350. uint8_t status = 0;
  351. Interface_PutString("\r\n\r\nSelect receive file... (press 'a' to abort)\r\n");
  352. while(1){
  353. Interface_Receive(&status, 1, RX_TIMEOUT);
  354. if(status == CRC16){
  355. /* Transmit the flash image through ymodem protocol */
  356. status = Ymodem_Transmit((uint8_t*)APPLICATION_ADDRESS, (const uint8_t*)"UploadedFlashImage.bin", USER_FLASH_SIZE);
  357. if(status != 0){
  358. if(status == COM_ABORT)
  359. Interface_PutString("\r\nAborted by user.\n\r");
  360. else
  361. Interface_PutString("\r\nError occurred while transmitting file\r\n");
  362. }
  363. else{
  364. Interface_PutString("\r\nFile uploaded successfully\r\n");
  365. }
  366. break;
  367. }
  368. else if(status == ABORT1 || status == ABORT2){
  369. Interface_PutString("\r\nAborted by user.\n\r");
  370. break;
  371. }
  372. }
  373. }
  374. /* common *********************************************************************/
  375. /**
  376. * @brief Convert an Integer to a string
  377. * @param p_str: The string output pointer
  378. * @param intnum: The integer to be converted
  379. */
  380. void Int2Str(uint8_t* p_str, uint32_t intnum){
  381. uint32_t i, divider = 1000000000, pos = 0, status = 0;
  382. for(i = 0; i < 10; i++){
  383. p_str[pos++] = (intnum / divider) + 48;
  384. intnum = intnum % divider;
  385. divider /= 10;
  386. if((p_str[pos - 1] == '0') & (status == 0)){
  387. pos = 0;
  388. }
  389. else{
  390. status++;
  391. }
  392. }
  393. }
  394. /**
  395. * @brief Convert a string to an integer
  396. * @param p_inputstr: The string to be converted
  397. * @param p_intnum: The integer value
  398. * @retval 1: Correct
  399. * 0: Error
  400. */
  401. uint32_t Str2Int(uint8_t* p_inputstr, uint32_t* p_intnum){
  402. uint32_t i = 0, res = 0;
  403. uint32_t val = 0;
  404. if((p_inputstr[0] == '0') && ((p_inputstr[1] == 'x') || (p_inputstr[1] == 'X'))){
  405. i = 2;
  406. while((i < 11) && (p_inputstr[i] != '\0')){
  407. if(ISVALIDHEX(p_inputstr[i])){
  408. val = (val << 4) + CONVERTHEX(p_inputstr[i]);
  409. }
  410. else{
  411. /* Return 0, Invalid input */
  412. res = 0;
  413. break;
  414. }
  415. i++;
  416. }
  417. /* valid result */
  418. if(p_inputstr[i] == '\0'){
  419. *p_intnum = val;
  420. res = 1;
  421. }
  422. }
  423. else /* max 10-digit decimal input */
  424. {
  425. while((i < 11) && (res != 1)){
  426. if(p_inputstr[i] == '\0'){
  427. *p_intnum = val;
  428. /* return 1 correct */
  429. res = 1;
  430. }
  431. else if(((p_inputstr[i] == 'k') || (p_inputstr[i] == 'K')) && (i > 0)){
  432. val = val << 10;
  433. *p_intnum = val;
  434. res = 1;
  435. }
  436. else if(((p_inputstr[i] == 'm') || (p_inputstr[i] == 'M')) && (i > 0)){
  437. val = val << 20;
  438. *p_intnum = val;
  439. res = 1;
  440. }
  441. else if(ISVALIDDEC(p_inputstr[i])){
  442. val = val * 10 + CONVERTDEC(p_inputstr[i]);
  443. }
  444. else{
  445. /* return 0, Invalid input */
  446. res = 0;
  447. break;
  448. }
  449. i++;
  450. }
  451. }
  452. return res;
  453. }
  454. /* flash_if *******************************************************************/
  455. /**
  456. * @brief Unlocks Flash for write access
  457. */
  458. void FLASH_If_Init(void){
  459. /* Unlock the Program memory */
  460. HAL_FLASH_Unlock();
  461. /* Clear all FLASH flags */
  462. __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPERR);
  463. /* Unlock the Program memory */
  464. HAL_FLASH_Lock();
  465. }
  466. /**
  467. * @brief This function does an erase of all user flash area
  468. * @param start: start of user flash area
  469. * @retval FLASHIF_OK : user flash area successfully erased
  470. * FLASHIF_ERASEKO : error occurred
  471. */
  472. uint32_t FLASH_If_Erase(uint32_t start){
  473. uint32_t NbrOfPages = 0;
  474. uint32_t PageError = 0;
  475. FLASH_EraseInitTypeDef pEraseInit;
  476. HAL_StatusTypeDef status = HAL_OK;
  477. /* Unlock the Flash to enable the flash control register access */
  478. HAL_FLASH_Unlock();
  479. /* Get the sector where start the user flash area */
  480. NbrOfPages = (USER_FLASH_END_ADDRESS - start) / FLASH_PAGE_SIZE;
  481. pEraseInit.TypeErase = FLASH_TYPEERASE_PAGES;
  482. pEraseInit.PageAddress = start;
  483. pEraseInit.Banks = FLASH_BANK_1;
  484. pEraseInit.NbPages = NbrOfPages;
  485. status = HAL_FLASHEx_Erase(&pEraseInit, &PageError);
  486. /* Lock the Flash to disable the flash control register access (recommended
  487. to protect the FLASH memory against possible unwanted operation) */
  488. HAL_FLASH_Lock();
  489. if(status != HAL_OK){
  490. /* Error occurred while page erase */
  491. return FLASHIF_ERASEKO;
  492. }
  493. return FLASHIF_OK;
  494. }
  495. /**
  496. * @brief This function writes a data buffer in flash (data are 32-bit aligned).
  497. * @note After writing data buffer, the flash content is checked.
  498. * @param destination: start address for target location
  499. * @param p_source: pointer on buffer with data to write
  500. * @param length: length of data buffer (unit is 32-bit word)
  501. * @retval uint32_t 0: Data successfully written to Flash memory
  502. * 1: Error occurred while writing data in Flash memory
  503. * 2: Written Data in flash memory is different from expected one
  504. */
  505. uint32_t FLASH_If_Write(uint32_t destination, uint32_t* p_source, uint32_t length){
  506. uint32_t i = 0;
  507. /* Unlock the Flash to enable the flash control register access */
  508. HAL_FLASH_Unlock();
  509. for(i = 0; (i < length) && (destination <= (USER_FLASH_END_ADDRESS - 4)); i++){
  510. /* Device voltage range supposed to be [2.7V to 3.6V], the operation will
  511. be done by word */
  512. if(HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, destination, *(uint32_t*)(p_source + i)) == HAL_OK){
  513. /* Check the written value */
  514. if(*(uint32_t*)destination != *(uint32_t*)(p_source + i)){
  515. /* Flash content doesn't match SRAM content */
  516. return(FLASHIF_WRITINGCTRL_ERROR);
  517. }
  518. /* Increment FLASH destination address */
  519. destination += 4;
  520. }
  521. else{
  522. /* Error occurred while writing data in Flash memory */
  523. return (FLASHIF_WRITING_ERROR);
  524. }
  525. }
  526. /* Lock the Flash to disable the flash control register access (recommended
  527. to protect the FLASH memory against possible unwanted operation) */
  528. HAL_FLASH_Lock();
  529. return (FLASHIF_OK);
  530. }
  531. /**
  532. * @brief Returns the write protection status of application flash area.
  533. * @retval If a sector in application area is write-protected returned value is a combinaison
  534. of the possible values : FLASHIF_PROTECTION_WRPENABLED, FLASHIF_PROTECTION_PCROPENABLED, ...
  535. * If no sector is write-protected FLASHIF_PROTECTION_NONE is returned.
  536. */
  537. uint32_t FLASH_If_GetWriteProtectionStatus(void){
  538. uint32_t ProtectedPAGE = FLASHIF_PROTECTION_NONE;
  539. FLASH_OBProgramInitTypeDef OptionsBytesStruct;
  540. /* Unlock the Flash to enable the flash control register access */
  541. HAL_FLASH_Unlock();
  542. /* Check if there are write protected sectors inside the user flash area */
  543. HAL_FLASHEx_OBGetConfig(&OptionsBytesStruct);
  544. /* Lock the Flash to disable the flash control register access (recommended
  545. to protect the FLASH memory against possible unwanted operation) */
  546. HAL_FLASH_Lock();
  547. /* Get pages already write protected */
  548. ProtectedPAGE = ~(OptionsBytesStruct.WRPPage) & FLASH_PAGE_TO_BE_PROTECTED;
  549. /* Check if desired pages are already write protected */
  550. if(ProtectedPAGE != 0){
  551. /* Some sectors inside the user flash area are write protected */
  552. return FLASHIF_PROTECTION_WRPENABLED;
  553. }
  554. else{
  555. /* No write protected sectors inside the user flash area */
  556. return FLASHIF_PROTECTION_NONE;
  557. }
  558. }
  559. /**
  560. * @brief Configure the write protection status of user flash area.
  561. * @param protectionstate : FLASHIF_WRP_DISABLE or FLASHIF_WRP_ENABLE the protection
  562. * @retval uint32_t FLASHIF_OK if change is applied.
  563. */
  564. uint32_t FLASH_If_WriteProtectionConfig(uint32_t protectionstate){
  565. uint32_t ProtectedPAGE = 0x0;
  566. FLASH_OBProgramInitTypeDef config_new, config_old;
  567. HAL_StatusTypeDef result = HAL_OK;
  568. /* Get pages write protection status */
  569. HAL_FLASHEx_OBGetConfig(&config_old);
  570. /* The parameter says whether we turn the protection on or off */
  571. config_new.WRPState = (protectionstate == FLASHIF_WRP_ENABLE ? OB_WRPSTATE_ENABLE : OB_WRPSTATE_DISABLE);
  572. /* We want to modify only the Write protection */
  573. config_new.OptionType = OPTIONBYTE_WRP;
  574. /* No read protection, keep BOR and reset settings */
  575. config_new.RDPLevel = OB_RDP_LEVEL_0;
  576. config_new.USERConfig = config_old.USERConfig;
  577. /* Get pages already write protected */
  578. ProtectedPAGE = config_old.WRPPage | FLASH_PAGE_TO_BE_PROTECTED;
  579. /* Unlock the Flash to enable the flash control register access */
  580. HAL_FLASH_Unlock();
  581. /* Unlock the Options Bytes */
  582. HAL_FLASH_OB_Unlock();
  583. /* Erase all the option Bytes */
  584. result = HAL_FLASHEx_OBErase();
  585. if(result == HAL_OK){
  586. config_new.WRPPage = ProtectedPAGE;
  587. result = HAL_FLASHEx_OBProgram(&config_new);
  588. }
  589. return (result == HAL_OK ? FLASHIF_OK : FLASHIF_PROTECTION_ERRROR);
  590. }
  591. /* ymodem *********************************************************************/
  592. /* activate the CRC16 integrity */
  593. #define CRC16_F
  594. /* ATTENTION - please keep this variable 32bit alligned */
  595. uint8_t aPacketData[PACKET_1K_SIZE + PACKET_DATA_INDEX + PACKET_TRAILER_SIZE];
  596. uint8_t aFileName[FILE_NAME_LENGTH];
  597. /**
  598. * @brief Receive a packet from sender
  599. * @param data
  600. * @param length
  601. * 0: end of transmission
  602. * 2: abort by sender
  603. * >0: packet length
  604. * @param timeout
  605. * @retval HAL_OK: normally return
  606. * HAL_BUSY: abort by user
  607. */
  608. uint8_t byteOneTmp = 0;
  609. HAL_StatusTypeDef statusA;
  610. static HAL_StatusTypeDef ReceivePacket(uint8_t* p_data, uint32_t* p_length, uint32_t timeout){
  611. uint32_t crc;
  612. uint32_t packet_size = 0;
  613. HAL_StatusTypeDef status;
  614. uint8_t byteOne;
  615. *p_length = 0;
  616. status = Interface_Receive(&byteOne, 1, timeout);
  617. statusA = status;
  618. byteOneTmp = byteOne;
  619. if(status == HAL_OK){
  620. switch(byteOne){
  621. case SOH:
  622. packet_size = PACKET_SIZE;
  623. break;
  624. case STX:
  625. packet_size = PACKET_1K_SIZE;
  626. break;
  627. case EOT:
  628. break;
  629. case CA:
  630. if((Interface_Receive(&byteOne, 1, timeout) == HAL_OK) && (byteOne == CA)){
  631. packet_size = 2;
  632. }
  633. else{
  634. status = HAL_ERROR;
  635. }
  636. break;
  637. case ABORT1:
  638. case ABORT2:
  639. status = HAL_BUSY;
  640. break;
  641. default:
  642. status = HAL_ERROR;
  643. break;
  644. }
  645. *p_data = byteOne;
  646. if(packet_size >= PACKET_SIZE){
  647. status = Interface_Receive(&p_data[PACKET_NUMBER_INDEX], packet_size + PACKET_OVERHEAD_SIZE, timeout);
  648. /* Simple packet sanity check */
  649. if(status == HAL_OK){
  650. if(p_data[PACKET_NUMBER_INDEX] != ((p_data[PACKET_CNUMBER_INDEX]) ^ NEGATIVE_BYTE)){
  651. packet_size = 0;
  652. status = HAL_ERROR;
  653. }
  654. else{
  655. /* Check packet CRC */
  656. crc = p_data[packet_size + PACKET_DATA_INDEX] << 8;
  657. crc += p_data[packet_size + PACKET_DATA_INDEX + 1];
  658. if(Cal_CRC16(&p_data[PACKET_DATA_INDEX], packet_size) != crc){
  659. packet_size = 0;
  660. status = HAL_ERROR;
  661. }
  662. }
  663. }
  664. else{
  665. packet_size = 0;
  666. }
  667. }
  668. }
  669. *p_length = packet_size;
  670. return status;
  671. }
  672. /**
  673. * @brief Prepare the first block
  674. * @param p_data: output buffer
  675. * @param p_file_name: name of the file to be sent
  676. * @param length: length of the file to be sent in bytes
  677. */
  678. static void PrepareIntialPacket(uint8_t* p_data, const uint8_t* p_file_name, uint32_t length){
  679. uint32_t i, j = 0;
  680. uint8_t astring[10];
  681. /* first 3 bytes are constant */
  682. p_data[PACKET_START_INDEX] = SOH;
  683. p_data[PACKET_NUMBER_INDEX] = 0x00;
  684. p_data[PACKET_CNUMBER_INDEX] = 0xff;
  685. /* Filename written */
  686. for(i = 0; (p_file_name[i] != '\0') && (i < FILE_NAME_LENGTH); i++){
  687. p_data[i + PACKET_DATA_INDEX] = p_file_name[i];
  688. }
  689. p_data[i + PACKET_DATA_INDEX] = 0x00;
  690. /* file size written */
  691. Int2Str(astring, length);
  692. i = i + PACKET_DATA_INDEX + 1;
  693. while(astring[j] != '\0'){
  694. p_data[i++] = astring[j++];
  695. }
  696. /* padding with zeros */
  697. for(j = i; j < PACKET_SIZE + PACKET_DATA_INDEX; j++){
  698. p_data[j] = 0;
  699. }
  700. }
  701. /**
  702. * @brief Prepare the data packet
  703. * @param p_source: pointer to the data to be sent
  704. * @param p_packet: pointer to the output buffer
  705. * @param pkt_nr: number of the packet
  706. * @param size_blk: length of the block to be sent in bytes
  707. */
  708. static void PreparePacket(uint8_t* p_source, uint8_t* p_packet, uint8_t pkt_nr, uint32_t size_blk){
  709. uint8_t* p_record;
  710. uint32_t i, size, packet_size;
  711. /* Make first three packet */
  712. packet_size = size_blk >= PACKET_1K_SIZE ? PACKET_1K_SIZE : PACKET_SIZE;
  713. size = size_blk < packet_size ? size_blk : packet_size;
  714. if(packet_size == PACKET_1K_SIZE){
  715. p_packet[PACKET_START_INDEX] = STX;
  716. }
  717. else{
  718. p_packet[PACKET_START_INDEX] = SOH;
  719. }
  720. p_packet[PACKET_NUMBER_INDEX] = pkt_nr;
  721. p_packet[PACKET_CNUMBER_INDEX] = (~pkt_nr);
  722. p_record = p_source;
  723. /* Filename packet has valid data */
  724. for(i = PACKET_DATA_INDEX; i < size + PACKET_DATA_INDEX; i++){
  725. p_packet[i] = *p_record++;
  726. }
  727. if(size <= packet_size){
  728. for(i = size + PACKET_DATA_INDEX; i < packet_size + PACKET_DATA_INDEX; i++){
  729. p_packet[i] = 0x1A; /* EOF (0x1A) or 0x00 */
  730. }
  731. }
  732. }
  733. /**
  734. * @brief Update CRC16 for input byte
  735. * @param crc_in input value
  736. * @param input byte
  737. */
  738. uint16_t UpdateCRC16(uint16_t crc_in, uint8_t byte){
  739. uint32_t crc = crc_in;
  740. uint32_t in = byte | 0x100;
  741. do{
  742. crc <<= 1;
  743. in <<= 1;
  744. if(in & 0x100)
  745. ++crc;
  746. if(crc & 0x10000)
  747. crc ^= 0x1021;
  748. }
  749. while(!(in & 0x10000));
  750. return crc & 0xffffu;
  751. }
  752. /**
  753. * @brief Cal CRC16 for YModem Packet
  754. * @param data
  755. * @param length
  756. */
  757. uint16_t Cal_CRC16(const uint8_t* p_data, uint32_t size){
  758. uint32_t crc = 0;
  759. const uint8_t* dataEnd = p_data + size;
  760. while(p_data < dataEnd)
  761. crc = UpdateCRC16(crc, *p_data++);
  762. crc = UpdateCRC16(crc, 0);
  763. crc = UpdateCRC16(crc, 0);
  764. return crc & 0xffffu;
  765. }
  766. /**
  767. * @brief Calculate Check sum for YModem Packet
  768. * @param p_data Pointer to input data
  769. * @param size length of input data
  770. * @retval uint8_t checksum value
  771. */
  772. uint8_t CalcChecksum(const uint8_t* p_data, uint32_t size){
  773. uint32_t sum = 0;
  774. const uint8_t* p_data_end = p_data + size;
  775. while(p_data < p_data_end){
  776. sum += *p_data++;
  777. }
  778. return (sum & 0xffu);
  779. }
  780. /* Public functions ---------------------------------------------------------*/
  781. /**
  782. * @brief Receive a file using the ymodem protocol with CRC16.
  783. * @param p_size The size of the file.
  784. * @retval COM_StatusTypeDef result of reception/programming
  785. */
  786. HAL_StatusTypeDef statA = HAL_OK;
  787. uint16_t packets_received;
  788. COM_StatusTypeDef Ymodem_Receive(uint32_t* p_size){
  789. uint32_t i, packet_length, session_done = 0, file_done, errors = 0, session_begin = 0;
  790. uint32_t flashdestination, ramsource, filesize;
  791. uint8_t* file_ptr;
  792. uint8_t file_size[FILE_SIZE_LENGTH], tmp;
  793. COM_StatusTypeDef result = COM_OK;
  794. /* Initialize flashdestination variable */
  795. flashdestination = APPLICATION_ADDRESS;
  796. while((session_done == 0) && (result == COM_OK)){
  797. packets_received = 0;
  798. file_done = 0;
  799. while((file_done == 0) && (result == COM_OK)){
  800. statA = ReceivePacket(aPacketData, &packet_length, DOWNLOAD_TIMEOUT);
  801. switch(statA){
  802. case HAL_OK:
  803. errors = 0;
  804. switch(packet_length){
  805. case 2:
  806. /* Abort by sender */
  807. Interface_PutByte(ACK);
  808. result = COM_ABORT;
  809. break;
  810. case 0:
  811. /* End of transmission */
  812. Interface_PutByte(ACK);
  813. file_done = 1;
  814. break;
  815. default:
  816. /* Normal packet */
  817. if(aPacketData[PACKET_NUMBER_INDEX] != (packets_received % 256)){
  818. Interface_PutByte(NAK);
  819. }
  820. else{
  821. if(packets_received == 0){
  822. /* File name packet */
  823. if(aPacketData[PACKET_DATA_INDEX] != 0){
  824. /* File name extraction */
  825. i = 0;
  826. file_ptr = aPacketData + PACKET_DATA_INDEX;
  827. while((*file_ptr != 0) && (i < FILE_NAME_LENGTH)){
  828. aFileName[i++] = *file_ptr++;
  829. }
  830. /* File size extraction */
  831. aFileName[i++] = '\0';
  832. i = 0;
  833. file_ptr++;
  834. while((*file_ptr != ' ') && (i < FILE_SIZE_LENGTH)){
  835. file_size[i++] = *file_ptr++;
  836. }
  837. file_size[i++] = '\0';
  838. Str2Int(file_size, &filesize);
  839. /* Test the size of the image to be sent */
  840. /* Image size is greater than Flash size */
  841. if(*p_size > (USER_FLASH_SIZE + 1)){
  842. /* End session */
  843. tmp = CA;
  844. Interface_Transmit(&tmp, 1, NAK_TIMEOUT);
  845. Interface_Transmit(&tmp, 1, NAK_TIMEOUT);
  846. result = COM_LIMIT;
  847. }
  848. /* Erase user application area */
  849. FLASH_If_Erase(APPLICATION_ADDRESS);
  850. *p_size = filesize;
  851. Interface_PutByte(ACK);
  852. Interface_PutByte(CRC16);
  853. }
  854. /* File header packet is empty, end session */
  855. else{
  856. Interface_PutByte(ACK);
  857. file_done = 1;
  858. session_done = 1;
  859. break;
  860. }
  861. }
  862. else /* Data packet */
  863. {
  864. ramsource = (uint32_t)&aPacketData[PACKET_DATA_INDEX];
  865. /* Write received data in Flash */
  866. if(FLASH_If_Write(flashdestination, (uint32_t*)ramsource, packet_length / 4) == FLASHIF_OK){
  867. flashdestination += packet_length;
  868. Interface_PutByte(ACK);
  869. }
  870. else /* An error occurred while writing to Flash memory */
  871. {
  872. /* End session */
  873. Interface_PutByte(CA);
  874. Interface_PutByte(CA);
  875. result = COM_DATA;
  876. }
  877. }
  878. packets_received++;
  879. session_begin = 1;
  880. }
  881. break;
  882. }
  883. break;
  884. case HAL_BUSY: /* Abort actually */
  885. Interface_PutByte(CA);
  886. Interface_PutByte(CA);
  887. result = COM_ABORT;
  888. break;
  889. default:
  890. if(session_begin > 0){
  891. errors++;
  892. }
  893. if(errors > MAX_ERRORS){
  894. /* Abort communication */
  895. Interface_PutByte(CA);
  896. Interface_PutByte(CA);
  897. }
  898. else{
  899. /* Ask for a packet */
  900. Interface_PutByte(CRC16);
  901. }
  902. break;
  903. }
  904. }
  905. }
  906. return result;
  907. }
  908. /**
  909. * @brief Transmit a file using the ymodem protocol
  910. * @param p_buf: Address of the first byte
  911. * @param p_file_name: Name of the file sent
  912. * @param file_size: Size of the transmission
  913. * @retval COM_StatusTypeDef result of the communication
  914. */
  915. COM_StatusTypeDef Ymodem_Transmit(uint8_t* p_buf, const uint8_t* p_file_name, uint32_t file_size){
  916. uint32_t errors = 0, ack_recpt = 0, size = 0, pkt_size;
  917. uint8_t* p_buf_int;
  918. COM_StatusTypeDef result = COM_OK;
  919. uint32_t blk_number = 1;
  920. uint8_t a_rx_ctrl[2];
  921. uint8_t i;
  922. #ifdef CRC16_F
  923. uint32_t temp_crc;
  924. #else /* CRC16_F */
  925. uint8_t temp_chksum;
  926. #endif /* CRC16_F */
  927. /* Prepare first block - header */
  928. PrepareIntialPacket(aPacketData, p_file_name, file_size);
  929. while((!ack_recpt) && (result == COM_OK)){
  930. /* Send Packet */
  931. Interface_Transmit(&aPacketData[PACKET_START_INDEX], PACKET_SIZE + PACKET_HEADER_SIZE, NAK_TIMEOUT);
  932. /* Send CRC or Check Sum based on CRC16_F */
  933. #ifdef CRC16_F
  934. temp_crc = Cal_CRC16(&aPacketData[PACKET_DATA_INDEX], PACKET_SIZE);
  935. Interface_PutByte(temp_crc >> 8);
  936. Interface_PutByte(temp_crc & 0xFF);
  937. #else /* CRC16_F */
  938. temp_chksum = CalcChecksum(&aPacketData[PACKET_DATA_INDEX], PACKET_SIZE);
  939. Interface_PutByte(temp_chksum);
  940. #endif /* CRC16_F */
  941. /* Wait for Ack and 'C' */
  942. if(Interface_Receive(&a_rx_ctrl[0], 1, NAK_TIMEOUT) == HAL_OK){
  943. if(a_rx_ctrl[0] == ACK){
  944. ack_recpt = 1;
  945. }
  946. else if(a_rx_ctrl[0] == CA){
  947. if((Interface_Receive(&a_rx_ctrl[0], 1, NAK_TIMEOUT) == HAL_OK) && (a_rx_ctrl[0] == CA)){
  948. HAL_Delay(2);
  949. Interface_Clean();
  950. result = COM_ABORT;
  951. }
  952. }
  953. else if(a_rx_ctrl[0] == ABORT1 || a_rx_ctrl[0] == ABORT2){
  954. result = COM_ABORT;
  955. }
  956. }
  957. else{
  958. errors++;
  959. }
  960. if(errors >= MAX_ERRORS){
  961. result = COM_ERROR;
  962. }
  963. }
  964. p_buf_int = p_buf;
  965. size = file_size;
  966. /* Here 1024 bytes length is used to send the packets */
  967. while((size) && (result == COM_OK)){
  968. /* Prepare next packet */
  969. PreparePacket(p_buf_int, aPacketData, blk_number, size);
  970. ack_recpt = 0;
  971. a_rx_ctrl[0] = 0;
  972. errors = 0;
  973. /* Resend packet if NAK for few times else end of communication */
  974. while((!ack_recpt) && (result == COM_OK)){
  975. /* Send next packet */
  976. if(size >= PACKET_1K_SIZE){
  977. pkt_size = PACKET_1K_SIZE;
  978. }
  979. else{
  980. pkt_size = PACKET_SIZE;
  981. }
  982. Interface_Transmit(&aPacketData[PACKET_START_INDEX], pkt_size + PACKET_HEADER_SIZE, NAK_TIMEOUT);
  983. /* Send CRC or Check Sum based on CRC16_F */
  984. #ifdef CRC16_F
  985. temp_crc = Cal_CRC16(&aPacketData[PACKET_DATA_INDEX], pkt_size);
  986. Interface_PutByte(temp_crc >> 8);
  987. Interface_PutByte(temp_crc & 0xFF);
  988. #else /* CRC16_F */
  989. temp_chksum = CalcChecksum(&aPacketData[PACKET_DATA_INDEX], pkt_size);
  990. Interface_PutByte(temp_chksum);
  991. #endif /* CRC16_F */
  992. /* Wait for Ack */
  993. if((Interface_Receive(&a_rx_ctrl[0], 1, NAK_TIMEOUT) == HAL_OK) && (a_rx_ctrl[0] == ACK)){
  994. ack_recpt = 1;
  995. if(size > pkt_size){
  996. p_buf_int += pkt_size;
  997. size -= pkt_size;
  998. if(blk_number == (USER_FLASH_SIZE / PACKET_1K_SIZE)){
  999. result = COM_LIMIT; /* boundary error */
  1000. }
  1001. else{
  1002. blk_number++;
  1003. }
  1004. }
  1005. else{
  1006. p_buf_int += pkt_size;
  1007. size = 0;
  1008. }
  1009. }
  1010. else{
  1011. errors++;
  1012. }
  1013. /* Resend packet if NAK for a count of 10 else end of communication */
  1014. if(errors >= MAX_ERRORS){
  1015. result = COM_ERROR;
  1016. }
  1017. }
  1018. }
  1019. /* Sending End Of Transmission char */
  1020. ack_recpt = 0;
  1021. a_rx_ctrl[0] = 0x00;
  1022. errors = 0;
  1023. while((!ack_recpt) && (result == COM_OK)){
  1024. Interface_PutByte(EOT);
  1025. /* Wait for Ack */
  1026. if(Interface_Receive(&a_rx_ctrl[0], 1, NAK_TIMEOUT) == HAL_OK){
  1027. if(a_rx_ctrl[0] == ACK){
  1028. ack_recpt = 1;
  1029. }
  1030. else if(a_rx_ctrl[0] == CA){
  1031. if((Interface_Receive(&a_rx_ctrl[0], 1, NAK_TIMEOUT) == HAL_OK) && (a_rx_ctrl[0] == CA)){
  1032. HAL_Delay(2);
  1033. Interface_Clean();
  1034. result = COM_ABORT;
  1035. }
  1036. }
  1037. }
  1038. else{
  1039. errors++;
  1040. }
  1041. if(errors >= MAX_ERRORS){
  1042. result = COM_ERROR;
  1043. }
  1044. }
  1045. /* Empty packet sent - some terminal emulators need this to close session */
  1046. if(result == COM_OK){
  1047. /* Preparing an empty packet */
  1048. aPacketData[PACKET_START_INDEX] = SOH;
  1049. aPacketData[PACKET_NUMBER_INDEX] = 0;
  1050. aPacketData[PACKET_CNUMBER_INDEX] = 0xFF;
  1051. for(i = PACKET_DATA_INDEX; i < (PACKET_SIZE + PACKET_DATA_INDEX); i++){
  1052. aPacketData[i] = 0x00;
  1053. }
  1054. /* Send Packet */
  1055. Interface_Transmit(&aPacketData[PACKET_START_INDEX], PACKET_SIZE + PACKET_HEADER_SIZE, NAK_TIMEOUT);
  1056. /* Send CRC or Check Sum based on CRC16_F */
  1057. #ifdef CRC16_F
  1058. temp_crc = Cal_CRC16(&aPacketData[PACKET_DATA_INDEX], PACKET_SIZE);
  1059. Interface_PutByte(temp_crc >> 8);
  1060. Interface_PutByte(temp_crc & 0xFF);
  1061. #else /* CRC16_F */
  1062. temp_chksum = CalcChecksum(&aPacketData[PACKET_DATA_INDEX], PACKET_SIZE);
  1063. Interface_PutByte(temp_chksum);
  1064. #endif /* CRC16_F */
  1065. /* Wait for Ack and 'C' */
  1066. if(Interface_Receive(&a_rx_ctrl[0], 1, NAK_TIMEOUT) == HAL_OK){
  1067. if(a_rx_ctrl[0] == CA){
  1068. HAL_Delay(2);
  1069. Interface_Clean();
  1070. result = COM_ABORT;
  1071. }
  1072. }
  1073. }
  1074. return result; /* File transmitted successfully */
  1075. }
  1076. #endif /* __IAP_YMODEM_STM32F1_ATY_C */
  1077. /******************************** End Of File *********************************/