0
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?

More than 3 years have passed since last update.

RaspberryPi4 SwitchBot編

Last updated at Posted at 2020-02-09

はじめに

python3の実行環境は入っている人向け

ここのPython3向けの設定をやる
https://github.com/OpenWonderLabs/python-host

依存関係

sudo apt install libboost-python-dev libboost-thread-dev libbluetooth-dev
sudo pip3 install pybluez gattlib

HPには書いていないけど、libbluetooth-devが無いとpybluezが入らないので、先に入れておく

実行コマンド

以下のコマンドでSwitchBotが動いたら成功

sudo python switchbot.py  xx:xx:xx:xx:xx:xx Press

xx:xx:xx:xx:xx:xxはSwitchBotのMACアドレス

バッテリ残量の取得

このやり方はなんかあんまり安定しなかったので別の方法を追記した
いつの間にか電池切れしているで、お馴染みのSwitchBot。
公式には電池残量の取得APIが載っていなかったけど、pipで switchbotpyってのを入れると取得できるっぽい

switchbotpyのインストール

pip install switchbotpy

サンプルコード

from switchbotpy import Bot

switchbot = 'XX:XX:XX:XX:XX:XX' #SwitchBotのMacアドレス


def GetSwitchBotBattery(addr):
    b = Bot(bot_id=1, mac=addr, name="data")
    settings = b.get_settings()

    return settings["battery"]


if __name__ == '__main__':
    bat = GetSwitchBotBattery(switchbot)
    print(bat)

これで電池切れで玄関解錠できないなんて事を回避できる

バッテリ残量の取得2

公式のpythonに設定情報取得コマンドを追加した
https://github.com/kanon700/python-host/tree/feature/add_get_settings

switchbot_py3.py
    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

bot = 'xx:xx:xx:xx:xx:xx' #switchbotのMACアドレス

def main():
    bot = Driver(device=entrance)
    bot.connect()
    value = bot.run_and_res_command('settings')
    settings = bot.get_settings_value(value)
    print(settings["battery"])


if __name__ == '__main__':
    main()

以上

0
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
0
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?