2016-06-20 3 views
0
#! /usr/bin/python 

import bluetooth 
import uuid 

server_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) 

port = 1 
server_socket.bind(("",port)) 
server_socket.listen(1) 

uuID = ##generated uuid 

bluetooth.advertise_service(server_socket, "test", service_id=uuID) 

client_socket, client_address = server_socket.accept() 
print(client_socket) 
print(client_address) 

Если кто-то может помочь в этом, это было бы здорово. Я пробовал перечислить приведенные здесь инструкции примерно 5 раз: Python code for Bluetooth throws error after I had to reset the adapterошибка Bluetooth нет рекламируемого устройства

Я продолжаю получать сообщение об ошибке «bluetooth.btcommon.BluetoothError: ошибка нет рекламируемого устройства» Номер строки указывает на строку advert_service, и она делает это или не добавлять меня дополнительные параметры, как показано в примере на странице pybluez GitHub или связать порт с bluetooth.PORT_ANY метод называют здесь:

def advertise_service (sock, name, service_id = "", service_classes = [], \ 
     profiles = [], provider = "", description = "", protocols = []): 
    if service_id != "" and not is_valid_uuid (service_id): 
     raise ValueError ("invalid UUID specified for service_id") 
    for uuid in service_classes: 
     if not is_valid_uuid (uuid): 
      raise ValueError ("invalid UUID specified in service_classes") 
    for uuid, version in profiles: 
     if not is_valid_uuid (uuid) or version < 0 or version > 0xFFFF: 
      raise ValueError ("Invalid Profile Descriptor") 
    for uuid in protocols: 
     if not is_valid_uuid (uuid): 
      raise ValueError ("invalid UUID specified in protocols")   

    try: 
     _bt.sdp_advertise_service (sock._sock, name, service_id, \ 
       service_classes, profiles, provider, description, \ 
       protocols) 
    except _bt.error as e: 
     raise BluetoothError (str (e)) 

Я не могу распечатать информацию о клиенте, если я не рекламирую, и получить исключение нулевого указателя на стороне Android, поэтому я считаю, что это необходимо, но не может пройти эту ошибку, если я делаю рекламу как таковые. Это наименьшее количество кода, которое я могу получить, чтобы получить эту ошибку. Как я уже упоминал, реклама не приводит к ошибке, но я не могу распечатать информацию о клиенте на подключении (сторона андроида не может найти pi).

Если вы знаете способ сделать это без той части, вот андроида код:

Set<BluetoothDevice> pairedDevices = BTAdapter.getBondedDevices(); 
      TextView textShowConnected = (TextView) findViewById(R.id.textShowConnected); 
      if (pairedDevices.size() > 0) 
      { 
       for (BluetoothDevice device : pairedDevices) 
       { 
        if(device.getName().toString().equals("Pi")) 
        { 
         textShowConnected.setText("Found the Pi. Address is "+device.getAddress()); 
         TextView textShowConnectedSocket = (TextView) findViewById(R.id.textShowConnectedSocket); 
         //textShowConnectedSocket.setText("uuid is: "+device.getUuids()[0].getUuid().toString()); 
         try 
         { 
          BluetoothSocket connection = device.createRfcommSocketToServiceRecord(device.getUuids()[0].getUuid()); 
          //BluetoothSocket connection = device.createInsecureRfcommSocketToServiceRecord(device.getUuids()[0].getUuid()); 
          connection.connect(); 
          if(connection.isConnected()) 
          { 
           textShowConnected.setText("Is connected from second."); 
           textShowConnectedSocket.setText("Is conencted to: "+connection.getRemoteDevice().getName().toString()); 
           textShowPlace.setText("Is connected to: "+connection.getRemoteDevice().getAddress().toString()); 
          } 
          else 
          { 
           textShowConnected.setText("No connection."); 
           textShowConnectedSocket.setText("No connection."); 
           textShowPlace.setText("No connection."); 
          } 
         } 
         catch (IOException e) 
         { 
          e.printStackTrace(); 
         } 
        } 
        //DeviceItem newDevice = new DeviceItem(device.getName(), device.getAddress(), "false"); 
        //deviceItemList.add(newDevice); 
       } 
      } 
     } 

Моя последняя Java сторона попытка (только в случае, если сторона пи было хорошо):

for (BluetoothDevice device : pairedDevices) 
{ 
    if(device.getName().toString().equals("Pi")) 
    { 
     textShowConnected.setText("Found the Pi. Address is "+device.getAddress()); 
     TextView textShowConnectedSocket = (TextView) findViewById(R.id.textShowConnectedSocket); 
     TextView textShowPlace = (TextView) findViewById(R.id.textShowPlace); 
     //textShowConnectedSocket.setText("uuid is: "+device.getUuids()[0].getUuid().toString()); 
     int bt_port_to_connect = 1; 
     BluetoothSocket deviceSocket = null; 
     Method m = null; 
     try { 
      textShowPlace.setText("created socket"); 
      m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class}); 
      deviceSocket = (BluetoothSocket) m.invoke(device,bt_port_to_connect); 
      deviceSocket.connect(); 
      if(deviceSocket.isConnected()) 
      { 
       textShowPlace.setText("is connected"); 
       textShowConnectedSocket.setText("Connected successfully."); 
       textShowConnected.setText("Connected to: "+deviceSocket.getRemoteDevice().getName().toString()); 
      } 
      else 
      { 
       textShowConnectedSocket.setText("Did not connect."); 
      } 
     } 
     catch (IOException e) 
     { 
      textShowPlace.setText("catch statement "+e); 
      textShowConnectedSocket.setText("No connection."); 
     } 
     catch (NoSuchMethodException e) 
     { 
      textShowConnected.setText("No such method."); 
      textShowPlace.setText("catch statement "+e); 
     } 
     catch (InvocationTargetException e) 
     { 
      textShowPlace.setText("catch statement "+e); 
      textShowConnectedSocket.setText("No connection."); 
     } 
     catch (IllegalAccessException e) 
     { 
      textShowPlace.setText("catch statement "+e); 
      textShowConnectedSocket.setText("No connection."); 
     } 
     //device.createRfcommSocketToServiceRecord(uuid);                    
     //device.createInsecureRfcommSocketToServiceRecord(uuid); 
    } 
    //DeviceItem newDevice = new DeviceItem(device.getName(), device.getAddress(), "false"); 
    //deviceItemList.add(newDevice); 
} 

Буду признателен за любую помощь в этом процессе получения соединения. Я не уверен, что здесь испортили.

ответ

0

выглядит как рекламировать это просто необходимо: «Суд hciconfig hci0 piscan»

И подключить его нужен bluetooth.PORT_ANY от этого импорта, поэтому я маркировка это как ответил.

Кому-нибудь, кто находит это из-за собственных проблем с этим. У вас есть ответ. Удачи.

Смежные вопросы