commprt.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. * commprt.c
  3. *
  4. * Created on: Jan 25, 2022
  5. * Author: radioman
  6. */
  7. #include <string.h>
  8. #include "stm32l1xx_hal.h"
  9. #include "commprt.h"
  10. #include "uartio.h"
  11. #include "usbd_cdc_if.h"
  12. #define COMM_HEADER_BYTE 0x55
  13. #define COMM_BUFFER_SIZE 260
  14. extern UART_HandleTypeDef huart1;
  15. static uint8_t comm_txbuffer[COMM_BUFFER_SIZE];
  16. static uint8_t comm_rxbuffer[COMM_BUFFER_SIZE];
  17. uint8_t COMM_Checksum(const uint8_t *data, uint8_t len)
  18. {
  19. uint8_t chk = 0;
  20. while(len--)
  21. chk ^= data[len];
  22. return chk;
  23. }
  24. COMM_StatusTypeDef COMM_Receive(uint8_t *buf, COMM_IfaceTypeDef iface, uint32_t timeout)
  25. {
  26. uint8_t header = 0, psize = 0;
  27. uint32_t stime = HAL_GetTick();
  28. int (*read_data)(uint8_t*, uint32_t);
  29. uint32_t (*data_avail)(void);
  30. if(iface == COMM_BT)
  31. {
  32. read_data = UARTIO_Receive;
  33. data_avail = UARTIO_DataAvailable;
  34. }
  35. if(iface == COMM_USB)
  36. {
  37. read_data = CDC_ReadData;
  38. data_avail = CDC_DataAvailable;
  39. }
  40. while((header != COMM_HEADER_BYTE))
  41. {
  42. if(read_data(&header, 1) <= 0)
  43. return COMM_FAIL;
  44. if((HAL_GetTick() - stime) > timeout)
  45. return COMM_TIMEOUT;
  46. }
  47. while(read_data(&psize, 1) != 1)
  48. {
  49. if((HAL_GetTick() - stime) > timeout)
  50. return COMM_TIMEOUT;
  51. }
  52. if(psize == 0)
  53. return COMM_FAIL;
  54. while(data_avail() < (psize + 1))
  55. {
  56. if((HAL_GetTick() - stime) > timeout)
  57. return COMM_TIMEOUT;
  58. }
  59. read_data(comm_rxbuffer, psize + 1);
  60. uint8_t checksum = (COMM_HEADER_BYTE ^ psize) ^ COMM_Checksum(comm_rxbuffer, psize);
  61. if(checksum != comm_rxbuffer[psize])
  62. return COMM_CHECKSUM_MISTMATCH;
  63. memcpy(buf, comm_rxbuffer, psize);
  64. return COMM_OK;
  65. }
  66. COMM_StatusTypeDef COMM_Transmit(uint8_t *data, uint8_t len, COMM_IfaceTypeDef iface)
  67. {
  68. comm_txbuffer[0] = COMM_HEADER_BYTE;
  69. comm_txbuffer[1] = len;
  70. memcpy(&comm_txbuffer[2], data, len);
  71. comm_txbuffer[len + 2] = COMM_Checksum(comm_txbuffer, len + 2);
  72. int (*write_data)(uint8_t*, uint32_t);
  73. if(iface == COMM_BT)
  74. write_data = UARTIO_Transmit;
  75. if(iface == COMM_USB)
  76. write_data = CDC_WriteData;
  77. if(write_data(data, len) > 0)
  78. return COMM_OK;
  79. else
  80. return COMM_FAIL;
  81. }