bluetooth socket connection with bluetooth headphones / Python

228 views Asked by At

This is the occuring error message. I cant establish a bluetooth socket connection with my airpods.

Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\tkinter\__init__.py", line 1948, in __call__
    return self.func(*args)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\andre\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\customtkinter\windows\widgets\ctk_button.py", line 554, in _clicked
    self._command()
  File "C:\Users\andre\vs cpp\Python Ordner\ChatBot\BluetoothGUI.py", line 234, in <lambda>
    button = ctk.CTkButton(master=self.new_window, text=(f"{addr} - {name} "), font=('Arial', 18, 'bold'), width=30, height=2, command = lambda a=addr, n = name, s = side : self.enter_headphone(a, n, s))
                                                                                                                                                                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\andre\vs cpp\Python Ordner\ChatBot\BluetoothGUI.py", line 242, in enter_headphone
    self.headphone_user = client(str(addr).lower(), None)
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\andre\vs cpp\Python Ordner\ChatBot\BluetoothGUI.py", line 35, in __init__
    self.client.connect((mac_addr, self.PORT))
OSError: [WinError 10064] Bei einem Socketvorgang ist ein Fehler aufgetreten, da der
Zielhost nicht verfügbar war   (#added by me: english: [WinError 10064] A socket operation failed because the
Target host was not available)

Here is my client Code.

class client():
    count = 0
    def __init__(self, mac_addr, language1):
        self.client = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
        # self.client = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        self.PORT = 4
        self.HEADER = 128
        self.FORMAT = 'utf-8'
        self.client.connect((mac_addr, self.PORT))
        self.language = language1
        
        self.DISCONNECT = '!DISCONNECT'
        self.thread_queue = Queue()
        
        
        
        thread = threading.Thread(target = self.handle_server)
        thread.start()
        # self.thread_transcribe = threading.Thread(target = self.transcribe, args = (self.language,  ))
        
    def send_msg(self,msg):
        encoded_msg = msg.encode(self.FORMAT)
        msg_length = len(encoded_msg)
        send_length = str(msg_length).encode(self.FORMAT)
        send_length += b' ' * (self.HEADER - len(send_length))
        self.client.send(send_length)
        self.client.send(encoded_msg)
        
        
    def handle_server(self):
        connected = True
        try:
            while connected:
                msg_length = self.client.recv(self.HEADER).decode(self.FORMAT)
                if msg_length:
                    try:
                        msg_length = int(msg_length)
                    except:
                        msg_length = len(msg_length)
                    msg = self.client.recv(msg_length).decode(self.FORMAT)
                    if msg.startswith('[0//])'):
                        audio_recv = self.client.recv(4096)
                        audio = pickle.loads(audio_recv)
                        thread = threading.Thread(target = self.play_audio, args = (audio,))
                        self.thread_queue.put(thread)
                        self.thread_start()
        except OSError as e:
            pass
        
        self.client.close()

Here is my GUI Code:

class Retra_GUI(ctk.CTk, client):
    
   
    def __init__(self):
        ctk.set_appearance_mode('Dark')
        ctk.set_default_color_theme('green')
        self.headphone_user = None
        self.headphone_user2 = None

        self.window = ctk.CTk()
        self.window.geometry('1000x800')
        self.window.title('ReTra')
        self.window.resizable(False,False)
        title_label = ctk.CTkLabel(master = self.window, text = 'ReTra', font  = ('Arial', 36, 'bold'))
        title_label.pack(padx = 10, pady  = 10 )

        self.headset_frame = ctk.CTkFrame(master = self.window)
        self.headset_frame.pack(padx = 50, pady = 50, anchor = 'nw', fill = 'x')

        
        self.headset_one = ctk.CTkButton(master = self.headset_frame, text = 'Select Headphone', font = ('Arial', 32, 'bold'), command = lambda:  self.select_headphone('left') )
        self.headset_one.pack(padx = 10, pady = 10, side = 'left')
        self.headset_two = ctk.CTkButton(master = self.headset_frame, text = 'Select Headphone', font = ('Arial', 32, 'bold'), command = lambda: self.select_headphone('right') )
        self.headset_two.pack(padx = 10, pady = 10, side = 'right')


        self.window.mainloop()
    
    def select_headphone(self, side):
        nearby_devices = bluetooth.discover_devices(lookup_names = True)
        self.new_window = ctk.CTkToplevel(self.window)
        self.new_window.title('Select Headphone')
        self.new_window.geometry('800x600')
        i = 0
        for addr, name in nearby_devices:
                                                                                    
            button = ctk.CTkButton(master=self.new_window, text=(f"{addr} - {name} "), font=('Arial', 18, 'bold'), width=30, height=2, command = lambda a=addr, n = name, s = side : self.enter_headphone(a, n, s))
            button.grid(row=i, column=0)      
            i += 1      

    def enter_headphone(self, addr, name, side1):
        if side1 == 'left':
            print(addr.lower(), name, side1)
            
            self.headphone_user = client(str(addr).lower(), None)
            self.headset_one = ctk.CTkButton(master = self.headset_frame, text = (f"{addr} - {name} "), font = ('Arial', 32, 'bold'), command = lambda s = side1 : self.select_headphone(s))
            self.headset_one.pack(padx = 10, pady = 10, side = 'left')
        
        else:
            self.headphone_user2 = client(str(addr).lower(), None)
            self.headset_two = ctk.CTkButton(master = self.headset_frame, text = (f"{addr} - {name} "), font = ('Arial', 32, 'bold'), command = lambda s = side1 : self.select_headphone(s))
            self.headset_two.pack(padx = 10, pady = 10, side = 'right')
        self.new_window.destroy()

In the following you will se my Server Code.

I used Port = 4 just because i saw it in a video of neurallink, i think. But i dont think the mistake is in this code

Server Code (Server.py):

class server():
   

    def __init__(self, mac_adress):
        self.server = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
        
        self.PORT = 4
        self.HEADER = 128
        self.FORMAT = 'utf-8'
        self.server.bind((mac_adress, self.PORT))
        self.translator = Translator()
        self.language1 = None
        self.language2 = None
        self.connections_list = []
        self.DISCONNECT = '!DISCONNECT'
        try:
            self.server.listen()
            print('Server listening...')
            while True:
                conn, addr = self.server.accept()
                thread = threading.Thread(target = self.handle_client, args = (conn, addr))
                thread.start()
                time.sleep(0.25)
        except OSError as e:
            pass
        
        self.server.close()
    # More irrelevant code...

I am very thankfull for every answer and please dont mind my english!

(moduls I imported:)

import customtkinter as ctk
import socket
import uuid
import time
import threading

import speech_recognition as sr
from datetime import datetime, timedelta
from googletrans import Translator
from gtts import gTTS
from pydub import AudioSegment
from pydub.playback import play
import nltk
from langid import classify
import random

import pickle
import os

import bluetooth
from gtts.lang import tts_langs
from queue import Queue

Hello. I am trying to connect my bluetooth headphones (airpods) with my pc. I use the modul socket to establish a socket connection with the server(pc), the client(headphones), and the modul bluetooth to determine the mac adress of the airpods. I also integrated a GUI with customtkinter. I achieved creating a bluetooth socket connection between my second laptop(client) and my main laptop(server), but if i try connecting my airpods following error message comes up:

Or is their a possibility that the moduls pybluez oder socket are not able to pair?

0

There are 0 answers