-
Notifications
You must be signed in to change notification settings - Fork 1
/
3_shutter.ino
137 lines (106 loc) · 2.49 KB
/
3_shutter.ino
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
class Shutter {
public:
uint8_t index;
String label;
uint8_t position;
uint8_t newPosition;
char statTopic[50];
char cmndTopic[50];
Shutter(unsigned int index, String label, unsigned int pinUp, unsigned int pinDown) {
this->index = index;
this->label = label;
sprintf(statTopic,"%s/%s", mqttStatTopic, label.c_str());
sprintf(cmndTopic,"%s/%s", mqttCmndTopic, label.c_str());
position = 0;
newPosition = 0;
_pinUp = pinUp;
_pinDown = pinDown;
}
void setup() {
setupPins();
stop();
setupPosition();
}
void subscribe() {
client.subscribe(cmndTopic);
}
int steps() {
return newPosition - position;
}
void setPosition(String updatePosition) {
Serial.print("setPosition ");
Serial.print(label + ": ");
Serial.println(updatePosition);
if (updatePosition == "STOP") {
newPosition = position;
stop();
} else {
newPosition = updatePosition.toInt();
updateRelays();
}
}
void afterStep() {
if (steps() == 0) {
return;
}
position += (steps() > 0 ? 1 : -1);
publishMqtt();
if (steps() == 0) {
savePosition();
stop();
}
}
void savePosition() {
Serial.println("Saving " + String(index) + " " + String(position));
EEPROM.put(index, position);
EEPROM.commit();
}
void stop() {
digitalWrite(_pinUp, HIGH);
digitalWrite(_pinDown, HIGH);
}
void publishSerial() {
Serial.println(label + " position: " + String(position));
}
void publishMqtt() {
char positionChar[3];
sprintf(positionChar, "%i", position);
client.publish(statTopic, positionChar, true);
}
private:
unsigned int _pinUp;
unsigned int _pinDown;
void updateRelays() {
if (steps() > 0) {
if (movingDown()) {
stop();
}
digitalWrite(_pinUp, LOW);
} else if (steps() < 0) {
if (movingUp()) {
stop();
}
digitalWrite(_pinDown, LOW);
} else {
stop();
}
}
bool movingUp() {
return digitalRead(_pinUp) == LOW;
}
bool movingDown() {
return digitalRead(_pinDown) == LOW;
}
bool relayStopped() {
return digitalRead(_pinUp) == HIGH && digitalRead(_pinDown) == HIGH;
}
void setupPins() {
pinMode(_pinUp, OUTPUT);
pinMode(_pinDown, OUTPUT);
}
void setupPosition() {
EEPROM.get(index, position);
newPosition = position;
Serial.println("Loading " + String(index) + " " + String(position));
}
};