2026年2月14日 星期六

[OTTO GO] MQTT再測試-ACK 回覆、I2S 切換保護、統一 Topic + info 上線宣告

 


OTTO GO 的控制 Topic

  • 送指令(Publish 到這個)
    otto_go/OTTO_GO_A1/4A65B7A0/cmd

  • 看即時狀態(Subscribe 這個)
    otto_go/OTTO_GO_A1/4A65B7A0/status

  • 看指令回覆 ACK(Subscribe 這個)
    otto_go/OTTO_GO_A1/4A65B7A0/ack

  • 看上線資訊(Subscribe 這個,retain)
    otto_go/OTTO_GO_A1/4A65B7A0/info

MQTTX 快速測試(直接複製貼上 payload)

把下面每一行都「發到 cmd topic」:

喇叭

  • spk=beep

  • spk=roar

虎嘴

  • mouth=open

  • mouth=close

TFT

  • tft=hello

  • tft=clear

伺服

  • servo=all,90

  • servo=1,120

  • servo=2,60

  • servo=3,90

  • servo=4,150

改狀態回報頻率

  • status_period=2000 (2 秒一次)

  • status_period=1000 (1 秒一次)



arduino:


  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
#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7789.h>
#include <ESP32Servo.h>
#include "driver/i2s.h"
#include "freertos/semphr.h"

// ===================== 你要改的設定 =====================
const char* WIFI_SSID = "您的SSID";
const char* WIFI_PASS = "您的密碼";

const char* MQTT_HOST = "mqttgo.io";
const uint16_t MQTT_PORT = 1883;

// 建議:現場貼標籤用(同一場域多台最好不一樣)
const char* DEVICE_NAME = "OTTO_GO_A1";

// base topic = otto_go/<DEVICE_NAME>/<chipid>
static String TOPIC_BASE;

// publish / subscribe topic
static String T_INFO, T_STATUS, T_ACK, T_CMD;

// status publish 週期(ms)
static uint32_t STATUS_PERIOD_MS = 2000;

// ===================== Pin map (OTTO GO) =====================
// TFT (SPI)
#define TFT_MOSI 19
#define TFT_SCLK 18
#define TFT_CS    5
#define TFT_DC   16
#define TFT_RST  23

// Ultrasonic
#define US_TRIG 27
#define US_ECHO 39

// Servos
#define SERVO1 21
#define SERVO2 22
#define SERVO3 4
#define SERVO4 14

// Speaker (I2S -> AMP -> SPK white socket)
#define SPK_I2S_LRCK 17
#define SPK_I2S_BCLK 2
#define SPK_I2S_DOUT 32

// Microphone (I2S MEMS)
#define MIC_I2S_SCK 13
#define MIC_I2S_SD  12
#define MIC_I2S_WS  15

// ===================== Objects =====================
WiFiClient wifiClient;
PubSubClient mqtt(wifiClient);

Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);
Servo s1, s2, s3, s4;

// ===================== Helpers =====================
static inline uint16_t RGB565(uint8_t r, uint8_t g, uint8_t b) {
  return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
}

