0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ESPHome × スマホのPingによる在宅検知の仕組み

0
Posted at

ESP32とESPHomeを用いて、スマートフォン(Android)の在宅・不在を自動判定する仕組みを作りました。
本構成ではBluetoothや専用ビーコンは使用せず、家庭内LAN上でのPing応答(パケットロス率)を指標として在宅判定を行います。
判定結果はESP32側で完結させつつ、n8nのWebhookに結果を通知、状態をデータテーブルに保存することでワークフローに活用できる構成としています。

判定ロジックの考え方

なぜPingを使うのか

  • ルーターやキャリア機器に依存しない
  • BLEビーコン等の追加デバイスが不要
  • ESPHome単体で完結できる

という理由から、ひとまず手持ちの機器でできる方法としてPingベースの検知を採用しました。

システム構成

  • ESP32
    • ESPHome(esp-idf フレームワーク)
  • スマートフォン
    • Androidスマートフォン(Pixel 7)
    • 家庭内Wi-Fiに接続
  • 判定方式
    • ESP32 → スマホへの Ping
    • パケットロス率を在宅判定に利用
  • 外部連携
    • n8n Webhook(在宅 / 不在通知)

ソース

esphome:
  name: presence_check
  on_boot:
    priority: -100
    then:
      # Pingが完了して値が入るまで待機(最大60秒)
      - wait_until:
          condition:
            lambda: 'return !isnan(id(packet_loss).state);'
          timeout: 60s
      - if:
          condition:
            binary_sensor.is_off: presence_sensor
          then:
            - logger.log: "Boot check: Presence NOT detected -> Sending initial Away status"
            - switch.turn_off: status_led
            - http_request.post:
                url: https://example.com/webhook/presence/away
          else:
            - logger.log: "Boot check: Presence detected -> Sending initial Home status"
            - switch.turn_on: status_led
            - http_request.post:
                url: https://example.com/webhook/presence/home

esp32:
  board: esp32dev
  framework:
    type: esp-idf

# Enable logging
logger:
  level: DEBUG

ota:
  - platform: esphome
    password: ""

wifi:
  ssid: "WiFiSSID"
  password: "WiFiPassword"

  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Presence Fallback Hotspot"
    password: "hogehoge"

external_components:
  - source: github://trombik/esphome-component-ping@main

sensor:
  - platform: ping
    ip_address: "xxx.xxx.xxx.xxx"
    loss:
      name: "Packet Loss"
      id: packet_loss
      on_value:
        then:
          - lambda: |-
              bool is_home = x < 100.0;
              if (id(presence_sensor).state != is_home) {
                ESP_LOGD("presence_debug", "Packet loss: %.1f%% -> Updating Presence to %s", x, is_home ? "true (Home)" : "false (Away)");
                id(presence_sensor).publish_state(is_home);
              } else {
                ESP_LOGD("presence_debug", "Packet loss: %.1f%% -> No change (Current: %s)", x, is_home ? "true (Home)" : "false (Away)");
              }
    latency:
      name: "Latency"
    update_interval: 10s

switch:
  - platform: gpio
    pin: 2
    name: "Presence Status LED"
    id: status_led

binary_sensor:
  - platform: template
    name: "Presence"
    id: presence_sensor # IDを追加
    # Logic driven by packet_loss sensor

    filters:
      - delayed_off: 300s # スマホのスリープ対策
    on_press:
      - logger.log: "Presence detected -> Action!"
      - switch.turn_on: status_led
      - http_request.post:
          url: https://example.com/webhook/presence/home
    on_release:
      - logger.log: "Presence lost -> Action!"
      - switch.turn_off: status_led
      - http_request.post:
          url: https://example.com/webhook/presence/away

http_request:
  timeout: 5s
  verify_ssl: false

在宅・不在の判定基準

  • パケットロス率 < 100%
    → スマホがLAN内に存在すると判断(在宅)
  • パケットロス率 = 100%
    → 応答なし(不在)

Pingは10秒間隔で実行しています。

ESPHome 設定のポイント

  1. 外部Pingコンポーネントの利用
    ESPHome 標準にはPingセンサーがないため、以下の外部コンポーネントを利用しています。
external_components:
  - source: github://trombik/esphome-component-ping@main
  1. Packet Loss を元にした在宅判定
    Pingセンサーのloss値(%)を利用し、
    テンプレート「binary_sensor」に在宅状態を反映しています。
bool is_home = x < 100.0;

状態が変化したときのみpublish_state()することで、
不要なイベント発火を抑えています。

  1. スマホスリープ対策(delayed_off)
    Androidはスリープや省電力制御により、一時的にPing応答が途切れることがあります。
    これによる誤判定を防ぐため、以下のフィルタを設定しています。
filters:
  - delayed_off: 300s

→ 5分間応答が途切れた場合のみ「不在」判定

  1. ESP32再起動時の初期状態送信
    ESP32再起動直後は、センサー値がまだ確定していません。
    そのため「on_boot」で以下の処理を行っています。
  • Ping 結果が取得できるまで待機(最大 60 秒)
  • 現在の在宅状態を判定
  • n8nに初期ステータスを送信
on_boot:
  priority: -100

これにより、再起動直後の状態不整合を防止しています。

  1. n8nへのWebhook通知
    在宅・不在の状態変化時に、以下のURLへPOSTしています。
  • /presence/home
  • /presence/away

ESP32側は「判定と通知」までに限定し、
記録・通知・自動化ロジックはn8n側に集約できるようにしています。

LEDによる状態可視化

ESP32のGPIO2のLEDを

  • 在宅:点灯
  • 不在:消灯

とすることで、デバッグ時や物理的な状態確認にも役立てています。
PXL_20251213_044419434.MP.jpg

この方式のメリット・注意点

メリット

  • BLEペアリング不要
  • 追加デバイス不要
  • ESPHome単体で完結
  • n8n など外部ワークフローと連携しやすい

注意点

  • スマホのIPアドレスは固定(DHCP予約)推奨
  • Wi-Fi OFF状態は「不在」扱い
  • スマホ側の省電力設定によっては調整が必要

今後の改善案

  • BLEビーコンで運用したほうが良さそう
  • 複数端末(人数)での運用
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?