#include #include #include "modbus_bridge.h" static int cmd_modbus_set_baud(const struct shell *sh, size_t argc, char **argv) { if (argc != 2) { shell_error(sh, "Usage: set_baud "); return -EINVAL; } uint32_t new_baud = (uint32_t)strtoul(argv[1], NULL, 10); const uint32_t valid_baud_rates[] = {1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200}; bool is_valid = false; for (int i = 0; i < ARRAY_SIZE(valid_baud_rates); i++) { if (new_baud == valid_baud_rates[i]) { is_valid = true; break; } } if (!is_valid) { char error_msg[128]; int offset = snprintf(error_msg, sizeof(error_msg), "Invalid baudrate. Valid rates are: "); for (int i = 0; i < ARRAY_SIZE(valid_baud_rates); i++) { offset += snprintf(error_msg + offset, sizeof(error_msg) - offset, "%u ", valid_baud_rates[i]); } shell_error(sh, "%s", error_msg); return -EINVAL; } if (modbus_reconfigure(new_baud, modbus_get_unit_id()) != 0) { shell_error(sh, "Failed to apply new baudrate"); } else { shell_print(sh, "Modbus baudrate set to: %u", new_baud); } return 0; } static int cmd_modbus_set_id(const struct shell *sh, size_t argc, char **argv) { if (argc != 2) { shell_error(sh, "Usage: set_id "); return -EINVAL; } uint32_t new_id = (uint32_t)strtoul(argv[1], NULL, 10); if (new_id == 0 || new_id > 247) { shell_error(sh, "Invalid slave ID: %s. Must be between 1 and 247.", argv[1]); return -EINVAL; } if (modbus_reconfigure(modbus_get_baudrate(), (uint8_t)new_id) != 0) { shell_error(sh, "Failed to apply new slave ID"); } else { shell_print(sh, "Modbus slave ID set to: %u", (uint8_t)new_id); } return 0; } static int cmd_modbus_show(const struct shell *sh, size_t argc, char **argv) { shell_print(sh, "Current Modbus Configuration:"); shell_print(sh, " Baudrate: %u", modbus_get_baudrate()); shell_print(sh, " Slave ID: %u", modbus_get_unit_id()); return 0; } SHELL_STATIC_SUBCMD_SET_CREATE(sub_modbus_cmds, SHELL_CMD(set_baud, NULL, "Set Modbus baudrate", cmd_modbus_set_baud), SHELL_CMD(set_id, NULL, "Set Modbus slave ID", cmd_modbus_set_id), SHELL_CMD(show, NULL, "Show current Modbus configuration", cmd_modbus_show), SHELL_SUBCMD_SET_END ); SHELL_CMD_REGISTER(modbus, &sub_modbus_cmds, "Modbus configuration", NULL);