This repository was archived by the owner on Jan 20, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqtt-switch.ino
212 lines (181 loc) · 6.13 KB
/
mqtt-switch.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
// Copyright (c) 2023 Niklas Bettgen
#include <ArduinoJson.h>
#include <Bridge.h>
#include <Process.h>
#include <PubSubClient.h>
#include <Servo.h>
#include <YunClient.h>
#include "./config.h"
#include "./src/state_machine.h"
#include "./src/lib/timer/timer.h"
#include "./src/lib/debouncer/debouncer.h"
// Git version fallback
#ifndef GIT_VERSION
#define GIT_VERSION __DATE__ " " __TIME__
#endif
YunClient yun_client;
PubSubClient mqtt_client(MQTT_BROKER, MQTT_PORT, yun_client);
DynamicJsonDocument json_buffer(MQTT_JSON_BUFFER);
Timer mqtt_reconnect_timer(MQTT_RECONNECT_TIMEOUT);
ServoStateMachine state_machine(SERVO_PIN, SERVO_POS_NEUTRAL_DEG, SERVO_POS_TOP_DEG, SERVO_POS_BOTTOM_DEG);
DebouncedSwitch button(BUTTON_PIN, BUTTON_DEBOUNCE_MS, BUTTON_USE_PULLUP);
bool latest_cmd_by_mqtt = false;
void setup() {
Bridge.begin();
Serial.begin(115200);
Serial.println(F("Starting " PROJECT_NAME " (version: " GIT_VERSION ")."));
pinMode(BUTTON_PIN, BUTTON_USE_PULLUP ? INPUT_PULLUP : INPUT);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
state_machine.setup();
mqtt_client.setCallback(onMsgReceived);
mqttConnect();
}
void loop() {
// Handle MQTT connection
if (mqtt_client.connected()) {
mqtt_client.loop();
} else {
// Indicate connection attempt by flashing LED with 2Hz
mqtt_reconnect_timer.start();
const Timer::ms freq = 500;
digitalWrite(LED_PIN, ((mqtt_reconnect_timer.getElapsedTime() % freq) < freq / 2) ? HIGH : LOW);
if (mqtt_reconnect_timer.checkAndRestart()) {
digitalWrite(LED_PIN, HIGH);
if (mqttConnect()) {
mqtt_reconnect_timer.reset();
}
digitalWrite(LED_PIN, LOW);
}
}
// Handle servo state machine
state_machine.loop();
if (state_machine.hasPosChanged()) {
onStateChanged();
}
// Handle actions triggered by button press
button.debounce();
if (button.hasChanged() && button.isClosed()) {
Serial.println(F("Button was pressed."));
latest_cmd_by_mqtt = false;
if (state_machine.getLatestPos() == ServoStateMachine::Position::TOP) {
setServoBottom();
} else {
setServoTop();
}
}
}
void onMsgReceived(char* topic, byte* payload, unsigned int length) {
Serial.print(F("MQTT message with "));
Serial.print(length);
Serial.print(F(" bytes received on topic "));
Serial.println(topic);
if (strcasecmp(topic, MQTT_COMMAND_TOPIC) == 0) {
deserializeJson(json_buffer, payload, length);
const char* state = json_buffer["switch"];
if (strcasecmp(state, "top") == 0) {
latest_cmd_by_mqtt = true;
setServoTop();
} else if (strcasecmp(state, "bottom") == 0) {
latest_cmd_by_mqtt = true;
setServoBottom();
} else if (json_buffer.containsKey("pos")) {
latest_cmd_by_mqtt = true;
const int pos = json_buffer["pos"];
setServoToPos(pos);
}
}
}
void onStateChanged() {
// Send MQTT message
if (mqtt_client.connected()) {
json_buffer.clear();
json_buffer["actual"] = "neutral";
json_buffer["latest"] = "unknown";
json_buffer["trigger"] = "unknown";
switch (state_machine.getCurrentPos()) {
case ServoStateMachine::Position::TOP:
json_buffer["actual"] = "top";
break;
case ServoStateMachine::Position::BOTTOM:
json_buffer["actual"] = "bottom";
break;
}
switch (state_machine.getLatestPos()) {
case ServoStateMachine::Position::TOP:
json_buffer["latest"] = "top";
break;
case ServoStateMachine::Position::BOTTOM:
json_buffer["latest"] = "bottom";
break;
}
if (latest_cmd_by_mqtt) {
json_buffer["trigger"] = "mqtt";
} else {
json_buffer["trigger"] = "button";
}
char payload[MQTT_JSON_BUFFER];
serializeJson(json_buffer, payload);
mqtt_client.publish(MQTT_STATE_TOPIC, payload, true);
}
// Update LED
setLed();
}
void onMqttConnected() {
Serial.print(F("Connected to MQTT broker. Subscribing to topic "));
Serial.println(MQTT_COMMAND_TOPIC);
mqtt_client.subscribe(MQTT_COMMAND_TOPIC);
// Update device availability
json_buffer.clear();
json_buffer["state"] = "online";
json_buffer["version"] = GIT_VERSION;
char payload[MQTT_JSON_BUFFER];
serializeJson(json_buffer, payload);
mqtt_client.publish(MQTT_AVAIL_TOPIC, payload, true);
}
bool mqttConnect() {
json_buffer.clear();
json_buffer["state"] = "offline";
char payload_avail[MQTT_JSON_BUFFER];
serializeJson(json_buffer, payload_avail);
Serial.print(F("Attempting MQTT connection... "));
if (mqtt_client.connect(
MQTT_CLIENT_ID,
MQTT_USER,
MQTT_PASSWORD,
MQTT_AVAIL_TOPIC,
0,
true,
payload_avail)
) {
Serial.println(F("connected!"));
onMqttConnected();
return true;
}
Serial.print(F("failed! RC="));
Serial.println(mqtt_client.state());
return false;
}
void setServoTop() {
if (state_machine.setPos(ServoStateMachine::Position::TOP)) {
Serial.println(F("Turning servo to position 'top'."));
} else {
Serial.println(F("State machine is busy! Not doing anything."));
}
}
void setServoBottom() {
if (state_machine.setPos(ServoStateMachine::Position::BOTTOM)) {
Serial.println(F("Turning servo to position 'bottom'."));
} else {
Serial.println(F("State machine is busy! Not doing anything."));
}
}
void setServoToPos(const int pos) {
state_machine.setManualPos(pos);
Serial.print(F("Turning servo to manual position: "));
Serial.println(pos);
}
void setLed() {
bool is_bottom = state_machine.getLatestPos() == ServoStateMachine::Position::BOTTOM;
digitalWrite(LED_PIN, (is_bottom ^ LED_ON_TOP) ? HIGH : LOW);
}