-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
739 lines (629 loc) · 22.8 KB
/
Copy pathmain.cpp
File metadata and controls
739 lines (629 loc) · 22.8 KB
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
// /*
// M5Core2 OpenAI Demo (M5Unified + ArduinoJson)
// ----------------------------------------------
// • secrets.h contains ONLY Wi-Fi + (optional) Firebase — no OpenAI key.
// • OpenAI key comes from the host env and is injected at build time:
// build_flags = -D OPENAI_API_KEY="${sysenv.OPENAI_API_KEY}"
// • Optional proxy: set USE_OPENAI_PROXY=1 and PROXY_URL in platformio.ini
// Buttons:
// A → Haiku
// B → What is Core2?
// C → Motivation
// The reply is drawn on the Core2 screen in the loop.
// NOTE (TLS): This demo uses client.setInsecure() for simplicity. For production,
// validate the server certificate or call your own proxy with pinning.
// */
// #include <Arduino.h>
// #include <M5Unified.h>
// #include <WiFi.h>
// #include <WiFiClientSecure.h>
// #include <HTTPClient.h>
// #include <ArduinoJson.h>
// // -----------------------------------------------------------------------------
// // secrets.h must define ONLY Wi-Fi + (optional) Firebase values (no OpenAI key)
// // Example (choose one naming style):
// //
// // #pragma once
// // // Style A
// // #define WIFI_SSID "Your_SSID"
// // #define WIFI_PASS "Your_WiFi_Password"
// //
// // // Style B
// // // #define SECRET_SSID "Your_SSID"
// // // #define SECRET_PASS "Your_WiFi_Password"
// //
// // // Optional / unused here
// // // #define FIREBASE_API_KEY "your-firebase-api-key"
// // // #define FIREBASE_PROJECT_ID "your-firebase-project-id"
// // // #define FIREBASE_HOST "your-project.firebaseio.com"
// // -----------------------------------------------------------------------------
// #include "secrets.h"
// // Normalize Wi-Fi macro names: accept either WIFI_* or SECRET_* from secrets.h
// #if defined(WIFI_SSID) && !defined(SECRET_SSID)
// #define SECRET_SSID WIFI_SSID
// #endif
// #if defined(WIFI_PASS) && !defined(SECRET_PASS)
// #define SECRET_PASS WIFI_PASS
// #endif
// #if !defined(SECRET_SSID) || !defined(SECRET_PASS)
// #error "Please define WIFI_SSID/WIFI_PASS or SECRET_SSID/SECRET_PASS in secrets.h"
// #endif
// // ===== Configuration switches provided from platformio.ini =====
// #ifndef USE_OPENAI_PROXY
// #define USE_OPENAI_PROXY 0
// #endif
// #if USE_OPENAI_PROXY
// #ifndef PROXY_URL
// #define PROXY_URL "https://your-proxy.example.com/openai"
// #endif
// static const char* OPENAI_URL = PROXY_URL; // Your server forwards to OpenAI
// #else
// static const char* OPENAI_URL = "https://api.openai.com/v1/responses"; // Official Responses API
// #endif
// // Demo prompts
// static const char* PROMPT_A = "Write a 3-line haiku about streetwear and creativity.";
// static const char* PROMPT_B = "Explain what an M5Stack Core2 is in one short sentence.";
// static const char* PROMPT_C = "Give me a single motivational line for a maker working late night.";
// // ---------- UI helpers ----------
// static void drawHeader(){
// M5.Display.fillScreen(TFT_BLACK);
// M5.Display.setRotation(1);
// M5.Display.setTextDatum(TC_DATUM);
// M5.Display.setTextSize(2);
// M5.Display.setTextColor(TFT_WHITE, TFT_BLACK);
// M5.Display.drawString("M5Core2 • OpenAI API Demo", M5.Display.width()/2, 8);
// M5.Display.drawFastHLine(0, 28, M5.Display.width(), TFT_DARKGREY);
// }
// static void drawMenu(){
// M5.Display.setTextDatum(TL_DATUM);
// M5.Display.setTextSize(2);
// M5.Display.setTextColor(TFT_CYAN, TFT_BLACK);
// int y=40; M5.Display.drawString("A: Haiku", 10, y); y+=24;
// M5.Display.drawString("B: What is Core2?", 10, y); y+=24;
// M5.Display.drawString("C: Motivation", 10, y);
// }
// static void showStatus(const String& s){
// M5.Display.fillRect(0, 72, M5.Display.width(), 24, TFT_BLACK);
// M5.Display.setTextDatum(TC_DATUM);
// M5.Display.setTextSize(2);
// M5.Display.setTextColor(TFT_SILVER, TFT_BLACK);
// M5.Display.drawString(s, M5.Display.width()/2, 84);
// }
// static void drawWrappedText(const String& text){
// const int x=8, top=100, maxW=M5.Display.width()-16; int y=top;
// M5.Display.fillRect(0, top, M5.Display.width(), M5.Display.height()-top, TFT_BLACK);
// M5.Display.setTextDatum(TL_DATUM);
// M5.Display.setTextSize(2);
// M5.Display.setTextColor(TFT_YELLOW, TFT_BLACK);
// String line, word;
// for (size_t i=0; i<text.length(); ++i){
// char c = text[i];
// if (c=='\n' || c==' '){
// String tryLine = line + word + (c=='\n' ? "" : " ");
// if (M5.Display.textWidth(tryLine.c_str()) > maxW){
// M5.Display.drawString(line.c_str(), x, y); y+=22; line = word + (c=='\n' ? "" : " "); word="";
// } else { line = tryLine; word=""; }
// if (c=='\n'){ M5.Display.drawString(line.c_str(), x, y); y+=22; line=""; }
// } else { word += c; }
// }
// if (word.length()) line += word;
// if (line.length()) M5.Display.drawString(line.c_str(), x, y);
// }
// // ---------- Wi-Fi ----------
// static void connectWiFi(){
// if (WiFi.status() == WL_CONNECTED) return;
// WiFi.mode(WIFI_STA);
// WiFi.setSleep(false); // keep radio awake to prevent stalls
// WiFi.begin(SECRET_SSID, SECRET_PASS);
// showStatus("Connecting WiFi...");
// uint32_t t0 = millis();
// while (WiFi.status() != WL_CONNECTED && millis()-t0 < 20000) delay(200);
// showStatus(WiFi.status()==WL_CONNECTED ? "WiFi connected" : "WiFi failed");
// }
// // ---------- OpenAI call (Responses API) ----------
// static String callOpenAI(const String& prompt){
// WiFiClientSecure client;
// client.setInsecure(); // DEMO ONLY (use proper validation in prod)
// client.setTimeout(30000); // TLS socket read timeout (ms)
// HTTPClient https;
// https.setConnectTimeout(15000); // TCP connect timeout (ms)
// https.setTimeout(45000); // HTTP read timeout (ms)
// https.setReuse(false); // avoid keep-alive on ESP32
// if (!https.begin(client, OPENAI_URL)) return F("[begin failed]");
// https.addHeader("Content-Type", "application/json");
// https.addHeader("Accept", "application/json");
// https.addHeader("Connection", "close"); // server closes after response
// #if !USE_OPENAI_PROXY
// // Add Authorization header ONLY when calling api.openai.com directly
// #ifdef OPENAI_API_KEY
// if (String(OPENAI_API_KEY).length() > 0) {
// https.addHeader("Authorization", String("Bearer ") + OPENAI_API_KEY);
// } else {
// https.end();
// return F("[No OPENAI_API_KEY set — set env var or use proxy]");
// }
// #else
// https.end();
// return F("[OPENAI_API_KEY macro missing — set via build_flags]");
// #endif
// #endif
// // Prefer modern ArduinoJson style
// JsonDocument doc; // dynamic; fine on ESP32
// doc["model"] = "gpt-4o-mini";
// doc["input"] = prompt; // Responses API allows string input
// doc["max_output_tokens"] = 120;
// doc["temperature"] = 0.7;
// String body; serializeJson(doc, body);
// int code = https.POST(body);
// if (code <= 0){
// String err = https.errorToString(code);
// https.end();
// return String("[HTTP] ") + err; // e.g., "[HTTP] read timeout"
// }
// String payload = https.getString();
// https.end();
// JsonDocument res;
// auto e = deserializeJson(res, payload);
// if (e) return String("[JSON parse] ") + e.c_str() + "\n" + payload;
// // --- Responses API proper parse: output[].content[].text ---
// if (res["output"].is<JsonArray>()){
// String collected;
// JsonArray out = res["output"].as<JsonArray>();
// for (JsonObject item : out){
// if (item["content"].is<JsonArray>()){
// JsonArray cont = item["content"].as<JsonArray>();
// for (JsonObject chunk : cont){
// if (chunk["text"].is<const char*>()){
// if (collected.length()) collected += "\n";
// collected += (const char*)chunk["text"];
// }
// }
// }
// }
// if (collected.length()) return collected;
// }
// // Fallback: single field if server provided it
// if (res["output_text"].is<const char*>()) return (const char*)res["output_text"];
// // Fallback: Chat Completions style
// if (res["choices"].is<JsonArray>()){
// JsonArray ch = res["choices"].as<JsonArray>();
// if (!ch.isNull() && ch.size()>0){
// if (ch[0]["message"]["content"].is<const char*>()) return (const char*)ch[0]["message"]["content"];
// if (ch[0]["text"].is<const char*>()) return (const char*)ch[0]["text"];
// }
// }
// return payload; // last resort show raw
// }
// void setup(){
// auto cfg = M5.config();
// M5.begin(cfg);
// Serial.begin(115200);
// drawHeader();
// drawMenu();
// connectWiFi();
// // --- Optional: quick TLS/API-key test (prints to Serial Monitor) ---
// if (WiFi.status()==WL_CONNECTED){
// WiFiClientSecure c;
// c.setInsecure();
// HTTPClient h;
// h.setTimeout(8000);
// h.setConnectTimeout(8000);
// h.setReuse(false);
// if (h.begin(c, "https://api.openai.com/v1/models")) {
// #ifdef OPENAI_API_KEY
// h.addHeader("Authorization", String("Bearer ") + OPENAI_API_KEY);
// #endif
// int rc = h.GET();
// Serial.printf("models GET rc=%d\n", rc);
// String s = h.getString();
// Serial.println(s.substring(0, min(200, (int)s.length()))); // first 200 chars
// h.end();
// }
// }
// // --- Initial demo call to show text immediately ---
// if (WiFi.status()==WL_CONNECTED){
// showStatus("Querying OpenAI...");
// String out = callOpenAI("Say hello from an ESP32 M5Core2.");
// drawWrappedText(out);
// }
// }
// void loop(){
// M5.update();
// const char* prompt = nullptr;
// if (M5.BtnA.wasPressed()) prompt = PROMPT_A;
// if (M5.BtnB.wasPressed()) prompt = PROMPT_B;
// if (M5.BtnC.wasPressed()) prompt = PROMPT_C;
// if (prompt){
// showStatus("Querying OpenAI...");
// String out = callOpenAI(prompt);
// drawWrappedText(out);
// }
// delay(5);
// }
// /*
// cURL (no proxy) — run this on your COMPUTER to test the same request:
// export OPENAI_API_KEY="sk-..." # set your key in the shell (do NOT hardcode)
// curl https://api.openai.com/v1/responses \
// -H "Content-Type: application/json" \
// -H "Authorization: Bearer $OPENAI_API_KEY" \
// -d '{
// "model": "gpt-4o-mini",
// "input": "write a haiku about ai",
// "max_output_tokens": 120,
// "temperature": 0.7
// }'
// */
/*
M5Core2 OpenAI Demo (M5Core2 + ArduinoJson)
-------------------------------------------
Buttons:
A → Haiku
B → What is Core2?
C → Motivation
The reply is drawn on the Core2 screen in the loop.
NOTE (TLS): This demo uses client.setInsecure() for simplicity. For production,
validate the server certificate or call your own proxy with pinning.
*/
//version 2
#include <Arduino.h>
#include <M5Core2.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <TinyGPSPlus.h>
#include "secrets.h"
//ai assited
// GPS on UART2 (Port C): RX=13, TX=14
static const int GPS_RX = 13; // Core2 Port C RX
static const int GPS_TX = 14; // Core2 Port C TX
HardwareSerial GPSSerial(2);
TinyGPSPlus gps;
static bool hasFix = false;
static double curLat = 0.0, curLon = 0.0;
// OpenAI endpoint
static const char* OPENAI_URL = "https://api.openai.com/v1/responses";
/* ------------ Demo prompts ------------- */
// static const char* PROMPT_A = "Write a 3-line haiku about streetwear and creativity.";
// static const char* PROMPT_B = "Explain what an M5Stack Core2 is in one short sentence.";
// static const char* PROMPT_C = "Give me a single motivational line for a maker working late night.";
// Layout constants
static const int HEADER_H = 28;
static const int STATUS_Y = 40;
static const int STATUS_H = 24;
static const int FOOTER_H = 28;
static const int CONTENT_TOP = STATUS_Y + STATUS_H + 4; // content starts below status
static const int CONTENT_H = 240;
static const int SIDE_PAD = 8; // left/right padding for content
//ai assited
// Text metrics
static const int LINE_H = 22; // line height for Size=2
static inline int CONTENT_W() { return M5.Lcd.width() - 2*SIDE_PAD; }
static inline int CONTENT_BOTTOM() { return M5.Lcd.height() - FOOTER_H; }
//ai assited
// Scrolling state
static std::vector<String> responseLines; // wrapped lines
static int scrollY = 0; // pixel offset from top of content (>=0)
static int maxScroll = 0; // max scroll (>=0) computed after wrapping
//ai assited
// Touch scroll state
static bool dragging = false;
static int lastTouchY = 0;
// UI Setup
static void drawHeader() {
M5.Lcd.fillScreen(BLACK);
M5.Lcd.setRotation(1);
M5.Lcd.setTextSize(2);
M5.Lcd.setTextColor(WHITE, BLACK);
M5.Lcd.setCursor(95,0);
M5.Lcd.print("Ask ChatGPT");
M5.Lcd.drawFastHLine(0, HEADER_H, M5.Lcd.width(), DARKGREY);
}
static void showStatus(const String &s) {
M5.Lcd.fillRect(0, STATUS_Y, M5.Lcd.width(), STATUS_H, BLACK);
if (s.length() == 0) return;
M5.Lcd.setTextDatum(TC_DATUM);
M5.Lcd.setTextSize(2);
M5.Lcd.setTextColor(WHITE, BLACK);
M5.Lcd.drawString(s, M5.Lcd.width()/2, STATUS_Y + STATUS_H/2 - 8);
}
static void drawFooter() {
int y = M5.Lcd.height() - FOOTER_H;
M5.Lcd.fillRect(0, y, M5.Lcd.width(), FOOTER_H, DARKGREY);
M5.Lcd.setTextSize(2);
M5.Lcd.setTextColor(CYAN, DARKGREY);
M5.Lcd.setCursor(10,220);
M5.Lcd.print("A: Food");
M5.Lcd.setCursor(110,220);
M5.Lcd.print("B: News");
M5.Lcd.setCursor(210,220);
M5.Lcd.print("C: Events");
}
//ai assited
static void clearContent() {
// Clear ONLY the scrollable content box; leave header/status/footer intact.
int h = (M5.Lcd.height() - FOOTER_H) - CONTENT_TOP;
if (h < 0) h = 0;
M5.Lcd.fillRect(0, CONTENT_TOP, M5.Lcd.width(), h, BLACK);
}
static void drawWrappedText(const String &text) {
clearContent();
M5.Lcd.setTextDatum(TL_DATUM);
M5.Lcd.setTextSize(2);
M5.Lcd.setTextColor(YELLOW, BLACK);
const int x = 8;
const int maxW = M5.Lcd.width() - 16;
const int lineH = 22;
int y = CONTENT_TOP;
String line, word;
auto flushLine = [&](){
if (line.length()) {
M5.Lcd.drawString(line.c_str(), x, y);
y += lineH;
line = "";
}
};
for (size_t i = 0; i < text.length(); ++i) {
char c = text[i];
if (c == '\n' || c == ' ') {
String tryLine = line + word + (c == '\n' ? "" : " ");
if (M5.Lcd.textWidth(tryLine.c_str()) > maxW) {
if (line.length()) flushLine();
line = word + (c == '\n' ? "" : " ");
} else {
line = tryLine;
}
word = "";
if (c == '\n') flushLine();
if (y + lineH > M5.Lcd.height() - FOOTER_H) return; // stop if overlaps footer
} else {
word += c;
}
}
if (word.length()) line += word;
if (line.length()) M5.Lcd.drawString(line.c_str(), x, y);
}
//ai assited
//Wrapping + Scrolling Draw
// Wrap a raw string into fixed-width lines we can scroll
static void cacheWrappedText(const String &text) {
responseLines.clear();
M5.Lcd.setTextDatum(TL_DATUM);
M5.Lcd.setTextSize(2);
const int maxW = CONTENT_W();
String line, word;
auto pushLine = [&](const String& s) {
responseLines.push_back(s.length() ? s : String(" "));
};
for (size_t i = 0; i < text.length(); ++i) {
char c = text[i];
if (c == '\n' || c == ' ') {
String tryLine = line + word + (c == '\n' ? "" : " ");
if (M5.Lcd.textWidth(tryLine.c_str()) > maxW) {
pushLine(line);
line = word + (c == '\n' ? "" : " ");
} else {
line = tryLine;
}
word = "";
if (c == '\n') { pushLine(line); line = ""; }
} else {
word += c;
}
}
if (word.length()) line += word;
if (line.length()) responseLines.push_back(line);
//ai assited
// Compute scroll bounds
int contentH = CONTENT_BOTTOM() - CONTENT_TOP;
int totalH = (int)responseLines.size() * LINE_H;
scrollY = 0;
maxScroll = totalH > contentH ? (totalH - contentH) : 0;
}
//ai assited
// Draw visible slice using current scrollY
static void drawScrolledContent() {
clearContent();
M5.Lcd.setTextDatum(TL_DATUM);
M5.Lcd.setTextSize(2);
M5.Lcd.setTextColor(YELLOW, BLACK);
const int contentTop = CONTENT_TOP;
const int contentBottom = M5.Lcd.height() - FOOTER_H;
const int x = 8; // SIDE_PAD
// figure out which line to start drawing and the pixel offset
int firstLineIdx = scrollY / LINE_H;
int yOffset = -(scrollY % LINE_H);
int y = contentTop + yOffset;
for (int i = firstLineIdx; i < (int)responseLines.size(); ++i) {
if (y > contentBottom) break; // don't draw into the footer
if (y + LINE_H >= contentTop) {
M5.Lcd.drawString(responseLines[i], x, y);
}
y += LINE_H;
}
// repaint the footer last so it stays visible on scroll
drawFooter();
}
//ai assited
// Touch Scrolling
static bool pointInContent(int16_t x, int16_t y) {
return (x >= 0 && x < M5.Lcd.width() && y >= CONTENT_TOP && y < CONTENT_BOTTOM());
}
static void handleTouchScroll() {
if (M5.Touch.ispressed()) {
auto p = M5.Touch.getPressPoint();
if (!dragging) {
if (pointInContent(p.x, p.y)) {
dragging = true;
lastTouchY = p.y;
}
} else {
int dy = p.y - lastTouchY;
lastTouchY = p.y;
// natural feel: finger up -> content moves up -> scrollY increases
scrollY = scrollY - dy;
if (scrollY < 0) scrollY = 0;
if (scrollY > maxScroll) scrollY = maxScroll;
drawScrolledContent();
}
} else {
dragging = false;
}
}
// Wi-Fi
static void connectWiFi() {
if (WiFi.status() == WL_CONNECTED) return;
WiFi.mode(WIFI_STA);
WiFi.setSleep(false);
WiFi.begin(SECRET_SSID, SECRET_PASS);
showStatus("Connecting WiFi...");
uint32_t t0 = millis();
while (WiFi.status() != WL_CONNECTED && millis() - t0 < 20000) delay(200);
showStatus(WiFi.status() == WL_CONNECTED ? "WiFi connected" : "WiFi failed");
}
//ai assited
//OpenAI call
static String callOpenAI(const String &prompt) {
WiFiClientSecure client;
client.setInsecure();
client.setTimeout(30000);
HTTPClient https;
https.setConnectTimeout(15000);
https.setTimeout(45000);
https.setReuse(false);
if (!https.begin(client, OPENAI_URL)) return F("[begin failed]");
https.addHeader("Content-Type", "application/json");
https.addHeader("Accept", "application/json");
https.addHeader("Connection", "close");
#ifdef OPENAI_API_KEY
https.addHeader("Authorization", String("Bearer ") + OPENAI_API_KEY);
#else
https.end();
return F("[OPENAI_API_KEY macro missing]");
#endif
JsonDocument doc;
doc["model"] = "gpt-4o-mini";
doc["input"] = prompt;
doc["max_output_tokens"] = 300;
doc["temperature"] = 0.3;
String body; serializeJson(doc, body);
int code = https.POST(body);
if (code <= 0) {
String err = https.errorToString(code);
https.end();
return String("[HTTP] ") + err;
}
String payload = https.getString();
https.end();
JsonDocument res;
if (deserializeJson(res, payload)) return payload;
if (res["output"].is<JsonArray>()) {
String collected;
for (JsonObject item : res["output"].as<JsonArray>()) {
for (JsonObject chunk : item["content"].as<JsonArray>()) {
if (chunk["text"].is<const char*>()) {
if (collected.length()) collected += "\n";
collected += (const char*)chunk["text"];
}
}
}
if (collected.length()) return collected;
}
if (res["output_text"].is<const char*>()) return (const char*)res["output_text"];
if (res["choices"].is<JsonArray>()) {
auto ch = res["choices"].as<JsonArray>();
if (ch.size() > 0) {
if (ch[0]["message"]["content"].is<const char*>()) return (const char*)ch[0]["message"]["content"];
if (ch[0]["text"].is<const char*>()) return (const char*)ch[0]["text"];
}
}
return payload;
}
//ai assited
// Location formatting
static String locationSummary() {
if (hasFix) {
// e.g., "lat:33.45, lon:-112.07 (±5mi)"
String s = "lat:" + String(curLat, 5) + ", lon:" + String(curLon, 5);
return s;
}
// Manual fallback
#ifdef FALLBACK_CITY
String s = String(FALLBACK_CITY);
#ifdef FALLBACK_REGION
s += String(", ") + FALLBACK_REGION;
#endif
#ifdef FALLBACK_COUNTRY
s += String(", ") + FALLBACK_COUNTRY;
#endif
return s;
#else
return "my area"; // ultimate fallback
#endif
}
// Dynamic prompts using location
static String buildPromptA() { // Food within 5 miles, Yelp-style best
String loc = locationSummary();
// NOTE: This relies on model knowledge, not Yelp API.
return "You are a local guide. Using recent, reliable knowledge, Search the Web and list the top 3 food spots within ~5 miles of "
+ loc +
" that consistently have the best Yelp reviews. Give a short bullet for each: name — cuisine — why it's top-rated. If unsure, say so.";
}
static String buildPromptB() { // State news in one sentence
String loc = locationSummary();
return "Search the Web and Summarize the most important current news in the State of " + loc +
" in exactly one concise sentence. If location is coordinates, infer the country. If uncertain, note the uncertainty.";
}
static String buildPromptC() { // Top 3 events this weekend
String loc = locationSummary();
return "Search the Web for a List the top 3 notable events happening this weekend near " + loc +
". Provide a brief bullet list: event — date — venue — why it's notable. If not confident, suggest how to verify.";
}
//ai assited
// GPS feed
static void pollGPS() {
while (GPSSerial.available()) {
char c = GPSSerial.read();
gps.encode(c);
}
if (gps.location.isUpdated() && gps.location.isValid()) {
curLat = gps.location.lat();
curLon = gps.location.lng();
hasFix = gps.hdop.isValid() ? (gps.hdop.hdop() < 6.0) : true; // crude quality gate
}
}
// Arduino setup/loop
void setup() {
M5.begin();
Serial.begin(115200);
//ai assited
// GPS serial
GPSSerial.begin(9600, SERIAL_8N1, GPS_RX, GPS_TX);
drawHeader();
showStatus("");
drawFooter();
connectWiFi();
}
void loop() {
M5.update();
// Smooth touch scrolling when a response is displayed
handleTouchScroll();
const char *which = nullptr;
if (M5.BtnA.wasPressed()) which = "A";
if (M5.BtnB.wasPressed()) which = "B";
if (M5.BtnC.wasPressed()) which = "C";
if (which) {
String prompt;
if (*which == 'A') prompt = buildPromptA();
else if (*which == 'B') prompt = buildPromptB();
else prompt = buildPromptC();
showStatus("Asking OpenAI...");
String out = callOpenAI(prompt);
showStatus("");
//ai assited
cacheWrappedText(out); // wrap into lines buffer for scrolling
scrollY = 0; // start at the top
drawScrolledContent(); // draw once using the scroller
}
delay(10);
}