2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ESP32からLINEに通知を送る方法

Last updated at Posted at 2024-03-06

概要

ESP32からLINEのAPIを叩き、通知を送信する方法に関して整理してみました。また、本題からは逸れますが、今回はテストも兼ねて自作モジュールを活用してみました。Wi-FiやBLEを内蔵しつつも低消費電力なESP32を搭載し、リチウムポリマー電池によって駆動できるため、今回のようなIoTデバイスを試作する用途に最適です。
picture.jpg

開発環境

  • Windows 11 Home 23H2
  • Arduino IDE 2.3.0
  • Android 14
  • LINE 8.6.0.3277

トークンを取得する

LINEのAPIを利用する上で必要になるため、トークンを発行します。まずはこちらにログインし、マイページを開きます。LINEのアカウントが必要です。その下部に表示されるボタンをクリックし、ダイアログが開いたらトークン名を入力し、通知の送信先も選択します。トークン名は任意です。最後にトークンが表示されるため、確実にメモしておきます。ダイアログを閉じると再確認できないので特に注意してください。

LINE Notify

公式の資料は以下の通りです。

ここではcURLを使用し、簡単にLINEのAPIを試してみます。まずは普通にメッセージを送る場合です。最大1000字まで入力できます。

curl -X POST -H "Authorization: Bearer {token}" -F "message={message}" "https://notify-api.line.me/api/notify"

次にスタンプも併せて送る場合です。スタンプのID、そのスタンプが含まれるパッケージのIDを指定します。なんと動くスタンプにも対応しています。ただし、メッセージは必須なのでスタンプだけを送るようなことはできません。

curl -X POST -H "Authorization: Bearer {token}" -F "message={message}&stickerPackageId={package}&stickerId={sticker}" "https://notify-api.line.me/api/notify"

プログラム

ボタンを押すとLINEに通知が送信されます。パラメータなどの詳細については上記の資料を参照してください。

line_notify.ino
#include <WiFi.h>
#include <HTTPClient.h>

#define BUTTON_PIN 1

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

const String token = "{token}";


void setup() {
  WiFi.begin(ssid, password);

  Serial.begin(115200);
  Serial.print("Connecting...");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("Connected to Wi-Fi");

  pinMode(BUTTON_PIN, INPUT_PULLUP);
}

void loop() {
  static int lastState = LOW;

  int state = digitalRead(BUTTON_PIN);
  if (state == LOW && lastState == HIGH) {
    sendMessage("LINE Notify");
  }
  lastState = state;
  delay(100);
}

void sendMessage(String message) { 
  HTTPClient client;

  String url = "https://notify-api.line.me/api/notify";
  client.begin(url);
  client.addHeader("Content-Type", "application/x-www-form-urlencoded");
  client.addHeader("Authorization", "Bearer " + token);

  String query = "message=" + message;
  client.POST(query);

  String body = client.getString();
  Serial.println("Sent the message");
  Serial.println(body);
  client.end();
}

おまけ

改行コードに関して補足です。試した中では\n\r\n、あるいはURLエンコードされた%0A%0D%0Aを挿入することで正しく改行されました。

結果

実際のトーク履歴です。トークン名はArduinoと指定しました。
screenshot.png

まとめ

ESP32を使用し、APIを通じて普段から使い慣れたLINEと連携することができました。

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?