はじめに
SwitchBotを使っていて困るのが電池切れ。
公式アプリを開けば電池残量を確認できるけど、日常的には見ないし、使いたい時に電池が切れてるでおなじみですよね。
私はオートロックの解錠に使っているので死活問題です。
SwitchBotの公式が公開しているPythonにはPressなどのコマンドはありますが、電池残量を取得するものはないです。
アプリで取れるんだから、そんなわけないだろと調べていると、やっぱりありました。
https://github.com/RoButton/switchbotpy
一旦これを使って満足してたんですけど、なんか安定して取れない時があるので安定してる公式のPythonにコマンド追加することにしました。
公式Pythonの修正
設定情報取得コマンドを追加しました。
公式からForkした私のリポジトリに公開しています。
https://github.com/kanon700/python-host/tree/feature/add_get_settings
修正内容は以下
switchbot_py3.py
class Driver(object):
handle = 0x16
notif_handle = 0x13
commands = {
'press' : '\x57\x01\x00',
'on' : '\x57\x01\x01',
'off' : '\x57\x01\x02',
'settings' : '\x57\x02',
}
def run_and_res_command(self, command):
self.req.write_by_handle(self.handle, self.commands[command])
return self.req.read_by_handle(self.notif_handle)
def get_settings_value(self, value):
value = struct.unpack('B' * len(value[0]), value[0])
settings = {}
settings["battery"] = value[1]
settings["firmware"] = value[2] / 10.0
settings["n_timers"] = value[8]
settings["dual_state_mode"] = bool(value[9] & 16)
settings["inverse_direction"] = bool(value[9] & 1)
settings["hold_seconds"] = value[10]
return settings
電池残量取得スクリプト
こんな感じのスクリプトでバッテリ残量を取得できます。
SwitchBot_Battery_Get.py
# !/usr/bin/python3
# -*- coding: utf-8 -*-
from switchbot_py3 import Driver
switchbot = 'xx:xx:xx:xx:xx:xx' #switchbotのMACアドレス
def main():
bot = Driver(device=switchbot)
bot.connect()
value = bot.run_and_res_command('settings')
settings = bot.get_settings_value(value)
print("battery:" + str(settings["battery"]))
if __name__ == '__main__':
main()
以上