Проблемы работы с bluetooth

Ответить
astridsnus
Сообщения: 4
Зарегистрирован: 27 фев 2014, 14:53

Проблемы работы с bluetooth

Сообщение astridsnus » 27 фев 2014, 16:58

Разъясняю проблему:
имеется железка (радиостанция) с bluetooth-модулем. она умеет через этот модуль выкидывать свою статистику, принимать команды и отвечать на них.

появилась задача написать интерфейс на андроид для управления этой желекой. у железки по сути 2 режима: 1.) конфигурационный, в котором я отправляю ей команду, она мне отвечает. этот режим работает нормально.
2.) статистический. в этом режиме железка пуляется строчками статистики со скоростью 1-2 сообщение в секунду. статистику я принимаю отлично. если же я отправляю ей некую команду, то получаю на нее ответ, после чего входной поток дочитывает статистику до конца буфера и затыкается. далее уже ничего принять от железки не могу.

структура ответа железки:
-> строчка статистики \r\n
-> еще строчка статистики \r\n

и.т.д.

буду благодарен за помощь.

[syntax=java]
package com.example.afhsscontrol;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

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.os.Handler;
//import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

Button aBtnEnableBluetooth;
Button aBtnConnecttoFHSS;
Button aBtnExchange;
TextView aTextViewConnectionStatus;
TextView aTextViewRecieve, textView1;
EditText aEditTextSend;
Button aBtnSend;
Handler h;

private static final int REQUEST_ENABLE_BT = 1;
private BluetoothSocket btSocket = null;
private BluetoothAdapter btAdapter = null;
private ConnectedThread mConnectedThread;
private StringBuilder sb = new StringBuilder();
final int RECIEVE_MESSAGE = 1;
String userdata = "";
String strIncom, substr, substr_fin;
String i1,i2;
int linelength, endOfLineIndex;
int ae, af;
int flag = 0;

private static final UUID device_uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String mac_address = "6B:E2:00:DA:18:02";


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
aBtnEnableBluetooth = (Button) findViewById(R.id.aBtnEnableBluetooth);
aBtnConnecttoFHSS = (Button) findViewById(R.id.aBtnConnecttoFHSS);
aTextViewConnectionStatus = (TextView) findViewById(R.id.aTextViewConnectionStatus);
aTextViewRecieve = (TextView) findViewById(R.id.aTextViewRecieve);
textView1 = (TextView) findViewById(R.id.textView1);
aBtnExchange = (Button) findViewById(R.id.aBtnExchange);
aEditTextSend = (EditText) findViewById(R.id.aEditTextSend);
aBtnSend = (Button) findViewById(R.id.aBtnSend);
btAdapter = BluetoothAdapter.getDefaultAdapter();

h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE:
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1);
textView1.setText(strIncom);
ae = strIncom.indexOf("->");
if (ae != -1) {
substr = strIncom.substring(ae);
af = substr.indexOf("\n\r");
if (af != -1) {
substr_fin = substr.substring(0, af);
aTextViewRecieve.setText(substr_fin);
substr = "";
substr_fin = "";
}
}
break;
}
};
};

OnClickListener oclaBtnConnect = new OnClickListener() {
@Override
public void onClick(View v) {
checkBTState();
}
};
aBtnEnableBluetooth.setOnClickListener(oclaBtnConnect);

OnClickListener oclaBtnExchange = new OnClickListener() {
@Override
public void onClick(View v) {
startthread();
}

};
aBtnExchange.setOnClickListener(oclaBtnExchange);


OnClickListener oclaBtnSend = new OnClickListener() {
@Override
public void onClick(View v) {
userdata = aEditTextSend.getText().toString() + "\r\n";
mConnectedThread.write(userdata);
userdata = "";
}

};
aBtnSend.setOnClickListener(oclaBtnSend);

OnClickListener oclaBtnConnecttoFHSS = new OnClickListener() {
@Override
public void onClick(View v) {
onConnect();
}
};
aBtnConnecttoFHSS.setOnClickListener(oclaBtnConnecttoFHSS);
}



void onConnect() {
BluetoothDevice device = btAdapter.getRemoteDevice(mac_address);
try {
btSocket = device.createInsecureRfcommSocketToServiceRecord(device_uuid);
}
catch (IOException e) {
aTextViewConnectionStatus.setText("Не удалось установить соединение по причине: " + e.getMessage());
}
btAdapter.cancelDiscovery();
aTextViewConnectionStatus.setText("Соединение...");
try {
btSocket.connect();
aTextViewConnectionStatus.setText("Соединение выполнено успешно");
}
catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
aTextViewConnectionStatus.setText("Ошибка : " + e2.getMessage());
}
}
}

void startthread() {
mConnectedThread = new ConnectedThread(btSocket);

mConnectedThread.start();
if (mConnectedThread.isAlive()==true) {
aTextViewConnectionStatus.setText("Режим обмена данными");
}
}




void checkBTState() {
if (btAdapter == null) {
aTextViewConnectionStatus.setText("Технология bluetooth не поддерживается данным устройством");
}
else {
if (btAdapter.isEnabled()) {
aTextViewConnectionStatus.setText("Bluetooth включен");

}
else {
Intent enableBTIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBTIntent, REQUEST_ENABLE_BT);
aTextViewConnectionStatus.setText("Bluetooth включен");
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;

public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;

try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
}
catch (IOException e) {}

mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;

while(true) {
try {
bytes = mmInStream.read(buffer);
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
}
catch (IOException e) {
aTextViewConnectionStatus.setText("Ошибка: " + e.getMessage());
break;
}
}
}

public void write(String message) {
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
aTextViewConnectionStatus.setText("Ошибка: " + e.getMessage());
}

}

}
}
[/syntax]


[syntax=xml]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="27dp"
android:layout_marginTop="85dp"
android:orientation="vertical" >

</LinearLayout>

<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TextView
android:id="@+id/aTextViewConnectionStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="..." />
</LinearLayout>

<Button
android:id="@+id/aBtnEnableBluetooth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/linearLayout2"
android:layout_below="@+id/linearLayout2"
android:text="Включить bluetooth" />

<Button
android:id="@+id/aBtnExchange"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/aBtnConnecttoFHSS"
android:layout_below="@+id/aBtnConnecttoFHSS"
android:text="Начать обмен данными" />

<Button
android:id="@+id/aBtnConnecttoFHSS"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/aBtnEnableBluetooth"
android:layout_below="@+id/aBtnEnableBluetooth"
android:text="Подключиться к устройству" />

<EditText
android:id="@+id/aEditTextSend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/aBtnExchange"
android:layout_below="@+id/aBtnExchange"
android:ems="10" >

<requestFocus />
</EditText>

<Button
android:id="@+id/aBtnSend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/aEditTextSend"
android:layout_below="@+id/aEditTextSend"
android:text="Отправить на устройство" />

<TextView
android:id="@+id/aTextViewRecieve"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/aBtnSend"
android:layout_below="@+id/aBtnSend"
android:layout_marginTop="72dp"
android:text="..." />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/aTextViewRecieve"
android:layout_alignParentBottom="true"
android:text="..." />

</RelativeLayout>
[/syntax]

astridsnus
Сообщения: 4
Зарегистрирован: 27 фев 2014, 14:53

Re: Проблемы работы с bluetooth

Сообщение astridsnus » 05 мар 2014, 16:48

Проблема решилась сменой планшета. Аппаратный глюк.

Ответить