Coder Social home page Coder Social logo

miband2's Introduction

MiBand2

Library to work with Xiaomi MiBand 2 (Support python2/python3) Read the Article here

Contributors & Info Sources

  1. Base lib provided by Leo Soares
  2. Additional debug & fixes was made by my friend Volodymyr Shymanskyy
  3. Some info that really helped i got from Freeyourgadget team

Interesting stuff

More interesing stuff about Software Developing

Run

  1. Install dependencies
pip install -r requirements.txt
  1. Turn on your Bluetooth
  2. Unpair you MiBand2 from current mobile apps
  3. Find out you MiBand2 MAC address
sudo hcitool lescan
  1. Run this to auth device
python example.py --mac MAC_ADDRESS --init
  1. Run this to call demo functions
python example.py --standard --mac MAC_ADDRESS
python example.py --help
  1. If you having problems(BLE can glitch sometimes) try this and repeat from 4)
sudo hciconfig hci0 reset

Also there is cool JS library that made Volodymyr Shymansky https://github.com/vshymanskyy/miband-js

Donate

If you like what im doing, you can send me some money for pepsi(i dont drink alcohol). https://patreon.com/mlworld

CC0
To the extent possible under law, Andrey Nikishaev has waived all copyright and related or neighboring rights to Library to work with Xiaomi MiBand 2 .

miband2's People

Contributors

aikoumei avatar askvictor avatar creotiv avatar fhantke avatar oldshaterhan avatar pablohn26 avatar typere avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

miband2's Issues

python example.py --mac MAC_ADDRESS --init

Traceback (most recent call last):
File "example.py", line 5, in
from base import MiBand2
File "/root/MiBand2/base.py", line 104
self.device.outfile.write(f"{timestamp.strftime('%d.%m.%Y - %H:%M')},{category},{intensity},{steps},{heart_rate}\n")

I can not connect to my miband 2

Hello, how are you? I'm having trouble connecting to my miband 2. I get this error right after I use it python example.py --mac F3:77:1A:30:11:BB --init can you help me?

2019-07-14 19:58:08,024 MiBand2 (INFO) > Connecting to F3:77:1A:30:11:BB
Traceback (most recent call last):
File "example.py", line 18, in
band = MiBand2(MAC, debug=True)
File "/media/joao/ae7aaea4-b12b-4927-9747-e801a8106f15/joao/Área de Trabalho/Pasta sem título/MiBand2-master/base.py", line 134, in init
Peripheral.init(self, mac_address, addrType=ADDR_TYPE_RANDOM)
File "/usr/local/lib/python2.7/dist-packages/bluepy/btle.py", line 391, in init
self._connect(deviceAddr, addrType, iface)
File "/usr/local/lib/python2.7/dist-packages/bluepy/btle.py", line 439, in _connect
raise BTLEDisconnectError("Failed to connect to peripheral %s, addr type: %s" % (addr, addrType), rsp)
bluepy.btle.BTLEDisconnectError: Failed to connect to peripheral F3:77:1A:30:11:BB, addr type: random

Read-only without pairing (Home-assistant sensor)

Hi! Is it possible to read steps+battery level from Mi Band 2 without pairing
(just by knowing MAC address ?)

I'm looking into integrating it into Home-assistant infrastructure.
It would work something like Mi Flora Sensor
Also it would allow to track presence of person at home using just bracelet.

Thank you.

Heart Rate plotting error

Hi,

I'm toying around with your lib but I can't get the plotting to work. Dumping raw data worked well but when trying to plot the results I get theses errors.

Traceback (most recent call last): File "plot.py", line 16, in <module> df.rolling(120).mean().plot() File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", line 2941, in __call__ sort_columns=sort_columns, **kwds) File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", line 1977, in plot_frame **kwds) File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", line 1804, in _plot plot_obj.generate() File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", line 266, in generate self._post_plot_logic_common(ax, self.data) File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", line 404, in _post_plot_logic_common fontsize=self.fontsize) File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", line 478, in _apply_axis_properties labels = axis.get_majorticklabels() + axis.get_minorticklabels() File "/usr/local/lib/python2.7/dist-packages/matplotlib/axis.py", line 1245, in get_majorticklabels ticks = self.get_major_ticks() File "/usr/local/lib/python2.7/dist-packages/matplotlib/axis.py", line 1396, in get_major_ticks numticks = len(self.get_major_locator()()) File "/usr/local/lib/python2.7/dist-packages/matplotlib/dates.py", line 1249, in __call__ self.refresh() File "/usr/local/lib/python2.7/dist-packages/matplotlib/dates.py", line 1269, in refresh dmin, dmax = self.viewlim_to_dt() File "/usr/local/lib/python2.7/dist-packages/matplotlib/dates.py", line 1026, in viewlim_to_dt .format(vmin)) ValueError: view limit minimum -0.001 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units
Soft revision: V1.0.1.81
Hardware revision: V0.1.3.3
System : Debian Stretch

Do you have any thoughts ?

Authorization fails

Hi,

I am trying to authorize my Mi band 2, but the device always disconnects while doing that.

Any advice?

Thanks
Jarek

pi@raspberry_router:~/MiBand2-master $ python example.py --mac CF:B9:0C:B5:07:7C --init
2019-09-13 01:51:57,573 MiBand2 (INFO) > Connecting to CF:B9:0C:B5:07:7C
2019-09-13 01:52:01,720 MiBand2 (INFO) > Connected
2019-09-13 01:52:12,019 MiBand2 (INFO) > Enabling Auth Service notifications status...
2019-09-13 01:52:12,265 MiBand2 (INFO) > Sending Key...
Traceback (most recent call last):
File "example.py", line 23, in
if band.initialize():
File "/home/pi/MiBand2-master/base.py", line 305, in initialize
self.waitForNotifications(0.1)
File "/home/pi/miniconda3/lib/python3.6/site-packages/bluepy/btle.py", line 560, in waitForNotifications
resp = self._getResp(['ntfy','ind'], timeout)
File "/home/pi/miniconda3/lib/python3.6/site-packages/bluepy/btle.py", line 407, in _getResp
resp = self._waitResp(wantType + ['ntfy', 'ind'], timeout)
File "/home/pi/miniconda3/lib/python3.6/site-packages/bluepy/btle.py", line 362, in _waitResp
raise BTLEDisconnectError("Device disconnected", resp)
bluepy.btle.BTLEDisconnectError: Device disconnected

Is it possible to use this to fetch data to magic mirror ?

Is it possible to use this to fetch data to magic mirror on raspberry pi for heart informations to display on the mirror ?
Im asking this cause i want to know if i am in the correct road to do that, or should i try something else.
with this code i can get data right ? so it will be possible then to display them with a module implementation.

Message notifications

Hi!

I'm working on a project, and i've seen different source python codes of miband. I have a question and I though you could help me with it.

The message notifications only allows to change the caller ID, and I want to know if you know how to change the content of the message. I need to know how to solve it.

Thanks,
Aurora.

Python3 - code for recorded hangs

Hey guys,
I'm running instance of this code, but unfortunately, for some reason when I run it in Python3 for old data (-r switch) it suddenly hangs on random date and time and doesn't finish it work. When I break it by Ctrl+C from traceback I see it hangs on band.waitForNotifications(0.1), what executes btle.py line 560, then 407 and 342.
Have anyone idea how to solve this issue?

Mi Band3

Hello, @creotiv,

Thanks for your project.

Will your software support the Mi Band3, have you any idea about that?

Thanks and regards

PPG data

Hello,
Can I read PPG Data from Pulse sensor ?

Any Plans to Port The Code To ESP32?

Since there are people who were able to read heart rate from the Polar H7 using ESP32, do you have plans to port the code to get data from the miband 2 using the ESP32?

what is KEY ?

What is _KEY = b'\xf5\xd2\x29\x87\x65\x0a\x1d\x82\x05\xab\x82\xbe\xb9\x38\x59\xcf' ?
can you help me ?

Difficulty implementing with a buzzer

I am trying to implement this with a buzzer and raspberry pi 3. That the condition is when the heart rate is below 60 it will alarm the buzzer but I am getting this error

typeerror:unorderable types:nonetype() < int()

i am using a code similarly to yours so I hope you could help me. Im new this sorry for my ignorance

here is the code

`#!/usr/bin/env python2
import struct
import time
import sys
import argparse
from Crypto.Cipher import AES
from bluepy.btle import Peripheral, DefaultDelegate, ADDR_TYPE_RANDOM
from gpiozero import Buzzer
from time import sleep
buzzer = Buzzer (17)
''' TODO
Key should be generated and stored during init
'''

UUID_SVC_MIBAND2 = "0000fee100001000800000805f9b34fb"
UUID_CHAR_AUTH = "00000009-0000-3512-2118-0009af100700"
UUID_SVC_ALERT = "0000180200001000800000805f9b34fb"
UUID_CHAR_ALERT = "00002a0600001000800000805f9b34fb"
UUID_SVC_HEART_RATE = "0000180d00001000800000805f9b34fb"
UUID_CHAR_HRM_MEASURE = "00002a3700001000800000805f9b34fb"
UUID_CHAR_HRM_CONTROL = "00002a3900001000800000805f9b34fb"

HRM_COMMAND = 0x15
HRM_MODE_SLEEP = 0x00
HRM_MODE_CONTINUOUS = 0x01
HRM_MODE_ONE_SHOT = 0x02

CCCD_UUID = 0x2902

class MiBand2(Peripheral):
_KEY = b'\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x40\x41\x42\x43\x44\x45'
_send_key_cmd = struct.pack('<18s', b'\x01\x08' + _KEY)
_send_rnd_cmd = struct.pack('<2s', b'\x02\x08')
_send_enc_key = struct.pack('<2s', b'\x03\x08')

def __init__(self, addr):
    Peripheral.__init__(self, addr, addrType=ADDR_TYPE_RANDOM)
    print("Connected")

    svc = self.getServiceByUUID(UUID_SVC_MIBAND2)
    self.char_auth = svc.getCharacteristics(UUID_CHAR_AUTH)[0]
    self.cccd_auth = self.char_auth.getDescriptors(forUUID=CCCD_UUID)[0]

    svc = self.getServiceByUUID(UUID_SVC_ALERT)
    self.char_alert = svc.getCharacteristics(UUID_CHAR_ALERT)[0]

    svc = self.getServiceByUUID(UUID_SVC_HEART_RATE)
    self.char_hrm_ctrl = svc.getCharacteristics(UUID_CHAR_HRM_CONTROL)[0]
    self.char_hrm = svc.getCharacteristics(UUID_CHAR_HRM_MEASURE)[0]
    self.cccd_hrm = self.char_hrm.getDescriptors(forUUID=CCCD_UUID)[0]

    self.timeout = 5.0
    self.state = None
    # Enable auth service notifications on startup
    self.auth_notif(True)
    self.waitForNotifications(0.1) # Let Mi Band to settle

def init_after_auth(self):
    self.cccd_hrm.write(b"\x01\x00", True)

def encrypt(self, message):
    aes = AES.new(self._KEY, AES.MODE_ECB)
    return aes.encrypt(message)

def auth_notif(self, status):
    if status:
        print("Enabling Auth Service notifications status...")
        self.cccd_auth.write(b"\x01\x00", True)
    elif not status:
        print("Disabling Auth Service notifications status...")
        self.cccd_auth.write(b"\x00\x00", True)
    else:
        print("Something went wrong while changing the Auth Service notifications status...")

def send_key(self):
    print("Sending Key...")
    self.char_auth.write(self._send_key_cmd)
    self.waitForNotifications(self.timeout)

def req_rdn(self):
    print("Requesting random number...")
    self.char_auth.write(self._send_rnd_cmd)
    self.waitForNotifications(self.timeout)

def send_enc_rdn(self, data):
    print("Sending encrypted random number")
    cmd = self._send_enc_key + self.encrypt(data)
    send_cmd = struct.pack('<18s', cmd)
    self.char_auth.write(send_cmd)
    self.waitForNotifications(self.timeout)

def initialize(self):
    self.setDelegate(AuthenticationDelegate(self))
    self.send_key()

    while True:
        self.waitForNotifications(0.1)
        if self.state == "AUTHENTICATED":
            return True
        elif self.state:
            return False

def authenticate(self):
    self.setDelegate(AuthenticationDelegate(self))
    self.req_rdn()

    while True:
        self.waitForNotifications(0.1)
        if self.state == "AUTHENTICATED":
            return True
        elif self.state:
            return False

def hrmStartContinuous(self):
    self.char_hrm_ctrl.write(b'\x15\x01\x01', True)
    

def hrmStopContinuous(self):
    self.char_hrm_ctrl.write(b'\x15\x01\x00', True)
    return

class AuthenticationDelegate(DefaultDelegate):

"""This Class inherits DefaultDelegate to handle the authentication process."""
def __init__(self, device):
    DefaultDelegate.__init__(self)
    self.device = device

def handleNotification(self, hnd, data):
    # Debug purposes
    #print("HANDLE: " + str(hex(hnd)))
    #print("DATA: " + str(data.encode("hex")))
    if hnd == self.device.char_auth.getHandle():
        if data[:3] == b'\x10\x01\x01':
            self.device.req_rdn()
        elif data[:3] == b'\x10\x01\x04':
            self.device.state = "ERROR: Key Sending failed"
        elif data[:3] == b'\x10\x02\x01':
            random_nr = data[3:]
            self.device.send_enc_rdn(random_nr)
        elif data[:3] == b'\x10\x02\x04':
            self.device.state = "ERROR: Something wrong when requesting the random number..."
        elif data[:3] == b'\x10\x03\x01':
            print("Authenticated!")
            self.device.state = "AUTHENTICATED"
        elif data[:3] == b'\x10\x03\x04':
            print("Encryption Key Auth Fail, sending new key...")
            self.device.send_key()
        else:
            self.device.state = "ERROR: Auth failed"
        #print("Auth Response: " + str(data.encode("hex")))
    elif hnd == self.device.char_hrm.getHandle():
        rate = struct.unpack('bb', data)[1]
        print("Heart Rate: " + str(rate))
    else:
        print("Unhandled Response " + hex(hnd) + ": " + str(data.encode("hex")))

def main():
""" main func """
parser = argparse.ArgumentParser()
parser.add_argument('host', action='store', help='MAC of BT device')
parser.add_argument('-t', action='store', type=float, default=3.0,
help='duration of each notification')

parser.add_argument('--init', action='store_true', default=False)
parser.add_argument('-n', '--notify', action='store_true', default=False)
parser.add_argument('-hrm', '--heart', action='store_true', default=False)
arg = parser.parse_args(sys.argv[1:])

print('Connecting to ' + arg.host)
band = MiBand2(arg.host)
band.setSecurityLevel(level="medium")

if arg.init:
    if band.initialize():
        print("Init OK")
    band.disconnect()
    return
else:
    band.authenticate()

band.init_after_auth()

if arg.notify:
    print("Sending message notification...")
    band.char_alert.write(b'\x01')
    time.sleep(arg.t)
    print("Sending phone notification...")
    band.char_alert.write(b'\x02')
    time.sleep(arg.t)
    print("Turning off notifications...")
    band.char_alert.write(b'\x00')

while True:
   
    band.hrmStopContinuous()
    band.hrmStartContinuous()
    for i in range(10):
        band.waitForNotifications(1.0)
    if band.hrmStopContinuous()<80:
        buzzer.on()
    else:
        buzzer.off()
       

print("Disconnecting...")
band.disconnect()
del band

if name == "main":
main()

`

