forked from dirkx/makerspaceleiden-payment-node-7segments
/
makerspaceleiden-payment-node-7seg.ino
404 lines (347 loc) · 10 KB
/
makerspaceleiden-payment-node-7seg.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
// dirkx@webweaving.org, apache license, for the makerspaceleiden.nl
//
// Tools settings:
// Board ESP32
// Port: [the COM port your board has connected to]
//
// Boards used:
// ESP32 WRover Module
// MFRC522 (https://www.tinytronics.nl/shop/nl/communicatie-en-signalen/draadloos/rfid/rfid-kit-mfrc522-s50-mifare-met-kaart-en-key-tag)
// 7 segment display ( https://www.hobbyelectronica.nl/product/4-digit-klok-display-module)
//
// Heater module
// ESP32 Dev Module
// MFRC522
// 7 segment display
// NPN transistor, 10k, 1k resistor
// 25Ampere, 5volt relay
//
// Additional Librariries (via Sketch -> library manager):
// MFRC522-spi-i2c-uart-async
// TM1637TinyDisplay
// Arduino_JSON
// PubSub (for MQTT)
#ifndef WIFI_NETWORK
#define WIFI_NETWORK "MyWifiNetwork"
#endif
#ifndef WIFI_PASSWD
#define WIFI_PASSWD "MyWifiPassword"
#error "You prolly do not want this!"
#endif
#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <Arduino_JSON.h>
#include <SPI.h>
#include <MFRC522.h>
#include <TM1637TinyDisplay.h>
#include <ESPmDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include "global.h"
#include "log.h"
#include "rfid.h"
#include "rest.h"
#include "TelnetSerialStream.h"
// Wiring of 7 segment display - just
// two wires. See https://www.mcielectronics.cl/website_MCI/static/documents/Datasheet_TM1637.pdf
// and https://create.arduino.cc/projecthub/ryanchan/tm1637-digit-display-arduino-quick-tutorial-ca8a93
//
#define DISPLAY_CLK (25)
#define DISPLAY_DIO (26)
TM1637TinyDisplay display(DISPLAY_CLK, DISPLAY_DIO);
// For the heater
#define RELAY (12)
// Very ugly global vars - used to communicate between the REST call and the rest.
//
char terminalName[64] = TERMINAL_NAME;
int NA = 0;
char **amounts = NULL;
char **prices = NULL;
char **descs = NULL;
int amount = 0;
int default_item = -1;
double amount_no_ok_needed = AMOUNT_NO_OK_NEEDED;
const char * version = VERSION;
unsigned long device_specific_reboot_offset;
String label;
state_t md = BOOT;
double paid = 0;
unsigned long paid_seconds = 0;
int countdown = 0;
void setupDisplay() {
display.setBrightness(BRIGHT_7);
display.showString(VERSION);
Log.println("Display set to " VERSION);
}
void setupRelay() {
// relay is high-active; but there is a 10k
// pulldown past the 1k driving resistor to
// not let HiZ engage the relay.
//
digitalWrite(RELAY, 0);
pinMode(RELAY, OUTPUT);
digitalWrite(RELAY, 0);
}
void heatingOnOff(bool onOff) {
digitalWrite(RELAY, onOff ? HIGH : LOW);
}
void setup()
{
const char * p = (const char*) __FILE__;
if (rindex(p, '/')) p = rindex(p, '/') + 1;
Serial.begin(115200);
md = BOOT;
byte mac[6];
WiFi.macAddress(mac);
snprintf(terminalName, sizeof(terminalName), "%s-%s-%02x%02x%02x", TERMINAL_NAME, 1 + VERSION, mac[3], mac[4], mac[5]);
device_specific_reboot_offset = (*(unsigned short*)(mac + 4)) % 3600;
Serial.print("\n\nBuild: " __DATE__ " " __TIME__ "\nUnit: ");
Serial.println(terminalName);
setupRelay();
setupDisplay();
setupAuth(terminalName);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_NETWORK, WIFI_PASSWD);
Log.print("Connecting to ");
Log.println(WIFI_NETWORK);
yield();
display.showString("conn");
WiFi.setHostname(terminalName);
Log.print(terminalName);
Log.println(" Wifi connecting");
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
Log.println("Rebooting, wifi issue" );
display.showString("FAIL");
delay(5000);
ESP.restart();
};
Log.println("Connected.");
yield();
setupLog();
// try to get some reliable time; to stop my cert
// checking code complaining.
configTime(0, 0, NTP_SERVER);
yield();
Log.printf( "File: %s\n", p);
Log.println("Firmware: " TERMINAL_NAME "-" VERSION);
Log.println("Build: " __DATE__ " " __TIME__ );
Log.print( "Unit: ");
Log.println(terminalName);
Log.print( "MacAddr: ");
Log.println(WiFi.macAddress());
Log.print( "IP: ");
Log.println(WiFi.localIP());
setupRFID();
ArduinoOTA.setHostname(terminalName);
#ifdef OTA_HASH
ArduinoOTA.setPasswordHash(OTA_HASH);
#else
#ifdef OTA_PASSWD
ArduinoOTA.setPassword(OTA_PASSWD);
#endif
#endif
ArduinoOTA
.onStart([]() {
display.showString("PROG");
Log.println("OTA started");
})
.onEnd([]() {
Log.println("OTA completed");
// prevent a cleversod uplading a special binary. ignore the hardware/serial angle
Log.println("OTA completed OK - need to wipe keystore before rebooting into new code.");
wipekeys();
display.showString("Done");
log_stop();
heatingOnOff(false);
})
.onProgress([](unsigned int progress, unsigned int total) {
static int l = -100;
int w = 100 * progress / total;
if (w != l) {
char fw[5];
snprintf(fw, sizeof(fw), "F%3d", w);
display.showString(fw);
};
l = w;
})
.onError([](ota_error_t error) {
const char * label = "FO:OF";
if (error == OTA_AUTH_ERROR) label = (const char*) "FO:AF";
else if (error == OTA_BEGIN_ERROR) label = (const char*) "FO:BF";
else if (error == OTA_CONNECT_ERROR) label = (const char*) "FO:CF";
else if (error == OTA_RECEIVE_ERROR) label = (const char*) "FO:RF";
else if (error == OTA_END_ERROR) label = (const char*) "FO:EF";
display.showString(label);
Log.print("OTA error: E=");
Log.print(error);
Log.print(" - ");
Log.println(label);
delay(10 * 1000);
});
Debug.println("Starting loop");
display.setBrightness(BRIGHT_HIGH / 3);
display.showString("----");
ArduinoOTA.begin();
md = WAITING_FOR_NTP;
}
static void loop_RebootAtMidnight() {
static unsigned long lst = millis();
if (millis() - lst < 60 * 1000)
return;
lst = millis();
time_t now = time(nullptr);
if (now < 3600)
return;
#ifdef AUTO_REBOOT_TIME
now += device_specific_reboot_offset;
char * p = ctime(&now);
// 0123456789012345678 9 0
// "Thu Nov 4 09:47:43\n\0" -> 09:47\0
p += 11;
p[5] = 0;
if (strncmp(p, AUTO_REBOOT_TIME, strlen(AUTO_REBOOT_TIME)) == 0 && millis() > 3600 * 1000 ) {
Log.println("Nightly reboot - also to fetch new pricelist and fix any memory leaks.");
heatingOnOff(false);
ESP.restart();
}
#endif
}
int checkcardswipe() {
int v = 0;
if (NA <= 0)
return v;
if (!loopRFID())
return v;
display.setBrightness(BRIGHT_HIGH);
display.showString("[--]");
int status = payByREST(tag, prices[amount], descs[amount]);
if (status == 200) {
display.showString("PAID");
delay(500);
paid += atof(prices[amount]);
// bit of a hack - if the description is normal - things work as a one
// off payment. But if the descripton starts with a number; then we assume
// that this is a `timed in minutes' item. Annd we return how many seconds
// the timer should be increased by.
//
// If the description is normal - the atoi() returns 0; so the function
// will return zero.
//
v = 60 * atoi(descs[amount]);
paid_seconds += v;
} else {
for (int i = 0; i < 4; i++) {
display.showString("FAIL");
delay(500);
display.showNumber(status);
delay(500);
};
};
display.setBrightness(BRIGHT_HIGH / 3);
display.showNumber(amount, 2);
return v;
}
void loop()
{
static unsigned long lst = millis();
log_loop();
ArduinoOTA.handle();
loop_RebootAtMidnight();
// flap relay every 5 seconds for testing.
//
if (0) {
static unsigned long t = millis();
if (millis() - t > 5000) {
digitalWrite(RELAY, !digitalRead(RELAY));
t = millis();
}
}
switch (md) {
case WAITING_FOR_NTP:
display.showString("ntp");
if (time(nullptr) > 3600)
md = FETCH_CA;
return;
break;
case FETCH_CA:
display.showString("F CA");
fetchCA();
return;
case REGISTER:
display.showString("reg");
registerDevice();
return;
case WAIT_FOR_REGISTER_SWIPE:
display.showString("pair");
if (loopRFID()) {
display.showString("vrfy");
registerDevice();
};
return;
case REGISTER_PRICELIST:
display.showString("F PL");
if (fetchPricelist())
md = ENTER_AMOUNT;
return;
case ENTER_AMOUNT:
display.setBrightness(BRIGHT_HIGH / 3);
display.showNumber(atof(prices[amount]), 2);
// Bit of a hack - some swipes can return a number of seconds; when
// they are not a one off payment for something - but entitle you to
// something like 15 minutes of heating.
// the value returned is in seconds.
countdown += checkcardswipe();
if (countdown > 0) {
md = IN_COUNTDOWN;
lst = millis();
}
break;
case IN_COUNTDOWN:
{
// catch up as needed.
while (millis() - lst >= 1000)
{
countdown--;
lst += 1000;
}
// flash display 1.5 times towards the end
if (countdown <= 60) {
display.setBrightness(((millis() / 300) & 1) ? BRIGHT_HIGH : BRIGHT_1 );
};
if (countdown <= 0) {
countdown = 0;
// flash aggressivily once time is up.
//
for (int i = 0; i < 20; i++) {
display.setBrightness((i & 1) ? BRIGHT_HIGH : BRIGHT_LOW);
display.showString("0000");
delay(120);
display.showString("----");
delay( 70);
};
// go back to normal, switch things off.
//
heatingOnOff(false);
md = ENTER_AMOUNT;
break;
};
// Check for a swipe while we are counting down, but do not reset millis().
countdown += checkcardswipe();
char timeleft[32];
snprintf(timeleft, sizeof(timeleft) - 1, "%02d%02d", countdown / 60, countdown % 60);
display.showString(timeleft, 4, 0 /*pos*/, 0b01000000 /* dots */);
heatingOnOff(true);
break;
}
case WIFI_FAIL_REBOOT:
{ static unsigned long last = millis();
if (millis() - last > 10 * 1000)
ESP.restart();
display.showString("FFER");
};
break;
default:
break;
};
}