115 lines
1.9 KiB
C
115 lines
1.9 KiB
C
#include <fcntl.h>
|
|
#include <unistd.h>
|
|
#include <errno.h>
|
|
#include <sys/types.h>
|
|
#include <sys/stat.h>
|
|
|
|
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
|
|
#include "jsonlogger.h"
|
|
|
|
#define LOG_OR_RETURN(...) \
|
|
if(dprintf(m_fifo_fd, __VA_ARGS__) < 0) { \
|
|
return false; \
|
|
}
|
|
|
|
static int m_fifo_fd = -1;
|
|
|
|
static bool start_message(void)
|
|
{
|
|
ssize_t ret = write(m_fifo_fd, "{", 1);
|
|
if(ret < 0) {
|
|
// FIFO is not writable or other error
|
|
if(errno != EAGAIN) {
|
|
perror("write");
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
static bool end_message(void)
|
|
{
|
|
ssize_t ret = write(m_fifo_fd, "}\n", 2);
|
|
if(ret < 0) {
|
|
// FIFO is not writable or other error
|
|
if(errno != EAGAIN) {
|
|
perror("write");
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
|
|
bool jsonlogger_init(const char *fifoname)
|
|
{
|
|
// try to create the named FIFO
|
|
int ret = mkfifo(fifoname, 0666);
|
|
if(ret < 0) {
|
|
if(errno != EEXIST) {
|
|
perror("mkfifo");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// FIFO was created or did already exist -> open it
|
|
m_fifo_fd = open(fifoname, O_WRONLY | O_NONBLOCK);
|
|
if(m_fifo_fd < 0) {
|
|
perror("open");
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
|
|
void jsonlogger_shutdown(void)
|
|
{
|
|
close(m_fifo_fd);
|
|
}
|
|
|
|
|
|
bool jsonlogger_log_simple_integer(const char *msg_type, int64_t value)
|
|
{
|
|
if(!start_message()) {
|
|
return false;
|
|
}
|
|
|
|
LOG_OR_RETURN("\"%s\": %ld", msg_type, value);
|
|
|
|
return end_message();
|
|
}
|
|
|
|
|
|
bool jsonlogger_log_simple_double(const char *msg_type, double value)
|
|
{
|
|
if(!start_message()) {
|
|
return false;
|
|
}
|
|
|
|
LOG_OR_RETURN("\"%s\": %g", msg_type, value);
|
|
|
|
return end_message();
|
|
}
|
|
|
|
|
|
bool jsonlogger_log_rx_stats(const rx_stats_t *rx_stats)
|
|
{
|
|
if(!start_message()) {
|
|
return false;
|
|
}
|
|
|
|
LOG_OR_RETURN("\"preambles_found\": %zd, ", rx_stats->preambles_found);
|
|
LOG_OR_RETURN("\"successful_decodes\": %zd, ", rx_stats->successful_decodes);
|
|
LOG_OR_RETURN("\"failed_decodes\": %zd, ", rx_stats->failed_decodes);
|
|
LOG_OR_RETURN("\"header_errors\": %zd, ", rx_stats->header_errors);
|
|
|
|
return end_message();
|
|
}
|