DeterministicESPAsyncWebServer v6.28.0
Zero-allocation, bounded-execution async HTTP server for ESP32
Loading...
Searching...
No Matches
nema_ts2.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 Douglas Quigg (dstroy0) <dquigg123@gmail.com>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4/**
5 * @file nema_ts2.cpp
6 * @brief NEMA TS 2 SDLC frame codec (see nema_ts2.h).
7 */
8
10
11#if DETWS_ENABLE_NEMA_TS2
12
13#include <string.h>
14
15uint16_t detws_nema_ts2_crc(const uint8_t *bytes, size_t len)
16{
17 // CRC-16/X-25: reflected poly 0x8408 (reverse of 0x1021), init 0xFFFF, xorout 0xFFFF.
18 uint16_t crc = 0xFFFF;
19 for (size_t i = 0; i < len; i++)
20 {
21 crc ^= bytes[i];
22 for (int b = 0; b < 8; b++)
23 crc = (crc & 1) ? (uint16_t)((crc >> 1) ^ 0x8408) : (uint16_t)(crc >> 1);
24 }
25 return (uint16_t)~crc;
26}
27
28size_t detws_nema_ts2_build(uint8_t address, uint8_t control, uint8_t frame_type, const uint8_t *data, size_t data_len,
29 uint8_t *out, size_t cap)
30{
31 if (!out || (data_len && !data))
32 return 0;
33 size_t n = 3 + data_len + 2;
34 if (n > cap)
35 return 0;
36 out[0] = address;
37 out[1] = control;
38 out[2] = frame_type;
39 if (data_len)
40 memcpy(out + 3, data, data_len);
41 uint16_t crc = detws_nema_ts2_crc(out, 3 + data_len);
42 out[3 + data_len] = (uint8_t)crc; // FCS low byte first
43 out[3 + data_len + 1] = (uint8_t)(crc >> 8);
44 return n;
45}
46
47bool detws_nema_ts2_parse(const uint8_t *frame, size_t len, NemaTs2Frame *out)
48{
49 if (!frame || !out || len < 5) // address + control + frame_type + 2-byte FCS
50 return false;
51 size_t body = len - 2;
52 uint16_t want = detws_nema_ts2_crc(frame, body);
53 uint16_t got = (uint16_t)(frame[body] | (frame[body + 1] << 8));
54 if (want != got)
55 return false;
56 out->address = frame[0];
57 out->control = frame[1];
58 out->frame_type = frame[2];
59 out->data = (body > 3) ? (frame + 3) : nullptr;
60 out->data_len = body - 3;
61 return true;
62}
63
64#endif // DETWS_ENABLE_NEMA_TS2
NEMA TS 2 traffic-cabinet SDLC frame codec (DETWS_ENABLE_NEMA_TS2).