Skip to content
Advertisement

Running functions on bluetooth pair request

I’ve recently been learning electric circuitry using arduino and am looking to implement some changes to my Raspberry Pi application.

I used this outdated tutorial a few years ago to create my pi bluetooth receiver which is working well at the moment (https://www.instructables.com/id/Turn-your-Raspberry-Pi-into-a-Portable-Bluetooth-A/) but one downfall of this out-dated tutorial is that bluetooth connections have to be accepted via the screen (which is off because bluetooth speakers do not have screens).

My plan: use a button to accept bluetooth connections and use a flashing green LED to indicate a connection request.

How can I create a script that ‘listens’ for bluetooth pairing requests and run python code accordingly when its listening? With this, how can I connect to the bluetooth to accept a pair request?

I’m not too familiar with Raspberry Pi script placement, but am familiar with Python and know how I can connect to GPIO.

Thanks 🙂

Advertisement

Answer

What you are searching for is called a Bluetooth Agent. You need to use an official linux bluetooth protocol stack BlueZ. There is documentation describing the Agent API link. It uses DBus for communication. You need to invoke the following steps:

  1. Create a bluetooth agent written in python and publish it at certain DBus object path. Your agent must implement org.bluez.Agent1 interface as described in Agent API doc.
  2. Then you need to register this agent by calling RegisterAgent method from Agent API. Here you will provide the DBus path where your agent is located and also you will provide the capability in your case “DisplayYesNo” (LED as a display for pairing request, and button with some timeout for implementing Yes/No).
  3. Also register your agent as a default agent by calling RequestDefaultAgent

  4. Now if you try to pair with your device the appropriate function in your agent will be called (I think for your use case it will be RequestAuthorization) If you want to accept the pairing you will just return from this function, if you want to reject the pairing you must throw a DBus error inside this function.

As a starting point for you I would suggest you to look at this simple python Agent: https://github.com/pauloborges/bluez/blob/master/test/simple-agent It implements all the functionality you need so just update it according to your needs.

Have fun 🙂

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement