1. Python APIs¶
MetaSensors are supported on Linux. Developers can create their own Apps using Python3 on Linux.
For this tutorial, most images will reflect Ubuntu Desktop on a VM. We will also run a few commands and scripts on Raspbian OS (on a RaspberryPi).
You should be comfortable with your choice of Linux distro.
Some installation steps may change or look slightly different depending on your Linux distro of choice.
Ubuntu is popular and highly recommended as the Linux distro of choice. Simply follow the Ubuntu install steps on the Ubuntu website :
The great thing about Ubuntu is that it comes with many packages installed. Please note that if you choose to install a bare-bones Linux distro, you may need to install many utilities, libraries and packages needed to support MetaWear development.
If you are going to use Raspbian OS, we recommend the “Raspbian Buster with desktop” (or similar), the lite and the max versions have either too much or too little pre-installed. Just follow the steps here.
For any other OS, simply follow the guide on their installation site.
1.1.1. OS Updates¶
If Ubuntu or your OS asks for an update, be kind and update! Run:
>>> sudo apt-get update
To upgrade (with caution) run: – this usually takes a while, DO NOT STOP IT.
>>> sudo apt upgrade
Make sure that the Bluetooth hardware (adapter) is recognized by your OS by using the following command:
>>> hcitool dev
If your distro does not come with Bluetooth drivers installed, install the required packages with their dependencies:
>>> sudo apt install bluetooth pi-bluetooth bluez blueman bluez-utils
Check the bluetooth status:
>>> systemctl status bluetooth
Connect your Bluetooth device and restart the Bluetooth services:
>>> sudo /etc/init.d/bluetooth restart
>>> sudo systemctl start bluetooth
Verify your Bluetooth device is detected along with the appropriate modules:
>>> lsusb Device 005: ID 0a12:0001 Cambridge Silicon Radio, Ltd Bluetooth Dongle (HCI mode)
Finally review the output of
>>> hcitool dev Devices: hci0 00:11:95:00:1A:CF
You can also load the Bluetooth command-line tool, you need to enter the following command on your Raspberry Pi.
Now that we are in the Bluetooth command-line tool, we need to go ahead and turn the agent on.
Switching the agent on will allow us to search for and pair with other Bluetooth devices. You can do this by using the command below.
>>> agent on
The next step is to tell the Bluetooth device on our Raspberry Pi to scan for other devices.
By scanning for devices, we can retrieve their MAC address and begin the process of pairing that device with the Raspberry Pi. To start the scan process, all you need to do is enter the following command.
>>> scan on
From this command, you should start seeing a result like what we have below.
>>> [bluetooth]# scan on Discovery started [CHG] Controller DC:A6:32:05:7F:06 Discovering: yes [NEW] Device 51:B8:16:6A:6F:C6 51-B8-16-6A-6F-C6 [NEW] Device 40:23:43:3F:4E:58 BRAVIA 4K UR2
If you are having difficulties, please consult the community forum and manual for your OS of choice. The Ubuntu forum has already addressed many issues you may come upon.
Linux systems typically support USB to Bluetooth Dongle; they might even support multiple Dongles.
You can use these Dongles to get more sensors connected via the BLE link simultaneously.
First, plug in the USB to BLE Dongle.
Then, you can use
lsusb -t to display how the USB devices and hubs are arranged and their allocated speeds.
>>> lsusb Bus 002 Device 005: ID 0a12:0001 Cambridge Silicon Radio, Ltd Bluetooth Dongle (HCI mode)
>>> hciconfig hci0: Type: USB
>>> hciconfig -a hci0 Manufacturer: Accel Semiconductor Ltd. (74)
If it shows up as an hci device, great, you are done!
If not, there are a couple things to consider. First, you need to make sure it is actually a Linux supported dongle: https://elinux.org/RPi_USB_Bluetooth_adapters.
If your dongle is not on this list, you are out of luck and need to purchase a new one that is on the list.
If you have two of the same dongles, sometimes the second dongle may not be recognized by the system.
Once you have determined that your BLE Dongle is Linux supported, run the following commands with the Dongles plugged-in:
>>> sudo apt-get update >>> sudo apt-get upgrade >>> sudo reboot now
1.1.4. Virtual Machines (VMs)¶
If you are running in a virtual environment, you will need to take extra care to make sure the Bluetooth drivers and adapters are working in the VM before you do anything else.
For example, VirtualBox guest OS doesn’t recognize the Bluetooth adapter by default. There are many great tutorials to get this working like this one here.
Steps you can take:
- Disable Bluetooth Adapter on Host OS
- Launch Guest OS
- Enable Bluetooth Adapter on Host OS
- Enable Bluetooth Adapter in the usb device list (Guest OS): Devices->usb->check my device
You may also need to install the VirtualBox extension Pack or similar support software, see more information here.
MbientLab is not responsible for VM support. Please consult the forum for the appropriate VM software you are using if you run into issues.
You also need to make sure you have internet access. The quickest way to test this is to use ping in the terminal:
>>> ping www.google.com
Also check with:
>>> ip address show >>> ip link show
If you are having trouble, you can Google “How to connect to the internet on Ubuntu” or similar. There are many options to connect to the internet including wireless and LAN; we quickly highlight them below.
You can troubleshoot through the Ubuntu Network manager. If your local network connection isn’t working, ensure the Enable Networking and Enable Wi-Fi options are selected here in the menu:
Connect to a Wireless Network
If you have a wireless-enabled computer running the Ubuntu operating system, you can connect to a nearby wireless network to get to the internet. To do this:
- Open the System Menu on the right side of the top bar.
- Click on Wi-Fi Not Connected to expand the menu.
- Click on Select Network.
- Look through the names of the nearby networks. Select the one you want. If you don’t see the name of the network you want, click More to see additional networks. If you still don’t see the network you want, it may be hidden or you may be out of range.
- Enter the password for the network and click Connect.
Configure to a Wired Network
To set up most wired network connections, all you need to do is plug in a network cable. The wired network icon (settings) is displayed on the top bar with three dots while the connection is being established. The dots disappear when you are connected.
If this does not happen, you should first of all make sure that your network cable is plugged in. One end of the cable should be plugged into the rectangular Ethernet (network) port on your computer, and the other end should be plugged into a switch, router, network wall socket or similar (depending on the network setup you have). Sometimes, a light beside the Ethernet port will indicate that it is plugged in and active.
If you are still not connected, your network may not support automatic setup (DHCP). In this case you will have to configure it manually. Please consult the appropriate documentation.
1.1.6. Install Python3¶
You probably already have Python3 and pip3 installed.
To see which version of Python 3 you have installed, open a command prompt and run:
>>> python3 --version
If you are using Ubuntu 16.10 or newer, then you can easily install Python 3.6 with the following commands:
>>> sudo apt-get update >>> sudo apt-get install python3.6
If you’re using another version of Ubuntu (e.g. the latest LTS release), we recommend using the deadsnakes PPA to install Python 3.6:
>>> sudo apt-get install software-properties-common >>> sudo add-apt-repository ppa:deadsnakes/ppa >>> sudo apt-get update >>> sudo apt-get install python3.6
If you are using other Linux distribution, chances are you already have Python 3 pre-installed as well. If not, use your distribution’s package manager. For example on Fedora, you would use dnf:
>>> sudo dnf install python3
Note that if the version of the python3 package is not recent enough for you, there may be ways of installing more recent versions as well, depending on you distribution. For example installing the python36 package on Fedora 25 to get Python 3.6. If you are a Fedora user, you might want to read about multiple Python versions available in Fedora.
Do a final check:
>>> which python3
1.1.7. Working with Python3¶
At this point, you may have system Python 2.7 available as well.
This will launch the Python 2 interpreter.
This will launch the Python 3 interpreter.
1.1.8. Setuptools & Pip3¶
The two most crucial third-party Python packages are setuptools and pip.
Once installed, you can download, install and uninstall any compliant Python software product with a single command. It also enables you to add this network installation capability to your own Python software with very little work.
Python 3.4 and later include pip by default.
To see if pip is installed, open a command prompt and run
>>> command -v pip (or pip3)
To install pip, follow the official pip installation guide. It will look something like this:
>>> sudo apt install python3-pip
You can also use your distribution’s package manager to install these.
Note that on some Linux distributions including Ubuntu and Fedora the pip command is meant for Python 2, while the pip3 command is meant for Python 3.
>>> command -v pip3
1.1.9. Upgrade Pip3¶
It is essential that your pip be up to date. For good measure, run the commands below:
>>> pip3 install pip --upgrade >>> pip3 install --upgrade pip setuptools
1.1.10. About Pip and Python¶
When a package is installed globally, it’s made available to all users that log into the system. Typically, that means Python and all packages will get installed to a directory under /usr/local/bin/ for a Unix-based system.
Conversely, when a package is installed locally, it’s only made available to the user that installed it. Locally installed Python and all packages will be installed under a directory similar to ~/.local/bin/ for a Unix-based system.
When I use pip to install python libraries, where in the folder hierarchy do they go?
For a single user (i.e. not using sudo), usually in:
For system-wide (i.e. using sudo pip) then usually in:
And for Python packages installed by apt (apt-get) then they usually go in:
Normally Python then uses the sub-directory site-packages but Debian based installs (of which Raspbian is) use the sub-directory dist-packages. So if you do
>>> sudo pip3 install mylib
then mylib should end up in:
So keep in mind whether or not you will want to execute your python scripts with
sudo or not:
>>> python3 stream_acc.py >>> sudo python3 stream_acc.py
Both work but from different directories and you need to install packages your script will use accordingly.
You need to install the metawear pip3 package accordingly:
>>> python3 -m pip install metawear >>> sudo python3 -m pip install metawear
You can install both if you want.
Just remember, they end up in different directories. Otherwise you will get an error:
ModuleNotFoundError: No module named mbientlab.
>>> python3 -m pip install metawear <-- installed in /home/pi/.local/lib >>> sudo python3 -m pip install metawear <-- installed in /usr/local/lib
Here’s a quick example showing the different folders I have my python packages installed in:
Please keep in mind ALL of our example scripts work with and without sudo EXCEPT for the
How to list Python packages that are globally installed:
>>> pip list >>> pip freeze
How to List Python Packages that are Locally Installed:
>>> pip list --user >>> pip freeze --user metawear==0.7.0 warble==1.2.0
The metawear libraries depend on warble, bluez, and cpp compilers, let’s install those first (some may already be installed and that’s ok):
1.2.1. Install Dev tools¶
These are nice to have tools as well as the latest bluetooth packages:
>>> sudo apt-get install build-essential >>> sudo apt-get install bluez >>> sudo apt-get install libboost-all-dev >>> sudo apt-get install libbluetooth-dev
1.2.2. Install Compilers¶
If you don’t need to re-compile our C++ library, please skip this section.
Make sure that you have a C++ compiler if you intend to make modifications to our C++ libraries.
Compilers that support C++14:
>>> which g++ >>> which gcc >>> which make
Otherwise run something like
sudo apt-get install -y gcc-6 g++-6 clang-3.8. You may need to Googlefu this.
1.2.3. Install Git¶
Git is a distributed version-control system for tracking changes in source code during software development. It is designed for coordinating work among programmers, but it can be used to track changes in any set of files.
Git is nice to have if you are going to fork our repository or create your own. You can learn more about it with some Googlefu.
>>> sudo apt-get install git-core
Check that everything works:
>>> git --version
Finally, let’s use pip to install the metawear python package.
Please keep in mind you may want to install the MetaWear package with or without sudo as mentioned earlier
>>> pip3 install metawear >>> sudo pip3 install metawear
You can also run the specific command:
>>> python3 -m pip install metawear >>> sudo python3 -m pip install metawear
Metawear has dependencies including pygattlib and PyWarble. We will check some below to make sure everything installed correctly.
1.3.1. Upgrade MetaWear¶
You should always upgrade the metawear package. Run:
>>> pip3 install metawear --upgrade >>> sudo pip3 install metawear --upgrade
1.3.2. Check and Install Warble¶
MetaWear should install Warble automatically. Check to see if it installed correctly:
>>> pip3 list --user warble (local) >>> pip3 list warble (global / sudo)
If you have warble installed, skip the rest of this section.
PyWarble provides Python classes that wrap around the exported functions of the
Warble C library.
Warble wraps around the
libblepp library, which is included as a submodule of Warble.
If warble failed to install; install it with the following command:
>>> pip3 install warble >>> sudo pip3 install warble
If the pip install fails, you can download the Warble repo and build it from source (expert developers only). You will need to have BlueZ, Boost headers, and GNU Make installed along with a C++ compiler that support C++14 to run these commands:
>>> git clone https://github.com/mbientlab/Warble.git >>> git submodule update --init >>> make
1.3.3. Download the Python API Code Repository¶
Head over to our Python Github page: https://github.com/mbientlab/MetaWear-SDK-Python
You can clone the repository or simply download as a ZIP file:
>>> git clone https://github.com/mbientlab/MetaWear-SDK-Python.git
Make sure the
MetaWear-SDK-Cpp submodule is also downloaded if you intend to modify the C++ libraries (expert developers only). If it is not present, use the command
git clone --recurse-submodules https://github.com/mbientlab/MetaWear-SDK-Python
>>> git clone --recurse-submodules https://github.com/mbientlab/MetaWear-SDK-Python.git
1.3.4. About Python APIs¶
The Python APIs are build around the C++ library. There are wrapper functions to tie the C++ to the Python.
When you download our Repository, you will find:
- MetaWear-SDK-Cpp -> The C++ metawear library pointer
- examples -> This is where we have many Python examples for you to look at
- mbientlab -> This is where the bindings reside
We also have C++ API documentation here. Please keep this documentation handy.
The most important folder in the repo will be the
MetaWear class and
libmetawear variable from the metawear module and everything from the cbindings module.
>>> from mbientlab.metawear import MetaWear, libmetawear >>> from mbientlab.metawear.cbindings import *
If you do not know the MAC address of your device, use PyWarble to scan for nearby devices.
from mbientlab.warble import * from mbientlab.metawear import * from threading import Event e = Event() address = None def device_discover_task(result): global address if (result.has_service_uuid(MetaWear.GATT_SERVICE)): # grab the first discovered metawear device address = result.mac e.set() BleScanner.set_handler(device_discover_task) BleScanner.start() e.wait() BleScanner.stop()
Once you have the device’s MAC address, create a MetaWear object with the MAC address and connect to the device.
>>> device = MetaWear(address) >>> device.connect()
Upon a successful connection, you can begin calling any of the functions from the C++ SDK, for example, blinking the LED green.
pattern= LedPattern(repeat_count= Const.LED_REPEAT_INDEFINITELY) libmetawear.mbl_mw_led_load_preset_pattern(byref(pattern), LedPreset.BLINK) libmetawear.mbl_mw_led_write_pattern(device.board, byref(pattern), LedColor.GREEN) libmetawear.mbl_mw_led_play(device.board)
1.5. First Script¶
Let’s go ahead and run our first script.
Head over to the examples folder and take a look at the
Make sure you have a MetaWear device with you, fully-charged, and that you have that device’s MAC address handy.
This python code will scan for nearby Bluetooth devices and print out a list of available devices. You can then choose a device you want to connect to.
Run the code:
>>> # usage: sudo python scan_connect.py >>> sudo python3 scan_connect.py
Don’t forget you have to use
sudo to run this one example because it uses the bluetooth OS level tools which require root permissions.
If you didn’t install the
metawear package with
sudo, this may not work. That’s ok, you can still run the other scripts.
Select the device you want to connect to. The MAC address for my favorite MetaSensor is
>>> Select your device (-1 to rescan): 1
The code will then connect to this device for 5 seconds, retrieve device information, and disconnect.
As you can see, your Windows machine connected to the MetaSensor using Bluetooth and retrieved some information about the devices such as the firmware version and the manufacturer name.
Congratulations, you ran your first Python script!
1.5.1. Example Scripts¶
led.py example makes the LED on your MetaSensor blink a green color.
Try it out by running:
>>> python3 led.py D8:B5:11:21:96:06
This script connects to a specific MetaSensor by specifying the MAC address on the cmd line. Blinks the LEDs with a preset pattern and then disconnects: