copy from an old project
This commit is contained in:
75
include/json.hpp
Normal file
75
include/json.hpp
Normal file
@@ -0,0 +1,75 @@
|
||||
#ifndef JSON_HPP
|
||||
#define JSON_HPP
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include <zephyr/data/json.h>
|
||||
|
||||
#include <log.hpp>
|
||||
|
||||
namespace JsonParser
|
||||
{
|
||||
void init();
|
||||
void add_text(uint8_t* buf, size_t size);
|
||||
int json_printer(const char* bytes, size_t len, void* data);
|
||||
|
||||
class HandlerBase
|
||||
{
|
||||
public:
|
||||
/* private but accessible from static functions */
|
||||
HandlerBase* _next;
|
||||
|
||||
HandlerBase();
|
||||
virtual bool handle(const char* buf, size_t size) = 0;
|
||||
};
|
||||
|
||||
template <typename Struct, size_t DESC_SIZE, typename Fct>
|
||||
class Handler: public HandlerBase
|
||||
{
|
||||
const Struct& _s;
|
||||
const json_obj_descr* _da;
|
||||
Fct _fct;
|
||||
bool _allow_partial;
|
||||
|
||||
const int64_t _all_fields;
|
||||
|
||||
public:
|
||||
Handler(Struct default_s, const json_obj_descr (&da)[DESC_SIZE], Fct fct, bool allow_partial=false):
|
||||
_s {default_s},
|
||||
_da {da},
|
||||
_fct {fct},
|
||||
_allow_partial{allow_partial},
|
||||
_all_fields {(1 << DESC_SIZE) - 1}
|
||||
{
|
||||
}
|
||||
|
||||
void print( const Struct& s) { json_obj_encode(_da, DESC_SIZE, &s, json_printer, NULL); }
|
||||
|
||||
bool handle(const char* buf, size_t size) override
|
||||
{
|
||||
Struct s{_s};
|
||||
int64_t ret = json_obj_parse((char*)buf, size, _da, DESC_SIZE, &s);
|
||||
if (ret <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if(ret != _all_fields && !_allow_partial)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (!_fct(s, ret, _all_fields))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// info("received a valid json\n");
|
||||
// print(s);
|
||||
// info("\n");
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace JsonParser
|
||||
|
||||
#endif /* JSON_HPP */
|
||||
Reference in New Issue
Block a user