[Raspberry Pi] スマートプラグ「TP-Link HS105」で iOS デバイスの充電を自動で停止する2

スマートプラグの「TP-Link HS105」を使って、iOS デバイスの充電が 95% を超えたら自動で停止させようとして、うまくいかなかったと書いた。

[Raspberry Pi] スマートプラグ「TP-Link HS105」で iOS デバイスの充電を自動で停止する(失敗) – with a Christian Wife
https://wacw.cf/2021/02/20/stopping-charging-ios-automatically/

別の方法を思い付いた。コマンドでスマートプラグを操作する方法だ。

具体的には、iOS の Shortcuts アプリの Automation で、バッテリー充電が 95% になったら、常時起動している Raspberry Pi へコマンドを送信。その Raspberry Pi からスマートプラグへオフのコマンドを送信する、という流れだ。

環境:iPad Pro 9.7″、iPadOS 14.2(英語環境)、Raspberry Pi 3 Model B(Raspberry Pi OS Buster )

(1)Raspberry Pi に node.js のインストールを済ませる。

この方法は前回と同じだ。

[Raspberry Pi] スマートプラグ「TP-Link HS105」で iOS デバイスの充電を自動で停止する(失敗) – with a Christian Wife
https://wacw.cf/2021/02/20/stopping-charging-ios-automatically/

(2)以下のコマンドで tplink-smarthome-api をインストールする。

$ sudo npm install -g tplink-smarthome-api

(3)TP-Link HS105 の IP アドレスを調べる。

その方法はいろいろあるが、tplink-smarthome-api の以下のコマンドが手軽だろう。

$ tplink-smarthome-api search
Searching...
startDiscovery({
  discoveryInterval: 2000,
  discoveryTimeout: 10000,
  breakoutChildren: true,
  broadcast: '255.255.255.255'
})
HS105(JP) plug IOT.SMARTPLUGSWITCH 192.168.100.100 9999 [いろいろ文字列が続く]

最後の行に IP アドレス(ここでは 1 92.168.100.100 9999)が表示されている。

これで、以下のコマンドを実行し、スマートプラグをオン・オフできることを確認しよう。

オン
$ tplink-smarthome-api sendCommand 192.168.100.100:9999 '{"system":{"set_relay_state":{"state":1}}}'

オフ
$ tplink-smarthome-api sendCommand 192.168.100.100:9999 '{"system":{"set_relay_state":{"state":0}}}'

(4)iPad の Shortcuts アプリで次の「Automation」を追加する。

When
・When battery level rises above 95%

Do
・Run Script Over SSH
Host:[Raspberry Pi の IP アドレス]
Port:22
User:pi
Authentication:[Raspberry Pi のユーザー名]
Password:[Raspberry Pi のパスワード]
Input:(変更しない)
Script:tplink-smarthome-api sendCommand 192.168.100.100:9999 '{"system":{"set_relay_state":{"state":0}}}'

初回実行時は初めて接続するホストなので接続していいかという確認が表示されるので、「Connect」をタップする。これで次回以降確認ダイアログが表示されないくなる。同時に、スマートプラグのオフもうまくいくはずだ。

これで、充電が 95% を超えたらスマートプラグがオフになり、充電を停止させることができるようになった!

なお、別途 Raspberry Pi およびスマートプラグの IP アドレスをルーターで固定しておく必要がある。

参考:
TP-Link のスマートプラグ HS105 を買って制御してみた | tech – 氾濫原
https://lowreal.net/2018/08/07/1

GitHub – plasticrake/tplink-smarthome-api: TP-Link Smarthome WiFi API
https://github.com/plasticrake/tplink-smarthome-api

スマートコンセント(HS105)を使って電気毛布を自動ON/OFF制御する #SleepTech – Qiita
https://qiita.com/tmitsuoka0423/items/582ff0c303abe8570ee5

iOS12のショートカットをSSHクライアントにしてsudoしてみるなど – (っ´∀`)っ ゃー | 一撃
https://nullpopopo.blogcube.info/2018/09/ios12-shortcut-ssh-sudo.html

Amazon.co.jp: 【Amazon Alexa認定取得製品】 TP-Link WiFi スマートプラグ 遠隔操作 直差しコンセント Echo シリーズ/Google ホーム/LINE Clova 対応 音声コントロール サーキュレーター ハブ不要 3年保証 HS105 : DIY・工具・ガーデン
https://amzn.to/3TwzXPV