| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832 |
- 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<LocationInfo> aidlResponse = FastJsonUtils.fromJson(json,new TypeReference<AidlResponse<LocationInfo>>(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<Boolean> 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 <String,String> 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<String> 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 <String> 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 <SubscriptionInfo> 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();
- }
- }
|