-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTally_Arbiter_TTGO_T.ino
677 lines (623 loc) · 20.1 KB
/
Tally_Arbiter_TTGO_T.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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
/*
#########################################################################################
include libs:
Websockets
Arduino_JSON
TFT_eSPI
MultiButton
Modify User_Setup_Select.h in libraryY TFT_eSPI
//#include <User_Setup.h>
#include <User_Setups/Setup25_TTGO_T_Display.h>
#########################################################################################
*/
#include "SPIFFS.h"
#include <WiFi.h>
#include <WebSocketsClient.h>
#include <SocketIOclient.h>
#include <Arduino_JSON.h>
#include <PinButton.h>
#include <Preferences.h>
#include <TFT_eSPI.h>
#include <SPI.h>
#include <Arduino.h>
#include <AsyncTCP.h>
//#include <ESPAsyncWebServer.h>
#include <ESPAsyncWebSrv.h>
#include "esp_adc_cal.h"
#include "TallyArbiter.h"
#define ADC_EN 14 //ADC_EN is the ADC detection enable port
#define ADC_PIN 34
AsyncWebServer server(80);
AsyncEventSource events("/events");
const char* ssidPath = "/ssid.txt";
const char* passPath = "/pass.txt";
const char* ipPath = "/ip.txt";
const char* portPath = "/port.txt";
const char* SSID_INPUT = "ssid";
const char* PASS_INPUT = "pass";
const char* IP_INPUT = "ip";
const char* PORT_INPUT = "port";
String ssid;
String pass;
String ip;
String port;
String localip;
float battery_voltage;
String voltage;
int vref = 1100;
int batteryLevel = 100;
int barLevel = 0;
int LevelColor = TFT_WHITE;
bool backlight = true;
PinButton btntop(35); //top button, switch screen. hold button while booting: setupmode
PinButton btnbottom(0); //bottom button, screen on/off
Preferences preferences;
TFT_eSPI tft = TFT_eSPI(); // Invoke library, pins defined in User_Setup.h
bool CUT_BUS = true; // true = Programm + Preview = Red Tally; false = Programm + Preview = Yellow Tally screen
bool LAST_MSG = true; // true = show messages on tally screen
//For static IP Configuration, change USE_STATIC to true and define your IP address settings below
bool USE_STATIC = false; // true = use static, false = use DHCP
IPAddress clientIp(192, 168, 2, 5); // Static IP
IPAddress subnet(255, 255, 255, 0); // Subnet Mask
IPAddress gateway(192, 168, 2, 1); // Gateway
//Tally Arbiter variables
SocketIOclient socket;
JSONVar BusOptions;
JSONVar Devices;
JSONVar DeviceStates;
String DeviceId = "Unassigned";
String DeviceName = "Unassigned";
String ListenerType = "m5-stickc";
// Name of the device - the 3 last bytes of the mac address will be appended to create a unique identifier for the server.
String listenerDeviceName = "m5StickC-";
bool mode_preview = false;
bool mode_program = false;
const byte led_program = 25; //red led connected with 270ohm resistor
const byte led_preview = 27; //green led connected with 270ohm resistor
const byte led_blue = 26; //blue led connected with 270ohm resistor
String LastMessage = "";
//General Variables
bool networkConnected = false;
int currentScreen = 0; //0 = Tally Screen, 1 = Settings Screen
bool setupmode = false;
void espDelay(int ms) {
esp_sleep_enable_timer_wakeup(ms * 1000);
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
esp_light_sleep_start();
}
// Initialize SPIFFS
void initSPIFFS() {
if (!SPIFFS.begin(true)) {
Serial.println("An error has occurred while mounting SPIFFS");
}
else{
Serial.println("SPIFFS mounted successfully");
}
}
String readFile(fs::FS &fs, const char * path){
Serial.printf("Reading file: %s\r\n", path);
File file = fs.open(path);
if(!file || file.isDirectory()){
Serial.println("- failed to open file for reading");
return String();
}
String fileContent;
while(file.available()){
fileContent = file.readStringUntil('\n');
break;
}
Serial.println(fileContent);
return fileContent;
}
void writeFile(fs::FS &fs, const char * path, const char * message){
Serial.printf("Writing file: %s\r\n", path);
File file = fs.open(path, FILE_WRITE);
if(!file){
Serial.println("- failed to open file for writing");
return;
}
if(file.print(message)){
Serial.println("- file written");
} else {
Serial.println("- frite failed");
}
}
void showVoltage() {
static uint64_t timeStamp = 0;
if (millis() - timeStamp > 5000) {
timeStamp = millis();
uint16_t v = analogRead(ADC_PIN);
battery_voltage = ((float)v / 4095.0) * 2.0 * 3.3 * (vref / 1000.0);
voltage = "Voltage :" + String(battery_voltage) + "V";
batteryLevel = floor(100.0 * (((battery_voltage * 1.1) - 3.0) / (4.07 - 3.0))); //100%=3.7V, Vmin = 2.8V
batteryLevel = batteryLevel > 100 ? 100 : batteryLevel;
barLevel = 133 - (batteryLevel * 133/100);
if (battery_voltage >= 3){
LevelColor = TFT_WHITE;
}
else {
LevelColor = TFT_RED;
}
if (currentScreen == 0){
tft.fillRect(232, 0, 8, 135, LevelColor);
tft.fillRect(233, 1, 6, barLevel, TFT_BLACK);
}
if (battery_voltage < 2.8){ //go into sleep,awake with top button
tft.setRotation(1);
tft.setCursor(0, 0);
tft.fillScreen(TFT_BLACK);
tft.setTextColor(TFT_WHITE);
tft.setTextSize(2);
tft.println("Battery level low");
tft.println("Going into sleepmode");
espDelay(5000);
tft.writecommand(TFT_DISPOFF);
tft.writecommand(TFT_SLPIN);
//After using light sleep, you need to disable timer wake, because here use external IO port to wake up
esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_TIMER);
// esp_sleep_enable_ext1_wakeup(GPIO_SEL_35, ESP_EXT1_WAKEUP_ALL_LOW);
esp_sleep_enable_ext0_wakeup(GPIO_NUM_35, 0);
delay(200);
esp_deep_sleep_start();
}
}
}
void showSettings() {
//displays the current network connection and Tally Arbiter server data
tft.setCursor(0, 0);
tft.fillScreen(TFT_BLACK);
tft.setTextSize(2);
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.println("SSID: " + String(ssid));
tft.println(WiFi.localIP());
tft.println();
tft.println("TallyArbiter Server:");
tft.println(String(ip) + ":" + String(port));
tft.println();
Serial.println(voltage);
if(battery_voltage >= 4.2){
tft.println("Battery charging..."); // show when TTGO is plugged in
}
else if (battery_voltage < 3) {
tft.println("Battery empty. Recharge!!");
}
else {
tft.println("Battery:" + String(batteryLevel) + "%");
}
}
void showDeviceInfo() {
//displays the currently assigned device and tally data
evaluateMode();
}
void logger(String strLog, String strType) {
if (strType == "info") {
Serial.println(strLog);
int x = strLog.length();
for (int i=0; i < x; i=i+19) {
tft.println(strLog.substring(0,19));
strLog = strLog.substring(19);
}
}
else {
Serial.println(strLog);
}
}
void connectToNetwork() {
logger("Connecting to SSID: " + String(ssid), "info");
WiFi.disconnect(true);
WiFi.onEvent(WiFiEvent);
WiFi.mode(WIFI_STA); //station
WiFi.setSleep(false);
if(USE_STATIC == true) {
WiFi.config(clientIp, gateway, subnet);
}
//WiFi.begin(networkSSID, networkPass);
WiFi.begin(ssid.c_str(), pass.c_str());
}
void WiFiEvent(WiFiEvent_t event) {
switch (event) {
case SYSTEM_EVENT_STA_GOT_IP:
logger("Network connected!", "info");
logger(WiFi.localIP().toString(), "info");
networkConnected = true;
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
tft.setCursor(0, 0);
tft.fillScreen(TFT_BLACK);
tft.setTextSize(2);
logger("Network connection lost!", "info");
showVoltage();
digitalWrite(led_blue, HIGH);
networkConnected = false;
delay(1000);
connectToNetwork();
break;
}
}
void ws_emit(String event, const char *payload = NULL) {
if (payload) {
String msg = "[\"" + event + "\"," + payload + "]";
socket.sendEVENT(msg);
} else {
String msg = "[\"" + event + "\"]";
socket.sendEVENT(msg);
}
}
void connectToServer() {
logger("Connecting to Tally Arbiter host: " + String(ip) + port, "info");
socket.onEvent(socket_event);
socket.begin(String(ip), port.toInt());
}
void socket_event(socketIOmessageType_t type, uint8_t * payload, size_t length) {
switch (type) {
case sIOtype_DISCONNECT:
socket_Disconnected();
break;
case sIOtype_CONNECT:
socket_Connected((char*)payload, length);
break;
case sIOtype_ACK:
case sIOtype_ERROR:
socket_Disconnected();
break;
case sIOtype_BINARY_EVENT:
case sIOtype_BINARY_ACK:
// Not handled
break;
case sIOtype_EVENT:
String msg = (char*)payload;
String type = msg.substring(2, msg.indexOf("\"",2));
String content = msg.substring(type.length() + 4);
content.remove(content.length() - 1);
logger("Got event '" + type + "', data: " + content, "info-quiet");
if (type == "bus_options") BusOptions = JSON.parse(content);
if (type == "reassign") socket_Reassign(content);
if (type == "flash") socket_Flash();
if (type == "messaging") socket_Messaging(content);
if (type == "deviceId") {
DeviceId = content.substring(1, content.length()-1);
SetDeviceName();
showDeviceInfo();
currentScreen = 0;
}
if (type == "devices") {
Devices = JSON.parse(content);
SetDeviceName();
}
if (type == "device_states") {
DeviceStates = JSON.parse(content);
processTallyData();
}
break;
}
}
void socket_Disconnected() {
digitalWrite(led_blue, HIGH);
tft.setCursor(0, 0);
tft.fillScreen(TFT_BLACK);
tft.setTextSize(2);
logger("Disconnected from TallyArbiter!", "info");
logger(voltage, "info");
}
void socket_Connected(const char * payload, size_t length) {
logger("Connected to Tally Arbiter server.", "info");
digitalWrite(led_blue, LOW);
tft.fillScreen(TFT_BLACK);
//String deviceObj = "{\"deviceId\": \"" + DeviceId + "\", \"listenerType\": \"" + ListenerType + "\"}";
String deviceObj = "{\"deviceId\": \"" + DeviceId + "\", \"listenerType\": \"" + listenerDeviceName.c_str() + "\", \"canBeReassigned\": true, \"canBeFlashed\": true, \"supportsChat\": true }";
char charDeviceObj[1024];
strcpy(charDeviceObj, deviceObj.c_str());
ws_emit("listenerclient_connect", charDeviceObj);
ws_emit("bus_options");
//ws_emit("device_listen_m5", charDeviceObj);
ws_emit("devices");
}
void socket_Flash() {
//flash the screen white 3 times
tft.fillScreen(TFT_WHITE);
digitalWrite(led_blue, HIGH);
delay(500);
tft.fillScreen(TFT_BLACK);
digitalWrite(led_blue, LOW);
delay(500);
tft.fillScreen(TFT_WHITE);
digitalWrite(led_blue, HIGH);
delay(500);
tft.fillScreen(TFT_BLACK);
digitalWrite(led_blue, LOW);
delay(500);
tft.fillScreen(TFT_WHITE);
digitalWrite(led_blue, HIGH);
delay(500);
tft.fillScreen(TFT_BLACK);
digitalWrite(led_blue, LOW);
//then resume normal operation
switch (currentScreen) {
case 0:
showDeviceInfo();
break;
case 1:
showSettings();
break;
}
}
String strip_quot(String str) {
if (str[0] == '"') {
str.remove(0, 1);
}
if (str.endsWith("\"")) {
str.remove(str.length()-1, 1);
}
return str;
}
void socket_Reassign(String payload) {
String oldDeviceId = payload.substring(0, payload.indexOf(','));
String newDeviceId = payload.substring(oldDeviceId.length()+1);
newDeviceId = newDeviceId.substring(0, newDeviceId.indexOf(','));
oldDeviceId = strip_quot(oldDeviceId);
newDeviceId = strip_quot(newDeviceId);
String reassignObj = "{\"oldDeviceId\": \"" + oldDeviceId + "\", \"newDeviceId\": \"" + newDeviceId + "\"}";
char charReassignObj[1024];
strcpy(charReassignObj, reassignObj.c_str());
//socket.emit("listener_reassign_object", charReassignObj);
ws_emit("listener_reassign_object", charReassignObj);
ws_emit("devices");
tft.fillScreen(TFT_WHITE);
digitalWrite(led_blue, HIGH);
delay(200);
tft.fillScreen(TFT_BLACK);
digitalWrite(led_blue, LOW);
delay(200);
tft.fillScreen(TFT_WHITE);
digitalWrite(led_blue, HIGH);
delay(200);
tft.fillScreen(TFT_BLACK);
digitalWrite(led_blue, LOW);
DeviceId = newDeviceId;
preferences.begin("tally-arbiter", false);
preferences.putString("deviceid", newDeviceId);
preferences.end();
SetDeviceName();
}
void socket_Messaging(String payload) {
String strPayload = String(payload);
int typeQuoteIndex = strPayload.indexOf(',');
String messageType = strPayload.substring(0, typeQuoteIndex);
messageType.replace("\"", "");
//Only messages from producer and clients.
if (messageType != "server") {
int messageQuoteIndex = strPayload.lastIndexOf(',');
String message = strPayload.substring(messageQuoteIndex + 1);
message.replace("\"", "");
LastMessage = messageType + ": " + message;
evaluateMode();
}
}
void processTallyData() {
for (int i = 0; i < DeviceStates.length(); i++) {
if (getBusTypeById(JSON.stringify(DeviceStates[i]["busId"])) == "\"preview\"") {
if (DeviceStates[i]["sources"].length() > 0) {
mode_preview = true;
}
else {
mode_preview = false;
}
}
if (getBusTypeById(JSON.stringify(DeviceStates[i]["busId"])) == "\"program\"") {
if (DeviceStates[i]["sources"].length() > 0) {
mode_program = true;
}
else {
mode_program = false;
}
}
}
currentScreen = 0;
evaluateMode();
}
String getBusTypeById(String busId) {
for (int i = 0; i < BusOptions.length(); i++) {
if (JSON.stringify(BusOptions[i]["id"]) == busId) {
return JSON.stringify(BusOptions[i]["type"]);
}
}
return "invalid";
}
void SetDeviceName() {
for (int i = 0; i < Devices.length(); i++) {
if (JSON.stringify(Devices[i]["id"]) == "\"" + DeviceId + "\"") {
String strDevice = JSON.stringify(Devices[i]["name"]);
DeviceName = strDevice.substring(1, strDevice.length() - 1);
break;
}
}
preferences.begin("tally-arbiter", false);
preferences.putString("devicename", DeviceName);
preferences.end();
evaluateMode();
}
void evaluateMode() {
tft.setCursor(0, 0);
tft.setTextSize(2);
if (mode_preview && !mode_program) {
logger("The device is in preview.", "info-quiet");
digitalWrite(led_program, LOW);
digitalWrite(led_preview, HIGH);
tft.setTextColor(TFT_BLACK);
tft.fillScreen(TFT_GREEN);
}
else if (!mode_preview && mode_program) {
logger("The device is in program.", "info-quiet");
digitalWrite(led_program, HIGH);
digitalWrite(led_preview, LOW);
tft.setTextColor(TFT_BLACK);
tft.fillScreen(TFT_RED);
}
else if (mode_preview && mode_program) {
logger("The device is in preview+program.", "info-quiet");
tft.setTextColor(TFT_BLACK);
if (CUT_BUS == true) {
tft.fillScreen(TFT_RED);
}
else {
tft.fillScreen(TFT_YELLOW);
}
digitalWrite(led_program, HIGH);
digitalWrite(led_preview, LOW);
}
else {
digitalWrite(led_program, LOW);
digitalWrite(led_preview, LOW);
tft.setTextColor(TFT_WHITE);
tft.fillScreen(TFT_BLACK);
}
tft.println(DeviceName);
tft.println("-------------------");
if (LAST_MSG == true) {
//tft.println(LastMessage);
logger(LastMessage, "info");
}
tft.fillRect(232, 0, 8, 135, LevelColor);
tft.fillRect(233, 1, 6, barLevel, TFT_BLACK);
}
void setup(void) {
Serial.begin(115200);
while (!Serial);
/*
ADC_EN is the ADC detection enable port
If the USB port is used for power supply, it is turned on by default.
If it is powered by battery, it needs to be set to high level
*/
pinMode(ADC_EN, OUTPUT);
digitalWrite(ADC_EN, HIGH);
// Initialize the TTGO object
logger("Initializing TTGO.", "info-quiet");
setCpuFrequencyMhz(80); //Save battery by turning down the CPU clock
btStop(); //Save battery by turning off BlueTooth
// Append last three pairs of MAC to listenerDeviceName to make it some what unique
byte mac[6]; // the MAC address of your Wifi shield
WiFi.macAddress(mac);
listenerDeviceName = listenerDeviceName + String(mac[3], HEX) + String(mac[4], HEX) + String(mac[5], HEX);
tft.init();
tft.setRotation(1);
tft.setCursor(0, 0);
tft.fillScreen(TFT_BLACK);
tft.setTextColor(TFT_WHITE);
tft.setTextSize(1);
tft.setSwapBytes(true);
tft.pushImage(0, 0, 240, 135, TallyArbiter);
//check if top button is pressed at boot foor setup mode
if (digitalRead(35) == 0) {
setupmode = true;
}
espDelay(5000);
logger("Tally Arbiter TTGO Listener Client booting.", "info");
initSPIFFS();
ssid = readFile(SPIFFS, ssidPath);
pass = readFile(SPIFFS, passPath);
ip = readFile(SPIFFS, ipPath);
port = readFile(SPIFFS, portPath);
pinMode(led_program, OUTPUT);
pinMode(led_preview, OUTPUT);
pinMode(led_blue, OUTPUT);
digitalWrite(led_blue, HIGH);
Serial.println("Blue LED ON.");
if(setupmode || ssid=="" || ip=="") {
Serial.println("Setting AP (Access Point)");
WiFi.softAP("TA-WIFI-MANAGER", NULL);
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(IP);
localip = String() + WiFi.softAPIP()[0] + "." + WiFi.softAPIP()[1] + "." + WiFi.softAPIP()[2] + "." + WiFi.softAPIP()[3];
setupmode = true;
// Web Server Root URL For WiFi Manager Web Page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(SPIFFS, "/index.html", "text/html");
});
server.serveStatic("/", SPIFFS, "/");
server.on("/", HTTP_POST, [](AsyncWebServerRequest *request) {
int params = request->params();
for(int i=0;i<params;i++){
AsyncWebParameter* p = request->getParam(i);
if(p->isPost()){
if (p->name() == SSID_INPUT) {
ssid = p->value().c_str();
writeFile(SPIFFS, ssidPath, ssid.c_str());
}
if (p->name() == PASS_INPUT) {
pass = p->value().c_str();
writeFile(SPIFFS, passPath, pass.c_str());
}
if (p->name() == IP_INPUT) {
ip = p->value().c_str();
writeFile(SPIFFS, ipPath, ip.c_str());
}
if (p->name() == PORT_INPUT) {
port = p->value().c_str();
writeFile(SPIFFS, portPath, port.c_str());
}
}
}
request->send(200, "text/plain", "Saved. Tally will restart.");
delay(3000);
ESP.restart();
});
server.begin();
}
else {
connectToNetwork();
while (!networkConnected) {
delay(200);
}
Serial.println("connected");
Serial.println(WiFi.localIP());
preferences.begin("tally-arbiter", false);
if(preferences.getString("deviceid").length() > 0){
DeviceId = preferences.getString("deviceid");
}
if(preferences.getString("devicename").length() > 0){
DeviceName = preferences.getString("devicename");
}
preferences.end();
connectToServer();
}
}
void loop() {
if (setupmode) {
digitalWrite(led_blue, HIGH);
tft.setCursor(0, 0);
tft.fillScreen(TFT_BLACK);
tft.setTextSize(2);
logger("Setup mode", "info");
logger("Connect to:", "info");
logger("TA-WIFI-MANAGER", "info");
logger("http://" + localip, "info");
delay(2000);
} else {
socket.loop();
btntop.update();
btnbottom.update();
showVoltage();
if (btntop.isClick()) {
switch (currentScreen) {
case 0:
showSettings();
currentScreen = 1;
break;
case 1:
showDeviceInfo();
currentScreen = 0;
break;
}
}
if (btnbottom.isClick()) {
if (backlight == true) {
digitalWrite(TFT_BL, LOW);
backlight = false;
} else {
digitalWrite(TFT_BL, HIGH);
backlight = true;
}
}
}
}