通过蓝牙将Android应用连接到Mac OS X上的Python脚本

2 投票
1 回答
1399 浏览
提问于 2025-04-18 13:35

我的目标很简单。我想通过蓝牙把一个字符串从我的安卓设备传输到运行OSX 10.9的Mac上。在我的Mac上,我使用lightblue这个Python库来建立连接。我觉得问题可能出在方法之间的类型不匹配上(下面会详细说明)。我对这种网络连接还比较陌生。这最终会成为一个粗略的概念验证。如果有任何建议也非常欢迎。

谢谢!

安卓代码(发送字符串):

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();
        }
    }
}
}

改编自:安卓示例蓝牙代码,用于通过蓝牙发送简单字符串

Python LightBlue示例代码(接收字符串):

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()

控制台中的错误:

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

最后一行是我觉得出错的地方。它期待接收到一个字符串,但我觉得我并没有发送一个内存视图(就我所知)。

1 个回答

0

在你的Android部分,使用DataOutputStream来发送字符串会更好。可以这样做:

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);

}

进一步阅读:MUTF-8(修改过的UTF-8)编码

撰写回答