Добавить регистратор телеметрии C99 с адаптером GAS

This commit is contained in:
2026-11-23 17:19:33 +03:00
parent 19da996fe5
commit 5ac902824c
7 changed files with 505 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
cmake_minimum_required(VERSION 3.16)
project(telemetry_logger C)
add_library(telemetry_logger STATIC telemetry_logger.c telemetry_gas.c)
target_include_directories(telemetry_logger PUBLIC . ../gas-logger/include)
target_compile_features(telemetry_logger PUBLIC c_std_99)
include(CTest)
if(BUILD_TESTING)
add_executable(telemetry_logger_test tests/test_telemetry_logger.c)
target_link_libraries(telemetry_logger_test PRIVATE telemetry_logger)
add_test(NAME telemetry_logger COMMAND telemetry_logger_test)
endif()
+53
View File
@@ -0,0 +1,53 @@
# Telemetry Logger
Переносимый регистратор C99 хранит историю сигналов, текущий отсчёт и закреплённый снимок события. Буферы выделяет проект. Монотонные метки хранятся в микросекундах, значения — как знаковые `int32_t` с масштабом проекта и маской достоверности.
```text
датчик/ISR → согласованный снимок проекта → telemetry_logger
→ telemetry_gas → GAS/RTU → SetGUI
```
| Файл | Назначение |
|---|---|
| `telemetry_logger.h/.c` | До 40 каналов, кольцевой буфер, курсор чтения и архив события |
| `telemetry_gas.h/.c` | Проекция на регистры GAS Logger v1, команды и коды недоступных значений |
| `tests/test_telemetry_logger.c` | Переполнение, предыстория, постинтервал, поколение и границы окна |
У ядра нет HAL, ОС, динамической памяти или глобального изменяемого состояния.
Один экземпляр подходит для пуска или фоновых измерений, несколько экземпляров
позволяют задать разную частоту для медленного и быстрого журналов. Передавайте
в `slog_push` уже готовые значения, маску и монотонное время. Применение
в ISR требует измерить время копирования и исключить одновременный вызов.
Для RTU и CAN выполняйте чтение и запись в одном контексте с регистрацией
отсчётов либо синхронизируйте доступ в порте. Ядро само IRQ не переключает.
```c
static slog_sample_t before[32], after[32];
static slog_t logger;
static slog_gas_t gas;
int32_t values[] = {1500, -25};
if (slog_init(&logger, 2, before, after, 32, 8) &&
slog_gas_init(&gas, &logger, service_base, signal_base, schema_crc, 1)) {
slog_push(&logger, elapsed_us, 3, 0, values, false);
}
```
При триггере текущая запись сохраняется вместе со следующими `post_rows`
отсчётами. Затем банки переключаются. Новый сбор продолжается, пока SetGUI
читает архив. Освобождение сверяет поколение. Перегруженный клиент может
обнаруживать пропуски по 64-битному номеру записи. Для GAS Logger v1 время
проецируется в `u32` мс, значения — в `u16/i16`. Недоступные данные кодируются
как `65535/-32768`, а SetGUI хранит их как пустую ячейку CSV.
Первый потребитель — ECU Ignition. Карта находится в
[`ecu.json`](../../python/set_devices/gas_logger_maps/ecu.json).
При создании карты для нового проекта назначьте свои адреса в GAS,
единицы и масштаб, а CRC JSON включите в прошивку. Порт SetGUI проверяет
CRC перед командами. Для Бальзама 2812 можно использовать то же ядро
при подключении собственных источников и согласовании новой GAS-карты.
```text
cmake -S c/telemetry-logger -B build/telemetry-logger
cmake --build build/telemetry-logger
ctest --test-dir build/telemetry-logger --output-on-failure
```
+129
View File
@@ -0,0 +1,129 @@
#include "telemetry_gas.h"
bool slog_gas_init(slog_gas_t *gas, slog_t *log, uint16_t base, uint16_t channel_base,
uint32_t schema_id, uint64_t unsigned_channels)
{
if (!gas || !log || !log->capacity || !log->archive.rows ||
(unsigned_channels >> log->channels)) {
return false;
}
uint32_t width = GL_HEADER_WORDS + log->channels;
uint32_t data_base = (uint32_t)base + GL_DATA_OFFSET;
uint32_t channel_end = (uint32_t)channel_base + log->channels;
if (data_base > 65536UL || log->capacity > (65536UL - data_base) / width ||
channel_end > 65536UL || (channel_end > base &&
channel_base < data_base + (uint32_t)log->capacity * width)) {
return false;
}
*gas = (slog_gas_t){.log = log, .schema_id = schema_id, .base = base,
.channel_base = channel_base, .unsigned_channels = unsigned_channels};
return true;
}
static uint16_t channel_word(const slog_gas_t *gas, const slog_sample_t *row, unsigned channel)
{
bool is_unsigned = ((gas->unsigned_channels >> channel) & 1U) != 0;
if (!((row->valid >> channel) & 1U)) {
return is_unsigned ? UINT16_MAX : UINT16_C(32768);
}
int32_t value = row->values[channel];
int32_t low = is_unsigned ? 0 : -32767;
int32_t high = is_unsigned ? 65534 : 32767;
if (value < low || value > high) {
return is_unsigned ? UINT16_MAX : UINT16_C(32768);
}
return (uint16_t)value;
}
static uint16_t archive_word(const slog_gas_t *gas, const slog_sample_t *row, unsigned column)
{
uint32_t time_ms = (uint32_t)(row->time_us / 1000U);
switch (column) {
case 0: return (uint16_t)time_ms;
case 1: return (uint16_t)(time_ms >> 16);
case 2: return (uint16_t)row->sequence;
case 3: return (uint16_t)(row->sequence >> 16);
case 4: return row->event;
default: return channel_word(gas, row, column - GL_HEADER_WORDS);
}
}
gl_result slog_gas_read(const slog_gas_t *gas, uint16_t address, uint16_t *out, uint16_t count)
{
if (!gas || !gas->log || !out || !count || count > 125U) {
return GL_ARGUMENT;
}
const slog_t *log = gas->log;
uint32_t end = (uint32_t)address + count;
uint32_t data_base = (uint32_t)gas->base + GL_DATA_OFFSET;
uint16_t width = GL_HEADER_WORDS + log->channels;
if (address >= gas->base && end <= (uint32_t)gas->base + 18U) {
uint16_t status[18] = {
GL_MAGIC, GL_VERSION, (gas->recording ? 1 : 0) | (log->archive.count ? 2 : 0),
log->channels, width, (uint16_t)log->capacity, (uint16_t)log->active.count,
(uint16_t)log->archive.count, (uint16_t)log->generation,
(uint16_t)(log->generation >> 16), (uint16_t)gas->schema_id,
(uint16_t)(gas->schema_id >> 16), (uint16_t)log->next_sequence,
(uint16_t)(log->next_sequence >> 16), (uint16_t)log->missed_triggers,
(uint16_t)(log->missed_triggers >> 16), 0, 0
};
for (uint16_t i = 0; i < count; ++i) {
out[i] = status[address - gas->base + i];
}
return GL_OK;
}
slog_sample_t row = {0};
if (address >= data_base && end <= data_base + (uint32_t)log->archive.count * width) {
uint32_t offset = address - data_base;
size_t index = offset / width;
uint16_t column = (uint16_t)(offset % width);
slog_archive_read(log, log->generation, index, &row);
for (uint16_t i = 0; i < count; ++i) {
if (column == width) {
slog_archive_read(log, log->generation, ++index, &row);
column = 0;
}
out[i] = archive_word(gas, &row, column++);
}
return GL_OK;
}
if (address >= gas->channel_base && end <= (uint32_t)gas->channel_base + log->channels) {
slog_latest(log, &row);
for (uint16_t i = 0; i < count; ++i) {
out[i] = channel_word(gas, &row, address - gas->channel_base + i);
}
return GL_OK;
}
return GL_ADDRESS;
}
gl_result slog_gas_write(slog_gas_t *gas, uint16_t address, uint16_t value)
{
if (!gas || !gas->log) {
return GL_ARGUMENT;
}
uint32_t base = gas->base;
if (address == base + GL_RELEASE_LO) {
gas->release_generation = (gas->release_generation & UINT32_C(0xffff0000)) | value;
} else if (address == base + GL_RELEASE_HI) {
gas->release_generation = (gas->release_generation & UINT32_C(0xffff)) |
((uint32_t)value << 16);
} else if (address != base + GL_COMMAND) {
return GL_ADDRESS;
} else if (value == GL_START) {
gas->recording = true;
} else if (value == GL_SNAPSHOT) {
if (!slog_snapshot(gas->log)) {
return gas->log->archive.count || gas->log->remaining ? GL_BUSY : GL_EMPTY;
}
} else if (value == GL_RELEASE) {
if (!slog_archive_release(gas->log, gas->release_generation)) {
return GL_STALE;
}
gas->release_generation = 0;
} else {
return GL_ARGUMENT;
}
return GL_OK;
}
+24
View File
@@ -0,0 +1,24 @@
#ifndef TELEMETRY_GAS_H
#define TELEMETRY_GAS_H
#include "telemetry_logger.h"
#include "gas_logger.h"
typedef struct {
slog_t *log;
uint32_t schema_id;
uint32_t release_generation;
uint64_t unsigned_channels;
uint16_t base;
uint16_t channel_base;
bool recording;
} slog_gas_t;
/* GAS logger v1 register projection. Words at channel_base are consecutive.
* Use a caller-owned lock if reading and capturing from different contexts. */
bool slog_gas_init(slog_gas_t *gas, slog_t *log, uint16_t base, uint16_t channel_base,
uint32_t schema_id, uint64_t unsigned_channels);
gl_result slog_gas_read(const slog_gas_t *gas, uint16_t address, uint16_t *out, uint16_t count);
gl_result slog_gas_write(slog_gas_t *gas, uint16_t address, uint16_t value);
#endif
+160
View File
@@ -0,0 +1,160 @@
#include "telemetry_logger.h"
static size_t bank_index(const slog_t *log, const slog_bank_t *bank, size_t index)
{
size_t tail = log->capacity - bank->oldest;
return index < tail ? bank->oldest + index : index - tail;
}
static void pin_active(slog_t *log, size_t trigger_index)
{
slog_sample_t *spare = log->archive.rows;
log->archive = log->active;
log->active = (slog_bank_t){.rows = spare};
log->trigger_index = trigger_index;
if (++log->generation == 0) {
++log->generation;
}
}
bool slog_init(slog_t *log, uint16_t channels, slog_sample_t *active,
slog_sample_t *archive, size_t capacity, size_t post_rows)
{
if (!log || !active || active == archive || !capacity ||
capacity > SIZE_MAX / sizeof(*active) ||
!channels || channels > SLOG_MAX_CHANNELS || post_rows >= capacity ||
(!archive && post_rows)) {
return false;
}
*log = (slog_t){0};
log->channels = channels;
log->active.rows = active;
log->archive.rows = archive;
log->capacity = capacity;
log->post_rows = post_rows;
return true;
}
bool slog_push(slog_t *log, uint64_t time_us, uint64_t valid,
uint16_t event, const int32_t *values, bool trigger)
{
if (!log || !log->capacity || !values || (valid >> log->channels) ||
(log->has_sample && time_us < log->last_us)) {
return false;
}
slog_bank_t *bank = &log->active;
size_t slot;
if (bank->count == log->capacity) {
slot = bank->oldest;
bank->oldest = bank_index(log, bank, 1U);
} else {
slot = bank_index(log, bank, bank->count);
++bank->count;
}
slog_sample_t *sample = &bank->rows[slot];
sample->time_us = time_us;
sample->sequence = log->next_sequence++;
sample->valid = valid;
sample->event = event;
uint64_t bits = valid;
for (size_t i = 0; i < log->channels; ++i) {
sample->values[i] = (bits & 1U) ? values[i] : 0;
bits >>= 1;
}
log->last_us = time_us;
log->has_sample = true;
bool accept = trigger && log->archive.rows && !log->remaining && !log->archive.count;
if (trigger && !accept && log->missed_triggers != UINT32_MAX) {
++log->missed_triggers;
}
if (accept) {
log->remaining = log->post_rows;
} else if (log->remaining) {
--log->remaining;
} else {
return true;
}
if (!log->remaining) {
pin_active(log, log->active.count - 1U - log->post_rows);
}
return true;
}
bool slog_snapshot(slog_t *log)
{
if (!log || !log->archive.rows || log->remaining || log->archive.count ||
!log->active.count) {
return false;
}
pin_active(log, log->active.count);
return true;
}
bool slog_latest(const slog_t *log, slog_sample_t *row)
{
if (!log || !row || !log->has_sample) {
return false;
}
const slog_bank_t *bank = log->active.count ? &log->active : &log->archive;
if (!bank->count) {
return false;
}
*row = bank->rows[bank_index(log, bank, bank->count - 1U)];
return true;
}
static bool read_bank(const slog_t *log, const slog_bank_t *bank,
uint64_t *next_sequence, slog_sample_t *row)
{
if (!bank->count) {
return false;
}
uint64_t first = bank->rows[bank->oldest].sequence;
uint64_t offset = *next_sequence > first ? *next_sequence - first : 0;
if (offset >= bank->count) {
return false;
}
*row = bank->rows[bank_index(log, bank, (size_t)offset)];
*next_sequence = row->sequence + 1U;
return true;
}
bool slog_read(slog_t const *log, uint64_t *next_sequence, slog_sample_t *row)
{
return log && next_sequence && row &&
(read_bank(log, &log->archive, next_sequence, row) ||
read_bank(log, &log->active, next_sequence, row));
}
bool slog_archive_info(slog_t const *log, uint32_t *generation, size_t *count,
size_t *trigger_index)
{
if (!log || !log->archive.count || !generation || !count || !trigger_index) {
return false;
}
*generation = log->generation;
*count = log->archive.count;
*trigger_index = log->trigger_index;
return true;
}
bool slog_archive_read(slog_t const *log, uint32_t generation, size_t index,
slog_sample_t *row)
{
if (!log || !row || generation != log->generation || index >= log->archive.count) {
return false;
}
*row = log->archive.rows[bank_index(log, &log->archive, index)];
return true;
}
bool slog_archive_release(slog_t *log, uint32_t generation)
{
if (!log || !log->archive.count || generation != log->generation) {
return false;
}
log->archive.count = 0;
return true;
}
+73
View File
@@ -0,0 +1,73 @@
#ifndef TELEMETRY_LOGGER_H
#define TELEMETRY_LOGGER_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define SLOG_MAX_CHANNELS 40U
typedef struct {
uint64_t time_us;
uint64_t sequence;
uint64_t valid;
uint16_t event;
int32_t values[SLOG_MAX_CHANNELS];
} slog_sample_t;
typedef struct {
slog_sample_t *rows;
size_t oldest;
size_t count;
} slog_bank_t;
typedef struct {
slog_bank_t active;
slog_bank_t archive;
size_t capacity;
size_t post_rows;
size_t remaining;
size_t trigger_index;
uint64_t last_us;
uint64_t next_sequence;
uint32_t generation;
uint32_t missed_triggers;
uint16_t channels;
bool has_sample;
} slog_t;
/* Banks are caller-owned, disjoint arrays of capacity rows each. A single bank
* (archive == NULL) supports rolling history. The caller serializes all calls. */
bool slog_init(slog_t *log, uint16_t channels, slog_sample_t *active,
slog_sample_t *archive, size_t capacity, size_t post_rows);
/* Values has log->channels elements. An accepted trigger keeps this row and
* post_rows following rows before swapping banks. Timestamp is monotonic. */
bool slog_push(slog_t *log, uint64_t time_us, uint64_t valid,
uint16_t event, const int32_t *values, bool trigger);
/* Returns the requested sequence if retained, or the oldest available sample
* after it. Initialize next_sequence to 0. A successful read advances cursor;
* subtract its previous value from row.sequence to count missed samples. */
bool slog_read(slog_t const *log, uint64_t *next_sequence, slog_sample_t *row);
/* Capture the rolling bank immediately. The archive uses count as its trigger
* index when the capture was requested manually. */
bool slog_snapshot(slog_t *log);
bool slog_latest(const slog_t *log, slog_sample_t *row);
/* A completed archive is immutable until released with its generation. */
bool slog_archive_info(slog_t const *log, uint32_t *generation, size_t *count,
size_t *trigger_index);
bool slog_archive_read(slog_t const *log, uint32_t generation, size_t index,
slog_sample_t *row);
bool slog_archive_release(slog_t *log, uint32_t generation);
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,53 @@
#include "telemetry_gas.h"
#include <assert.h>
int main(void)
{
slog_t log;
slog_gas_t gas;
slog_sample_t bank[2][4] = {0};
uint16_t words[18];
assert(!slog_init(&log, 2, bank[0], bank[1], 4, 4));
assert(slog_init(&log, 2, bank[0], bank[1], 4, 1));
assert(!slog_gas_init(&gas, &log, 0x6000, 0x6001, 0, 1));
assert(slog_gas_init(&gas, &log, 0x6000, 0x5000, 0x89abcdef, 1));
assert(slog_gas_write(&gas, 0x6012, GL_START) == GL_OK);
int32_t values[] = {2000, -302};
for (unsigned i = 0; i < 7; ++i) {
assert(slog_push(&log, i * 1250, i == 5 ? 2 : 3, i == 5 ? 9 : 0, values, i == 5));
}
uint64_t cursor = 0;
slog_sample_t row;
assert(slog_read(&log, &cursor, &row) && cursor == 4 && row.sequence == 3);
uint32_t generation;
size_t count, trigger;
assert(slog_archive_info(&log, &generation, &count, &trigger));
assert(count == 4 && trigger == 2);
assert(slog_gas_read(&gas, 0x6000, words, 18) == GL_OK);
assert(words[2] == 3 && words[7] == 4 && words[10] == 0xcdef && words[11] == 0x89ab);
assert(slog_gas_read(&gas, 0x610d, words, 9) == GL_OK);
assert(words[1] == 6 && words[2] == 0 && words[3] == 5 && words[5] == 9);
assert(words[6] == UINT16_MAX && words[7] == (uint16_t)-302 && words[8] == 7);
assert(slog_push(&log, 10000, 3, 8, values, true));
assert(log.missed_triggers == 1);
assert(slog_gas_write(&gas, 0x6012, GL_RELEASE) == GL_STALE);
assert(slog_gas_write(&gas, 0x6013, (uint16_t)generation) == GL_OK);
assert(slog_gas_write(&gas, 0x6012, GL_RELEASE) == GL_OK);
assert(slog_read(&log, &cursor, &row) && cursor == 8 && row.sequence == 7);
assert(!slog_push(&log, 1, 3, 0, values, false));
assert(slog_gas_read(&gas, 0x5000, words, 2) == GL_OK);
assert(words[0] == 2000 && words[1] == (uint16_t)-302);
assert(slog_gas_write(&gas, 0x6012, GL_SNAPSHOT) == GL_OK);
assert(slog_archive_info(&log, &generation, &count, &trigger));
assert(count == 1 && trigger == count);
slog_t other;
static slog_sample_t wide[1];
int32_t channels[40] = {0};
channels[39] = 42;
assert(slog_init(&other, 40, wide, NULL, 1, 0));
assert(slog_push(&other, 0, UINT64_C(1) << 39, 0, channels, false));
assert(slog_latest(&other, &row) && row.values[39] == 42);
return 0;
}