forked from Longan-Labs/Serial_CAN_Bus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcan.cpp
57 lines (47 loc) · 1.06 KB
/
can.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
#include "can.h"
#include "mcp_can.h"
#include "at.h"
static Frame* canAlloc(CanState& state)
{
size_t next = (state.writeIndex + 1) % FRAME_BUFFER;
if (next == state.readIndex)
return nullptr;
Frame* frame = state.frames + state.writeIndex;
state.writeIndex = next;
return frame;
}
void canReadMessages(CanState& state)
{
if (state.dev->checkReceive() != CAN_MSGAVAIL)
{
return;
}
unsigned long id;
byte length;
byte data[MAX_CHAR_IN_MESSAGE];
byte result = state.dev->readMsgBufID(&id, &length, data);
Frame* frame = canAlloc(state);
if (frame == nullptr)
{
return;
}
frame->id = id;
frame->length = length;
memcpy(frame->data, data, (length > 8) ? 8 : length);
}
int canAvailableFrames(CanState& state)
{
int read = state.readIndex;
int write = state.writeIndex;
if (write < read)
write += FRAME_BUFFER;
return write - read;
}
Frame* canGetFrame(CanState& state)
{
if (canAvailableFrames(state) == 0)
return nullptr;
Frame* frame = state.frames + state.readIndex;
state.readIndex = (state.readIndex + 1) % FRAME_BUFFER;
return frame;
}