embox
136 строк · 2.7 Кб
1/**
2* @file
3*
4* @date Aug 3, 2021
5* @author Anton Bondarev
6*/
7
8#include <assert.h>9#include <sys/stat.h>10#include <fcntl.h>11#include <unistd.h>12#include <stdio.h>13#include <string.h>14#include <stdlib.h>15
16#include <lib/loop_file_logger.h>17
18#include <framework/mod/options.h>19
20#define LOGGER_FILE_NAME OPTION_STRING_GET(file_name)21#define RECORD_SIZE OPTION_GET(NUMBER,record_size)22#define RECORD_QUANTITY OPTION_GET(NUMBER,record_quantity)23
24static_assert(RECORD_QUANTITY <= 256, "");25
26static char loop_logger_buf[RECORD_SIZE];27
28static int find_current_record(int fd, int *label) {29int res;30int i;31char cur_label;32
33res = read(fd, loop_logger_buf, RECORD_SIZE);34if (res != RECORD_SIZE) {35*label = 0;36return 0;37}38
39cur_label = loop_logger_buf[0];40
41for(i = 1; i < RECORD_QUANTITY; i++) {42res = read(fd, loop_logger_buf, RECORD_SIZE);43if (res != RECORD_SIZE) {44break;45}46if (loop_logger_buf[0] != cur_label) {47*label = (loop_logger_buf[0] == '0') ? 1 : 0;48return i;49}50}51
52*label = (cur_label == '0') ? 1 : 0;53return 0;54}
55
56int loop_logger_write(char *message) {57int fd;58int start_idx = -1;59int flip;60char tmp_buf[4];61int len;62
63if (loop_logger_size() < RECORD_QUANTITY) {64start_idx = 0;65}66fd = open(LOGGER_FILE_NAME, O_RDWR);67if (fd < 0) {68return -1;69}70if (start_idx == -1) {71start_idx = find_current_record(fd, &flip);72} else {73start_idx = loop_logger_size();74flip = 0;75}76lseek(fd, start_idx * RECORD_SIZE, SEEK_SET);77memset(loop_logger_buf, 0, RECORD_SIZE);78//snprintf(loop_logger_buf, "%d%02X:%s\n",flip, start_idx,message);79itoa(flip, loop_logger_buf, 10);80itoa(start_idx, tmp_buf, 16);81if (strlen(tmp_buf) == 1) {82strcat(loop_logger_buf,"0");83}84strcat(loop_logger_buf, tmp_buf);85strcat(loop_logger_buf,":");86strncat(loop_logger_buf, message, RECORD_SIZE - 1);87
88len = strlen(loop_logger_buf);89if (len < (RECORD_SIZE - 1)) {90memset(&loop_logger_buf[len], ' ', (RECORD_SIZE - 1) - len);91}92loop_logger_buf[RECORD_SIZE - 1] = '\n';93write(fd, loop_logger_buf, RECORD_SIZE);94
95return 0;96}
97
98int loop_logger_read(int idx_mes, char *out_mes, int buf_size) {99int fd;100int start_idx = -1;101
102if (loop_logger_size() < RECORD_QUANTITY) {103start_idx = 0;104}105fd = open(LOGGER_FILE_NAME, O_RDONLY);106if (fd < 0) {107return -1;108}109if (start_idx == -1) {110int tmp;111start_idx = find_current_record(fd, &tmp);112}113start_idx += idx_mes;114start_idx %= RECORD_QUANTITY;115lseek(fd, start_idx * RECORD_SIZE + 4, SEEK_SET);116
117read(fd, out_mes, buf_size);118close(fd);119
120return 0;121}
122
123int loop_logger_size(void) {124struct stat st;125
126stat(LOGGER_FILE_NAME, &st);127if (st.st_size < RECORD_SIZE * RECORD_QUANTITY) {128return st.st_size / RECORD_SIZE;129}130
131return RECORD_QUANTITY;132}
133
134int loop_logger_message_size(void) {135return RECORD_SIZE - (4 + 1);136}
137
138