[PYTHON] Check! Get sensor data via Bluetooth with Raspberry Pi ~ Preparation

Hello, this is @dz_ this and Ohira Kazumi of oak fan.

Prologue-Introduction

I investigated how to handle Bluetooth so that the Raspberry Pi can use Bluetooth to acquire data from the sensor device.

I started this trial with Raspberry Pi Zero, but I couldn't install the necessary libraries due to lack of memory, so I decided to proceed with Raspberry Pi 2 Model B.

Using Bluethooth with Raspberry Pi

Preparation of Bluetooth adapter

The Raspberry Pi used this time does not have Bluetooth, so use a USB adapter.

Bluetooth USB adapter this and that

It seems that PLANEX products are often used. When I went to a certain electric shop, I didn't have PLANEX, so I bought the cheapest PRINCETON one (laughs). It works without any problems.

-PLANEX BT-Micro4 -PRINCETON PTM-UBT7

Sensor device connected via Bluetooth

Use SensorTag CC2650 equipped with 10 types of sensors. It can be connected via Bluetooth, and it seems to be easy to handle because there are sample code and user information here and there.

Peripheral circumstances when dealing with Bluetooth on Linux

I'm still studying, but it seems that the following mechanism will be used to handle Bluetooth on Linux.

BlueZ

GATT (Generic Attribute Profile) --A standardized framework for data transfer and storage based on the Attribute Protocol (ATT) --Reference: Bluetooth Story (2) | Wireless ・ Oto | Silex Technology, Inc.

Operation check

As you will learn a lot about difficult things, first, refer to RPi Bluetooth LE --eLinux.org from the command line. I tried to check the operation.

#Check the connected USB device
$ lsusb
...
Bus 001 Device 011: ID 0a12:0001 Cambridge Silicon Radio, Ltd Bluetooth Dongle (HCI mode)
...

#Check the status of the Bluetooth adapter
$ hciconfig
hci0:   Type: BR/EDR  Bus: USB
        BD Address: XX:XX:XX:XX:XX:XX  ACL MTU: 310:10  SCO MTU: 64:8
        UP RUNNING 
        RX bytes:610 acl:0 sco:0 events:36 errors:0
        TX bytes:942 acl:0 sco:0 commands:36 errors:0

#If above`DOWN`Is displayed, enable it with the following command
$ sudo hciconfig hci0 up

#Scan nearby Bluetooth devices
$ sudo hcitool lescan
LE Scan ...
XX:XX:XX:XX:XX:XX (unknown)
XX:XX:XX:XX:XX:XX CC2650 SensorTag
...

SensorTag was displayed in the scan result. It seems that you can recognize it safely.

Use Bluetooth from Python

Now, let's try using Bluetooth programmatically.

As for the language, I will try using Python, which is a major language in the Raspberry Pi area, after reviewing it. As a library for handling Bluetooth, I will introduce pybluez.

Install pybluez

Please refer to the following for the installation itself. Since gattlib is also required to handle BLE compatible devices with pybluez, install it as well.

#Install pyBluez dependent packages
$ sudo apt-get install python-dev libbluetooth3-dev

#Install pyBluez
$ sudo pip install pybluez

#Install gattlib dependent packages
$ sudo apt-get install libglib2.0 libboost-python-dev libboost-thread-dev

#Install gattlib required when using BLE
$ sudo pip install gattlib

Sample code

Now let's look for SensorTag in python.

SensorTag supports BLE, so you can scan with this sample code.

Also, to get the data, this sample code will be helpful.

As you may have already noticed, pybluez actually uses gattlib via pybluez when dealing with BLE compatible devices, so the documentation for gattlib itself is also helpful.

In GATT, data is acquired and set using an address (?) Called a "handle". The GATT table of SensorTag is in "Sensors and Services" of Disassemble | Simplelink Sensor Tag --TI Please refer to it as it is posted.

Now you can get your favorite sensor data! ??

(Actually, the acquired data requires conversion of LSB, MSB, etc.)

Epilogue-Conclusion

It was a pity that I couldn't get it to work on my favorite Raspberry Pi Zero, but now I'm ready to use Bluetooth from my Raspberry Pi 2!

I will continue to move forward!


The following is about troubleshooting.

pybluez Installation troubleshooting

If Python.h is not found

If you get the error fatal error: Python.h: No such file or directory, you need to install python-dev.

error contents

    arm-linux-gnueabihf-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno
