bonus-edge-proxy/src/light_control/light_controller.cc

80 lines
2.3 KiB
C++
Raw Normal View History

2026-01-21 11:04:34 +08:00
#include "light_controller.hpp"
#include <iostream>
// 构造函数
LightController::LightController(std::string baseUrl, std::string token)
: baseUrl(baseUrl), token(token) {
// 可以在这里做全局初始化,或者在 main 中做
}
LightController::~LightController() {
// 如果有需要释放的资源放在这里
}
// 静态回调函数实现
size_t LightController::WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
// 核心控制逻辑
bool LightController::ControlLight(std::string deviceId, std::string switchType) {
CURL* curl;
CURLcode res;
std::string readBuffer;
long httpCode = 0;
bool success = false;
curl = curl_easy_init();
if (curl) {
// 拼接完整 URL
std::string url = this->baseUrl + "/hk_service/modbus/lightControl";
// 设置 URL
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1L);
// 构造 Headers
struct curl_slist* headers = NULL;
std::string tokenHeader = "token: " + this->token;
headers = curl_slist_append(headers, tokenHeader.c_str());
headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
// 构造 Body: deviceId=351&type=0
std::string postData = "deviceId=" + deviceId + "&type=" + switchType;
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData.c_str());
// 设置超时 (5秒)
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5L);
// 设置响应接收
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
// 执行请求
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cerr << "[LightControl] 请求失败: " << curl_easy_strerror(res) << std::endl;
} else {
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
// 简单打印结果
std::cout << "[LightControl] ID:" << deviceId
<< " 动作:" << (switchType == "1" ? "开启" : "关闭")
<< " -> 返回状态码: " << httpCode << std::endl;
// std::cout << "响应内容: " << readBuffer << std::endl; // 调试时可打开
if (httpCode == 200) {
success = true;
}
}
// 清理
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
}
return success;
}