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

Posted

技术标签:

【中文标题】通过蓝牙将 Android 应用程序连接到 Mac OS X 上的 Python 脚本【英文标题】:Connect Android App to Python script on Mac OS X via Bluetooth 【发布时间】:2014-09-07 11:38:09 【问题描述】:

我的目标非常基本。我正在尝试通过蓝牙将字符串从我的 android 设备传输到运行 OSX 10.9 的 Mac。在我的 Mac 上,我使用 lightblue python 库进行连接。我很确定这个问题是由预期的方法之间的类似强制转换的异常引起的(下面有更多详细信息)。我对这种类型的网络比较陌生。这最终将成为一个粗略的概念证明。任何建议都可以。

谢谢!

Android 代码(发送字符串):

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


改编自:Android sample bluetooth code to send a simple string via bluetooth

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】:

在您的 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 (Modified UTF-8) Encoding

【讨论】:

以上是关于通过蓝牙将 Android 应用程序连接到 Mac OS X 上的 Python 脚本的主要内容,如果未能解决你的问题,请参考以下文章

使用 Android 手机连接到 Mac OSX

Android:可以将蓝牙连接到自己吗?

Android 蓝牙:服务发现失败,连接到台式机/笔记本电脑

蓝牙连接到 iOS 和 android

如何从 Mac 连接到蓝牙 4.0/蓝牙 LE 设备?

无法连接到android上的蓝牙套接字