Try running the toio core cube on Windows 10 / macOS / Linux with the Python library bleak

I want to run the toio core cube on a computer near me

The toio core cube is a "very cute" two-wheeled robot that can be controlled by BLE communication. https://toio.github.io/toio-spec/

The other day, I wrote A story about using a smartphone to move the toio core cube directly using BLE communication, but this time I used a personal computer. Let's move the toio core cube.

The official environment for javascript and visual programming is provided.

--Visual programming environment (scratch) - https://toio.io/programming/visual-programming.html --JavaScript library (node.js) - https://github.com/toio/toio.js

However, this article uses python. Visual Programming Environment has been released only for macOS (as of December 10, 2019), and ~~ Windows10 64bit or Requires macOS 10.13 or later. JavaScript library also requires installation of node.js and noble. The purpose of this article is to move the toio core cube quickly using a personal computer or Raspberry Pi that can be used around you, so I will introduce how to use python, which is relatively easy to install.

In addition, since the sample code of bleak uses asyncio, the corresponding Python version is Python 3.5 or later.

What is bleak?

A library for BLE communication Python that runs on Windows 10 / Linux / macOS.

There are various python libraries for BLE communication, but I chose bleak as one that can run (almost) in the same way on three types of OS: Windows10, Linux (raspbian, ubuntu), and macOS.

Other BLE communication python libraries

If you don't want to go straight to BLE, it's better to use the library for toio core cube created by great ancestors. Check the operating requirements for each operating system.

-Control toio core cube with Raspberry Pi (2nd time) -Notify processing + bonus -Play with Toio (1) -I made a library that can control toio with Mac + Python

How bleak works

bleak is implemented by wrapping the BLE communication API of each OS.

--On Windows 10, the common language runtime (CLR) is used to call the dll, and the UWP API is called in it. --On Linux, it calls the bluez stack. --On macOS, pyobjc is used to call the Objective-C Core Bluetooth API.

Since it is made into a python library in a form that hides the BLE communication part of each OS, it is possible to perform BLE communication with (almost) the same python script on any OS.

Well, let's do it anyway

Install python on Windows 10 and macOS

Linux includes python from the beginning (usually), but Windows 10 doesn't, so you need to install it. Also, macOS includes python2.7, but python3 is not included, so you need to install it as well. The following articles will be helpful.

-[Windows 10] Install Python environment in one shot from command prompt -Python3 installation (Mac version)

In the following explanation, the prompt is "$", but it is assumed that the prompt is for Windows10, macOS, and Linux environments. The operation itself is the same in any environment.

Install bleak

--Make the command prompt (PowerShell or command prompt (cmd.exe) for Windows 10), LXterminal for Linux, etc., and start the terminal for macOS) ready for use. --Install bleak with the pip command.

$ pip install bleak

After waiting for a while, the bleak library will be installed and available.

Find out the BLE device address of the toio core cube

This is bleak sample code discover.py ) That's right.

discover.py


import asyncio

from bleak import discover

async def run():
    devices = await discover()
    for d in devices:
        print(d)

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

If you move this, the output will be as follows.

$ python3 discover.py
D0:8B:7F:12:34:56: toio Core Cube
B0:52:22:33:44:5A: Unknown
6E:E4:DA:12:34:55: bluetooth deviceY
63:87:F5:55:22:33: bluetooth deviceX

The device address is a 6-byte hexadecimal number where there is toio Core Cube. Make a note of this value. We will set this value in a later script. In the above execution example, "D0: 8B: 7F: 12: 34: 56". For macOS, it's a long UUID string like 243E23AE-4A99-406C-B317-18F1BD7B4CBE instead of a 6-byte hexadecimal number.

Read the battery level of the toio core cube, turn on the LED, and turn the motor

To read the battery level of the toio core cube, connect it to the oio core cube and then read the battery (Battery Information) characteristic (10B20108-5B3B-4571-9508-CF3EFCD7BBAE). To turn on the LED, write to the characteristic of the lamp (Light Control) (10B20103-5B3B-4571-9508-CF3EFCD7BBAE). To move the motor, write the value to the characteristic of the motor (Motor Control) (10B20102-5B3B-4571-9508-CF3EFCD7BBAE).

Let's write the value referring to the example of "lamp" and "motor" of the communication specification of the toio core cube technical specification.

--Communication specifications of toio core cube technical specifications -Battery -Lamp -Motor

read_write_sample.py


import asyncio
import platform

