package com.wdkl.callingbed2.ui; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.drawable.AnimationDrawable; import android.media.MediaPlayer; import android.media.MediaRecorder; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.ImageView; import com.google.gson.Gson; import com.wdkl.callingbed2.MyApplication; import com.wdkl.callingbed2.R; import com.wdkl.callingbed2.base.BaseActivity; import com.wdkl.callingbed2.common.Constants; import com.wdkl.callingbed2.entity.InitDataEntity; import com.wdkl.callingbed2.entity.MessageEvent; import com.wdkl.callingbed2.service.SoundPoolManager; import com.wdkl.callingbed2.util.AutoRebootUtil; import com.wdkl.callingbed2.util.CutSerialPortUtil; import com.wdkl.callingbed2.util.DateUtil; import com.wdkl.callingbed2.util.DownloadUtil; import com.wdkl.callingbed2.util.LogUtil; import com.wdkl.callingbed2.util.NetUtil; import com.wdkl.callingbed2.util.ScreenManagerUtil; import com.wdkl.callingbed2.util.SharedPreferencesUtil; import com.wdkl.callingbed2.util.StringUtils; import com.wdkl.callingbed2.util.ToastUtil; import com.wdkl.callingbed2.util.UdpSendUtil; import com.wdkl.callingbed2.util.VoiceManagerUtil; import com.wdkl.callingbed2.util.ethernetwifiwithsipconnectstatus.WifiNet; import com.wdkl.callingbed2.util.sendcommand.CallingBedSendCommand; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.StringCallback; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.json.JSONObject; import java.io.File; import java.io.IOException; import butterknife.Bind; import butterknife.OnClick; import okhttp3.Call; import serialporttest.utils.SerialPortUtil; import static com.wdkl.callingbed2.util.AutoRebootUtil.ethreboot; import static com.wdkl.callingbed2.util.sendcommand.CallingBedSendCommand.closeHeart; import static com.wdkl.callingbed2.util.sendcommand.CallingBedSendCommand.setCallStatus; import static com.wdkl.callingbed2.util.sendcommand.CallingBedSendCommand.setNurseBrightness; /** * 类名称:InitActivity
* 类描述:APP初始化页面
* 创建人:Waderson
* 创建时间:2018-02-01
* * @version V1.0 */ public class InitActivity extends BaseActivity implements SerialPortUtil.ISerialPortBedOnclickEvent, SerialPortUtil.ISerialPortBedOnclickString { @Bind(R.id.activity_init_layout_rl) View initView; @Bind(R.id.activity_init_layout_iv_loading) ImageView ivLoading; AnimationDrawable animationDrawable; ConnectivityManager cm; /** * mac地址 */ String macAddress = ""; SerialPortUtil serialPortUtil; private static int countsReboot = 0;//重启计数 private boolean wifiEnabled = false; @Override public int getLayoutId() { return R.layout.activity_init_layout; } @Override protected void initView() { ivLoading.setVisibility(View.VISIBLE); animationDrawable = (AnimationDrawable) ivLoading.getBackground(); animationDrawable.start(); SoundPoolManager.getInstance().init(); VoiceManagerUtil.setMusicVoice(MyApplication.getAppContext(), 100); } @Override protected void initUtil() { serialPortUtil = MyApplication.serialPortUtil; serialPortUtil.setOnDataReceiveListener(this); serialPortUtil.setOnDataReceiveStringListener(this); File file = new File(TEST_AUDIO_FILE_PATH); if (!file.exists()) { file.mkdir(); } //重置分机灯 setCallStatus(serialPortUtil, "0"); } @Override protected void initData() { //刚进来的时候将所有的护理灯全部灭掉 dismissNurseBrightness(); //20190415 waderson ScreenManagerUtil.setScreenBrightness(context, 210); //startEnableWifi(); dateRefresh(); } @Override public View getLoadingTargetView() { return initView; } @OnClick(R.id.activity_init_layout_rl) public void init(View view) { //isNewWork(); } private void startEnableWifi() { wifiEnabled = WifiNet.getInstance().enableWifi(); } /** * 获取网络请求地址头 */ private void getLocalWayAddress() { try { //Constants.URL = "http://" + NetUtil.getLocalElement(NetUtil.getLocalInetAddress().toString()); Constants.URL = "http://" + NetUtil.getLocalElement(3); } catch (Exception e) { LogUtil.e("getLocalWayAddress", "Exception==" + e.toString()); CallingBedSendCommand.setSipStatus(serialPortUtil, "0"); showNetErrorView("MAC地址: " + macAddress + "\nError:请检查网络连接是否正常" + "\n" + AutoRebootUtil.getTextTip()); e.printStackTrace(); } } /** * 获取MAC地址 */ private void getMacAddress() { if (NetUtil.isethernetConnected(cm)) { macAddress = NetUtil.getMacAddress(); if (null != macAddress) { SharedPreferences sharedPreferences = getSharedPreferences(Constants.MSG_SP, Context.MODE_PRIVATE); //私有数据 SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("macAddress", macAddress); editor.commit();//提交修改 } } else { SharedPreferences sharedPreferences = getSharedPreferences(Constants.MSG_SP, Context.MODE_PRIVATE); //私有数据 macAddress = sharedPreferences.getString("macAddress", null); } LogUtil.d("getMacAddress", "macAddress==" + macAddress); Constants.MAC_ADDRESS = macAddress; } /** * 判断网络连接 * 无网络显示错误页面 */ public void isNewWork() { //尝试连接wifi if (wifiEnabled) { boolean connect = WifiNet.getInstance().connectWifi("NCS", "23456789"); } if (cm != null) { //ethreboot();//wuyq add String ipStr = NetUtil.getLocalIP(); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); LogUtil.d("initwifi", "network info: " + networkInfo); if (networkInfo != null && networkInfo.isConnected()) { //wuyq modify LogUtil.d("Initwifi", "network type: " + networkInfo.getType() + ", network typeName: " + networkInfo.getTypeName()); if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI || networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) { CallingBedSendCommand.setSipStatus(serialPortUtil, "2"); getInitData(networkInfo.getTypeName()); countsReboot = 0; //wuyq add } else { updateHandler.sendEmptyMessageDelayed(404, DATEREFRESH_DELAYMILLIS); showNetErrorView("MAC地址: " + macAddress + " IP地址: " + ipStr + "\nError:本地网络或wifi连接错误"); ToastUtil.showToast("本地网络或wifi连接错误"); CallingBedSendCommand.setSipStatus(serialPortUtil, "0"); } } else { //updateHandler.sendEmptyMessageDelayed(404, DATEREFRESH_DELAYMILLIS);//wuyq remove updateHandler.sendEmptyMessageDelayed(4444, DATEREFRESH_DELAYMILLIS);//wuyq add CallingBedSendCommand.setSipStatus(serialPortUtil, "0"); showNetErrorView("MAC地址: " + macAddress + " IP地址: " + ipStr + "\nError:无网络连接;网络是否连接正常?");//网络信息初始化错误 ToastUtil.showToast("无网络连接;网络是否连接正常?");//网络信息初始化错误 resetEthernet(); } } else { updateHandler.sendEmptyMessageDelayed(404, DATEREFRESH_DELAYMILLIS); showNetErrorView("MAC地址: " + macAddress + "\nError:ConnectivityManager初始化失败"); CallingBedSendCommand.setSipStatus(serialPortUtil, "0"); ToastUtil.showToast("ConnectivityManager初始化失败"); } } /** * =================================================(网络不通)15次以上自动重启系统===================================================== */ private void resetEthernet() { if (countsReboot == 15) { updateHandler.sendEmptyMessage(222); countsReboot = 0; } countsReboot++; } /** * 检查APP更新版本 * */ private void appCheckUpdate() { if (!StringUtils.notEmpty(Constants.URL)) return; if (!StringUtils.notEmpty(Constants.PartID)) return; try { OkHttpUtils.post().url(Constants.URL + Constants.URL_END + Constants.APP_CHECK_UPDATE) .addParams("PartID", Constants.PartID) .build() .execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { Constants.UPDATE_APP_FLAG = false; } @Override public void onResponse(String response, int id) { String data = response.substring(0, response.length() - 4); LogUtil.d("appCheckUpdate", "appCheckUpdate==" + data); try { JSONObject object = new JSONObject(data); if (object.getString("Code").equals("OK!")) { String APPVersion = StringUtils.deleteCharAt(object.getString("APPVersion"), 0); String APPVersion_Now = StringUtils.getAppVersionName(InitActivity.this); String downloadURL = object.getString("downloadURL"); if (!APPVersion_Now.equals(APPVersion)) { if (StringUtils.notEmpty(downloadURL)) { ToastUtil.showToast("开始下载! 当前版本: " + APPVersion_Now + ", 服务器版本: " + APPVersion); closeHeart();//关闭心跳 Intent intent = new Intent(InitActivity.this, APPUpdateActivity.class); intent.putExtra("downLoadURL", Constants.URL + Constants.URL_END + "/" + downloadURL); startActivity(intent); } } } } catch (Exception e) { e.printStackTrace(); Constants.UPDATE_APP_FLAG = false; } } }); } catch (Exception e) { Constants.UPDATE_APP_FLAG = false; e.printStackTrace(); } } /** * 获取初始化信息 */ private void getInitData(final String type) { LogUtil.d("getInitData", "URL==" + Constants.URL + Constants.URL_END + Constants.CALLINGBED_INIT); final String ipStr = NetUtil.getLocalIP(); //网络恢复正常,重置重启计数 if (!TextUtils.isEmpty(ipStr)) { SharedPreferencesUtil.putIntSp(context, Constants.REBOOT_COUNT, Constants.REBOOT_COUNT, 0); } if (Constants.URL.length() > 7) { OkHttpUtils .post() .url(Constants.URL + Constants.URL_END + Constants.CALLINGBED_INIT) .addParams("deviceMAC", macAddress) .build() .execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { ivLoading.setVisibility(View.INVISIBLE); dismissNurseBrightness(); showNetErrorView("MAC地址: " + macAddress + " IP地址: " + ipStr + "\nError:" + "初始化数据请求错误[MAC地址是否注册?], " + type); //updateHandler.sendEmptyMessageDelayed(404, DATEREFRESH_DELAYMILLIS);//wuyq remove updateHandler.sendEmptyMessageDelayed(4444, DATEREFRESH_DELAYMILLIS);//wuyq add ToastUtil.showToast("初始化数据请求错误"); } @Override public void onResponse(String response, int id) { String data = response.substring(0, response.length() - 4); ivLoading.setVisibility(View.INVISIBLE); LogUtil.d("getInitData", "getInitData==" + data); try { showContent(); JSONObject object = new JSONObject(data); if (object.getString("Code").equals("ERROR!")) { dismissNurseBrightness(); showNetErrorView("MAC地址: " + macAddress + " IP地址: " + ipStr + "\nError:" + "数据错误异常[ERROR!], " + type); updateHandler.sendEmptyMessageDelayed(404, DATEREFRESH_DELAYMILLIS); ToastUtil.showToast("数据请求失败"); } else { if (object.getString("deviceStatus").equals("1")) { Gson gson = new Gson(); InitDataEntity initDataEntity = gson.fromJson(data, InitDataEntity.class); saveData(initDataEntity); Intent intent = new Intent(); intent.putExtra(Constants.INITENTITY, initDataEntity); intent.setClass(InitActivity.this, CallingBedActivity.class); startActivity(intent); InitActivity.this.finish(); } else { dismissNurseBrightness(); showNetErrorView("MAC地址: " + macAddress + " IP地址: " + ipStr + "\nError: " + "设备未启用, " + type); updateHandler.sendEmptyMessageDelayed(404, DATEREFRESH_DELAYMILLIS); ToastUtil.showToast("设备未启用"); } } } catch (Exception e) { LogUtil.d("getInitData", "getInitData==Exception"); showNetErrorView("MAC地址: " + macAddress + "\nError:" + "Response was Exception"); e.printStackTrace(); } } }); } } private void saveData(InitDataEntity initDataEntity) { if (null != initDataEntity) { Constants.SIP_ID = initDataEntity.getDeviceSipId(); Constants.SIP_PASS_WORD = initDataEntity.getDeviceSipPassWord(); Constants.SIP_IP = initDataEntity.getDeviceSipIp(); Constants.DEVICE_WIFI_HOST_NAME = initDataEntity.getDeviceWifiHostName(); Constants.BED_ID = initDataEntity.getId(); Constants.CALLMAIN_ID = initDataEntity.getDeviceHostingID(); Constants.MYSELF_ID = initDataEntity.getId(); Constants.ROOM_ID = initDataEntity.getDeviceRoomId(); Constants.DEVICE_SCREEN_SLEEP = initDataEntity.getDeviceScreamSleep(); Constants.DEVICE_HUMAN_ID = initDataEntity.getDeviceHumanId(); Constants.PartID = initDataEntity.getPartId(); LogUtil.d("saveData", "deviceHostingID==" + initDataEntity.getDeviceHostingID()); if (StringUtils.notEmpty(initDataEntity.getDeviceHostingID())) { String n = StringUtils.substringByLengh(initDataEntity.getDeviceHostingID(), 0, 1); if ("#".equals(n)) {//服务器托管状态:处于托管中 String nDis = StringUtils.deleteCharAt(initDataEntity.getDeviceHostingID(), 0); Constants.DEVICE_HOSTING_ID = nDis.split(",")[0]; Constants.TRUST_NEW_MAIN_ID = nDis.split(",")[1]; } else {//服务器托管状态:处于未托管 Constants.DEVICE_HOSTING_ID = initDataEntity.getDeviceHostingID(); Constants.TRUST_NEW_MAIN_ID = ""; } } setSystemTime(initDataEntity); } } /** * 设置系统时间 (邓喆) * * @param initDataEntity */ private void setSystemTime(InitDataEntity initDataEntity) { LogUtil.d("setSystemTime", initDataEntity.getCurTime()); String[] time = initDataEntity.getCurTime().trim().split(" "); String[] day = time[0].split("/"); String[] hour = time[1].split(":"); //=================设置时间(可用) DateUtil.setSystemTime(this, Integer.valueOf(day[0]), Integer.valueOf(day[1]) - 1, Integer.valueOf(day[2]) , Integer.valueOf(hour[0]), Integer.valueOf(hour[1]), Integer.valueOf(hour[2])); // if (!TimeUtil.isRoot()) { // String t = initDataEntity.getCurTime().trim().replaceAll("/", "").replace(":", "").replace(" ", "."); // if (t != null && t != "") { // TimeUtil.setSysDate(t); // } // } } @Override public void onReload() { super.onReload(); dateRefresh(); } public void dateRefresh() { cm = (ConnectivityManager) MyApplication.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE); if (null != cm) getMacAddress(); getLocalWayAddress(); isNewWork(); } @Override protected void onDestroy() { super.onDestroy(); animationDrawable.stop(); updateHandler.removeCallbacksAndMessages(null); updateHandler = null; serialPortUtil = null;//2018-01-10 add by Waderson } /** * 灭掉护理灯 */ public void dismissNurseBrightness() { //7寸分机无护理灯 /*new Thread(new Runnable() { @Override public void run() { try { setNurseBrightness(serialPortUtil, 1, "000000", "000000", "000000", "000000", "000000"); } catch (InterruptedException e) { e.printStackTrace(); } } }).start();*/ } private boolean isRecord = false; private boolean isPlay = false; public static final String TEST_AUDIO_FILE_PATH = Environment.getExternalStorageDirectory().getPath() + "/test"; private String audiofilePath; private MediaRecorder mediaRecorder; private MediaPlayer mediaPlayer; /** * 监听呼叫按钮 buffer[5] 如果按下则 放松注册信息给后台 */ @Override public void serialPortBedOnclick(byte[] buffer) { // mScreenExtinguishUtil.touchScreen();//===============================息屏 LogUtil.d("serialPortBedOnclick", "buffer[5]==" + buffer[5] + ", buffer[8]==" + buffer[8]); //呼叫护士键短按/长按松开 if (buffer[5] == 1 | buffer[5] == 2) { if (null != Constants.MAC_ADDRESS) { //有线mac地址,设备出场信息,无线mac地址 final String str = "MGR_REG_A" + Constants.DELIMITER + Constants.MAC_ADDRESS + Constants.DELIMITER + "4" + Constants.DELIMITER + android.os.Build.DISPLAY +"_"+Constants.MCU_VERSION_NUMBER + Constants.DELIMITER + Constants.MAC_ADDRESS + Constants.DELIMITER + "FF:FF:FF:FF:FF:FF" + Constants.DELIMITER + SerialPortUtil.KEY_ID; UdpSendUtil.sendManualReboot(str); runOnUiThread(new Runnable() { @Override public void run() { ToastUtil.showToast("收到按键消息,发送注册信息:" + str); } }); } } if (buffer[8] == 2) { SoundPoolManager.getInstance().playSound(3); new Thread(new Runnable() { @Override public void run() { boolean pingStatus = NetUtil.ping("192.168.101.1", 2, null); if (pingStatus) { showTips("连接192.168.101.1成功!"); } else { showTips("连接192.168.101.1失败, 请检查设备!"); } } }).start(); } //测试麦克风录音 if (buffer[6] == 2) { if (!isRecord && !isPlay) { startRecording(); updateHandler.sendEmptyMessageDelayed(111, 3000); } } } @Override public void serialPortBedOnclickString(String str) { try { String newStr = str.substring(str.indexOf("$") + 1, str.indexOf("#")); LogUtil.d("serialPortBedOnclickString", "newStr==" + newStr); if (newStr.startsWith("V")) { Constants.MCU_VERSION_NUMBER = newStr.substring(newStr.indexOf(",") + 1, 16); LogUtil.d("serialPortBedOnclick", "Constants.MCU_VERSION_NUMBER==" + Constants.MCU_VERSION_NUMBER); } } catch (Exception e) { e.printStackTrace(); } } private void showTips(final String tips) { runOnUiThread(new Runnable() { @Override public void run() { ToastUtil.showToast(tips); } }); } private void startRecording() { showTips("开始录音"); new Thread(new Runnable() { @Override public void run() { mediaRecorder = new MediaRecorder(); try { audiofilePath = TEST_AUDIO_FILE_PATH + "/" + System.currentTimeMillis() + "_test.mp3"; mediaRecorder.setOutputFile(audiofilePath); mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置MediaRecorder的音频源为麦克风 mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);// 设置MediaRecorder录制的音频格式 mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);// 设置MediaRecorder录制音频的编码为amr mediaRecorder.prepare(); mediaRecorder.start(); } catch (IOException e) { Log.i("error", "call startAmr(File mRecAudioFile) failed!" + e.getMessage()); } finally { isRecord = false; } } }).start(); } private void stopRecord() { showTips("结束录音"); new Thread(new Runnable() { @Override public void run() { try { mediaRecorder.stop(); mediaRecorder.release(); mediaRecorder = null; Thread.sleep(200); mediaPlayer = new MediaPlayer(); mediaPlayer.reset(); mediaPlayer.setDataSource(audiofilePath); mediaPlayer.setVolume(1.0f, 1.0f); mediaPlayer.prepare(); mediaPlayer.start(); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer player) { File file = new File(audiofilePath); if (file.exists()) { file.delete(); } mediaPlayer.release(); } }); mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer player, int what, int extra) { File file = new File(audiofilePath); if (file.exists()) { file.delete(); } mediaPlayer.release(); return false; } }); }catch (Exception e) { e.printStackTrace(); } finally { isPlay = false; } } }).start(); } @SuppressLint("HandlerLeak") Handler updateHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 404: dateRefresh(); break; case 4444: // wuyq add ethreboot(); dateRefresh(); break; case 111: if (!isPlay) { stopRecord(); } break; case 222: int count = SharedPreferencesUtil.getIntSp(context, Constants.REBOOT_COUNT, Constants.REBOOT_COUNT); LogUtil.d("wzlll", "NetReset reboot count: " + count); if (count >= 10) { ToastUtil.showToast("设备出现异常,请确保网络连接正常或重启设备"); } else { count++; SharedPreferencesUtil.putIntSp(context, Constants.REBOOT_COUNT, Constants.REBOOT_COUNT, count); ToastUtil.showToast("网络异常,即将重启"); updateHandler.sendEmptyMessageDelayed(333, 5000); } break; case 333: LogUtil.d("wzlll", "NetReset reboot..."); AutoRebootUtil.reboot(MyApplication.getAppContext()); CallingBedSendCommand.setNetStatus(serialPortUtil, "1"); break; } } }; public static final long DATEREFRESH_DELAYMILLIS = 10000; @Subscribe(threadMode = ThreadMode.MAIN) public void onMoonEvent(MessageEvent messageEvent) { switch (messageEvent.getType()) { case Constants.EVENT_MGR_APP_UPDATE://APP更新 appCheckUpdate(); break; } } }