#include "ModuleHTTP.h" #include #include #include using namespace httplib; namespace mdd{ bool ModuleHTTP::connect(){ Client cli(_id, _port); std::string body; auto res = cli.Get("/status", [&](const char *data, size_t data_length) { body.append(data, data_length); return true; }); //assert(res->body.empty()); if(body.empty()){ return false; } body = std::string(R"()") + body; json status = json::parse(body.c_str()); if (status["status"].get() == "ready"){ return true; } else{ return false; } } std::string ModuleHTTP::str_to_json(const std::string& input){ if(input.empty()){ return input; } std::string str = input; size_t start_pos = 0; while((start_pos = str.find('[', start_pos)) != std::string::npos) { str.replace(start_pos, 1, "{"); start_pos += 1; } start_pos = 0; while((start_pos = str.find(']', start_pos)) != std::string::npos) { str.replace(start_pos, 1, "}"); start_pos += 1; } return str; } void ModuleHTTP::updateLayout(){ Client cli(_id, _port); std::string body; auto res = cli.Get("/inputs", [&](const char *data, size_t data_length) { body.append(data, data_length); return true; }); assert(res->body.empty()); body = std::string(R"()") + body; json inputs = json::parse(body.c_str()); for(int j = 0; j < (int)getInputs().size()-(int)inputs.size(); ++j){ pop_backInput(); } for(size_t i=0; i < getInputs().size(); i++){ getInput(i)->setType(inputs[i]["type"].get()); getInput(i)->setAppendix(i); getInput(i)->setDefaultValue() = inputs[i]; } for(int index = getInputs().size(); index < inputs.size(); ++index){ json val; val["value"] = inputs[index]["value"]; addInput(inputs[index]["type"].get(),val); } body.clear(); res = cli.Get("/outputs", [&](const char *data, size_t data_length) { body.append(data, data_length); return true; }); assert(res->body.empty()); body = std::string(R"()") + body; json outputs = json::parse(body); for(int j = 0; j < (int)getOutputs().size()-(int)outputs.size(); ++j){ pop_backOutput(); } for(size_t i=0; i < getOutputs().size(); i++){ getOutput(i)->setType(outputs[i]["type"].get()); getOutput(i)->setAppendix(i); getOutput(i)->getValueInternal() = outputs[i]; } for(int index = getOutputs().size(); index < outputs.size(); ++index){ json val; val["value"] = outputs[index]["value"]; addOutput(outputs[index]["type"].get(),val); } } ModuleHTTP::ModuleHTTP(std::string fname, std::string id, int port): _fname(fname), _id(id), _port(port) { if(!fname.empty()){ std::string command = "python3 " + fname+"&"; system(command.c_str()); } while(!connect()){ usleep(1000); } updateLayout(); } bool ModuleHTTP::update() { updateLayout(); /*Client cli(_id, _port); std::string outputs; auto res = cli.Get("/update", [&](const char *data, size_t data_length) { outputs.append(data, data_length); return true; }); */ } }