api-hal-spi.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "api-hal-spi.h"
  2. #include <cmsis_os2.h>
  3. #include <stdbool.h>
  4. #include <string.h>
  5. osMutexId_t spi_mutex_r;
  6. osMutexId_t spi_mutex_d;
  7. extern SPI_HandleTypeDef SPI_R;
  8. extern SPI_HandleTypeDef SPI_D;
  9. extern void Enable_SPI(SPI_HandleTypeDef* spi);
  10. void api_hal_spi_init() {
  11. spi_mutex_r = osMutexNew(NULL);
  12. spi_mutex_d = osMutexNew(NULL);
  13. }
  14. void api_hal_spi_apply_config(const SPIDevice* device) {
  15. osKernelLock();
  16. memcpy(&device->spi->Init, &device->config, sizeof(SPI_InitTypeDef));
  17. if(HAL_SPI_Init(device->spi) != HAL_OK) {
  18. Error_Handler();
  19. }
  20. Enable_SPI(device->spi);
  21. osKernelUnlock();
  22. }
  23. bool api_hal_spi_config_are_actual(const SPIDevice* device) {
  24. return (memcmp(&device->config, &device->spi->Init, sizeof(SPI_InitTypeDef)) == 0);
  25. }
  26. void api_hal_spi_config_device(const SPIDevice* device) {
  27. if(!api_hal_spi_config_are_actual(device)) {
  28. api_hal_spi_apply_config(device);
  29. }
  30. }
  31. void api_hal_spi_lock(SPI_HandleTypeDef* spi) {
  32. if(spi == &SPI_D) {
  33. osMutexAcquire(spi_mutex_d, osWaitForever);
  34. } else if(spi == &SPI_R) {
  35. osMutexAcquire(spi_mutex_r, osWaitForever);
  36. } else {
  37. Error_Handler();
  38. }
  39. }
  40. void api_hal_spi_unlock(SPI_HandleTypeDef* spi) {
  41. if(spi == &SPI_D) {
  42. osMutexRelease(spi_mutex_d);
  43. } else if(spi == &SPI_R) {
  44. osMutexRelease(spi_mutex_r);
  45. } else {
  46. Error_Handler();
  47. }
  48. }
  49. void api_hal_spi_lock_device(const SPIDevice* device) {
  50. api_hal_spi_lock(device->spi);
  51. api_hal_spi_config_device(device);
  52. }
  53. void api_hal_spi_unlock_device(const SPIDevice* device) {
  54. api_hal_spi_unlock(device->spi);
  55. }