core-legacy/controllers/api_v1_devices_relays.cc

101 lines
2.8 KiB
C++
Raw Normal View History

#include <netdb.h>
#include <models/relay_dbo.h>
2019-07-20 22:29:05 +00:00
#include <helpers.h>
2019-07-21 22:00:07 +00:00
#include <models/device_dbo.h>
#include "api_v1_devices.h"
using namespace api::v1;
void
devices::get_relays_all(const HttpRequestPtr &req, std::function<void(const HttpResponsePtr &)> &&callback,
const std::string& device_id)
{
2019-07-20 22:29:05 +00:00
relay_dbo **all_device_relays = relay_dbo::get_by_simple("device_id", (void *) device_id.c_str(), (intptr_t) sqlite3_bind_text);
Json::Value all_relays_json(Json::arrayValue);
for(int i = 0; all_device_relays[i] != nullptr; i++)
{
all_relays_json.append(all_device_relays[i]->to_json());
}
auto resp = HttpResponse::newHttpJsonResponse(all_relays_json);
callback(resp);
relay_dbo::free_list(all_device_relays);
}
void
devices::get_relays_one_by_id_and_num(const HttpRequestPtr &req,
std::function<void(const HttpResponsePtr &)> &&callback, const std::string& device_id,
int relay_num)
{
2019-07-21 22:00:07 +00:00
relay_dbo *relay = relay_dbo::get_relay_for_device(device_id.c_str(), relay_num);
if(relay)
{
2019-07-21 22:00:07 +00:00
auto resp = HttpResponse::newHttpJsonResponse(relay->to_json());
callback(resp);
2019-07-21 22:00:07 +00:00
delete relay;
}
else
{
auto resp = HttpResponse::newHttpResponse();
resp->setStatusCode(k404NotFound);
callback(resp);
}
}
void
devices::put_relays_one_by_id_and_num(const HttpRequestPtr &req,
std::function<void(const HttpResponsePtr &)> &&callback, const std::string& device_id,
int relay_num)
{
2019-07-21 22:00:07 +00:00
if(!relay_dbo::valid_num_for_device(device_id.c_str(), relay_num))
{
auto resp = HttpResponse::newHttpResponse();
resp->setStatusCode(k400BadRequest);
callback(resp);
return;
}
relay_dbo *relay = relay_dbo::get_relay_for_device(device_id.c_str(), relay_num);
Json::Value body = *req->getJsonObject();
bool db_action_result;
if(relay)
{
strncpy(relay->name, body["name"].asCString(), 128);
strncpy(relay->active_schedule_id, body["active_schedule"].asCString(), 33);
db_action_result = relay->update();
}
else
{
relay = new relay_dbo();
relay->number = relay_num;
strncpy(relay->name, body["name"].asCString(), 128);
strncpy(relay->active_schedule_id, body["active_schedule"].asCString(), 33);
strncpy(relay->device_id, device_id.c_str(), 33);
db_action_result = relay->insert();
}
if(!db_action_result)
{
auto resp = HttpResponse::newHttpResponse();
resp->setStatusCode(k500InternalServerError);
callback(resp);
}
else
{
auto resp = HttpResponse::newHttpJsonResponse(relay->to_json());
callback(resp);
}
2019-07-21 22:00:07 +00:00
delete relay;
}