Skip to content

AhmedFatrah2001/miband4_python

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Mi Band 4 Python Controller

A comprehensive Python library and REST API for controlling Xiaomi Mi Band 4 devices via Bluetooth Low Energy (BLE). This project provides both a command-line interface and a Flask REST API for interacting with Mi Band 4 features.

Features

πŸ”§ Core Functionality

  • Device Discovery - Find nearby Mi Band 4 devices
  • Authentication - Secure pairing with auth keys
  • Device Information - Get firmware, hardware, and serial info
  • Battery Monitoring - Check battery level and status
  • Time Management - Get/set device time

πŸ“± Notifications

  • Send custom notifications (Message, Call, Missed Call, Mail)
  • Real-time notification delivery
  • Support for custom titles and messages

🎡 Music Control

  • Set music track information
  • Control playback state
  • Receive music control events from the band

πŸƒβ€β™‚οΈ Health & Fitness (Requires Authentication)

  • Step counting and activity data
  • Heart rate monitoring (single and real-time)
  • Calorie and distance tracking

⏰ Smart Features (Requires Authentication)

  • Set and manage alarms
  • Real-time heart rate monitoring
  • Activity data retrieval

System Requirements

  • Operating System: Linux (tested on Ubuntu/Debian)
  • Python: 3.8+
  • Bluetooth: Bluetooth Low Energy (BLE) support
  • Dependencies: See requirements.txt

Installation

1. Clone the Repository

git clone https://github.com/AhmedFatrah2001/miband4_python.git
cd miband4_python

2. Set Up Virtual Environment (Recommended)

# Create virtual environment
python3 -m venv venv

# Activate virtual environment
source venv/bin/activate  # Linux/macOS
# or
venv\Scripts\activate     # Windows

3. Install System Dependencies

# Ubuntu/Debian
sudo apt-get update
sudo apt-get install libglib2.0-dev bluetooth bluez

# Fedora/RHEL
sudo dnf install glib2-devel bluez bluez-tools

# Arch Linux
sudo pacman -S glib2 bluez bluez-utils

4. Install Python Dependencies

pip install -r requirements.txt

5. Configure Your Device

Find Your Mi Band 4 MAC Address

# Scan for Bluetooth devices
sudo hcitool lescan
# or
bluetoothctl scan on

Get Authentication Key

Your Mi Band 4 requires an authentication key for full functionality. You can:

  1. Use MiFit app to pair initially and extract the key
  2. Use https://www.freemyband.com/ for non-rooted devices
  3. Root method: Extract from MiFit database

Configure Environment Variables

Create a .env file in the project root:

# Mi Band 4 Configuration
MAC_ADDRESS=XX:XX:XX:XX:XX:XX
AUTH_KEY=your32characterhexauthkey
FLASK_SECRET_KEY=your-secret-key-for-api
FLASK_HOST=0.0.0.0
FLASK_PORT=5000
FLASK_DEBUG=False

Example .env file:

MAC_ADDRESS=FD:FE:3F:DA:C0:C9
AUTH_KEY=75bff4200a13603b26647d4f33cceb69
FLASK_SECRET_KEY=miband4-secure-secret-key
FLASK_HOST=0.0.0.0
FLASK_PORT=5000
FLASK_DEBUG=False

6. Test Your Setup

# Test basic connectivity
python3 cli.py --help

# Test with your device
python3 cli.py -m XX:XX:XX:XX:XX:XX

Usage

Command Line Interface (CLI)

The CLI provides an interactive menu for all Mi Band 4 features:

# Using .env configuration
python3 cli.py

# Override with command line arguments
python3 cli.py -m XX:XX:XX:XX:XX:XX -k your_auth_key

# Show help
python3 cli.py --help

CLI Features:

  • Interactive menu system
  • Device discovery
  • Real-time heart rate monitoring
  • Custom notifications
  • Music control
  • Comprehensive testing suite

REST API Server

Start the Flask API server:

python3 app.py

The API will be available at http://localhost:5000

API Quick Start

  1. Register your device:
curl -X POST http://localhost:5000/api/register \
  -H "Content-Type: application/json" \
  -d '{"mac_address":"XX:XX:XX:XX:XX:XX","auth_key":"your_auth_key"}'
  1. Connect to device:
curl -X POST http://localhost:5000/api/connect \
  -H "Content-Type: application/json" \
  -H "X-Session-ID: your_session_id"
  1. Send a notification:
curl -X POST http://localhost:5000/api/notification \
  -H "Content-Type: application/json" \
  -H "X-Session-ID: your_session_id" \
  -d '{"type":"message","title":"Hello","message":"From API!"}'

API Documentation

Visit http://localhost:5000/api/docs for complete API documentation.

API Health Check

curl http://localhost:5000/api/health

Configuration

Environment Variables

Variable Description Default Required
MAC_ADDRESS Your Mi Band 4 MAC address None Yes
AUTH_KEY 32-character hex authentication key None For full features
FLASK_SECRET_KEY Secret key for Flask sessions Auto-generated No
FLASK_HOST Flask server host 0.0.0.0 No
FLASK_PORT Flask server port 5000 No
FLASK_DEBUG Enable Flask debug mode False No

Authentication Key

The authentication key enables advanced features:

βœ… Features WITHOUT auth key:

  • Device discovery
  • Basic device information
  • Notifications
  • Music control
  • Time reading

πŸ”’ Features REQUIRING auth key:

  • Step counting and fitness data
  • Heart rate monitoring
  • Setting device time
  • Alarms
  • Advanced device settings

Troubleshooting

Common Issues

Bluetooth Permission Errors

# Add user to bluetooth group
sudo usermod -a -G bluetooth $USER

# Restart bluetooth service
sudo systemctl restart bluetooth

Connection Timeouts

# Reset Bluetooth adapter
sudo hciconfig hci0 down
sudo hciconfig hci0 up

# Clear Bluetooth cache
sudo rm -rf /var/lib/bluetooth/*/cache
sudo systemctl restart bluetooth

Mi Band 4 Not Discoverable

  1. Ensure Mi Band 4 is not connected to phone
  2. Wake up the device
  3. Try scanning multiple times
  4. Reset the Mi Band if necessary

Authentication Failures

  1. Verify auth key format (32 hex characters)
  2. Ensure Mi Band is initially paired with MiFit
  3. Re-extract auth key after hard reset
  4. Check that MAC address hasn't changed

Debug Mode

Enable debug logging:

# CLI with debug
python3 cli.py --debug

# API with debug
FLASK_DEBUG=True python3 app.py

Development

Project Structure

miband4_python/
β”œβ”€β”€ cli.py              # Interactive command-line interface
β”œβ”€β”€ app.py              # Flask REST API server
β”œβ”€β”€ mib4.py             # Core Mi Band 4 library
β”œβ”€β”€ constants.py        # Bluetooth protocol constants
β”œβ”€β”€ requirements.txt    # Python dependencies
β”œβ”€β”€ .env               # Environment configuration
β”œβ”€β”€ .env.example       # Example environment file
└── README.md          # This file

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature-name
  3. Make your changes
  4. Test thoroughly
  5. Submit a pull request

Testing

# Run CLI tests
python3 cli.py
# Choose option 17 "Run all tests"

# Test API endpoints
python3 -m pytest tests/  # If you add tests

# Manual API testing
curl http://localhost:5000/api/health

API Endpoints Overview

Method Endpoint Description Auth Required
GET /api/health API health check No
POST /api/discover Discover devices No
POST /api/register Register device No
POST /api/connect Connect to device No
GET /api/device/info Device information No
GET /api/device/battery Battery status No
POST /api/notification Send notification No
POST /api/music Set music info No
GET /api/steps Get steps data Yes
GET /api/heart_rate Get heart rate Yes
POST /api/alarm Set alarm Yes

License

MIT License - see LICENSE file for details.

Acknowledgments

  • Freeyourgadget Team - Gadgetbridge project insights
  • Andrey Nikishaev - Mi Band 2 foundation work
  • Original Mi Band 4 reverse engineering - Community efforts

Support

Disclaimer

This project is not affiliated with Xiaomi. Use at your own risk. The authors are not responsible for any damage to your device.

About

Comprehensive Python library and REST API for Xiaomi Mi Band 4 - BLE connectivity, notifications, heart rate monitoring, music control

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages