SimplePyBLE - Python bindings for SimpleBLE

Overview

SimplePyBLE - Python bindings for SimpleBLE

The ultimate fully-fledged cross-platform BLE library, designed for simplicity and ease of use.

All specific operating system quirks are handled to provide a consistent behavior across all platforms. Each major version of the library will have a stable API that will be fully forwards compatible.

If you want to use the library and need help. Please reach out! You can find me at: kevin at dewald dot me

Instalation

pip install simplepyble

Usage

Please review the provided examples in the source code. They are all self-contained and can be run from the command line. More documentation will be available soon.

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

License

All components within this project that have not been bundled from external creators, are licensed under the terms of the MIT Licence.

Comments
  • Repeated read gives always the same value

    Repeated read gives always the same value

    It seems that reading value from characteristic from peripheral never gets updated during one connection, multiple reads during the same connection always give me the same value, even when the characteristic is updated on the service side. I did a test, I created a peripheral with service with 2 text characteristics, A for writing and B for reading. On the service side, when A is written , B is updated. When I do the the connection to this peripheral and then the sequence: write - read - write different value - read, the second read gives me the value from the first read, it never gets updated. When I disconnect from peripheral and connect again, read gives me updated second value. Is this a "feature" or the bug?

    opened by piotromt 11
  • peripheral.identifier() in the scan example always return an empty string.

    peripheral.identifier() in the scan example always return an empty string.

    I am running the scan.py example on windows 10 pro, Python 3.9.5. Everything works well except that the device names are not printed. I think it's supposed to come from peripheral.identifier() but it seems to return an empty string for all devices.

    By device name I mean the human friendly name that we see in the bluetooth device setting screens of Windows, iPhone, etc.

    opened by zapta 5
  • Please expose the pairing related methods in the Python API

    Please expose the pairing related methods in the Python API

    These two pairing related methods are not reflected in the Python API.

    Please add them there.

    https://github.com/OpenBluetoothToolbox/SimpleBLE/blob/main/include/simpleble/Peripheral.h#L32

    opened by zapta 3
  • peripheral.read: UnicodeDecodeError: 'utf-8' codec can't decode byte

    peripheral.read: UnicodeDecodeError: 'utf-8' codec can't decode byte

    Windows 10; python 3.9.7

    import simplepyble
    import random
    import threading
    import time
    from Crypto.Cipher import AES
    from Crypto.Random import get_random_bytes
    
    def encrypt(key, data):
      k = AES.new(bytes(reversed(key)), AES.MODE_ECB)
      data = reversed(list(k.encrypt(bytes(reversed(data)))))
      rev = []
      for d in data:
        rev.append(d)
      return rev
    
    
    def key_encrypt(name, password, key):
      name = name.ljust(16, chr(0))
      password = password.ljust(16, chr(0))
      data = [ord(a) ^ ord(b) for a,b in zip(name,password)]
      return encrypt(key, data)
    
    class dimond:
      def __init__(self, vendor, mac, name, password, mesh=None, callback=None):
        self.vendor = vendor
        self.mac = mac
        self.macarray = mac.split(':')
        self.name = name
        self.password = password
        self.callback = callback
        self.mesh = mesh
        self.packet_count = random.randrange(0xffff)
        self.macdata = [int(self.macarray[5], 16), int(self.macarray[4], 16), int(self.macarray[3], 16), int(self.macarray[2], 16), int(self.macarray[1], 16), int(self.macarray[0], 16)]
      
      def __done__(self):
        self.peripheral.disconnect()
    
      def set_sk(self, sk):
        self.sk = sk
    
      def connect(self):
        #self.device = btle.Peripheral(self.mac, addrType=btle.ADDR_TYPE_PUBLIC)
        adapters = simplepyble.Adapter.get_adapters()
    
        if len(adapters) == 0:
            print("No adapters found")
    
        # Query the user to pick an adapter
        adapter = adapters[0]
    
        print(f"Selected adapter: {adapter.identifier()} [{adapter.address()}]")
    
        adapter.set_callback_on_scan_start(lambda: print("Scan started."))
        adapter.set_callback_on_scan_stop(lambda: print("Scan complete."))
        adapter.set_callback_on_scan_found(lambda peripheral: (peripheral.address() == self.mac) and print(f"Found {peripheral.identifier()} [{peripheral.address()}]"))
    
        # Scan for 5 seconds
        adapter.scan_for(5000)
        peripherals = adapter.scan_get_results()
        
        self.peripheral = None
        # Query the user to pick a peripheral
        for i, p in enumerate(peripherals):
            if p.address() == self.mac:
                self.peripheral = p
                break
    
        if (self.peripheral):
            connectable_str = "Connectable" if self.peripheral.is_connectable() else "Non-Connectable"
            print(f"{self.peripheral.identifier()} [{self.peripheral.address()}] - {connectable_str}")
    
            manufacturer_data = self.peripheral.manufacturer_data()
            for manufacturer_id, value in manufacturer_data.items():
                print(f"    Manufacturer ID: {manufacturer_id}")
                print(f"    Manufacturer data: {value}")
    
            print(f"Connecting to: {self.peripheral.identifier()} [{self.peripheral.address()}]")
            self.peripheral.connect()
            '''
            print("Successfully connected, listing services...")
            services = self.peripheral.services()
            for service in services:
                print(f"Service: {service.uuid}")
                for characteristic in service.characteristics:
                    print(f"    Characteristic: {characteristic}")
            '''
            self.notification = '00010203-0405-0607-0809-0a0b0c0d1911'
            self.control = '00010203-0405-0607-0809-0a0b0c0d1912'
            self.pairing = '00010203-0405-0607-0809-0a0b0c0d1914'
           
            data = [0] * 16
            random_data = get_random_bytes(8)
            for i in range(8):
              data[i] = random_data[i]
            enc_data = key_encrypt(self.name, self.password, data)
            packet = [0x0c]
            packet += data[0:8]
            packet += enc_data[0:8]
            try:
              self.peripheral.write_request('00010203-0405-0607-0809-0a0b0c0d1910', self.pairing, bytes(packet))
              time.sleep(0.3)
              data2 = self.peripheral.read('00010203-0405-0607-0809-0a0b0c0d1910', self.pairing)
            except:
              raise Exception("Unable to connect")
            
            print('Ok!')
    
        else:
            print('BT device "{}" not found!'.format(target_mac))
    
    target_mac = '08:65:f0:04:04:e1'
    
    if __name__ == "__main__":
        network = dimond(0x0211, target_mac, "ZenggeMesh", "ZenggeTechnology")#, callback=callback)
        network.connect()
    
    (base) D:\work\btdimmer>python btdimmer.py
    Selected adapter: dongle [00:1a:7d:da:71:12]
    Scan started.
    Found abd8302448845239 [08:65:f0:04:04:e1]
    Scan complete.
    abd8302448845239 [08:65:f0:04:04:e1] - Connectable
        Manufacturer ID: 529
        Manufacturer data: b'\x11\x02\xe1\x04\x04\xf0\x02\x0f\x01\x02\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
    Connecting to: abd8302448845239 [08:65:f0:04:04:e1]
    Traceback (most recent call last):
      File "D:\work\btdimmer\btdimmer.py", line 109, in connect
        data2 = self.peripheral.read('00010203-0405-0607-0809-0a0b0c0d1910', self.pairing)
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0x86 in position 1: invalid start byte
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "D:\work\btdimmer\btdimmer.py", line 122, in <module>
        network.connect()
      File "D:\work\btdimmer\btdimmer.py", line 111, in connect
        raise Exception("Unable to connect")
    Exception: Unable to connect
    
    (base) D:\work\btdimmer>
    
    opened by zenbooster 2
  • How to pair with BLE device?

    How to pair with BLE device?

    Hi, I am using Library "simplepyble". It is looking very simple and easy to use but I didn't find any method or syntax for pairing or bonding in the examples. Can you please guide me on how I can pair my PC with my BLE device using "simplepyble". Thanks.

    opened by inamghouss 1
  • run example scan.py error: Process finished with exit code -1073741819 (0xC0000005)

    run example scan.py error: Process finished with exit code -1073741819 (0xC0000005)

    some details window10 python => 3.8.5 simplepyble => 0.0.5

    sometimes return an empty string for all devices, sometimes return error Process finished with exit code -1073741819 (0xC0000005)

    opened by fanleung 0
Releases(v0.0.5)
  • v0.0.5(Jun 13, 2022)

    [0.0.5] - 2022-06-12

    Added

    • Python's Global Interpreter Lock (GIL) will be released during Peripheral.connect()
    • Keep-alive policies for function objects passed into SimplePyBLE.
    Source code(tar.gz)
    Source code(zip)
  • v0.0.4(Feb 14, 2022)

  • v0.0.3(Feb 13, 2022)

    [0.0.3] - 2022-01-22

    Fixed

    • write_request and write_command functions would accept strings instead of bytes as payloads. (Thanks kaedenbrinkman!)
    Source code(tar.gz)
    Source code(zip)
  • v0.0.2(Jan 16, 2022)

  • v0.0.1(Jan 11, 2022)

Owner
Open Bluetooth Toolbox
Tools and code for Bluetooth development
Open Bluetooth Toolbox
A compiler for ARM, X86, MSP430, xtensa and more implemented in pure Python

A compiler for ARM, X86, MSP430, xtensa and more implemented in pure Python

Windel Bouwman 277 Dec 26, 2022
Paxos in Python, tested with Jepsen

Python implementation of Multi-Paxos with a stable leader and reconfiguration, roughly following "Paxos Made Moderately Complex". Run python3 paxos/st

A. Jesse Jiryu Davis 25 Dec 15, 2022
Superset custom path for python

It is a common requirement to have superset running under a base url, (https://mydomain.at/analytics/ instead of https://mydomain.at/). I created the

9 Dec 14, 2022
Uma moeda simples e segura!

SecCoin - Documentação A SecCoin foi criada com intuito de ser uma moeda segura, de fácil investimento e mineração. A Criptomoeda está na sua primeira

Sec-Coin Team 5 Dec 09, 2022
Singularity Containers on Apple M1 (ARM64)

Singularity Containers on Apple M1 (ARM64) This is a repository containing a ready-to-use environment for singularity in arm64 (M1). It has been prepa

Manuel Parra 4 Nov 14, 2022
《practical python programming》的中文翻译

欢迎光临 大约 25 年前,当我第一次学习 Python 时,发现 Python 竟然可以被高效地应用到各种混乱的工作项目上,我立即被震惊了。15 年前,我自己也将这种乐趣教授给别人。教学的结果就是本课程——一门实用的学习 Python的课程。

编程人 125 Dec 17, 2022
Python bindings for `ign-msgs` and `ign-transport`

Python Ignition This project aims to provide Python bindings for ignition-msgs and ignition-transport. It is a work in progress... C++ and Python libr

Rhys Mainwaring 3 Nov 08, 2022
A conda-smithy repository for boost-histogram.

The official Boost.Histogram Python bindings. Provides fast, efficient histogramming with a variety of different storages combined with dozens of composable axes. Part of the Scikit-HEP family.

conda-forge 0 Dec 17, 2021
Resources for the 2021 offering of COMP 598

comp598-2021 Resources for the 2021 offering of COMP 598 General submission instructions Important Please read these instructions located in the corre

Derek Ruths 23 May 18, 2022
Minimalistic Gridworld Environment (MiniGrid)

Minimalistic Gridworld Environment (MiniGrid) There are other gridworld Gym environments out there, but this one is designed to be particularly simple

Maxime Chevalier-Boisvert 1.7k Jan 03, 2023
Simple dependency injection framework for Python

A simple, strictly typed dependency injection library.

BentoML 14 Jun 29, 2022
Repositório contendo atividades no curso de desenvolvimento de sistemas no SENAI

SENAI-DES Este é um repositório contendo as atividades relacionadas ao curso de desenvolvimento de sistemas no SENAI. Se é a primeira vez em contato c

Abe Hidek 4 Dec 06, 2022
This collection is to provide an easier way to interact with Juniper

Ansible Collection - cremsburg.apstra Overview The goal of this collection is to provide an easier way to interact with Juniper's Apstra solution. Whi

Calvin Remsburg 1 Jan 18, 2022
Files for QMC Workshop 2021

QMC Workshop 2021 This repository contains the presented slides and example files for the Quantum Monte Carlo (QMC) Workshop 5 October - 23 November,

QMCPACK 39 Nov 04, 2022
Hydralit package is a wrapping and template project to combine multiple independant Streamlit applications into a multi-page application.

Hydralit The Hydralit package is a wrapping and template project to combine multiple independant (or somewhat dependant) Streamlit applications into a

Jackson Storm 108 Jan 08, 2023
Submission to the HEAR2021 Challenge

Submission to the HEAR 2021 Challenge For model evaluation, python=3.8 and cuda10.2 with cudnn7.6.5 have been tested. The work uses a mixed supervised

Heinrich Dinkel 10 Dec 08, 2022
Framework To Ease Operating with Quantum Computers

QType Framework To Ease Operating with Quantum Computers Concept # define an array of 15 cubits:

Antonio Párraga Navarro 2 Jun 06, 2022
Build Xmas cards with user inputs

Automatically build Xmas cards with user inputs

Anand 9 Jan 25, 2022
Process GPX files (adding sensor metrics, uploading to InfluxDB, etc.) exported from imxingzhe.com

Xingzhe GPX Processor 行者轨迹处理工具 Xingzhe sells cheap GPS bike meters with sensor support including cadence, heart rate and power. But the GPX files expo

Shengqi Chen 8 Sep 23, 2022
A Python application that helps users determine their calorie intake, and automatically generates customized weekly meal and workout plans based on metrics computed using their physical parameters

A Python application that helps users determine their calorie intake, and automatically generates customized weekly meal and workout plans based on metrics computed using their physical parameters

Anam Iqbal 1 Jan 13, 2022