在实际开发中经常会遇到简单调试接口的场景,需要从键盘输入一个字符,响应相应操作,整体逻辑就是
1.获取键盘输入
2.执行操作
3.再次等待获取键盘输入
虽然上述步骤极其容易但是总归是需要时间去拉一个demo,下面给出demo 用例,便于大家修改测试
#include <iostream>
#include <string>
#include <vector>#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>using namespace std;
void PrintTestList()
{cout << "*--------------------------------------------------*" << endl;cout << "| _______ ______ ____ _______ |" << endl;cout << "| | | | | |" << endl;cout << "| | |_____ |____ | |" << endl;cout << "| | | | | |" << endl;cout << "| | |______ ____| | |" << endl;cout << "| |" << endl;cout << "|UAV control_valve |" << endl;cout << "| 1 : control_take_off 3: control |" << endl;cout << "| 2 : control_turn_off |" << endl;cout << "| |" << endl;cout << "| |" << endl;cout << "|0:Exit. lt |" << endl;cout << "*--------------------------------------------------*" << endl;}std::string GetInput()
{std::string input;(void)getline(std::cin, input);if (input == "") {return "";}return input;
}int GetIntInput()
{std::string input;(void)getline(std::cin, input);if (input == "") {return -1;}int inputIndex = stoi(input);if (inputIndex < 0) {cout << "invalid input" << endl;return -1;}return inputIndex;
}int DOControllerEngine(string deviceId, string cmd)
{int ret = EM_ERR_OK;string input = "";string output = "";ret = ControllerEngine::GetInstance()->ExecCommand(deviceId, cmd, "input", output);if (ret != EM_ERR_OK) {std::cout << "ExecCommand " << deviceId << cmd << "failed. ret=" << ret << ", output: " << output << std::endl;} else {std::cout << "ExecCommand " << deviceId << cmd << "success." << ", output: " << output << std::endl;}return ret;
}int DOControllerEngine(string deviceId, string cmd, string &input, string &output)
{int ret = EM_ERR_OK;ret = ControllerEngine::GetInstance()->ExecCommand(deviceId, cmd, input, output);if (ret != EM_ERR_OK) {std::cout << "ExecCommand " << deviceId << cmd << "failed. ret=" << ret << ", output: " << output << std::endl;} else {std::cout << "ExecCommand " << deviceId << cmd << "success." << ", output: " << output << std::endl;}return ret;
}int main()
{while (true) {PrintTestList();switch (GetIntInput()) {case 0:goto EXIT;break;case 1:DOControllerEngine("kaihong_controller_uav_001","control_take_off");break;case 2:DOControllerEngine("kaihong_controller_uav_001","control_turn_off");break;case 3: {cout << "Please enter a percentage value (0 ~ 100) :" ;int num = GetIntInput();char buf[1024] = {0};//sprintf(buf,"{\"name\":\"status\",\"value\":%d}",num);sprintf(buf,"[{\"name\" : \"status\",\"value\" : %d }]",num);string output;string input(buf);cout << buf << endl;DOControllerEngine("control_valve_dl_001","control",input,output);break;}case 4: {break;}case 5:{break;}case 6: break;case 7:break;case 8:break;case 9:break;default:cout << "invalid input" << endl;break;}}
EXIT:return 0;
}