// ===================== Ultrasonic =====================
long readDistanceCM_once() {
  digitalWrite(US_TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(US_TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(US_TRIG, LOW);

  unsigned long duration = pulseIn(US_ECHO, HIGH, 30000UL);
  if (duration == 0) return -1;
  return (long)(duration / 58UL);
}
long median3(long a, long b, long c) {
  if (a > b) { long t=a; a=b; b=t; }
  if (b > c) { long t=b; b=c; c=t; }
  if (a > b) { long t=a; a=b; b=t; }
  return b;
}
long readDistanceCM_median3() {
  long d1 = readDistanceCM_once();
  long d2 = readDistanceCM_once();
  long d3 = readDistanceCM_once();
  long d  = median3(d1, d2, d3);
  return d;
}

// ===================== TFT =====================
void tftHello() {
  tft.fillScreen(ST77XX_BLACK);
  tft.setTextColor(ST77XX_WHITE);
  tft.setTextSize(3);
  tft.setCursor(20, 40);
  tft.print("Hello");
}

static bool mouthOpen = false;

void drawTigerMouth(bool open) {
  mouthOpen = open;

  int cx = tft.width()/2;
  int cy = tft.height()/2;

  uint16_t furLight = RGB565(235, 228, 210);
  uint16_t shadow   = RGB565(160, 150, 135);
  uint16_t lineDark = RGB565(40, 40, 40);
  uint16_t dotDark  = RGB565(70, 70, 70);

  tft.fillScreen(ST77XX_BLACK);

  tft.fillCircle(cx - 55, cy + 10, 55, furLight);
  tft.fillCircle(cx + 55, cy + 10, 55, furLight);
  tft.fillRoundRect(cx - 90, cy - 25, 180, 110, 28, furLight);

  tft.fillRoundRect(cx - 85, cy + 60, 170, 22, 12, shadow);
  tft.fillRoundRect(cx - 40, cy + 55, 80, 10, 5, RGB565(120,110,100));

  int dotY1 = cy + 6, dotY2 = cy + 26;
  for (int k=0;k<3;k++){
    tft.fillCircle(cx - 55 - k*12, dotY1 + k*2, 2, dotDark);
    tft.fillCircle(cx - 55 - k*12, dotY2 + k*2, 2, dotDark);
    tft.fillCircle(cx + 55 + k*12, dotY1 + k*2, 2, dotDark);
    tft.fillCircle(cx + 55 + k*12, dotY2 + k*2, 2, dotDark);
  }

  tft.drawLine(cx, cy - 5, cx, open ? (cy + 10) : (cy + 20), lineDark);
  tft.drawLine(cx-1, cy - 5, cx-1, open ? (cy + 10) : (cy + 20), RGB565(80,80,80));

  int mouthY = open ? (cy + 16) : (cy + 18);
  int N = open ? 36 : 34;
  int div = open ? 85 : 95;
  for (int i=0;i<N;i++){
    int y = mouthY + (i*i)/div;
    tft.drawPixel(cx-i, y, lineDark);
    tft.drawPixel(cx-i, y+1, lineDark);
    tft.drawPixel(cx+i, y, lineDark);
    tft.drawPixel(cx+i, y+1, lineDark);
  }

  tft.fillCircle(cx - (open?38:36), mouthY + (open?14:12), 3, lineDark);
  tft.fillCircle(cx + (open?38:36), mouthY + (open?14:12), 3, lineDark);

  if (!open) {
    tft.fillRoundRect(cx - 10, mouthY + 20, 20, 4, 2, RGB565(90,80,70));
  } else {
    uint16_t mouthIn = RGB565(15,15,15);
    uint16_t tongue  = RGB565(210,120,120);
    int w=90, h=45;
    int x=cx-w/2, y0=cy+28;
    tft.fillRoundRect(x, y0, w, h, 18, mouthIn);
    tft.fillCircle(cx, y0+h, 22, mouthIn);
    tft.fillRoundRect(cx-22, y0+18, 44, 20, 10, tongue);
    tft.fillCircle(cx, y0+36, 14, tongue);
  }

  tft.setTextSize(2);
  tft.setTextColor(ST77XX_YELLOW, ST77XX_BLACK);
  tft.setCursor(10, 10);
  tft.print(open ? "MOUTH: OPEN" : "MOUTH: CLOSE");
}

// ===================== I2S0 mode switching(穩定版 + 保護) =====================
const i2s_port_t I2S_PORT = I2S_NUM_0;

enum I2SMode { MODE_NONE=0, MODE_SPK=1, MODE_MIC=2 };
static volatile I2SMode curMode = MODE_NONE;

static SemaphoreHandle_t i2sMutex = nullptr;

// 狀態顯示
static bool spk_ok = false;
static bool mic_ok = false;

// 切換保護(避免太頻繁卸載/安裝造成崩潰)
static uint32_t lastSwitchMs = 0;
static const uint32_t MIN_SWITCH_GAP_MS = 250;

static void lockI2S()   { if (i2sMutex) xSemaphoreTake(i2sMutex, portMAX_DELAY); }
static void unlockI2S() { if (i2sMutex) xSemaphoreGive(i2sMutex); }

static void i2sStopAndUninstallSafe() {
  if (curMode == MODE_NONE) return;
  i2s_stop(I2S_PORT);
  i2s_driver_uninstall(I2S_PORT);
  curMode = MODE_NONE;
}

static bool i2sInitSpeaker_locked() {
  i2sStopAndUninstallSafe();

  i2s_config_t cfg = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX),
    .sample_rate = 22050,
    .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
    .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
    .communication_format = I2S_COMM_FORMAT_I2S_MSB,
    .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
    .dma_buf_count = 4,
    .dma_buf_len   = 128,
    .use_apll = false,
    .tx_desc_auto_clear = true,
    .fixed_mclk = 0
  };

  i2s_pin_config_t pin_cfg = {
    .bck_io_num = SPK_I2S_BCLK,
    .ws_io_num  = SPK_I2S_LRCK,
    .data_out_num = SPK_I2S_DOUT,
    .data_in_num  = I2S_PIN_NO_CHANGE
  };

  esp_err_t e1 = i2s_driver_install(I2S_PORT, &cfg, 0, NULL);
  if (e1 != ESP_OK) return false;

  esp_err_t e2 = i2s_set_pin(I2S_PORT, &pin_cfg);
  if (e2 != ESP_OK) return false;

  i2s_zero_dma_buffer(I2S_PORT);
  i2s_start(I2S_PORT);
  curMode = MODE_SPK;
  lastSwitchMs = millis();
  return true;
}

