#include #include #include #include #include #include void api_v1_controllers_STR_relays_GET(struct mg_connection *c, endpoint_args_t *args, struct http_message *hm) { (void)hm; uuid_t target_uid; if(uuid_parse(args[0].value.v_str, target_uid)) { LOG_ERROR("failed to unparse uid\n"); mg_send_head(c, 400, 2, "Content-Type: application/json\r\n" STANDARD_HEADERS); mg_printf(c, "{}"); return; } controller_t* controller = controller_get_by_uid(target_uid); if(!controller) { LOG_ERROR("could not find a controller for uid '%s'\n", args[0].value.v_str); mg_send_head(c, 404, 2, "Content-Type: application/json\r\n" STANDARD_HEADERS); mg_printf(c, "{}"); return; } relay_t** all_relays = relay_get_by_controller_id(controller->id); cJSON *json = cJSON_CreateArray(); for(int i = 0; all_relays[i] != NULL; ++i) { cJSON *json_relay = relay_to_json(all_relays[i]); cJSON_AddItemToArray(json, json_relay); } char *json_str = cJSON_Print(json); if (json_str == NULL) { LOG_ERROR("failed to print relays json\n"); mg_send_head(c, 500, 2, "Content-Type: application/json\r\n" STANDARD_HEADERS); mg_printf(c, "[]"); } else { mg_send_head(c, 200, strlen(json_str), "Content-Type: application/json\r\n" STANDARD_HEADERS); mg_printf(c, "%s", json_str); free(json_str); } cJSON_Delete(json); relay_free_list(all_relays); controller_free(controller); }