forked from marcelstoer/Lovebox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lovebox.ino
257 lines (224 loc) · 6.59 KB
/
lovebox.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
// *****************************************************************************
//
// See README for explanations how the MQTT and GitHub-gist-fetching versions of
// this application work.
//
// *****************************************************************************
#include "settings.h"
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <Servo.h>
#include <TZ.h>
#include "SSD1306Wire.h"
#ifdef USE_MQTT
#include <PubSubClient.h>
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
char* mqttMessage;
bool newMqttMessageAvailable;
#else
const int fetchIntervalMillis = fetchIntervalSeconds * 1000;
#endif
SSD1306Wire oled(0x3C, D2, D1);
Servo myservo;
int pos = 90;
int increment = -1;
int lightValue;
String mode;
char idSaved = '0';
bool wasRead = true;
void drawMessage(const String& message) {
Serial.println("Drawing message....");
oled.clear();
// differentiat between *t*ext and image messages
if (mode[0] == 't') {
oled.drawStringMaxWidth(0, 0, 128, message);
} else {
for (int i = 0; i <= message.length(); i++) {
int x = i % 129;
int y = i / 129;
if (message[i] == '1') {
oled.setPixel(x, y);
}
}
}
oled.display();
Serial.println("done.");
}
// Set time via NTP, as required for x.509 validation
void setClock() {
// General C time functions: https://en.wikipedia.org/wiki/C_date_and_time_functions
configTime(TIMEZONE, "pool.ntp.org");
Serial.print("Waiting for NTP time sync: ");
time_t now = time(nullptr);
// 1546300800 = 01/01/2019 @ 12:00am (UTC)
while (now < 1546300800) {
delay(500);
Serial.print(".");
now = time(nullptr);
}
Serial.println();
time_t nowUtc = mktime(gmtime(&now));
Serial.print("Local time: ");
Serial.print(ctime(&now));
Serial.print("UTC: ");
Serial.print(ctime(&nowUtc));
Serial.println();
}
void wifiConnect() {
Serial.printf("Connecting to WiFi '%s'...", ssid);
if (WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
Serial.print("..done. IP ");
Serial.println(WiFi.localIP());
}
#ifdef USE_MQTT
void mqttConnect() {
mqttClient.setServer(mqttServer, mqttPort);
mqttClient.setCallback(mqttCallback);
while (!mqttClient.connected()) {
Serial.println("Connecting to MQTT...");
if (mqttClient.connect(mqttClientId, mqttUser, mqttPassword)) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.println(mqttClient.state());
delay(2000);
}
}
mqttClient.publish(mqttPublishTopic, "Hello from Lovebox");
mqttClient.subscribe(mqttSubscribeTopic);
}
void mqttCallback(char* topic, byte* payload, unsigned int length) {
// resetting the "message was read" flag
wasRead = 0;
mode = (char)payload[0];
Serial.println("New MQTT message:");
Serial.println(mode);
// skip 2 bytes (mode plus follwing newline) but add 1 for the terminating 0 appended at the end
mqttMessage = new char[length - 2 + 1];
memcpy (mqttMessage, (char*)payload + 2, length - 2);
mqttMessage[length - 2] = '\0';
Serial.print(mqttMessage);
newMqttMessageAvailable = true;
mqttClient.publish(mqttPublishTopic, "New message fully processed");
}
#else
void getGistMessage() {
Serial.println("Fetching gist message...");
const int httpsPort = 443;
const char* host = "gist.githubusercontent.com";
BearSSL::WiFiClientSecure client;
BearSSL::X509List cert(digicertRootCert);
client.setTrustAnchors(&cert);
if (!client.connect(host, httpsPort)) {
Serial.println("Failed to connect to GitHub");
return;
}
// add current millis as a cache-busting means
client.print(String("GET ") + url + "?" + millis() + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: ESP8266\r\n" +
"Connection: close\r\n\r\n");
while (client.connected()) {
String temp = client.readStringUntil('\n');
if (temp == "\r") {
break;
}
}
String id = client.readStringUntil('\n');
Serial.printf("\tid: '%s', last processed id: '%c'\n", id.c_str(), idSaved);
if (id[0] != idSaved) { // new message
wasRead = 0;
idSaved = id[0];
mode = client.readStringUntil('\n');
Serial.println("\tmode: " + mode);
String line = client.readStringUntil(0);
Serial.println("\tmessage: " + line);
drawMessage(line);
} else {
Serial.println("\t-> message id wasn't updated");
}
}
#endif
void spinServo() {
myservo.write(pos);
delay(50); // wait 50ms to turn servo
if (pos == 75 || pos == 105) { // 75°-105° range
increment *= -1;
}
pos += increment;
}
void setup() {
Serial.begin(115200);
Serial.println("\n\n");
Serial.print("Attaching servo...");
myservo.attach(16); // Servo an D0
Serial.println("done.");
Serial.print("Initializing display...");
oled.init();
oled.flipScreenVertically();
oled.setColor(WHITE);
oled.setTextAlignment(TEXT_ALIGN_LEFT);
oled.setFont(ArialMT_Plain_10);
oled.clear();
oled.drawString(30, 30, "<3 LOVEBOX <3");
oled.display();
Serial.println("done.");
wifiConnect();
setClock();
#ifdef USE_MQTT
Serial.println("Running in MQTT mode.");
// 128 x 64 pixels require at most 8192 bytes (1 per pixel) for pixelated images
// plus 1 byte to denote the message type ('t' = text, 'b' = "binary")
// plus newlines
mqttClient.setBufferSize(8192 + 100);
mqttConnect();
#else
Serial.printf("Running in GitHub-gist-fetching mode. Initial state: last processed id '%c' %s read.\n", idSaved, (wasRead ? "was" : "wasn't"));
#endif
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Lost WiFi connection. Attempting to reconnect.");
wifiConnect();
setClock();
}
#ifdef USE_MQTT
if (!mqttClient.connected()) {
Serial.println("Lost connection to MQTT broker. Attempting to reconnect.");
mqttConnect();
}
mqttClient.loop();
if (newMqttMessageAvailable) {
drawMessage(mqttMessage);
mqttClient.publish(mqttPublishTopic, "New message rendered");
delete[] mqttMessage;
newMqttMessageAvailable = false;
}
#else
if (wasRead) {
getGistMessage();
}
#endif
while (!wasRead) {
yield();
spinServo();
lightValue = analogRead(0);
if (lightValue > lightValueThreshold) {
Serial.printf("Analog read value (LDR) %d above threshold of %d -> consider message read.\n", lightValue, lightValueThreshold);
#ifdef USE_MQTT
mqttClient.publish(mqttPublishTopic, "Message was read");
#endif
wasRead = 1;
}
}
#ifndef USE_MQTT
delay(fetchIntervalMillis);
#endif
}