-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArduino code
385 lines (353 loc) · 10.9 KB
/
Arduino code
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
//dont you try to copy this
#include <WiFi.h>
#include <Preferences.h>
#include "BluetoothSerial.h"
#include <PubSubClient.h>
#include "ESPAsyncWebServer.h"
// Set to true to define Relay as Normally Open (NO)
#define RELAY_NO false
// Set number of relays
#define NUM_RELAYS 2
// Assign each GPIO to a relay
int relayGPIOs[NUM_RELAYS] = {26, 25};
String ssids_array[50];
String network_string;
String connected_string;
String device_type = "2_relay";
String device_name = "PowerPlugTwo";
const char* pref_ssid = "";
const char* pref_pass = "";
String client_wifi_ssid;
String client_wifi_password;
const char *mqtt_broker = "broker.hivemq.com";
const char *topic = "biriguesp32";
const char *topic1 = "biriguesp32/relay1";
const char *topic2 = "biriguesp32/relay2";
const char *mqtt_username = "doesntmatter";
const char *mqtt_password = "doesntmatter";
const int mqtt_port = 1883;
const char* bluetooth_name = "esp32test";
long start_wifi_millis;
long wifi_timeout = 20000;
bool bluetooth_disconnect = false;
enum wifi_setup_stages { NONE, SCAN_START, SCAN_COMPLETE, SSID_ENTERED, WAIT_PASS, PASS_ENTERED, WAIT_CONNECT, LOGIN_FAILED };
enum wifi_setup_stages wifi_stage = NONE;
BluetoothSerial SerialBT;
Preferences preferences;
WiFiClient espClient;
PubSubClient client(espClient);
const char* PARAM_INPUT_1 = "relay";
const char* PARAM_INPUT_2 = "state";
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html {font-family: Arial; display: inline-block; text-align: center;}
h2 {font-size: 3.0rem;}
p {font-size: 3.0rem;}
body {
max-width: 600px; margin:0px auto; padding-bottom: 25px;
background-image: url('https://drive.google.com/uc?id=1EMH7SwrH8Ib3cBNaCjXR-FoUk8GX1UMi&export=download');
background-repeat: no-repeat;
background-size: cover;
color: white;
}
.switch {position: relative; display: inline-block; width: 120px; height: 68px}
.switch input {display: none}
.slider {position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; border-radius: 34px}
.slider:before {position: absolute; content: ""; height: 52px; width: 52px; left: 8px; bottom: 8px; background-color: #fff; -webkit-transition: .4s; transition: .4s; border-radius: 68px}
input:checked+.slider {background-color: #2196F3}
input:checked+.slider:before {-webkit-transform: translateX(52px); -ms-transform: translateX(52px); transform: translateX(52px)}
</style>
</head>
<body>
<h2>NMCT Smart Home Project</h2>
%BUTTONPLACEHOLDER%
<script>
function toggleCheckbox(element) {
var xhr = new XMLHttpRequest();
if(element.checked){
xhr.open("GET", "/update?relay="+element.id+"&state=1", true);
}
else {
xhr.open("GET", "/update?relay="+element.id+"&state=0", true);
}
xhr.send();
}
</script>
</body>
</html>
)rawliteral";
// Replaces placeholder with button section in your web page
String processor(const String& var){
//Serial.println(var);
if(var == "BUTTONPLACEHOLDER"){
String buttons ="";
for(int i=1; i<=NUM_RELAYS; i++){
String relayStateValue = relayState(i);
buttons+= "<h4>Untraalga #" + String(i) + "</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"" + String(i) + "\" "+ relayStateValue +"><span class=\"slider\"></span></label>";
}
return buttons;
}
return String();
}
String relayState(int numRelay){
if(RELAY_NO){
if(digitalRead(relayGPIOs[numRelay-1])){
return "";
}
else {
return "checked";
}
}
else {
if(digitalRead(relayGPIOs[numRelay-1])){
return "checked";
}
else {
return "";
}
}
return "";
}
// Set your Static IP address
IPAddress local_IP(192, 168, 1, 172);
// Set your Gateway IP address
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 0, 0);
IPAddress primaryDNS(8, 8, 8, 8); //optional
IPAddress secondaryDNS(8, 8, 4, 4); //optional
void setup()
{
Serial.begin(115200);
for(int i=1; i<=NUM_RELAYS; i++){
pinMode(relayGPIOs[i-1], OUTPUT);
if(RELAY_NO){
digitalWrite(relayGPIOs[i-1], HIGH);
}
else{
digitalWrite(relayGPIOs[i-1], LOW);
}
}
preferences.begin("wifi_access", false);
// preferences.remove("pref_ssid");
// preferences.remove("pref_pass");
// Configures static IP address
if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
Serial.println("STA Failed to configure");
}
if (!init_wifi()) { // Connect to Wi-Fi fails
SerialBT.register_callback(callback);
} else {
SerialBT.register_callback(callback_show_ip);
}
SerialBT.begin(bluetooth_name);
}
bool init_wifi()
{
String temp_pref_ssid = preferences.getString("pref_ssid");
String temp_pref_pass = preferences.getString("pref_pass");
pref_ssid = temp_pref_ssid.c_str();
pref_pass = temp_pref_pass.c_str();
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
start_wifi_millis = millis();
WiFi.begin(pref_ssid, pref_pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
if (millis() - start_wifi_millis > wifi_timeout) {
WiFi.disconnect(true, true);
return false;
}
}
//connected
Serial.println(WiFi.localIP());
mqttbrokersetup();
startserver();
return true;
}
void startserver() {
// Route for root / web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);
});
// Send a GET request to <ESP_IP>/update?relay=<inputMessage>&state=<inputMessage2>
server.on("/update", HTTP_GET, [] (AsyncWebServerRequest *request) {
String inputMessage;
String inputParam;
String inputMessage2;
String inputParam2;
// GET input1 value on <ESP_IP>/update?relay=<inputMessage>
if (request->hasParam(PARAM_INPUT_1) & request->hasParam(PARAM_INPUT_2)) {
inputMessage = request->getParam(PARAM_INPUT_1)->value();
inputParam = PARAM_INPUT_1;
inputMessage2 = request->getParam(PARAM_INPUT_2)->value();
inputParam2 = PARAM_INPUT_2;
if(RELAY_NO){
Serial.print("NO ");
digitalWrite(relayGPIOs[inputMessage.toInt()-1], !inputMessage2.toInt());
}
else{
Serial.print("NC ");
digitalWrite(relayGPIOs[inputMessage.toInt()-1], inputMessage2.toInt());
}
}
else {
inputMessage = "No message sent";
inputParam = "none";
}
Serial.println(inputMessage + inputMessage2);
request->send(200, "text/plain", "OK");
});
// Start server
server.begin();
}
void mqttbrokersetup() {
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(mqttcallback);
while (!client.connected()) {
String client_id = "birigutestesp";
client_id += String(WiFi.macAddress());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
//connected
} else {
//failed
delay(2000);
}
}
// publish and subscribe
client.subscribe(topic);
client.subscribe(topic1);
client.subscribe(topic2);
}
void mqttcallback(char *topic, byte *payload, unsigned int length) {
String receivedPayload;
for (int i = 0; i < length; i++) {
//message char
char receivedchar = (char) payload[i];
receivedPayload += receivedchar;
}
String topicc = String(topic);
if(topicc == "biriguesp32/relay1") {
if (receivedPayload == "on") {
digitalWrite(relayGPIOs[0], HIGH);
}
else if (receivedPayload == "off") {
digitalWrite(relayGPIOs[0], LOW);
}
}
if(topicc == "biriguesp32/relay2") {
if (receivedPayload == "on") {
digitalWrite(relayGPIOs[1], HIGH);
}
else if (receivedPayload == "off") {
digitalWrite(relayGPIOs[1], LOW);
}
}
}
void scan_wifi_networks()
{
WiFi.mode(WIFI_STA);
int n = WiFi.scanNetworks();
if (n == 0) {
SerialBT.println("no networks found");
} else {
SerialBT.print(n);
SerialBT.println(" networks found");
delay(1000);
for (int i = 0; i < n; ++i) {
ssids_array[i + 1] = WiFi.SSID(i);
network_string = i + 1;
network_string = network_string + ": " + WiFi.SSID(i) + " (Strength:" + WiFi.RSSI(i) + ")\n";
SerialBT.print(network_string);
}
wifi_stage = SCAN_COMPLETE;
}
}
void callback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param)
{
if (event == ESP_SPP_SRV_OPEN_EVT) {
wifi_stage = SCAN_START;
}
if (event == ESP_SPP_DATA_IND_EVT && wifi_stage == SCAN_COMPLETE) { // data from phone is SSID
int client_wifi_ssid_id = SerialBT.readString().toInt();
client_wifi_ssid = ssids_array[client_wifi_ssid_id];
wifi_stage = SSID_ENTERED;
}
if (event == ESP_SPP_DATA_IND_EVT && wifi_stage == WAIT_PASS) { // data from phone is password
client_wifi_password = SerialBT.readString();
client_wifi_password.trim();
wifi_stage = PASS_ENTERED;
}
}
void callback_show_ip(esp_spp_cb_event_t event, esp_spp_cb_param_t *param)
{
if (event == ESP_SPP_SRV_OPEN_EVT) {
SerialBT.print("ESP32 IP: ");
SerialBT.println(WiFi.localIP());
bluetooth_disconnect = true;
}
}
void disconnect_bluetooth()
{
delay(1000);
SerialBT.println("Bluetooth disconnecting...");
delay(1000);
SerialBT.flush();
SerialBT.disconnect();
SerialBT.end();
delay(1000);
bluetooth_disconnect = false;
}
void loop()
{
client.loop();
if (bluetooth_disconnect)
{
disconnect_bluetooth();
}
switch (wifi_stage)
{
case SCAN_START:
SerialBT.println("Scanning Wi-Fi networks");
Serial.println("Scanning Wi-Fi networks");
scan_wifi_networks();
delay(200);
SerialBT.println("");
SerialBT.println("Please enter the number for your Wi-Fi");
wifi_stage = SCAN_COMPLETE;
break;
case SSID_ENTERED:
SerialBT.println("Please enter your Wi-Fi password");
Serial.println("Please enter your Wi-Fi password");
wifi_stage = WAIT_PASS;
break;
case PASS_ENTERED:
SerialBT.println("Please wait for Wi-Fi connection...");
Serial.println("Please wait for Wi_Fi connection...");
wifi_stage = WAIT_CONNECT;
preferences.putString("pref_ssid", client_wifi_ssid);
preferences.putString("pref_pass", client_wifi_password);
if (init_wifi()) { // Connected to WiFi
connected_string = "ESP32 IP: ";
connected_string = connected_string + WiFi.localIP().toString();
String device_info = device_name + "," + device_type;
SerialBT.println(connected_string);
Serial.println(connected_string);
SerialBT.println(device_info);
bluetooth_disconnect = true;
} else { // try again
wifi_stage = LOGIN_FAILED;
}
break;
case LOGIN_FAILED:
SerialBT.println("Wi-Fi wrong password or unknown error. Try again");
Serial.println("Wi-Fi connection failed");
delay(2000);
wifi_stage = SCAN_START;
break;
}
}
//birigu baby