Run SwitchBot on Windows 10 with Bleak

Introduction

This article is a tutorial article for those who want to perform BLE communication of SwitchBot using Bleak on Windows 10. It connects to SwitchBot and sends instruction bytes. The language is python. Also, although SwitchBot is used in this article, it can be used for other BrueTooth devices as BLE communication using Bleak because it only connects and sends instruction bytes. (Probably)

Requirements

SwitchBot It is a switch that can be operated remotely by Bluetooth. There are multiple types, but this time we will use the following SwitchBot https://www.switchbot.jp/bot

BLE communication

BLE (Bluetooth Low Energy) communication is a standard added from Bluetooth version 4.0 that enables communication with Bluetooth devices with low power consumption. I think it is easier to understand this area if you refer to the article of the predecessor. https://houwa-js.co.jp/blog/2018/06/20180629/
https://jellyware.jp/kurage/bluejelly/ble_guide.html

Pyblues cannot be used under Windows environment

If you want to perform BLE communication of SwitchBot under Windows environment, pybluez, which is the main BLE communication library used, cannot be used on Windows. (Reference: https://atatat.hatenablog.com/entry/2020/07/09/003000#3-Bleak%E3%81%AE%E5%88%A9%E7%94%A8) In addition, github for BLE communication on PC is published on SwitchBot, but since it is a code supported only by pyblues, It cannot be used as it is.

Use of Bleak

From this article Since it was said that a module called Bleak can be used for BLE communication under Windows environment, I will use it. Execute the following pip command.

pip install bleak

Find out the MAC address of the SwitchBot

While referring to the Official Document, execute the program to search for nearby Bluetooth devices on your PC.

Discover.py


import asyncio
from bleak import discover

async def run():
    devices = await discover()
    for d in devices:
        #Show mac address, name, distance of found device
        print(d.address,d.name,d.rssi)
        print(d)

loop = asyncio.get_event_loop()
loop.run_until_complete(run())

If SwitchBot is found here, the MAC address of SwitchBot will be displayed, so copy it. If you can't find it, download the Bluetooth driver from here and check if the SwitchBot is recognized correctly. In addition, there is a possibility of initial failure of SwitchBot, so it is recommended to perform a connection test from the SwitchBot app provided by the Android / iOS app. The detailed method is described in the quick start guide enclosed with Switchbot.

Connection with SwutchBot

If the MAC address can be obtained, connect to SwitchBot using BLE communication → send a command. The following program is a sample of the created connection and transmission.

Bleak_Connect_SwitchBot.py


import asyncio
from bleak import discover

async def run():
import asyncio
from bleak import BleakClient
import time

#switchbot mac address.[Discover.py]Need to find out in
address = " "
#switchbot UUID.Excavated from SwitchBot's github
UUID = "cba20002-224d-11e6-9fb8-0002a5d5c51b"


async def run(address, loop):
    async with BleakClient(address, loop=loop) as client:
        #Pause to prevent synchronization mistakes.
        time.sleep(5)

        #Connection test below.[Connected: False]Is displayed, the connection has failed.
        x = await client.is_connected()
        print("Connected: {0}".format(x))
        #Check the current status of switchbot
        y = await client.read_gatt_char(UUID)
        print(y)
        print("The connection was successful. Please enter the command.\n command → press,on,off,exit")
        while True:
            #Receive input. Change the instruction to be sent for each command. exit if exit
            command = input()
            if command == "press":
                write_byte = bytearray(b'\x57\x01\x00')
            elif command == "on":
                write_byte = bytearray(b'\x57\x01\x01')
            elif command == "off":
                write_byte = bytearray(b'\x57\x01\x02')
            elif command == "exit":
                #[exit]If you enter, it will end in 1 second
                await asyncio.sleep(1.0, loop=loop)
                break
            else:
                print("Please enter the command.\n command → press,on,off,exit")
                continue

            #Send instructions to switchbot
            await client.write_gatt_char(UUID, write_byte)
            #Check the current status of switchbot
            y = await client.read_gatt_char(UUID)
            print(y)
            #Pause due to synchronization error
            time.sleep(2)


#Start communication with switchbot by bleak
loop = asyncio.get_event_loop()
loop.run_until_complete(run(address, loop))

This program waits for input from standard I / O if the connection is successful. You can enter the following command:

Switch the instruction byte according to the operation you want to perform, and send the instruction to Switchbot by client.write_gatt_char (UUID, write_byte). If the SwitchBot works correctly, you are successful.

Summary

I explained how to use SwitchBot for BLE communication (python) under Windows environment. The content explained in this article can only connect and send, and I do not yet know how to switch modes of SwtichBot due to my lack of study. In the future, when I find a mode switching method from the official document or github, I would like to add it and describe it in another article.

[]( Github that summarizes the code is here (only the code in this article is available) ) Postscript (2020/09/11): SwitchBot API uses BlueZ, so it could not be used on Windows. https://github.com/RoButton/switchbotpy

Recommended Posts

Run SwitchBot on Windows 10 with Bleak
Run servo with Python on ESP32 (Windows)
Run Jupyter on Ubuntu on Windows
Run Openpose on Python (Windows)
Run Jupyter Notebook on windows
Blogging with Pelican on Windows
Run Kali Linux on Windows with GUI (without VirtualBox)
Run Tensorflow natively supported on windows
Use Tensorflow 2.1.0 with Anaconda on Windows 10!
Run XGBoost on Bash on Ubuntu on Windows
Getting started with USD on Windows
Getting started with Python 3.8 on Windows
Run Radeon GPU on Windows on QEMU / KVM
Use Tabpy with Cloud Run (on GKE)
Django + Apache with mod_wsgi on Windows Server 2016
Run py.test on Windows Anaconda and MinGW
Run (legacy) Windows apps with Windows Application Driver
Run matplotlib on a Windows Docker container
Run Linux on ARM architecture with QEMU
Python on Windows
Rock-paper-scissors with Python Let's run on a Windows local server for beginners
Install and run Python3.5 + NumPy + SciPy on Windows 10
Run django applications on Windows + Apache + mod_wsgi + services.
Put MicroPython on Windows to run ESP32 on Python
Install OpenCV 4.0 and Python 3.7 on Windows 10 with Anaconda
Run yolov4 "for the time being" on windows
Organize files on Windows with Linux commands-using WSL-
Boot CentOS 8 from Windows 10 with Wake On LAN
Run Flask on CentOS with python3.4, Gunicorn + Nginx.
Run LEDmatrix interactively with Raspberry Pi 3B + on Slackbot
Run Python with VBA
Run Tensorflow from Jupyter Notebook on Bash on Ubuntu on Windows
Run prepDE.py with python3
Problems with windows python being called on pipenv on WSL
Pylint on Windows Atom
Linux (WSL) on Windows
Run Django on PythonAnywhere
Run mysqlclient on Lambda
Run Blender with python
Python starting with Windows 7
Try running the toio core cube on Windows 10 / macOS / Linux with the Python library bleak
Anaconda on Windows Terminal
Install Anaconda on Windows 10
python basic on windows ②
PIL with Python on Windows 8 (for Google App Engine)
Install python on windows
Install pycuda on Windows10
Create an OpenAI Gym environment with bash on Windows 10
Run OpenMVG on Mac
Build TensorFlow on Windows
Try FEniCS on Windows!
Build XGBoost on Windows
Install pygraphviz on Windows 10
Use Ansible on Windows
Try Poerty on Windows
Install Chainer 1.5.0 on Windows
Until you create a machine learning environment with Python on Windows 7 and run it
Use QuTiP on Windows
How to run Django on IIS on a Windows server
Use pip on Windows
How to operate Firefox with selenium on Windows Memo