-
Notifications
You must be signed in to change notification settings - Fork 0
/
Can_Controller.cpp
99 lines (88 loc) · 2.29 KB
/
Can_Controller.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
95
96
97
98
99
#include "Can_Controller.h"
#include "Logger.h"
// Must define instance prior to use
Can_Controller* Can_Controller::instance = NULL;
Can_Controller::Can_Controller ()
: begun(false)
{
delegate = MCP_CAN(MCP_CS_PIN);
}
Can_Controller& Can_Controller::getInstance() {
if(!instance) {
instance = new Can_Controller();
instance->begin();
}
return *instance;
}
Can_Controller& CAN() {
return Can_Controller::getInstance();
}
void Can_Controller::begin() {
// Idempotent
if (begun) {
return;
}
begun = true;
// Set interrupt pin.
// DON'T set MCP_CS: mcp_can library does it for us
pinMode(MCP_INT_PIN, INPUT);
uint8_t response = delegate.begin(CAN_500KBPS);
if (delegate.begin(CAN_500KBPS) != CAN_OK) {
Computer().logTwo("CAN_begin_error", canResponseToString(response));
Onboard().logTwo("CAN_begin_error", canResponseToString(response));
}
}
bool Can_Controller::msgAvailable() {
return delegate.checkReceive() == CAN_MSGAVAIL;
}
Frame Can_Controller::read() {
Frame frame;
uint8_t response = delegate.readMsgBuf(&frame.len, frame.body);
if (response != CAN_OK) {
Computer().logTwo("CAN_read_error", canResponseToString(response));
Onboard().logTwo("CAN_read_error", canResponseToString(response));
}
frame.id = delegate.getCanId();
return frame;
}
String Can_Controller::canResponseToString(uint8_t response) {
switch (response) {
case CAN_OK:
return "CAN_OK";
break;
case CAN_FAILINIT:
return "CAN_FAILINIT";
break;
case CAN_FAILTX:
return "CAN_FAILTX";
break;
case CAN_MSGAVAIL:
return "CAN_MSGAVAIL";
break;
case CAN_NOMSG:
return "CAN_NOMSG";
break;
case CAN_CTRLERROR:
return "CAN_CTRLERROR";
break;
case CAN_GETTXBFTIMEOUT:
return "CAN_GETTXBFTIMEOUT";
break;
case CAN_SENDMSGTIMEOUT:
return "CAN_SENDMSGTIMEOUT";
break;
case CAN_FAIL:
return "CAN_FAIL";
break;
default:
return "UNKNOWN_ERROR";
break;
}
}
void Can_Controller::write(Frame f) {
uint8_t response = delegate.sendMsgBuf(f.id, 0, f.len, f.body);
if (response != CAN_OK) {
Computer().logTwo("CAN_write_error", canResponseToString(response));
Onboard().logTwo("CAN_write_error", canResponseToString(response));
}
}