Files
templates/c/rs485-boot/tests/test_rs485_boot.c
T
Andrey e93bd3b6aa style: унифицируй форматирование C и C++
Закрепи табуляцию и размещение скобок в настройках проекта. Примени единый стиль к собственным исходникам.
2026-12-02 11:33:41 +03:00

104 lines
2.6 KiB
C

/*
* Проверки rs485_boot: фиксируют ожидаемое поведение на воспроизводимых входных данных.
* Тестовые значения и подмены окружения относятся к проверке контракта; они не являются
* настройками рабочего устройства.
*/
#include "rs485_boot.h"
#include <assert.h>
#include <string.h>
static uint8_t flash_mem[256], reply[600];
static uint16_t reply_len;
static bool tx(void *u, const uint8_t *d, uint16_t n)
{
(void)u;
memcpy(reply, d, n);
reply_len = n;
return true;
}
static bool erase(void *u, uint32_t n)
{
(void)u;
(void)n;
memset(flash_mem, 0xff, sizeof(flash_mem));
return true;
}
static bool write_cb(void *u, uint32_t o, const uint8_t *d, uint16_t n)
{
(void)u;
memcpy(&flash_mem[o], d, n);
return true;
}
static bool read_cb(void *u, uint32_t o, uint8_t *d, uint16_t n)
{
(void)u;
memcpy(d, &flash_mem[o], n);
return true;
}
static bool valid(void *u, uint32_t n, uint32_t crc)
{
(void)u;
return rs485_boot_crc32(flash_mem, n) == crc;
}
static uint16_t frame(uint8_t type, uint16_t seq, const uint8_t *p, uint16_t n, uint8_t *out)
{
uint32_t c;
uint16_t i;
out[0] = 0xa5;
out[1] = 0x5a;
out[2] = 1;
out[3] = type;
out[4] = (uint8_t)(seq >> 8);
out[5] = (uint8_t)seq;
out[6] = (uint8_t)(n >> 8);
out[7] = (uint8_t)n;
for (i = 0; i < n; i++)
out[8 + i] = p[i];
c = rs485_boot_crc32(&out[2], 6U + n);
out[8 + n] = (uint8_t)c;
out[9 + n] = (uint8_t)(c >> 8);
out[10 + n] = (uint8_t)(c >> 16);
out[11 + n] = (uint8_t)(c >> 24);
return (uint16_t)(12 + n);
}
static void p32(uint8_t *p, uint32_t v)
{
p[0] = (uint8_t)v;
p[1] = (uint8_t)(v >> 8);
p[2] = (uint8_t)(v >> 16);
p[3] = (uint8_t)(v >> 24);
}
int main(void)
{
rs485_boot_t b;
rs485_boot_config_t c = {0x08003000, 256, 64};
rs485_boot_port_t p = {tx, erase, write_cb, read_cb, valid, 0};
uint8_t f[600], x[32] = {0};
uint8_t image[4] = {1, 2, 3, 4};
uint32_t crc = rs485_boot_crc32(image, 4);
uint16_t n;
assert(rs485_boot_init(&b, &c, &p, 0));
p32(x, 4);
p32(&x[4], crc);
p32(&x[12], c.app_address);
n = frame(0x0b, 1, x, 16, f);
rs485_boot_feed(&b, f, n);
assert(b.state == RS485_BOOT_RECEIVING && reply_len == 16);
p32(x, 0);
x[4] = 4;
x[5] = 0;
x[6] = 10;
x[7] = 0;
memcpy(&x[8], image, 4);
n = frame(0x0c, 2, x, 12, f);
rs485_boot_feed(&b, f, n);
assert(b.next_offset == 4 && memcmp(flash_mem, image, 4) == 0);
p32(x, 4);
p32(&x[4], crc);
n = frame(0x0d, 3, x, 8, f);
rs485_boot_feed(&b, f, n);
assert(b.state == RS485_BOOT_READY);
return 0;
}