replace messy nlohmann json lib

This commit is contained in:
Sébastien Bourdeauducq 2025-01-19 18:56:04 +08:00
parent 71c7ac8bb9
commit 9415402a1e
3 changed files with 25 additions and 11 deletions

View File

@ -2,7 +2,7 @@ PROG= sndlock
SRCS= imgui_impl_glfw.cpp imgui_impl_opengl3.cpp imgui_draw.cpp imgui_widgets.cpp imgui_tables.cpp imgui.cpp kirdy.cpp sndlock.cpp SRCS= imgui_impl_glfw.cpp imgui_impl_opengl3.cpp imgui_draw.cpp imgui_widgets.cpp imgui_tables.cpp imgui.cpp kirdy.cpp sndlock.cpp
CXXOPTS= -Wall `pkg-config --cflags glfw3 gl` CXXOPTS= -Wall `pkg-config --cflags glfw3 gl`
LDFLAGS= `pkg-config --libs glfw3 gl` LDFLAGS= `pkg-config --libs glfw3 gl`
LDADD= -lsndio -lm LDADD= -lsndio -lm -ljsoncpp
BINDIR= /usr/local/bin BINDIR= /usr/local/bin
NOMAN= noman NOMAN= noman

View File

@ -1,5 +1,7 @@
#include <iostream>
#include <asio.hpp> #include <asio.hpp>
#include <nlohmann/json.hpp> #include <json/json.h>
#include "kirdy.hpp" #include "kirdy.hpp"
@ -16,18 +18,30 @@ Kirdy::~Kirdy()
delete socket; delete socket;
} }
nlohmann::json Kirdy::command(nlohmann::json &request) Json::Value Kirdy::command(Json::Value &request)
{ {
std::string reply; Json::StreamWriterBuilder builder_w;
asio::write(*socket, asio::buffer(request.dump() + "\n")); std::string request_str = Json::writeString(builder_w, request);
asio::read_until(*socket, asio::dynamic_buffer(reply, 1024), '\n'); asio::write(*socket, asio::buffer(request_str + "\n"));
return nlohmann::json::parse(reply);
std::cout << request_str << std::endl;
std::string reply_str;
std::size_t len = asio::read_until(*socket, asio::dynamic_buffer(reply_str, 1024), '\n');
Json::CharReaderBuilder builder_r;
const std::unique_ptr<Json::CharReader> reader(builder_r.newCharReader());
Json::Value reply;
JSONCPP_STRING err;
if(!reader->parse(reply_str.c_str(), reply_str.c_str() + len, &reply, &err))
std::cerr << "JSON parse error: " << err << std::endl;
return reply;
} }
float Kirdy::get_laser_temp() float Kirdy::get_laser_temp()
{ {
nlohmann::json json; Json::Value json;
json["device_cmd"] = "GetStatusReport"; json["device_cmd"] = "GetStatusReport";
auto reply = command(json); auto reply = command(json);
return reply["thermostat"]["temperature"]; return reply["thermostat"]["temperature"].asFloat();
} }

View File

@ -1,13 +1,13 @@
#pragma once #pragma once
#include <asio.hpp> #include <asio.hpp>
#include <nlohmann/json.hpp> #include <json/json.h>
class Kirdy { class Kirdy {
private: private:
asio::io_context io_context; asio::io_context io_context;
asio::ip::tcp::socket *socket; asio::ip::tcp::socket *socket;
nlohmann::json command(nlohmann::json &request); Json::Value command(Json::Value &request);
public: public:
Kirdy(asio::string_view host, asio::string_view service); Kirdy(asio::string_view host, asio::string_view service);
~Kirdy(); ~Kirdy();