static bool i2sInitMic_locked() {
  i2sStopAndUninstallSafe();

  i2s_config_t cfg = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),
    .sample_rate = 16000,
    .bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT,
    .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
    .communication_format = I2S_COMM_FORMAT_I2S_MSB,
    .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
    .dma_buf_count = 4,
    .dma_buf_len   = 128,
    .use_apll = false,
    .tx_desc_auto_clear = false,
    .fixed_mclk = 0
  };

  i2s_pin_config_t pin_cfg = {
    .bck_io_num = MIC_I2S_SCK,
    .ws_io_num  = MIC_I2S_WS,
    .data_out_num = I2S_PIN_NO_CHANGE,
    .data_in_num  = MIC_I2S_SD
  };

  esp_err_t e1 = i2s_driver_install(I2S_PORT, &cfg, 0, NULL);
  if (e1 != ESP_OK) return false;

  esp_err_t e2 = i2s_set_pin(I2S_PORT, &pin_cfg);
  if (e2 != ESP_OK) return false;

  i2s_zero_dma_buffer(I2S_PORT);
  i2s_start(I2S_PORT);
  curMode = MODE_MIC;
  lastSwitchMs = millis();
  return true;
}

static bool ensureSpeakerMode_locked() {
  if (curMode == MODE_SPK) return true;
  if (millis() - lastSwitchMs < MIN_SWITCH_GAP_MS) delay(MIN_SWITCH_GAP_MS);
  spk_ok = i2sInitSpeaker_locked();
  return spk_ok;
}

static bool ensureMicMode_locked() {
  if (curMode == MODE_MIC) return true;
  if (millis() - lastSwitchMs < MIN_SWITCH_GAP_MS) delay(MIN_SWITCH_GAP_MS);
  mic_ok = i2sInitMic_locked();
  return mic_ok;
}

// ===================== Speaker sound =====================
static uint32_t rng = 1;
static inline int16_t noise16() {
  rng = rng * 1664525UL + 1013904223UL;
  return (int16_t)(rng >> 16);
}

static void playBeep1kHz_200ms_locked() {
  if (!ensureSpeakerMode_locked()) return;

  const int sampleRate = 22050;
  const float freq = 1000.0f;
  const float durSec = 0.2f;
  const int total = (int)(sampleRate * durSec);

  const int N = 256;
  int16_t stereo[N * 2];
  float phase = 0.0f;

  for (int i=0;i<total;){
    int n = (total-i > N) ? N : (total-i);
    for (int k=0;k<n;k++){
      phase += 2.0f * 3.1415926f * freq / (float)sampleRate;
      if (phase > 2.0f*3.1415926f) phase -= 2.0f*3.1415926f;

      int16_t v = (int16_t)(sinf(phase) * 12000);
      stereo[2*k+0] = v;
      stereo[2*k+1] = v;
    }
    size_t written=0;
    i2s_write(I2S_PORT, (const char*)stereo, n*2*sizeof(int16_t), &written, portMAX_DELAY);
    i += n;
  }
}

