正如标题所述,我正在尝试从Android手机发送数据,我已通过蓝牙与树莓派配对。我当前的问题是,由于android代码将其放入IOException Catch中,因此出现了连接超时问题。 任何解决方案,方向或见识将不胜感激。
android代码如下:
public void onClickBtn(View v) {
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
Toast err;
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if(bondedDevices.size() > 0) {
Object[] devices = (Object[]) bondedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[0];
try {
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID.fromString("11111111-1111-1111-1111-111111111111"));
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
TextView tv0 = findViewById(R.id.textView0);
TextView tv1 = findViewById(R.id.textView1);
TextView tv2 = findViewById(R.id.textView2);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
String eff = spinner.getSelectedItem().toString();
String out = eff + ',' + tv0.getText() + ',' + tv1.getText() + ',' + tv2.getText();
outputStream.write(out.getBytes());
} catch (IOException e) {
err = Toast.makeText(getApplicationContext(), "Unexpected Error", Toast.LENGTH_LONG);
err.show();
}
}
err = Toast.makeText(getApplicationContext(),"No Device Connected", Toast.LENGTH_LONG);
err.show();
} else {
err = Toast.makeText(getApplicationContext(),"Bluetooth Disabled", Toast.LENGTH_LONG);
err.show();
}
}
}
Python代码如下:
import bluetooth
import redis
r = redis.StrictRedis(host='localhost', port=6379,db=0)
hostMACAddress = 'B8:27:EB:F1:69:D9'
port = 3
backlog = 1
size = 1024
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.bind((hostMACAddress, port))
s.listen(backlog)
uuid = "11111111-1111-1111-1111-111111111111"
bluetooth.advertise_service( s, "LedPiServer",
service_id = uuid
)
try:
client, clientInfo = s.accept()
while 1:
data = client.recv(size)
if data:
data = data.split(',')
r.set('effect', data[0])
tmp = tuple(int(data[1][i:i+2], 16) for i in (0, 2 ,4))
r.set('l1', tmp[0] + ',' + tmp[1] + ',' + tmp[2])
tmp = tuple(int(data[2][i:i+2], 16) for i in (0, 2 ,4))
r.set('l2', tmp[0] + ',' + tmp[1] + ',' + tmp[2])
tmp = tuple(int(data[3][i:i+2], 16) for i in (0, 2 ,4))
r.set('l3', tmp[0] + ',' + tmp[1] + ',' + tmp[2])
except:
print("Closing socket")
client.close()
s.close()