简体   繁体   中英

Connect Android App to Python script on Mac OS X via Bluetooth

My goal is very basic. I am trying to transmit a String from my android device to my Mac running OSX 10.9 via bluetooth. On my Mac I am using the lightblue python library to do the connections. I am pretty sure that the issue is raised by a cast-like exception between what methods are expecting (more detail below). I am relatively new to this type of networking. This is ultimately going to become a rough proof of concept. Any advice would work as well.

Thanks!

Android Code (Sending String):

public class Main extends Activity {

private OutputStream outputStream;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        init();
        write("Test");

    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0){
                BluetoothDevice device = (BluetoothDevice) bondedDevices.toArray()[0];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        }else{
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
}

Adapted from: Android sample bluetooth code to send a simple string via bluetooth

Python LightBlue Example Code (Receiving String):

import lightblue

# create and set up server socket
sock = lightblue.socket()
sock.bind(("", 0))    # bind to 0 to bind to a dynamically assigned channel
sock.listen(1)
lightblue.advertise("EchoService", sock, lightblue.RFCOMM)
print "Advertised and listening on channel %d..." % sock.getsockname()[1]

conn, addr = sock.accept()
print "Connected by", addr

data = conn.recv(1024) #CRASHES HERE
print "Echoing received data:", data

# sometimes the data isn't sent if the connection is closed immediately after
# the call to send(), so wait a second
import time
time.sleep(1)

conn.close()
sock.close()

Error in console:

python test.py
Advertised and listening on channel 1...
Connected by ('78:52:1A:69:B2:6D', 1)
Traceback (most recent call last):
  File "test.py", line 16, in <module> 
    data = conn.recv(1024)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lightblue/_bluetoothsockets.py", line 470, in recv
    return self.__incomingdata.read(bufsize)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lightblue/_bluetoothsockets.py", line 150, in read
    self._build_str()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lightblue/_bluetoothsockets.py", line 135, in _build_str
    new_string = "".join(self.l_buffer)
  TypeError: sequence item 0: expected string, memoryview found

The last line is where I am pretty sure I am messing up. It is expecting a string, but I am pretty sure I am not sending a memoryview (as far as I am aware).

In your Android part, you're better off using DataOutputStream to send string. Do it like this:

public void write(String s) throws IOException {

    // outputStream.write(s.getBytes());
    // Wrap the OutputStream with DataOutputStream
    DataOutputStream dOut = new DataOutputStream(outputStream);

    // Encode the string with UTF-8
    byte[] message = s.getBytes("UTF-8");

    // Send it out
    dOut.write(message, 0, message.length);

}

Further reading: MUTF-8 (Modified UTF-8) Encoding

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