Google Glass (클라이언트)를 내 컴퓨터 (파이썬 서버)에 연결하는 앱을 만들고 있습니다. 나는 간단한 문자열을 보내고 싶다. 여러 방법을 시도했지만 많은 운이 없었습니다. 현재 찾은 샘플 코드를 사용하고 있습니다. 모두를 실행 한 후, 내가 메시지를 얻을 Android 블루투스 클라이언트와 서버가 연결되지 않습니다.
"onResume()에서 예외 쓰기 동안 오류가 발생했습니다 : 소켓 청산"유리에
, 내 컴퓨터 (HP 파빌리온 DV6가 블루투스와 우분투 12.04를 실행 Dongle)이 완전히 얼어 버립니다. 한 번 GUI 자체가 추락하고 콘솔 (그 무서운 검은 화면)에서 스택 추적을보고있었습니다. 여기
클라이언트 코드 :import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import com.myPackage.glassbluetooth.R;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
public class ConnectTest extends Activity {
TextView out;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// Well known SPP UUID
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert your server's MAC address
private static String address = "00:1F:81:00:08:30";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
out = (TextView) findViewById(R.id.out);
out.append("\n...In onCreate()...");
btAdapter = BluetoothAdapter.getDefaultAdapter();
CheckBTState();
}
@Override
public void onStart() {
super.onStart();
out.append("\n...In onStart()...");
}
@Override
public void onResume() {
super.onResume();
out.append("\n...In onResume...\n...Attempting client connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d("CONNECTTEST", "Try to open socket");
try {
btSocket.connect();
Log.d("CONNECTTEST", "btSocket.connect executed");
out.append("\n...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
out.append("\n...Sending message to server...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
String message = "Hello from Android.\n";
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
AlertBox("Fatal Error", msg);
}
}
@Override
public void onPause() {
super.onPause();
out.append("\n...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
@Override
public void onStop() {
super.onStop();
out.append("\n...In onStop()...");
}
@Override
public void onDestroy() {
super.onDestroy();
out.append("\n...In onDestroy()...");
}
private void CheckBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
AlertBox("Fatal Error", "Bluetooth Not supported. Aborting.");
} else {
if (btAdapter.isEnabled()) {
out.append("\n...Bluetooth is enabled...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
public void AlertBox(String title, String message){
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message + " Press OK to exit.")
.setPositiveButton("OK", new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
}).show();
}
}
여기에 서버 코드 :
$ hcitool scan
Scanning ...
F4:B7:E2:F9:74:63 GLASS-YUKON
$ hcitool dev
Devices:
hci0 00:1F:81:00:08:30
사람이 어떤 생각을 가지고 있습니까 : 여기
from bluetooth import *
server_sock=BluetoothSocket(RFCOMM)
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
uuid = "1aefbf9b-ea60-47de-b5a0-ed0e3a36d9a5"
testUuid = "00001101-0000-1000-8000-00805F9B34FB"
advertise_service(server_sock, "GlassServer",
service_id = testUuid,
service_classes = [ uuid, SERIAL_PORT_CLASS ],
profiles = [ SERIAL_PORT_PROFILE ],
# protocols = [ OBEX_UUID ]
)
print("Waiting for connection on RFCOMM channel %d" % port)
client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)
try:
while True:
data = client_sock.recv(1024)
if len(data) == 0: break
print("received [%s]" % data)
except IOError:
pass
print("disconnected")
client_sock.close()
server_sock.close()
print("all done")
이 hcitool의 출력 무슨 일이야? 또한 작동 할 수있는 관련 샘플 프로그램을 알고 있다면 시도해 보는 데 관심이 있습니다! 미리 감사드립니다!
범프, 아무도 도와 드릴까요?
블루투스 기능이 내장 된 컴퓨터로 실험 한 후 조금 더 문제를 해결할 수있었습니다. 이 문제는 코드가 RFComm 소켓을 만들려고 할 때 발생합니다. 지금 가지고있는 코드를 사용하면 서비스 발견에 실패했습니다. 나는 여기에있는 조언을 사용하여 그 오류를 없앴습니다. Service discovery failed exception using Bluetooth on Android
이제 "호스트가 다운되었습니다"라는 예외가 생깁니다. 내가 찾은 수정 프로그램 중 아무 것도 작동하지 않았습니다. 어떤 아이디어?
커널 패닉 내 블루투스 동글 내 코드가 아니라 결함이 드라이버 소프트웨어에 의한되지 않습니다 :