2014-07-16 7 views
2

내 목표는 매우 기본입니다. 내 안드로이드 장치에서 OSX 10.9를 실행하는 Mac으로 Bluetooth를 통해 String을 전송하려고합니다. 내 Mac에서는 lightblue python 라이브러리를 사용하여 연결합니다. 나는이 문제가 어떤 메소드가 기대하고있는 것 사이의 캐스트와 같은 예외에 의해 제기된다는 것을 확신한다. 나는이 유형의 네트워킹에 상대적으로 새로운 것이다. 이것은 궁극적으로 개념의 대략적인 증거가 될 것입니다. 어떤 조언도 잘 작동합니다.블루투스를 통해 Mac OS X의 Python 스크립트에 Android 앱 연결

감사합니다.

안드로이드 코드 (문자열 전송) : (문자열 받기) Android sample bluetooth code to send a simple string via bluetooth

파이썬 연한 파랑 예제 코드 : 콘솔에서

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 

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

에서 적응

마지막 줄은 내가 엉망이라고 확신하는 곳입니다. 그것은 문자열을 기대하고 있지만, 나는 내가 아는 한 memoryview를 보내지 않을 것이라고 확신한다.

답변

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