Control requests
Handler using Variant - Control requests
The Variant API is generally much easier to use but requires Device OS 6.2 or later.
void ctrl_request_custom_handler(ctrl_request *req) {
int result = SYSTEM_ERROR_NOT_SUPPORTED;
// Parse the incoming request as JSON
String reqData(req->request_data, req->request_size);
Variant reqVar = Variant::fromJSON(reqData.c_str());
// Optionally fill this in with JSON data to return by USB control request
Variant respVar;
// Read the "op" value out of the JSON. You can use a different key.
String op = reqVar.get("op").asString();
Log.info("Request received op=%s %s", op.c_str(), reqVar.toJSON().c_str());
if (op == "test") {
// If "op" is "test" then do something here
respVar.set("counter", ++counter);
respVar.set("result", 0);
result = SYSTEM_ERROR_NONE;
}
if (respVar.isMap()) {
// If respVar is a JSON object, then return it to the caller.
String respJson = respVar.toJSON();
if (respJson.length()) {
if (system_ctrl_alloc_reply_data(req, respJson.length(), nullptr) == 0) {
memcpy(req->reply_data, respJson.c_str(), respJson.length());
} else {
result = SYSTEM_ERROR_NO_MEMORY;
}
Log.info("response %s", respJson.c_str());
}
}
system_ctrl_set_result(req, result, nullptr, nullptr, nullptr);
}