ffx_master.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //
  2. // Created by DELL on 2024/10/16.
  3. //
  4. #include "ffx_master.h"
  5. #include "modbus.h"
  6. #include "usart.h"
  7. #include "cmsis_os2.h"
  8. static nmbs_t nmbs;
  9. static uint8_t slaves[] = {0}; // 保存已经存在的从站号
  10. static uint8_t index = 0;
  11. static int32_t uart_read(uint8_t *buf, uint16_t count, int32_t byte_timeout_ms,
  12. void *arg) {
  13. HAL_StatusTypeDef status = HAL_UART_Receive(&huart2, buf, count, byte_timeout_ms);
  14. if (status == HAL_OK) {
  15. return count;
  16. } else {
  17. return 0;
  18. }
  19. }
  20. static int32_t uart_write(const uint8_t *buf, uint16_t count, int32_t byte_timeout_ms,
  21. void *arg) {
  22. HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_SET);
  23. HAL_UART_Transmit(&huart2, buf, count, byte_timeout_ms);
  24. HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_RESET);
  25. return count;
  26. }
  27. _Noreturn void ffx_mater_task(void *pv) {
  28. for (;;) {
  29. for (int i = 0; i < sizeof(slaves); i++) {
  30. nmbs_set_destination_rtu_address(&nmbs, slaves[i]);
  31. uint16_t data[2];
  32. ffx_status_t ffxStatus;
  33. nmbs_error err = nmbs_read_holding_registers(&nmbs, POWER_REG_ADDRESS, 2, data);
  34. if(err == NMBS_ERROR_NONE) {
  35. // TODO:
  36. ffxStatus.power = data[0];
  37. ffxStatus.mode = data[1];
  38. }
  39. // 发送到消息队列
  40. }
  41. osDelay(3000);
  42. }
  43. }
  44. // 检测从机是否存在
  45. bool check_slave_exist(uint8_t slave_addr) {
  46. nmbs_set_destination_rtu_address(&nmbs, slave_addr);
  47. uint16_t result;
  48. nmbs_error err = nmbs_read_holding_registers(&nmbs, 0x01, 1, &result);
  49. return err == NMBS_ERROR_NONE;
  50. }
  51. // 轮询从站
  52. void search_ffx_slave() {
  53. for (int i = SLAVE_ADDRESS_START; i <= SLAVE_ADDRESS_END; i++) {
  54. bool exist = check_slave_exist(i);
  55. if (exist) {
  56. slaves[index] = i;
  57. index++;
  58. }
  59. }
  60. index = 0;
  61. }
  62. void ffx_master_init() {
  63. nmbs_platform_conf platformConf;// 配置uart
  64. platformConf.transport = NMBS_TRANSPORT_RTU;// RTU
  65. platformConf.read = &uart_read; // 读写函数
  66. platformConf.write = &uart_write; // 读写函数
  67. nmbs_client_create(&nmbs, &platformConf);// 创建客户端
  68. nmbs_set_read_timeout(&nmbs, 1000);//
  69. nmbs_set_byte_timeout(&nmbs, 1000);
  70. search_ffx_slave();
  71. // 开启轮询任务
  72. osThreadNew(ffx_mater_task, NULL, NULL);
  73. }