package ru.ln_group.counter; import android.content.DialogInterface; import android.graphics.Color; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.os.Handler; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import java.lang.reflect.Method; import java.io.IOException; import java.io.OutputStream; import android.widget.ImageView; import android.widget.ScrollView; import android.widget.Toast; import java.util.UUID; import android.content.BroadcastReceiver; import android.content.Context; import android.content.IntentFilter; import java.io.InputStream; //import java.util.logging.Handler; import android.widget.TextView; import android.os.Build; import android.content.Intent; import android.text.method.ScrollingMovementMethod; import android.os.SystemClock; import static android.R.id.message; import static java.lang.Thread.sleep; import static ru.ln_group.counter.R.attr.title; public class MainActivity extends AppCompatActivity { //Context context; TextView txtArduino; EditText addr; Handler h; Button onButton,testButton,initButton,loopButton,stopButton; String getDataStr; // TextView textView; TextView sn; TextView Aplus,Aminus,Rplus,Rminus,A1,A2,A3,U1,U2,U3,terminal,I1,I2,I3,Asum,Angle1,Angle2,Angle3,Freq; CheckBox LogTerm; final int RECIEVE_MESSAGE = 1; // Status for Handler private BluetoothAdapter btAdapter = null; private BluetoothSocket btSocket = null; private StringBuilder sb = new StringBuilder(); private String sendAdr = null; private ConnectedThread mConnectedThread; private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private static String address;// = "20:16:06:12:88:67"; private boolean startOK = false; private static String appName; ScrollView scrollScreen; ImageView screenSplash; //private boolean startOK = false; //------------------------------------------------------------------------------------------------ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_logo); setTitle("Меркурий-230 v2.1"); setContentView(R.layout.activity_main); terminal = (TextView)findViewById(R.id.terminal); terminal.setMovementMethod(new ScrollingMovementMethod()); // onButton = (Button) findViewById(R.id.On); // testButton = (Button) findViewById(R.id.test); //initButton = (Button) findViewById(R.id.init); // loopButton = (Button) findViewById(R.id.loop); // stopButton = (Button) findViewById(R.id.stop); addr = (EditText) findViewById(R.id.editText); sn = (TextView)findViewById(R.id.textView4); Aplus = (TextView)findViewById(R.id.Aplus); Aminus = (TextView)findViewById(R.id.Aminus); Rplus = (TextView)findViewById(R.id.Rplus); Rminus = (TextView)findViewById(R.id.Rminus); I1 = (TextView)findViewById(R.id.I1); I2 = (TextView)findViewById(R.id.I2); I3 = (TextView)findViewById(R.id.I3); U1 = (TextView)findViewById(R.id.U1); U2 = (TextView)findViewById(R.id.U2); U3 = (TextView)findViewById(R.id.U3); Angle1 = (TextView)findViewById(R.id.Angl1); Angle2 = (TextView)findViewById(R.id.Angl2); Angle3 = (TextView)findViewById(R.id.Angl3); Asum = (TextView)findViewById(R.id.Asum); A1 = (TextView)findViewById(R.id.A1); A2 = (TextView)findViewById(R.id.A2); A3 = (TextView)findViewById(R.id.A3); Freq = (TextView)findViewById(R.id.freq); LogTerm = (CheckBox) findViewById(R.id.logTerm); scrollScreen = (ScrollView) findViewById(R.id.scr1); screenSplash = (ImageView) findViewById(R.id.imageView2); btAdapter = BluetoothAdapter.getDefaultAdapter(); scrollScreen.setVisibility(View.INVISIBLE); //terminal.setVisibility(View.INVISIBLE); terminal.setHeight(0); checkBTState(); h = new Handler() { public void handleMessage(android.os.Message msg) { // switch (msg.what) { try { byte[] readBuf = (byte[]) msg.obj; String strIncom = new String(readBuf, 0, msg.arg1); sb.append(strIncom); int endOfLineIndex = sb.indexOf("\r\n"); if (endOfLineIndex > 0) { String sbprint = sb.substring(0, endOfLineIndex); sb.delete(0, sb.length()); addText(sbprint); connectToUnit(sbprint); } } catch (Exception e) { } //} }; }; } //---------------------------------------------------------------------------------------------- @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); //--------------------------- find units if(id == R.id.findmenu ) { findDev(); // SystemClock.sleep(5000); scrollScreen.setVisibility(View.VISIBLE); screenSplash.setVisibility(View.INVISIBLE); return true; } //-------------------------------------- test conn if(id == R.id.testmenu ) { try { mConnectedThread.write("ping_"); } catch (Exception e) { Toast.makeText(getApplicationContext(), "Bluetooth не активирован", Toast.LENGTH_LONG).show(); } return true; } //--------------------------------------- init if(id == R.id.initmenu ) { try { int address; String newAdr = null; sn.setText(""); Aplus.setText(""); Aminus.setText(""); Rplus.setText(""); Rminus.setText(""); I1.setText(""); I2.setText(""); I3.setText(""); U1.setText(""); U2.setText(""); U3.setText(""); Angle1.setText(""); Angle2.setText(""); Angle3.setText(""); Asum.setText(""); A1.setText(""); A2.setText(""); A3.setText(""); Freq.setText(""); terminal.setText(""); try { address = Integer.parseInt(addr.getText().toString()); if (address < 100 & address > 9) { newAdr = Integer.toString(address); mConnectedThread.write("init_0" + newAdr); } if (address > 255) { Toast.makeText(getApplicationContext(), "Адрес не может быть больше 255", Toast.LENGTH_LONG).show(); } if (address > 99 & address < 256) { newAdr = Integer.toString(address); mConnectedThread.write("init_" + newAdr); } if (address < 10 || address == 0) { newAdr = Integer.toString(address); mConnectedThread.write("init_00" + newAdr); } sendAdr = newAdr; } catch (NumberFormatException nfe) { Toast.makeText(getApplicationContext(), "Введите адрес цифрами", Toast.LENGTH_LONG).show(); } } catch (Exception e) { Toast.makeText(getApplicationContext(), "Bluetooth не активирован", Toast.LENGTH_LONG).show(); } return true; } //-------------------------------------------------------------------------------- if(id == R.id.loopmenu ) { try { int address; String newAdr; sn.setText(""); Aplus.setText(""); Aminus.setText(""); Rplus.setText(""); Rminus.setText(""); I1.setText(""); I2.setText(""); I3.setText(""); U1.setText(""); U2.setText(""); U3.setText(""); Angle1.setText(""); Angle2.setText(""); Angle3.setText(""); Asum.setText(""); A1.setText(""); A2.setText(""); A3.setText(""); Freq.setText(""); terminal.setText(""); try { address = Integer.parseInt(addr.getText().toString()); if (address < 100) { newAdr = Integer.toString(address); mConnectedThread.write("loop_0" + newAdr); } else { if (address > 255) { Toast.makeText(getApplicationContext(), "Адрес не может быть больше 255", Toast.LENGTH_LONG).show(); } else { newAdr = Integer.toString(address); mConnectedThread.write("loop_" + newAdr); } } } catch (NumberFormatException nfe) { Toast.makeText(getApplicationContext(), "Введите адрес цифрами", Toast.LENGTH_LONG).show(); } } catch (Exception e){ Toast.makeText(getApplicationContext(), "Bluetooth не активирован", Toast.LENGTH_LONG).show(); } return true; } //-------------------------------------------------------------------------------- if(id == R.id.stoploopmenu ) { try { mConnectedThread.write("stop_"); } catch (Exception e){ Toast.makeText(getApplicationContext(), "Bluetooth не активирован", Toast.LENGTH_LONG).show(); } return true; } //-------------------------------------------------------------------------------- if(id == R.id.logmenu ) { try { if(LogTerm.isChecked() == true ) { LogTerm.setChecked(false); terminal.setHeight(0); } else { LogTerm.setChecked(true); terminal.setHeight(300); } } catch (Exception e) { } return true; } return super.onOptionsItemSelected(item); //} } //////////////////////////////////////////////////////////////////////////// private final BroadcastReceiver mmReceiver=new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); addText("Обнаружено устройство:\n"+ device.getName()+":adr:" +device.getAddress()); // Toast.makeText(getApplicationContext(), "Обнаружено устройство:\n"+ device.getName()+":adr:" +device.getAddress(), Toast.LENGTH_LONG).show(); //////////////////////////////////////////////// final String sss; AlertDialog.Builder ad; ad = new AlertDialog.Builder(context); ad.setTitle("Подключение"); // заголовок ad.setMessage("Обнаружено устройство:\n"+ device.getName()+" adr:" +device.getAddress()); address = device.getAddress(); ad.setPositiveButton("ДА", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { String adrs = address; connectBt(adrs); Toast.makeText(getApplicationContext(), "Подключение к "+adrs , Toast.LENGTH_LONG).show(); } }); ad.setNegativeButton("НЕТ", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { Toast.makeText(getApplicationContext(), "Отмена подключения", Toast.LENGTH_LONG).show(); } }); ad.setCancelable(true); ad.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { // Toast.makeText(context, "Вы ничего не выбрали", // Toast.LENGTH_LONG).show(); Toast.makeText(getApplicationContext(), "Отмена операции.", Toast.LENGTH_LONG).show(); } }); // public void onClick(View v) { ad.show(); // } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } btAdapter.cancelDiscovery(); } }; //---------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------- private void connectToUnit(String s) { try { if (s.equals("Connect_FAIL")) { addr.setBackgroundColor(Color.RED); sn.setText(""); } if (s.equals("Connect_OK")) { addr.setBackgroundColor(Color.GRAY); } if (s.equals("Access_OK")) { addr.setBackgroundColor(Color.LTGRAY); } if (s.substring(0, 2).equals("s:")) { int rez1 = s.indexOf(";"); sn.setText(s.substring(rez1 + 1)); } if (s.substring(0, 2).equals("p:")) { int rez1 = s.indexOf(";"); String s1= s.substring(rez1 + 1); String tmp [] =s1.split(";"); try { Aplus.setText("Aкт.имп: "+String.format("%.2f", Float.parseFloat(tmp[0] ) / 1000)+ " кВт/ч"); } catch(Exception e) {Aplus.setText("A+: Error"); } try { Aminus.setText("Aкт.эксп: "+String.format("%.2f", Float.parseFloat(tmp[1]) / 1000)+ " кВт/ч");} catch(Exception e) {Aplus.setText("A-: Error"); } try { Rplus.setText("Реакт.имп: "+String.format("%.2f", Float.parseFloat(tmp[2]) / 1000)+ " кВар/ч"); } catch(Exception e) {Aplus.setText("R+: Error"); } try { Rminus.setText("Реакт.эксп: "+String.format("%.2f", Float.parseFloat(tmp[3]) / 1000)+ " кВар/ч");} catch(Exception e) {Aplus.setText("R-: Error"); } } if (s.substring(0, 2).equals("a:")) { int rez1 = s.indexOf(";"); String s1= s.substring(rez1 + 1); String tmp [] =s1.split(";"); try { I1.setText("Фаза 1: "+String.format("%.2f", Float.parseFloat(tmp[0]) / 1000)+ " А");} catch(Exception e) {Aplus.setText("I1: Error"); } try { I2.setText("Фаза 2: "+String.format("%.2f", Float.parseFloat(tmp[1]) / 1000)+" А");} catch(Exception e) {Aplus.setText("I2: Error"); } try { I3.setText("Фаза 3: "+String.format("%.2f", Float.parseFloat(tmp[2]) / 1000)+" А");} catch(Exception e) {Aplus.setText("I3: Error"); } } if (s.substring(0, 2).equals("u:")) { int rez1 = s.indexOf(";"); String s1= s.substring(rez1 + 1); String tmp [] =s1.split(";"); try { U1.setText("Фаза 1: "+String.format("%.2f", Float.parseFloat(tmp[0]) / 100)+" В");} catch(Exception e) {Aplus.setText("U1: Error"); } try { U2.setText("Фаза 2: "+String.format("%.2f", Float.parseFloat(tmp[1]) / 100)+" В");} catch(Exception e) {Aplus.setText("U1: Error"); } try { U3.setText("Фаза 3: "+String.format("%.2f", Float.parseFloat(tmp[2]) / 100)+" В");} catch(Exception e) {Aplus.setText("U1: Error"); } } if (s.substring(0, 2).equals("g:")) { int rez1 = s.indexOf(";"); String s1= s.substring(rez1 + 1); String tmp [] =s1.split(";"); try { Angle1.setText("Угол 12: "+String.format("%.2f", Float.parseFloat(tmp[0]) / 1000)+" Град.");} catch(Exception e) {Aplus.setText("Angl1: Error"); } try { Angle2.setText("Угол 13: "+String.format("%.2f", Float.parseFloat(tmp[1]) / 1000)+" Град.");} catch(Exception e) {Aplus.setText("Angl2: Error"); } try { Angle3.setText("Угол 23: "+String.format("%.2f", Float.parseFloat(tmp[2]) / 1000)+" Град.");} catch(Exception e) {Aplus.setText("Angl3: Error"); } } if (s.substring(0, 2).equals("e:")) { int rez1 = s.indexOf(";"); String s1= s.substring(rez1 + 1); String tmp [] =s1.split(";"); try { Asum.setText("Мощн.сум.: "+String.format("%.2f", Float.parseFloat(tmp[0]) / 1000)+" Ватт");} catch(Exception e) {Aplus.setText("As: Error"); } try { A1.setText("Мощн.Фаза 1: "+String.format("%.2f", Float.parseFloat(tmp[0]) / 1000)+" Ватт");} catch(Exception e) {Aplus.setText("A1: Error"); } try { A2.setText("Мощн.Фаза 2: "+String.format("%.2f", Float.parseFloat(tmp[0]) / 1000)+" Ватт");} catch(Exception e) {Aplus.setText("A2: Error"); } try { A3.setText("Мощн.Фаза 3: "+String.format("%.2f", Float.parseFloat(tmp[0]) / 1000)+" Ватт");} catch(Exception e) {Aplus.setText("A3: Error"); } } if (s.substring(0, 2).equals("f:")) { int rez1 = s.indexOf(";"); String s1= s.substring(rez1 + 1); try { Freq.setText("Частота: "+String.format("%.2f", Float.parseFloat(s1) / 1000)+" Герц.");} catch(Exception e) {Aplus.setText("F: Error"); } } } catch (Exception e) { } } //-------------------------------------------------------------------------------------------------- private void findDev() { if (btAdapter.isEnabled()) { // if (btAdapter.isDiscovering()) // { // btAdapter.cancelDiscovery(); // } btAdapter.startDiscovery(); IntentFilter filter=new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mmReceiver, filter); } else { Toast.makeText(getApplicationContext(), "Устройства не найдены", Toast.LENGTH_LONG).show(); //addText("Устройства не найдены"); } //btAdapter.cancelDiscovery(); //connectBt(); } //--------------------------------------------------------------------------------------------- private void addText(String s) { if(LogTerm.isChecked() == true) { terminal.append(s + "\r\n"); while (terminal.canScrollVertically(1)) { terminal.scrollBy(0, 10); } } } //--------------------------------------------------------------------------------------------- private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException { if(Build.VERSION.SDK_INT >= 10) { try { final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class }); return (BluetoothSocket) m.invoke(device, MY_UUID); } catch (Exception e) { } } return device.createRfcommSocketToServiceRecord(MY_UUID); } //------------------------------------------------------------------------------------ public void connectBt(String addressToConnect) { //super.onResume(); BluetoothDevice device = btAdapter.getRemoteDevice(addressToConnect); if(btSocket != null) { addText("Already connect OK"); } else { try { btAdapter.cancelDiscovery(); btSocket = createBluetoothSocket(device); addText("Socket to " + address + " OK"); Toast.makeText(getApplicationContext(), "Socket to " + address + " OK", Toast.LENGTH_LONG).show(); } catch (IOException e) { errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + "."); addText("Socket to " + address + " Fail"); Toast.makeText(getApplicationContext(), "Socket to " + address + " Fail", Toast.LENGTH_LONG).show(); } btAdapter.cancelDiscovery(); try { btSocket.connect(); addText("Connect OK"); Toast.makeText(getApplicationContext(),"Connect OK", Toast.LENGTH_LONG).show(); } catch (IOException e) { addText("Connect Fail"); Toast.makeText(getApplicationContext(),"Connect Fail", Toast.LENGTH_LONG).show(); try { btSocket.close(); addText("Connect closed"); } catch (IOException e2) { errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + "."); addText("Connect not closed"); } } mConnectedThread = new ConnectedThread(btSocket); mConnectedThread.start(); } } //------------------------------------------------------------ @Override public void onResume() { super.onResume(); /* BluetoothDevice device = btAdapter.getRemoteDevice(address); if(startOK == true) { try { btSocket = createBluetoothSocket(device); addText("Socket OK"); } catch (IOException e) { errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + "."); addText("Socket Fail"); } btAdapter.cancelDiscovery(); try { btSocket.connect(); addText("Connect OK"); } catch (IOException e) { addText("Connect Fail"); try { btSocket.close(); } catch (IOException e2) { errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + "."); } } mConnectedThread = new ConnectedThread(btSocket); mConnectedThread.start(); }*/ } //---------------------------------------------------------------------------- @Override public void onPause() { super.onPause(); // try { // btSocket.close(); // } catch (IOException e2) { // errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + "."); // } } private void checkBTState() { try { if (btAdapter == null) { addText("Bluetooth не поддерживается"); } else { if (btAdapter.isEnabled()) { Toast.makeText(getApplicationContext(), "Bluetooth включен", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Bluetooth надо включить", Toast.LENGTH_LONG).show(); try { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, 1); } catch (Exception e) { Toast.makeText(getApplicationContext(), "Ошибка подключения", Toast.LENGTH_LONG).show(); } } } } catch (Exception e) { Toast.makeText(getApplicationContext(), "Ошибка подключения", Toast.LENGTH_LONG).show(); } } //---------------------------------------------------------------------------- private void errorExit(String title, String message){ Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show(); finish(); } //-------------------------------------------------------------------------------- private class ConnectedThread extends Thread { private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket 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[1024]; int bytes=0; // byte[] buffer = new byte[1024]; int begin = 0; // int bytes = 0; while (true) { SystemClock.sleep(150); try { bytes = mmInStream.read(buffer); h.obtainMessage(RECIEVE_MESSAGE, bytes, 0, buffer).sendToTarget(); // getDataStr = new String(buffer, 0, bytes); // addText(new String(buffer)); getDataStr = new String(buffer, 0, bytes);// +"-"+ Integer.toString(bytes);; // bytes=0; } catch (IOException e) { break; } } } //---------------------------------------------------------------------------- public void write(String message) { byte[] msgBuffer = message.getBytes(); try { mmOutStream.write(msgBuffer); } catch (IOException e) { } } } //---------------------------------------------------------------------------- }