-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSerialBridge.cpp
97 lines (86 loc) · 2.44 KB
/
SerialBridge.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
/*
SerialBridge.cpp - mcu <=> mpu serial bridge
Created by Luca Paolini, April 3, 2019.
*/
#include "SerialBridge.h"
SerialBridge::SerialBridge(
HardwareSerial &serial, long linkSpeed, int statusLed,
char enableChar, char disableChar, unsigned long enableGraceMillis,
void (*enableHandler)(HardwareSerial serial, char enableChar, boolean justEnabled),
void (*disableHandler)(HardwareSerial serial, char disableChar, boolean justEnabled),
void (*readHandler)(HardwareSerial serial, char readChar)
) : serial(serial) {
this->linkSpeed = linkSpeed;
this->statusLed = statusLed;
this->enableChar = enableChar;
this->disableChar = disableChar;
this->enableGraceMillis = enableGraceMillis;
this->enableHandler = enableHandler;
this->disableHandler = disableHandler;
this->readHandler = readHandler;
}
void SerialBridge::start() {
serial.begin(linkSpeed);
}
void SerialBridge::stop() {
serial.end();
}
boolean SerialBridge::isEnabled() {
boolean withinGracePeriod = (enableGraceMillis == 0) || (millis() - lastEnabled < enableGraceMillis);
return enabled && withinGracePeriod;
}
void SerialBridge::read() {
int c = serial.read();
if (c == enableChar) {
boolean wasEnabled = enabled;
enabled = true;
lastEnabled = millis();
blink();
if (enableHandler) {
enableHandler(serial, enableChar, wasEnabled == false);
}
return;
}
if (c == disableChar) {
boolean wasEnabled = enabled;
enabled = false;
if (disableHandler) {
disableHandler(serial, disableChar, wasEnabled == true);
}
return;
}
if (isEnabled()) {
if (readHandler) {
readHandler(serial, c);
}
};
}
void SerialBridge::blink() {
lastBlink = millis();
ledState = HIGH;
digitalWrite(statusLed, ledState);
}
void SerialBridge::resetBlink() {
unsigned long now = millis();
unsigned long duration = now - lastBlink;
if (ledState == HIGH && duration > BLINK_DURATION_MS) {
ledState = LOW;
digitalWrite(statusLed, ledState);
lastBlink = now;
}
}
void SerialBridge::begin() {
pinMode(statusLed, OUTPUT);
digitalWrite(statusLed, HIGH);
delay(2500);
start();
digitalWrite(statusLed, LOW);
}
void SerialBridge::end() {
stop();
digitalWrite(statusLed, LOW);
}
void SerialBridge::loop() {
read();
resetBlink();
}