-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDeathOfThings.ino
249 lines (207 loc) · 6.77 KB
/
DeathOfThings.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
#include <MQTT.h>
#include <IotWebConf.h>
#include <Arduino.h>
#include <U8x8lib.h>
// -- Initial name of the Thing. Used e.g. as SSID of the own Access Point.
String thingName = "DoT_"+String(ESP.getChipId(),HEX);
int buttonPin = D5;
int buttonValue = 0;
int lastRead = 0;
// -- Initial password to connect to the Thing, when it creates an own Access Point.
const char wifiInitialApPassword[] = "";
#define STRING_LEN 256
// -- Configuration specific key. The value should be modified if config structure was changed.
#define CONFIG_VERSION "mqt2"
// -- When CONFIG_PIN is pulled to ground on startup, the Thing will use the initial
// password to buld an AP. (E.g. in case of lost password)
#define CONFIG_PIN D2
// -- Status indicator pin.
// First it will light up (kept LOW), on Wifi connection it will blink,
// when connected to the Wifi it will turn off (kept HIGH).
#define STATUS_PIN LED_BUILTIN
U8X8_SSD1306_128X64_NONAME_SW_I2C u8x8(/* clock=*/ 2, /* data=*/ 0, /* reset=*/ U8X8_PIN_NONE); // Digispark ATTiny85
// -- Callback method declarations.
void wifiConnected();
void configSaved();
boolean formValidator();
void mqttMessageReceived(String &topic, String &payload);
DNSServer dnsServer;
WebServer server(80);
HTTPUpdateServer httpUpdater;
WiFiClient net;
MQTTClient mqttClient;
char mqttServerValue[STRING_LEN];
char mqttUserNameValue[STRING_LEN];
char mqttUserPasswordValue[STRING_LEN];
IotWebConf iotWebConf(thingName.c_str(), &dnsServer, &server, wifiInitialApPassword, CONFIG_VERSION);
IotWebConfParameter mqttServerParam = IotWebConfParameter("MQTT server", "mqttServer", mqttServerValue, STRING_LEN);
IotWebConfParameter mqttUserNameParam = IotWebConfParameter("MQTT user", "mqttUser", mqttUserNameValue, STRING_LEN);
IotWebConfParameter mqttUserPasswordParam = IotWebConfParameter("MQTT password", "mqttPass", mqttUserPasswordValue, STRING_LEN, "password");
boolean needMqttConnect = false;
boolean needReset = false;
int pinState = HIGH;
unsigned long lastReport = 0;
unsigned long lastMqttConnectionAttempt = 0;
#define U8LOG_WIDTH 16
#define U8LOG_HEIGHT 8
uint8_t u8log_buffer[U8LOG_WIDTH*U8LOG_HEIGHT];
U8X8LOG u8x8log;
void setup()
{
Serial.begin(115200);
Serial.println();
Serial.println("Starting up...");
iotWebConf.setStatusPin(STATUS_PIN);
iotWebConf.setConfigPin(CONFIG_PIN);
iotWebConf.addParameter(&mqttServerParam);
iotWebConf.addParameter(&mqttUserNameParam);
iotWebConf.addParameter(&mqttUserPasswordParam);
iotWebConf.setConfigSavedCallback(&configSaved);
iotWebConf.setFormValidator(&formValidator);
iotWebConf.setWifiConnectionCallback(&wifiConnected);
iotWebConf.setupUpdateServer(&httpUpdater);
// -- Initializing the configuration.
boolean validConfig = iotWebConf.init();
if (!validConfig)
{
mqttServerValue[0] = '\0';
mqttUserNameValue[0] = '\0';
mqttUserPasswordValue[0] = '\0';
}
// -- Set up required URL handlers on the web server.
server.on("/", handleRoot);
server.on("/config", []{ iotWebConf.handleConfig(); });
server.onNotFound([](){ iotWebConf.handleNotFound(); });
mqttClient.begin(mqttServerValue, net);
mqttClient.onMessage(mqttMessageReceived);
u8x8.begin();
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8log.begin(u8x8, U8LOG_WIDTH, U8LOG_HEIGHT, u8log_buffer);
u8x8log.setRedrawMode(0); // 0: Update screen with newline, 1: Update screen for every char
u8x8log.println(thingName);
pinMode(buttonPin,INPUT_PULLUP);
lastRead = millis();
}
void loop()
{
// -- doLoop should be called as frequently as possible.
iotWebConf.doLoop();
mqttClient.loop();
if (needMqttConnect)
{
if (connectMqtt())
{
needMqttConnect = false;
}
}
else if ((iotWebConf.getState() == IOTWEBCONF_STATE_ONLINE) && (!mqttClient.connected()))
{
Serial.println("MQTT reconnect");
connectMqtt();
}
if (needReset)
{
Serial.println("Rebooting after 1 second.");
iotWebConf.delay(1000);
ESP.restart();
}
unsigned long now = millis();
if ((500 < now - lastReport) && (pinState != digitalRead(CONFIG_PIN)))
{
pinState = 1 - pinState; // invert pin state as it is changed
lastReport = now;
Serial.print("Sending on MQTT channel '/test/status' :");
Serial.println(pinState == LOW ? "ON" : "OFF");
mqttClient.publish("/test/status", pinState == LOW ? "ON" : "OFF");
}
int digRead = digitalRead(buttonPin);
if((200 < now - lastRead) && (digRead != buttonValue)){
Serial.println(String("button!") + String(buttonValue));
buttonValue = digRead;
lastRead = now;
mqttClient.publish(String(mqttUserNameValue) + "/feeds/button",String(buttonValue));
}
}
/**
* Handle web requests to "/" path.
*/
void handleRoot()
{
// -- Let IotWebConf test and handle captive portal requests.
if (iotWebConf.handleCaptivePortal())
{
// -- Captive portal request were already served.
return;
}
String s = "<!DOCTYPE html><html lang=\"en\"><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\"/>";
s += "<title>IotWebConf 06 MQTT App</title></head><body>MQTT App demo";
s += "<ul>";
s += "<li>MQTT server: ";
s += mqttServerValue;
s += "</ul>";
s += "Go to <a href='config'>configure page</a> to change values.";
s += "</body></html>\n";
server.send(200, "text/html", s);
}
void wifiConnected()
{
needMqttConnect = true;
}
void configSaved()
{
Serial.println("Configuration was updated.");
needReset = true;
}
boolean formValidator()
{
Serial.println("Validating form.");
boolean valid = true;
int l = server.arg(mqttServerParam.getId()).length();
if (l < 3)
{
mqttServerParam.errorMessage = "Please provide at least 3 characters!";
valid = false;
}
return valid;
}
boolean connectMqtt() {
unsigned long now = millis();
if (1000 > now - lastMqttConnectionAttempt)
{
// Do not repeat within 1 sec.
return false;
}
Serial.println("Connecting to MQTT server...");
if (!connectMqttOptions()) {
lastMqttConnectionAttempt = now;
return false;
}
Serial.println("Connected!");
//mqttClient.subscribe(String(mqttUserNameValue) + "/feeds/button");
mqttClient.subscribe(String(mqttUserNameValue) + "/feeds/text_screen");
return true;
}
boolean connectMqttOptions()
{
boolean result;
if (mqttUserPasswordValue[0] != '\0')
{
result = mqttClient.connect(mqttUserNameValue, mqttUserNameValue, mqttUserPasswordValue);
}
else if (mqttUserNameValue[0] != '\0')
{
result = mqttClient.connect(mqttUserNameValue, mqttUserNameValue);
}
else
{
result = mqttClient.connect(mqttUserNameValue);
}
return result;
}
void mqttMessageReceived(String &topic, String &payload)
{
Serial.println("Incoming: " + topic + " - " + payload);
if(topic.endsWith("/text_screen")){
u8x8log.println(payload);
}
}