/* * Copyright 2009 Cedric Priscal * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.serialport.api.sample; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import sendData.Commands; import sendData.SendDatas; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.DialogInterface.OnClickListener; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.serialport.api.SerialPort; import android.view.MotionEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import android.serialport.api.sample.R; import android.util.Log; import android.widget.Switch; public class ConsoleActivity extends Activity { public static final int INDUCTOR_LEAVE = 1; private List SendDatasList = new ArrayList(); private TextView Seekbar_value; private EditText T_TextView; private EditText key_state; private EditText c_value; private Switch loop1Button; private Switch loop2Button; private Switch loop3Button; private Switch loop4Button; private Switch powerButton; private Switch openBackLight; private RadioButton radioButton1; private RadioButton radioButton2; private RadioButton radioButton3; private RadioButton radioButton4; private RadioButton radioButton5; private RadioButton radioButton6; private SeekBar SSeekbar; private static Button Btn_state; private Button C_Btn; protected Application mApplication; protected SerialPort mSerialPort; protected OutputStream mOutputStream; private InputStream mInputStream; private ReadThread mReadThread; int id = -1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.console); iniView(); iniData(); } private void iniView() { c_value = (EditText) findViewById(R.id.c_value); T_TextView = (EditText) findViewById(R.id.Temperature); key_state = (EditText) findViewById(R.id.key_status); Seekbar_value = (TextView) findViewById(R.id.seekbar_value); loop1Button = (Switch) findViewById(R.id.loopId1); loop1Button.setTag("0"); loop1Button.setOnClickListener(onClick); loop2Button = (Switch) findViewById(R.id.loopId2); loop2Button.setTag("0"); loop2Button.setOnClickListener(onClick); loop3Button = (Switch) findViewById(R.id.loopId3); loop3Button.setTag("0"); loop3Button.setOnClickListener(onClick); loop4Button = (Switch) findViewById(R.id.loopId4); loop4Button.setTag("0"); loop4Button.setOnClickListener(onClick); powerButton = (Switch) findViewById(R.id.powerButton); powerButton.setTag("Off"); powerButton.setOnClickListener(powerOnClick); radioButton1 = (RadioButton) findViewById(R.id.radioButton1); radioButton2 = (RadioButton) findViewById(R.id.radioButton2); radioButton3 = (RadioButton) findViewById(R.id.radioButton3); radioButton4 = (RadioButton) findViewById(R.id.radioButton4); radioButton5 = (RadioButton) findViewById(R.id.radioButton5); radioButton6 = (RadioButton) findViewById(R.id.radioButton6); openBackLight = (Switch) findViewById(R.id.openbacklight); openBackLight.setTag("1"); openBackLight.setChecked(true); openBackLight.setOnClickListener(backLightOnClick); Btn_state = (Button) findViewById(R.id.btn_state); Btn_state.setTag(new Inductor()); Btn_state.setBackground(null); C_Btn = (Button) findViewById(R.id.c_btn); C_Btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 设置补偿值 try { int _value = Integer.parseInt(c_value.getText().toString()); byte[] sendBytes = SendDatas.AddSendData(Commands.SET_TEMP_COMPENSATE_VALUE.getCommand(), 250, 250, new byte[] { (byte) 1, (byte) 0, (byte) (_value + 10) }); SendDatasList.add(sendBytes); SharedPreferences SP = ConsoleActivity.this.getSharedPreferences("Serialport", ConsoleActivity.this.MODE_PRIVATE); SharedPreferences.Editor editor = SP.edit(); editor.putInt("c_value", _value); editor.commit(); editor.apply(); InputMethodManager imm = (InputMethodManager) getSystemService( ConsoleActivity.this.INPUT_METHOD_SERVICE); // 得到InputMethodManager的实例 if (imm.isActive()) { // 如果开启 imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS); // 关闭软键盘,开启方法相同,这个方法是切换开启与关闭状态的 } } catch (Exception e) { } } }); SSeekbar = (SeekBar) findViewById(R.id.set_sensitivity); SSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { // 写 int _value = seekBar.getProgress(); byte[] sendBytes = SendDatas.AddSendData(Commands.Sensor.getCommand(), 250, 250, new byte[] { 1, (byte) _value }); SendDatasList.add(sendBytes); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { Seekbar_value.setText(progress + ""); } }); } private int getC_value() { SharedPreferences SP = this.getSharedPreferences("Serialport", this.MODE_PRIVATE); int _value = SP.getInt("c_value", 0); return _value; } private void iniData() { getSerialPort(); SendDatasList.clear(); // 读取温度 1秒钟读取一次 new SendThread().start(); new SendDatasThread().start(); ReadSensitivity(); c_value.setText(getC_value() + ""); } private void ReadSensitivity() { byte[] sendBytes = SendDatas.AddSendData(Commands.Sensor.getCommand(), 250, 250, new byte[] { 0 }); SendDatasList.add(sendBytes); } private android.view.View.OnClickListener onClick = new android.view.View.OnClickListener() { @Override public void onClick(View v) { Switch view = (Switch) v; if (mOutputStream == null) { Toast.makeText(ConsoleActivity.this, "Please Open Serial Port", android.widget.Toast.LENGTH_SHORT) .show(); view.setChecked(false); return; } int tag = Integer.parseInt(view.getTag().toString()); if (tag == 0) { view.setTag("100"); view.setChecked(true); } else { view.setTag("0"); view.setChecked(false); } tag = Integer.parseInt(view.getTag().toString()); if (view.equals(loop1Button)) { setData(1, tag); } else if (view.equals(loop2Button)) { setData(2, tag); } else if (view.equals(loop3Button)) { setData(3, tag); } else if (view.equals(loop4Button)) { setData(4, tag); } } }; private android.view.View.OnClickListener powerOnClick = new android.view.View.OnClickListener() { @Override public void onClick(View view) { if (view.getTag().toString().equals("On")) { view.setTag("Off"); mApplication.closeSerialPort(); try { mOutputStream.close(); mOutputStream = null; } catch (Exception e) { e.printStackTrace(); return; } powerButton.setChecked(false); } else if (view.getTag().toString().equals("Off")) { getSerialPort(); } } }; private android.view.View.OnClickListener backLightOnClick = new android.view.View.OnClickListener() { @Override public void onClick(View v) { Switch view = (Switch) v; if (view.isChecked()) { // sendBackLight(1); if (0 < SerialPort.BackLight_ON()) { Toast.makeText(ConsoleActivity.this, "-1", Toast.LENGTH_SHORT).show(); } } else { // sendBackLight(0); if (0 < SerialPort.BackLight_OFF()) { Toast.makeText(ConsoleActivity.this, "-1", Toast.LENGTH_SHORT).show(); } } } }; private android.view.View.OnTouchListener onTouch = new android.view.View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (MotionEvent.ACTION_DOWN == event.getAction()) { v.setBackgroundResource(R.drawable.selected); if (mOutputStream == null) { Toast.makeText(ConsoleActivity.this, "Please Open Serial Port", android.widget.Toast.LENGTH_SHORT) .show(); } else { setBuzzerData(); } } else if (MotionEvent.ACTION_UP == event.getAction()) { v.setBackgroundResource(R.drawable.unselected); } return false; } }; /** * Open the serial port, input and output streams */ private void getSerialPort() { mApplication = new Application(); try { mSerialPort = mApplication.getSerialPort(); mOutputStream = mSerialPort.getOutputStream(); mInputStream = mSerialPort.getInputStream(); mReadThread = new ReadThread(); mReadThread.start(); if (powerButton != null) { powerButton.setChecked(true); powerButton.setTag("On"); } } catch (SecurityException e) { if (powerButton != null) { powerButton.setChecked(false); powerButton.setTag("Off"); } DisplayError(R.string.error_security); } catch (IOException e) { if (powerButton != null) { powerButton.setChecked(false); powerButton.setTag("Off"); } DisplayError(R.string.error_unknown); } catch (InvalidParameterException e) { if (powerButton != null) { powerButton.setChecked(false); powerButton.setTag("Off"); } DisplayError(R.string.error_configuration); } } /** * send buzzer */ private void setBuzzerData() { byte[] sendBytes = SendDatas.AddSendData(Commands.buzzer.getCommand(), 250, 250, new byte[] { (byte) 2, (byte) 5, (byte) 1 }); this.SendDatasList.add(sendBytes); /** * 2017.12.17 try { mOutputStream.flush(); * mOutputStream.write(sendBytes); * * } catch (IOException e) { e.printStackTrace(); } */ } private void readDateTime() { byte[] sendBytes = SendDatas.AddSendData(Commands.ReadTime.getCommand(), 250, 250, new byte[] {}); this.SendDatasList.add(sendBytes); } private byte[] sendData(int loopId, int linght) { byte[] sendBytes = SendDatas.AddSendData(Commands.regulationControl.getCommand(), 250, 250, new byte[] { (byte) loopId, (byte) linght }); return sendBytes; } private void setData(int loopId, int linght) { byte[] sendBytes = sendData(loopId, linght); this.SendDatasList.add(sendBytes); } /** * 2015.12.10 读取温度 */ private class SendThread extends Thread { @Override public void run() { super.run(); while (true) { try { byte[] sendBytes = SendDatas.AddSendData(Commands.READ_TEMP_WITH_DRY1.getCommand(), 250, 250, new byte[] {}); mOutputStream.flush(); mOutputStream.write(sendBytes); sleep(1000); } catch (Exception e) { // continue; } } } } private class SendDatasThread extends Thread { @Override public void run() { super.run(); while (true) { try { Thread.sleep(10); } catch (Exception e) { e.getMessage(); } for (int i = 0; i < SendDatasList.size(); i++) { try { byte[] sendBytes = SendDatasList.get(i); try { mOutputStream.flush(); mOutputStream.write(sendBytes); } catch (Exception e) { e.printStackTrace(); } SendDatasList.remove(i); i--; } catch (Exception ex) { ex.getMessage(); } } } } } /** * Read data thread * * @author 2017年12月19日 */ private class ReadThread extends Thread { @Override public void run() { super.run(); while (!isInterrupted()) { int size = 0; try { byte[] buffer = new byte[64]; if (mInputStream == null) { return; } size = mInputStream.read(buffer); for (int i = 0; i < size - 1; i++) { if (i != 0) { if ((buffer[i] & 0xFF) == 0xAA && (buffer[i + 1] & 0xFF) == 0xAA) { // byte[] _bf = new byte[i]; System.arraycopy(buffer, 0, _bf, 0, i); if (_bf.length >= 13) { int command = (buffer[7] & 0xFF) * 256 + (buffer[8] & 0xFF); if (command == Commands.ReadTimeFeedback.getCommand() || command == Commands.DryContactInitiativeToSend.getCommand() || command == Commands.READ_TEMP_WITH_DRY1_ACK.getCommand() || command == Commands.InductorState.getCommand() || command == Commands.SensorBack.getCommand() || command == Commands.ClickState.getCommand()) { onDataReceived(buffer, size); } } byte[] _bf2 = new byte[size - i]; System.arraycopy(buffer, i, _bf2, 0, size - i); if (_bf2.length >= 13) { int command = (buffer[7] & 0xFF) * 256 + (buffer[8] & 0xFF); if (command == Commands.ReadTimeFeedback.getCommand() || command == Commands.DryContactInitiativeToSend.getCommand() || command == Commands.READ_TEMP_WITH_DRY1_ACK.getCommand() || command == Commands.InductorState.getCommand() || command == Commands.SensorBack.getCommand() || command == Commands.ClickState.getCommand()) { onDataReceived(buffer, size); } } } } else { if (size >= 13) { int command = (buffer[7] & 0xFF) * 256 + (buffer[8] & 0xFF); if (command == Commands.ReadTimeFeedback.getCommand() || command == Commands.DryContactInitiativeToSend.getCommand() || command == Commands.READ_TEMP_WITH_DRY1_ACK.getCommand() || command == Commands.InductorState.getCommand() || command == Commands.SensorBack.getCommand() || command == Commands.ClickState.getCommand()) { onDataReceived(buffer, size); } } } } } catch (Exception e) { e.printStackTrace(); return; } } } } protected void onDataReceived(final byte[] buffer, final int size) { runOnUiThread(new Runnable() { public void run() { int command = (buffer[7] & 0xFF) * 256 + (buffer[8] & 0xFF); if (command == Commands.ReadTimeFeedback.getCommand()) { // ReadDateTimeTextView.setText( // (buffer[12] & 0xFF) + "\\" + (buffer[13] & 0xFF) + "\\20" // + (buffer[11] & 0xFF) + " " // + (buffer[14] & 0xFF) + ":" + (buffer[15] & 0xFF) + ":" + // (buffer[16] & 0xFF)); } else if (command == Commands.DryContactInitiativeToSend.getCommand()) { try { mOutputStream .write(SendDatas.AddSendData(Commands.DryContactInitiativeToSendFeedback.getCommand(), 250, 250, new byte[] { (byte) 0xf8 })); } catch (Exception e) { e.printStackTrace(); } if ((buffer[11] & 0xFF) == 1) radioButton1.setChecked(true); else radioButton1.setChecked(false); if ((buffer[12] & 0xFF) == 1) radioButton2.setChecked(true); else radioButton2.setChecked(false); if ((buffer[13] & 0xFF) == 1) radioButton3.setChecked(true); else radioButton3.setChecked(false); if ((buffer[14] & 0xFF) == 1) radioButton4.setChecked(true); else radioButton4.setChecked(false); if ((buffer[15] & 0xFF) == 1) radioButton5.setChecked(true); else radioButton5.setChecked(false); if ((buffer[16] & 0xFF) == 1) radioButton6.setChecked(true); else radioButton6.setChecked(false); } else if (command == Commands.READ_TEMP_WITH_DRY1_ACK.getCommand()) {// 读取温度 if ((buffer[13] & 0xFF) == 0) { // 单位摄氏度 T_TextView.setText((buffer[11] & 0xFF) + "℃"); } else { // 华氏度 T_TextView.setText((buffer[11] & 0xFF) + "℉"); } } else if (command == Commands.SensorBack.getCommand()) { // 传感器灵敏度 SSeekbar.setProgress(buffer[12] & 0xFF); Seekbar_value.setText((buffer[12] & 0xFF) + ""); } else if (command == Commands.InductorState.getCommand()) { try { Btn_state.setBackgroundColor(Color.RED); ((Inductor) Btn_state.getTag()).LastTime = Calendar.getInstance(); } catch (Exception e) { } } else if (command == Commands.ClickState.getCommand()) { int key = buffer[12] & 0xFF; switch (key) { case 0:// 弹起 key_state.setText("KEY_UP"); Log.i("adf", "KEY_UP"); break; case 1:// 按下 key_state.setText("KEY_DOWN"); Log.i("adf", "KEY_DOWN"); break; case 2:// 长按 key_state.setText("KEY_LONGPRESS"); Log.i("adf", "KEY_LONGPRESS"); break; } } else if (command == Commands.SET_TEMP_COMPENSATE_VALUE_ACK.getCommand()) { if ((buffer[11] & 0xFF) == 0xF5) { Toast.makeText(ConsoleActivity.this, "set compensate value failed", Toast.LENGTH_SHORT).show(); } } } }); } /** * Error message * * @param resourceId */ private void DisplayError(int resourceId) { AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle("Error"); b.setMessage(resourceId); b.setPositiveButton("OK", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { // ConsoleActivity.this.finish(); } }); b.show(); } @Override protected void onDestroy() { if (mReadThread != null) mReadThread.interrupt(); mApplication.closeSerialPort(); mSerialPort = null; super.onDestroy(); } private android.view.View.OnTouchListener ReadTimeButtonOnTouch = new android.view.View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (MotionEvent.ACTION_DOWN == event.getAction()) { v.setBackgroundResource(R.drawable.selected); if (mOutputStream == null) { Toast.makeText(ConsoleActivity.this, "Please Open Serial Port", android.widget.Toast.LENGTH_SHORT) .show(); } else { readDateTime(); } } else if (MotionEvent.ACTION_UP == event.getAction()) { v.setBackgroundResource(R.drawable.unselected); } return false; } }; public static Handler MainHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case INDUCTOR_LEAVE: Btn_state.setBackground(null); break; default: break; } } }; }