// // Created by DELL on 2024/10/16. // #include "ffx_master.h" #include "modbus.h" #include "usart.h" #include "cmsis_os2.h" static nmbs_t nmbs; static uint8_t slaves[] = {0}; // 保存已经存在的从站号 static uint8_t index = 0; static int32_t uart_read(uint8_t *buf, uint16_t count, int32_t byte_timeout_ms, void *arg) { HAL_StatusTypeDef status = HAL_UART_Receive(&huart2, buf, count, byte_timeout_ms); if (status == HAL_OK) { return count; } else { return 0; } } static int32_t uart_write(const uint8_t *buf, uint16_t count, int32_t byte_timeout_ms, void *arg) { HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_SET); HAL_UART_Transmit(&huart2, buf, count, byte_timeout_ms); HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_RESET); return count; } _Noreturn void ffx_mater_task(void *pv) { for (;;) { for (int i = 0; i < sizeof(slaves); i++) { nmbs_set_destination_rtu_address(&nmbs, slaves[i]); uint16_t data[2]; ffx_status_t ffxStatus; nmbs_error err = nmbs_read_holding_registers(&nmbs, POWER_REG_ADDRESS, 2, data); if(err == NMBS_ERROR_NONE) { // TODO: ffxStatus.power = data[0]; ffxStatus.mode = data[1]; } // 发送到消息队列 } osDelay(3000); } } // 检测从机是否存在 bool check_slave_exist(uint8_t slave_addr) { nmbs_set_destination_rtu_address(&nmbs, slave_addr); uint16_t result; nmbs_error err = nmbs_read_holding_registers(&nmbs, 0x01, 1, &result); return err == NMBS_ERROR_NONE; } // 轮询从站 void search_ffx_slave() { for (int i = SLAVE_ADDRESS_START; i <= SLAVE_ADDRESS_END; i++) { bool exist = check_slave_exist(i); if (exist) { slaves[index] = i; index++; } } index = 0; } void ffx_master_init() { nmbs_platform_conf platformConf;// 配置uart platformConf.transport = NMBS_TRANSPORT_RTU;// RTU platformConf.read = &uart_read; // 读写函数 platformConf.write = &uart_write; // 读写函数 nmbs_client_create(&nmbs, &platformConf);// 创建客户端 nmbs_set_read_timeout(&nmbs, 1000);// nmbs_set_byte_timeout(&nmbs, 1000); search_ffx_slave(); // 开启轮询任务 osThreadNew(ffx_mater_task, NULL, NULL); }