A serial command line interface with buffer editing.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.2 KiB

3 months ago
  1. #include <cmd.h>
  2. // Global command variable.
  3. Cmd *cmd;
  4. // Command entered was invalid, or help is being requested.
  5. void cmd_unrecognized(Cmd *thisCmd, char *command, bool printHelp) {
  6. // If help is being requested, print the available commands.
  7. if (printHelp) {
  8. // Get the command parameters.
  9. size_t size = cmd->GetSize();
  10. PGM_P *commands = cmd->GetCmds();
  11. // Print each command.
  12. Serial.println("Available commands:\n");
  13. for (int i = 0; i < size && commands[i] != NULL; i++) {
  14. char buf[100];
  15. sprintf_P(buf, commands[i]);
  16. Serial.println(buf);
  17. }
  18. // Stop here.
  19. return;
  20. }
  21. // No help was requested, so the command provided likely doesn't exist.
  22. Serial.print("Unrecognized command [");
  23. Serial.print(command);
  24. Serial.println("]");
  25. }
  26. // Simple echo ping command.
  27. void cmd_pi(Cmd *thisCmd, char *command, bool printHelp) {
  28. // If help was requested, print the help for this command.
  29. if (printHelp) {
  30. Serial.print(command);
  31. Serial.println(" *");
  32. return;
  33. }
  34. // Echo back the buffer.
  35. Serial.println(cmd->GetBuffer());
  36. }
  37. // Demo send command.
  38. void cmd_send(Cmd *thisCmd, char *command, bool printHelp) {
  39. // If help was requested, print the help.
  40. if (printHelp) {
  41. Serial.print(command);
  42. Serial.println(" address code");
  43. return;
  44. }
  45. // Parse the next available argument.
  46. char *parsed = cmd->Parse();
  47. if (parsed == NULL) {
  48. Serial.println("Invalid address");
  49. return;
  50. }
  51. // Parse integer.
  52. int address = atoi(parsed);
  53. // Get the next argument.
  54. parsed = cmd->Parse();
  55. if (parsed == NULL) {
  56. Serial.println("Invalid code");
  57. return;
  58. }
  59. // Parse char.
  60. unsigned char code = atoi(parsed);
  61. // Print parsed arguments.
  62. Serial.print("Sending code: ");
  63. Serial.print(code);
  64. Serial.print(" to <");
  65. Serial.print(address);
  66. Serial.println(">");
  67. }
  68. void setup() {
  69. // Setup serial interface.
  70. Serial.begin(9600);
  71. // Initialize the command line with 2 commands.
  72. cmd = new Cmd(2, cmd_unrecognized);
  73. // Add commands.
  74. cmd->AddCmd(PSTR("pi"), cmd_pi);
  75. cmd->AddCmd(PSTR("send"), cmd_send);
  76. // Print a line indicator to inform the user the cli is ready.
  77. Serial.print(cmd->GetLineIndicator());
  78. }
  79. void loop() {
  80. // Run the command line loop.
  81. cmd->Loop();
  82. }