static void playRoarOnce_locked() {
  if (!ensureSpeakerMode_locked()) return;

  const int sampleRate = 22050;
  const float durSec = 0.6f;
  const int total = (int)(sampleRate * durSec);

  const int N = 256;
  int16_t stereo[N * 2];
  float phase = 0.0f;

  for (int i=0;i<total;){
    int n = (total-i > N) ? N : (total-i);

    for (int k=0;k<n;k++){
      float t = (float)(i+k)/(float)total;
      float f = 120.0f - 50.0f*t;
      phase += 2.0f * 3.1415926f * f / (float)sampleRate;
      if (phase > 2.0f*3.1415926f) phase -= 2.0f*3.1415926f;

      float env = (t < 0.08f) ? (t/0.08f) : (1.0f - (t-0.08f)/0.92f);
      if (env < 0) env = 0;

      float s  = sinf(phase)*0.65f + sinf(phase*0.5f)*0.35f;
      float nz = (noise16()/32768.0f)*0.35f;
      float out = (s + nz) * env;

      float gain = 0.85f;
      int32_t v = (int32_t)(out * gain * 30000.0f);
      if (v > 32767) v = 32767;
      if (v < -32768) v = -32768;

      int16_t vv = (int16_t)v;
      stereo[2*k+0] = vv;
      stereo[2*k+1] = vv;
    }

    size_t written=0;
    i2s_write(I2S_PORT, (const char*)stereo, n*2*sizeof(int16_t), &written, portMAX_DELAY);
    i += n;
  }
}

// ===================== Microphone energy =====================
static const int MIC_FRAME = 128;
static int32_t micBuf[MIC_FRAME];

static float readMicEnergyOnce_locked() {
  if (!ensureMicMode_locked()) return 0;

  size_t bytesRead = 0;
  i2s_read(I2S_PORT, (void*)micBuf, sizeof(micBuf), &bytesRead, 20 / portTICK_PERIOD_MS);
  int n = bytesRead / 4;
  if (n <= 0) return 0;

  uint64_t sumAbs = 0;
  for (int i=0;i<n;i++){
    int16_t s16 = (int16_t)(micBuf[i] >> 16);
    sumAbs += (uint16_t)abs(s16);
  }
  return (float)sumAbs / (float)n;
}

// ===================== ACK / status =====================
static String lastAck = "BOOT";
static uint32_t lastAckMs = 0;

static void publishAck(const String& cmd, bool ok, const String& extra="") {
  lastAckMs = millis();
  lastAck = String(ok ? "OK " : "FAIL ") + cmd;
  if (extra.length()) lastAck += " " + extra;

  // ack topic(即時回覆)
  if (mqtt.connected()) {
    String payload = "{\"ts\":" + String(lastAckMs) +
                     ",\"ok\":" + String(ok ? 1 : 0) +
                     ",\"ack\":\"" + lastAck + "\"}";
    mqtt.publish(T_ACK.c_str(), payload.c_str(), false);
  }
}

// ===================== Servo state =====================
static int sAng[4] = {90,90,90,90};

static void servoWriteAll(int a) {
  a = constrain(a, 0, 180);
  sAng[0]=sAng[1]=sAng[2]=sAng[3]=a;
  s1.write(a); s2.write(a); s3.write(a); s4.write(a);
}

static void servoWriteCh(int ch, int a) {
  a = constrain(a, 0, 180);
  if (ch<1 || ch>4) return;
  sAng[ch-1]=a;
  switch(ch){
    case 1: s1.write(a); break;
    case 2: s2.write(a); break;
    case 3: s3.write(a); break;
    case 4: s4.write(a); break;
  }
}

// ===================== MQTT 指令格式(不依賴 ArduinoJson) =====================
//
// 你用 MQTTX / Node-RED 都好發:
//
// 1) 喇叭: "spk=beep" 或 "spk=roar"
// 2) TFT:  "tft=hello" / "tft=clear"
// 3) 虎嘴: "mouth=open" / "mouth=close"
// 4) 伺服: "servo=all,90" 或 "servo=1,120"
// 5) 超音波: "ultra=read"  (會立即 publish 一次 status)
// 6) 設定: "status_period=2000"
//
// topic: otto_go/<DEVICE_NAME>/<chipid>/cmd
//
static bool startsWith(const String& s, const char* p) {
  return s.startsWith(p);
}