from bleak import BleakClient

#Battery, LED and motor characteristics
BATTERY_CHARACTERISTIC_UUID = ("10b20108-5b3b-4571-9508-cf3efcd7bbae")
LAMP_CHARACTERISTIC_UUID = ("10b20103-5b3b-4571-9508-cf3efcd7bbae")
MOTOR_CHARACTERISTIC_UUID = ("10b20102-5b3b-4571-9508-cf3efcd7bbae")  
#In bleak, it seems that the UUID of the characteristic must be written in lowercase.

async def run(address, loop):
    async with BleakClient(address, loop=loop) as client:
        x = await client.is_connected()
        #logger.info("Connected: {0}".format(x))
        print("Connected: {0}".format(x))
        #Battery level reading
        battery = await client.read_gatt_char(BATTERY_CHARACTERISTIC_UUID)
        print("battery: {0}".format(int(battery[0])))
        #LED lights red for 160ms
        write_value = bytearray(b'\x03\x10\x01\x01\xff\x00\x00')
        await client.write_gatt_char(LAMP_CHARACTERISTIC_UUID, write_value)
        #Motor: 100 speeds in front of the left, 20 speeds in the back of the right
        write_value = bytearray(b'\x01\x01\x01\x64\x02\x02\x14')
        await client.write_gatt_char(MOTOR_CHARACTERISTIC_UUID, write_value)
        #Ends after 5 seconds
        await asyncio.sleep(5.0, loop=loop)

if __name__ == "__main__":
    address = (
        # discovery.Set the device address of the toio Core Cube found by py here
        "D0:8B:7F:12:34:56"  #For Windows or Linux, specify a hexadecimal 6-byte device address.
        if platform.system() != "Darwin"
        else "243E23AE-4A99-406C-B317-18F1BD7B4CBE"  #UUID attached to macOS for macOS
    )
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run(address, loop))
$ python read_write_sample.py
Connected: True
battery: 100

When you move it, the remaining battery level is read and displayed, and then the LED lights red for a moment. P_20191209_221300.jpg Then rotate clockwise around the slightly right side of the toio core cube. P_20191209_221458.jpg It will end in 5 seconds.

Notify the button status of the toio core cube and the ID read by the reading sensor

To notify the button status of the toio core cube and the read ID of the read sensor (Button Information) characteristic (10B20107-5B3B-4571-9508-CF3EFCD7BBAE) and the read sensor (ID Information) Be notified of the characteristic (10B20101-5B3B-4571-9508-CF3EFCD7BBAE).

For this, refer to bleak sample code enable_notifications.py and write the following script.

enable_button_and_id_info_notification.py


import asyncio
import platform

from bleak import BleakClient

#Button and reading sensor characteristics
BUTTON_CHARACTERISTIC_UUID = ("10b20107-5b3b-4571-9508-cf3efcd7bbae") 
ID_READER_CHARACTERISTIC_UUID = ("10b20101-5b3b-4571-9508-cf3efcd7bbae") 
#In bleak, it seems that the UUID of the characteristic must be written in lowercase.

#Button state notification handler
def button_notification_handler(sender, data):
    print("BUTTON {0}: {1}".format(sender, data))

#Read sensor notification handler
def id_reader_notification_handler(sender, data):
    print("toio ID {0}: {1}".format(sender, data))

async def run(address, loop):
    async with BleakClient(address, loop=loop) as client:
        x = await client.is_connected()
        print("Connected: {0}".format(x))
        #Button status notification start
        await client.start_notify(BUTTON_CHARACTERISTIC_UUID, button_notification_handler)
        #Read sensor notification start
        await client.start_notify(ID_READER_CHARACTERISTIC_UUID, id_reader_notification_handler)
        #Ends in 10 seconds
        await asyncio.sleep(10.0, loop=loop)
        #Button status, reading sensor notification end
        await client.stop_notify(BUTTON_CHARACTERISTIC_UUID)
        await client.stop_notify(ID_READER_CHARACTERISTIC_UUID)

if __name__ == "__main__":
    address = (
        # discovery.Set the device address of the toio Core Cube found by py here
        "D0:8B:7F:12:34:56"  #For Windows or Linux, specify a hexadecimal 6-byte device address.
        if platform.system() != "Darwin"
        else "243E23AE-4A99-406C-B317-18F1BD7B4CBE"  #UUID attached to macOS for macOS
    )
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run(address, loop))

After moving it, lift the toio core cube and press a button, or place it on a mat or sticker in the Toio collection.

$ python enable_button_and_id_info_notification.py
Connected: True
toio ID 10b20101-5b3b-4571-9508-cf3efcd7bbae: bytearray(b'\x01\xa4\x01g\x01|\x00\xaf\x01e\x01|\x00')
toio ID 10b20101-5b3b-4571-9508-cf3efcd7bbae: bytearray(b'\x01\xa4\x01h\x01|\x00\xaf\x01f\x01|\x00')
toio ID 10b20101-5b3b-4571-9508-cf3efcd7bbae: bytearray(b'\x01\xa4\x01g\x01|\x00\xaf\x01e\x01|\x00')

You can see that the value that changes every time is notified.

Actually ...

Only Windows 10 (1909) and Linux (raspbian buster, RasPi 3B and 4B have been confirmed to work) have actually been confirmed to work. I'm sorry. I couldn't run bleak on macOS in my environment. discovery.py works, but everything else doesn't work at all. (The environment is MacBook Pro 13inch (early2015) macOS 10.14.6 (mojave)) In this macOS environment, it works with Adafruit's BLE library that claims to support Linux / macOS, but on the contrary, this is the raspbian buster. It didn't work. (Caused by the difference in the version of bluez) It seems that it will work if the backend of bluez is corrected, but I can't figure out the cause.

at the end

Computer club in elementary school or junior high school? I introduced how to move the toio core cube and see it using python on a familiar personal computer or Raspberry Pi that seems to be in. I think that even a PC that does not have a built-in bluetooth interface, such as a notebook PC, can be operated by attaching a USB dongle type Bluetooth interface. For those who have a little high hurdle to install node.js, noble, and scratch-link, and even in an environment where Windows 10 can be used but the apps that can be installed are limited to store apps, the store app python3 can be installed and bleak You can use it, so please give it a try.

Recommended Posts

Try running the toio core cube on Windows 10 / macOS / Linux with the Python library bleak
Put Cabocha 0.68 on Windows and try to analyze the dependency with Python
Try running Python with Try Jupyter
Run SwitchBot on Windows 10 with Bleak
Getting started with Python 3.8 on Windows
Put MeCab binding for Python with pip on Windows, mac and Linux
The story of running the asp.net core 3.1 app on arm64 version Amazon Linux 2
Run servo with Python on ESP32 (Windows)
[C] [python] Read with AquesTalk on Linux
Download files on the web with Python
Try HTML scraping with a Python library
Installing PIL with Python 3.x on macOS
Location information data display in Python --Try plotting with the map display library (folium)-
Try to use up the Raspberry Pi 2's 4-core CPU with Parallel Python
Try running Google Chrome with Python and Selenium
Try to solve the man-machine chart with Python
Try CIing the pushed python code on GitHub.
Manage AWS nicely with the Python library Boto
Try working with Mongo in Python on Mac
Organize files on Windows with Linux commands-using WSL-
Introduction to Python with Atom (on the way)
Get started with Python on macOS Big Sur
Install Python 3 on MacOS Catalina (with Homebrew only)
Try using the DropBox Core API in Python
Python on Windows
Try to solve the programming challenge book with python3
Run Kali Linux on Windows with GUI (without VirtualBox)
Problems with windows python being called on pipenv on WSL
[Cloudian # 8] Try setting the bucket versioning with Python (boto3)
Try translating with Python while maintaining the PDF layout
Try to solve the internship assignment problem with Python
Try touching the micro: bit with VS Code + Python
Install selenium on Mac and try it with python
Try debugging Python on Raspberry Pi with Visual Studio.
I tried to solve the soma cube with python
Yum command to access MySQL with Python 3 on Linux
Install the 3rd party python library on Cinema 4D
Make a breakpoint on the c layer with python
Information for controlling the motor with Python on RaspberryPi
PIL with Python on Windows 8 (for Google App Engine)
About the --enable-shared option when building Python on Linux
[Beginner] Installing Python and running programs (Windows)
The basics of running NoxPlayer in Python
Until you use the Kaggle API with Colab
Trap trapped when running a Python Windows executable
Python on Windows
python windows environment
Python installation (Windows)
Try running the toio core cube on Windows 10 / macOS / Linux with the Python library bleak
Touching the latest physics-based renderer Mitsuba2 (2) Running from Python
I tried running the app on the IoT platform "Rimotte"
The process of installing Atom and getting Python running
From python to running instance on google cloud platform