From 9415402a1ea98f614b2d8dc61fb61b32d80ec2fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Bourdeauducq?= Date: Sun, 19 Jan 2025 18:56:04 +0800 Subject: [PATCH] replace messy nlohmann json lib --- Makefile | 2 +- kirdy.cpp | 30 ++++++++++++++++++++++-------- kirdy.hpp | 4 ++-- 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/Makefile b/Makefile index 66c4372..f0dce60 100644 --- a/Makefile +++ b/Makefile @@ -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 CXXOPTS= -Wall `pkg-config --cflags glfw3 gl` LDFLAGS= `pkg-config --libs glfw3 gl` -LDADD= -lsndio -lm +LDADD= -lsndio -lm -ljsoncpp BINDIR= /usr/local/bin NOMAN= noman diff --git a/kirdy.cpp b/kirdy.cpp index fa92140..0fadd39 100644 --- a/kirdy.cpp +++ b/kirdy.cpp @@ -1,5 +1,7 @@ +#include + #include -#include +#include #include "kirdy.hpp" @@ -16,18 +18,30 @@ Kirdy::~Kirdy() delete socket; } -nlohmann::json Kirdy::command(nlohmann::json &request) +Json::Value Kirdy::command(Json::Value &request) { - std::string reply; - asio::write(*socket, asio::buffer(request.dump() + "\n")); - asio::read_until(*socket, asio::dynamic_buffer(reply, 1024), '\n'); - return nlohmann::json::parse(reply); + Json::StreamWriterBuilder builder_w; + std::string request_str = Json::writeString(builder_w, request); + asio::write(*socket, asio::buffer(request_str + "\n")); + + 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 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() { - nlohmann::json json; + Json::Value json; json["device_cmd"] = "GetStatusReport"; auto reply = command(json); - return reply["thermostat"]["temperature"]; + return reply["thermostat"]["temperature"].asFloat(); } + diff --git a/kirdy.hpp b/kirdy.hpp index 48b1886..2a821c5 100644 --- a/kirdy.hpp +++ b/kirdy.hpp @@ -1,13 +1,13 @@ #pragma once #include -#include +#include class Kirdy { private: asio::io_context io_context; asio::ip::tcp::socket *socket; - nlohmann::json command(nlohmann::json &request); + Json::Value command(Json::Value &request); public: Kirdy(asio::string_view host, asio::string_view service); ~Kirdy();