SAE Teensy ECU
IIT SAE Microcontroller programming
Loading...
Searching...
No Matches
SerialCommand.cpp
Go to the documentation of this file.
1
12// @cond
13#include "SerialCommand.h"
14#include "Log.h"
15#include "core_pins.h"
16#include "usb_serial.h"
17
18namespace Cmd {
19
20static LOG_TAG ID = "Serial Command";
21
22#define X(value) value,
23static const size_t COMMAND_COUNT = PP_NARG_MO(SERIAL_COMMANDS);
24static CommandCallback callbacks[COMMAND_COUNT];
25static size_t cmdMap[COMMAND_COUNT] = {SERIAL_COMMANDS};
26#undef X
27
28static size_t matchCommand(uint8_t val) {
29 size_t i = 0;
30#define X(value) \
31 if (value == val) { \
32 return i; \
33 } \
34 i++;
36#undef X
37 return COMMAND_COUNT;
38}
39
40int receiveCommand(void) {
41 int serialData = -1;
42 if (Serial.available()) {
43 serialData = Serial.read();
44 Log.d(ID, "Data received: ", serialData);
45 size_t i;
46 if ((i = matchCommand(serialData)) != COMMAND_COUNT && callbacks[i]) {
47 callbacks[i]();
48 }
49 }
50 return serialData;
51}
52
53void setCommand(uint8_t command, CommandCallback callback) {
54 for (size_t i = 0; i < COMMAND_COUNT; i++) {
55 if (cmdMap[i] == command) {
56 callbacks[i] = callback;
57 Log.i(ID, "Command set for:", command);
58 return;
59 }
60 }
61 Log.w(ID, "No Command found for command:", command);
62}
63} // namespace Cmd
64 // @endcond
Special logging functionality.
const char * LOG_TAG
Type definition of logging tags This typedef is necessary to allow for easier manipulation of code by...
Definition Log.h:48
Logging::Log_t Log
The global logging object.
#define SERIAL_COMMANDS
Defines commands that the ECU must react to.
SerialCommand functionality.
void(* CommandCallback)(void)
A function that will be called whenever its corresponding command byte is received.
A simple way to run commands over serial.
int receiveCommand(void)
receive any command from serial by matching incoming bytes to a callback
void setCommand(uint8_t command, CommandCallback callback)
attach a single callback to a byte value that will be received over serial
void d(LOG_TAG TAG, LOG_MSG message)
Log a string using a debug tag.
void w(LOG_TAG TAG, LOG_MSG message)
Log a string using a warning tag.
void i(LOG_TAG TAG, LOG_MSG message)
Log a string using an info tag.