ProtoCore v0.0.2
Deterministic, zero-heap network stack for embedded targets
Loading...
Searching...
No Matches
sercos.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 sercos.cpp
6 * @brief SERCOS III telegram + IDN codec (see sercos.h).
7 */
8
10
11#if PC_ENABLE_SERCOS
12
13#include <string.h>
14
15uint16_t pc_sercos_idn(bool is_product, uint8_t param_set, uint16_t data_block)
16{
17 return (uint16_t)(((is_product ? 1u : 0u) << 15) | ((uint32_t)(param_set & 0x7) << 12) | (data_block & 0x0FFF));
18}
19
20void pc_sercos_idn_parse(uint16_t idn, bool *is_product, uint8_t *param_set, uint16_t *data_block)
21{
22 if (is_product)
23 {
24 *is_product = (idn & 0x8000) != 0;
25 }
26 if (param_set)
27 {
28 *param_set = (uint8_t)((idn >> 12) & 0x7);
29 }
30 if (data_block)
31 {
32 *data_block = (uint16_t)(idn & 0x0FFF);
33 }
34}
35
36size_t pc_sercos_build(uint8_t type, uint8_t phase, uint16_t cycle, const uint8_t *data, size_t data_len, uint8_t *out,
37 size_t cap)
38{
39 if (!out || (data_len && !data) || (type != Sercos::SERCOS_TEL_MDT && type != Sercos::SERCOS_TEL_AT))
40 {
41 return 0;
42 }
43 size_t n = Sercos::SERCOS_HDR_LEN + data_len;
44 if (n > cap)
45 {
46 return 0;
47 }
48 out[0] = type;
49 out[1] = phase;
50 out[2] = (uint8_t)cycle; // little-endian cycle count
51 out[3] = (uint8_t)(cycle >> 8);
52 if (data_len)
53 {
54 memcpy(out + Sercos::SERCOS_HDR_LEN, data, data_len);
55 }
56 return n;
57}
58
59bool pc_sercos_parse(const uint8_t *frame, size_t len, SercosTelegram *out)
60{
61 if (!frame || !out || len < Sercos::SERCOS_HDR_LEN)
62 {
63 return false;
64 }
65 if (frame[0] != Sercos::SERCOS_TEL_MDT && frame[0] != Sercos::SERCOS_TEL_AT)
66 {
67 return false;
68 }
69 out->type = frame[0];
70 out->phase = frame[1];
71 out->cycle = (uint16_t)(frame[2] | (frame[3] << 8));
72 out->data = (len > Sercos::SERCOS_HDR_LEN) ? (frame + Sercos::SERCOS_HDR_LEN) : nullptr;
73 out->data_len = len - Sercos::SERCOS_HDR_LEN;
74 return true;
75}
76
77#endif // PC_ENABLE_SERCOS
SERCOS III motion-bus telegram + IDN codec (PC_ENABLE_SERCOS).