package com.wdkl.callingbed.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.Build;
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.callingbed.MyApplication;
import com.wdkl.callingbed.R;
import com.wdkl.callingbed.base.BaseActivity;
import com.wdkl.callingbed.common.Constants;
import com.wdkl.callingbed.entity.InitDataEntity;
import com.wdkl.callingbed.entity.MessageEvent;
import com.wdkl.callingbed.service.SoundPoolManager;
import com.wdkl.callingbed.util.AutoRebootUtil;
import com.wdkl.callingbed.util.CutSerialPortUtil;
import com.wdkl.callingbed.util.DateUtil;
import com.wdkl.callingbed.util.DownloadUtil;
import com.wdkl.callingbed.util.LogUtil;
import com.wdkl.callingbed.util.NetUtil;
import com.wdkl.callingbed.util.ScreenManagerUtil;
import com.wdkl.callingbed.util.SharedPreferencesUtil;
import com.wdkl.callingbed.util.StringUtils;
import com.wdkl.callingbed.util.ToastUtil;
import com.wdkl.callingbed.util.UdpSendUtil;
import com.wdkl.callingbed.util.sendcommand.CallingBedSendCommand;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import org.greenrobot.eventbus.EventBus;
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.callingbed.util.AutoRebootUtil.ethreboot;
import static com.wdkl.callingbed.util.sendcommand.CallingBedSendCommand.closeHeart;
import static com.wdkl.callingbed.util.sendcommand.CallingBedSendCommand.setHandsMIC;
import static com.wdkl.callingbed.util.sendcommand.CallingBedSendCommand.setNurseBrightness;
/**
* 类名称:InitActivity
* 类描述:APP初始化页面
* 创建人:Waderson
* 创建时间:2018-02-01
*
* @version V1.0
*/
public class InitActivity extends BaseActivity implements SerialPortUtil.ISerialPortBedOnclickEvent, SerialPortUtil.ISerialPortBedOnclickString {
private String TAG = InitActivity.class.getSimpleName();
@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 int countsReboot;//重启计数
@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();
}
@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();
}
//延迟发送串口命令
updateHandler.sendEmptyMessageDelayed(666, 5000);
}
@Override
protected void initData() {
//刚进来的时候将所有的护理灯全部灭掉
dismissNurseBrightness();
//20190415 waderson
ScreenManagerUtil.setScreenBrightness(context, 210);
dateRefresh();
//3分钟自动重启测试
//updateHandler.sendEmptyMessageDelayed(555, 180000);
}
@Override
public View getLoadingTargetView() {
return initView;
}
@OnClick(R.id.activity_init_layout_rl)
public void init(View view) {
isNewWork();
}
/**
* 获取网络请求地址头
*/
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() {
if (cm != null) {
//ethreboot();//wuyq add
String ipStr = NetUtil.getLocalIP();
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) { //wuyq modify
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI || networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
CallingBedSendCommand.setSipStatus(serialPortUtil, "2");
getInitData();
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 == 10) {
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);
//Log.e(TAG,"appCheckUpdate() 服务器返回版本 "+APPVersion+" 设备当前版本 "+APPVersion_Now);
ToastUtil.showToast("当前版本: " + APPVersion_Now + ", 服务器版本: " + APPVersion);
String downloadURL = object.getString("downloadURL");
if (!APPVersion_Now.equals(APPVersion)) {
if (StringUtils.notEmpty(downloadURL)) {
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() {
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地址是否注册?]");
//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!]");
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: " + "设备未启用");
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() {
new Thread(new Runnable() {
@Override
public void run() {
try {
setNurseBrightness(serialPortUtil, 1, "000000", "000000", "000000", "000000", "000000");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
private long clickTime = 0;
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();//===============================息屏
//测试喇叭及网络
if (buffer[4] == 1 || buffer[4] == 2) {
//long curTime = System.currentTimeMillis();
//if (curTime - clickTime < 2000) {
SoundPoolManager.getInstance().playSound(3);
new Thread(new Runnable() {
@Override
public void run() {
final boolean pingStatus = NetUtil.ping("192.168.101.1", 2, null);
if (pingStatus) {
showTips("连接192.168.101.1成功!");
} else {
showTips("连接192.168.101.1失败, 请检查设备!");
}
}
}).start();
//}
//clickTime = curTime;
}
//呼叫护士键短按/长按松开
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);
showTips("收到按键消息,发送注册信息:" + str);
}
}
//测试麦克风录音
if ("rk3128".equals(Build.MODEL)) {
if (buffer[6] == 2) {
if (!isRecord && !isPlay) {
startRecording();
updateHandler.sendEmptyMessageDelayed(111, 3000);
}
}
} else {
if (buffer[6] == 1) {
if (System.currentTimeMillis() - clickTime > 2000) {
showTips("再按一次录音");
} else {
if (!isRecord && !isPlay) {
startRecording();
updateHandler.sendEmptyMessageDelayed(111, 3000);
}
}
clickTime = System.currentTimeMillis();
}
}
}
@Override
public void serialPortBedOnclickString(String str) {
try {
String newStr = CutSerialPortUtil.delHeadAndEnd(str, "$", "#");
String content[] = newStr.split(",");
LogUtil.d("serialPortBedOnclickString", "InitActivity newStr==" + newStr);
switch (content[0]) {
case "V":
Constants.MCU_VERSION_NUMBER = content[1].substring(0, 14);
LogUtil.d("serialPortBedOnclick", "Constants.MCU_VERSION_NUMBER==" + Constants.MCU_VERSION_NUMBER);
break;
}
} catch (Exception e) {
LogUtil.d("serialPortBedOnclickString", "Exception==");
}
}
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() {
isRecord = true;
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 {
isPlay = true;
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;
case 666:
setHandsMIC(serialPortUtil, true);//使用手柄mic
break;
/*case 555:
AutoRebootUtil.reboot(MyApplication.getAppContext());
break;*/
}
}
};
public static final long DATEREFRESH_DELAYMILLIS = 8000;
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMoonEvent(MessageEvent messageEvent) {
switch (messageEvent.getType()) {
case Constants.EVENT_MGR_APP_UPDATE://APP更新
appCheckUpdate();
break;
}
}
}