Stucks on Heart rate oneshot

I changed my firmware version to one that you mentioned in previous issues. However, still, I have a problem when I run example.py it stucks on heart rate one-shot part. If I need to update my HW version, how I can do that?
FW:1.0.1.81 HW: V0.1.3.3, MiFit2 : 3.3.1›

screen shot 2018-11-11 at 12 40 03 pm

Device is not connecting error

Hi,
After connecting the device through bluetooth, I have run the example.py. I am getting error at line number 410 saying Failed to connect to the peripheral. The error remains even if the addrType is changed from random to public.

Does the library work with any other versions of MiBands?

I have MiBand 6 and want to extract the accelerometer and gyroscope data from it. Will this solution work with it? Did anyone try it?
Or if it doesn't work out of the box, maybe there are a few things i need to change to achieve the compatibility with other mi bands.
Thanks

Adapt for Amazfit Bip

Would it be possible to adapt this for a Amazfit Bip watch?
I tried it and get Authenticated. Message and Phone notif is Ok, but band.get_battery_info() dies with a TypeError: a byte-like object is required, not 'int'
Do you have an idea what to change?

--recorded breaks bc of TypeError

When I fire
python3 example.py --recorded -mac xx:xx:xx:xx:xx:xx
I receive the following exception:

File "example.py", line 34, in <module>
    band.start_get_previews_data(start_time)
  File "/home/homer77/Programming/MiBand2/base.py", line 516, in start_get_previews_data
    ts = year + month + day + hour + minute
TypeError: can't concat int to bytes

I already messed around a little with the struc.pack lines to translate everything into bytes type. But then the script breaks again because the byte type doesn't have recode method.

Is anyone able to reproduce this error?

Connecting Error

Python 3.10
Kernel 5.15.0-69-generic

Cannot init device or do something else

