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.

Note

Some installation steps may change or look slightly different depending on your Linux distro of choice.

1.1. Installation

Ubuntu is popular and highly recommended as the Linux distro of choice. Simply follow the Ubuntu install steps on the Ubuntu website :

_images/ubuntu-0.png

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

1.1.2. Bluetooth

Make sure that the Bluetooth hardware (adapter) is recognized by your OS by using the following command:

>>> hcitool dev
_images/ubuntu-1.png

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

or

>>> 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:

>>> 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.

>>> bluetoothctl

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.

1.1.3. Dongles

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.

Warning

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.

_images/vm-0.png

Steps you can take:

  1. Disable Bluetooth Adapter on Host OS
  2. Launch Guest OS
  3. Enable Bluetooth Adapter on Host OS
  4. 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.

1.1.5. Internet

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
_images/ubuntu-2.png

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:

_images/ubuntu-11.png

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:

  1. Open the System Menu on the right side of the top bar.
  2. Click on Wi-Fi Not Connected to expand the menu.
  3. Click on Select Network.
  4. 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.
  5. Enter the password for the network and click Connect.
_images/ubuntu-26.jpeg

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.

_images/ubuntu-27.png

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.

_images/ubuntu-15.png

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.

>>> python

This will launch the Python 2 interpreter.

>>> python3

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:

>>> ~/.local/lib/python3

For system-wide (i.e. using sudo pip) then usually in:

>>> /usr/local/lib/python3

And for Python packages installed by apt (apt-get) then they usually go in:

>>> /usr/lib/python3

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:

>>> /usr/local/lib/python3/dist-packages

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:

_images/python3-12.png

Please keep in mind ALL of our example scripts work with and without sudo EXCEPT for the scan_connect.py example.

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

1.2. Dependencies

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
_images/ubuntu-19.png

1.2.2. Install Compilers

Note

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.

_images/ubuntu-8.png

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

1.3. MetaWear

Finally, let’s use pip to install the metawear python package.

Note

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
_images/python3-9.jpg

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)

Note

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

_images/python-6.jpg

You can clone the repository or simply download as a ZIP file:

>>>  git clone https://github.com/mbientlab/MetaWear-SDK-Python.git
_images/ubuntu-12.png

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:

  1. MetaWear-SDK-Cpp -> The C++ metawear library pointer
  2. examples -> This is where we have many Python examples for you to look at
  3. 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 examples folder.

1.4. Usage

Import 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 scan_connect.py example.

Note

Make sure you have a MetaWear device with you, fully-charged, and that you have that device’s MAC address handy.

_images/python-8.jpg

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
_images/python-9.jpg

Warning

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.

Note

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 D8:B5:11:21:96:06.

>>>  Select your device (-1 to rescan): 1

The code will then connect to this device for 5 seconds, retrieve device information, and disconnect.

_images/python-10.jpg

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

The led.py example makes the LED on your MetaSensor blink a green color.

Note

For this example you can refer to the API documentation for LEDs here and the API references for the LED here.

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:

_images/python-11.jpg

1.6. Next Steps

Go over to our Python Developers Section to learn more about Python development.