4

I wanted to use bluetooth in Python to comunicate with my robot, so I looked online for some tutorials. I've found some examples using socket module which I've used before. So I tried to use it, but I'm getting this error AttributeError: module 'socket' has no attribute 'AF_BLUETOOTH'. I've checked the official python documentation https://docs.python.org/3/library/socket.html and there it is. I'm using Windows10 and Python3.6.4 complete code:

import socket

hostMACAddress = 'adress'
port = 3
backlog = 1
size = 1024
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
s.bind((hostMACAddress,port))
s.listen(backlog)
try:
    client, address = s.accept()
    while 1:
        data = client.recv(size)
        if data:
            print(data)
            client.send(data)
except:
    print("Closing socket")
    client.close()
    s.close()
to_matih
  • 41
  • 1
  • 4

1 Answers1

0

I found this old question for a search for this error. This is not a full answer, but it may contain some useful hints.

According to the BLE Monitor FAQ this error occurs when Python has been compiled without Bluetooth support. It may also be as per the comment above that Bluetooth sockets are not available on windows - I don't have any knowledge in this area.

Here's the important text from the link above

I get AttributeError: module ‘socket’ has no attribute ‘AF_BLUETOOTH’ in Home Assistant after the installation or python upgrade

This means that Python is built/installed without support for Bluetooth. You will have to rebuild Python 3 with bluetooth.h. When using a virtual environment (venv), you can do this with the following instructions. Please make a backup first!!!, as you will have to delete the venv with Home Assistant and reinstall it in a new venv. You might need to modify commands for your own situation and the latest python version.

  1. Install BT library with

Code below (without this line formatting doesn't work)

sudo apt-get install bluetooth libbluetooth-dev
  1. Rebuild Python:

Code below (without this line formatting doesn't work)

cd Python-x.x.x/
./configure
make
sudo make install

Alternative build process. According to text in the Python Makefile "altinstall" deploys python without overwriting older versions.

./configure --enable-optimizations
sudo apt update
sudo apt install -y build-essential tk-dev libncurses5-dev libncursesw5-dev libreadline6-dev libdb5.3-dev libgdbm-dev libsqlite3-dev libssl-dev libbz2-dev libexpat1-dev liblzma-dev zlib1g-dev libffi-dev
sudo make altinstall
Tim
  • 616
  • 7
  • 23