-strict-aliasing -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-se
curity -fPIC -I./port3 -I/usr/include/python2.7 -c bluez/btmodule.c -o build/temp.linux-arm
v6l-2.7/bluez/btmodule.o
    In file included from bluez/btmodule.c:20:0:
    bluez/btmodule.h:4:20: fatal error: Python.h: No such file or directory
     #include "Python.h"
                        ^
    compilation terminated.
    error: command 'arm-linux-gnueabihf-gcc' failed with exit status 1
    
    ----------------------------------------
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-4nXTDu
/pybluez/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\
r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-fWWiRf-record/install-record.txt
 --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-
4nXTDu/pybluez/

Coping

$ sudo apt-get install python-dev

If bluetooth / Bluetooth.h is not found

Fatal error: bluetooth / bluetooth.h: No such file or directory as below If you get the error , you need to install libbluetooth3-dev.

error contents

    arm-linux-gnueabihf-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno
-strict-aliasing -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-se
curity -fPIC -I./port3 -I/usr/include/python2.7 -c bluez/btmodule.c -o build/temp.linux-arm
v6l-2.7/bluez/btmodule.o
    In file included from bluez/btmodule.c:20:0:
    bluez/btmodule.h:5:33: fatal error: bluetooth/bluetooth.h: No such file or directory
     #include <bluetooth/bluetooth.h>
                                     ^
    compilation terminated.
    error: command 'arm-linux-gnueabihf-gcc' failed with exit status 1
    
    ----------------------------------------
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-OWwZct
/pybluez/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\
r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-_zZYsg-record/install-record.txt
 --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-
OWwZct/pybluez/

Coping

$ sudo apt-get install libbluetooth3-dev

gattlib Installation troubleshooting

If boost / python / list.php is not found

If you get the error fatal error: boost / python / list.hpp: No such file or directory, you need to install libboost-python-dev.

error contents

    arm-linux-gnueabihf-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno
-strict-aliasing -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-se
curity -fPIC -DVERSION="5.25" -I/usr/include/glib-2.0 -I/usr/lib/arm-linux-gnueabihf/glib-2
.0/include -Isrc/bluez -I/usr/include/python2.7 -c src/gattservices.cpp -o build/temp.linux
-armv6l-2.7/src/gattservices.o
    cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not
 for C++
    In file included from src/gattservices.cpp:12:0:
    src/gattlib.h:11:33: fatal error: boost/python/list.hpp: No such file or directory
     #include <boost/python/list.hpp>
                                     ^
    compilation terminated.
    error: command 'arm-linux-gnueabihf-gcc' failed with exit status 1
    
    ----------------------------------------
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-lIdNTN
/gattlib/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\
r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-h_pTpQ-record/install-record.txt
 --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-
lIdNTN/gattlib/

Coping

$ sudo apt-get install libboost-python-dev

If glib-2.0 is not found

If you get the error No package'glib-2.0' found, as shown below, you need to install libglib2.0.

error contents

