forked from thehookup/motor-on-roller-blind-ws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
motor_on_a_roller_blind-ws.ino
615 lines (529 loc) · 19.6 KB
/
motor_on_a_roller_blind-ws.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
/****************** ALEXA INTEGRATION LIBRARIES *************************************/
#include <Espalexa.h> //https://github.com/Aircoookie/Espalexa
#include <ESP8266mDNS.h> //if you get an error here you need to install the ESP8266 board manager
/****************** ORIGINAL SKETCH LIBRARIES *************************************/
#include <ArduinoJson.h>
#include <ArduinoOTA.h>
#include <ESP8266mDNS.h>
#include <ESP8266WebServer.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Stepper_28BYJ_48.h>
#include <WebSocketsServer.h>
#include <WiFiClient.h>
#include <WiFiManager.h>
#include <WiFiUdp.h>
#include "FS.h"
#include "index_html.h"
#include "NidayandHelper.h"
//--------------- CHANGE PARAMETERS ------------------
//Configure Default Settings for Access Point logon
String APid = "Roller Shade Configuration"; //Name of access point
//Set up buttons
const uint8_t btnup = D7; //Up button
const uint8_t btndn = D6; //Down button
const uint8_t btnres = D5; //Reset button
//----------------------------------------------------
// Version number for checking if there are new code releases and notifying the user
String version = "1.3.1";
NidayandHelper helper = NidayandHelper();
Espalexa espalexa;
EspalexaDevice* device1;
void process_alexa_command(EspalexaDevice* dev);
//Fixed settings for WIFI
WiFiClient espClient;
PubSubClient psclient(espClient); //MQTT client
char alexa_invocation[40]; //WIFI config: Alexa Invocation Name (optional)
char mqtt_server[40]; //WIFI config: MQTT server config (optional)
char mqtt_port[6] = "1883"; //WIFI config: MQTT port config (optional)
char mqtt_uid[40]; //WIFI config: MQTT server username (optional)
char mqtt_pwd[40]; //WIFI config: MQTT server password (optional)
String outputTopic; //MQTT topic for sending messages
String inputTopic; //MQTT topic for listening
boolean mqttActive = true;
char config_name[40]; //WIFI config: Bonjour name of device
char config_rotation[40] = "false"; //WIFI config: Detault rotation is CCW
String action; //Action manual/auto
int path = 0; //Direction of blind (1 = down, 0 = stop, -1 = up)
int setPos = 0; //The set position 0-100% by the client
long currentPosition = 0; //Current position of the blind
long maxPosition = 2000000; //Max position of the blind. Initial value
boolean loadDataSuccess = false;
boolean saveItNow = false; //If true will store positions to SPIFFS
bool shouldSaveConfig = false; //Used for WIFI Manager callback to save parameters
boolean initLoop = true; //To enable actions first time the loop is run
boolean ccw = true; //Turns counter clockwise to lower the curtain
bool alexaActive = false;
Stepper_28BYJ_48 small_stepper(D1, D3, D2, D4); //Initiate stepper driver
ESP8266WebServer server(80); // TCP server at port 80 will respond to HTTP requests
WebSocketsServer webSocket = WebSocketsServer(81); // WebSockets will respond on port 81
bool loadConfig() {
if (!helper.loadconfig())
return false;
JsonVariant json = helper.getconfig();
//Useful if you need to see why confing is read incorrectly
json.printTo(Serial);
//Store variables locally
currentPosition = json["currentPosition"].as<long>();
maxPosition = json["maxPosition"].as<long>();
strcpy(config_name, json["config_name"]);
strcpy(alexa_invocation, json["alexa_invocation"]);
strcpy(mqtt_server, json["mqtt_server"]);
strcpy(mqtt_port, json["mqtt_port"]);
strcpy(mqtt_uid, json["mqtt_uid"]);
strcpy(mqtt_pwd, json["mqtt_pwd"]);
strcpy(config_rotation, json["config_rotation"]);
return true;
}
/**
Save configuration data to a JSON file
on SPIFFS
*/
bool saveConfig() {
DynamicJsonBuffer jsonBuffer(500);
JsonObject& json = jsonBuffer.createObject();
json["currentPosition"] = currentPosition;
json["maxPosition"] = maxPosition;
json["config_name"] = config_name;
json["alexa_invocation"] = alexa_invocation;
json["mqtt_server"] = mqtt_server;
json["mqtt_port"] = mqtt_port;
json["mqtt_uid"] = mqtt_uid;
json["mqtt_pwd"] = mqtt_pwd;
json["config_rotation"] = config_rotation;
return helper.saveconfig(json);
}
/*
Connect to MQTT server and publish a message on the bus.
Finally, close down the connection and radio
*/
void sendmsg(String topic, String payload) {
if (!mqttActive)
return;
helper.mqtt_publish(psclient, topic, payload);
}
/****************************************************************************************
*/
void processMsg(String res, uint8_t clientnum) {
/*
Check if calibration is running and if stop is received. Store the location
*/
if (action == "set" && res == "(0)") {
maxPosition = currentPosition;
saveItNow = true;
}
//Below are actions based on inbound MQTT payload
if (res == "(start)") {
//Store the current position as the start position
currentPosition = 0;
path = 0;
saveItNow = true;
action = "manual";
} else if (res == "(max)") {
//Store the max position of a closed blind
maxPosition = currentPosition;
path = 0;
saveItNow = true;
action = "manual";
} else if (res == "(0)") {
//Stop
path = 0;
saveItNow = true;
action = "manual";
} else if (res == "(1)") {
//Move down without limit to max position
path = 1;
action = "manual";
} else if (res == "(-1)") {
//Move up without limit to top position
path = -1;
action = "manual";
} else if (res == "(update)") {
//Send position details to client
int set = (setPos * 100) / maxPosition;
int pos = (currentPosition * 100) / maxPosition;
sendmsg(outputTopic, "{ \"set\":" + String(set) + ", \"position\":" + String(pos) + " }");
webSocket.sendTXT(clientnum, "{ \"set\":" + String(set) + ", \"position\":" + String(pos) + " }");
} else if (res == "(ping)") {
//Do nothing
} else {
/*
Any other message will take the blind to a position
Incoming value = 0-100
path is now the position
*/
path = maxPosition * res.toInt() / 100;
setPos = path; //Copy path for responding to updates
action = "auto";
int set = (setPos * 100) / maxPosition;
int pos = (currentPosition * 100) / maxPosition;
//Send the instruction to all connected devices
sendmsg(outputTopic, "{ \"set\":" + String(set) + ", \"position\":" + String(pos) + " }");
webSocket.broadcastTXT("{ \"set\":" + String(set) + ", \"position\":" + String(pos) + " }");
}
}
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
switch (type) {
case WStype_TEXT:
Serial.printf("[%u] get Text: %s\n", num, payload);
String res = (char*)payload;
//Send to common MQTT and websocket function
processMsg(res, num);
break;
}
}
void mqttCallback(char* topic, byte* payload, unsigned int length) {
Serial.print(F("Message arrived ["));
Serial.print(topic);
Serial.print(F("] "));
String res = "";
for (int i = 0; i < length; i++) {
res += String((char) payload[i]);
}
processMsg(res, NULL);
}
/**
Turn of power to coils whenever the blind
is not moving
*/
void stopPowerToCoils() {
digitalWrite(D1, LOW);
digitalWrite(D2, LOW);
digitalWrite(D3, LOW);
digitalWrite(D4, LOW);
Serial.println(F("Motor stopped"));
}
/*
Callback from WIFI Manager for saving configuration
*/
void saveConfigCallback () {
shouldSaveConfig = true;
}
void handleRoot() {
server.send(200, "text/html", INDEX_HTML);
}
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
if (alexaActive)
{
if (!espalexa.handleAlexaApiCall(server.uri(), server.arg(0)))
{
server.send(404, "text/plain", "Not found");
}
}
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void process_alexa_command(EspalexaDevice* d)
{
int brightnessCommand = d->getValue();
Serial.println("Got Data for Shade Position");
Serial.println(brightnessCommand);
if (brightnessCommand == 0)
{
processMsg("0", NULL);
}
else
{
int tempPosition = map(brightnessCommand, 0, 255, 0, 100);
String res = String(tempPosition);
processMsg(res, NULL);
}
}
void setup(void)
{
Serial.begin(115200);
delay(100);
Serial.print(F("Starting now\n"));
pinMode(btnup, INPUT_PULLUP);
pinMode(btndn, INPUT_PULLUP);
pinMode(btnres, INPUT_PULLUP);
//Reset the action
action = "";
//Set MQTT properties
outputTopic = helper.mqtt_gettopic("out");
inputTopic = helper.mqtt_gettopic("in");
//Set the WIFI hostname
WiFi.hostname(config_name);
//Define customer parameters for WIFI Manager
WiFiManagerParameter custom_config_name("Name", "Bonjour name", config_name, 40);
WiFiManagerParameter custom_rotation("Rotation", "Clockwise rotation", config_rotation, 40);
WiFiManagerParameter custom_text3("<p><b>Optional Alexa configuration:</b></p>");
WiFiManagerParameter custom_alexa_invocation("invocation", "Invocation Name", alexa_invocation, 40);
WiFiManagerParameter custom_text("<p><b>Optional MQTT server parameters:</b></p>");
WiFiManagerParameter custom_mqtt_server("server", "MQTT server", mqtt_server, 40);
WiFiManagerParameter custom_mqtt_port("port", "MQTT port", mqtt_port, 6);
WiFiManagerParameter custom_mqtt_uid("uid", "MQTT username", mqtt_server, 40);
WiFiManagerParameter custom_mqtt_pwd("pwd", "MQTT password", mqtt_server, 40);
WiFiManagerParameter custom_text2("<script>t = document.createElement('div');t2 = document.createElement('input');t2.setAttribute('type', 'checkbox');t2.setAttribute('id', 'tmpcheck');t2.setAttribute('style', 'width:10%');t2.setAttribute('onclick', \"if(document.getElementById('Rotation').value == 'false'){document.getElementById('Rotation').value = 'true'} else {document.getElementById('Rotation').value = 'false'}\");t3 = document.createElement('label');tn = document.createTextNode('Clockwise rotation');t3.appendChild(t2);t3.appendChild(tn);t.appendChild(t3);document.getElementById('Rotation').style.display='none';document.getElementById(\"Rotation\").parentNode.insertBefore(t, document.getElementById(\"Rotation\"));</script>");
//Setup WIFI Manager
WiFiManager wifiManager;
//reset settings - for testing
//clean FS, for testing
//helper.resetsettings(wifiManager);
wifiManager.setSaveConfigCallback(saveConfigCallback);
//add all your parameters here
wifiManager.addParameter(&custom_config_name);
wifiManager.addParameter(&custom_rotation);
wifiManager.addParameter(&custom_text3);
wifiManager.addParameter(&custom_alexa_invocation);
wifiManager.addParameter(&custom_text);
wifiManager.addParameter(&custom_mqtt_server);
wifiManager.addParameter(&custom_mqtt_port);
wifiManager.addParameter(&custom_mqtt_uid);
wifiManager.addParameter(&custom_mqtt_pwd);
wifiManager.addParameter(&custom_text2);
// if (digitalRead(btnres) == LOW)
// {
// helper.resetsettings(wifiManager);
// delay(2000);
// if (!wifiManager.autoConnect(APid.c_str()))
// {
// Serial.println("failed to connect and hit timeout");
// delay(3000);
// //reset and try again, or maybe put it to deep sleep
// ESP.reset();
// delay(5000);
// }
// }
wifiManager.autoConnect(APid.c_str());
//Load config upon start
if (!SPIFFS.begin()) {
Serial.println(F("Failed to mount file system"));
return;
}
/* Save the config back from WIFI Manager.
This is only called after configuration
when in AP mode
*/
if (shouldSaveConfig) {
//read updated parameters
strcpy(config_name, custom_config_name.getValue());
strcpy(mqtt_server, custom_mqtt_server.getValue());
strcpy(alexa_invocation, custom_alexa_invocation.getValue());
strcpy(mqtt_port, custom_mqtt_port.getValue());
strcpy(mqtt_uid, custom_mqtt_uid.getValue());
strcpy(mqtt_pwd, custom_mqtt_pwd.getValue());
strcpy(config_rotation, custom_rotation.getValue());
//Save the data
saveConfig();
}
/*
Try to load FS data configuration every time when
booting up. If loading does not work, set the default
positions
*/
loadDataSuccess = loadConfig();
if (!loadDataSuccess) {
Serial.println(F("Unable to load saved data"));
currentPosition = 0;
maxPosition = 2000000;
}
/*
Setup multi DNS (Bonjour)
*/
if (MDNS.begin(config_name)) {
Serial.println(F("MDNS responder started"));
MDNS.addService("http", "tcp", 80);
MDNS.addService("ws", "tcp", 81);
} else {
Serial.println(F("Error setting up MDNS responder!"));
while (1) {
delay(1000);
}
}
if (String(alexa_invocation) != "") {
espalexa.begin(&server);
Serial.println("Registering Alexa Device");
server.on("/", handleRoot);
server.onNotFound([]() {
if (!espalexa.handleAlexaApiCall(server.uri(), server.arg(0))) //if you don't know the URI, ask espalexa whether it is an Alexa control request
{
handleNotFound();
}
});
device1 = new EspalexaDevice(alexa_invocation, process_alexa_command, EspalexaDeviceType::color);
espalexa.addDevice(device1);
int pos = (currentPosition * 255) / maxPosition;
device1->setValue(pos);
alexaActive = true;
}
else {
alexaActive = false;
Serial.println("NOTE: No Alexa invocation is active. Only using websockets");
server.on("/", handleRoot);
server.onNotFound(handleNotFound);
server.begin();
}
Serial.print("Connect to http://" + String(config_name) + ".local or http://");
Serial.println(WiFi.localIP());
//Start websocket
webSocket.begin();
webSocket.onEvent(webSocketEvent);
/* Setup connection for MQTT and for subscribed
messages IF a server address has been entered
*/
if (String(mqtt_server) != "") {
Serial.println(F("Registering MQTT server"));
psclient.setServer(mqtt_server, String(mqtt_port).toInt());
psclient.setCallback(mqttCallback);
} else {
mqttActive = false;
Serial.println(F("NOTE: No MQTT server address has been registered. Only using websockets"));
}
//Set rotation direction of the blinds
if (String(config_rotation) == "false")
ccw = true;
else
ccw = false;
//Update webpage
INDEX_HTML.replace("{VERSION}", "V" + version);
INDEX_HTML.replace("{NAME}", String(config_name));
//Setup OTA
//helper.ota_setup(config_name);
{
// Authentication to avoid unauthorized updates
//ArduinoOTA.setPassword(OTA_PWD);
ArduinoOTA.setHostname(config_name);
ArduinoOTA.onStart([]() {
Serial.println(F("Start"));
});
ArduinoOTA.onEnd([]() {
Serial.println(F("\nEnd"));
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println(F("Auth Failed"));
else if (error == OTA_BEGIN_ERROR) Serial.println(F("Begin Failed"));
else if (error == OTA_CONNECT_ERROR) Serial.println(F("Connect Failed"));
else if (error == OTA_RECEIVE_ERROR) Serial.println(F("Receive Failed"));
else if (error == OTA_END_ERROR) Serial.println(F("End Failed"));
});
ArduinoOTA.begin();
}
}
void loop(void)
{
//OTA client code
ArduinoOTA.handle();
//Websocket listner
webSocket.loop();
//Serving the webpage
if(alexaActive)
{
espalexa.loop();
}
else
{
server.handleClient();
}
//MQTT client
if (mqttActive)
helper.mqtt_reconnect(psclient, mqtt_uid, mqtt_pwd, { inputTopic.c_str() });
if (digitalRead(btnres)) {
bool pres_cont = false;
while (!digitalRead(btndn) && currentPosition > 0) {
Serial.println(F("Moving down"));
small_stepper.step(ccw ? -1 : 1);
currentPosition = currentPosition - 1;
yield();
delay(1);
pres_cont = true;
}
while (!digitalRead(btnup) && currentPosition < maxPosition) {
Serial.println(F("Moving up"));
small_stepper.step(ccw ? 1 : -1);
currentPosition = currentPosition + 1;
yield();
delay(1);
pres_cont = true;
}
if (pres_cont) {
int set = (setPos * 100) / maxPosition;
int pos = (currentPosition * 100) / maxPosition;
webSocket.broadcastTXT("{ \"set\":" + String(set) + ", \"position\":" + String(pos) + " }");
sendmsg(outputTopic, "{ \"set\":" + String(set) + ", \"position\":" + String(pos) + " }");
Serial.println(F("Stopped. Reached wanted position"));
saveItNow = true;
}
}
if (!(digitalRead(btnres) || digitalRead(btndn) || digitalRead(btnup))) {
Serial.println(F("Hold to reset..."));
uint32_t restime = millis();
while (!(digitalRead(btnres) || digitalRead(btndn) || digitalRead(btnup)))
yield(); //Prevent watchdog trigger
if (millis() - restime >= 2500) {
stopPowerToCoils();
Serial.println(F("Removing configs..."));
WiFi.disconnect(true);
WiFiManager wifiManager;
helper.resetsettings(wifiManager);
Serial.println(F("Reboot"));
ESP.wdtFeed();
yield();
ESP.restart();
}
}
//Storing positioning data and turns off the power to the coils
if (saveItNow) {
saveConfig();
saveItNow = false;
/*
If no action is required by the motor make sure to
turn off all coils to avoid overheating and less energy
consumption
*/
stopPowerToCoils();
}
//Manage actions. Steering of the blind
if (action == "auto") {
//Automatically open or close blind
if (currentPosition > path) {
Serial.println(F("Moving down"));
small_stepper.step(ccw ? -1 : 1);
currentPosition = currentPosition - 1;
} else if (currentPosition < path) {
Serial.println(F("Moving up"));
small_stepper.step(ccw ? 1 : -1);
currentPosition = currentPosition + 1;
} else {
path = 0;
action = "";
int set = (setPos * 100) / maxPosition;
int pos = (currentPosition * 100) / maxPosition;
webSocket.broadcastTXT("{ \"set\":" + String(set) + ", \"position\":" + String(pos) + " }");
sendmsg(outputTopic, "{ \"set\":" + String(set) + ", \"position\":" + String(pos) + " }");
Serial.println(F("Stopped. Reached wanted position"));
saveItNow = true;
}
} else if (action == "manual" && path != 0) {
//Manually running the blind
small_stepper.step(ccw ? path : -path);
currentPosition = currentPosition + path;
Serial.println(F("Moving motor manually"));
}
/*
After running setup() the motor might still have
power on some of the coils. This is making sure that
power is off the first time loop() has been executed
to avoid heating the stepper motor draining
unnecessary current
*/
if (initLoop) {
initLoop = false;
stopPowerToCoils();
Serial.println(alexa_invocation);
}
}