-
-
Notifications
You must be signed in to change notification settings - Fork 84
/
decoder.cpp
94 lines (90 loc) · 2.64 KB
/
decoder.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
* This file is part of cannelloni, a SocketCAN over Ethernet tunnel.
*
* Copyright (C) 2014-2023 Maximilian Güntner <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#include <cstring>
#include <netinet/in.h>
#include "decoder.h"
#include "cannelloni.h"
#define CAN_ID_SIZE_BYTES 4
#define CAN_LEN_SIZE_BYTES 1
#define CAN_FLAGS_SIZE_BYTES 1
#define MAX_TRANSMIT_BUFFER_SIZE_BYTES CAN_ID_SIZE_BYTES + CAN_LEN_SIZE_BYTES + CAN_FLAGS_SIZE_BYTES + CANFD_MAX_DLEN
using namespace cannelloni;
ssize_t decodeFrame(uint8_t *data, size_t len, canfd_frame *frame, DecodeState *state) {
switch (*state) {
case STATE_INIT:
*state = STATE_CAN_ID;
return CAN_ID_SIZE_BYTES;
case STATE_CAN_ID:
if (len != CAN_ID_SIZE_BYTES) {
return -1;
}
canid_t tmp;
memcpy(&tmp, data, sizeof(canid_t));
frame->can_id = ntohl(tmp);
*state = STATE_LEN;
return CAN_LEN_SIZE_BYTES;
case STATE_LEN:
if (len != CAN_LEN_SIZE_BYTES) {
return -1;
}
frame->len = *data;
/* If this is a CAN FD frame, also retrieve the flags */
if (frame->len & CANFD_FRAME) {
*state = STATE_FLAGS;
return CAN_FLAGS_SIZE_BYTES;
}
/* RTR Frames have no data section although they have a dlc */
if (frame->can_id & CAN_RTR_FLAG) {
*state = STATE_INIT;
frame->len=0;
return 0;
}
if (canfd_len(frame) == 0) {
*state = STATE_INIT;
return 0;
}
*state = STATE_DATA;
return canfd_len(frame);
case STATE_FLAGS:
if (len != CAN_FLAGS_SIZE_BYTES) {
return -1;
}
frame->flags = *data;
/* RTR Frames have no data section although they have a dlc */
if (frame->can_id & CAN_RTR_FLAG) {
*state = STATE_INIT;
return 0;
}
if (canfd_len(frame) == 0) {
*state = STATE_INIT;
return 0;
}
*state = STATE_DATA;
return canfd_len(frame);
case STATE_DATA:
if (len != canfd_len(frame)) {
return -1;
}
memcpy(frame->data, data, canfd_len(frame));
*state = STATE_INIT;
return 0;
}
return -1;
}