Estoy tratando de enviar un "helloWorld" (solo una cadena) desde mi teléfono Android (samsung galaxy s2) a una secuencia de comandos python en mi pc con Linux. Pero no puedo hacer que funcione. A continuación se muestra el código para la aplicación de Android (cliente) y el script de python (servidor). El bluetooth funciona bien en la PC y el teléfono (por ejemplo, puedo enviar fotos desde el teléfono a través de BT). Cuando llamo a btSocket.connect(); en el código de Java debajo simplemente no se conecta. ¿Tengo que especificar un puerto para conectarme, ya que he especificado un puerto para serverSocket? Cualquier ayuda sería muy apreciada.Inicializando la conexión bluetooth android (cliente) a python (servidor) en la pc
public class BlueTooth_testActivity extends Activity {
TextView header;
Button discoverDevicesBtn;
Button sendMsgBtn;
Button closeBtn;
EditText sendTxt;
BluetoothAdapter btAdapter;
BluetoothSocket btSocket;
private static String btAdress = "00:10:60:D1:95:CD";
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private OutputStream out;
public BluetoothDevice device;
private Boolean CONNECTED = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//init layout parameters
header = (TextView) findViewById(R.id.text1);
discoverDevicesBtn = (Button) findViewById(R.id.discBtn);
sendMsgBtn = (Button) findViewById(R.id.sendButton);
closeBtn = (Button) findViewById(R.id.closeButton);
sendTxt = (EditText) findViewById(R.id.editText1);
discoverDevicesBtn.setOnClickListener(discoverDeviceListener);
sendMsgBtn.setOnClickListener(sendMsgListener);
closeBtn.setOnClickListener(closeBtnListener);
//init bluetooth
btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter.isEnabled()) {
Toast.makeText(this, "Bluetooth state:" + btAdapter.getState() + " Ok!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Bluetooth state:" + btAdapter.getState() + " Not ok!", Toast.LENGTH_LONG).show();
}
}
private Button.OnClickListener discoverDeviceListener = new Button.OnClickListener() {@Override
public void onClick(View v) {
if (!CONNECTED) {
device = btAdapter.getRemoteDevice(btAdress);
header.append("\nRemote device: " + device.getName());
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (Exception e) {
}
header.append("\n createRfcommsockettoservice! ");
btAdapter.cancelDiscovery();
try {
btSocket.connect();
CONNECTED = true;
header.append("\n btSocket Created!");
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Could not connect to socket", Toast.LENGTH_LONG);
try {
btSocket.close();
} catch (Exception b) {}
}
}
}
};
private Button.OnClickListener sendMsgListener = new Button.OnClickListener() {@Override
public void onClick(View v) {
if (CONNECTED) {
try {
out = btSocket.getOutputStream();
String msg = sendTxt.getText().toString();
byte[] msgBffr = msg.getBytes();
out.write(msgBffr);
Toast.makeText(getApplicationContext(), "Message sent", Toast.LENGTH_LONG).show();
} catch (Exception a) {
Toast.makeText(getApplicationContext(), "Could not send msg", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "cant send msg, not connected", Toast.LENGTH_LONG).show();
}
}
};
}
(I havnt molestado en incluir el resto del código de Java como el problema está en algún lugar en el establecimiento de la conexión)
import bluetooth
name="bt_server"
target_name="siggen"
uuid="00001101-0000-1000-8000-00805F9B34FB"
def runServer():
serverSocket=bluetooth.BluetoothSocket(bluetooth.RFCOMM)
port=bluetooth.PORT_ANY
serverSocket.bind(("",port))
print "Listening for connections on port: ", port
serverSocket.listen(1)
port=serverSocket.getsockname()[1]
inputSocket, address=serverSocket.accept()
print "Got connection with" , address
data=inputSocket.recv("1024")
print "received [%s] \n " % data
inputSocket.close()
serverSocket.close()
runServer()
.
¿Sería útil una captura de Wireshark aquí? – James
¿Has reducido a si el problema está en python o java? –
Siempre debe probar las implementaciones de cliente/servidor tratando de usar su cliente/servidor junto con una pieza de software probado. Vea si puede obtener una aplicación bluetooth con una calificación alta en la tienda de aplicaciones e intente conectarse a su secuencia de comandos de Python.Luego, vea si puede obtener un servidor Python de calidad que se conectará a su aplicación Android. * Luego * ver si tu script se puede conectar a tu aplicación de Android. –