The problem with using SwitchBot is that the battery is dead. You can check the battery level by opening the official app, but you don't see it on a daily basis, and you're familiar with it because the battery is dead when you want to use it. I use it to unlock the auto lock, so it's a matter of life and death.
There are commands such as Press in Python released by the official SwitchBot, but there is nothing to get the remaining battery level. When I was investigating that it wasn't because I could get it with the app, I found it. https://github.com/RoButton/switchbotpy
I was happy with this once, but I decided to add a command to the official Python that is stable because there are times when I can not get it stably.
A setting information acquisition command has been added. It is published in my repository that was officially forked. https://github.com/kanon700/python-host/tree/feature/add_get_settings
The correction contents are as follows
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
You can get the battery level with a script like this.
SwitchBot_Battery_Get.py
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from switchbot_py3 import Driver
switchbot = 'xx:xx:xx:xx:xx:xx' #switchbot MAC address
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()
that's all
Recommended Posts