116 lines
2.4 KiB
C++
116 lines
2.4 KiB
C++
#include <json.hpp>
|
|
#include <zephyr/logging/log.h>
|
|
|
|
LOG_MODULE_REGISTER(json);
|
|
|
|
static constexpr size_t BUF_SIZE = 512;
|
|
char _buf[BUF_SIZE];
|
|
size_t _idx;
|
|
size_t _indent;
|
|
|
|
JsonParser::HandlerBase* _handlers;
|
|
|
|
JsonParser::HandlerBase::HandlerBase()
|
|
{
|
|
_next = _handlers;
|
|
_handlers = this;
|
|
}
|
|
|
|
//FIXME weird prtink to LOG_* update?
|
|
// int JsonParser::json_printer(const char* bytes, size_t len, void* data)
|
|
// {
|
|
// // LOG_INF("[[%d]]", len);
|
|
// // for (size_t i = 0; i < len; i++)
|
|
// // {
|
|
// // LOG_INF("%c", bytes[i]);
|
|
// // }
|
|
// // return 0;
|
|
//
|
|
// for (size_t i = 0; i < len; i++)
|
|
// {
|
|
// bool nl = true;
|
|
// if (bytes[i] == '}' || bytes[i] == ']')
|
|
// {
|
|
// nl = false;
|
|
// _indent--;
|
|
// LOG_INF("");
|
|
// for (size_t i = 0; i < _indent; i++)
|
|
// {
|
|
// LOG_ERR(" ");
|
|
// }
|
|
// }
|
|
// LOG_INF("%c", bytes[i]);
|
|
// if (bytes[i] == '{' || bytes[i] == '[')
|
|
// {
|
|
// _indent++;
|
|
// }
|
|
// if (nl
|
|
// && (bytes[i] == ',' || bytes[i] == '{' || bytes[i] == '}'
|
|
// || bytes[i] == '[' || bytes[i] == ']'))
|
|
// {
|
|
// LOG_INF("");
|
|
// for (size_t i = 0; i < _indent; i++)
|
|
// {
|
|
// LOG_INF(" ");
|
|
// }
|
|
// }
|
|
// }
|
|
// return 0;
|
|
// }
|
|
|
|
void commit()
|
|
{
|
|
_buf[_idx] = '\0';
|
|
bool ok = false;
|
|
JsonParser::HandlerBase* h = _handlers;
|
|
while (h)
|
|
{
|
|
if (h->handle(_buf, _idx))
|
|
{
|
|
ok = true;
|
|
break;
|
|
}
|
|
h = h->_next;
|
|
};
|
|
_idx = 0;
|
|
if (!ok)
|
|
{
|
|
LOG_INF("parse end error");
|
|
}
|
|
}
|
|
|
|
void flush_LOG_ERRR()
|
|
{
|
|
_idx = 0;
|
|
LOG_ERR("input buffer overflow, flushing");
|
|
}
|
|
|
|
void JsonParser::init()
|
|
{
|
|
/* nothing to do */
|
|
}
|
|
|
|
void JsonParser::add_text(const uint8_t* buf, size_t size)
|
|
{
|
|
for (size_t i = 0; i < size; i++)
|
|
{
|
|
if (buf[i] == ' ' || buf[i] == '\r' || buf[i] == '\n')
|
|
{
|
|
continue;
|
|
}
|
|
if (buf[i] == '}')
|
|
{
|
|
_buf[_idx] = buf[i];
|
|
_idx++;
|
|
commit();
|
|
continue;
|
|
}
|
|
_buf[_idx] = buf[i];
|
|
_idx++;
|
|
if (_idx >= BUF_SIZE)
|
|
{
|
|
flush_LOG_ERRR();
|
|
}
|
|
}
|
|
}
|