python example.py --mac E7:39:2F:DB:D9:E1 --init
2023-04-05 14:49:49,299 MiBand2 (INFO) > Connecting to E7:39:2F:DB:D9:E1
2023-04-05 14:49:50,739 MiBand2 (INFO) > Connected
2023-04-05 14:50:02,146 MiBand2 (INFO) > Enabling Auth Service notifications status...
2023-04-05 14:50:02,388 MiBand2 (INFO) > Sending Key...
2023-04-05 14:50:03,788 MiBand2 (INFO) > Requesting random number...
2023-04-05 14:50:03,938 MiBand2 (INFO) > Sending encrypted random number
Traceback (most recent call last):
File "/home/vkudak/software/MiBand2/MiBand2-master/example.py", line 23, in
if band.initialize():
File "/home/vkudak/software/MiBand2/MiBand2-master/base.py", line 308, in initialize
self.waitForNotifications(0.1)
File "/usr/local/lib/python3.10/dist-packages/bluepy/btle.py", line 560, in waitForNotifications
resp = self._getResp(['ntfy','ind'], timeout)
File "/usr/local/lib/python3.10/dist-packages/bluepy/btle.py", line 416, in _getResp
self.delegate.handleNotification(hnd, data)
File "/home/vkudak/software/MiBand2/MiBand2-master/base.py", line 28, in handleNotification
self.device._req_rdn()
File "/home/vkudak/software/MiBand2/MiBand2-master/base.py", line 208, in _req_rdn
self.waitForNotifications(self.timeout)
File "/usr/local/lib/python3.10/dist-packages/bluepy/btle.py", line 560, in waitForNotifications
resp = self._getResp(['ntfy','ind'], timeout)
File "/usr/local/lib/python3.10/dist-packages/bluepy/btle.py", line 416, in _getResp
self.delegate.handleNotification(hnd, data)
File "/home/vkudak/software/MiBand2/MiBand2-master/base.py", line 34, in handleNotification
self.device._send_enc_rdn(random_nr)
File "/home/vkudak/software/MiBand2/MiBand2-master/base.py", line 212, in _send_enc_rdn
cmd = self._send_enc_key + self._encrypt(data)
File "/home/vkudak/software/MiBand2/MiBand2-master/base.py", line 197, in _encrypt
aes = AES.new(self._KEY, AES.MODE_ECB)
File "/usr/local/lib/python3.10/dist-packages/Crypto/Cipher/AES.py", line 95, in new
return AESCipher(key, *args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/Crypto/Cipher/AES.py", line 59, in init
blockalgo.BlockAlgo.init(self, _AES, key, *args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/Crypto/Cipher/blockalgo.py", line 141, in init
self._cipher = factory.new(key, *args, **kwargs)
SystemError: PY_SSIZE_T_CLEAN macro must be defined for '#' formats

Issue with Installing

Hey Creotiv,

I have found an issue with your Mi Band code, when you install the requirements on a Raspberry Pi 3, it gives me the following:

Collecting bluepy (from -r requirements.txt (line 1))
Using cached https://files.pythonhosted.org/packages/85/06/0729bd5860a6658d3ddd38061caaa14914c0843cfb1305703724bd807005/bluepy-1.1.4.tar.gz
Collecting pycrypto (from -r requirements.txt (line 2))
Downloading https://files.pythonhosted.org/packages/60/db/645aa9af249f059cc3a368b118de33889219e0362141e75d4eaf6f80f163/pycrypto-2.6.1.tar.gz (446kB)
100% |████████████████████████████████| 450kB 267kB/s
Building wheels for collected packages: bluepy, pycrypto
Running setup.py bdist_wheel for bluepy ... error
Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-build-SVCm50/bluepy/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" bdist_wheel -d /tmp/tmpl_4FDupip-wheel- --python-tag cp27:
running bdist_wheel
running build
running build_py
Working dir is /tmp/pip-build-SVCm50/bluepy
execute make -C ./bluepy clean
execute make -C bluepy -j1
Failed to compile bluepy-helper. Exiting install.
Command was 'make -C bluepy -j1' in /tmp/pip-build-SVCm50/bluepy
Return code was 2
Output was:
make: Entering directory '/tmp/pip-build-SVCm50/bluepy/bluepy'
tar xzf bluez-src.tgz
touch ./bluez-5.29/lib/bluetooth.c ./bluez-5.29/lib/hci.c ./bluez-5.29/lib/sdp.c ./bluez-5.29/lib/uuid.c ./bluez-5.29/attrib/att.c ./bluez-5.29/attrib/gatt.c ./bluez-5.29/attrib/gattrib.c ./bluez-5.29/attrib/utils.c ./bluez-5.29/btio/btio.c ./bluez-5.29/src/log.c ./bluez-5.29/src/shared/mgmt.c ./bluez-5.29/src/shared/crypto.c ./bluez-5.29/src/shared/att.c ./bluez-5.29/src/shared/queue.c ./bluez-5.29/src/shared/util.c ./bluez-5.29/src/shared/io-glib.c ./bluez-5.29/src/shared/timeout-glib.c
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 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
gcc -L. -Os -g -Wall -DHAVE_CONFIG_H -I./bluez-5.29/attrib -I./bluez-5.29 -I./bluez-5.29/lib -I./bluez-5.29/src -I./bluez-5.29/gdbus -I./bluez-5.29/btio -o bluepy-helper bluepy-helper.c ./bluez-5.29/lib/bluetooth.c ./bluez-5.29/lib/hci.c ./bluez-5.29/lib/sdp.c ./bluez-5.29/lib/uuid.c ./bluez-5.29/attrib/att.c ./bluez-5.29/attrib/gatt.c ./bluez-5.29/attrib/gattrib.c ./bluez-5.29/attrib/utils.c ./bluez-5.29/btio/btio.c ./bluez-5.29/src/log.c ./bluez-5.29/src/shared/mgmt.c ./bluez-5.29/src/shared/crypto.c ./bluez-5.29/src/shared/att.c ./bluez-5.29/src/shared/queue.c ./bluez-5.29/src/shared/util.c ./bluez-5.29/src/shared/io-glib.c ./bluez-5.29/src/shared/timeout-glib.c
bluepy-helper.c:33:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
./bluez-5.29/attrib/att.c:33:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
./bluez-5.29/attrib/gatt.c:32:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
./bluez-5.29/attrib/gattrib.c:34:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
./bluez-5.29/attrib/utils.c:30:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
./bluez-5.29/btio/btio.c:37:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
./bluez-5.29/src/log.c:32:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
./bluez-5.29/src/shared/io-glib.c:30:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
./bluez-5.29/src/shared/timeout-glib.c:22:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
Makefile:28: recipe for target 'bluepy-helper' failed
make: *** [bluepy-helper] Error 1
make: Leaving directory '/tmp/pip-build-SVCm50/bluepy/bluepy'


Failed building wheel for bluepy
Running setup.py clean for bluepy
Running setup.py bdist_wheel for pycrypto ... done
Stored in directory: /home/pi/.cache/pip/wheels/27/02/5e/77a69d0c16bb63c6ed32f5386f33a2809c94bd5414a2f6c196
Successfully built pycrypto
Failed to build bluepy
Installing collected packages: bluepy, pycrypto
Running setup.py install for bluepy ... error
Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-build-SVCm50/bluepy/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-u2grqH-record/install-record.txt --single-version-externally-managed --compile --user --prefix=:
running install
running build
running build_py
Working dir is /tmp/pip-build-SVCm50/bluepy
execute make -C ./bluepy clean
execute make -C bluepy -j1
Failed to compile bluepy-helper. Exiting install.
Command was 'make -C bluepy -j1' in /tmp/pip-build-SVCm50/bluepy
Return code was 2
Output was:
make: Entering directory '/tmp/pip-build-SVCm50/bluepy/bluepy'
tar xzf bluez-src.tgz
touch ./bluez-5.29/lib/bluetooth.c ./bluez-5.29/lib/hci.c ./bluez-5.29/lib/sdp.c ./bluez-5.29/lib/uuid.c ./bluez-5.29/attrib/att.c ./bluez-5.29/attrib/gatt.c ./bluez-5.29/attrib/gattrib.c ./bluez-5.29/attrib/utils.c ./bluez-5.29/btio/btio.c ./bluez-5.29/src/log.c ./bluez-5.29/src/shared/mgmt.c ./bluez-5.29/src/shared/crypto.c ./bluez-5.29/src/shared/att.c ./bluez-5.29/src/shared/queue.c ./bluez-5.29/src/shared/util.c ./bluez-5.29/src/shared/io-glib.c ./bluez-5.29/src/shared/timeout-glib.c
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 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
gcc -L. -Os -g -Wall -DHAVE_CONFIG_H -I./bluez-5.29/attrib -I./bluez-5.29 -I./bluez-5.29/lib -I./bluez-5.29/src -I./bluez-5.29/gdbus -I./bluez-5.29/btio -o bluepy-helper bluepy-helper.c ./bluez-5.29/lib/bluetooth.c ./bluez-5.29/lib/hci.c ./bluez-5.29/lib/sdp.c ./bluez-5.29/lib/uuid.c ./bluez-5.29/attrib/att.c ./bluez-5.29/attrib/gatt.c ./bluez-5.29/attrib/gattrib.c ./bluez-5.29/attrib/utils.c ./bluez-5.29/btio/btio.c ./bluez-5.29/src/log.c ./bluez-5.29/src/shared/mgmt.c ./bluez-5.29/src/shared/crypto.c ./bluez-5.29/src/shared/att.c ./bluez-5.29/src/shared/queue.c ./bluez-5.29/src/shared/util.c ./bluez-5.29/src/shared/io-glib.c ./bluez-5.29/src/shared/timeout-glib.c
bluepy-helper.c:33:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
./bluez-5.29/attrib/att.c:33:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
./bluez-5.29/attrib/gatt.c:32:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
./bluez-5.29/attrib/gattrib.c:34:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
./bluez-5.29/attrib/utils.c:30:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
./bluez-5.29/btio/btio.c:37:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
./bluez-5.29/src/log.c:32:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
./bluez-5.29/src/shared/io-glib.c:30:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
./bluez-5.29/src/shared/timeout-glib.c:22:18: fatal error: glib.h: No such file or directory
#include <glib.h>
^
compilation terminated.
Makefile:28: recipe for target 'bluepy-helper' failed
make: *** [bluepy-helper] Error 1
make: Leaving directory '/tmp/pip-build-SVCm50/bluepy/bluepy'

----------------------------------------

Command "/usr/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-build-SVCm50/bluepy/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-u2grqH-record/install-record.txt --single-version-externally-managed --compile --user --prefix=" failed with error code 1 in /tmp/pip-build-SVCm50/bluepy/

I am an than unable to continue the steps to use example.py. If I am doing anything could you please inform me on my mistake.

Thanks for the hardwork, Sam

Heart rate oneshot does not work

example.py hangs at heart rate oneshot. Everthing else before seems to work.

I am using Miband2 with Soft revision: V1.0.0.53, Hardware revision: V0.1.3.2

spo2 sensor data

hello,
can we retrieve SPO2 sensor data from Mi Band 5?
thank

Raw acceleration data and raw heart data missing

When running example.py, there appears to be no Raw accel and Raw heart data. Perhaps the band firmware changed its instruction, or perhaps the band removed the functionality altogether.

My firmware data is as follows:

Soft revision: V1.0.1.81
Hardware revision: V0.9.3.4

Example.py hangs after 'Connected'

Hi, I followed the instructions up till running the example.py script.

After running example.py, the (INFO) > Connecting to MAC_Address moves on to (INFO) > Connected, and the code hangs/pauses infinitely. Traceback after stopping is as below:

Traceback (most recent call last):
File "example.py", line 8, in
band = MiBand2(MAC, debug=True)
File "/home/pi/MiBand2/base.py", line 85, in init
self.svc_1 = self.getServiceByUUID(UUIDS.SERVICE_MIBAND1)
File "/usr/local/lib/python2.7/dist-packages/bluepy/btle.py", line 447, in getServiceByUUID
rsp = self._getResp('find')
File "/usr/local/lib/python2.7/dist-packages/bluepy/btle.py", line 369, in _getResp
resp = self._waitResp(wantType + ['ntfy', 'ind'], timeout)
File "/usr/local/lib/python2.7/dist-packages/bluepy/btle.py", line 312, in _waitResp
rv = self._helper.stdout.readline()
KeyboardInterrupt
Exception IOError: (32, 'Broken pipe') in <bound method MiBand2.del of <base.MiBand2 instance at 0x76be3440>> ignored

Past/saved data on the MiBand2

Hello Andrey,

first, thank you for your great article and this program, I learned a lot.

I try to plot past/saved data like minutely steps since yesterday. I know it is possible as I have seen in wireshark, but I don't get it. I don't get it working for me...

Do you have any idea how it could work?

Another Issue with installing (macos)

./bluez-5.47/sys/bluetooth/bluetooth.h:36:10: fatal error: 'endian.h' file not found

❯ pip install -r requirements.txt

Collecting bluepy (from -r requirements.txt (line 1))
  Downloading https://files.pythonhosted.org/packages/27/91/6cfca10bee9862f93015413cf9e6a52c3081a71f1518963396a055128f8e/bluepy-1.3.0.tar.gz (217kB)
    100% |████████████████████████████████| 225kB 1.3MB/s 
Collecting pycrypto (from -r requirements.txt (line 2))
  Downloading https://files.pythonhosted.org/packages/60/db/645aa9af249f059cc3a368b118de33889219e0362141e75d4eaf6f80f163/pycrypto-2.6.1.tar.gz (446kB)
    100% |████████████████████████████████| 450kB 1.3MB/s 
Building wheels for collected packages: bluepy, pycrypto
  Running setup.py bdist_wheel for bluepy ... error
  Complete output from command /usr/local/opt/python@2/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/private/var/folders/fv/czs5vy5x6rx6zn__lg7ss5y80000gn/T/pip-install-kJE_cE/bluepy/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /private/var/folders/fv/czs5vy5x6rx6zn__lg7ss5y80000gn/T/pip-wheel-f2_AkG --python-tag cp27:
  running bdist_wheel
  running build
  running build_py
  Working dir is /private/var/folders/fv/czs5vy5x6rx6zn__lg7ss5y80000gn/T/pip-install-kJE_cE/bluepy
  execute make -C ./bluepy clean
  execute make -C bluepy -j1
  Failed to compile bluepy-helper. Exiting install.
  Command was 'make -C bluepy -j1' in /private/var/folders/fv/czs5vy5x6rx6zn__lg7ss5y80000gn/T/pip-install-kJE_cE/bluepy
  Return code was 2
  Output was:
  tar xzf bluez-src.tgz
  touch ./bluez-5.47/lib/bluetooth.c ./bluez-5.47/lib/hci.c ./bluez-5.47/lib/sdp.c ./bluez-5.47/lib/uuid.c ./bluez-5.47/attrib/att.c ./bluez-5.47/attrib/gatt.c ./bluez-5.47/attrib/gattrib.c ./bluez-5.47/attrib/utils.c ./bluez-5.47/btio/btio.c ./bluez-5.47/src/log.c ./bluez-5.47/src/shared/mgmt.c ./bluez-5.47/src/shared/crypto.c ./bluez-5.47/src/shared/att.c ./bluez-5.47/src/shared/queue.c ./bluez-5.47/src/shared/util.c ./bluez-5.47/src/shared/io-glib.c ./bluez-5.47/src/shared/timeout-glib.c
  cc -L. -g -Wall  -Os -DHAVE_CONFIG_H -I./bluez-5.47/attrib -I./bluez-5.47 -I./bluez-5.47/lib -I./bluez-5.47/src -I./bluez-5.47/gdbus -I./bluez-5.47/btio -I./bluez-5.47/sys -I/usr/local/Cellar/glib/2.58.3/include/glib-2.0 -I/usr/local/Cellar/glib/2.58.3/lib/glib-2.0/include -I/usr/local/opt/gettext/include -I/usr/local/Cellar/pcre/8.42/include -o bluepy-helper bluepy-helper.c ./bluez-5.47/lib/bluetooth.c ./bluez-5.47/lib/hci.c ./bluez-5.47/lib/sdp.c ./bluez-5.47/lib/uuid.c ./bluez-5.47/attrib/att.c ./bluez-5.47/attrib/gatt.c ./bluez-5.47/attrib/gattrib.c ./bluez-5.47/attrib/utils.c ./bluez-5.47/btio/btio.c ./bluez-5.47/src/log.c ./bluez-5.47/src/shared/mgmt.c ./bluez-5.47/src/shared/crypto.c ./bluez-5.47/src/shared/att.c ./bluez-5.47/src/shared/queue.c ./bluez-5.47/src/shared/util.c ./bluez-5.47/src/shared/io-glib.c ./bluez-5.47/src/shared/timeout-glib.c -L/usr/local/Cellar/glib/2.58.3/lib -L/usr/local/opt/gettext/lib -lglib-2.0 -lintl -Wl,-framework -Wl,CoreFoundation
  In file included from bluepy-helper.c:36:
  ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
  #include <endian.h>
           ^~~~~~~~~~
  1 error generated.
  In file included from ./bluez-5.47/lib/bluetooth.c:38:
  ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
  #include <endian.h>
           ^~~~~~~~~~
  1 error generated.
  In file included from ./bluez-5.47/lib/hci.c:44:
  ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
  #include <endian.h>
           ^~~~~~~~~~
  1 error generated.
  In file included from ./bluez-5.47/lib/sdp.c:45:
  ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
  #include <endian.h>
           ^~~~~~~~~~
  1 error generated.
  In file included from ./bluez-5.47/lib/uuid.c:33:
  ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
  #include <endian.h>
           ^~~~~~~~~~
  1 error generated.
  In file included from ./bluez-5.47/attrib/att.c:35:
  ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
  #include <endian.h>
           ^~~~~~~~~~
  1 error generated.
  In file included from ./bluez-5.47/attrib/gatt.c:34:
  In file included from ./bluez-5.47/lib/sdp.h:35:
  ./bluez-5.47/sys/bluetooth/bluetooth.h:36:10: fatal error: 'endian.h' file not found
  #include <endian.h>
           ^~~~~~~~~~
  1 error generated.
  In file included from ./bluez-5.47/attrib/gattrib.c:36:
  ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
  #include <endian.h>
           ^~~~~~~~~~
  1 error generated.
  In file included from ./bluez-5.47/attrib/utils.c:32:
  ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
  #include <endian.h>
           ^~~~~~~~~~
  1 error generated.
  In file included from ./bluez-5.47/btio/btio.c:39:
  ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
  #include <endian.h>
           ^~~~~~~~~~
  1 error generated.
  In file included from ./bluez-5.47/src/log.c:40:
  ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
  #include <endian.h>
           ^~~~~~~~~~
  1 error generated.
  In file included from ./bluez-5.47/src/shared/mgmt.c:33:
  ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
  #include <endian.h>
           ^~~~~~~~~~
  1 error generated.
  In file included from ./bluez-5.47/src/shared/crypto.c:33:
  ./bluez-5.47/src/shared/util.h:27:10: fatal error: 'byteswap.h' file not found
  #include <byteswap.h>
           ^~~~~~~~~~~~
  1 error generated.
  In file included from ./bluez-5.47/src/shared/att.c:34:
  ./bluez-5.47/src/shared/util.h:27:10: fatal error: 'byteswap.h' file not found
  #include <byteswap.h>
           ^~~~~~~~~~~~
  1 error generated.
  In file included from ./bluez-5.47/src/shared/queue.c:28:
  ./bluez-5.47/src/shared/util.h:27:10: fatal error: 'byteswap.h' file not found
  #include <byteswap.h>
           ^~~~~~~~~~~~
  1 error generated.
  In file included from ./bluez-5.47/src/shared/util.c:38:
  ./bluez-5.47/src/shared/util.h:27:10: fatal error: 'byteswap.h' file not found
  #include <byteswap.h>
           ^~~~~~~~~~~~
  1 error generated.
  make: *** [bluepy-helper] Error 1
  
  
  ----------------------------------------
  Failed building wheel for bluepy
  Running setup.py clean for bluepy
  Running setup.py bdist_wheel for pycrypto ... \python example.py --ma\done
  Stored in directory: /Users/mxtnr/Library/Caches/pip/wheels/27/02/5e/77a69d0c16bb63c6ed32f5386f33a2809c94bd5414a2f6c196
Successfully built pycrypto
Failed to build bluepy
Installing collected packages: bluepy, pycrypto
  Running setup.py install for bluepy ... error
    Complete output from command /usr/local/opt/python@2/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/private/var/folders/fv/czs5vy5x6rx6zn__lg7ss5y80000gn/T/pip-install-kJE_cE/bluepy/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/var/folders/fv/czs5vy5x6rx6zn__lg7ss5y80000gn/T/pip-record-6NqdRk/install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    Working dir is /private/var/folders/fv/czs5vy5x6rx6zn__lg7ss5y80000gn/T/pip-install-kJE_cE/bluepy
    execute make -C ./bluepy clean
    execute make -C bluepy -j1
    Failed to compile bluepy-helper. Exiting install.
    Command was 'make -C bluepy -j1' in /private/var/folders/fv/czs5vy5x6rx6zn__lg7ss5y80000gn/T/pip-install-kJE_cE/bluepy
    Return code was 2
    Output was:
    tar xzf bluez-src.tgz
    touch ./bluez-5.47/lib/bluetooth.c ./bluez-5.47/lib/hci.c ./bluez-5.47/lib/sdp.c ./bluez-5.47/lib/uuid.c ./bluez-5.47/attrib/att.c ./bluez-5.47/attrib/gatt.c ./bluez-5.47/attrib/gattrib.c ./bluez-5.47/attrib/utils.c ./bluez-5.47/btio/btio.c ./bluez-5.47/src/log.c ./bluez-5.47/src/shared/mgmt.c ./bluez-5.47/src/shared/crypto.c ./bluez-5.47/src/shared/att.c ./bluez-5.47/src/shared/queue.c ./bluez-5.47/src/shared/util.c ./bluez-5.47/src/shared/io-glib.c ./bluez-5.47/src/shared/timeout-glib.c
    cc -L. -g -Wall  -Os -DHAVE_CONFIG_H -I./bluez-5.47/attrib -I./bluez-5.47 -I./bluez-5.47/lib -I./bluez-5.47/src -I./bluez-5.47/gdbus -I./bluez-5.47/btio -I./bluez-5.47/sys -I/usr/local/Cellar/glib/2.58.3/include/glib-2.0 -I/usr/local/Cellar/glib/2.58.3/lib/glib-2.0/include -I/usr/local/opt/gettext/include -I/usr/local/Cellar/pcre/8.42/include -o bluepy-helper bluepy-helper.c ./bluez-5.47/lib/bluetooth.c ./bluez-5.47/lib/hci.c ./bluez-5.47/lib/sdp.c ./bluez-5.47/lib/uuid.c ./bluez-5.47/attrib/att.c ./bluez-5.47/attrib/gatt.c ./bluez-5.47/attrib/gattrib.c ./bluez-5.47/attrib/utils.c ./bluez-5.47/btio/btio.c ./bluez-5.47/src/log.c ./bluez-5.47/src/shared/mgmt.c ./bluez-5.47/src/shared/crypto.c ./bluez-5.47/src/shared/att.c ./bluez-5.47/src/shared/queue.c ./bluez-5.47/src/shared/util.c ./bluez-5.47/src/shared/io-glib.c ./bluez-5.47/src/shared/timeout-glib.c -L/usr/local/Cellar/glib/2.58.3/lib -L/usr/local/opt/gettext/lib -lglib-2.0 -lintl -Wl,-framework -Wl,CoreFoundation
    In file included from bluepy-helper.c:36:
    ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
    #include <endian.h>
             ^~~~~~~~~~
    1 error generated.
    In file included from ./bluez-5.47/lib/bluetooth.c:38:
    ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
    #include <endian.h>
             ^~~~~~~~~~
    1 error generated.
    In file included from ./bluez-5.47/lib/hci.c:44:
    ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
    #include <endian.h>
             ^~~~~~~~~~
    1 error generated.
    In file included from ./bluez-5.47/lib/sdp.c:45:
    ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
    #include <endian.h>
             ^~~~~~~~~~
    1 error generated.
    In file included from ./bluez-5.47/lib/uuid.c:33:
    ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
    #include <endian.h>
             ^~~~~~~~~~
    1 error generated.
    In file included from ./bluez-5.47/attrib/att.c:35:
    ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
    #include <endian.h>
             ^~~~~~~~~~
    1 error generated.
    In file included from ./bluez-5.47/attrib/gatt.c:34:
    In file included from ./bluez-5.47/lib/sdp.h:35:
    ./bluez-5.47/sys/bluetooth/bluetooth.h:36:10: fatal error: 'endian.h' file not found
    #include <endian.h>
             ^~~~~~~~~~
    1 error generated.
    In file included from ./bluez-5.47/attrib/gattrib.c:36:
    ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
    #include <endian.h>
             ^~~~~~~~~~
    1 error generated.
    In file included from ./bluez-5.47/attrib/utils.c:32:
    ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
    #include <endian.h>
             ^~~~~~~~~~
    1 error generated.
    In file included from ./bluez-5.47/btio/btio.c:39:
    ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
    #include <endian.h>
             ^~~~~~~~~~
    1 error generated.
    In file included from ./bluez-5.47/src/log.c:40:
    ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
    #include <endian.h>
             ^~~~~~~~~~
    1 error generated.
    In file included from ./bluez-5.47/src/shared/mgmt.c:33:
    ./bluez-5.47/lib/bluetooth.h:36:10: fatal error: 'endian.h' file not found
    #include <endian.h>
             ^~~~~~~~~~
    1 error generated.
    In file included from ./bluez-5.47/src/shared/crypto.c:33:
    ./bluez-5.47/src/shared/util.h:27:10: fatal error: 'byteswap.h' file not found
    #include <byteswap.h>
             ^~~~~~~~~~~~
    1 error generated.
    In file included from ./bluez-5.47/src/shared/att.c:34:
    ./bluez-5.47/src/shared/util.h:27:10: fatal error: 'byteswap.h' file not found
    #include <byteswap.h>
             ^~~~~~~~~~~~
    1 error generated.
    In file included from ./bluez-5.47/src/shared/queue.c:28:
    ./bluez-5.47/src/shared/util.h:27:10: fatal error: 'byteswap.h' file not found
    #include <byteswap.h>
             ^~~~~~~~~~~~
    1 error generated.
    In file included from ./bluez-5.47/src/shared/util.c:38:
    ./bluez-5.47/src/shared/util.h:27:10: fatal error: 'byteswap.h' file not found
    #include <byteswap.h>
             ^~~~~~~~~~~~
    1 error generated.
    make: *** [bluepy-helper] Error 1
    
    
    ----------------------------------------
Command "/usr/local/opt/python@2/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/private/var/folders/fv/czs5vy5x6rx6zn__lg7ss5y80000gn/T/pip-install-kJE_cE/bluepy/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/var/folders/fv/czs5vy5x6rx6zn__lg7ss5y80000gn/T/pip-record-6NqdRk/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/fv/czs5vy5x6rx6zn__lg7ss5y80000gn/T/pip-install-kJE_cE/bluepy/

MiBand2 on master took 20s ❯ python example.py --mac F0:0F:F1:A5:64:A8 --init
Traceback (most recent call last):
  File "example.py", line 5, in <module>
    from base import MiBand2
  File "/Users/mxtnr/xp/xiaomi-mi-band-2-heart-rate/MiBand2/base.py", line 5, in <module>
    from Crypto.Cipher import AES
ImportError: No module named Crypto.Cipher

I looked into https://stackoverflow.com/questions/20813028/endian-h-not-found-on-mac-osx also.
I haven't /usr/include/machine/endian.h too. I even haven't /usr/include (it's macos, not a linux huh)

I have x code entirely and I did the xcode-select --install earlier.

Project dependencies may have API risk issues

Hi, In MiBand2, inappropriate dependency versioning constraints can cause risks.

Below are the dependencies and version constraints that the project is using

bluepy==1.3.0
pycrypto==2.6.1

The version constraint == will introduce the risk of dependency conflicts because the scope of dependencies is too strict.
The version constraint No Upper Bound and * will introduce the risk of the missing API Error because the latest version of the dependencies may remove some APIs.

After further analysis, in this project,
The version constraint of dependency pycrypto can be changed to >=2.6,<=2.6.1.

The above modification suggestions can reduce the dependency conflicts as much as possible,
and introduce the latest version as much as possible without calling Error in the projects.

The invocation of the current project includes all the following methods.

The calling methods from the pycrypto
Crypto.Cipher.AES.new
The calling methods from the all methods
df.set_index.set_index
pandas.to_datetime
logging.basicConfig
self.queue.get
self._auth_notif
base.MiBand2.get_heart_rate_one_time
datetime.datetime.now.replace
self._desc_fetch.write
base.MiBand2.start_get_previews_data
hex
logging.getLogger
print
char.read.hex
self.device._char_heart_measure.getHandle
base.MiBand2.get_hrdw_revision
self.waitForNotifications
format
datetime.datetime.now
self.device.start_get_previews_data
self.device._log.error
self.device._char_activity.getHandle
self.svc_1.getCharacteristics.write
Exception
Crypto.Cipher.AES.new
base.MiBand2.get_current_time
datetime.datetime.strptime
base.MiBand2.start_raw_data_realtime
self._parse_queue
self._char_activity.getDescriptors
argparse.ArgumentParser.add_argument
self._char_auth.getDescriptors
base.MiBand2._auth_previews_data_notif
self.device.queue.put
AuthenticationDelegate
svc.getCharacteristics.read
len
self._auth_previews_data_notif
self.setDelegate
self._get_from_queue
sys.exit
datetime.timedelta
self._char_fetch.getDescriptors
base.MiBand2.get_serial
self._get_from_queue.append
self._req_rdn
self.device._send_key
self.svc_heart.getCharacteristics
self.queue.put
df.set_index.describe
self._desc_activity.write
self.heart_raw_callback
self._parse_raw_accel
self.create_date_data
argparse.ArgumentParser.parse_args
struct.pack
range
os.remove
time.sleep
self.getServiceByUUID
self.heart_measure_callback
self._parse_raw_heart
self._char_fetch.write
self.svc_heart.getCharacteristics.write
open
base.MiBand2.get_revision
char_m.getDescriptors.write
self._parse_date
self._encrypt
date.weekday
pandas.DataFrame.from_csv
self.device._send_enc_rdn
self.device._char_fetch.write
self._log.info
os.path.exists
df.set_index.head
open.write
base.MiBand2.waitForNotifications
self._desc_auth.write
self.svc_1.getCharacteristics.getDescriptors
matplotlib.pyplot.show
self.svc_1.getCharacteristics
df.rolling.mean
queue.Queue
time.time
self._char_auth.write
base.MiBand2
bluepy.btle.DefaultDelegate.__init__
bluepy.btle.Peripheral.__init__
datetime.timedelta.strftime
self._send_key
svc.getCharacteristics.write
self.device.outfile.write
base.MiBand2.disconnect
Crypto.Cipher.AES.new.encrypt
self.device._char_auth.getHandle
self.device._req_rdn
bytes
self.svc_heart.getCharacteristics.getDescriptors
base.MiBand2.get_battery_info
datetime.datetime
base.MiBand2.set_current_time
self.svc_2.getCharacteristics
base.MiBand2.initialize
self.getServiceByUUID.getCharacteristics
base.MiBand2.authenticate
self._parse_battery_response
self.device._char_fetch.getHandle
char.read.encode
self._log.error
argparse.ArgumentParser
base.MiBand2.send_alert
self.getCharacteristics
df.rolling.mean.plot
struct.unpack
int
base.MiBand2.set_heart_monitor_sleep_support
char_sensor1.getDescriptors.write
str
base.MiBand2.get_steps
self._log.setLevel
base.MiBand2.setSecurityLevel
self._char_heart_ctrl.write
base.MiBand2.start_heart_rate_realtime
self.accel_raw_callback
df.set_index.rolling

@developer
Could please help me check this issue?
May I pull a request to fix it?
Thank you very much.

AES encryption question

I am trying to port your code in to Dart. The first 2 steps of the authorization it works fine however MiBand does not like my encrypted randomkey. So I must be doing something wrong.

My Secret Key is 16 charachters long(same as yours)
The Random key MiBand gives is the same length.

Question is; How long the encrypted key that we need to send to the MiBand2 should be?
After I encrypt randomkey using SecretKey+AES I get a 32 character long value which is twice as large as the secretkey&randomkey. Is this my problem? What should I do?

Problem with installing in Termux

Traceback (most recent call last):
File "example.py", line 5, in
from base import MiBand2
File "/data/data/com.termux/files/home/MiBand2/base.py", line 5, in
from Crypto.Cipher import AES
ModuleNotFoundError: No module named 'Crypto'

Sorry if my question is stupid

I write in Termux "pip install pycrypto" but it's don't work

Help me please :)

There is a bug while running example.py

2018-03-25 01:58:29,534 MiBand2 (INFO) > Connecting to F7:DE:36:63:23:E3
Traceback (most recent call last):
File "example.py", line 8, in
band = MiBand2(MAC, debug=True)
File "/root/MiBand2/base.py", line 74, in init
Peripheral.init(self, mac_address, addrType=ADDR_TYPE_RANDOM)
File "/usr/local/lib/python2.7/dist-packages/bluepy/btle.py", line 353, in init
self._connect(deviceAddr, addrType, iface)
File "/usr/local/lib/python2.7/dist-packages/bluepy/btle.py", line 402, in _connect
"Failed to connect to peripheral %s, addr type: %s" % (addr, addrType))
bluepy.btle.BTLEException: Failed to connect to peripheral F7:DE:36:63:23:E3, addr type: random

Is there any problem with bulepy library or my hci-device? I'm running a Linux in VMware.

Raw heart rate: is each beat measured, or just BPM?

This is not an issue with the code, just a question:

Is it possible with this watch or the Mi Band 3 to read each individual heart beat, so you could display your heart beating on screen in real time?

Or does the watch just output the averaged BPM in "raw data", as seen on its own display?

I ask this, because I have PVC arrhythmias. My heart skips a beat every 4th or 8th or 20th or whatever beat (it varies all the time, god knows why). I really need a watch that can output actual raw data one way or the other, not just averaged BPM, to monitor and understand my health condition.

Why could never find mi-band-2's services' UUID while using embedded devices?

I had tried many times to use a embedded device with ble(such as arduino 101 and esp32) to connect with miband2 but it can't find it's services'uuid while scaning. It seems that miband2 is very different from other ble device. It hid it's uuid on purpose. But it works well while running this Python library on raspberry pi. What's cause this difference?

Does support MiBand2 with Raspberry Pi?

Thanks Good Source code!
Sorry to English
I am thinking RPi with MiBand2 connecting.
I need Heart Rate data.
Is it possible that RPi supports Bluetooth?
Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.