static void handleCommandLine(String msg) {
  msg.trim();
  if (!msg.length()) return;

  bool ok = true;
  String extra = "";

  if (startsWith(msg, "spk=")) {
    String v = msg.substring(4); v.trim();
    lockI2S();
    if (v == "beep") playBeep1kHz_200ms_locked();
    else if (v == "roar") playRoarOnce_locked();
    else ok = false;
    unlockI2S();
  }
  else if (startsWith(msg, "tft=")) {
    String v = msg.substring(4); v.trim();
    if (v == "hello") tftHello();
    else if (v == "clear") tft.fillScreen(ST77XX_BLACK);
    else ok = false;
  }
  else if (startsWith(msg, "mouth=")) {
    String v = msg.substring(6); v.trim();
    if (v == "open") drawTigerMouth(true);
    else if (v == "close") drawTigerMouth(false);
    else ok = false;
  }
  else if (startsWith(msg, "servo=")) {
    // servo=all,90 or servo=2,120
    String v = msg.substring(6); v.trim();
    int comma = v.indexOf(',');
    if (comma < 0) ok = false;
    else {
      String a = v.substring(0, comma); a.trim();
      String b = v.substring(comma+1); b.trim();
      int ang = b.toInt();
      if (a == "all") servoWriteAll(ang);
      else {
        int ch = a.toInt();
        if (ch < 1 || ch > 4) ok = false;
        else servoWriteCh(ch, ang);
      }
    }
  }
  else if (startsWith(msg, "status_period=")) {
    String v = msg.substring(strlen("status_period=")); v.trim();
    uint32_t p = (uint32_t)v.toInt();
    if (p < 500) p = 500;
    if (p > 10000) p = 10000;
    STATUS_PERIOD_MS = p;
    extra = "period=" + String(STATUS_PERIOD_MS);
  }
  else if (startsWith(msg, "ultra=read")) {
    // 立即 publish 一次 status(loop 會自然發,這裡只做 ack)
  }
  else {
    ok = false;
  }

  publishAck(msg, ok, extra);
}

// ===================== MQTT callback =====================
static void mqttCallback(char* topic, byte* payload, unsigned int length) {
  String t = String(topic);
  String msg;
  msg.reserve(length+1);
  for (unsigned int i=0;i<length;i++) msg += (char)payload[i];

  // 只處理 cmd topic(避免誤觸)
  if (t == T_CMD) {
    handleCommandLine(msg);
  }
}

// ===================== WiFi / MQTT connect =====================
static void wifiConnect() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  Serial.printf("WiFi connecting to %s ...\n", WIFI_SSID);

  uint32_t t0 = millis();
  while (WiFi.status() != WL_CONNECTED) {
    delay(300);
    Serial.print(".");
    if (millis() - t0 > 20000) break;
  }
  Serial.println();

  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("WiFi OK IP=");
    Serial.println(WiFi.localIP());
  } else {
    Serial.println("WiFi FAIL (check SSID/PASS)");
  }
}

static String makeClientId() {
  uint64_t mac = ESP.getEfuseMac();
  char buf[32];
  snprintf(buf, sizeof(buf), "%s_%08X", DEVICE_NAME, (uint32_t)(mac & 0xFFFFFFFF));
  return String(buf);
}

static void publishInfoOnce(const String& clientId) {
  if (!mqtt.connected()) return;

  String payload;
  payload.reserve(256);
  payload += "{";
  payload += "\"device\":\""; payload += DEVICE_NAME; payload += "\",";
  payload += "\"clientId\":\""; payload += clientId; payload += "\",";
  payload += "\"ip\":\""; payload += WiFi.localIP().toString(); payload += "\",";
  payload += "\"base\":\""; payload += TOPIC_BASE; payload += "\",";
  payload += "\"cmd\":\""; payload += T_CMD; payload += "\"";
  payload += "}";
  mqtt.publish(T_INFO.c_str(), payload.c_str(), true);
}

static bool mqttEnsureConnected() {
  if (mqtt.connected()) return true;
  if (WiFi.status() != WL_CONNECTED) return false;

  String clientId = makeClientId();
  Serial.print("MQTT connecting... ");

  // LWT(可選):離線狀態
  String lwt = "{\"online\":0}";
  bool ok = mqtt.connect(clientId.c_str(), nullptr, nullptr, T_STATUS.c_str(), 0, true, lwt.c_str());
  if (!ok) {
    Serial.printf("FAIL rc=%d\n", mqtt.state());
    return false;
  }
  Serial.println("OK");

  mqtt.subscribe(T_CMD.c_str());

  // online status + info
  mqtt.publish(T_STATUS.c_str(), "{\"online\":1,\"boot\":1}", true);
  publishInfoOnce(clientId);

  publishAck("CONNECTED", true);

  return true;
}