$ sudo pip install gattlib
Collecting gattlib
  Downloading gattlib-0.20150805.tar.gz (1.7MB)
    100% |████████████████████████████████| 1.7MB 86kB/s 
    Complete output from command python setup.py egg_info:
    Package glib-2.0 was not found in the pkg-config search path.
    Perhaps you should add the directory containing `glib-2.0.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'glib-2.0' found
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-ix7ocM/gattlib/setup.py", line 12, in <module>
        "pkg-config --cflags glib-2.0".split()).decode('utf-8')
      File "/usr/lib/python2.7/subprocess.py", line 573, in check_output
        raise CalledProcessError(retcode, cmd, output=output)
    subprocess.CalledProcessError: Command '['pkg-config', '--cflags', 'glib-2.0']' returne
d non-zero exit status 1
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-ix7ocM/gattli
b/

Coping

$ sudo apt-get install libglib2.0

If -lboost_thread is not found

If you get the error cannot find -lboost_thread, as shown below, you need to install libboost-thread-dev.

error contents

  c++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -
DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector-s
trong -Wformat -Werror=format-security -Wl,-z,relro -D_FORTIFY_SOURCE=2 -g -fstack-protecto
r-strong -Wformat -Werror=format-security build/temp.linux-armv7l-2.7/src/gattservices.o bu
ild/temp.linux-armv7l-2.7/src/beacon.o build/temp.linux-armv7l-2.7/src/bindings.o build/tem
p.linux-armv7l-2.7/src/gattlib.o build/temp.linux-armv7l-2.7/src/bluez/lib/uuid.o build/tem
p.linux-armv7l-2.7/src/bluez/attrib/gatt.o build/temp.linux-armv7l-2.7/src/bluez/attrib/gat
trib.o build/temp.linux-armv7l-2.7/src/bluez/attrib/utils.o build/temp.linux-armv7l-2.7/src
/bluez/attrib/att.o build/temp.linux-armv7l-2.7/src/bluez/src/shared/crypto.o build/temp.li
nux-armv7l-2.7/src/bluez/src/log.o build/temp.linux-armv7l-2.7/src/bluez/btio/btio.o -lglib
-2.0 -lboost_python -lboost_thread -lbluetooth -o build/lib.linux-armv7l-2.7/gattlib.so
  /usr/bin/ld: cannot find -lboost_thread
  collect2: error: ld returned 1 exit status
  error: command 'c++' failed with exit status 1

Coping

$ sudo apt-get install libboost-thread-dev

internal compiler error: For Killed

At the time of this error, the prompt does not come back easily, and if you think that it has returned, this error is displayed.

error contents

  arm-linux-gnueabihf-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-s
trict-aliasing -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-secu
rity -fPIC -DVERSION="5.25" -I/usr/include/glib-2.0 -I/usr/lib/arm-linux-gnueabihf/glib-2.0
/include -Isrc/bluez -I/usr/include/python2.7 -c src/bindings.cpp -o build/temp.linux-armv6
l-2.7/src/bindings.o
  cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not f
or C++
  arm-linux-gnueabihf-gcc: internal compiler error: Killed (program cc1plus)
  Please submit a full bug report,
  with preprocessed source if appropriate.
  See <file:///usr/share/doc/gcc-4.9/README.Bugs> for instructions.
  error: command 'arm-linux-gnueabihf-gcc' failed with exit status 4

Cause

This seems to be out of memory. The Raspberry Pi Zero I was trying out didn't allow me to install gattlib anymore, but with the Raspberry Pi 2 Model B I was able to install gattlib without this error.

Recommended Posts

Check! Get sensor data via Bluetooth with Raspberry Pi ~ Preparation
Get BITCOIN LTP information with Raspberry PI
Improved motion sensor made with Raspberry Pi
Use PIR motion sensor with raspberry Pi
Get GrovePi + sensor value with Raspberry Pi and store it in kintone
Media programming with Raspberry Pi (preparation for audio)
CSV output of pulse data with Raspberry Pi (CSV output)
Get CPU information of Raspberry Pi with Python
Get temperature and humidity with DHT11 and Raspberry Pi
GPGPU with Raspberry Pi
DigitalSignage with Raspberry Pi
Get data from database via ODBC with Python (Access)
Realize a super IoT house by acquiring sensor data in the house with Raspberry Pi
I tried using the DS18B20 temperature sensor with Raspberry Pi
Get US stock price from Python with Web API with Raspberry Pi
Periodically log the value of Omron environment sensor with Raspberry Pi
[Raspberry Pi] Stepping motor control with Raspberry Pi
Use vl53l0x with Raspberry Pi (python)
Servo motor control with Raspberry Pi
Serial communication with Raspberry Pi + PySerial
[Python] Get economic data with DataReader
OS setup with Raspberry Pi Imager
Try L Chika with raspberry pi
VPN server construction with Raspberry Pi
Try moving 3 servos with Raspberry Pi
Using a webcam with Raspberry Pi
A memo to simply use the illuminance sensor TSL2561 with Raspberry Pi 2
Note: I want to do home automation with Home Assistant + Raspberry Pi + sensor # 1
Logging the value of Omron environment sensor with Raspberry Pi (USB type)
Get additional data in LDAP with python
Measure SIM signal strength with Raspberry Pi
Pet monitoring with Rekognition and Raspberry pi
[Note] Get data from PostgreSQL with Python
Hello World with Raspberry Pi + Minecraft Pi Edition
Build a Tensorflow environment with Raspberry Pi [2020]
Get data from Cloudant with Bluemix flask
Try fishing for smelt with Raspberry Pi
Programming normally with Node-RED programming on Raspberry Pi 3
Use the Grove sensor on the Raspberry Pi
Try Object detection with Raspberry Pi 4 + Coral
Power SG-90 servo motor with raspberry pi
Working with sensors on Mathematica on Raspberry Pi
Make a wash-drying timer with a Raspberry Pi
Infer Custom Vision model with Raspberry Pi
Operate an oscilloscope with a Raspberry Pi
Get data from an oscilloscope with pyVISA
Create a car meter with raspberry pi
Inkbird IBS-TH1 value logged with Raspberry Pi
Working with GPS on Raspberry Pi 3 Python
I tweeted the illuminance of the room with Raspberry Pi, Arduino and optical sensor
[For beginners] I made a motion sensor with Raspberry Pi and notified LINE!
I made a Python program for Raspberry Pi that operates Omron's environmental sensor in the mode with data storage