아두이노와 블루투스 연결하여 연결된 블루투스 장치와 상태를 받아서 textview에 뜨게 작성한 코드입니다.
블루투스 연결은 성공적으로 되는데 babystate(아두이노에서 받아온 상태 변수)는 뜨지 않습니다ㅜㅜ
public class MainActivity extends AppCompatActivity {
private BluetoothSPP bt; //블루투스 객체
TextView textView; //텍스트뷰 객체
TextView babyState; //텍스트뷰 객체
private CameraManager cameraManager; //카메라관리자
private String cameraId; //카메라
private boolean flashOn; //플래시 On/Off
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = new BluetoothSPP(this); //Initializing
textView = (TextView) findViewById(R.id.textView); //레이아웃과 연결
babyState = (TextView) findViewById(R.id.textView2); //레이아웃과 연결
final Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
bt.setOnDataReceivedListener(new BluetoothSPP.OnDataReceivedListener() { //데이터가 수신될 경우
@RequiresApi(api = Build.VERSION_CODES.M)
public void onDataReceived(byte[] data, String message) { //수신 받은 데이터
String state = message; //수신 데이터 저장
switch (state) { //수신받은 데이터의 case마다 실행
case "A":
babyState.setText("OFF"); //텍스트 세팅
vibrator.cancel(); //진동 종료
flashOn = false; //플래시 작동 끔
flashlight(); //플래시 함수 호출
break;
case "B":
babyState.setText("ON");
break;
case "C":
babyState.setText("아기가 잠들었습니다.");
break;
case "D":
babyState.setText("아기가 놀고 있습니다.");
break;
case "E":
babyState.setText("아기가 없습니다.");
break;
case "F":
babyState.setText("아기가 울고있습니다.");
vibrator.vibrate(
new long[]{100, 1000, 100, 1000, 100, 1000, 100, 1000}, 0);
//0.1초 쉬고 1초동안 진동하는 것을 무한 반복
flashOn = true; //플래시를 킴
flashlight(); //플래시 함수 호출
//flashOn = false; //작동종료?
break;
case "G":
babyState.setText("아기가 뒤척입니다.");
vibrator.vibrate(
new long[]{100, 1000, 100, 1000}, -1);
//0.1초 쉬고 1초 진동을 2번 반복하고 종료
break;
case "H":
babyState.setText("아기가 깨어났습니다.");
vibrator.vibrate(
new long[]{100, 1000, 100, 1000, 100, 1000, 100, 1000}, 0);
//0.1초 쉬고 1초동안 진동하는 것을 무한 반복
flashOn = true; //플래시를 킴
flashlight(); //플래시 함수 호출
// flashOn = false; //작동종료?
break;
default:
babyState.setText("시스템을 다시 시작해주세요."); //수신 데이터 오류
}
}
});
bt.setBluetoothConnectionListener(new BluetoothSPP.BluetoothConnectionListener() {
//블루투스가 연결되는 경우
@SuppressLint("SetText | 18n")
public void onDeviceConnected(String name, String address) { //이름과 Mac주소
String blueTooth = "블루투스 이름 : ";
String textTotal = blueTooth + name;
textView.setText(textTotal); //블루투스 이름 전달
}
public void onDeviceDisconnected() {
textView.setText("연결이 끊어졌습니다.");
} //연결 끊어질 때
public void onDeviceConnectionFailed() {
textView.setText("다시 시도해주세요.");
} //연결 실패할 때
});
Button btnConnect = (Button) findViewById(R.id.btnConnect); //블루투스 연결 버튼
btnConnect.setOnClickListener((v) -> { // 블루투스 연결버튼 누를때
if (bt.getServiceState() == BluetoothState.STATE_CONNECTED) { //연결되어있는 경우
bt.disconnect();
} //연결 종료
else { //연결되어 있지 않은 경우
Intent intent = new Intent(getApplicationContext(), DeviceList.class); //블루투스 목록창
startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE);
} //연결가능한 블루투스
});
}