// ===================== status publish =====================
static uint32_t lastStatusMs = 0;

static void publishStatus() {
  if (!mqtt.connected()) return;

  // distance
  long d = readDistanceCM_median3();
  if (d < 0) d = -1;

  // mic energy(讀一次就切回喇叭,維持可播放)
  float e = 0;
  lockI2S();
  e = readMicEnergyOnce_locked();
  spk_ok = ensureSpeakerMode_locked();
  unlockI2S();

  String payload;
  payload.reserve(320);
  payload += "{";
  payload += "\"online\":1,";
  payload += "\"ts\":"; payload += String(millis()); payload += ",";
  payload += "\"dist_cm\":"; payload += String(d); payload += ",";
  payload += "\"mic_energy\":"; payload += String(e, 1); payload += ",";
  payload += "\"mic_ok\":"; payload += String(mic_ok ? 1 : 0); payload += ",";
  payload += "\"spk_ok\":"; payload += String(spk_ok ? 1 : 0); payload += ",";
  payload += "\"mouth\":\""; payload += (mouthOpen ? "OPEN" : "CLOSE"); payload += "\",";
  payload += "\"servo\":[";
  payload += String(sAng[0]); payload += ",";
  payload += String(sAng[1]); payload += ",";
  payload += String(sAng[2]); payload += ",";
  payload += String(sAng[3]); payload += "],";
  payload += "\"ack_ts\":"; payload += String(lastAckMs); payload += ",";
  payload += "\"ack\":\""; payload += lastAck; payload += "\"";
  payload += "}";

  mqtt.publish(T_STATUS.c_str(), payload.c_str(), false);
}

// ===================== Setup/Loop =====================
void setup() {
  Serial.begin(115200);

  i2sMutex = xSemaphoreCreateMutex();

  pinMode(US_TRIG, OUTPUT);
  pinMode(US_ECHO, INPUT);

  // TFT init
  SPI.begin(TFT_SCLK, -1, TFT_MOSI, TFT_CS);
  tft.init(240, 320);
  tft.setRotation(1);
  tftHello();

  // Servo init
  s1.attach(SERVO1, 600, 2400);
  s2.attach(SERVO2, 600, 2400);
  s3.attach(SERVO3, 600, 2400);
  s4.attach(SERVO4, 600, 2400);
  servoWriteAll(90);

  // 開機先進 Speaker 模式並 beep(確認喇叭)
  lockI2S();
  spk_ok = i2sInitSpeaker_locked();
  if (spk_ok) playBeep1kHz_200ms_locked();
  unlockI2S();

  // topics
  uint64_t mac = ESP.getEfuseMac();
  char chip[16];
  snprintf(chip, sizeof(chip), "%08X", (uint32_t)(mac & 0xFFFFFFFF));

  TOPIC_BASE = String("otto_go/") + DEVICE_NAME + "/" + chip;
  T_INFO   = TOPIC_BASE + "/info";
  T_STATUS = TOPIC_BASE + "/status";
  T_ACK    = TOPIC_BASE + "/ack";
  T_CMD    = TOPIC_BASE + "/cmd";

  // WiFi
  wifiConnect();

  // MQTT
  mqtt.setServer(MQTT_HOST, MQTT_PORT);
  mqtt.setCallback(mqttCallback);

  Serial.println("----- MQTT Topics -----");
  Serial.println("INFO   : " + T_INFO);
  Serial.println("STATUS : " + T_STATUS);
  Serial.println("ACK    : " + T_ACK);
  Serial.println("CMD    : " + T_CMD);
  Serial.println("-----------------------");
}

void loop() {
  // WiFi 保活
  if (WiFi.status() != WL_CONNECTED) {
    static uint32_t lastRetry = 0;
    if (millis() - lastRetry > 5000) {
      lastRetry = millis();
      wifiConnect();
    }
    delay(10);
    return;
  }

  // MQTT 連線
  mqttEnsureConnected();
  mqtt.loop();

  // 週期 publish status
  uint32_t now = millis();
  if (now - lastStatusMs >= STATUS_PERIOD_MS) {
    lastStatusMs = now;
    publishStatus();
  }
}


沒有留言:

張貼留言