M5StickCを使ってGoogleHomeからmp3を再生する

公開日時
更新日時

以前、M5StickCを使って照明を自動ON/OFFするようにした。

今回は人感センサを玄関に設置し、家に帰ってきたら通知音が出るようにしてみる。

  • Arduino ESP32 filesystem uploaderのインストール

下記記事を参考に、スケッチブックの保存ディレクトリにtoolsディレクトリを作成し、ESP32FSを設置する

  • mp3再生用のスケッチを保存しているディレクトリにdataディレクトリを作成し、その中に[[notify.mp3]]を設置する

  • スケッチファイルの作成

下記記事を参考にさせていただきgoogle-home-notifierを使ってmp3を再生するようにした。

#include <M5StickC.h>
#include <WebServer.h>
#include <HTTPClient.h>
#include <WiFi.h>
#include <ArduinoJson.h>
#include <esp8266-google-home-notifier.h>
#include <SPIFFS.h>

const char* ssid     = "";
const char* password = "";

long counter = 0;

// google-home-notifier
GoogleHomeNotifier ghn;
WebServer server(80);
String head = "<meta charset=\"utf-8\">";

void setupWifi() {
  WiFi.begin(ssid, password);
  Serial.printf("WIFI: Connecting to %s ", ssid);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(100);
  }
  Serial.println();
  Serial.println("IP address: " + WiFi.localIP().toString());

  const char displayName[] = "GoogleHomeName";
  Serial.println("connecting to Google Home...");
  if (ghn.device(displayName, "en") != true) {
    Serial.println(ghn.getLastError());
    return;
  }
  Serial.print("found Google Home(");
  Serial.print(ghn.getIPAddress());
  Serial.print(":");
  Serial.print(ghn.getPort());
  Serial.println(")");

  // WebServer
  server.on("/notify.mp3", handlePlay);
  server.begin();
}

void setup() {
  M5.begin();
  M5.Lcd.setRotation(1);
  M5.Axp.ScreenBreath(7);
  M5.Lcd.setTextColor(BLACK, WHITE);
  M5.Lcd.fillScreen(WHITE);

  Serial.begin(9600);
  while (!Serial);
  delay(100);

  setupWifi();

  pinMode(36, INPUT_PULLUP);
}

void sound() {
  String mp3url = "http://" + WiFi.localIP().toString() + "/notify.mp3";
  Serial.println("GoogleHomeNotifier.play() start");
  if (ghn.play(mp3url.c_str()) != true) {
    Serial.print("GoogleHomeNotifier.play() error:");
    Serial.println(ghn.getLastError());
  }
}

void loop() {
  server.handleClient();

  M5.Lcd.fillScreen(WHITE);
  M5.Lcd.setCursor(60, 30, 4);
  M5.Lcd.println(counter);
  if (digitalRead(36) == HIGH) {
    if (counter < 0) {
      counter = 0;
    }
    counter += 1;
  } else {
    if (counter > 0) {
      counter = 0;
    }
    counter -= 1;
  }

  if (counter == 25) {
    sound();
  }
  delay(200);
}

void handlePlay()
{
  String path = server.uri();
  SPIFFS.begin();
  if (SPIFFS.exists(path)) {
    Serial.println("handlePlay: sending " + path);
    File file = SPIFFS.open(path, "r");
    server.streamFile(file, "audio/mp3");
    file.close();
  } else {
    server.send(200, "text/html", head + "SPIFFS file not found:" + path);
  }
  SPIFFS.end();
}

参考


Related #raspberry pi