在PC上初始化蓝牙连接android(客户端)到python(服务器)服务器部分客户

2022-09-03 08:06:34

我正在尝试从我的Android手机(三星galaxy s2)发送一个“helloWorld”(只是一个字符串)到运行linux的PC上的python脚本。但我无法让它工作。以下是android应用程序(客户端)和python脚本(服务器)的代码。蓝牙在PC和手机上工作正常(例如,我可以通过BT从手机发送照片)。当我调用btSocket.connect();在下面的java代码中,它只是不会连接。我是否必须指定要连接到的端口,因为我已为 serverSocket 指定了端口?任何帮助将不胜感激。

public class BlueTooth_testActivity extends Activity {
    TextView header;
    Button discoverDevicesBtn;
    Button sendMsgBtn;
    Button closeBtn;
    EditText sendTxt;
    BluetoothAdapter btAdapter;
    BluetoothSocket btSocket;
    private static String btAdress = "00:10:60:D1:95:CD";
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private OutputStream out;
    public BluetoothDevice device;
    private Boolean CONNECTED = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //init layout parameters        
        header = (TextView) findViewById(R.id.text1);
        discoverDevicesBtn = (Button) findViewById(R.id.discBtn);
        sendMsgBtn = (Button) findViewById(R.id.sendButton);
        closeBtn = (Button) findViewById(R.id.closeButton);
        sendTxt = (EditText) findViewById(R.id.editText1);
        discoverDevicesBtn.setOnClickListener(discoverDeviceListener);
        sendMsgBtn.setOnClickListener(sendMsgListener);
        closeBtn.setOnClickListener(closeBtnListener);
        //init bluetooth
        btAdapter = BluetoothAdapter.getDefaultAdapter();
        if (btAdapter.isEnabled()) {
            Toast.makeText(this, "Bluetooth state:" + btAdapter.getState() + " Ok!", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "Bluetooth state:" + btAdapter.getState() + " Not ok!", Toast.LENGTH_LONG).show();
        }

    }

    private Button.OnClickListener discoverDeviceListener = new Button.OnClickListener() {@Override
        public void onClick(View v) {
            if (!CONNECTED) {
                device = btAdapter.getRemoteDevice(btAdress);
                header.append("\nRemote device: " + device.getName());
                try {
                    btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
                } catch (Exception e) {
                                    }
                header.append("\n createRfcommsockettoservice! ");
                btAdapter.cancelDiscovery();
                try {
                    btSocket.connect();
                    CONNECTED = true;
                    header.append("\n btSocket Created!");
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(), "Could not connect to socket", Toast.LENGTH_LONG);
                    try {
                        btSocket.close();
                    } catch (Exception b) {}
                }
            }

        }
    };


    private Button.OnClickListener sendMsgListener = new Button.OnClickListener() {@Override
        public void onClick(View v) {
            if (CONNECTED) {
                try {
                    out = btSocket.getOutputStream();
                    String msg = sendTxt.getText().toString();
                    byte[] msgBffr = msg.getBytes();
                    out.write(msgBffr);
                    Toast.makeText(getApplicationContext(), "Message sent", Toast.LENGTH_LONG).show();
                } catch (Exception a) {
                    Toast.makeText(getApplicationContext(), "Could not send msg", Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(getApplicationContext(), "cant send msg, not connected", Toast.LENGTH_LONG).show();
            }

        }
    };


}  

(我没有费心去包含其余的java代码,因为问题出在连接设置的某个地方)

import bluetooth

name="bt_server"
target_name="siggen"
uuid="00001101-0000-1000-8000-00805F9B34FB"

def runServer():
serverSocket=bluetooth.BluetoothSocket(bluetooth.RFCOMM )
    port=bluetooth.PORT_ANY
    serverSocket.bind(("",port))
    print "Listening for connections on port: ", port   
    serverSocket.listen(1)
    port=serverSocket.getsockname()[1]
    inputSocket, address=serverSocket.accept()
    print "Got connection with" , address
    data=inputSocket.recv("1024")
    print "received [%s] \n " % data    
    inputSocket.close()
    serverSocket.close()  

runServer()  

.


答案 1

您无需指定端口,只需将您连接到第一个打开的 RFComm 通道即可。我发现我制作的蓝牙应用程序的一件事是,为了让它在我的手机上工作,我必须手动连接到运行服务器的计算机,然后再尝试在应用程序中连接。也就是说,我完成并完成所有这些操作,直到通知在我的系统托盘中弹出。然后,当我尝试通过我的应用程序建立套接字连接时,它可以正常工作。我觉得这很奇怪,因为我只需要在手机上跳过这些箍,而不是平板电脑,所以也许这取决于设备。Settings -> Wireless/Networks -> Bluetooth Settings -> <Find/Pair to Computer>

另外,您将要在单独的.Thread


答案 2

服务器部分

当涉及到python时,我已经超出了我的深度,但看起来你的python片段在任何地方都没有使用uuid。例如,pybluez 存储库有一个示例服务器,他们在调用时使用 uuid,而您的代码段中似乎没有 uuid。如果您要执行类似操作,则您的截图可能如下所示:advertise_service

import bluetooth

name="bt_server"
target_name="siggen"
uuid="00001101-0000-1000-8000-00805F9B34FB"

def runServer():
serverSocket=bluetooth.BluetoothSocket(bluetooth.RFCOMM )
    port=bluetooth.PORT_ANY
    serverSocket.bind(("",port))
    print "Listening for connections on port: ", port   
    serverSocket.listen(1)
    port=serverSocket.getsockname()[1]

    #the missing piece
    advertise_service( server_sock, "SampleServer",
                       service_id = uuid,
                       service_classes = [ uuid, bluetooth.SERIAL_PORT_CLASS ],
                       profiles = [ bluetooth.SERIAL_PORT_PROFILE ] 
                        )

    inputSocket, address=serverSocket.accept()
    print "Got connection with" , address
    data=inputSocket.recv("1024")
    print "received [%s] \n " % data    
    inputSocket.close()
    serverSocket.close()  

runServer()  

客户

BluetoothDevice.createRfcommSocketToServiceRecord() 用于创建“安全通信套接字”。这是您的服务器正在做的事情吗?如果没有,也许BluetoothDevice.createInsecureRfcommSocketToServiceRecord()是合适的调用?