简体   繁体   中英

How to build Android Bluetooth server app handling data sent from Raspberry Pi using pybluez

I was wondering how to build Android app handling data sent from Raspberry pi.

I installed pybluez module on Raspberry Pi and send data using following python script.

import bluetooth
port = 1
sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((targetBluetoothMacAddress, port)) 
                      #targetBluetoothMacAddress is my phone MacAddress
sock.send("hello!!")
sock.close()

On my phone I did see two devices paired successfully. But can not find a way to get data sent from Raspberry Pi. Is there a way to build an app handling data from sock.send()?

You need to consult the Android Bluetooth APIs, but yes you can build an app pretty easily. First what you'll wanna do is get a reference to the BluetoothDevice that represents the Raspberry Pi you wanna connect to. You can do this by calling BluetoothAdapter.startDiscovery() or by directly asking the framework for a device with the MAC address of the Raspberry Pi by calling BluetoothAdapter.getRemoteDevice(...) .

Once you get have the device you'll wanna open BluetoothSocket with the device. To do this call createRfcommSocketToServiceRecord(UUID) . The UUID argument will more thank likely "0001101-0000-1000-8000-00805F9B34FB" if you're connecting to the Raspberry Pi using SPP. The create method will return to you a BluetoothSocket which you will need to call connect() on. Note, connect is a blocking call and you will need to perform all this work in a worker thread to prevent locking up your UI. If connect returns successfully you've successfully connected with the device. In order to achieve back and forth communication with the device, you'll need to get ahold to it's Input and Output streams by calling the following two methods getInputStream() and getOutputStream() on BluetoothSocket .

Once you have these two streams you can send byte data back and forth between the two devices. note that reading and writing from the steams are blocking operations so I recommend creating two separate threads for reading and writing data, passing in the streams and a Handler into the thread constructor so you can send back data back to the UI thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM