package com.example.yunfeiapplication; import android.Manifest; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Color; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.ConnectivityManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.RemoteException; import android.provider.Settings; import android.telephony.SignalStrength; import android.telephony.SubscriptionInfo; import android.telephony.SubscriptionManager; import android.telephony.TelephonyManager; import android.util.Log; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.widget.Toast; import androidx.activity.EdgeToEdge; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.FragmentResultListener; import com.alibaba.fastjson.TypeReference; import com.example.yunfeiapplication.fragments.FragmentMac0; import com.example.yunfeiapplication.fragments.FragmentMac1; import com.example.yunfeiapplication.fragments.FragmentMac2; import com.example.yunfeiapplication.fragments.FragmentMac3; import com.example.yunfeiapplication.fragments.FragmentMac4; import com.example.yunfeiapplication.fragments.FragmentMac5; import com.example.yunfeiapplication.managerClass.CustomAudioPlayerManager; import com.example.yunfeiapplication.managerClass.CustomJsonProcessorManager; import com.example.yunfeiapplication.managerClass.CustomYModemManager; import com.example.yunfeiapplication.managerClass.FtpTransferManager; import com.example.yunfeiapplication.managerClass.MvccCameraManager; import com.example.yunfeiapplication.managerClass.SerialManager; import com.example.yunfeiapplication.managerClass.UserMqttManager; import com.example.yunfeiapplication.ownClass.FastJsonUtils; import com.example.yunfeiapplication.ownClass.HistoryDataManager; import com.example.yunfeiapplication.variable.UserGlobalVariable; import com.google.android.material.navigation.NavigationView; import com.hzmct.enjoysdk.api.EnjoySDK; import com.hzmct.enjoysdk.transform.EnjoyApiNotSupportException; import com.mc.android.mckeepalive.McKeepAliveApp; import com.wif.baseservice.IBaseServiceCallback; import com.wif.baseservice.IBaseServiceInterface; import com.wif.bslib.AidlConstants; import com.wif.bslib.AidlRequest; import com.wif.bslib.AidlResponse; import com.wif.bslib.BaseRequest; import com.wif.bslib.BaseResponse; import com.wif.bslib.bean.LocationInfo; import org.apache.commons.net.ftp.FTPClient; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; /* * 1.安卓设备取消默认启动应用 * 命令:adb shell * monkey -p com.hzmct.enjoyConfig 1 * 2.取消应用保活 * EnjoySDK enjoySDK = new EnjoySDK(context); * int ret = enjoySDK.EnableKeepAlive(false); * */ public class MainActivity extends AppCompatActivity implements CustomJsonProcessorManager.CustomMessageInterface { private static final int PLATFROM_TYPE_MAICHONG = 1; private static final int PLATFROM_TYPE_WANGFEI = 2; private final int USER_PLATFORM_TYPE = PLATFROM_TYPE_WANGFEI; EnjoySDK enjoySDK; private IBaseServiceInterface serviceInterface; private AidlCallback AidlCallback; private BaseServiceConnection ServiceConnection; private boolean BaseServiceConnectionFlag = false; private boolean HeartBeatFirstReportFlag = true; private static final String TAG_UPGRADE_OPERATE = "UpgradeOperate"; private static final String TAG_LOG_MANAGER = "MacLogOperate"; private static final String TAG_CAMERA_OPERATE = "CameraTakePhoto"; private static final String TAG_PLATFORM_MAICHON = "MacPlatformMaiChong"; private static final String TAG_PLATFORM_WANGFEI = "MacPlatformWangFei"; private static final String TAG_FMACX_MSG_TO_MAC = "FMacXMessageToMainActivity"; private static final String TAG_FTP_APP_UPGRADE = "FMacFtpAppUpgrade"; private static final String TAG_REQUEST_PERMISSIONS = "RequestPermissions"; private static final String TAG_SYSTEM_PARAMETER_SP = "SystemParameterSP"; private static final String TAG_HISTORY_DATA = "HistoryData"; /* 滑动侧边栏 */ DrawerLayout MainDrawerLayout; NavigationView MainNavigationView; private int OldFragmentIndex; /* 当前Fragment页面标签号 */ private int MacGetPhoneStateInfoTime = 0; private boolean MacGetPhoneStateInfoFlag = true; /* 定位相关 */ private LocationManager locationManager; private LocationListener locationListener; /* 设备操作日志相关 */ private LogFileManager LogFileManagerOperate; /* 音频播放相关 */ CustomAudioPlayerManager MacAudioPlayer; private boolean VoicePlayingFlag = false; private int VoicePlayingID = 0; /* 系统永久变量存储相关 */ SharedPreferences SystemParameterSettings; // SharedPreferences文件名 private static final String PREFS_NAME = "SystemParameterSP"; // SharedPreferences中的键 private static final String SYS_PARA_CLIENT_SERVER_INFO = "ClientServerInfo"; private static final String SYS_PARA_CAMERA_TAKE_PHOTO_WAIT_EXPOSURE = "CameraTakePhotoWaitExposure"; private static final String SYS_PARA_GPS_LONGITUDE = "GPSLongitude"; private static final String SYS_PARA_GPS_LATITUDE = "GPSLatitude"; /* 秒触发Handler */ private final Handler MacOneSecondTriggerHandler = new Handler(Looper.getMainLooper()); private Runnable MacOneSecondTiggerRunnable; JSONObject MacUpgradeInfoJson = new JSONObject(); //大数据平台 int MacDeviceDataToServerTime = 0; boolean MacAppHeartbeatFlag = true; int CustomerMqttHeartbeatToServerTime = 0; boolean CustomerMqttHeartbeatToServerFlag = true; private final String MQTT_MAIN_SUB_TOPIC = "/yfkj/XCT/sub/"; private final String MQTT_MAIN_PUB_TOPIC = "/yfkj/XCT/pub/"; private final String MQTT_MAIN_HOST_URL = "tcp://8.136.98.49:61883"; private final String MQTT_MAIN_USER = "user"; private final String MQTT_MAIN_PASSWORD = "f335bf402c655ee5fd2b5300905124e"; private final String FTP_INFO_HOST_URL = "8.136.98.49"; private final int FTP_INFO_HOST_PORT = 21; private final String FTP_INFO_HOST_USER = "cbd_XCT"; private final String FTP_INFO_HOST_PASSWD = "YFkj@6O2O"; private boolean MacExecuteShellSilentFlag = false; SerialManager serialManager; CustomJsonProcessorManager customJsonProcessorManager; UserMqttManager userMqttManager = null; UserMqttManager customerMqttManager = null; public static MainActivity Instance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Instance = this; //EdgeToEdge.enable(this); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); hideSystemUI(); /*ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> { Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()); v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); return insets; });*/ /* 加载存储的系统参数 */ SystemParameterSettings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); MacGetSystemParameterSP(); /* 平台选择 */ if (PLATFROM_TYPE_MAICHONG == USER_PLATFORM_TYPE) { MaiChongPlatformSInit(); //MacStartLocationUpdates(); MacHideSystemUI(); } else { AidlCallback = new AidlCallback(); ServiceConnection = new BaseServiceConnection(); Intent intent = new Intent(AidlConstants.ACTION_BASE_SERVICE); intent.setPackage(AidlConstants.PACKAGE_BASE_SERVICE); bindService(intent, ServiceConnection, BIND_AUTO_CREATE); } /* 启动GPS位置信息获取服务 */ MacStartLocationUpdates(); /* 修改相机权限及设置缓冲区 */ MacSystemExecuteShellCommand(); /*获取定位、手机状态、存储权限*/ GetSelfPermissionPhoneState(); /* 程序运行起始界面, Modified by NiuJiuRu @2025-05-20 */ FragmentMac0 fragment = new FragmentMac0(); getSupportFragmentManager() .beginTransaction() .replace(R.id.mainFragmentContainerView, fragment) .commitNow(); //getSupportFragmentManager().beginTransaction().replace(R.id.mainFragmentContainerView, FragmentMac0.class,null).commit(); OldFragmentIndex = 0; /* 侧边栏初始化 */ MainNavigationView = findViewById(R.id.mainNavigationView); MainNavigationView.setItemIconTintList(null); MainDrawerLayout = findViewById(R.id.mainDrawerLayout); MainDrawerLayout.setScrimColor(Color.TRANSPARENT); /* 日志记录初始化 */ LogFileManagerOperate = new LogFileManager(); LogFileManagerOperate.VerifyLogFileConformsToJson(); MacAudioPlayer = new CustomAudioPlayerManager(getApplicationContext()); /* 串口初始化 */ serialManager = SerialManager.getInstance(); customJsonProcessorManager = new CustomJsonProcessorManager(); serialManager.setDataProcessor(customJsonProcessorManager); customJsonProcessorManager.setCustomMessageInterface(this); /* 主线程初始化 */ ThreadMainActivity threadMainActivity = new ThreadMainActivity(); threadMainActivity.start(); if (isMobileDataEnabled(this)) { Log.i("TAG", "onCreate: 数据流量开关已开启"); }else{ Log.i("TAG", "onCreate: 数据流量开关已关闭"); setMobileDataEnabledByRoot(true); } /*** 侧边栏点击事件处理 ***/ MainNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { int itemId = item.getItemId(); int tempIndex = 0; if (itemId == R.id.menu_item_1) { tempIndex = 1; } else if (itemId == R.id.menu_item_2) { tempIndex = 2; } else if (itemId == R.id.menu_item_3) { tempIndex = 3; } else if (itemId == R.id.menu_item_4) { tempIndex = 4; } else if (itemId == R.id.menu_item_5) { tempIndex = 5; } else if (itemId == R.id.menu_item_6) { tempIndex = 6; } String tempStr = UserGlobalVariable.getValue("login"); if(tempStr != null && !tempStr.isEmpty()){ /* 监测是否已登录成功,否则点击侧边栏时不跳转. */ if(tempStr.equals("1")){ /* 如果此时准备跳转至'相机操作'界面但主线程正在执行自动拍照则不执行界面跳转操作 */ //20250414MARK01-1:界面跳转时相机忙。 if ((OldFragmentIndex == 2 || OldFragmentIndex == 3) && MvccCameraManager.getInstance().getCameraState()) { Log.i(TAG_CAMERA_OPERATE,"Camera Is Busy #1!!!"); VoicePlayingFlag = true; VoicePlayingID = 9; } else { MacReplaceFragment(tempIndex); } }else{ //20250413MARK02 if(OldFragmentIndex != 0){ UserGlobalVariable.setlValue("login","1"); Log.i(TAG_CAMERA_OPERATE,"登录状态异常,更正为已登录."); } } } /* 点击侧边栏500毫秒后自动收起 */ MainNavigationView.postDelayed(new Runnable() { @Override public void run() { if (MainDrawerLayout.isDrawerOpen(MainNavigationView)) { MainDrawerLayout.closeDrawer(MainNavigationView); MainDrawerLayout.requestDisallowInterceptTouchEvent(true); } } },500); return false; } }); /*** 监听及解析来自FragmentMac0的消息 ***/ getSupportFragmentManager().setFragmentResultListener("FMac0ToMainActivity", this, new FragmentResultListener() { @Override public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) { /*** 解析语音类型 ***/ String strVoiceType = result.getString("SystemVoiceID"); if(strVoiceType != null){ VoicePlayingFlag = true; VoicePlayingID = Integer.parseInt(strVoiceType); } /*** 解析操作日志类型 ***/ String strOptEvents = result.getString("OptEvents"); if (strOptEvents != null) { Log.i(TAG_FMACX_MSG_TO_MAC, "FromFMac0->> OptEvents = " + strOptEvents); LogFileManagerOperate.VerifyLogFileConformsToJson(); LogFileManagerOperate.CheckLogFileNumber(); LogFileManagerOperate.AddOneLogItem(strOptEvents); } String strOptCommand = result.getString("OptCommand"); if (strOptCommand != null) { /* 用户登录验证成功,跳转至‘工作状态’操作界面 */ if (strOptCommand.equals("1")) { MacReplaceFragment(1); } else if(strOptCommand.equals("2")) { if (PLATFROM_TYPE_MAICHONG == USER_PLATFORM_TYPE) { MaiChongStartRawLauncher(); } else { if (PLATFROM_TYPE_WANGFEI == USER_PLATFORM_TYPE) { RequestKioskMode(false); // 退出霸屏模式 } finish(); } } } } }); /*** 监听及解析来自FragmentMac1的消息 ***/ getSupportFragmentManager().setFragmentResultListener("FMac1ToMainActivity", this, new FragmentResultListener() { @Override public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) { String resString = result.getString("OptCommand"); /* FMac1界面按钮操作解析 */ if (resString != null) { MainSerialSendFragmentMac1OperateCommand(resString); } /*** 解析操作日志类型 ***/ String strOptEvents = result.getString("OptEvents"); if (strOptEvents != null) { Log.i(TAG_FMACX_MSG_TO_MAC,"FromFMac1->> OptEvents = " + strOptEvents); LogFileManagerOperate.VerifyLogFileConformsToJson(); LogFileManagerOperate.CheckLogFileNumber(); LogFileManagerOperate.AddOneLogItem(strOptEvents); } /*** 解析语音类型 ***/ String strVoiceType = result.getString("SystemVoiceID"); if(strVoiceType != null){ VoicePlayingFlag = true; VoicePlayingID = Integer.parseInt(strVoiceType); } } }); /*** 监听及解析来自FragmentMac2的消息 ***/ getSupportFragmentManager().setFragmentResultListener("FMac2ToMainActivity", this, new FragmentResultListener() { @Override public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) { /*** 解析操作日志类型 ***/ String strOptEvents = result.getString("OptEvents"); if (strOptEvents != null) { Log.i(TAG_FMACX_MSG_TO_MAC,"FromFMac2->> OptEvents = " + strOptEvents); LogFileManagerOperate.VerifyLogFileConformsToJson(); LogFileManagerOperate.CheckLogFileNumber(); LogFileManagerOperate.AddOneLogItem(strOptEvents); } /*** 解析语音类型 ***/ String strVoiceType = result.getString("SystemVoiceID"); if (strVoiceType != null) { VoicePlayingFlag = true; VoicePlayingID = Integer.parseInt(strVoiceType); } } }); /*** 监听及解析来自FragmentMac3的消息 ***/ getSupportFragmentManager().setFragmentResultListener("FMac3ToMainActivity", this, new FragmentResultListener() { @Override public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) { /* 向MCU获取指定页面的操作记录信息 */ String resString = result.getString("PageOperate"); if (resString != null) { Log.i(TAG_FMACX_MSG_TO_MAC,"FMac3ToMac->> PageOperate = " + resString); JSONObject jsonMainObject = new JSONObject(); JSONObject jsonSubObject = new JSONObject(); try { jsonSubObject.put("ecode_pagenum",Integer.parseInt(resString)); } catch (JSONException e) { throw new RuntimeException(e); } try { jsonMainObject.put("cmd","paramconf"); // jsonSubObject.put("no_reply", "1"); jsonMainObject.put("ext",jsonSubObject); } catch (JSONException e) { throw new RuntimeException(e); } if(!SerialManager.getInstance().getUpgradingFlag()){ SerialManager.getInstance().write(jsonMainObject.toString().getBytes());//指令下发与升级冲突#2 } } /* 向MCU获取操作记录页面和数据总数信息 */ resString = result.getString("GetPageInfo"); if (resString != null) { Log.i(TAG_FMACX_MSG_TO_MAC, "获取MCU端操作日志数据信息."); String Command = "{\"cmd\":\"ReadEcodeInfo\"}"; if(!SerialManager.getInstance().getUpgradingFlag()){ SerialManager.getInstance().write(Command.getBytes());//指令下发与升级冲突#3 } } } }); /*** 监听及解析来自FragmentMac5的消息 ***/ getSupportFragmentManager().setFragmentResultListener("FMac5ToMainActivity", this, new FragmentResultListener() { @Override public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) { String resString = result.getString("FMac5Command"); if (resString != null) { Log.i(TAG_FMACX_MSG_TO_MAC, "FMac5ToMac->> " + resString); MainSerialSendFragmentMac1OperateCommand(resString); } /*** 解析语音类型 ***/ String strVoiceType = result.getString("SystemVoiceID"); if(strVoiceType != null){ VoicePlayingFlag = true; VoicePlayingID = Integer.parseInt(strVoiceType); } } }); MacOneSecondTiggerRunnable = new Runnable() { @Override public void run() { /* 设备心跳 */ MacDeviceDataToServerTime++; if(MacDeviceDataToServerTime > 30){ MacDeviceDataToServerTime = 0; MacAppHeartbeatFlag = true; if (USER_PLATFORM_TYPE == PLATFROM_TYPE_WANGFEI) { WifRequestLocationInfo(); } } /* 设备心跳 */ CustomerMqttHeartbeatToServerTime++; if(CustomerMqttHeartbeatToServerTime > 30){ CustomerMqttHeartbeatToServerTime = 0; CustomerMqttHeartbeatToServerFlag = true; } MacGetPhoneStateInfoTime++; if(MacGetPhoneStateInfoTime > 60){ MacGetPhoneStateInfoTime = 0; MacGetPhoneStateInfoFlag = true; } if(UserGlobalVariable.Mqtt_M_ReConnect_Flag == 2){ if(UserGlobalVariable.Mqtt_M_ReConnect_Time >= 30){ UserGlobalVariable.Mqtt_M_ReConnect_Time = 0; UserGlobalVariable.Mqtt_M_ReConnect_Flag = 1; }else{ UserGlobalVariable.Mqtt_M_ReConnect_Time ++; } } if(UserGlobalVariable.Customer_Mqtt_ReConnect_Flag == 2){ if(UserGlobalVariable.Customer_Mqtt_ReConnect_Time >= 30){ UserGlobalVariable.Customer_Mqtt_ReConnect_Time = 0; UserGlobalVariable.Customer_Mqtt_ReConnect_Flag = 1; }else{ UserGlobalVariable.Customer_Mqtt_ReConnect_Time ++; } } UserGlobalVariable.Dev_Serial_Comm_Timeout_Val ++; if(UserGlobalVariable.Dev_Serial_Comm_Timeout_Val >= 60){ UserGlobalVariable.Dev_Serial_Comm_Timeout_Val = 0; UserGlobalVariable.DevStuCode_Serial = 3; } MacOneSecondTriggerHandler.postDelayed(MacOneSecondTiggerRunnable,1000); } }; MacOneSecondTriggerHandler.postDelayed(MacOneSecondTiggerRunnable,1000); } private void hideSystemUI() { View decor = getWindow().getDecorView(); decor.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY ); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { hideSystemUI(); } } @Override protected void onResume() { super.onResume(); hideSystemUI(); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { // Log.i("MacScreenSleepTime", "dispatchTouchEvent: MacScreenSleepTime Clear."); return super.dispatchTouchEvent(ev); } @Override public void MessageBetweenActivityAndFragment(String requestKey, String key, String value) { Bundle result = new Bundle(); result.putString(key,value); getSupportFragmentManager().setFragmentResult(requestKey,result); // MainActivityMessageToFragment(requestKey,key,value); } private void MacSetSystemParameterSP(String key, String value) { // 获取编辑器并存储数据 SharedPreferences.Editor editor = SystemParameterSettings.edit(); editor.putString(key, value); editor.apply(); // 或者使用 editor.commit(); } private void MacGetSystemParameterSP() { // 获取编辑器并存储数据 String tempParameterName = SystemParameterSettings.getString(SYS_PARA_CLIENT_SERVER_INFO,"null"); if(tempParameterName.equals("null")){ Log.i(TAG_SYSTEM_PARAMETER_SP,"系统参数#01.1-> Mqtt客户端信息为空."); }else{ Log.i(TAG_SYSTEM_PARAMETER_SP,"系统参数#01.1-> Mqtt客户端信息: " + tempParameterName); try { JSONObject jsonObject = new JSONObject(tempParameterName); UserGlobalVariable.setlValue("clientServer",jsonObject.getString("clientServer")); String tempEnable = jsonObject.getString("clientServer"); if(tempEnable.equals("1")){ Log.i(TAG_SYSTEM_PARAMETER_SP,"MAC#568-> 需要连接客户服务器."); Log.i(TAG_SYSTEM_PARAMETER_SP,"MAC#569-> 客户服务器信息: " + tempParameterName); if(jsonObject.getString("mqttEnable").equals("1")){ UserGlobalVariable.Customer_Mqtt_Enable = true; UserGlobalVariable.setlValue("mqttIP",jsonObject.getString("mqttIP")); UserGlobalVariable.setlValue("mqttPort",jsonObject.getString("mqttPort")); UserGlobalVariable.setlValue("mqttUser",jsonObject.getString("mqttUser")); UserGlobalVariable.setlValue("mqttPasswd",jsonObject.getString("mqttPasswd")); UserGlobalVariable.setlValue("mqttSubTopic",jsonObject.getString("mqttSubTopic")); UserGlobalVariable.setlValue("mqttPubTopic",jsonObject.getString("mqttPubTopic")); } if(jsonObject.getString("ftpEnable").equals("1")){ UserGlobalVariable.Customer_FTP_Enable = true; UserGlobalVariable.setlValue("ftpIP",jsonObject.getString("ftpIP")); UserGlobalVariable.setlValue("ftpPort",jsonObject.getString("ftpPort")); UserGlobalVariable.setlValue("ftpUser",jsonObject.getString("ftpUser")); UserGlobalVariable.setlValue("ftpPasswd",jsonObject.getString("ftpPasswd")); UserGlobalVariable.setlValue("ftpFilePath",jsonObject.getString("ftpFilePath")); } } } catch (JSONException e) { //// Log.i("updateUserGlobalVariable", "JSONException: Error,#03"); } } // 获取编辑器并存储数据 String tempTakePhotoWaitExposure = SystemParameterSettings.getString(SYS_PARA_CAMERA_TAKE_PHOTO_WAIT_EXPOSURE,"10"); UserGlobalVariable.CameraTakePhotoWaitExposure = Integer.parseInt(tempTakePhotoWaitExposure); Log.i(TAG_SYSTEM_PARAMETER_SP,"系统参数#01.2-> 拍照等待曝光时间值: " + UserGlobalVariable.CameraTakePhotoWaitExposure); String tempLongitude = SystemParameterSettings.getString(SYS_PARA_GPS_LONGITUDE,"0"); String tempLatitude = SystemParameterSettings.getString(SYS_PARA_GPS_LATITUDE,"0"); UserGlobalVariable.setlValue("lng",tempLongitude); UserGlobalVariable.setlValue("lat",tempLatitude); Log.i(TAG_SYSTEM_PARAMETER_SP,"系统参数#01.3-> 历史定位: 经度 - " + tempLongitude + ", 纬度 - " + tempLatitude); } private void MaiChongPlatformSInit() { enjoySDK = new EnjoySDK(this); try { int res = enjoySDK.getSecurePasswdStatus(); } catch (EnjoyApiNotSupportException e) { Log.i(TAG_PLATFORM_MAICHON, "getSecurePasswdStatus: Error"); } try { int res = enjoySDK.setSecurePasswd("Abc12345","Abc12345"); } catch (EnjoyApiNotSupportException e) { Log.i(TAG_PLATFORM_MAICHON, "registerSafeProgram: Error"); } try { //注册当前应用为安全密码应用。 int res = enjoySDK.registSafeProgram("Abc12345"); } catch (EnjoyApiNotSupportException e) { Log.i(TAG_PLATFORM_MAICHON, "registerSafeProgram: Error"); } try { //检查当前应用是否在安全应用列表中。 boolean res = enjoySDK.checkSafeProgramOfSelf(); if(res){ Log.i(TAG_PLATFORM_MAICHON, "checkSafeProgramOfSelf: Register Successful."); } } catch (EnjoyApiNotSupportException e) { Log.i(TAG_PLATFORM_MAICHON, "checkSafeProgramOfSelf: Error"); } try { int res= enjoySDK.setScreenBrightness(128); } catch (EnjoyApiNotSupportException e) { Log.i(TAG_PLATFORM_MAICHON, "setScreenBrightness: Error"); } try { int res = enjoySDK.setTouchWake(true); Log.i(TAG_PLATFORM_MAICHON, "setTouchWake: Set Successful."); } catch (EnjoyApiNotSupportException e) { Log.i(TAG_PLATFORM_MAICHON, "setTouchWake: Set Failed."); } try { enjoySDK.EnableKeepAlive(true); Log.i(TAG_PLATFORM_MAICHON, "设置使能应用保活: 成功."); } catch (EnjoyApiNotSupportException e) { Log.i(TAG_PLATFORM_MAICHON, "设置使能应用保活: 失败."); } McKeepAliveApp mcKeepAliveApp = new McKeepAliveApp(); mcKeepAliveApp.setPackagename("com.example.yunfeiapplication"); mcKeepAliveApp.setInterval(30); mcKeepAliveApp.setPriority(1); Log.i(TAG_PLATFORM_MAICHON, "应用保活名称:" + mcKeepAliveApp.getPackagename()); Log.i(TAG_PLATFORM_MAICHON, "应用保活间隔:" + String.valueOf(mcKeepAliveApp.getInterval())); } private void MaiChongStartRawLauncher(){ enjoySDK = new EnjoySDK(this); try { enjoySDK.EnableKeepAlive(false); Log.i(TAG_PLATFORM_MAICHON, "设置取消应用保活: 成功."); } catch (EnjoyApiNotSupportException e) { Log.i(TAG_PLATFORM_MAICHON, "设置取消应用保活: 失败."); } try { enjoySDK.startRawLauncher(); Log.i("TAG", " 启动默认界面成功."); } catch (EnjoyApiNotSupportException e) { Log.i("TAG", " 启动默认界面失败."); throw new RuntimeException(e); } } private void MaiChongPlatformSleep() { enjoySDK = new EnjoySDK(this); try { int res = enjoySDK.getSecurePasswdStatus(); } catch (EnjoyApiNotSupportException e) { Log.i(TAG_PLATFORM_MAICHON, "getSecurePasswdStatus: Error"); } try { int res = enjoySDK.setSecurePasswd("Abc12345","Abc12345"); } catch (EnjoyApiNotSupportException e) { Log.i(TAG_PLATFORM_MAICHON, "registerSafeProgram: Error"); } try { int res = enjoySDK.goToSleep(); Log.i(TAG_PLATFORM_MAICHON, "goToSleep: Successful"); } catch (EnjoyApiNotSupportException e) { //throw new RuntimeException(e); Log.i(TAG_PLATFORM_MAICHON, "goToSleep: Error"); } } // AIDL 连接 public class BaseServiceConnection implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.i("onServiceConnected", "onServiceConnected: Successful"); serviceInterface = IBaseServiceInterface.Stub.asInterface(service); BaseServiceConnectionFlag = true; MacHideSystemUI(); RequestKioskMode(true); // 进入霸屏模式 } @Override public void onServiceDisconnected(ComponentName name) { } } // AIDL 请求回调 public class AidlCallback extends IBaseServiceCallback.Stub { @Override public void onResponse(String json) throws RemoteException { Log.d(TAG_PLATFORM_WANGFEI, "onResponse------" + json); BaseResponse baseResponse = FastJsonUtils.fromJson(json, BaseResponse.class); if (baseResponse == null || baseResponse.getType() == null) { return; } switch (baseResponse.getType()) { /*case AidlConstants.TYPE_LOCATION: AidlResponse aidlResponse = FastJsonUtils.fromJson(json,new TypeReference>(LocationInfo.class){}); LocationInfo locationInfo = aidlResponse.data; if (locationInfo != null) { Log.i("TAG", "lng: " + locationInfo.longitude + " lat: " + locationInfo.latitude); MacSetSystemParameterSP(SYS_PARA_GPS_LONGITUDE,String.valueOf(locationInfo.longitude)); MacSetSystemParameterSP(SYS_PARA_GPS_LATITUDE,String.valueOf(locationInfo.latitude)); } break;*/ case AidlConstants.TYPE_KIOSK_MODE: case AidlConstants.TYPE_INSTALL: Log.i("TAG", "onResponse: " + json); break; } } } private void WifRequestLocationInfo() { BaseRequest request = new BaseRequest(); request.setType(AidlConstants.TYPE_LOCATION); try { serviceInterface.request(FastJsonUtils.toJson(request), AidlCallback); } catch (RemoteException e) { throw new RuntimeException(e); } } /* 网飞屏霸屏模式 */ private void RequestKioskMode(boolean enable) { AidlRequest request = new AidlRequest<>(); request.setType(AidlConstants.TYPE_KIOSK_MODE); request.setParam(enable); try { serviceInterface.request( FastJsonUtils.toJson(request), AidlCallback ); } catch (RemoteException e) { e.printStackTrace(); } } /* 隐藏底部导航栏 */ private void MacHideSystemUI() { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN); } /******************************************** 语音播报功能 ********************************************/ void MainActivityVoiceMediaPlayer(int voiceID) { if(VoicePlayingFlag){ int playId = 0; if (voiceID == 0) { playId = R.raw.loginsuccessful; /*登录成功*/ } else if(voiceID == 1) { playId = R.raw.loginfailure; /*密码错误*/ } else if(voiceID == 2) { playId = R.raw.networkconnected; /*网络连接成功*/ } else if(voiceID == 3) { playId = R.raw.networkdisconnected; /*网络断开连接*/ } else if(voiceID == 4) { playId = R.raw.cameratakingpictures; /*开始拍照*/ } else if(voiceID == 5) { playId = R.raw.camerauploadpictures; /*上传图片*/ } else if(voiceID == 6) { playId = R.raw.camerauploadsuccessful; /*图片上传成功*/ } else if(voiceID == 7) { playId = R.raw.camerauploadfailure; /*图片上传失败*/ } else if(voiceID == 8) { playId = R.raw.camerabusy; /*相机忙,本次自动拍照取消*/ } else if(voiceID == 9) { playId = R.raw.cameraautotakingphoto; /*正在执行自动拍照,操作无效*/ } else if(voiceID == 10) { playId = R.raw.settingsuccessful; /*正在执行自动拍照,操作无效*/ } else if(voiceID == 11) { playId = R.raw.settingfailed; /*正在执行自动拍照,操作无效*/ } Log.i("TAG", "MainActivityVoiceMediaPlayer: 语音播放." + voiceID); MacAudioPlayer.playSound(playId); VoicePlayingFlag = false; } } /******************************************** 侧边栏功能 ********************************************/ /*** 界面切换 ***/ public void SwitchToFragment(int index){ MacReplaceFragment(index); } private void MacReplaceFragment(int index) { if (index < 1 || index > 7 || index == OldFragmentIndex) { Log.i("MacReplaceFragment", "当前界面即目标界面,无需跳转。"); return; } if (1 == index) { getSupportFragmentManager().beginTransaction().replace(R.id.mainFragmentContainerView, FragmentMac1.class,null).commit(); } else if (2 == index) { /*** @CameraMark01其他界面跳转至“相机操作”界面时,如果主线程正在执行自动拍照,等主线程完成拍照上传后再跳转至拍照界面 ***/ // if (!MacTakePhotoBusyFlag) { getSupportFragmentManager().beginTransaction().replace(R.id.mainFragmentContainerView, FragmentMac2.class,null).commit(); // } else { // Toast.makeText(getApplicationContext(),"相机正在拍摄上传",Toast.LENGTH_SHORT).show(); // } } else if(3 == index) { getSupportFragmentManager().beginTransaction().replace(R.id.mainFragmentContainerView, FragmentMac3.class,null).commit(); } else if(4 == index) { getSupportFragmentManager().beginTransaction().replace(R.id.mainFragmentContainerView, FragmentMac4.class,null).commit(); } else if(5 == index) { getSupportFragmentManager().beginTransaction().replace(R.id.mainFragmentContainerView, FragmentMac5.class,null).commit(); } else if(6 == index) { UserGlobalVariable.setlValue("login","0"); index = 0; getSupportFragmentManager().beginTransaction().replace(R.id.mainFragmentContainerView, FragmentMac0.class,null).commit(); } /*** 等主线程完成拍照上传后再跳转至拍照界面,不更新界面标识。(发生 '@CameraMark01' 时此次操作无效。) ***/ // if (!MacTakePhotoBusyFlag) { OldFragmentIndex = index; // } } /******************************************** GPS功能部分 ********************************************/ private void MacStartLocationUpdates() { locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (locationManager == null) { Log.e("GPS Location", "LocationManager is null"); return; } if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { Log.e("GPS Location", "No GPS permission"); return; } String provider = LocationManager.GPS_PROVIDER; if (!locationManager.isProviderEnabled(provider)) { Log.e("GPS Location", "GPS provider disabled"); return; } Location lastLocation = locationManager.getLastKnownLocation(provider); if (lastLocation != null) { Log.d("GPS Location", "Got last location"); handleLocation(lastLocation); //return; } Log.d("GPS Location", "Start GPS locating"); locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { if (location == null) { Log.e("GPS Location", "location null"); return; } Log.d("GPS Location", "location:" + location.getLatitude() + "," + location.getLongitude()); handleLocation(location); locationManager.removeUpdates(this); } @Override public void onProviderEnabled(String provider) { Log.d("GPS Location", "enabled:" + provider); } @Override public void onProviderDisabled(String provider) { Log.d("GPS Location", "disabled:" + provider); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } }; try { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 1000, 0, locationListener, Looper.getMainLooper() ); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } private void handleLocation(Location location) { double latitude = location.getLatitude(); double longitude = location.getLongitude(); Log.d("GPS Location", "+++ Latitude: " + latitude + ", Longitude: " + longitude); if(!UserGlobalVariable.GPS_LocationRefresh){ UserGlobalVariable.GPS_LocationRefresh = true; MacSetSystemParameterSP(SYS_PARA_GPS_LONGITUDE,String.valueOf(longitude)); MacSetSystemParameterSP(SYS_PARA_GPS_LATITUDE,String.valueOf(latitude)); UserGlobalVariable.setlValue("lng", String.valueOf(longitude)); UserGlobalVariable.setlValue("lat", String.valueOf(latitude)); } } // 检测移动数据是否开启 public static boolean isMobileDataEnabled(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); try { // 通过反射获取移动数据状态(兼容旧版本) Class connectivityManagerClass = Class.forName(ConnectivityManager.class.getName()); java.lang.reflect.Method getMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("getMobileDataEnabled"); getMobileDataEnabledMethod.setAccessible(true); return (boolean) getMobileDataEnabledMethod.invoke(cm); } catch (Exception e) { e.printStackTrace(); // 如果反射失败,尝试通过其他方式(如检查网络类型) return false; } } public static boolean setMobileDataEnabledByRoot(boolean enable) { Process process = null; DataOutputStream os = null; try { // 获取 root 权限 process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); // Android 4.0-4.3 使用的旧方法 // os.writeBytes("service call phone 115 i32 " + (enable ? "1" : "0") + "\n"); // Android 4.4+ 使用的新方法 os.writeBytes("svc data " + (enable ? "enable" : "disable") + "\n"); // 修改系统设置(双保险) os.writeBytes("settings put global mobile_data " + (enable ? "1" : "0") + "\n"); // 刷新网络设置 os.writeBytes("am broadcast -a android.intent.action.ANY_DATA_STATE --ez state " + enable + "\n"); os.writeBytes("exit\n"); os.flush(); // 等待命令执行完成 int exitCode = process.waitFor(); return exitCode == 0; } catch (Exception e) { Log.e("TAG", "Root command failed", e); return false; } finally { try { if (os != null) os.close(); if (process != null) process.destroy(); } catch (Exception e) { Log.e("TAG", "Close stream error", e); } } } /*** FragmentMac1界面控件操作时对应的串口指令下发 ***/ public void MainSerialSendFragmentMac1OperateCommand(String string) { JSONObject jsonObjectEXT = new JSONObject(); JSONObject jsonMainObject = new JSONObject(); String commandString = ""; /*获取全局变量*/ UserGlobalVariable fragmentGlobalVariable = UserGlobalVariable.getInstance(); Map fragmentMap = fragmentGlobalVariable.infoMap; String jsonString = fragmentMap.get("JsonMainObject"); JSONObject jsonObject = null; try { jsonObject = new JSONObject(jsonString); String logString = ""; switch (string) { case "0": // Added by NiuJiuRu @2025-05-20 logString = "执行一键恢复所有参数到默认出厂设置"; break; case "1": jsonObjectEXT.put("ts", jsonObject.getJSONObject("ext").get("ts")); if (jsonObject.getJSONObject("ext").get("ts").toString().equals("0")) { logString = "切换为时控模式"; Log.i("TempTAG040801", "TAG#02.0->> 串口下发指令切换为时控模式."); } else { logString = "切换为光控模式"; Log.i("TempTAG040801", "TAG#02.1->> 串口下发指令切换为光控模式."); } break; case "2": jsonObjectEXT.put("tps", jsonObject.getJSONObject("ext").get("tps")); if(jsonObject.getJSONObject("ext").get("tps").toString().equals("0")){ logString = "温控保护关闭"; }else{ logString = "温控保护开启"; } break; case "3": jsonObjectEXT.put("rps", jsonObject.getJSONObject("ext").get("rps")); logString = "切换为晨曦模式"; break; case "4": jsonObjectEXT.put("tt", jsonObject.getJSONObject("ext").get("tt")); logString = "设置光控工作时长: " + jsonObject.getJSONObject("ext").get("tt").toString(); break; case "5": jsonObjectEXT.put("collstart", jsonObject.getJSONObject("ext").get("collstart")); jsonObjectEXT.put("collend", jsonObject.getJSONObject("ext").get("collend")); logString = "设置时控定时: " + jsonObject.getJSONObject("ext").get("collstart") + "|" +jsonObject.getJSONObject("ext").get("collend") + " (开始|结束时刻)"; break; case "6": jsonObjectEXT.put("tpl", jsonObject.getJSONObject("ext").get("tpl")); jsonObjectEXT.put("tph", jsonObject.getJSONObject("ext").get("tph")); logString = "设置温控阈值: " + jsonObject.getJSONObject("ext").get("tpl") + "|" + jsonObject.getJSONObject("ext").get("tph") + " (下限|上限)"; break; case "7": jsonObjectEXT.put("dat_f", jsonObject.getJSONObject("ext").get("dat_f")); logString = "设置数据上传间隔: " + jsonObject.getJSONObject("ext").get("dat_f") + " 分"; break; case "8": jsonObjectEXT.put("pho_f", jsonObject.getJSONObject("ext").get("pho_f")); logString = "设置图片上传间隔: " + jsonObject.getJSONObject("ext").get("pho_f") + " 分"; break; case "9": jsonObjectEXT.put("Demo_mode", jsonObject.getJSONObject("ext").get("Demo_mode")); logString = "演示模式状态: " + jsonObject.getJSONObject("ext").get("Demo_mode"); break; case "51": commandString = "systest autotest touch"; logString = "测试操作: 一键测试"; break; case "52": commandString = "systest Traplamp touch"; logString = "测试操作: 诱捕灯"; break; case "53": commandString = "systest collect touch"; logString = "测试操作: 采集风机"; break; case "54": commandString = "systest Trap_Down touch"; logString = "测试操作: 下诱捕灯"; break; case "55": commandString = "systest switchled touch"; logString = "测试操作: 补光设置"; break; case "56": commandString = "systest fb_test touch"; logString = "测试操作: 翻版测试"; break; } int commandType = Integer.parseInt(string); if (commandType == 0) { // Added by NiuJiuRu @2025-05-20 String resetCmd = "{\"cmd\": \"ctrl\", \"ext\": {\"RC\": \"Force_Reset\"}}"; Log.i("TAG", "serialSend: " + resetCmd); if (!SerialManager.getInstance().getUpgradingFlag()) { SerialManager.getInstance().write(resetCmd.getBytes()); } } else if (commandType >= 1 && commandType <= 50) { jsonMainObject.put("cmd","paramconf"); // jsonObjectEXT.put("no_reply", "1"); jsonMainObject.put("ext",jsonObjectEXT); Log.i("TAG", "serialSend: " + jsonMainObject.toString()); if(!SerialManager.getInstance().getUpgradingFlag()){ SerialManager.getInstance().write(jsonMainObject.toString().getBytes());//串口下发界面操作指令(升级冲突#3) } } else if (commandType >= 51 && commandType <= 80) { if(!SerialManager.getInstance().getUpgradingFlag()){ SerialManager.getInstance().write(commandString.getBytes());;//串口下发界面操作指令(升级冲突#3) } } Log.i(TAG_FMACX_MSG_TO_MAC,"FromMac->> OptEvents = " + commandType); LogFileManagerOperate.VerifyLogFileConformsToJson(); LogFileManagerOperate.CheckLogFileNumber(); LogFileManagerOperate.AddOneLogItem(logString); } catch (JSONException e) { Log.i("jsonObjectCreate", "JSONException Error,#01"); } } /******************************************** Mqtt部分功能 ********************************************/ private void MacAppHeartbeatToServer() { JSONObject jsonObjectEXT = new JSONObject(); try { jsonObjectEXT.put("version",UserGlobalVariable.ANDROID_APP_VERSION); if(HeartBeatFirstReportFlag){ HeartBeatFirstReportFlag = false; jsonObjectEXT.put("first","1"); }else{ jsonObjectEXT.put("first","0"); } jsonObjectEXT.put("imei",UserGlobalVariable.getValue("imei")); jsonObjectEXT.put("iccid",UserGlobalVariable.getValue("iccid")); jsonObjectEXT.put("csq",UserGlobalVariable.getValue("csq")); jsonObjectEXT.put("lat",UserGlobalVariable.getValue("lat")); jsonObjectEXT.put("lng",UserGlobalVariable.getValue("lng")); jsonObjectEXT.put("mcuComm",UserGlobalVariable.DevStuCode_Serial); JSONObject jsonObjectMain = new JSONObject(); try { jsonObjectMain.put("cmd","app"); jsonObjectMain.put("ext",jsonObjectEXT); // mqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),jsonObjectMain.toString(),0,false,10000); userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),jsonObjectMain.toString(),0); } catch (JSONException e) { throw new RuntimeException(e); } } catch (JSONException e) { throw new RuntimeException(e); } } private void MacAppCustomerMqttHeartbeatToServer() { JSONObject jsonObjectEXT = new JSONObject(); try { jsonObjectEXT.put("version",UserGlobalVariable.ANDROID_APP_VERSION); jsonObjectEXT.put("imei",UserGlobalVariable.getValue("imei")); jsonObjectEXT.put("iccid",UserGlobalVariable.getValue("iccid")); jsonObjectEXT.put("csq",UserGlobalVariable.getValue("csq")); jsonObjectEXT.put("lat",UserGlobalVariable.getValue("lat")); jsonObjectEXT.put("lng",UserGlobalVariable.getValue("lng")); jsonObjectEXT.put("mcuComm",UserGlobalVariable.DevStuCode_Serial); JSONObject jsonObjectMain = new JSONObject(); try { jsonObjectMain.put("cmd","app"); jsonObjectMain.put("ext",jsonObjectEXT); customerMqttManager.publish(UserGlobalVariable.getValue("mqttPubTopic") + UserGlobalVariable.getValue("imei"),jsonObjectMain.toString(),0); } catch (JSONException e) { throw new RuntimeException(e); } } catch (JSONException e) { throw new RuntimeException(e); } } /******************************************** 操作日志部分功能 ********************************************/ public class LogFileManager { private static final int MaxNumber = 100; private static final String LogFilePath = "log.txt"; private int logTips; public void CatLogFileEachLine() { File logFile = new File(getFilesDir(),"log.txt"); if (!logFile.exists() || !logFile.isFile()) { return; } try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) { String line; while ((line = reader.readLine()) != null) { //Log.d(TAG_LOG_MANAGER, line); } } catch (IOException e) { Log.i(TAG_LOG_MANAGER, "IOException: Error.#01"); } } public void CheckLogFileNumber() { File logFile = new File(getFilesDir(),"log.txt"); if (!logFile.exists() || !logFile.isFile()) { return; } List lines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) { String line; while ((line = reader.readLine()) != null) { lines.add(line); } } catch (IOException e) { //e.printStackTrace(); Log.i(TAG_LOG_MANAGER, "IOException: Error.#02"); } if (lines.size() > MaxNumber) { lines = lines.subList(lines.size() - MaxNumber, lines.size()); } try (BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, false))) { for (String line : lines) { writer.write(line); writer.newLine(); } } catch (IOException e) { //e.printStackTrace(); Log.i(TAG_LOG_MANAGER,"IOException: Error.#03"); } } public void VerifyLogFileConformsToJson() { File logFile = new File(getFilesDir(),"log.txt"); if (!logFile.exists() || !logFile.isFile()) { return; } List validLines = new ArrayList <> (); try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) { String line; while ((line = reader.readLine()) != null) { try { new JSONObject(line); // 尝试解析为JSON对象 validLines.add(line); } catch (JSONException e) { // 格式不正确,忽略此行 } } } catch (IOException e) { //throw new RuntimeException(e); Log.i(TAG_LOG_MANAGER,"IOException: Error.#04"); } // 写回有效行到原文件 try (BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, false))) { // false 表示不追加,而是覆盖写 for (String validLine : validLines) { writer.write(validLine); writer.newLine(); } } catch (IOException e) { Log.i(TAG_LOG_MANAGER,"IOException: Error.#05"); } } public void JsonStringToLogFile(String jsonData) { File logFile = new File(getFilesDir(),"log.txt"); // 使用FileOutputStream以追加模式写入文件 try (FileOutputStream fos = new FileOutputStream(logFile, true)) { fos.write(jsonData.getBytes()); fos.write(System.lineSeparator().getBytes()); // 添加换行符以分隔不同的JSON记录 } catch (IOException e) { //e.printStackTrace(); Log.i(TAG_LOG_MANAGER,"IOException: Error.#06"); } } public void AddOneLogItem(String event) { JSONObject jsonObject = new JSONObject(); try { Date currentDate = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); String dateStr = dateFormat.format(currentDate); jsonObject.put("Date", dateStr); jsonObject.put("Event", event); String jsonDataStr = jsonObject.toString(); Log.i(TAG_LOG_MANAGER,"LogItem: " + jsonDataStr); JsonStringToLogFile(jsonDataStr); } catch (Exception e) { //e.printStackTrace(); Log.i(TAG_LOG_MANAGER,"Exception: Error.#07"); } } } /******************************************** 相机平台预设部分功能 ********************************************/ public void MacSystemExecuteShellCommand() { Log.i(TAG_CAMERA_OPERATE, "TakePhoto#00->> Shell端执行摄像头初始化配置."); try { Process process = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); os.writeBytes("chmod -R 777 /dev/bus/usb\n"); os.writeBytes("echo 2000 > /sys/module/usbcore/parameters/usbfs_memory_mb\n"); os.writeBytes("cat /sys/module/usbcore/parameters/usbfs_memory_mb\n"); os.writeBytes("exit\n"); os.flush(); } catch (IOException e) { e.printStackTrace(); } } public void MacSystemExecuteShellCommand2() { Log.i(TAG_CAMERA_OPERATE, "TakePhoto#00->> Shell端执行摄像头初始化配置."); try { Process process = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); os.writeBytes("monkey -p com.hzmct.enjoyConfig 1"); os.flush(); } catch (IOException e) { e.printStackTrace(); } } /******************************************** 定时拍照上传部分功能 ********************************************/ private void MacCleanInvalidImages() { // 获取应用的私有目录下的photos文件夹 File photosDir = new File(getFilesDir(), "photos"); // 如果目录不存在或不是一个文件夹,则直接返回 if (!photosDir.exists() || !photosDir.isDirectory()) { return; } // 获取并删除不符合格式的文件 File[] files = photosDir.listFiles(); if (files != null) { for (File file : files) { // 检查文件名是否不符合.jpeg格式(不区分大小写) if (!isValidJpegFileName(file.getName())) { // 删除文件 if (file.delete()) { Log.i(TAG_CAMERA_OPERATE,"A-TakePhoto#03.1->> 照片 < " + file.getName() + " > 格式不符合规范.删除成功."); } else { Log.i(TAG_CAMERA_OPERATE,"A-TakePhoto#03.2->> 照片 < " + file.getName() + " > 格式不符合规范.删除失败."); } } } } } // 检查文件名是否以.jpg结尾(不区分大小写),并且确保它是唯一的扩展名 private static boolean isValidJpegFileName(String fileName) { String lowerCaseFileName = fileName.toLowerCase(); int dotIndex = lowerCaseFileName.indexOf('.'); // 如果没有点,则不是有效的.jpeg文件 if (dotIndex == -1) { return false; } // 获取扩展名 String extension = lowerCaseFileName.substring(dotIndex + 1); return "jpg".equals(extension); } private void MacSaveBitmapToPhotosDir(Bitmap bitmap,String fileName) { // 获取应用的私有目录 //File photosDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "photos"); File photosDir = new File(getFilesDir(), "photos"); if(!photosDir.exists()) { if(!photosDir.mkdir()) { Log.i(TAG_CAMERA_OPERATE,"A-TakePhoto#04.1->> 私有目录下'photos'文件夹创建失败."); } } File[] files = photosDir.listFiles(); if(files.length > 100){ Log.i(TAG_CAMERA_OPERATE,"A-TakePhoto#04.1.1->> 缓存图片数量超过100张."); return; } // 创建目标文件 File file = new File(photosDir, fileName); // 尝试将 Bitmap 写入文件 try (FileOutputStream out = new FileOutputStream(file)) { // 压缩 Bitmap 为 JPEG 格式并写入文件 bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out); // 100 表示最高质量 Log.i(TAG_CAMERA_OPERATE,"A-TakePhoto#04.2->> 图片成功保存至'photos'文件夹."); } catch (IOException e) { Log.i(TAG_CAMERA_OPERATE,"A-TakePhoto#04.3->> 图片保存至'photos'文件夹失败."); } } private void AutoTakePhotoAndUploadThread(){ new Thread(new Runnable() { boolean threadExitStatus = true; boolean threadRunStatus = true; boolean openCameraOperate = false; boolean cameraGrabbing = false; int takePhotoDelay = 0; MvccCameraManager mvccCameraManager = MvccCameraManager.getInstance(); @Override public void run() { while (threadRunStatus) { if(!threadExitStatus){ return; } if (!openCameraOperate) { openCameraOperate = true; Log.i(TAG_CAMERA_OPERATE, "TakePhoto#01.0->> 尝试打开相机."); if(mvccCameraManager.openCameraDevice(true)){ Log.i(TAG_CAMERA_OPERATE, "TakePhoto#01.1->> 相机打开成功."); if (mvccCameraManager.toggleGrabbing(true)) { Log.i(TAG_CAMERA_OPERATE, "TakePhoto#01.2->> 视频流开启成功."); cameraGrabbing = true; } else { threadExitStatus = false; } }else{ Log.i(TAG_CAMERA_OPERATE, "TakePhoto#01.3->> 相机打开失败.本次拍照任务取消."); threadExitStatus = false; } } if (cameraGrabbing) { takePhotoDelay++; Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.4->> 拍照延时: " + takePhotoDelay); if(takePhotoDelay >= UserGlobalVariable.CameraTakePhotoWaitExposure){ Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.5->> 开始截取视频流生成图片."); Bitmap MacBitmapToServer = mvccCameraManager.getCameraBitmap(); if(MacBitmapToServer != null){ Calendar calendar = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss"); String formattedDate = sdf.format(calendar.getTime()); String deviceIMEI = UserGlobalVariable.getValue("imei"); //公司服务器路径 String remoteFilesPathServerM = "/" + deviceIMEI + "/"; String remoteFilesPathServerC = "/" + deviceIMEI + "/"; //上传至服务器的文件名 String pictureNameToServer = deviceIMEI + "-" + formattedDate + ".jpg"; //存储在设备中的文件名 String pictureNameToDevStorage = formattedDate + ".jpg"; Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.6->> " + "开始上传图片"); boolean uploadToServerResultM = false; boolean uploadToServerResultC = false; Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.7.1->> 公司服务器路径: " + remoteFilesPathServerM); Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.7.2->> 公司服务器图片: " + pictureNameToServer); if(UserGlobalVariable.Customer_FTP_Enable){ String ftpIP = UserGlobalVariable.getValue("ftpIP"); String ftpPort = UserGlobalVariable.getValue("ftpPort"); String ftpUser = UserGlobalVariable.getValue("ftpUser"); String ftpPasswd = UserGlobalVariable.getValue("ftpPasswd"); String ftpFilePath = UserGlobalVariable.getValue("ftpFilePath") + UserGlobalVariable.getValue("imei") + "/"; Log.i(TAG_CAMERA_OPERATE, "Mac#1442->> 客户服务器信息-IP : " + ftpIP); Log.i(TAG_CAMERA_OPERATE, "Mac#1442->> 客户服务器信息-Port : " + ftpPort); Log.i(TAG_CAMERA_OPERATE, "Mac#1442->> 客户服务器信息-User : " + ftpUser); Log.i(TAG_CAMERA_OPERATE, "Mac#1442->> 客户服务器信息-Passwd: " + ftpPasswd); FtpTransferManager ftpTransferManagerToC = new FtpTransferManager(ftpIP,Integer.parseInt(ftpPort),ftpUser,ftpPasswd,remoteFilesPathServerC); // FtpTransferManager ftpTransferManagerToC = new FtpTransferManager(FTP_INFO_HOST_URL,FTP_INFO_HOST_PORT,FTP_INFO_HOST_USER,FTP_INFO_HOST_PASSWD,remoteFilesPathServerC); uploadToServerResultC = ftpTransferManagerToC.uploadFile(MacBitmapToServer,pictureNameToServer,120); if (uploadToServerResultC) { Log.i(TAG_CAMERA_OPERATE,"Mac#1451->> 向客户端上传图片成功."); MqttCustomPublishFunction("{\"cmd\":\"ctrl\",\"type\":\"takephoto\",\"status\":\"3\"}"); } else { Log.i(TAG_CAMERA_OPERATE,"Mac#1456->> 向客户端上传图片失败."); MqttCustomPublishFunction("{\"cmd\":\"ctrl\",\"type\":\"takephoto\",\"status\":\"2\"}"); } ftpTransferManagerToC.shutdown(); } FtpTransferManager ftpTransferManagerToM = new FtpTransferManager(FTP_INFO_HOST_URL,FTP_INFO_HOST_PORT,FTP_INFO_HOST_USER,FTP_INFO_HOST_PASSWD,remoteFilesPathServerM); uploadToServerResultM = ftpTransferManagerToM.uploadFile(MacBitmapToServer,pictureNameToServer,120); if (uploadToServerResultM) { Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.7.3.0->> 图片上传成功."); MqttCustomPublishFunction("{\"cmd\":\"ctrl\",\"type\":\"takephoto\",\"status\":\"1\"}"); } else { Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.7.3.0->> 图片上传失败."); MqttCustomPublishFunction("{\"cmd\":\"ctrl\",\"type\":\"takephoto\",\"status\":\"0\"}"); } ftpTransferManagerToM.shutdown(); /* 定时上传失败时保存图片 */ if(!uploadToServerResultM) { Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.7.7->> 图片上传失败,保存至本地存储."); MacCleanInvalidImages(); MacSaveBitmapToPhotosDir(MacBitmapToServer, pictureNameToDevStorage); } Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.7.8->> 向MCU发送拍照结束指令"); String takePhotoOver = "{\"photolink\":\"ALARM_INPUT\"}"; if(!SerialManager.getInstance().getUpgradingFlag()){ SerialManager.getInstance().write(takePhotoOver.getBytes());//串口下发界面操作指令(升级冲突#3) } /* 退出线程 */ exitThread(); } else { Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.7.9->> 图片数据无效."); } } try { Thread.sleep(1000); } catch (InterruptedException e) { Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.7.10->> 线程延时错误."); } } } } public void exitThread(){ threadExitStatus = false; threadRunStatus = false; mvccCameraManager.closeCameraDevice(); } }).start(); } private void RemoteSetCameraParametersThread(){ new Thread(new Runnable() { boolean threadExitStatus = true; boolean threadRunStatus = true; boolean openCameraOperate = false; boolean cameraGrabbing = false; int takePhotoDelay = 0; MvccCameraManager mvccCameraManager = MvccCameraManager.getInstance(); @Override public void run() { while(threadRunStatus){ if(!threadExitStatus){ return; } if(!openCameraOperate){ openCameraOperate = true; Log.i(TAG_CAMERA_OPERATE, "TakePhoto#01.0->> 尝试打开相机."); if(mvccCameraManager.openCameraDevice(true)){ Log.i(TAG_CAMERA_OPERATE, "TakePhoto#01.1->> 相机打开成功."); if(UserGlobalVariable.Camera_SG_Parameters_Flag == 0){ mvccCameraManager.getCameraCommonParameter(); } else { mvccCameraManager.setCameraCommonParameter(); mvccCameraManager.getCameraCommonParameter(); } MacReportCameraParameters(); /* 退出线程 */ exitThread(); }else{ Log.i(TAG_CAMERA_OPERATE, "TakePhoto#01.3->> 相机打开失败.本次拍照任务取消."); threadExitStatus = false; } } } } public void exitThread(){ threadExitStatus = false; threadRunStatus = false; mvccCameraManager.closeCameraDevice(); } }).start(); } private void MacReportCameraParameters() { JSONObject jsonObjectEXT = new JSONObject(); try { jsonObjectEXT.put("ExposureAuto",UserGlobalVariable.getValue("ExposureAuto")); jsonObjectEXT.put("ExposureTime",UserGlobalVariable.getValue("ExposureTime")); jsonObjectEXT.put("BalanceWhiteAuto",UserGlobalVariable.getValue("BalanceWhiteAuto")); jsonObjectEXT.put("GammaEnable",UserGlobalVariable.getValue("GammaEnable")); jsonObjectEXT.put("Gamma",UserGlobalVariable.getValue("Gamma")); jsonObjectEXT.put("HueEnable",UserGlobalVariable.getValue("HueEnable")); jsonObjectEXT.put("Hue",UserGlobalVariable.getValue("Hue")); JSONObject jsonObjectMain = new JSONObject(); try { jsonObjectMain.put("cmd","Camera"); jsonObjectMain.put("status","1"); jsonObjectMain.put("parameters",jsonObjectEXT); userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),jsonObjectMain.toString(),0); } catch (JSONException e) { throw new RuntimeException(e); } } catch (JSONException e) { throw new RuntimeException(e); } } /******************************************** FTP下载Application安装包功能 ********************************************/ private void MacAppUpgradeDeleteApkIfExists() { // 构建app.apk文件的路径 File appApkFile = new File(getFilesDir(),"XCT.apk"); // 检查文件是否存在 if (appApkFile.exists()) { // 删除文件 boolean isDeleted = appApkFile.delete(); if (isDeleted) { // 文件删除成功 Log.i(TAG_FTP_APP_UPGRADE,"AppUpgrade#06.1->> 删除旧APK文件成功!!!"); } else { // 文件删除失败 Log.i(TAG_FTP_APP_UPGRADE,"AppUpgrade#06.2->> 删除旧APK文件失败!!!"); } } else { // 文件不存在 Log.i(TAG_FTP_APP_UPGRADE,"AppUpgrade#06.3->> 'XCT.apk' 文件不存在!!!"); } } public static void MacExecuteShellSilent(String apkFilePath) { try { String pmStr = "pm install -r " + apkFilePath + "\n"; Process process = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); os.writeBytes(pmStr); os.writeBytes("exit\n"); os.flush(); } catch (IOException e) { //e.printStackTrace(); Log.i("ApplicationUpgrade", "executeShellSilent: Error"); } } /******************************************** 权限获取部分功能 ********************************************/ /* 获取手机状态权限 */ public void GetSelfPermissionPhoneState() { if (ActivityCompat.checkSelfPermission(MainActivity.this, "android.permission.READ_PHONE_STATE") != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this,new String[]{"android.permission.READ_PHONE_STATE"},1); Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#1.0-> 请求获取手机状态读取权限."); } else { Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#1.1-> 手机状态读取权限已获取."); GetSelfPermissionLocation(); } } /* 获取位置权限 */ public void GetSelfPermissionLocation() { if (ActivityCompat.checkSelfPermission(MainActivity.this, "android.permission.ACCESS_FINE_LOCATION") != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this,new String[]{"android.permission.ACCESS_FINE_LOCATION"},2); Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#2.0-> 请求获取手机位置读取权限."); } else { Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#2.1-> 手机位置读取权限已获取."); GetSelfPermissionExternalStorage(); } } /* 获取外部存储读写权限 */ public void GetSelfPermissionExternalStorage() { if (ActivityCompat.checkSelfPermission(this, "android.permission.READ_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED) { Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#3.0-> 请求获取外部存储权限."); ActivityCompat.requestPermissions(this, new String[]{ "android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"},3); }else{ Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#3.1-> 外部存储权限已获取."); // GetSelfPermissionWriteSettings(); // GetSelfPermissionWriteSettings2(); } } /* 获取外部存储读写权限 */ public void GetSelfPermissionWriteSettings() { if (ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_SECURE_SETTINGS") != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_SECURE_SETTINGS") != PackageManager.PERMISSION_GRANTED) { Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#4.0-> 请求获取数据流量开关权限."); ActivityCompat.requestPermissions(this, new String[]{ "android.permission.WRITE_SECURE_SETTINGS"},4); }else{ Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#4.1-> 数据流量控制权限已获取."); } } /* 获取外部存储读写权限 */ public void GetSelfPermissionWriteSettings2() { if (ActivityCompat.checkSelfPermission(this, "android.permission.MODIFY_PHONE_STATE") != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, "android.permission.MODIFY_PHONE_STATE") != PackageManager.PERMISSION_GRANTED) { Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#4.0-> 请求获取数据流量开关权限."); ActivityCompat.requestPermissions(this, new String[]{ "android.permission.MODIFY_PHONE_STATE"},5); }else{ Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#5.1-> 数据流量控制权限已获取."); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 1) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { /* 权限被授予,获取定位权限 */ GetSelfPermissionLocation(); } else { /* 权限被拒绝,重复获取 */ GetSelfPermissionPhoneState(); } } else if(requestCode == 2) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // 权限被授予,获取外部存储权限 GetSelfPermissionExternalStorage(); } else { /* 权限被拒绝,重复获取 */ GetSelfPermissionLocation(); } } else if(requestCode == 3) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { /* 主要权限已全部获取完成 */ } else { /* 权限被拒绝,重复获取 */ GetSelfPermissionExternalStorage(); } }else if(requestCode == 4) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { /* 主要权限已全部获取完成 */ Log.i("TAG", "onRequestPermissionsResult: 数据流量开关权限获取完成"); } else { /* 权限被拒绝,重复获取 */ GetSelfPermissionExternalStorage(); } } } /******************************************** 硬件信息获取部分功能 ********************************************/ public void MacGetPhoneStateInfo() { if (ActivityCompat.checkSelfPermission(this, "android.permission.READ_PHONE_STATE") == PackageManager.PERMISSION_GRANTED) { String iccid = "-1"; TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); /* 获取信号强度 */ int fragmentMac1_SignalStrength = 0; SignalStrength signalStrength = telephonyManager.getSignalStrength(); if(signalStrength != null){ fragmentMac1_SignalStrength = signalStrength.getLevel(); } // 获取SIM卡状态 int fragmentMac1_SimState = telephonyManager.getSimState(); // 获取ICCID if(telephonyManager.getSimState() != TelephonyManager.SIM_STATE_ABSENT){ iccid = telephonyManager.getSimSerialNumber(); if(iccid == null || iccid.length() < 20){ SubscriptionManager sm = SubscriptionManager.from(this); List sis = sm.getActiveSubscriptionInfoList(); if(sis.size() >= 1){ SubscriptionInfo si1 = sis.get(0); iccid = si1.getIccId(); // Log.i("PhoneStateInfo", "ICCID: " + iccid); } } } // 获取IMEI String imei = telephonyManager.getImei(); if(imei != null && imei.length() > 10){ UserGlobalVariable.Android_Dev_GetIMEIResult = true; } UserGlobalVariable.setlValue("iccid",iccid); UserGlobalVariable.setlValue("imei",imei); UserGlobalVariable.setlValue("csq", String.valueOf(fragmentMac1_SignalStrength)); UserGlobalVariable.setlValue("simCard", String.valueOf(fragmentMac1_SimState)); //MainActivityMessageToFragment("MainActivityToFMac0","Operate","Refresh"); } } public void MainActivityMessageToFragment(String requestKey,String key,String value) { Bundle result = new Bundle(); result.putString(key,value); getSupportFragmentManager().setFragmentResult(requestKey,result); } /******************************************** 硬件信息获取部分功能 ********************************************/ private void AutoUploadPhotosToFTP() { if (UserGlobalVariable.AutoUploadCachedImagesFlag) { return; } UserGlobalVariable.AutoUploadCachedImagesFlag = true; Log.i(TAG_CAMERA_OPERATE, "AutoUploadPic#01->> 检测是否有缓存图片."); // 获取应用的私有目录下的photos文件夹 File photosDir = new File(getFilesDir(),"photos"); // 如果目录不存在或不是一个文件夹,则直接返回 if (!photosDir.exists() || !photosDir.isDirectory()) { return; } File[] files = photosDir.listFiles(); if (files != null && files.length!= 0) { Log.i(TAG_CAMERA_OPERATE, "AutoUploadPic#01->> 自动上传进程开始运行!!!"); Log.i(TAG_CAMERA_OPERATE, "AutoUploadPic#02->> 图片缓存数量: " + files.length); // for (File filed : files) { // Log.i(TAG_CAMERA_OPERATE, "PhotosDir: " + filed.getName()); // } new Thread(new Runnable() { @Override public void run() { File photosDir = new File(getFilesDir(), "photos"); File[] files = photosDir.listFiles(); FTPClient ftpClient = new FTPClient(); try { /* 连接超时时间 */ ftpClient.setConnectTimeout(10 * 1000); /* 数据传输超时时间 */ ftpClient.setDataTimeout(10 * 1000); //正式服务器 ftpClient.connect(FTP_INFO_HOST_URL, FTP_INFO_HOST_PORT); ftpClient.login(FTP_INFO_HOST_USER, FTP_INFO_HOST_PASSWD); ftpClient.enterLocalPassiveMode(); // 通常用于解决NAT和防火墙问题 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // 设置文件类型为二进制,适用于图片 String tempIMEI = UserGlobalVariable.getValue("imei"); String remoteFilePath = "/" + tempIMEI + "/"; if (!ftpClient.changeWorkingDirectory(remoteFilePath)) { String[] dirs = remoteFilePath.split("/"); String currentDir = ""; for (String dir : dirs) { if (dir.isEmpty()) continue; currentDir += "/" + dir; if (!ftpClient.changeWorkingDirectory(currentDir)) { if (!ftpClient.makeDirectory(currentDir)) { //throw new IOException("创建目录失败: " + currentDir); Log.d(TAG_CAMERA_OPERATE, "AutoUploadPic#03.0.1->> 创建目录失败."); }else{ Log.d(TAG_CAMERA_OPERATE, "AutoUploadPic#03.0.2->> 创建目录成功."); } }else{ Log.d(TAG_CAMERA_OPERATE, "AutoUploadPic#03.0.3->> 切换目录失败."); } } }else{ Log.d(TAG_CAMERA_OPERATE, "AutoUploadPic#03.0.4->> 缓存图片路径已存在."); } for (File file : files) { try (FileInputStream inputStream = new FileInputStream(file)) { String remotePicPath = remoteFilePath + "history-" + tempIMEI + "-" + file.getName(); Log.d(TAG_CAMERA_OPERATE, "AutoUploadPic#03.1->> 缓存图片路径名称: " + remotePicPath); boolean done = ftpClient.storeFile(remotePicPath, inputStream); if (done) { Log.d(TAG_CAMERA_OPERATE, "AutoUploadPic#03.1->> 图片 < " + file.getName() + " > 上传成功."); if (file.delete()) { Log.i(TAG_CAMERA_OPERATE,"AutoUploadPic#03.2->> 图片 < " + file.getName() + " > 删除成功."); } else { Log.i(TAG_CAMERA_OPERATE,"AutoUploadPic#03.3->> 图片 < " + file.getName() + " > 删除失败."); } } else { Log.e(TAG_CAMERA_OPERATE, "AutoUploadPic#03.4->> 图片 < " + file.getName() + " > 上传失败."); } } catch (IOException ex) { Log.e(TAG_CAMERA_OPERATE, "AutoUploadPic#03.5->> 图片 < " + file.getName() + " > 加载出错:", ex); } } ftpClient.logout(); } catch (IOException ex) { Log.e(TAG_CAMERA_OPERATE, "AutoUploadPic#04->> Ftp传输出错!!!"); } finally { try { if (ftpClient.isConnected()) { ftpClient.disconnect(); Log.i(TAG_CAMERA_OPERATE, "AutoUploadPic#05.1->> 关闭Ftp传输通道"); } } catch (IOException ex) { // 处理断开连接时的异常 Log.e(TAG_CAMERA_OPERATE, "AutoUploadPic#05.2->> Ftp传输通道关闭出错!!!", ex); } // UserGlobalVariable.AutoUploadCachedImagesFlag = false; Log.d(TAG_CAMERA_OPERATE, "AutoUploadPic#06->> 自动上传图片进程结束"); } } }).start(); } } void MacMainMqttFunction(){ if(!UserGlobalVariable.Android_Dev_GetIMEIResult){ return; } if(userMqttManager == null){ userMqttManager = new UserMqttManager(MQTT_MAIN_HOST_URL,MQTT_MAIN_USER,MQTT_MAIN_PASSWORD,UserGlobalVariable.getValue("imei")); userMqttManager.setMqttConnectionCallback(new UserMqttManager.MqttConnectionCallback() { @Override public void onConnectionChanged(boolean isConnected) { if(isConnected){ UserGlobalVariable.Mqtt_M_Connect_Status = 1; UserGlobalVariable.Mqtt_M_ReConnect_Flag = 0; }else { UserGlobalVariable.Mqtt_M_Connect_Status = 0; UserGlobalVariable.Mqtt_M_ReConnect_Flag = 1; } } @Override public void onMessageReceived(String topic, String message, boolean retained) { if(retained){ Log.i("TAG", "清除Retained消息"); userMqttManager.publishNull(MQTT_MAIN_SUB_TOPIC + UserGlobalVariable.getValue("imei")); } if (!message.isEmpty()) { String logString = ""; JSONObject arrivedMessageJsonObject = null; try { arrivedMessageJsonObject = new JSONObject(message); if (arrivedMessageJsonObject.has("cmd")) { String cmdType = arrivedMessageJsonObject.get("cmd").toString(); boolean sendMessageToMcuFlag = false; Log.i("TAG", "onMessageReceived: " + cmdType); if(cmdType.equals("update")) { Log.i(TAG_UPGRADE_OPERATE,"Upgrade#01.02.1->> MCU固件升级."); if(!UserGlobalVariable.Upgrade_Mcu_Status){ /* MCU固件升级 */ logString = "服务器下发: MCU固件升级"; MacUpgradeInfoJson.put("ftpIP","8.136.98.49"); MacUpgradeInfoJson.put("ftpPort","21"); MacUpgradeInfoJson.put("ftpUser","cbd_user"); MacUpgradeInfoJson.put("ftpPasswd","YFkj@6O2O"); MacUpgradeInfoJson.put("ftpFilePath","/_UPDATE_FILE/A7/XCT/STM32/XCT.rbl"); //升级状态标识赋 UserGlobalVariable.Upgrade_Mcu_Status = true; UserGlobalVariable.Upgrade_Mcu_FW_Download_Flag = true; UserGlobalVariable.Upgrade_Mcu_Timeout_Flag = false; String mcuUpgradeInfo = "{\"cmd\":\"paramconf\",\"ext\":{\"Demo_mode\":1,\"no_reply\": 1}}"; SerialManager.getInstance().write(mcuUpgradeInfo.getBytes());//辅助YModem升级指令 userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"upgrade\",\"type\":\"mcu\",\"status\":\"2\"}",0); }else{ logString = "服务器下发: MCU升级中,勿重复操作."; Log.i(TAG_UPGRADE_OPERATE,"Upgrade#01.02.2->> MCU升级中,勿重复操作."); userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"upgrade\",\"type\":\"mcu\",\"status\":\"3\"}",0); } } else if(cmdType.equals("dtu_update")) { Log.i(TAG_UPGRADE_OPERATE,"Upgrade#01.01->> APP应用升级."); MacUpgradeInfoJson.put("ftpIP","8.136.98.49"); MacUpgradeInfoJson.put("ftpPort","21"); MacUpgradeInfoJson.put("ftpUser","cbd_user"); MacUpgradeInfoJson.put("ftpPasswd","YFkj@6O2O"); MacUpgradeInfoJson.put("ftpFilePath","/_UPDATE_FILE/A7/XCT/Android/XCT.apk"); if(!SerialManager.getInstance().getUpgradingFlag()){ if(!UserGlobalVariable.Upgrade_APP_Operate_Status){ logString = "服务器下发: APP应用升级"; UserGlobalVariable.Upgrade_APP_Operate_Flag = true; userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"upgrade\",\"type\":\"app\",\"status\":\"2\"}",0); }else{ Log.i(TAG_UPGRADE_OPERATE,"Upgrade#01.03->> APP应用升级中,勿重复操作."); logString = "服务器下发: APP应用升级(升级中)"; } }else{ userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"upgrade\",\"type\":\"app\",\"status\":\"3\"}",0); } } else if(cmdType.equals("setnet")) { JSONObject jsonObject = new JSONObject(); String clientServer = arrivedMessageJsonObject.getString("status"); if(clientServer.equals("1")){ UserGlobalVariable.setlValue("clientServer",clientServer); if(arrivedMessageJsonObject.has("mqtt")){ String mqttUser = arrivedMessageJsonObject.getJSONObject("mqtt").getString("uid"); String mqttPasswd = arrivedMessageJsonObject.getJSONObject("mqtt").getString("pwd"); String mqttIP = arrivedMessageJsonObject.getJSONObject("mqtt").getString("ip"); String mqttPort = arrivedMessageJsonObject.getJSONObject("mqtt").getString("port"); String mqttSubTopic = arrivedMessageJsonObject.getJSONObject("mqtt").getString("sub"); String mqttPubTopic = arrivedMessageJsonObject.getJSONObject("mqtt").getString("pub"); UserGlobalVariable.setlValue("mqttIP",mqttIP); UserGlobalVariable.setlValue("mqttPort",mqttPort); UserGlobalVariable.setlValue("mqttUser",mqttUser); UserGlobalVariable.setlValue("mqttPasswd",mqttPasswd); UserGlobalVariable.setlValue("mqttSubTopic",mqttSubTopic); UserGlobalVariable.setlValue("mqttPubTopic",mqttPubTopic); UserGlobalVariable.Customer_Mqtt_Enable = true; try { jsonObject.put("clientServer",clientServer); jsonObject.put("mqttEnable","1"); jsonObject.put("mqttIP",mqttIP); jsonObject.put("mqttPort",mqttPort); jsonObject.put("mqttUser",mqttUser); jsonObject.put("mqttPasswd",mqttPasswd); jsonObject.put("mqttSubTopic",mqttSubTopic); jsonObject.put("mqttPubTopic",mqttPubTopic); } catch (JSONException e) { throw new RuntimeException(e); } }else{ jsonObject.put("mqttEnable","0"); } if(arrivedMessageJsonObject.has("ftp")){ String ftpUser = arrivedMessageJsonObject.getJSONObject("ftp").getString("uid"); String ftpPasswd = arrivedMessageJsonObject.getJSONObject("ftp").getString("pwd"); String ftpIP = arrivedMessageJsonObject.getJSONObject("ftp").getString("ip"); String ftpPort = arrivedMessageJsonObject.getJSONObject("ftp").getString("port"); String ftpFilePath = arrivedMessageJsonObject.getJSONObject("ftp").getString("filepath"); UserGlobalVariable.setlValue("ftpIP",ftpIP); UserGlobalVariable.setlValue("ftpPort",ftpPort); UserGlobalVariable.setlValue("ftpUser",ftpUser); UserGlobalVariable.setlValue("ftpPasswd",ftpPasswd); UserGlobalVariable.setlValue("ftpFilePath",ftpFilePath); UserGlobalVariable.Customer_FTP_Enable = true; try { jsonObject.put("clientServer",clientServer); jsonObject.put("ftpEnable","1"); jsonObject.put("ftpIP",ftpIP); jsonObject.put("ftpPort",ftpPort); jsonObject.put("ftpUser",ftpUser); jsonObject.put("ftpPasswd",ftpPasswd); jsonObject.put("ftpFilePath",ftpFilePath); MacSetSystemParameterSP(SYS_PARA_CLIENT_SERVER_INFO,jsonObject.toString()); } catch (JSONException e) { throw new RuntimeException(e); } }else{ jsonObject.put("ftpEnable","0"); } MacSetSystemParameterSP(SYS_PARA_CLIENT_SERVER_INFO,jsonObject.toString()); } // 如果当前MQTT正在连接,则先断开连接。 if (customerMqttManager != null && customerMqttManager.isConnected()) { customerMqttManager = null; Log.i("TAG", "MQTT已连接,先断开已有连接.: "); customerMqttManager.disconnect(); } logString = "服务器下发: 客户服务器配置."; } else if(cmdType.equals("Camera")) { //20250414MARK01-3 服务器下发相机拍照时相机忙。 if (MvccCameraManager.getInstance().getCameraState()) { Log.i(TAG_CAMERA_OPERATE,"Camera Is Busy #3!!!"); userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"Camera\",\"status\":\"3\"}",0); } else { UserGlobalVariable.Camera_Set_Parameters_Flag = true; userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"Camera\",\"status\":\"2\"}",0); //设置参数 if(arrivedMessageJsonObject.getString("operate").equals("1")) { UserGlobalVariable.Camera_SG_Parameters_Flag = 1; //自动曝光 if(arrivedMessageJsonObject.getJSONObject("parameters").has("ExposureAuto")) { UserGlobalVariable.Camera_Set_ExposureAuto_Flag = true; String tempParameter = arrivedMessageJsonObject.getJSONObject("parameters").getString("ExposureAuto"); UserGlobalVariable.setlValue("ExposureAuto",tempParameter); // Log.i("MVCC_CAMERA_OPERATE","Mac#1982->> P01: 自动曝光使能: " + UserGlobalVariable.getValue("ExposureAuto")); } //自动曝光时间 if(arrivedMessageJsonObject.getJSONObject("parameters").has("ExposureTime")){ UserGlobalVariable.Camera_Set_ExposureTime_Flag = true; String tempParameter = arrivedMessageJsonObject.getJSONObject("parameters").getString("ExposureTime"); UserGlobalVariable.setlValue("ExposureTime",tempParameter); // Log.i("MVCC_CAMERA_OPERATE","Mac#1990->> P02: 自动曝光时间: " + UserGlobalVariable.getValue("ExposureTime")); } //伽马使能 if(arrivedMessageJsonObject.getJSONObject("parameters").has("BalanceWhiteAuto")){ UserGlobalVariable.Camera_Set_BalanceWhiteAuto_Flag = true; String tempParameter = arrivedMessageJsonObject.getJSONObject("parameters").getString("BalanceWhiteAuto"); UserGlobalVariable.setlValue("BalanceWhiteAuto",tempParameter); // Log.i("MVCC_CAMERA_OPERATE","Mac#1998->> P03: 伽马使能开关: " + UserGlobalVariable.getValue("BalanceWhiteAuto")); } //伽马使能 if(arrivedMessageJsonObject.getJSONObject("parameters").has("GammaEnable")){ UserGlobalVariable.Camera_Set_GammaEnable_Flag = true; String tempParameter = arrivedMessageJsonObject.getJSONObject("parameters").getString("GammaEnable"); UserGlobalVariable.setlValue("GammaEnable",tempParameter); // Log.i("MVCC_CAMERA_OPERATE","Mac#1998->> P03: 伽马使能开关: " + UserGlobalVariable.getValue("GammaEnable")); } //伽马值 if(arrivedMessageJsonObject.getJSONObject("parameters").has("Gamma")){ UserGlobalVariable.Camera_Set_Gamma_Flag = true; String tempParameter = arrivedMessageJsonObject.getJSONObject("parameters").getString("Gamma"); UserGlobalVariable.setlValue("Gamma",tempParameter); // Log.i("MVCC_CAMERA_OPERATE","Mac#2006->> P04: 伽马值: " + UserGlobalVariable.getValue("Gamma")); } //色度使能 if(arrivedMessageJsonObject.getJSONObject("parameters").has("HueEnable")){ UserGlobalVariable.Camera_Set_HueEnable_Flag = true; String tempParameter = arrivedMessageJsonObject.getJSONObject("parameters").getString("HueEnable"); UserGlobalVariable.setlValue("HueEnable",tempParameter); // Log.i("MVCC_CAMERA_OPERATE","Mac#2014->> P05: 色度使能开关: " + UserGlobalVariable.getValue("HueEnable")); } //色度值 if(arrivedMessageJsonObject.getJSONObject("parameters").has("Hue")){ UserGlobalVariable.Camera_Set_Hue_Flag = true; String tempParameter = arrivedMessageJsonObject.getJSONObject("parameters").getString("Hue"); UserGlobalVariable.setlValue("Hue",tempParameter); // Log.i("MVCC_CAMERA_OPERATE","Mac#2022->> P06: 色度值: " + UserGlobalVariable.getValue("Hue")); } } else { UserGlobalVariable.Camera_SG_Parameters_Flag = 0; } } logString = "服务器下发: 相机参数配置."; } else if(cmdType.toString().equals("ctrl")) { if(arrivedMessageJsonObject.getJSONObject("ext").has("type")){ if(arrivedMessageJsonObject.getJSONObject("ext").getString("type").equals("takephoto")){ /* 此时正在"相机操作"界面时或相机正在执行拍照任务时 */ //20250414MARK01-3 服务器下发相机拍照时相机忙。 if (MvccCameraManager.getInstance().getCameraState()) { Log.i(TAG_CAMERA_OPERATE,"Camera Is Busy #3!!!"); userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"ctrl\",\"type\":\"takephoto\",\"status\":\"3\"}",0); } else { logString = "服务器下发: 立即拍照"; UserGlobalVariable.Camera_TimingTakePhoto_Flag = true; sendMessageToMcuFlag = true; userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"ctrl\",\"type\":\"takephoto\",\"status\":\"2\"}",0); } } }else{ sendMessageToMcuFlag = true; } } else if(cmdType.toString().equals("paramconf")) { sendMessageToMcuFlag = true; logString = "服务器下发: 参数设置"; } else if(cmdType.toString().equals("dtu_reboot")) { sendMessageToMcuFlag = true; logString = "服务器下发: 安卓重启"; } else if(cmdType.toString().equals("systemParameter")) { String waitTime = arrivedMessageJsonObject.getJSONObject("ext").getString("waitTime"); Log.i("TAG", "onMessageReceived: " + waitTime); UserGlobalVariable.CameraTakePhotoWaitExposure = Integer.parseInt(waitTime); MacSetSystemParameterSP(SYS_PARA_CAMERA_TAKE_PHOTO_WAIT_EXPOSURE,waitTime); } if (sendMessageToMcuFlag) { sendMessageToMcuFlag = false; if(!SerialManager.getInstance().getUpgradingFlag()){ SerialManager.getInstance().write(message.getBytes());//串口下发界面操作指令(升级冲突#3) } } if(!logString.isEmpty()){ Log.i(TAG_FMACX_MSG_TO_MAC,"FromMqtt->> OptEvents = " + logString); LogFileManagerOperate.VerifyLogFileConformsToJson(); LogFileManagerOperate.CheckLogFileNumber(); LogFileManagerOperate.AddOneLogItem(logString); } } } catch (JSONException e) { // throw new RuntimeException(e); } } } @Override public void onError(Throwable throwable) { } }); Log.i("MqttOperate","Mac#2037-> 连接公司Mqtt服务器 " + UserGlobalVariable.getValue("imei")); userMqttManager.mqttConnect(MQTT_MAIN_SUB_TOPIC + UserGlobalVariable.getValue("imei")); } else { if (userMqttManager.isConnected()) { if(UserGlobalVariable.McuData_UploadToOfficialServer_Flag){ UserGlobalVariable.McuData_UploadToOfficialServer_Flag = false; userMqttManager.publish(MQTT_MAIN_PUB_TOPIC + UserGlobalVariable.getValue("imei"),UserGlobalVariable.McuData_UploadToOfficialServer,0); UserGlobalVariable.McuData_UploadToOfficialServer = ""; Log.i("TAG", "MacMainMqttFunction: 向服务器发送数据."); } if (MacAppHeartbeatFlag) { MacAppHeartbeatFlag = false; MacAppHeartbeatToServer(); } HistoryDataManager historyManager = new HistoryDataManager(this); // 统计行数 int lineCount = historyManager.countLines(); if(lineCount > 0){ //取出数据 String lastLine = historyManager.removeLastLine(); // mqttManager.publish(MQTT_MAIN_PUB_TOPIC + UserGlobalVariable.getValue("imei"),lastLine,0,false,10000); userMqttManager.publish(MQTT_MAIN_PUB_TOPIC + UserGlobalVariable.getValue("imei"),lastLine,0); // 再次统计行数 lineCount = historyManager.countLines(); } } else { if(UserGlobalVariable.Mqtt_M_ReConnect_Flag == 1){ UserGlobalVariable.Mqtt_M_ReConnect_Flag = 2; Log.i("TAG", "MAC#2050-> 主MQTT服务器重连."); userMqttManager.mqttConnect(MQTT_MAIN_SUB_TOPIC + UserGlobalVariable.getValue("imei")); } // 网络断开连接时保存数据到本地 if(UserGlobalVariable.McuData_UploadToOfficialServer_Flag){ UserGlobalVariable.McuData_UploadToOfficialServer_Flag = false; try { JSONObject hisJsonObject = new JSONObject(UserGlobalVariable.McuData_UploadToOfficialServer); if(hisJsonObject.has("cmd")){ //如果要上传的数据是data类型的,则保存至本地. if(hisJsonObject.get("cmd").equals("data")){ Log.i("TAG", "MacMainMqttFunction#1: data类型数据,做本地保存."); hisJsonObject.put("cmd","HistoryData"); HistoryDataManager historyManager = new HistoryDataManager(this); // 统计行数 int lineCount = historyManager.countLines(); //写入数据 historyManager.writeJsonData(hisJsonObject); }else{ Log.i("TAG", "MacMainMqttFunction#2: 非data类型数据,不做本地保存."); } } } catch (JSONException e) { //throw new RuntimeException(e); // Log.i(TAG_HISTORY_DATA,"HD#5.0.3->> 数据生成异常."); } UserGlobalVariable.McuData_UploadToOfficialServer = ""; } } } } void MqttCustomPublishFunction(String payload){ if(userMqttManager != null){ if(userMqttManager.isConnected()){ userMqttManager.publish(MQTT_MAIN_PUB_TOPIC + UserGlobalVariable.getValue("imei"),payload,0); } } } void MacCustomerMqttFunction(){ if (!UserGlobalVariable.Android_Dev_GetIMEIResult || !UserGlobalVariable.Customer_Mqtt_Enable) { return; } if(customerMqttManager == null){ // 使用String.format组合 String TempURL = String.format("tcp://%s:%s", UserGlobalVariable.getValue("mqttIP"), UserGlobalVariable.getValue("mqttPort")); String TempUSER = UserGlobalVariable.getValue("mqttUser"); String TempPASSWD = UserGlobalVariable.getValue("mqttPasswd"); Log.i("TAG", "Mac#2115-> Mqtt: " + TempURL + " " + TempPASSWD); customerMqttManager = new UserMqttManager(TempURL, TempUSER, TempPASSWD, UserGlobalVariable.getValue("imei")); customerMqttManager.setMqttConnectionCallback(new UserMqttManager.MqttConnectionCallback() { @Override public void onConnectionChanged(boolean isConnected) { if(isConnected){ UserGlobalVariable.Customer_Mqtt_Connect_Status = 1; UserGlobalVariable.Customer_Mqtt_ReConnect_Flag = 0; Log.i("TAG", "MAC#2116-> 客户端MQTT连接成功."); }else { UserGlobalVariable.Customer_Mqtt_Connect_Status = 0; UserGlobalVariable.Customer_Mqtt_ReConnect_Flag = 1; Log.i("TAG", "MAC#2116-> 客户端MQTT连接断开."); } } @Override public void onMessageReceived(String topic, String message, boolean retained) { if(retained){ Log.i("TAG", "清除Retained消息"); customerMqttManager.publishNull(UserGlobalVariable.getValue("mqttSubTopic") + UserGlobalVariable.getValue("imei")); } if (!message.isEmpty()) { JSONObject arrivedMessageJsonObject = null; try { arrivedMessageJsonObject = new JSONObject(message); if (arrivedMessageJsonObject.has("cmd")) { String cmdType = arrivedMessageJsonObject.get("cmd").toString(); boolean sendMessageToMcuFlag = false; Log.i("TAG", "onMessageReceived: " + cmdType); if(cmdType.toString().equals("ctrl")) { if(arrivedMessageJsonObject.getJSONObject("ext").has("type")){ if(arrivedMessageJsonObject.getJSONObject("ext").getString("type").equals("takephoto")){ /* 此时正在"相机操作"界面时或相机正在执行拍照任务时 */ //20250414MARK01-3 服务器下发相机拍照时相机忙。 if (MvccCameraManager.getInstance().getCameraState()) { Log.i(TAG_CAMERA_OPERATE,"Camera Is Busy #3!!!"); customerMqttManager.publish(UserGlobalVariable.getValue("mqttPubTopic") + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"ctrl\",\"type\":\"takephoto\",\"status\":\"3\"}",0); } else { UserGlobalVariable.Camera_TimingTakePhoto_Flag = true; sendMessageToMcuFlag = true; customerMqttManager.publish(UserGlobalVariable.getValue("mqttPubTopic") + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"ctrl\",\"type\":\"takephoto\",\"status\":\"2\"}",0); } } }else{ sendMessageToMcuFlag = true; } } else if(cmdType.toString().equals("paramconf")) { sendMessageToMcuFlag = true; } else if(cmdType.toString().equals("dtu_reboot")) { sendMessageToMcuFlag = true; } if (sendMessageToMcuFlag) { sendMessageToMcuFlag = false; if(!SerialManager.getInstance().getUpgradingFlag()){ SerialManager.getInstance().write(message.getBytes());//串口下发界面操作指令(升级冲突#3) } } } } catch (JSONException e) { // throw new RuntimeException(e); } } } @Override public void onError(Throwable throwable) { } }); Log.i("MqttOperate","Mac#2236-> 连接客户Mqtt服务器 " + UserGlobalVariable.getValue("imei")); customerMqttManager.mqttConnect(UserGlobalVariable.getValue("mqttSubTopic") + UserGlobalVariable.getValue("imei")); } else { if (customerMqttManager.isConnected()) { if (UserGlobalVariable.Customer_Mqtt_McuDataToServer_Flag) { UserGlobalVariable.Customer_Mqtt_McuDataToServer_Flag = false; customerMqttManager.publish(UserGlobalVariable.getValue("mqttPubTopic") + UserGlobalVariable.getValue("imei"),UserGlobalVariable.Customer_Mqtt_McuDataToServer,0); UserGlobalVariable.Customer_Mqtt_McuDataToServer = ""; Log.i("TAG", "MacMainMqttFunction: 向客户服务器发送数据."); } if (CustomerMqttHeartbeatToServerFlag) { CustomerMqttHeartbeatToServerFlag = false; MacAppCustomerMqttHeartbeatToServer(); } } else { if (UserGlobalVariable.Customer_Mqtt_ReConnect_Flag == 1) { UserGlobalVariable.Customer_Mqtt_ReConnect_Flag = 2; Log.i("TAG", "MAC#2240-> 客MQTT服务器重连."); customerMqttManager.mqttConnect(UserGlobalVariable.getValue("mqttSubTopic") + UserGlobalVariable.getValue("imei")); } } } } /******************************************** 主线程功能 ********************************************/ public class ThreadMainActivity extends Thread { public void run() { while(true) { MacMainMqttFunction(); MacCustomerMqttFunction(); /* 获取手机状态信息 */ if(MacGetPhoneStateInfoFlag || !UserGlobalVariable.Android_Dev_GetIMEIResult){ MacGetPhoneStateInfoFlag = false; MacGetPhoneStateInfo(); } MainActivityMessageToFragment("MainActivityToFMac0","Operate","Refresh"); /* MCU固件升级 */ if (UserGlobalVariable.Upgrade_Mcu_Status) { if (UserGlobalVariable.Upgrade_Mcu_FW_Download_Flag) { UserGlobalVariable.Upgrade_Mcu_FW_Download_Flag = false; try { String ftpIP = MacUpgradeInfoJson.get("ftpIP").toString(); int ftpPort = Integer.parseInt(MacUpgradeInfoJson.get("ftpPort").toString()); String ftpUser = MacUpgradeInfoJson.get("ftpUser").toString(); String ftpPasswd = MacUpgradeInfoJson.get("ftpPasswd").toString(); String ftpFilePath = MacUpgradeInfoJson.get("ftpFilePath").toString(); Log.i(TAG_UPGRADE_OPERATE,"Upgrade#04.00->> ftpIP : " + ftpIP); Log.i(TAG_UPGRADE_OPERATE,"Upgrade#04.00->> ftpPort : " + ftpPort); Log.i(TAG_UPGRADE_OPERATE,"Upgrade#04.00->> ftpUser : " + ftpUser); Log.i(TAG_UPGRADE_OPERATE,"Upgrade#04.00->> ftpPasswd : " + ftpPasswd); Log.i(TAG_UPGRADE_OPERATE,"Upgrade#04.00->> ftpFilePath: " + ftpFilePath); FtpTransferManager upgradeFtpTrans = new FtpTransferManager(ftpIP, ftpPort, ftpUser, ftpPasswd, ftpFilePath); boolean res = upgradeFtpTrans.downloadFile(String.valueOf(getFilesDir()),30); upgradeFtpTrans.shutdown(); if(res){ File firmware = new File(getFilesDir(),"XCT.rbl"); new CustomYModemManager().startUpgrade(firmware); UserGlobalVariable.Upgrade_Mcu_Process_Status = true; UserGlobalVariable.Upgrade_Mcu_Timeout_Value = 0; MqttCustomPublishFunction("{\"cmd\":\"upgrade\",\"type\":\"mcu\",\"status\":\"4\"}"); }else{ Log.i(TAG_UPGRADE_OPERATE,"MCU固件下载失败."); UserGlobalVariable.Upgrade_Mcu_Status = false; MqttCustomPublishFunction("{\"cmd\":\"upgrade\",\"type\":\"mcu\",\"status\":\"0\"}"); } } catch (JSONException e) { // throw new RuntimeException(e); Log.i(TAG_UPGRADE_OPERATE,"MCU固件升级信息获取有误"); } } if (UserGlobalVariable.Upgrade_Mcu_Process_Status) { if (SerialManager.getInstance().getUpgradingFlag()) { Log.i(TAG_UPGRADE_OPERATE,"MCU YModem升级操作进行中." + UserGlobalVariable.Upgrade_Mcu_Timeout_Value); UserGlobalVariable.Upgrade_Mcu_Timeout_Value ++; if(UserGlobalVariable.Upgrade_Mcu_Timeout_Value > 360){ UserGlobalVariable.Upgrade_Mcu_Timeout_Value = 0; Log.i(TAG_UPGRADE_OPERATE,"MCU YModem升级操作异常超时."); SerialManager.getInstance().setUpgrading(false); serialManager.setDataProcessor(customJsonProcessorManager); UserGlobalVariable.Upgrade_Mcu_Process_Status = false; String endCmd = "{\"cmd\":\"paramconf\",\"ext\":{\"Demo_mode\":0}}"; SerialManager.getInstance().write(endCmd.getBytes()); UserGlobalVariable.Upgrade_Mcu_Status = false; MqttCustomPublishFunction("{\"cmd\":\"upgrade\",\"type\":\"mcu\",\"status\":\"5\"}"); } } else { Log.i(TAG_UPGRADE_OPERATE,"MCU YModem升级操作结束."); serialManager.setDataProcessor(customJsonProcessorManager); UserGlobalVariable.Upgrade_Mcu_Process_Status = false; UserGlobalVariable.Upgrade_Mcu_Status = false; if(UserGlobalVariable.Upgrade_Mcu_Timeout_Flag){ MqttCustomPublishFunction("{\"cmd\":\"upgrade\",\"type\":\"mcu\",\"status\":\"6\"}"); }else{ MqttCustomPublishFunction("{\"cmd\":\"upgrade\",\"type\":\"mcu\",\"status\":\"1\"}"); } String endCmd = "{\"cmd\":\"paramconf\",\"ext\":{\"Demo_mode\":0}}"; SerialManager.getInstance().write(endCmd.getBytes()); UserGlobalVariable.Upgrade_Mcu_Timeout_Flag = false; } } } /* 自动拍照上传 */ if (UserGlobalVariable.Camera_TimingTakePhoto_Flag) { UserGlobalVariable.Camera_TimingTakePhoto_Flag = false; Log.i(TAG_CAMERA_OPERATE, "开始拍照上传"); AutoTakePhotoAndUploadThread(); } /* 读取/设置相机参数 */ if(UserGlobalVariable.Camera_Set_Parameters_Flag){ UserGlobalVariable.Camera_Set_Parameters_Flag = false; Log.i(TAG_CAMERA_OPERATE, "远程设置相机参数"); RemoteSetCameraParametersThread(); } /* 自动上传缓存照片 */ AutoUploadPhotosToFTP(); /* 静默升级 */ if (UserGlobalVariable.Upgrade_APP_Operate_Flag) { UserGlobalVariable.Upgrade_APP_Operate_Flag = false; UserGlobalVariable.Upgrade_APP_Operate_Status = true; String appUpgradeStart = "{\"cmd\":\"paramconf\",\"ext\":{\"Demo_mode\":1}}"; SerialManager.getInstance().write(appUpgradeStart.getBytes()); //删除本地缓存的旧安装包 MacAppUpgradeDeleteApkIfExists(); try { String ftpIP = MacUpgradeInfoJson.get("ftpIP").toString(); int ftpPort = Integer.parseInt(MacUpgradeInfoJson.get("ftpPort").toString()); String ftpUser = MacUpgradeInfoJson.get("ftpUser").toString(); String ftpPasswd = MacUpgradeInfoJson.get("ftpPasswd").toString(); String ftpFilePath = MacUpgradeInfoJson.get("ftpFilePath").toString(); Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.00->> ftpIP : " + ftpIP); Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.00->> ftpPort : " + ftpPort); Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.00->> ftpUser : " + ftpUser); Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.00->> ftpPasswd : " + ftpPasswd); Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.00->> ftpFilePath: " + ftpFilePath); FtpTransferManager apkFileTransByFTP = new FtpTransferManager(ftpIP, ftpPort, ftpUser, ftpPasswd, ftpFilePath); boolean res = apkFileTransByFTP.downloadFile(String.valueOf(getFilesDir()),180); apkFileTransByFTP.shutdown(); if (res) { MacExecuteShellSilentFlag = true; Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.00->> APK下载成功."); MqttCustomPublishFunction("{\"cmd\":\"upgrade\",\"type\":\"app\",\"status\":\"1\"}"); }else{ MqttCustomPublishFunction("{\"cmd\":\"upgrade\",\"type\":\"app\",\"status\":\"0\"}"); } /* 成功或失败都退出'演示模式',安卓设备不会立即断电,最短断电时间为数据上传周期后. */ appUpgradeStart = "{\"cmd\":\"paramconf\",\"ext\":{\"Demo_mode\":0}}"; SerialManager.getInstance().write(appUpgradeStart.getBytes()); UserGlobalVariable.Upgrade_APP_Operate_Status = false; } catch (JSONException e) { // throw new RuntimeException(e); appUpgradeStart = "{\"cmd\":\"paramconf\",\"ext\":{\"Demo_mode\":0}}"; SerialManager.getInstance().write(appUpgradeStart.getBytes()); UserGlobalVariable.Upgrade_APP_Operate_Status = false; Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.00->> APP应用升级信息获取有误"); } } if (MacExecuteShellSilentFlag) { MacExecuteShellSilentFlag = false; /*if (USER_PLATFORM_TYPE == PLATFROM_TYPE_WANGFEI) { Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.01->> 网飞设备由天工平台安装."); } else {*/ Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.01->> 执行安装操作."); MacExecuteShellSilent(String.valueOf(new File(getFilesDir(),"XCT.apk"))); //} } /* 语音播放 */ MainActivityVoiceMediaPlayer(VoicePlayingID); /* 线程延时 */ try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } } @Override protected void onDestroy() { super.onDestroy(); } }