#include #include #include #include #include #include #include "api_v1_controllers.h" using namespace api::v1; void controllers::get_relays_all(const HttpRequestPtr &req, std::function &&callback, const std::string& controller_id) { relay_dbo **all_controller_relays = relay_dbo::get_by_simple("controller_id", (void *) controller_id.c_str(), (intptr_t) sqlite3_bind_text); Json::Value all_relays_json(Json::arrayValue); for(int i = 0; all_controller_relays[i] != nullptr; i++) { all_relays_json.append(all_controller_relays[i]->to_json()); } auto resp = HttpResponse::newHttpJsonResponse(all_relays_json); callback(resp); relay_dbo::free_list(all_controller_relays); } void controllers::get_relays_one_by_id_and_num(const HttpRequestPtr &req, std::function &&callback, const std::string& controller_id, int relay_num) { relay_dbo *relay = relay_dbo::get_relay_for_controller(controller_id.c_str(), relay_num); if(relay) { auto resp = HttpResponse::newHttpJsonResponse(relay->to_json()); callback(resp); delete relay; } else { auto resp = HttpResponse::newHttpResponse(); resp->setStatusCode(k404NotFound); callback(resp); } } void controllers::put_relays_one_by_id_and_num(const HttpRequestPtr &req, std::function &&callback, const std::string& controller_id, int relay_num) { if(!relay_dbo::valid_num_for_controller(controller_id.c_str(), relay_num)) { auto resp = HttpResponse::newHttpResponse(); resp->setStatusCode(k400BadRequest); callback(resp); return; } relay_dbo *relay = relay_dbo::get_relay_for_controller(controller_id.c_str(), relay_num); Json::Value body = *req->getJsonObject(); bool db_action_result; if(relay) { strncpy(relay->name, body["name"].asCString(), 127); strncpy(relay->active_schedule_id, body["active_schedule"].asCString(), 32); db_action_result = relay->update(); } else { relay = new relay_dbo(); relay->number = relay_num; strncpy(relay->name, body["name"].asCString(), 127); strncpy(relay->active_schedule_id, body["active_schedule"].asCString(), 32); strncpy(relay->controller_id, controller_id.c_str(), 32); db_action_result = relay->insert(); } if(!db_action_result) { auto resp = HttpResponse::newHttpResponse(); resp->setStatusCode(k500InternalServerError); callback(resp); } else { auto schedules = schedule_dbo::get_by_simple("id", body["active_schedule"].asCString(), (intptr_t)&sqlite3_bind_text); auto controllers = controller_dbo::get_by_simple("id", controller_id.c_str(), (intptr_t)&sqlite3_bind_text); Json::Value payload; payload["target"] = relay_num; payload["schedule"] = schedules[0]->to_json(); Json::StreamWriterBuilder json_writer; controllers[0]->command(config::command_code_set_schedule, Json::writeString(json_writer, payload).c_str()); auto resp = HttpResponse::newHttpJsonResponse(relay->to_json()); callback(resp); schedule_dbo::free_list(schedules); controller_dbo::free_list(controllers); } delete relay; }