-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathESP_SHD_Relay.cpp
89 lines (75 loc) · 2.14 KB
/
ESP_SHD_Relay.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
#include "ESP_SHD_Relay.h"
uint8_t ShdRelay::relayCount = 0;
ShdRelay::ShdRelay(uint8_t _pin, uint32_t _millisBetweenToggle, bool _lowActive, bool _valueAtBeginning) : pin(_pin), lowActive(_lowActive){
relayCount++;
relayNumber = relayCount;
if (_millisBetweenToggle/5 > 0) {
minCyclesBetweenToggles = _millisBetweenToggle/5;
} else {
minCyclesBetweenToggles = 1;
}
setPoint = _valueAtBeginning;
pinMode(pin, OUTPUT);
setOuput(setPoint);
snprintf(subTopicSetStatus, 50, "%s/Relay/%d/setStatus", name, relayNumber);
snprintf(pubTopicGetStatus, 50, "%s/Relay/%d/getStatus", name, relayNumber);
mqttSubscribe(this, subTopicSetStatus);
#if DEBUG >= 1
Serial.print("RLY: No. ");
Serial.print(relayCount);
Serial.print(" subscribed to ");
Serial.println(subTopicSetStatus);
#endif
}
void ShdRelay::timer5msHandler(){
// increase cycleCounterSinceLastToggle:
cycleCounterSinceLastToggle++;
// if overflow, reset to minCyclesBetweenToggles:
if (cycleCounterSinceLastToggle == 0xFFFF) {
cycleCounterSinceLastToggle = minCyclesBetweenToggles+1;
}
if (setPoint != currentStatus) {
if (cycleCounterSinceLastToggle > minCyclesBetweenToggles) {
setOuput(setPoint);
}
}
}
bool ShdRelay::handleMqttRequest(char *_topic, unsigned char *_payload, uint16_t _length){
if (strcmp(_topic, subTopicSetStatus) == 0) {
if (_payload[0] == 0x31) {
#if DEBUG > 2
Serial.print("RLY: No. ");
Serial.print(relayNumber);
Serial.println(" is set to ON.");
#endif
setPoint = true;
} else {
#if DEBUG > 2
Serial.print("RLY: No. ");
Serial.print(relayNumber);
Serial.println(" is set to OFF.");
#endif
setPoint = false;
}
} else {
return false;
}
republish();
return true;
}
void ShdRelay::republish(){
if (setPoint == true) {
mqttPublish(pubTopicGetStatus, "1");
} else {
mqttPublish(pubTopicGetStatus, "0");
}
}
void ShdRelay::setOuput(bool _setPoint) {
if (!lowActive) {
digitalWrite(pin, _setPoint);
} else {
digitalWrite(pin, !_setPoint);
}
currentStatus = _setPoint;
cycleCounterSinceLastToggle = 0;
}