MainActivity.java 132 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832
  1. package com.example.yunfeiapplication;
  2. import android.Manifest;
  3. import android.content.ComponentName;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.ServiceConnection;
  7. import android.content.SharedPreferences;
  8. import android.content.pm.PackageManager;
  9. import android.graphics.Bitmap;
  10. import android.graphics.Color;
  11. import android.location.Location;
  12. import android.location.LocationListener;
  13. import android.location.LocationManager;
  14. import android.media.AudioManager;
  15. import android.media.MediaPlayer;
  16. import android.net.ConnectivityManager;
  17. import android.net.Uri;
  18. import android.os.Build;
  19. import android.os.Bundle;
  20. import android.os.Environment;
  21. import android.os.Handler;
  22. import android.os.IBinder;
  23. import android.os.Looper;
  24. import android.os.RemoteException;
  25. import android.provider.Settings;
  26. import android.telephony.SignalStrength;
  27. import android.telephony.SubscriptionInfo;
  28. import android.telephony.SubscriptionManager;
  29. import android.telephony.TelephonyManager;
  30. import android.util.Log;
  31. import android.view.MenuItem;
  32. import android.view.MotionEvent;
  33. import android.view.View;
  34. import android.view.WindowManager;
  35. import android.widget.Toast;
  36. import androidx.activity.EdgeToEdge;
  37. import androidx.annotation.NonNull;
  38. import androidx.appcompat.app.AppCompatActivity;
  39. import androidx.core.app.ActivityCompat;
  40. import androidx.core.graphics.Insets;
  41. import androidx.core.view.ViewCompat;
  42. import androidx.core.view.WindowInsetsCompat;
  43. import androidx.drawerlayout.widget.DrawerLayout;
  44. import androidx.fragment.app.FragmentResultListener;
  45. import com.alibaba.fastjson.TypeReference;
  46. import com.example.yunfeiapplication.fragments.FragmentMac0;
  47. import com.example.yunfeiapplication.fragments.FragmentMac1;
  48. import com.example.yunfeiapplication.fragments.FragmentMac2;
  49. import com.example.yunfeiapplication.fragments.FragmentMac3;
  50. import com.example.yunfeiapplication.fragments.FragmentMac4;
  51. import com.example.yunfeiapplication.fragments.FragmentMac5;
  52. import com.example.yunfeiapplication.managerClass.CustomAudioPlayerManager;
  53. import com.example.yunfeiapplication.managerClass.CustomJsonProcessorManager;
  54. import com.example.yunfeiapplication.managerClass.CustomYModemManager;
  55. import com.example.yunfeiapplication.managerClass.FtpTransferManager;
  56. import com.example.yunfeiapplication.managerClass.MvccCameraManager;
  57. import com.example.yunfeiapplication.managerClass.SerialManager;
  58. import com.example.yunfeiapplication.managerClass.UserMqttManager;
  59. import com.example.yunfeiapplication.ownClass.FastJsonUtils;
  60. import com.example.yunfeiapplication.ownClass.HistoryDataManager;
  61. import com.example.yunfeiapplication.variable.UserGlobalVariable;
  62. import com.google.android.material.navigation.NavigationView;
  63. import com.hzmct.enjoysdk.api.EnjoySDK;
  64. import com.hzmct.enjoysdk.transform.EnjoyApiNotSupportException;
  65. import com.mc.android.mckeepalive.McKeepAliveApp;
  66. import com.wif.baseservice.IBaseServiceCallback;
  67. import com.wif.baseservice.IBaseServiceInterface;
  68. import com.wif.bslib.AidlConstants;
  69. import com.wif.bslib.AidlRequest;
  70. import com.wif.bslib.AidlResponse;
  71. import com.wif.bslib.BaseRequest;
  72. import com.wif.bslib.BaseResponse;
  73. import com.wif.bslib.bean.LocationInfo;
  74. import org.apache.commons.net.ftp.FTPClient;
  75. import org.json.JSONException;
  76. import org.json.JSONObject;
  77. import java.io.BufferedReader;
  78. import java.io.BufferedWriter;
  79. import java.io.DataOutputStream;
  80. import java.io.File;
  81. import java.io.FileInputStream;
  82. import java.io.FileOutputStream;
  83. import java.io.FileReader;
  84. import java.io.FileWriter;
  85. import java.io.IOException;
  86. import java.lang.reflect.Method;
  87. import java.text.SimpleDateFormat;
  88. import java.util.ArrayList;
  89. import java.util.Calendar;
  90. import java.util.Date;
  91. import java.util.List;
  92. import java.util.Locale;
  93. import java.util.Map;
  94. /*
  95. * 1.安卓设备取消默认启动应用
  96. * 命令:adb shell
  97. * monkey -p com.hzmct.enjoyConfig 1
  98. * 2.取消应用保活
  99. * EnjoySDK enjoySDK = new EnjoySDK(context);
  100. * int ret = enjoySDK.EnableKeepAlive(false);
  101. * */
  102. public class MainActivity extends AppCompatActivity implements CustomJsonProcessorManager.CustomMessageInterface {
  103. private static final int PLATFROM_TYPE_MAICHONG = 1;
  104. private static final int PLATFROM_TYPE_WANGFEI = 2;
  105. private final int USER_PLATFORM_TYPE = PLATFROM_TYPE_WANGFEI;
  106. EnjoySDK enjoySDK;
  107. private IBaseServiceInterface serviceInterface;
  108. private AidlCallback AidlCallback;
  109. private BaseServiceConnection ServiceConnection;
  110. private boolean BaseServiceConnectionFlag = false;
  111. private boolean HeartBeatFirstReportFlag = true;
  112. private static final String TAG_UPGRADE_OPERATE = "UpgradeOperate";
  113. private static final String TAG_LOG_MANAGER = "MacLogOperate";
  114. private static final String TAG_CAMERA_OPERATE = "CameraTakePhoto";
  115. private static final String TAG_PLATFORM_MAICHON = "MacPlatformMaiChong";
  116. private static final String TAG_PLATFORM_WANGFEI = "MacPlatformWangFei";
  117. private static final String TAG_FMACX_MSG_TO_MAC = "FMacXMessageToMainActivity";
  118. private static final String TAG_FTP_APP_UPGRADE = "FMacFtpAppUpgrade";
  119. private static final String TAG_REQUEST_PERMISSIONS = "RequestPermissions";
  120. private static final String TAG_SYSTEM_PARAMETER_SP = "SystemParameterSP";
  121. private static final String TAG_HISTORY_DATA = "HistoryData";
  122. /* 滑动侧边栏 */
  123. DrawerLayout MainDrawerLayout;
  124. NavigationView MainNavigationView;
  125. private int OldFragmentIndex; /* 当前Fragment页面标签号 */
  126. private int MacGetPhoneStateInfoTime = 0;
  127. private boolean MacGetPhoneStateInfoFlag = true;
  128. /* 定位相关 */
  129. private LocationManager locationManager;
  130. private LocationListener locationListener;
  131. /* 设备操作日志相关 */
  132. private LogFileManager LogFileManagerOperate;
  133. /* 音频播放相关 */
  134. CustomAudioPlayerManager MacAudioPlayer;
  135. private boolean VoicePlayingFlag = false;
  136. private int VoicePlayingID = 0;
  137. /* 系统永久变量存储相关 */
  138. SharedPreferences SystemParameterSettings;
  139. // SharedPreferences文件名
  140. private static final String PREFS_NAME = "SystemParameterSP";
  141. // SharedPreferences中的键
  142. private static final String SYS_PARA_CLIENT_SERVER_INFO = "ClientServerInfo";
  143. private static final String SYS_PARA_CAMERA_TAKE_PHOTO_WAIT_EXPOSURE = "CameraTakePhotoWaitExposure";
  144. private static final String SYS_PARA_GPS_LONGITUDE = "GPSLongitude";
  145. private static final String SYS_PARA_GPS_LATITUDE = "GPSLatitude";
  146. /* 秒触发Handler */
  147. private final Handler MacOneSecondTriggerHandler = new Handler(Looper.getMainLooper());
  148. private Runnable MacOneSecondTiggerRunnable;
  149. JSONObject MacUpgradeInfoJson = new JSONObject();
  150. //大数据平台
  151. int MacDeviceDataToServerTime = 0;
  152. boolean MacAppHeartbeatFlag = true;
  153. int CustomerMqttHeartbeatToServerTime = 0;
  154. boolean CustomerMqttHeartbeatToServerFlag = true;
  155. private final String MQTT_MAIN_SUB_TOPIC = "/yfkj/XCT/sub/";
  156. private final String MQTT_MAIN_PUB_TOPIC = "/yfkj/XCT/pub/";
  157. private final String MQTT_MAIN_HOST_URL = "tcp://8.136.98.49:61883";
  158. private final String MQTT_MAIN_USER = "user";
  159. private final String MQTT_MAIN_PASSWORD = "f335bf402c655ee5fd2b5300905124e";
  160. private final String FTP_INFO_HOST_URL = "8.136.98.49";
  161. private final int FTP_INFO_HOST_PORT = 21;
  162. private final String FTP_INFO_HOST_USER = "cbd_XCT";
  163. private final String FTP_INFO_HOST_PASSWD = "YFkj@6O2O";
  164. private boolean MacExecuteShellSilentFlag = false;
  165. SerialManager serialManager;
  166. CustomJsonProcessorManager customJsonProcessorManager;
  167. UserMqttManager userMqttManager = null;
  168. UserMqttManager customerMqttManager = null;
  169. public static MainActivity Instance;
  170. @Override
  171. protected void onCreate(Bundle savedInstanceState) {
  172. super.onCreate(savedInstanceState);
  173. Instance = this;
  174. //EdgeToEdge.enable(this);
  175. getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
  176. setContentView(R.layout.activity_main);
  177. hideSystemUI();
  178. /*ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
  179. Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
  180. v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
  181. return insets;
  182. });*/
  183. /* 加载存储的系统参数 */
  184. SystemParameterSettings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
  185. MacGetSystemParameterSP();
  186. /* 平台选择 */
  187. if (PLATFROM_TYPE_MAICHONG == USER_PLATFORM_TYPE) {
  188. MaiChongPlatformSInit();
  189. //MacStartLocationUpdates();
  190. MacHideSystemUI();
  191. } else {
  192. AidlCallback = new AidlCallback();
  193. ServiceConnection = new BaseServiceConnection();
  194. Intent intent = new Intent(AidlConstants.ACTION_BASE_SERVICE);
  195. intent.setPackage(AidlConstants.PACKAGE_BASE_SERVICE);
  196. bindService(intent, ServiceConnection, BIND_AUTO_CREATE);
  197. }
  198. /* 启动GPS位置信息获取服务 */
  199. MacStartLocationUpdates();
  200. /* 修改相机权限及设置缓冲区 */
  201. MacSystemExecuteShellCommand();
  202. /*获取定位、手机状态、存储权限*/
  203. GetSelfPermissionPhoneState();
  204. /* 程序运行起始界面, Modified by NiuJiuRu @2025-05-20 */
  205. FragmentMac0 fragment = new FragmentMac0();
  206. getSupportFragmentManager()
  207. .beginTransaction()
  208. .replace(R.id.mainFragmentContainerView, fragment)
  209. .commitNow();
  210. //getSupportFragmentManager().beginTransaction().replace(R.id.mainFragmentContainerView, FragmentMac0.class,null).commit();
  211. OldFragmentIndex = 0;
  212. /* 侧边栏初始化 */
  213. MainNavigationView = findViewById(R.id.mainNavigationView);
  214. MainNavigationView.setItemIconTintList(null);
  215. MainDrawerLayout = findViewById(R.id.mainDrawerLayout);
  216. MainDrawerLayout.setScrimColor(Color.TRANSPARENT);
  217. /* 日志记录初始化 */
  218. LogFileManagerOperate = new LogFileManager();
  219. LogFileManagerOperate.VerifyLogFileConformsToJson();
  220. MacAudioPlayer = new CustomAudioPlayerManager(getApplicationContext());
  221. /* 串口初始化 */
  222. serialManager = SerialManager.getInstance();
  223. customJsonProcessorManager = new CustomJsonProcessorManager();
  224. serialManager.setDataProcessor(customJsonProcessorManager);
  225. customJsonProcessorManager.setCustomMessageInterface(this);
  226. /* 主线程初始化 */
  227. ThreadMainActivity threadMainActivity = new ThreadMainActivity();
  228. threadMainActivity.start();
  229. if (isMobileDataEnabled(this)) {
  230. Log.i("TAG", "onCreate: 数据流量开关已开启");
  231. }else{
  232. Log.i("TAG", "onCreate: 数据流量开关已关闭");
  233. setMobileDataEnabledByRoot(true);
  234. }
  235. /*** 侧边栏点击事件处理 ***/
  236. MainNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
  237. @Override
  238. public boolean onNavigationItemSelected(@NonNull MenuItem item) {
  239. int itemId = item.getItemId();
  240. int tempIndex = 0;
  241. if (itemId == R.id.menu_item_1) {
  242. tempIndex = 1;
  243. } else if (itemId == R.id.menu_item_2) {
  244. tempIndex = 2;
  245. } else if (itemId == R.id.menu_item_3) {
  246. tempIndex = 3;
  247. } else if (itemId == R.id.menu_item_4) {
  248. tempIndex = 4;
  249. } else if (itemId == R.id.menu_item_5) {
  250. tempIndex = 5;
  251. } else if (itemId == R.id.menu_item_6) {
  252. tempIndex = 6;
  253. }
  254. String tempStr = UserGlobalVariable.getValue("login");
  255. if(tempStr != null && !tempStr.isEmpty()){
  256. /* 监测是否已登录成功,否则点击侧边栏时不跳转. */
  257. if(tempStr.equals("1")){
  258. /* 如果此时准备跳转至'相机操作'界面但主线程正在执行自动拍照则不执行界面跳转操作 */
  259. //20250414MARK01-1:界面跳转时相机忙。
  260. if ((OldFragmentIndex == 2 || OldFragmentIndex == 3) && MvccCameraManager.getInstance().getCameraState()) {
  261. Log.i(TAG_CAMERA_OPERATE,"Camera Is Busy #1!!!");
  262. VoicePlayingFlag = true;
  263. VoicePlayingID = 9;
  264. } else {
  265. MacReplaceFragment(tempIndex);
  266. }
  267. }else{
  268. //20250413MARK02
  269. if(OldFragmentIndex != 0){
  270. UserGlobalVariable.setlValue("login","1");
  271. Log.i(TAG_CAMERA_OPERATE,"登录状态异常,更正为已登录.");
  272. }
  273. }
  274. }
  275. /* 点击侧边栏500毫秒后自动收起 */
  276. MainNavigationView.postDelayed(new Runnable() {
  277. @Override
  278. public void run() {
  279. if (MainDrawerLayout.isDrawerOpen(MainNavigationView)) {
  280. MainDrawerLayout.closeDrawer(MainNavigationView);
  281. MainDrawerLayout.requestDisallowInterceptTouchEvent(true);
  282. }
  283. }
  284. },500);
  285. return false;
  286. }
  287. });
  288. /*** 监听及解析来自FragmentMac0的消息 ***/
  289. getSupportFragmentManager().setFragmentResultListener("FMac0ToMainActivity", this, new FragmentResultListener() {
  290. @Override
  291. public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) {
  292. /*** 解析语音类型 ***/
  293. String strVoiceType = result.getString("SystemVoiceID");
  294. if(strVoiceType != null){
  295. VoicePlayingFlag = true;
  296. VoicePlayingID = Integer.parseInt(strVoiceType);
  297. }
  298. /*** 解析操作日志类型 ***/
  299. String strOptEvents = result.getString("OptEvents");
  300. if (strOptEvents != null) {
  301. Log.i(TAG_FMACX_MSG_TO_MAC, "FromFMac0->> OptEvents = " + strOptEvents);
  302. LogFileManagerOperate.VerifyLogFileConformsToJson();
  303. LogFileManagerOperate.CheckLogFileNumber();
  304. LogFileManagerOperate.AddOneLogItem(strOptEvents);
  305. }
  306. String strOptCommand = result.getString("OptCommand");
  307. if (strOptCommand != null) {
  308. /* 用户登录验证成功,跳转至‘工作状态’操作界面 */
  309. if (strOptCommand.equals("1")) {
  310. MacReplaceFragment(1);
  311. } else if(strOptCommand.equals("2")) {
  312. if (PLATFROM_TYPE_MAICHONG == USER_PLATFORM_TYPE) {
  313. MaiChongStartRawLauncher();
  314. } else {
  315. if (PLATFROM_TYPE_WANGFEI == USER_PLATFORM_TYPE) {
  316. RequestKioskMode(false); // 退出霸屏模式
  317. }
  318. finish();
  319. }
  320. }
  321. }
  322. }
  323. });
  324. /*** 监听及解析来自FragmentMac1的消息 ***/
  325. getSupportFragmentManager().setFragmentResultListener("FMac1ToMainActivity", this, new FragmentResultListener() {
  326. @Override
  327. public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) {
  328. String resString = result.getString("OptCommand");
  329. /* FMac1界面按钮操作解析 */
  330. if (resString != null) {
  331. MainSerialSendFragmentMac1OperateCommand(resString);
  332. }
  333. /*** 解析操作日志类型 ***/
  334. String strOptEvents = result.getString("OptEvents");
  335. if (strOptEvents != null) {
  336. Log.i(TAG_FMACX_MSG_TO_MAC,"FromFMac1->> OptEvents = " + strOptEvents);
  337. LogFileManagerOperate.VerifyLogFileConformsToJson();
  338. LogFileManagerOperate.CheckLogFileNumber();
  339. LogFileManagerOperate.AddOneLogItem(strOptEvents);
  340. }
  341. /*** 解析语音类型 ***/
  342. String strVoiceType = result.getString("SystemVoiceID");
  343. if(strVoiceType != null){
  344. VoicePlayingFlag = true;
  345. VoicePlayingID = Integer.parseInt(strVoiceType);
  346. }
  347. }
  348. });
  349. /*** 监听及解析来自FragmentMac2的消息 ***/
  350. getSupportFragmentManager().setFragmentResultListener("FMac2ToMainActivity", this, new FragmentResultListener() {
  351. @Override
  352. public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) {
  353. /*** 解析操作日志类型 ***/
  354. String strOptEvents = result.getString("OptEvents");
  355. if (strOptEvents != null) {
  356. Log.i(TAG_FMACX_MSG_TO_MAC,"FromFMac2->> OptEvents = " + strOptEvents);
  357. LogFileManagerOperate.VerifyLogFileConformsToJson();
  358. LogFileManagerOperate.CheckLogFileNumber();
  359. LogFileManagerOperate.AddOneLogItem(strOptEvents);
  360. }
  361. /*** 解析语音类型 ***/
  362. String strVoiceType = result.getString("SystemVoiceID");
  363. if (strVoiceType != null) {
  364. VoicePlayingFlag = true;
  365. VoicePlayingID = Integer.parseInt(strVoiceType);
  366. }
  367. }
  368. });
  369. /*** 监听及解析来自FragmentMac3的消息 ***/
  370. getSupportFragmentManager().setFragmentResultListener("FMac3ToMainActivity", this, new FragmentResultListener() {
  371. @Override
  372. public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) {
  373. /* 向MCU获取指定页面的操作记录信息 */
  374. String resString = result.getString("PageOperate");
  375. if (resString != null) {
  376. Log.i(TAG_FMACX_MSG_TO_MAC,"FMac3ToMac->> PageOperate = " + resString);
  377. JSONObject jsonMainObject = new JSONObject();
  378. JSONObject jsonSubObject = new JSONObject();
  379. try {
  380. jsonSubObject.put("ecode_pagenum",Integer.parseInt(resString));
  381. } catch (JSONException e) {
  382. throw new RuntimeException(e);
  383. }
  384. try {
  385. jsonMainObject.put("cmd","paramconf");
  386. // jsonSubObject.put("no_reply", "1");
  387. jsonMainObject.put("ext",jsonSubObject);
  388. } catch (JSONException e) {
  389. throw new RuntimeException(e);
  390. }
  391. if(!SerialManager.getInstance().getUpgradingFlag()){
  392. SerialManager.getInstance().write(jsonMainObject.toString().getBytes());//指令下发与升级冲突#2
  393. }
  394. }
  395. /* 向MCU获取操作记录页面和数据总数信息 */
  396. resString = result.getString("GetPageInfo");
  397. if (resString != null) {
  398. Log.i(TAG_FMACX_MSG_TO_MAC, "获取MCU端操作日志数据信息.");
  399. String Command = "{\"cmd\":\"ReadEcodeInfo\"}";
  400. if(!SerialManager.getInstance().getUpgradingFlag()){
  401. SerialManager.getInstance().write(Command.getBytes());//指令下发与升级冲突#3
  402. }
  403. }
  404. }
  405. });
  406. /*** 监听及解析来自FragmentMac5的消息 ***/
  407. getSupportFragmentManager().setFragmentResultListener("FMac5ToMainActivity", this, new FragmentResultListener() {
  408. @Override
  409. public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) {
  410. String resString = result.getString("FMac5Command");
  411. if (resString != null) {
  412. Log.i(TAG_FMACX_MSG_TO_MAC, "FMac5ToMac->> " + resString);
  413. MainSerialSendFragmentMac1OperateCommand(resString);
  414. }
  415. /*** 解析语音类型 ***/
  416. String strVoiceType = result.getString("SystemVoiceID");
  417. if(strVoiceType != null){
  418. VoicePlayingFlag = true;
  419. VoicePlayingID = Integer.parseInt(strVoiceType);
  420. }
  421. }
  422. });
  423. MacOneSecondTiggerRunnable = new Runnable() {
  424. @Override
  425. public void run() {
  426. /* 设备心跳 */
  427. MacDeviceDataToServerTime++;
  428. if(MacDeviceDataToServerTime > 30){
  429. MacDeviceDataToServerTime = 0;
  430. MacAppHeartbeatFlag = true;
  431. if (USER_PLATFORM_TYPE == PLATFROM_TYPE_WANGFEI) {
  432. WifRequestLocationInfo();
  433. }
  434. }
  435. /* 设备心跳 */
  436. CustomerMqttHeartbeatToServerTime++;
  437. if(CustomerMqttHeartbeatToServerTime > 30){
  438. CustomerMqttHeartbeatToServerTime = 0;
  439. CustomerMqttHeartbeatToServerFlag = true;
  440. }
  441. MacGetPhoneStateInfoTime++;
  442. if(MacGetPhoneStateInfoTime > 60){
  443. MacGetPhoneStateInfoTime = 0;
  444. MacGetPhoneStateInfoFlag = true;
  445. }
  446. if(UserGlobalVariable.Mqtt_M_ReConnect_Flag == 2){
  447. if(UserGlobalVariable.Mqtt_M_ReConnect_Time >= 30){
  448. UserGlobalVariable.Mqtt_M_ReConnect_Time = 0;
  449. UserGlobalVariable.Mqtt_M_ReConnect_Flag = 1;
  450. }else{
  451. UserGlobalVariable.Mqtt_M_ReConnect_Time ++;
  452. }
  453. }
  454. if(UserGlobalVariable.Customer_Mqtt_ReConnect_Flag == 2){
  455. if(UserGlobalVariable.Customer_Mqtt_ReConnect_Time >= 30){
  456. UserGlobalVariable.Customer_Mqtt_ReConnect_Time = 0;
  457. UserGlobalVariable.Customer_Mqtt_ReConnect_Flag = 1;
  458. }else{
  459. UserGlobalVariable.Customer_Mqtt_ReConnect_Time ++;
  460. }
  461. }
  462. UserGlobalVariable.Dev_Serial_Comm_Timeout_Val ++;
  463. if(UserGlobalVariable.Dev_Serial_Comm_Timeout_Val >= 60){
  464. UserGlobalVariable.Dev_Serial_Comm_Timeout_Val = 0;
  465. UserGlobalVariable.DevStuCode_Serial = 3;
  466. }
  467. MacOneSecondTriggerHandler.postDelayed(MacOneSecondTiggerRunnable,1000);
  468. }
  469. };
  470. MacOneSecondTriggerHandler.postDelayed(MacOneSecondTiggerRunnable,1000);
  471. }
  472. private void hideSystemUI() {
  473. View decor = getWindow().getDecorView();
  474. decor.setSystemUiVisibility(
  475. View.SYSTEM_UI_FLAG_LAYOUT_STABLE
  476. | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
  477. | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
  478. | View.SYSTEM_UI_FLAG_FULLSCREEN
  479. | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
  480. | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
  481. );
  482. }
  483. @Override
  484. public void onWindowFocusChanged(boolean hasFocus) {
  485. super.onWindowFocusChanged(hasFocus);
  486. if (hasFocus) {
  487. hideSystemUI();
  488. }
  489. }
  490. @Override
  491. protected void onResume() {
  492. super.onResume();
  493. hideSystemUI();
  494. }
  495. @Override
  496. public boolean dispatchTouchEvent(MotionEvent ev) {
  497. // Log.i("MacScreenSleepTime", "dispatchTouchEvent: MacScreenSleepTime Clear.");
  498. return super.dispatchTouchEvent(ev);
  499. }
  500. @Override
  501. public void MessageBetweenActivityAndFragment(String requestKey, String key, String value) {
  502. Bundle result = new Bundle();
  503. result.putString(key,value);
  504. getSupportFragmentManager().setFragmentResult(requestKey,result);
  505. // MainActivityMessageToFragment(requestKey,key,value);
  506. }
  507. private void MacSetSystemParameterSP(String key, String value) {
  508. // 获取编辑器并存储数据
  509. SharedPreferences.Editor editor = SystemParameterSettings.edit();
  510. editor.putString(key, value);
  511. editor.apply(); // 或者使用 editor.commit();
  512. }
  513. private void MacGetSystemParameterSP() {
  514. // 获取编辑器并存储数据
  515. String tempParameterName = SystemParameterSettings.getString(SYS_PARA_CLIENT_SERVER_INFO,"null");
  516. if(tempParameterName.equals("null")){
  517. Log.i(TAG_SYSTEM_PARAMETER_SP,"系统参数#01.1-> Mqtt客户端信息为空.");
  518. }else{
  519. Log.i(TAG_SYSTEM_PARAMETER_SP,"系统参数#01.1-> Mqtt客户端信息: " + tempParameterName);
  520. try {
  521. JSONObject jsonObject = new JSONObject(tempParameterName);
  522. UserGlobalVariable.setlValue("clientServer",jsonObject.getString("clientServer"));
  523. String tempEnable = jsonObject.getString("clientServer");
  524. if(tempEnable.equals("1")){
  525. Log.i(TAG_SYSTEM_PARAMETER_SP,"MAC#568-> 需要连接客户服务器.");
  526. Log.i(TAG_SYSTEM_PARAMETER_SP,"MAC#569-> 客户服务器信息: " + tempParameterName);
  527. if(jsonObject.getString("mqttEnable").equals("1")){
  528. UserGlobalVariable.Customer_Mqtt_Enable = true;
  529. UserGlobalVariable.setlValue("mqttIP",jsonObject.getString("mqttIP"));
  530. UserGlobalVariable.setlValue("mqttPort",jsonObject.getString("mqttPort"));
  531. UserGlobalVariable.setlValue("mqttUser",jsonObject.getString("mqttUser"));
  532. UserGlobalVariable.setlValue("mqttPasswd",jsonObject.getString("mqttPasswd"));
  533. UserGlobalVariable.setlValue("mqttSubTopic",jsonObject.getString("mqttSubTopic"));
  534. UserGlobalVariable.setlValue("mqttPubTopic",jsonObject.getString("mqttPubTopic"));
  535. }
  536. if(jsonObject.getString("ftpEnable").equals("1")){
  537. UserGlobalVariable.Customer_FTP_Enable = true;
  538. UserGlobalVariable.setlValue("ftpIP",jsonObject.getString("ftpIP"));
  539. UserGlobalVariable.setlValue("ftpPort",jsonObject.getString("ftpPort"));
  540. UserGlobalVariable.setlValue("ftpUser",jsonObject.getString("ftpUser"));
  541. UserGlobalVariable.setlValue("ftpPasswd",jsonObject.getString("ftpPasswd"));
  542. UserGlobalVariable.setlValue("ftpFilePath",jsonObject.getString("ftpFilePath"));
  543. }
  544. }
  545. } catch (JSONException e) {
  546. //// Log.i("updateUserGlobalVariable", "JSONException: Error,#03");
  547. }
  548. }
  549. // 获取编辑器并存储数据
  550. String tempTakePhotoWaitExposure = SystemParameterSettings.getString(SYS_PARA_CAMERA_TAKE_PHOTO_WAIT_EXPOSURE,"10");
  551. UserGlobalVariable.CameraTakePhotoWaitExposure = Integer.parseInt(tempTakePhotoWaitExposure);
  552. Log.i(TAG_SYSTEM_PARAMETER_SP,"系统参数#01.2-> 拍照等待曝光时间值: " + UserGlobalVariable.CameraTakePhotoWaitExposure);
  553. String tempLongitude = SystemParameterSettings.getString(SYS_PARA_GPS_LONGITUDE,"0");
  554. String tempLatitude = SystemParameterSettings.getString(SYS_PARA_GPS_LATITUDE,"0");
  555. UserGlobalVariable.setlValue("lng",tempLongitude);
  556. UserGlobalVariable.setlValue("lat",tempLatitude);
  557. Log.i(TAG_SYSTEM_PARAMETER_SP,"系统参数#01.3-> 历史定位: 经度 - " + tempLongitude + ", 纬度 - " + tempLatitude);
  558. }
  559. private void MaiChongPlatformSInit() {
  560. enjoySDK = new EnjoySDK(this);
  561. try {
  562. int res = enjoySDK.getSecurePasswdStatus();
  563. } catch (EnjoyApiNotSupportException e) {
  564. Log.i(TAG_PLATFORM_MAICHON, "getSecurePasswdStatus: Error");
  565. }
  566. try {
  567. int res = enjoySDK.setSecurePasswd("Abc12345","Abc12345");
  568. } catch (EnjoyApiNotSupportException e) {
  569. Log.i(TAG_PLATFORM_MAICHON, "registerSafeProgram: Error");
  570. }
  571. try {
  572. //注册当前应用为安全密码应用。
  573. int res = enjoySDK.registSafeProgram("Abc12345");
  574. } catch (EnjoyApiNotSupportException e) {
  575. Log.i(TAG_PLATFORM_MAICHON, "registerSafeProgram: Error");
  576. }
  577. try {
  578. //检查当前应用是否在安全应用列表中。
  579. boolean res = enjoySDK.checkSafeProgramOfSelf();
  580. if(res){
  581. Log.i(TAG_PLATFORM_MAICHON, "checkSafeProgramOfSelf: Register Successful.");
  582. }
  583. } catch (EnjoyApiNotSupportException e) {
  584. Log.i(TAG_PLATFORM_MAICHON, "checkSafeProgramOfSelf: Error");
  585. }
  586. try {
  587. int res= enjoySDK.setScreenBrightness(128);
  588. } catch (EnjoyApiNotSupportException e) {
  589. Log.i(TAG_PLATFORM_MAICHON, "setScreenBrightness: Error");
  590. }
  591. try {
  592. int res = enjoySDK.setTouchWake(true);
  593. Log.i(TAG_PLATFORM_MAICHON, "setTouchWake: Set Successful.");
  594. } catch (EnjoyApiNotSupportException e) {
  595. Log.i(TAG_PLATFORM_MAICHON, "setTouchWake: Set Failed.");
  596. }
  597. try {
  598. enjoySDK.EnableKeepAlive(true);
  599. Log.i(TAG_PLATFORM_MAICHON, "设置使能应用保活: 成功.");
  600. } catch (EnjoyApiNotSupportException e) {
  601. Log.i(TAG_PLATFORM_MAICHON, "设置使能应用保活: 失败.");
  602. }
  603. McKeepAliveApp mcKeepAliveApp = new McKeepAliveApp();
  604. mcKeepAliveApp.setPackagename("com.example.yunfeiapplication");
  605. mcKeepAliveApp.setInterval(30);
  606. mcKeepAliveApp.setPriority(1);
  607. Log.i(TAG_PLATFORM_MAICHON, "应用保活名称:" + mcKeepAliveApp.getPackagename());
  608. Log.i(TAG_PLATFORM_MAICHON, "应用保活间隔:" + String.valueOf(mcKeepAliveApp.getInterval()));
  609. }
  610. private void MaiChongStartRawLauncher(){
  611. enjoySDK = new EnjoySDK(this);
  612. try {
  613. enjoySDK.EnableKeepAlive(false);
  614. Log.i(TAG_PLATFORM_MAICHON, "设置取消应用保活: 成功.");
  615. } catch (EnjoyApiNotSupportException e) {
  616. Log.i(TAG_PLATFORM_MAICHON, "设置取消应用保活: 失败.");
  617. }
  618. try {
  619. enjoySDK.startRawLauncher();
  620. Log.i("TAG", " 启动默认界面成功.");
  621. } catch (EnjoyApiNotSupportException e) {
  622. Log.i("TAG", " 启动默认界面失败.");
  623. throw new RuntimeException(e);
  624. }
  625. }
  626. private void MaiChongPlatformSleep() {
  627. enjoySDK = new EnjoySDK(this);
  628. try {
  629. int res = enjoySDK.getSecurePasswdStatus();
  630. } catch (EnjoyApiNotSupportException e) {
  631. Log.i(TAG_PLATFORM_MAICHON, "getSecurePasswdStatus: Error");
  632. }
  633. try {
  634. int res = enjoySDK.setSecurePasswd("Abc12345","Abc12345");
  635. } catch (EnjoyApiNotSupportException e) {
  636. Log.i(TAG_PLATFORM_MAICHON, "registerSafeProgram: Error");
  637. }
  638. try {
  639. int res = enjoySDK.goToSleep();
  640. Log.i(TAG_PLATFORM_MAICHON, "goToSleep: Successful");
  641. } catch (EnjoyApiNotSupportException e) {
  642. //throw new RuntimeException(e);
  643. Log.i(TAG_PLATFORM_MAICHON, "goToSleep: Error");
  644. }
  645. }
  646. // AIDL 连接
  647. public class BaseServiceConnection implements ServiceConnection {
  648. @Override
  649. public void onServiceConnected(ComponentName name, IBinder service) {
  650. Log.i("onServiceConnected", "onServiceConnected: Successful");
  651. serviceInterface = IBaseServiceInterface.Stub.asInterface(service);
  652. BaseServiceConnectionFlag = true;
  653. MacHideSystemUI();
  654. RequestKioskMode(true); // 进入霸屏模式
  655. }
  656. @Override
  657. public void onServiceDisconnected(ComponentName name) {
  658. }
  659. }
  660. // AIDL 请求回调
  661. public class AidlCallback extends IBaseServiceCallback.Stub {
  662. @Override
  663. public void onResponse(String json) throws RemoteException {
  664. Log.d(TAG_PLATFORM_WANGFEI, "onResponse------" + json);
  665. BaseResponse baseResponse = FastJsonUtils.fromJson(json, BaseResponse.class);
  666. if (baseResponse == null || baseResponse.getType() == null) {
  667. return;
  668. }
  669. switch (baseResponse.getType()) {
  670. /*case AidlConstants.TYPE_LOCATION:
  671. AidlResponse<LocationInfo> aidlResponse = FastJsonUtils.fromJson(json,new TypeReference<AidlResponse<LocationInfo>>(LocationInfo.class){});
  672. LocationInfo locationInfo = aidlResponse.data;
  673. if (locationInfo != null) {
  674. Log.i("TAG", "lng: " + locationInfo.longitude + " lat: " + locationInfo.latitude);
  675. MacSetSystemParameterSP(SYS_PARA_GPS_LONGITUDE,String.valueOf(locationInfo.longitude));
  676. MacSetSystemParameterSP(SYS_PARA_GPS_LATITUDE,String.valueOf(locationInfo.latitude));
  677. }
  678. break;*/
  679. case AidlConstants.TYPE_KIOSK_MODE:
  680. case AidlConstants.TYPE_INSTALL:
  681. Log.i("TAG", "onResponse: " + json);
  682. break;
  683. }
  684. }
  685. }
  686. private void WifRequestLocationInfo() {
  687. BaseRequest request = new BaseRequest();
  688. request.setType(AidlConstants.TYPE_LOCATION);
  689. try {
  690. serviceInterface.request(FastJsonUtils.toJson(request), AidlCallback);
  691. } catch (RemoteException e) {
  692. throw new RuntimeException(e);
  693. }
  694. }
  695. /* 网飞屏霸屏模式 */
  696. private void RequestKioskMode(boolean enable) {
  697. AidlRequest<Boolean> request = new AidlRequest<>();
  698. request.setType(AidlConstants.TYPE_KIOSK_MODE);
  699. request.setParam(enable);
  700. try {
  701. serviceInterface.request(
  702. FastJsonUtils.toJson(request),
  703. AidlCallback
  704. );
  705. } catch (RemoteException e) {
  706. e.printStackTrace();
  707. }
  708. }
  709. /* 隐藏底部导航栏 */
  710. private void MacHideSystemUI() {
  711. View decorView = getWindow().getDecorView();
  712. decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN);
  713. }
  714. /******************************************** 语音播报功能 ********************************************/
  715. void MainActivityVoiceMediaPlayer(int voiceID) {
  716. if(VoicePlayingFlag){
  717. int playId = 0;
  718. if (voiceID == 0) {
  719. playId = R.raw.loginsuccessful; /*登录成功*/
  720. } else if(voiceID == 1) {
  721. playId = R.raw.loginfailure; /*密码错误*/
  722. } else if(voiceID == 2) {
  723. playId = R.raw.networkconnected; /*网络连接成功*/
  724. } else if(voiceID == 3) {
  725. playId = R.raw.networkdisconnected; /*网络断开连接*/
  726. } else if(voiceID == 4) {
  727. playId = R.raw.cameratakingpictures; /*开始拍照*/
  728. } else if(voiceID == 5) {
  729. playId = R.raw.camerauploadpictures; /*上传图片*/
  730. } else if(voiceID == 6) {
  731. playId = R.raw.camerauploadsuccessful; /*图片上传成功*/
  732. } else if(voiceID == 7) {
  733. playId = R.raw.camerauploadfailure; /*图片上传失败*/
  734. } else if(voiceID == 8) {
  735. playId = R.raw.camerabusy; /*相机忙,本次自动拍照取消*/
  736. } else if(voiceID == 9) {
  737. playId = R.raw.cameraautotakingphoto; /*正在执行自动拍照,操作无效*/
  738. } else if(voiceID == 10) {
  739. playId = R.raw.settingsuccessful; /*正在执行自动拍照,操作无效*/
  740. } else if(voiceID == 11) {
  741. playId = R.raw.settingfailed; /*正在执行自动拍照,操作无效*/
  742. }
  743. Log.i("TAG", "MainActivityVoiceMediaPlayer: 语音播放." + voiceID);
  744. MacAudioPlayer.playSound(playId);
  745. VoicePlayingFlag = false;
  746. }
  747. }
  748. /******************************************** 侧边栏功能 ********************************************/
  749. /*** 界面切换 ***/
  750. public void SwitchToFragment(int index){
  751. MacReplaceFragment(index);
  752. }
  753. private void MacReplaceFragment(int index) {
  754. if (index < 1 || index > 7 || index == OldFragmentIndex) {
  755. Log.i("MacReplaceFragment", "当前界面即目标界面,无需跳转。");
  756. return;
  757. }
  758. if (1 == index) {
  759. getSupportFragmentManager().beginTransaction().replace(R.id.mainFragmentContainerView, FragmentMac1.class,null).commit();
  760. } else if (2 == index) {
  761. /*** @CameraMark01其他界面跳转至“相机操作”界面时,如果主线程正在执行自动拍照,等主线程完成拍照上传后再跳转至拍照界面 ***/
  762. // if (!MacTakePhotoBusyFlag) {
  763. getSupportFragmentManager().beginTransaction().replace(R.id.mainFragmentContainerView, FragmentMac2.class,null).commit();
  764. // } else {
  765. // Toast.makeText(getApplicationContext(),"相机正在拍摄上传",Toast.LENGTH_SHORT).show();
  766. // }
  767. } else if(3 == index) {
  768. getSupportFragmentManager().beginTransaction().replace(R.id.mainFragmentContainerView, FragmentMac3.class,null).commit();
  769. } else if(4 == index) {
  770. getSupportFragmentManager().beginTransaction().replace(R.id.mainFragmentContainerView, FragmentMac4.class,null).commit();
  771. } else if(5 == index) {
  772. getSupportFragmentManager().beginTransaction().replace(R.id.mainFragmentContainerView, FragmentMac5.class,null).commit();
  773. } else if(6 == index) {
  774. UserGlobalVariable.setlValue("login","0");
  775. index = 0;
  776. getSupportFragmentManager().beginTransaction().replace(R.id.mainFragmentContainerView, FragmentMac0.class,null).commit();
  777. }
  778. /*** 等主线程完成拍照上传后再跳转至拍照界面,不更新界面标识。(发生 '@CameraMark01' 时此次操作无效。) ***/
  779. // if (!MacTakePhotoBusyFlag) {
  780. OldFragmentIndex = index;
  781. // }
  782. }
  783. /******************************************** GPS功能部分 ********************************************/
  784. private void MacStartLocationUpdates() {
  785. locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  786. if (locationManager == null) {
  787. Log.e("GPS Location", "LocationManager is null");
  788. return;
  789. }
  790. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  791. Log.e("GPS Location", "No GPS permission");
  792. return;
  793. }
  794. String provider = LocationManager.GPS_PROVIDER;
  795. if (!locationManager.isProviderEnabled(provider)) {
  796. Log.e("GPS Location", "GPS provider disabled");
  797. return;
  798. }
  799. Location lastLocation = locationManager.getLastKnownLocation(provider);
  800. if (lastLocation != null) {
  801. Log.d("GPS Location", "Got last location");
  802. handleLocation(lastLocation);
  803. //return;
  804. }
  805. Log.d("GPS Location", "Start GPS locating");
  806. locationListener = new LocationListener() {
  807. @Override
  808. public void onLocationChanged(Location location) {
  809. if (location == null) {
  810. Log.e("GPS Location", "location null");
  811. return;
  812. }
  813. Log.d("GPS Location", "location:" + location.getLatitude() + "," + location.getLongitude());
  814. handleLocation(location);
  815. locationManager.removeUpdates(this);
  816. }
  817. @Override
  818. public void onProviderEnabled(String provider) {
  819. Log.d("GPS Location", "enabled:" + provider);
  820. }
  821. @Override
  822. public void onProviderDisabled(String provider) {
  823. Log.d("GPS Location", "disabled:" + provider);
  824. }
  825. @Override
  826. public void onStatusChanged(String provider, int status, Bundle extras) {
  827. }
  828. };
  829. try {
  830. locationManager.requestLocationUpdates(
  831. LocationManager.GPS_PROVIDER,
  832. 1000, 0,
  833. locationListener,
  834. Looper.getMainLooper()
  835. );
  836. } catch (SecurityException e) {
  837. e.printStackTrace();
  838. } catch (IllegalArgumentException e) {
  839. e.printStackTrace();
  840. }
  841. }
  842. private void handleLocation(Location location) {
  843. double latitude = location.getLatitude();
  844. double longitude = location.getLongitude();
  845. Log.d("GPS Location", "+++ Latitude: " + latitude + ", Longitude: " + longitude);
  846. if(!UserGlobalVariable.GPS_LocationRefresh){
  847. UserGlobalVariable.GPS_LocationRefresh = true;
  848. MacSetSystemParameterSP(SYS_PARA_GPS_LONGITUDE,String.valueOf(longitude));
  849. MacSetSystemParameterSP(SYS_PARA_GPS_LATITUDE,String.valueOf(latitude));
  850. UserGlobalVariable.setlValue("lng", String.valueOf(longitude));
  851. UserGlobalVariable.setlValue("lat", String.valueOf(latitude));
  852. }
  853. }
  854. // 检测移动数据是否开启
  855. public static boolean isMobileDataEnabled(Context context) {
  856. ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  857. try {
  858. // 通过反射获取移动数据状态(兼容旧版本)
  859. Class<?> connectivityManagerClass = Class.forName(ConnectivityManager.class.getName());
  860. java.lang.reflect.Method getMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("getMobileDataEnabled");
  861. getMobileDataEnabledMethod.setAccessible(true);
  862. return (boolean) getMobileDataEnabledMethod.invoke(cm);
  863. } catch (Exception e) {
  864. e.printStackTrace();
  865. // 如果反射失败,尝试通过其他方式(如检查网络类型)
  866. return false;
  867. }
  868. }
  869. public static boolean setMobileDataEnabledByRoot(boolean enable) {
  870. Process process = null;
  871. DataOutputStream os = null;
  872. try {
  873. // 获取 root 权限
  874. process = Runtime.getRuntime().exec("su");
  875. os = new DataOutputStream(process.getOutputStream());
  876. // Android 4.0-4.3 使用的旧方法
  877. // os.writeBytes("service call phone 115 i32 " + (enable ? "1" : "0") + "\n");
  878. // Android 4.4+ 使用的新方法
  879. os.writeBytes("svc data " + (enable ? "enable" : "disable") + "\n");
  880. // 修改系统设置(双保险)
  881. os.writeBytes("settings put global mobile_data " + (enable ? "1" : "0") + "\n");
  882. // 刷新网络设置
  883. os.writeBytes("am broadcast -a android.intent.action.ANY_DATA_STATE --ez state " + enable + "\n");
  884. os.writeBytes("exit\n");
  885. os.flush();
  886. // 等待命令执行完成
  887. int exitCode = process.waitFor();
  888. return exitCode == 0;
  889. } catch (Exception e) {
  890. Log.e("TAG", "Root command failed", e);
  891. return false;
  892. } finally {
  893. try {
  894. if (os != null) os.close();
  895. if (process != null) process.destroy();
  896. } catch (Exception e) {
  897. Log.e("TAG", "Close stream error", e);
  898. }
  899. }
  900. }
  901. /*** FragmentMac1界面控件操作时对应的串口指令下发 ***/
  902. public void MainSerialSendFragmentMac1OperateCommand(String string) {
  903. JSONObject jsonObjectEXT = new JSONObject();
  904. JSONObject jsonMainObject = new JSONObject();
  905. String commandString = "";
  906. /*获取全局变量*/
  907. UserGlobalVariable fragmentGlobalVariable = UserGlobalVariable.getInstance();
  908. Map <String,String> fragmentMap = fragmentGlobalVariable.infoMap;
  909. String jsonString = fragmentMap.get("JsonMainObject");
  910. JSONObject jsonObject = null;
  911. try {
  912. jsonObject = new JSONObject(jsonString);
  913. String logString = "";
  914. switch (string) {
  915. case "0": // Added by NiuJiuRu @2025-05-20
  916. logString = "执行一键恢复所有参数到默认出厂设置";
  917. break;
  918. case "1":
  919. jsonObjectEXT.put("ts", jsonObject.getJSONObject("ext").get("ts"));
  920. if (jsonObject.getJSONObject("ext").get("ts").toString().equals("0")) {
  921. logString = "切换为时控模式";
  922. Log.i("TempTAG040801", "TAG#02.0->> 串口下发指令切换为时控模式.");
  923. } else {
  924. logString = "切换为光控模式";
  925. Log.i("TempTAG040801", "TAG#02.1->> 串口下发指令切换为光控模式.");
  926. }
  927. break;
  928. case "2":
  929. jsonObjectEXT.put("tps", jsonObject.getJSONObject("ext").get("tps"));
  930. if(jsonObject.getJSONObject("ext").get("tps").toString().equals("0")){
  931. logString = "温控保护关闭";
  932. }else{
  933. logString = "温控保护开启";
  934. }
  935. break;
  936. case "3":
  937. jsonObjectEXT.put("rps", jsonObject.getJSONObject("ext").get("rps"));
  938. logString = "切换为晨曦模式";
  939. break;
  940. case "4":
  941. jsonObjectEXT.put("tt", jsonObject.getJSONObject("ext").get("tt"));
  942. logString = "设置光控工作时长: " + jsonObject.getJSONObject("ext").get("tt").toString();
  943. break;
  944. case "5":
  945. jsonObjectEXT.put("collstart", jsonObject.getJSONObject("ext").get("collstart"));
  946. jsonObjectEXT.put("collend", jsonObject.getJSONObject("ext").get("collend"));
  947. logString = "设置时控定时: " + jsonObject.getJSONObject("ext").get("collstart") + "|" +jsonObject.getJSONObject("ext").get("collend") + " (开始|结束时刻)";
  948. break;
  949. case "6":
  950. jsonObjectEXT.put("tpl", jsonObject.getJSONObject("ext").get("tpl"));
  951. jsonObjectEXT.put("tph", jsonObject.getJSONObject("ext").get("tph"));
  952. logString = "设置温控阈值: " + jsonObject.getJSONObject("ext").get("tpl") + "|" + jsonObject.getJSONObject("ext").get("tph") + " (下限|上限)";
  953. break;
  954. case "7":
  955. jsonObjectEXT.put("dat_f", jsonObject.getJSONObject("ext").get("dat_f"));
  956. logString = "设置数据上传间隔: " + jsonObject.getJSONObject("ext").get("dat_f") + " 分";
  957. break;
  958. case "8":
  959. jsonObjectEXT.put("pho_f", jsonObject.getJSONObject("ext").get("pho_f"));
  960. logString = "设置图片上传间隔: " + jsonObject.getJSONObject("ext").get("pho_f") + " 分";
  961. break;
  962. case "9":
  963. jsonObjectEXT.put("Demo_mode", jsonObject.getJSONObject("ext").get("Demo_mode"));
  964. logString = "演示模式状态: " + jsonObject.getJSONObject("ext").get("Demo_mode");
  965. break;
  966. case "51":
  967. commandString = "systest autotest touch";
  968. logString = "测试操作: 一键测试";
  969. break;
  970. case "52":
  971. commandString = "systest Traplamp touch";
  972. logString = "测试操作: 诱捕灯";
  973. break;
  974. case "53":
  975. commandString = "systest collect touch";
  976. logString = "测试操作: 采集风机";
  977. break;
  978. case "54":
  979. commandString = "systest Trap_Down touch";
  980. logString = "测试操作: 下诱捕灯";
  981. break;
  982. case "55":
  983. commandString = "systest switchled touch";
  984. logString = "测试操作: 补光设置";
  985. break;
  986. case "56":
  987. commandString = "systest fb_test touch";
  988. logString = "测试操作: 翻版测试";
  989. break;
  990. }
  991. int commandType = Integer.parseInt(string);
  992. if (commandType == 0) { // Added by NiuJiuRu @2025-05-20
  993. String resetCmd = "{\"cmd\": \"ctrl\", \"ext\": {\"RC\": \"Force_Reset\"}}";
  994. Log.i("TAG", "serialSend: " + resetCmd);
  995. if (!SerialManager.getInstance().getUpgradingFlag()) {
  996. SerialManager.getInstance().write(resetCmd.getBytes());
  997. }
  998. }
  999. else if (commandType >= 1 && commandType <= 50) {
  1000. jsonMainObject.put("cmd","paramconf");
  1001. // jsonObjectEXT.put("no_reply", "1");
  1002. jsonMainObject.put("ext",jsonObjectEXT);
  1003. Log.i("TAG", "serialSend: " + jsonMainObject.toString());
  1004. if(!SerialManager.getInstance().getUpgradingFlag()){
  1005. SerialManager.getInstance().write(jsonMainObject.toString().getBytes());//串口下发界面操作指令(升级冲突#3)
  1006. }
  1007. } else if (commandType >= 51 && commandType <= 80) {
  1008. if(!SerialManager.getInstance().getUpgradingFlag()){
  1009. SerialManager.getInstance().write(commandString.getBytes());;//串口下发界面操作指令(升级冲突#3)
  1010. }
  1011. }
  1012. Log.i(TAG_FMACX_MSG_TO_MAC,"FromMac->> OptEvents = " + commandType);
  1013. LogFileManagerOperate.VerifyLogFileConformsToJson();
  1014. LogFileManagerOperate.CheckLogFileNumber();
  1015. LogFileManagerOperate.AddOneLogItem(logString);
  1016. } catch (JSONException e) {
  1017. Log.i("jsonObjectCreate", "JSONException Error,#01");
  1018. }
  1019. }
  1020. /******************************************** Mqtt部分功能 ********************************************/
  1021. private void MacAppHeartbeatToServer() {
  1022. JSONObject jsonObjectEXT = new JSONObject();
  1023. try {
  1024. jsonObjectEXT.put("version",UserGlobalVariable.ANDROID_APP_VERSION);
  1025. if(HeartBeatFirstReportFlag){
  1026. HeartBeatFirstReportFlag = false;
  1027. jsonObjectEXT.put("first","1");
  1028. }else{
  1029. jsonObjectEXT.put("first","0");
  1030. }
  1031. jsonObjectEXT.put("imei",UserGlobalVariable.getValue("imei"));
  1032. jsonObjectEXT.put("iccid",UserGlobalVariable.getValue("iccid"));
  1033. jsonObjectEXT.put("csq",UserGlobalVariable.getValue("csq"));
  1034. jsonObjectEXT.put("lat",UserGlobalVariable.getValue("lat"));
  1035. jsonObjectEXT.put("lng",UserGlobalVariable.getValue("lng"));
  1036. jsonObjectEXT.put("mcuComm",UserGlobalVariable.DevStuCode_Serial);
  1037. JSONObject jsonObjectMain = new JSONObject();
  1038. try {
  1039. jsonObjectMain.put("cmd","app");
  1040. jsonObjectMain.put("ext",jsonObjectEXT);
  1041. // mqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),jsonObjectMain.toString(),0,false,10000);
  1042. userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),jsonObjectMain.toString(),0);
  1043. } catch (JSONException e) {
  1044. throw new RuntimeException(e);
  1045. }
  1046. } catch (JSONException e) {
  1047. throw new RuntimeException(e);
  1048. }
  1049. }
  1050. private void MacAppCustomerMqttHeartbeatToServer() {
  1051. JSONObject jsonObjectEXT = new JSONObject();
  1052. try {
  1053. jsonObjectEXT.put("version",UserGlobalVariable.ANDROID_APP_VERSION);
  1054. jsonObjectEXT.put("imei",UserGlobalVariable.getValue("imei"));
  1055. jsonObjectEXT.put("iccid",UserGlobalVariable.getValue("iccid"));
  1056. jsonObjectEXT.put("csq",UserGlobalVariable.getValue("csq"));
  1057. jsonObjectEXT.put("lat",UserGlobalVariable.getValue("lat"));
  1058. jsonObjectEXT.put("lng",UserGlobalVariable.getValue("lng"));
  1059. jsonObjectEXT.put("mcuComm",UserGlobalVariable.DevStuCode_Serial);
  1060. JSONObject jsonObjectMain = new JSONObject();
  1061. try {
  1062. jsonObjectMain.put("cmd","app");
  1063. jsonObjectMain.put("ext",jsonObjectEXT);
  1064. customerMqttManager.publish(UserGlobalVariable.getValue("mqttPubTopic") + UserGlobalVariable.getValue("imei"),jsonObjectMain.toString(),0);
  1065. } catch (JSONException e) {
  1066. throw new RuntimeException(e);
  1067. }
  1068. } catch (JSONException e) {
  1069. throw new RuntimeException(e);
  1070. }
  1071. }
  1072. /******************************************** 操作日志部分功能 ********************************************/
  1073. public class LogFileManager {
  1074. private static final int MaxNumber = 100;
  1075. private static final String LogFilePath = "log.txt";
  1076. private int logTips;
  1077. public void CatLogFileEachLine() {
  1078. File logFile = new File(getFilesDir(),"log.txt");
  1079. if (!logFile.exists() || !logFile.isFile()) {
  1080. return;
  1081. }
  1082. try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) {
  1083. String line;
  1084. while ((line = reader.readLine()) != null) {
  1085. //Log.d(TAG_LOG_MANAGER, line);
  1086. }
  1087. } catch (IOException e) {
  1088. Log.i(TAG_LOG_MANAGER, "IOException: Error.#01");
  1089. }
  1090. }
  1091. public void CheckLogFileNumber() {
  1092. File logFile = new File(getFilesDir(),"log.txt");
  1093. if (!logFile.exists() || !logFile.isFile()) {
  1094. return;
  1095. }
  1096. List<String> lines = new ArrayList<>();
  1097. try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) {
  1098. String line;
  1099. while ((line = reader.readLine()) != null) {
  1100. lines.add(line);
  1101. }
  1102. } catch (IOException e) {
  1103. //e.printStackTrace();
  1104. Log.i(TAG_LOG_MANAGER, "IOException: Error.#02");
  1105. }
  1106. if (lines.size() > MaxNumber) {
  1107. lines = lines.subList(lines.size() - MaxNumber, lines.size());
  1108. }
  1109. try (BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, false))) {
  1110. for (String line : lines) {
  1111. writer.write(line);
  1112. writer.newLine();
  1113. }
  1114. } catch (IOException e) {
  1115. //e.printStackTrace();
  1116. Log.i(TAG_LOG_MANAGER,"IOException: Error.#03");
  1117. }
  1118. }
  1119. public void VerifyLogFileConformsToJson() {
  1120. File logFile = new File(getFilesDir(),"log.txt");
  1121. if (!logFile.exists() || !logFile.isFile()) {
  1122. return;
  1123. }
  1124. List <String> validLines = new ArrayList <> ();
  1125. try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) {
  1126. String line;
  1127. while ((line = reader.readLine()) != null) {
  1128. try {
  1129. new JSONObject(line); // 尝试解析为JSON对象
  1130. validLines.add(line);
  1131. } catch (JSONException e) {
  1132. // 格式不正确,忽略此行
  1133. }
  1134. }
  1135. } catch (IOException e) {
  1136. //throw new RuntimeException(e);
  1137. Log.i(TAG_LOG_MANAGER,"IOException: Error.#04");
  1138. }
  1139. // 写回有效行到原文件
  1140. try (BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, false))) { // false 表示不追加,而是覆盖写
  1141. for (String validLine : validLines) {
  1142. writer.write(validLine);
  1143. writer.newLine();
  1144. }
  1145. } catch (IOException e) {
  1146. Log.i(TAG_LOG_MANAGER,"IOException: Error.#05");
  1147. }
  1148. }
  1149. public void JsonStringToLogFile(String jsonData) {
  1150. File logFile = new File(getFilesDir(),"log.txt");
  1151. // 使用FileOutputStream以追加模式写入文件
  1152. try (FileOutputStream fos = new FileOutputStream(logFile, true)) {
  1153. fos.write(jsonData.getBytes());
  1154. fos.write(System.lineSeparator().getBytes()); // 添加换行符以分隔不同的JSON记录
  1155. } catch (IOException e) {
  1156. //e.printStackTrace();
  1157. Log.i(TAG_LOG_MANAGER,"IOException: Error.#06");
  1158. }
  1159. }
  1160. public void AddOneLogItem(String event) {
  1161. JSONObject jsonObject = new JSONObject();
  1162. try {
  1163. Date currentDate = new Date();
  1164. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
  1165. String dateStr = dateFormat.format(currentDate);
  1166. jsonObject.put("Date", dateStr);
  1167. jsonObject.put("Event", event);
  1168. String jsonDataStr = jsonObject.toString();
  1169. Log.i(TAG_LOG_MANAGER,"LogItem: " + jsonDataStr);
  1170. JsonStringToLogFile(jsonDataStr);
  1171. } catch (Exception e) {
  1172. //e.printStackTrace();
  1173. Log.i(TAG_LOG_MANAGER,"Exception: Error.#07");
  1174. }
  1175. }
  1176. }
  1177. /******************************************** 相机平台预设部分功能 ********************************************/
  1178. public void MacSystemExecuteShellCommand() {
  1179. Log.i(TAG_CAMERA_OPERATE, "TakePhoto#00->> Shell端执行摄像头初始化配置.");
  1180. try {
  1181. Process process = Runtime.getRuntime().exec("su");
  1182. DataOutputStream os = new DataOutputStream(process.getOutputStream());
  1183. os.writeBytes("chmod -R 777 /dev/bus/usb\n");
  1184. os.writeBytes("echo 2000 > /sys/module/usbcore/parameters/usbfs_memory_mb\n");
  1185. os.writeBytes("cat /sys/module/usbcore/parameters/usbfs_memory_mb\n");
  1186. os.writeBytes("exit\n");
  1187. os.flush();
  1188. } catch (IOException e) {
  1189. e.printStackTrace();
  1190. }
  1191. }
  1192. public void MacSystemExecuteShellCommand2() {
  1193. Log.i(TAG_CAMERA_OPERATE, "TakePhoto#00->> Shell端执行摄像头初始化配置.");
  1194. try {
  1195. Process process = Runtime.getRuntime().exec("su");
  1196. DataOutputStream os = new DataOutputStream(process.getOutputStream());
  1197. os.writeBytes("monkey -p com.hzmct.enjoyConfig 1");
  1198. os.flush();
  1199. } catch (IOException e) {
  1200. e.printStackTrace();
  1201. }
  1202. }
  1203. /******************************************** 定时拍照上传部分功能 ********************************************/
  1204. private void MacCleanInvalidImages() {
  1205. // 获取应用的私有目录下的photos文件夹
  1206. File photosDir = new File(getFilesDir(), "photos");
  1207. // 如果目录不存在或不是一个文件夹,则直接返回
  1208. if (!photosDir.exists() || !photosDir.isDirectory()) {
  1209. return;
  1210. }
  1211. // 获取并删除不符合格式的文件
  1212. File[] files = photosDir.listFiles();
  1213. if (files != null) {
  1214. for (File file : files) {
  1215. // 检查文件名是否不符合.jpeg格式(不区分大小写)
  1216. if (!isValidJpegFileName(file.getName())) {
  1217. // 删除文件
  1218. if (file.delete()) {
  1219. Log.i(TAG_CAMERA_OPERATE,"A-TakePhoto#03.1->> 照片 < " + file.getName() + " > 格式不符合规范.删除成功.");
  1220. } else {
  1221. Log.i(TAG_CAMERA_OPERATE,"A-TakePhoto#03.2->> 照片 < " + file.getName() + " > 格式不符合规范.删除失败.");
  1222. }
  1223. }
  1224. }
  1225. }
  1226. }
  1227. // 检查文件名是否以.jpg结尾(不区分大小写),并且确保它是唯一的扩展名
  1228. private static boolean isValidJpegFileName(String fileName) {
  1229. String lowerCaseFileName = fileName.toLowerCase();
  1230. int dotIndex = lowerCaseFileName.indexOf('.');
  1231. // 如果没有点,则不是有效的.jpeg文件
  1232. if (dotIndex == -1) {
  1233. return false;
  1234. }
  1235. // 获取扩展名
  1236. String extension = lowerCaseFileName.substring(dotIndex + 1);
  1237. return "jpg".equals(extension);
  1238. }
  1239. private void MacSaveBitmapToPhotosDir(Bitmap bitmap,String fileName) {
  1240. // 获取应用的私有目录
  1241. //File photosDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "photos");
  1242. File photosDir = new File(getFilesDir(), "photos");
  1243. if(!photosDir.exists()) {
  1244. if(!photosDir.mkdir()) {
  1245. Log.i(TAG_CAMERA_OPERATE,"A-TakePhoto#04.1->> 私有目录下'photos'文件夹创建失败.");
  1246. }
  1247. }
  1248. File[] files = photosDir.listFiles();
  1249. if(files.length > 100){
  1250. Log.i(TAG_CAMERA_OPERATE,"A-TakePhoto#04.1.1->> 缓存图片数量超过100张.");
  1251. return;
  1252. }
  1253. // 创建目标文件
  1254. File file = new File(photosDir, fileName);
  1255. // 尝试将 Bitmap 写入文件
  1256. try (FileOutputStream out = new FileOutputStream(file)) {
  1257. // 压缩 Bitmap 为 JPEG 格式并写入文件
  1258. bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out); // 100 表示最高质量
  1259. Log.i(TAG_CAMERA_OPERATE,"A-TakePhoto#04.2->> 图片成功保存至'photos'文件夹.");
  1260. } catch (IOException e) {
  1261. Log.i(TAG_CAMERA_OPERATE,"A-TakePhoto#04.3->> 图片保存至'photos'文件夹失败.");
  1262. }
  1263. }
  1264. private void AutoTakePhotoAndUploadThread(){
  1265. new Thread(new Runnable() {
  1266. boolean threadExitStatus = true;
  1267. boolean threadRunStatus = true;
  1268. boolean openCameraOperate = false;
  1269. boolean cameraGrabbing = false;
  1270. int takePhotoDelay = 0;
  1271. MvccCameraManager mvccCameraManager = MvccCameraManager.getInstance();
  1272. @Override
  1273. public void run() {
  1274. while (threadRunStatus) {
  1275. if(!threadExitStatus){
  1276. return;
  1277. }
  1278. if (!openCameraOperate) {
  1279. openCameraOperate = true;
  1280. Log.i(TAG_CAMERA_OPERATE, "TakePhoto#01.0->> 尝试打开相机.");
  1281. if(mvccCameraManager.openCameraDevice(true)){
  1282. Log.i(TAG_CAMERA_OPERATE, "TakePhoto#01.1->> 相机打开成功.");
  1283. if (mvccCameraManager.toggleGrabbing(true)) {
  1284. Log.i(TAG_CAMERA_OPERATE, "TakePhoto#01.2->> 视频流开启成功.");
  1285. cameraGrabbing = true;
  1286. } else {
  1287. threadExitStatus = false;
  1288. }
  1289. }else{
  1290. Log.i(TAG_CAMERA_OPERATE, "TakePhoto#01.3->> 相机打开失败.本次拍照任务取消.");
  1291. threadExitStatus = false;
  1292. }
  1293. }
  1294. if (cameraGrabbing) {
  1295. takePhotoDelay++;
  1296. Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.4->> 拍照延时: " + takePhotoDelay);
  1297. if(takePhotoDelay >= UserGlobalVariable.CameraTakePhotoWaitExposure){
  1298. Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.5->> 开始截取视频流生成图片.");
  1299. Bitmap MacBitmapToServer = mvccCameraManager.getCameraBitmap();
  1300. if(MacBitmapToServer != null){
  1301. Calendar calendar = Calendar.getInstance();
  1302. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
  1303. String formattedDate = sdf.format(calendar.getTime());
  1304. String deviceIMEI = UserGlobalVariable.getValue("imei");
  1305. //公司服务器路径
  1306. String remoteFilesPathServerM = "/" + deviceIMEI + "/";
  1307. String remoteFilesPathServerC = "/" + deviceIMEI + "/";
  1308. //上传至服务器的文件名
  1309. String pictureNameToServer = deviceIMEI + "-" + formattedDate + ".jpg";
  1310. //存储在设备中的文件名
  1311. String pictureNameToDevStorage = formattedDate + ".jpg";
  1312. Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.6->> " + "开始上传图片");
  1313. boolean uploadToServerResultM = false;
  1314. boolean uploadToServerResultC = false;
  1315. Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.7.1->> 公司服务器路径: " + remoteFilesPathServerM);
  1316. Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.7.2->> 公司服务器图片: " + pictureNameToServer);
  1317. if(UserGlobalVariable.Customer_FTP_Enable){
  1318. String ftpIP = UserGlobalVariable.getValue("ftpIP");
  1319. String ftpPort = UserGlobalVariable.getValue("ftpPort");
  1320. String ftpUser = UserGlobalVariable.getValue("ftpUser");
  1321. String ftpPasswd = UserGlobalVariable.getValue("ftpPasswd");
  1322. String ftpFilePath = UserGlobalVariable.getValue("ftpFilePath") + UserGlobalVariable.getValue("imei") + "/";
  1323. Log.i(TAG_CAMERA_OPERATE, "Mac#1442->> 客户服务器信息-IP : " + ftpIP);
  1324. Log.i(TAG_CAMERA_OPERATE, "Mac#1442->> 客户服务器信息-Port : " + ftpPort);
  1325. Log.i(TAG_CAMERA_OPERATE, "Mac#1442->> 客户服务器信息-User : " + ftpUser);
  1326. Log.i(TAG_CAMERA_OPERATE, "Mac#1442->> 客户服务器信息-Passwd: " + ftpPasswd);
  1327. FtpTransferManager ftpTransferManagerToC = new FtpTransferManager(ftpIP,Integer.parseInt(ftpPort),ftpUser,ftpPasswd,remoteFilesPathServerC);
  1328. // FtpTransferManager ftpTransferManagerToC = new FtpTransferManager(FTP_INFO_HOST_URL,FTP_INFO_HOST_PORT,FTP_INFO_HOST_USER,FTP_INFO_HOST_PASSWD,remoteFilesPathServerC);
  1329. uploadToServerResultC = ftpTransferManagerToC.uploadFile(MacBitmapToServer,pictureNameToServer,120);
  1330. if (uploadToServerResultC) {
  1331. Log.i(TAG_CAMERA_OPERATE,"Mac#1451->> 向客户端上传图片成功.");
  1332. MqttCustomPublishFunction("{\"cmd\":\"ctrl\",\"type\":\"takephoto\",\"status\":\"3\"}");
  1333. } else {
  1334. Log.i(TAG_CAMERA_OPERATE,"Mac#1456->> 向客户端上传图片失败.");
  1335. MqttCustomPublishFunction("{\"cmd\":\"ctrl\",\"type\":\"takephoto\",\"status\":\"2\"}");
  1336. }
  1337. ftpTransferManagerToC.shutdown();
  1338. }
  1339. FtpTransferManager ftpTransferManagerToM = new FtpTransferManager(FTP_INFO_HOST_URL,FTP_INFO_HOST_PORT,FTP_INFO_HOST_USER,FTP_INFO_HOST_PASSWD,remoteFilesPathServerM);
  1340. uploadToServerResultM = ftpTransferManagerToM.uploadFile(MacBitmapToServer,pictureNameToServer,120);
  1341. if (uploadToServerResultM) {
  1342. Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.7.3.0->> 图片上传成功.");
  1343. MqttCustomPublishFunction("{\"cmd\":\"ctrl\",\"type\":\"takephoto\",\"status\":\"1\"}");
  1344. } else {
  1345. Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.7.3.0->> 图片上传失败.");
  1346. MqttCustomPublishFunction("{\"cmd\":\"ctrl\",\"type\":\"takephoto\",\"status\":\"0\"}");
  1347. }
  1348. ftpTransferManagerToM.shutdown();
  1349. /* 定时上传失败时保存图片 */
  1350. if(!uploadToServerResultM) {
  1351. Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.7.7->> 图片上传失败,保存至本地存储.");
  1352. MacCleanInvalidImages();
  1353. MacSaveBitmapToPhotosDir(MacBitmapToServer, pictureNameToDevStorage);
  1354. }
  1355. Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.7.8->> 向MCU发送拍照结束指令");
  1356. String takePhotoOver = "{\"photolink\":\"ALARM_INPUT\"}";
  1357. if(!SerialManager.getInstance().getUpgradingFlag()){
  1358. SerialManager.getInstance().write(takePhotoOver.getBytes());//串口下发界面操作指令(升级冲突#3)
  1359. }
  1360. /* 退出线程 */
  1361. exitThread();
  1362. } else {
  1363. Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.7.9->> 图片数据无效.");
  1364. }
  1365. }
  1366. try {
  1367. Thread.sleep(1000);
  1368. } catch (InterruptedException e) {
  1369. Log.i(TAG_CAMERA_OPERATE,"TakePhoto#01.7.10->> 线程延时错误.");
  1370. }
  1371. }
  1372. }
  1373. }
  1374. public void exitThread(){
  1375. threadExitStatus = false;
  1376. threadRunStatus = false;
  1377. mvccCameraManager.closeCameraDevice();
  1378. }
  1379. }).start();
  1380. }
  1381. private void RemoteSetCameraParametersThread(){
  1382. new Thread(new Runnable() {
  1383. boolean threadExitStatus = true;
  1384. boolean threadRunStatus = true;
  1385. boolean openCameraOperate = false;
  1386. boolean cameraGrabbing = false;
  1387. int takePhotoDelay = 0;
  1388. MvccCameraManager mvccCameraManager = MvccCameraManager.getInstance();
  1389. @Override
  1390. public void run() {
  1391. while(threadRunStatus){
  1392. if(!threadExitStatus){
  1393. return;
  1394. }
  1395. if(!openCameraOperate){
  1396. openCameraOperate = true;
  1397. Log.i(TAG_CAMERA_OPERATE, "TakePhoto#01.0->> 尝试打开相机.");
  1398. if(mvccCameraManager.openCameraDevice(true)){
  1399. Log.i(TAG_CAMERA_OPERATE, "TakePhoto#01.1->> 相机打开成功.");
  1400. if(UserGlobalVariable.Camera_SG_Parameters_Flag == 0){
  1401. mvccCameraManager.getCameraCommonParameter();
  1402. } else {
  1403. mvccCameraManager.setCameraCommonParameter();
  1404. mvccCameraManager.getCameraCommonParameter();
  1405. }
  1406. MacReportCameraParameters();
  1407. /* 退出线程 */
  1408. exitThread();
  1409. }else{
  1410. Log.i(TAG_CAMERA_OPERATE, "TakePhoto#01.3->> 相机打开失败.本次拍照任务取消.");
  1411. threadExitStatus = false;
  1412. }
  1413. }
  1414. }
  1415. }
  1416. public void exitThread(){
  1417. threadExitStatus = false;
  1418. threadRunStatus = false;
  1419. mvccCameraManager.closeCameraDevice();
  1420. }
  1421. }).start();
  1422. }
  1423. private void MacReportCameraParameters() {
  1424. JSONObject jsonObjectEXT = new JSONObject();
  1425. try {
  1426. jsonObjectEXT.put("ExposureAuto",UserGlobalVariable.getValue("ExposureAuto"));
  1427. jsonObjectEXT.put("ExposureTime",UserGlobalVariable.getValue("ExposureTime"));
  1428. jsonObjectEXT.put("BalanceWhiteAuto",UserGlobalVariable.getValue("BalanceWhiteAuto"));
  1429. jsonObjectEXT.put("GammaEnable",UserGlobalVariable.getValue("GammaEnable"));
  1430. jsonObjectEXT.put("Gamma",UserGlobalVariable.getValue("Gamma"));
  1431. jsonObjectEXT.put("HueEnable",UserGlobalVariable.getValue("HueEnable"));
  1432. jsonObjectEXT.put("Hue",UserGlobalVariable.getValue("Hue"));
  1433. JSONObject jsonObjectMain = new JSONObject();
  1434. try {
  1435. jsonObjectMain.put("cmd","Camera");
  1436. jsonObjectMain.put("status","1");
  1437. jsonObjectMain.put("parameters",jsonObjectEXT);
  1438. userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),jsonObjectMain.toString(),0);
  1439. } catch (JSONException e) {
  1440. throw new RuntimeException(e);
  1441. }
  1442. } catch (JSONException e) {
  1443. throw new RuntimeException(e);
  1444. }
  1445. }
  1446. /******************************************** FTP下载Application安装包功能 ********************************************/
  1447. private void MacAppUpgradeDeleteApkIfExists() {
  1448. // 构建app.apk文件的路径
  1449. File appApkFile = new File(getFilesDir(),"XCT.apk");
  1450. // 检查文件是否存在
  1451. if (appApkFile.exists()) {
  1452. // 删除文件
  1453. boolean isDeleted = appApkFile.delete();
  1454. if (isDeleted) {
  1455. // 文件删除成功
  1456. Log.i(TAG_FTP_APP_UPGRADE,"AppUpgrade#06.1->> 删除旧APK文件成功!!!");
  1457. } else {
  1458. // 文件删除失败
  1459. Log.i(TAG_FTP_APP_UPGRADE,"AppUpgrade#06.2->> 删除旧APK文件失败!!!");
  1460. }
  1461. } else {
  1462. // 文件不存在
  1463. Log.i(TAG_FTP_APP_UPGRADE,"AppUpgrade#06.3->> 'XCT.apk' 文件不存在!!!");
  1464. }
  1465. }
  1466. public static void MacExecuteShellSilent(String apkFilePath) {
  1467. try {
  1468. String pmStr = "pm install -r " + apkFilePath + "\n";
  1469. Process process = Runtime.getRuntime().exec("su");
  1470. DataOutputStream os = new DataOutputStream(process.getOutputStream());
  1471. os.writeBytes(pmStr);
  1472. os.writeBytes("exit\n");
  1473. os.flush();
  1474. } catch (IOException e) {
  1475. //e.printStackTrace();
  1476. Log.i("ApplicationUpgrade", "executeShellSilent: Error");
  1477. }
  1478. }
  1479. /******************************************** 权限获取部分功能 ********************************************/
  1480. /* 获取手机状态权限 */
  1481. public void GetSelfPermissionPhoneState() {
  1482. if (ActivityCompat.checkSelfPermission(MainActivity.this, "android.permission.READ_PHONE_STATE") != PackageManager.PERMISSION_GRANTED) {
  1483. ActivityCompat.requestPermissions(MainActivity.this,new String[]{"android.permission.READ_PHONE_STATE"},1);
  1484. Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#1.0-> 请求获取手机状态读取权限.");
  1485. } else {
  1486. Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#1.1-> 手机状态读取权限已获取.");
  1487. GetSelfPermissionLocation();
  1488. }
  1489. }
  1490. /* 获取位置权限 */
  1491. public void GetSelfPermissionLocation() {
  1492. if (ActivityCompat.checkSelfPermission(MainActivity.this, "android.permission.ACCESS_FINE_LOCATION") != PackageManager.PERMISSION_GRANTED) {
  1493. ActivityCompat.requestPermissions(MainActivity.this,new String[]{"android.permission.ACCESS_FINE_LOCATION"},2);
  1494. Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#2.0-> 请求获取手机位置读取权限.");
  1495. } else {
  1496. Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#2.1-> 手机位置读取权限已获取.");
  1497. GetSelfPermissionExternalStorage();
  1498. }
  1499. }
  1500. /* 获取外部存储读写权限 */
  1501. public void GetSelfPermissionExternalStorage() {
  1502. if (ActivityCompat.checkSelfPermission(this, "android.permission.READ_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED ||
  1503. ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED) {
  1504. Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#3.0-> 请求获取外部存储权限.");
  1505. ActivityCompat.requestPermissions(this, new String[]{ "android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"},3);
  1506. }else{
  1507. Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#3.1-> 外部存储权限已获取.");
  1508. // GetSelfPermissionWriteSettings();
  1509. // GetSelfPermissionWriteSettings2();
  1510. }
  1511. }
  1512. /* 获取外部存储读写权限 */
  1513. public void GetSelfPermissionWriteSettings() {
  1514. if (ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_SECURE_SETTINGS") != PackageManager.PERMISSION_GRANTED ||
  1515. ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_SECURE_SETTINGS") != PackageManager.PERMISSION_GRANTED) {
  1516. Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#4.0-> 请求获取数据流量开关权限.");
  1517. ActivityCompat.requestPermissions(this, new String[]{ "android.permission.WRITE_SECURE_SETTINGS"},4);
  1518. }else{
  1519. Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#4.1-> 数据流量控制权限已获取.");
  1520. }
  1521. }
  1522. /* 获取外部存储读写权限 */
  1523. public void GetSelfPermissionWriteSettings2() {
  1524. if (ActivityCompat.checkSelfPermission(this, "android.permission.MODIFY_PHONE_STATE") != PackageManager.PERMISSION_GRANTED ||
  1525. ActivityCompat.checkSelfPermission(this, "android.permission.MODIFY_PHONE_STATE") != PackageManager.PERMISSION_GRANTED) {
  1526. Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#4.0-> 请求获取数据流量开关权限.");
  1527. ActivityCompat.requestPermissions(this, new String[]{ "android.permission.MODIFY_PHONE_STATE"},5);
  1528. }else{
  1529. Log.i(TAG_REQUEST_PERMISSIONS, "Permissions#5.1-> 数据流量控制权限已获取.");
  1530. }
  1531. }
  1532. @Override
  1533. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  1534. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  1535. if (requestCode == 1) {
  1536. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  1537. /* 权限被授予,获取定位权限 */
  1538. GetSelfPermissionLocation();
  1539. } else {
  1540. /* 权限被拒绝,重复获取 */
  1541. GetSelfPermissionPhoneState();
  1542. }
  1543. } else if(requestCode == 2) {
  1544. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  1545. // 权限被授予,获取外部存储权限
  1546. GetSelfPermissionExternalStorage();
  1547. } else {
  1548. /* 权限被拒绝,重复获取 */
  1549. GetSelfPermissionLocation();
  1550. }
  1551. } else if(requestCode == 3) {
  1552. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  1553. /* 主要权限已全部获取完成 */
  1554. } else {
  1555. /* 权限被拒绝,重复获取 */
  1556. GetSelfPermissionExternalStorage();
  1557. }
  1558. }else if(requestCode == 4) {
  1559. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  1560. /* 主要权限已全部获取完成 */
  1561. Log.i("TAG", "onRequestPermissionsResult: 数据流量开关权限获取完成");
  1562. } else {
  1563. /* 权限被拒绝,重复获取 */
  1564. GetSelfPermissionExternalStorage();
  1565. }
  1566. }
  1567. }
  1568. /******************************************** 硬件信息获取部分功能 ********************************************/
  1569. public void MacGetPhoneStateInfo() {
  1570. if (ActivityCompat.checkSelfPermission(this, "android.permission.READ_PHONE_STATE") == PackageManager.PERMISSION_GRANTED) {
  1571. String iccid = "-1";
  1572. TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
  1573. /* 获取信号强度 */
  1574. int fragmentMac1_SignalStrength = 0;
  1575. SignalStrength signalStrength = telephonyManager.getSignalStrength();
  1576. if(signalStrength != null){
  1577. fragmentMac1_SignalStrength = signalStrength.getLevel();
  1578. }
  1579. // 获取SIM卡状态
  1580. int fragmentMac1_SimState = telephonyManager.getSimState();
  1581. // 获取ICCID
  1582. if(telephonyManager.getSimState() != TelephonyManager.SIM_STATE_ABSENT){
  1583. iccid = telephonyManager.getSimSerialNumber();
  1584. if(iccid == null || iccid.length() < 20){
  1585. SubscriptionManager sm = SubscriptionManager.from(this);
  1586. List <SubscriptionInfo> sis = sm.getActiveSubscriptionInfoList();
  1587. if(sis.size() >= 1){
  1588. SubscriptionInfo si1 = sis.get(0);
  1589. iccid = si1.getIccId();
  1590. // Log.i("PhoneStateInfo", "ICCID: " + iccid);
  1591. }
  1592. }
  1593. }
  1594. // 获取IMEI
  1595. String imei = telephonyManager.getImei();
  1596. if(imei != null && imei.length() > 10){
  1597. UserGlobalVariable.Android_Dev_GetIMEIResult = true;
  1598. }
  1599. UserGlobalVariable.setlValue("iccid",iccid);
  1600. UserGlobalVariable.setlValue("imei",imei);
  1601. UserGlobalVariable.setlValue("csq", String.valueOf(fragmentMac1_SignalStrength));
  1602. UserGlobalVariable.setlValue("simCard", String.valueOf(fragmentMac1_SimState));
  1603. //MainActivityMessageToFragment("MainActivityToFMac0","Operate","Refresh");
  1604. }
  1605. }
  1606. public void MainActivityMessageToFragment(String requestKey,String key,String value) {
  1607. Bundle result = new Bundle();
  1608. result.putString(key,value);
  1609. getSupportFragmentManager().setFragmentResult(requestKey,result);
  1610. }
  1611. /******************************************** 硬件信息获取部分功能 ********************************************/
  1612. private void AutoUploadPhotosToFTP() {
  1613. if (UserGlobalVariable.AutoUploadCachedImagesFlag) {
  1614. return;
  1615. }
  1616. UserGlobalVariable.AutoUploadCachedImagesFlag = true;
  1617. Log.i(TAG_CAMERA_OPERATE, "AutoUploadPic#01->> 检测是否有缓存图片.");
  1618. // 获取应用的私有目录下的photos文件夹
  1619. File photosDir = new File(getFilesDir(),"photos");
  1620. // 如果目录不存在或不是一个文件夹,则直接返回
  1621. if (!photosDir.exists() || !photosDir.isDirectory()) {
  1622. return;
  1623. }
  1624. File[] files = photosDir.listFiles();
  1625. if (files != null && files.length!= 0) {
  1626. Log.i(TAG_CAMERA_OPERATE, "AutoUploadPic#01->> 自动上传进程开始运行!!!");
  1627. Log.i(TAG_CAMERA_OPERATE, "AutoUploadPic#02->> 图片缓存数量: " + files.length);
  1628. // for (File filed : files) {
  1629. // Log.i(TAG_CAMERA_OPERATE, "PhotosDir: " + filed.getName());
  1630. // }
  1631. new Thread(new Runnable() {
  1632. @Override
  1633. public void run() {
  1634. File photosDir = new File(getFilesDir(), "photos");
  1635. File[] files = photosDir.listFiles();
  1636. FTPClient ftpClient = new FTPClient();
  1637. try {
  1638. /* 连接超时时间 */
  1639. ftpClient.setConnectTimeout(10 * 1000);
  1640. /* 数据传输超时时间 */
  1641. ftpClient.setDataTimeout(10 * 1000);
  1642. //正式服务器
  1643. ftpClient.connect(FTP_INFO_HOST_URL, FTP_INFO_HOST_PORT);
  1644. ftpClient.login(FTP_INFO_HOST_USER, FTP_INFO_HOST_PASSWD);
  1645. ftpClient.enterLocalPassiveMode(); // 通常用于解决NAT和防火墙问题
  1646. ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // 设置文件类型为二进制,适用于图片
  1647. String tempIMEI = UserGlobalVariable.getValue("imei");
  1648. String remoteFilePath = "/" + tempIMEI + "/";
  1649. if (!ftpClient.changeWorkingDirectory(remoteFilePath)) {
  1650. String[] dirs = remoteFilePath.split("/");
  1651. String currentDir = "";
  1652. for (String dir : dirs) {
  1653. if (dir.isEmpty())
  1654. continue;
  1655. currentDir += "/" + dir;
  1656. if (!ftpClient.changeWorkingDirectory(currentDir)) {
  1657. if (!ftpClient.makeDirectory(currentDir)) {
  1658. //throw new IOException("创建目录失败: " + currentDir);
  1659. Log.d(TAG_CAMERA_OPERATE, "AutoUploadPic#03.0.1->> 创建目录失败.");
  1660. }else{
  1661. Log.d(TAG_CAMERA_OPERATE, "AutoUploadPic#03.0.2->> 创建目录成功.");
  1662. }
  1663. }else{
  1664. Log.d(TAG_CAMERA_OPERATE, "AutoUploadPic#03.0.3->> 切换目录失败.");
  1665. }
  1666. }
  1667. }else{
  1668. Log.d(TAG_CAMERA_OPERATE, "AutoUploadPic#03.0.4->> 缓存图片路径已存在.");
  1669. }
  1670. for (File file : files) {
  1671. try (FileInputStream inputStream = new FileInputStream(file)) {
  1672. String remotePicPath = remoteFilePath + "history-" + tempIMEI + "-" + file.getName();
  1673. Log.d(TAG_CAMERA_OPERATE, "AutoUploadPic#03.1->> 缓存图片路径名称: " + remotePicPath);
  1674. boolean done = ftpClient.storeFile(remotePicPath, inputStream);
  1675. if (done) {
  1676. Log.d(TAG_CAMERA_OPERATE, "AutoUploadPic#03.1->> 图片 < " + file.getName() + " > 上传成功.");
  1677. if (file.delete()) {
  1678. Log.i(TAG_CAMERA_OPERATE,"AutoUploadPic#03.2->> 图片 < " + file.getName() + " > 删除成功.");
  1679. } else {
  1680. Log.i(TAG_CAMERA_OPERATE,"AutoUploadPic#03.3->> 图片 < " + file.getName() + " > 删除失败.");
  1681. }
  1682. } else {
  1683. Log.e(TAG_CAMERA_OPERATE, "AutoUploadPic#03.4->> 图片 < " + file.getName() + " > 上传失败.");
  1684. }
  1685. } catch (IOException ex) {
  1686. Log.e(TAG_CAMERA_OPERATE, "AutoUploadPic#03.5->> 图片 < " + file.getName() + " > 加载出错:", ex);
  1687. }
  1688. }
  1689. ftpClient.logout();
  1690. } catch (IOException ex) {
  1691. Log.e(TAG_CAMERA_OPERATE, "AutoUploadPic#04->> Ftp传输出错!!!");
  1692. } finally {
  1693. try {
  1694. if (ftpClient.isConnected()) {
  1695. ftpClient.disconnect();
  1696. Log.i(TAG_CAMERA_OPERATE, "AutoUploadPic#05.1->> 关闭Ftp传输通道");
  1697. }
  1698. } catch (IOException ex) {
  1699. // 处理断开连接时的异常
  1700. Log.e(TAG_CAMERA_OPERATE, "AutoUploadPic#05.2->> Ftp传输通道关闭出错!!!", ex);
  1701. }
  1702. // UserGlobalVariable.AutoUploadCachedImagesFlag = false;
  1703. Log.d(TAG_CAMERA_OPERATE, "AutoUploadPic#06->> 自动上传图片进程结束");
  1704. }
  1705. }
  1706. }).start();
  1707. }
  1708. }
  1709. void MacMainMqttFunction(){
  1710. if(!UserGlobalVariable.Android_Dev_GetIMEIResult){
  1711. return;
  1712. }
  1713. if(userMqttManager == null){
  1714. userMqttManager = new UserMqttManager(MQTT_MAIN_HOST_URL,MQTT_MAIN_USER,MQTT_MAIN_PASSWORD,UserGlobalVariable.getValue("imei"));
  1715. userMqttManager.setMqttConnectionCallback(new UserMqttManager.MqttConnectionCallback() {
  1716. @Override
  1717. public void onConnectionChanged(boolean isConnected) {
  1718. if(isConnected){
  1719. UserGlobalVariable.Mqtt_M_Connect_Status = 1;
  1720. UserGlobalVariable.Mqtt_M_ReConnect_Flag = 0;
  1721. }else {
  1722. UserGlobalVariable.Mqtt_M_Connect_Status = 0;
  1723. UserGlobalVariable.Mqtt_M_ReConnect_Flag = 1;
  1724. }
  1725. }
  1726. @Override
  1727. public void onMessageReceived(String topic, String message, boolean retained) {
  1728. if(retained){
  1729. Log.i("TAG", "清除Retained消息");
  1730. userMqttManager.publishNull(MQTT_MAIN_SUB_TOPIC + UserGlobalVariable.getValue("imei"));
  1731. }
  1732. if (!message.isEmpty()) {
  1733. String logString = "";
  1734. JSONObject arrivedMessageJsonObject = null;
  1735. try {
  1736. arrivedMessageJsonObject = new JSONObject(message);
  1737. if (arrivedMessageJsonObject.has("cmd")) {
  1738. String cmdType = arrivedMessageJsonObject.get("cmd").toString();
  1739. boolean sendMessageToMcuFlag = false;
  1740. Log.i("TAG", "onMessageReceived: " + cmdType);
  1741. if(cmdType.equals("update")) {
  1742. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#01.02.1->> MCU固件升级.");
  1743. if(!UserGlobalVariable.Upgrade_Mcu_Status){
  1744. /* MCU固件升级 */
  1745. logString = "服务器下发: MCU固件升级";
  1746. MacUpgradeInfoJson.put("ftpIP","8.136.98.49");
  1747. MacUpgradeInfoJson.put("ftpPort","21");
  1748. MacUpgradeInfoJson.put("ftpUser","cbd_user");
  1749. MacUpgradeInfoJson.put("ftpPasswd","YFkj@6O2O");
  1750. MacUpgradeInfoJson.put("ftpFilePath","/_UPDATE_FILE/A7/XCT/STM32/XCT.rbl");
  1751. //升级状态标识赋
  1752. UserGlobalVariable.Upgrade_Mcu_Status = true;
  1753. UserGlobalVariable.Upgrade_Mcu_FW_Download_Flag = true;
  1754. UserGlobalVariable.Upgrade_Mcu_Timeout_Flag = false;
  1755. String mcuUpgradeInfo = "{\"cmd\":\"paramconf\",\"ext\":{\"Demo_mode\":1,\"no_reply\": 1}}";
  1756. SerialManager.getInstance().write(mcuUpgradeInfo.getBytes());//辅助YModem升级指令
  1757. userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"upgrade\",\"type\":\"mcu\",\"status\":\"2\"}",0);
  1758. }else{
  1759. logString = "服务器下发: MCU升级中,勿重复操作.";
  1760. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#01.02.2->> MCU升级中,勿重复操作.");
  1761. userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"upgrade\",\"type\":\"mcu\",\"status\":\"3\"}",0);
  1762. }
  1763. } else if(cmdType.equals("dtu_update")) {
  1764. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#01.01->> APP应用升级.");
  1765. MacUpgradeInfoJson.put("ftpIP","8.136.98.49");
  1766. MacUpgradeInfoJson.put("ftpPort","21");
  1767. MacUpgradeInfoJson.put("ftpUser","cbd_user");
  1768. MacUpgradeInfoJson.put("ftpPasswd","YFkj@6O2O");
  1769. MacUpgradeInfoJson.put("ftpFilePath","/_UPDATE_FILE/A7/XCT/Android/XCT.apk");
  1770. if(!SerialManager.getInstance().getUpgradingFlag()){
  1771. if(!UserGlobalVariable.Upgrade_APP_Operate_Status){
  1772. logString = "服务器下发: APP应用升级";
  1773. UserGlobalVariable.Upgrade_APP_Operate_Flag = true;
  1774. userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"upgrade\",\"type\":\"app\",\"status\":\"2\"}",0);
  1775. }else{
  1776. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#01.03->> APP应用升级中,勿重复操作.");
  1777. logString = "服务器下发: APP应用升级(升级中)";
  1778. }
  1779. }else{
  1780. userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"upgrade\",\"type\":\"app\",\"status\":\"3\"}",0);
  1781. }
  1782. } else if(cmdType.equals("setnet")) {
  1783. JSONObject jsonObject = new JSONObject();
  1784. String clientServer = arrivedMessageJsonObject.getString("status");
  1785. if(clientServer.equals("1")){
  1786. UserGlobalVariable.setlValue("clientServer",clientServer);
  1787. if(arrivedMessageJsonObject.has("mqtt")){
  1788. String mqttUser = arrivedMessageJsonObject.getJSONObject("mqtt").getString("uid");
  1789. String mqttPasswd = arrivedMessageJsonObject.getJSONObject("mqtt").getString("pwd");
  1790. String mqttIP = arrivedMessageJsonObject.getJSONObject("mqtt").getString("ip");
  1791. String mqttPort = arrivedMessageJsonObject.getJSONObject("mqtt").getString("port");
  1792. String mqttSubTopic = arrivedMessageJsonObject.getJSONObject("mqtt").getString("sub");
  1793. String mqttPubTopic = arrivedMessageJsonObject.getJSONObject("mqtt").getString("pub");
  1794. UserGlobalVariable.setlValue("mqttIP",mqttIP);
  1795. UserGlobalVariable.setlValue("mqttPort",mqttPort);
  1796. UserGlobalVariable.setlValue("mqttUser",mqttUser);
  1797. UserGlobalVariable.setlValue("mqttPasswd",mqttPasswd);
  1798. UserGlobalVariable.setlValue("mqttSubTopic",mqttSubTopic);
  1799. UserGlobalVariable.setlValue("mqttPubTopic",mqttPubTopic);
  1800. UserGlobalVariable.Customer_Mqtt_Enable = true;
  1801. try {
  1802. jsonObject.put("clientServer",clientServer);
  1803. jsonObject.put("mqttEnable","1");
  1804. jsonObject.put("mqttIP",mqttIP);
  1805. jsonObject.put("mqttPort",mqttPort);
  1806. jsonObject.put("mqttUser",mqttUser);
  1807. jsonObject.put("mqttPasswd",mqttPasswd);
  1808. jsonObject.put("mqttSubTopic",mqttSubTopic);
  1809. jsonObject.put("mqttPubTopic",mqttPubTopic);
  1810. } catch (JSONException e) {
  1811. throw new RuntimeException(e);
  1812. }
  1813. }else{
  1814. jsonObject.put("mqttEnable","0");
  1815. }
  1816. if(arrivedMessageJsonObject.has("ftp")){
  1817. String ftpUser = arrivedMessageJsonObject.getJSONObject("ftp").getString("uid");
  1818. String ftpPasswd = arrivedMessageJsonObject.getJSONObject("ftp").getString("pwd");
  1819. String ftpIP = arrivedMessageJsonObject.getJSONObject("ftp").getString("ip");
  1820. String ftpPort = arrivedMessageJsonObject.getJSONObject("ftp").getString("port");
  1821. String ftpFilePath = arrivedMessageJsonObject.getJSONObject("ftp").getString("filepath");
  1822. UserGlobalVariable.setlValue("ftpIP",ftpIP);
  1823. UserGlobalVariable.setlValue("ftpPort",ftpPort);
  1824. UserGlobalVariable.setlValue("ftpUser",ftpUser);
  1825. UserGlobalVariable.setlValue("ftpPasswd",ftpPasswd);
  1826. UserGlobalVariable.setlValue("ftpFilePath",ftpFilePath);
  1827. UserGlobalVariable.Customer_FTP_Enable = true;
  1828. try {
  1829. jsonObject.put("clientServer",clientServer);
  1830. jsonObject.put("ftpEnable","1");
  1831. jsonObject.put("ftpIP",ftpIP);
  1832. jsonObject.put("ftpPort",ftpPort);
  1833. jsonObject.put("ftpUser",ftpUser);
  1834. jsonObject.put("ftpPasswd",ftpPasswd);
  1835. jsonObject.put("ftpFilePath",ftpFilePath);
  1836. MacSetSystemParameterSP(SYS_PARA_CLIENT_SERVER_INFO,jsonObject.toString());
  1837. } catch (JSONException e) {
  1838. throw new RuntimeException(e);
  1839. }
  1840. }else{
  1841. jsonObject.put("ftpEnable","0");
  1842. }
  1843. MacSetSystemParameterSP(SYS_PARA_CLIENT_SERVER_INFO,jsonObject.toString());
  1844. }
  1845. // 如果当前MQTT正在连接,则先断开连接。
  1846. if (customerMqttManager != null && customerMqttManager.isConnected()) {
  1847. customerMqttManager = null;
  1848. Log.i("TAG", "MQTT已连接,先断开已有连接.: ");
  1849. customerMqttManager.disconnect();
  1850. }
  1851. logString = "服务器下发: 客户服务器配置.";
  1852. } else if(cmdType.equals("Camera")) {
  1853. //20250414MARK01-3 服务器下发相机拍照时相机忙。
  1854. if (MvccCameraManager.getInstance().getCameraState()) {
  1855. Log.i(TAG_CAMERA_OPERATE,"Camera Is Busy #3!!!");
  1856. userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"Camera\",\"status\":\"3\"}",0);
  1857. } else {
  1858. UserGlobalVariable.Camera_Set_Parameters_Flag = true;
  1859. userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"Camera\",\"status\":\"2\"}",0);
  1860. //设置参数
  1861. if(arrivedMessageJsonObject.getString("operate").equals("1")) {
  1862. UserGlobalVariable.Camera_SG_Parameters_Flag = 1;
  1863. //自动曝光
  1864. if(arrivedMessageJsonObject.getJSONObject("parameters").has("ExposureAuto")) {
  1865. UserGlobalVariable.Camera_Set_ExposureAuto_Flag = true;
  1866. String tempParameter = arrivedMessageJsonObject.getJSONObject("parameters").getString("ExposureAuto");
  1867. UserGlobalVariable.setlValue("ExposureAuto",tempParameter);
  1868. // Log.i("MVCC_CAMERA_OPERATE","Mac#1982->> P01: 自动曝光使能: " + UserGlobalVariable.getValue("ExposureAuto"));
  1869. }
  1870. //自动曝光时间
  1871. if(arrivedMessageJsonObject.getJSONObject("parameters").has("ExposureTime")){
  1872. UserGlobalVariable.Camera_Set_ExposureTime_Flag = true;
  1873. String tempParameter = arrivedMessageJsonObject.getJSONObject("parameters").getString("ExposureTime");
  1874. UserGlobalVariable.setlValue("ExposureTime",tempParameter);
  1875. // Log.i("MVCC_CAMERA_OPERATE","Mac#1990->> P02: 自动曝光时间: " + UserGlobalVariable.getValue("ExposureTime"));
  1876. }
  1877. //伽马使能
  1878. if(arrivedMessageJsonObject.getJSONObject("parameters").has("BalanceWhiteAuto")){
  1879. UserGlobalVariable.Camera_Set_BalanceWhiteAuto_Flag = true;
  1880. String tempParameter = arrivedMessageJsonObject.getJSONObject("parameters").getString("BalanceWhiteAuto");
  1881. UserGlobalVariable.setlValue("BalanceWhiteAuto",tempParameter);
  1882. // Log.i("MVCC_CAMERA_OPERATE","Mac#1998->> P03: 伽马使能开关: " + UserGlobalVariable.getValue("BalanceWhiteAuto"));
  1883. }
  1884. //伽马使能
  1885. if(arrivedMessageJsonObject.getJSONObject("parameters").has("GammaEnable")){
  1886. UserGlobalVariable.Camera_Set_GammaEnable_Flag = true;
  1887. String tempParameter = arrivedMessageJsonObject.getJSONObject("parameters").getString("GammaEnable");
  1888. UserGlobalVariable.setlValue("GammaEnable",tempParameter);
  1889. // Log.i("MVCC_CAMERA_OPERATE","Mac#1998->> P03: 伽马使能开关: " + UserGlobalVariable.getValue("GammaEnable"));
  1890. }
  1891. //伽马值
  1892. if(arrivedMessageJsonObject.getJSONObject("parameters").has("Gamma")){
  1893. UserGlobalVariable.Camera_Set_Gamma_Flag = true;
  1894. String tempParameter = arrivedMessageJsonObject.getJSONObject("parameters").getString("Gamma");
  1895. UserGlobalVariable.setlValue("Gamma",tempParameter);
  1896. // Log.i("MVCC_CAMERA_OPERATE","Mac#2006->> P04: 伽马值: " + UserGlobalVariable.getValue("Gamma"));
  1897. }
  1898. //色度使能
  1899. if(arrivedMessageJsonObject.getJSONObject("parameters").has("HueEnable")){
  1900. UserGlobalVariable.Camera_Set_HueEnable_Flag = true;
  1901. String tempParameter = arrivedMessageJsonObject.getJSONObject("parameters").getString("HueEnable");
  1902. UserGlobalVariable.setlValue("HueEnable",tempParameter);
  1903. // Log.i("MVCC_CAMERA_OPERATE","Mac#2014->> P05: 色度使能开关: " + UserGlobalVariable.getValue("HueEnable"));
  1904. }
  1905. //色度值
  1906. if(arrivedMessageJsonObject.getJSONObject("parameters").has("Hue")){
  1907. UserGlobalVariable.Camera_Set_Hue_Flag = true;
  1908. String tempParameter = arrivedMessageJsonObject.getJSONObject("parameters").getString("Hue");
  1909. UserGlobalVariable.setlValue("Hue",tempParameter);
  1910. // Log.i("MVCC_CAMERA_OPERATE","Mac#2022->> P06: 色度值: " + UserGlobalVariable.getValue("Hue"));
  1911. }
  1912. } else {
  1913. UserGlobalVariable.Camera_SG_Parameters_Flag = 0;
  1914. }
  1915. }
  1916. logString = "服务器下发: 相机参数配置.";
  1917. } else if(cmdType.toString().equals("ctrl")) {
  1918. if(arrivedMessageJsonObject.getJSONObject("ext").has("type")){
  1919. if(arrivedMessageJsonObject.getJSONObject("ext").getString("type").equals("takephoto")){
  1920. /* 此时正在"相机操作"界面时或相机正在执行拍照任务时 */
  1921. //20250414MARK01-3 服务器下发相机拍照时相机忙。
  1922. if (MvccCameraManager.getInstance().getCameraState()) {
  1923. Log.i(TAG_CAMERA_OPERATE,"Camera Is Busy #3!!!");
  1924. userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"ctrl\",\"type\":\"takephoto\",\"status\":\"3\"}",0);
  1925. } else {
  1926. logString = "服务器下发: 立即拍照";
  1927. UserGlobalVariable.Camera_TimingTakePhoto_Flag = true;
  1928. sendMessageToMcuFlag = true;
  1929. userMqttManager.publish("/yfkj/XCT/pub/" + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"ctrl\",\"type\":\"takephoto\",\"status\":\"2\"}",0);
  1930. }
  1931. }
  1932. }else{
  1933. sendMessageToMcuFlag = true;
  1934. }
  1935. } else if(cmdType.toString().equals("paramconf")) {
  1936. sendMessageToMcuFlag = true;
  1937. logString = "服务器下发: 参数设置";
  1938. } else if(cmdType.toString().equals("dtu_reboot")) {
  1939. sendMessageToMcuFlag = true;
  1940. logString = "服务器下发: 安卓重启";
  1941. } else if(cmdType.toString().equals("systemParameter")) {
  1942. String waitTime = arrivedMessageJsonObject.getJSONObject("ext").getString("waitTime");
  1943. Log.i("TAG", "onMessageReceived: " + waitTime);
  1944. UserGlobalVariable.CameraTakePhotoWaitExposure = Integer.parseInt(waitTime);
  1945. MacSetSystemParameterSP(SYS_PARA_CAMERA_TAKE_PHOTO_WAIT_EXPOSURE,waitTime);
  1946. }
  1947. if (sendMessageToMcuFlag) {
  1948. sendMessageToMcuFlag = false;
  1949. if(!SerialManager.getInstance().getUpgradingFlag()){
  1950. SerialManager.getInstance().write(message.getBytes());//串口下发界面操作指令(升级冲突#3)
  1951. }
  1952. }
  1953. if(!logString.isEmpty()){
  1954. Log.i(TAG_FMACX_MSG_TO_MAC,"FromMqtt->> OptEvents = " + logString);
  1955. LogFileManagerOperate.VerifyLogFileConformsToJson();
  1956. LogFileManagerOperate.CheckLogFileNumber();
  1957. LogFileManagerOperate.AddOneLogItem(logString);
  1958. }
  1959. }
  1960. } catch (JSONException e) {
  1961. // throw new RuntimeException(e);
  1962. }
  1963. }
  1964. }
  1965. @Override
  1966. public void onError(Throwable throwable) {
  1967. }
  1968. });
  1969. Log.i("MqttOperate","Mac#2037-> 连接公司Mqtt服务器 " + UserGlobalVariable.getValue("imei"));
  1970. userMqttManager.mqttConnect(MQTT_MAIN_SUB_TOPIC + UserGlobalVariable.getValue("imei"));
  1971. } else {
  1972. if (userMqttManager.isConnected()) {
  1973. if(UserGlobalVariable.McuData_UploadToOfficialServer_Flag){
  1974. UserGlobalVariable.McuData_UploadToOfficialServer_Flag = false;
  1975. userMqttManager.publish(MQTT_MAIN_PUB_TOPIC + UserGlobalVariable.getValue("imei"),UserGlobalVariable.McuData_UploadToOfficialServer,0);
  1976. UserGlobalVariable.McuData_UploadToOfficialServer = "";
  1977. Log.i("TAG", "MacMainMqttFunction: 向服务器发送数据.");
  1978. }
  1979. if (MacAppHeartbeatFlag) {
  1980. MacAppHeartbeatFlag = false;
  1981. MacAppHeartbeatToServer();
  1982. }
  1983. HistoryDataManager historyManager = new HistoryDataManager(this);
  1984. // 统计行数
  1985. int lineCount = historyManager.countLines();
  1986. if(lineCount > 0){
  1987. //取出数据
  1988. String lastLine = historyManager.removeLastLine();
  1989. // mqttManager.publish(MQTT_MAIN_PUB_TOPIC + UserGlobalVariable.getValue("imei"),lastLine,0,false,10000);
  1990. userMqttManager.publish(MQTT_MAIN_PUB_TOPIC + UserGlobalVariable.getValue("imei"),lastLine,0);
  1991. // 再次统计行数
  1992. lineCount = historyManager.countLines();
  1993. }
  1994. } else {
  1995. if(UserGlobalVariable.Mqtt_M_ReConnect_Flag == 1){
  1996. UserGlobalVariable.Mqtt_M_ReConnect_Flag = 2;
  1997. Log.i("TAG", "MAC#2050-> 主MQTT服务器重连.");
  1998. userMqttManager.mqttConnect(MQTT_MAIN_SUB_TOPIC + UserGlobalVariable.getValue("imei"));
  1999. }
  2000. // 网络断开连接时保存数据到本地
  2001. if(UserGlobalVariable.McuData_UploadToOfficialServer_Flag){
  2002. UserGlobalVariable.McuData_UploadToOfficialServer_Flag = false;
  2003. try {
  2004. JSONObject hisJsonObject = new JSONObject(UserGlobalVariable.McuData_UploadToOfficialServer);
  2005. if(hisJsonObject.has("cmd")){
  2006. //如果要上传的数据是data类型的,则保存至本地.
  2007. if(hisJsonObject.get("cmd").equals("data")){
  2008. Log.i("TAG", "MacMainMqttFunction#1: data类型数据,做本地保存.");
  2009. hisJsonObject.put("cmd","HistoryData");
  2010. HistoryDataManager historyManager = new HistoryDataManager(this);
  2011. // 统计行数
  2012. int lineCount = historyManager.countLines();
  2013. //写入数据
  2014. historyManager.writeJsonData(hisJsonObject);
  2015. }else{
  2016. Log.i("TAG", "MacMainMqttFunction#2: 非data类型数据,不做本地保存.");
  2017. }
  2018. }
  2019. } catch (JSONException e) {
  2020. //throw new RuntimeException(e);
  2021. // Log.i(TAG_HISTORY_DATA,"HD#5.0.3->> 数据生成异常.");
  2022. }
  2023. UserGlobalVariable.McuData_UploadToOfficialServer = "";
  2024. }
  2025. }
  2026. }
  2027. }
  2028. void MqttCustomPublishFunction(String payload){
  2029. if(userMqttManager != null){
  2030. if(userMqttManager.isConnected()){
  2031. userMqttManager.publish(MQTT_MAIN_PUB_TOPIC + UserGlobalVariable.getValue("imei"),payload,0);
  2032. }
  2033. }
  2034. }
  2035. void MacCustomerMqttFunction(){
  2036. if (!UserGlobalVariable.Android_Dev_GetIMEIResult || !UserGlobalVariable.Customer_Mqtt_Enable) {
  2037. return;
  2038. }
  2039. if(customerMqttManager == null){
  2040. // 使用String.format组合
  2041. String TempURL = String.format("tcp://%s:%s", UserGlobalVariable.getValue("mqttIP"), UserGlobalVariable.getValue("mqttPort"));
  2042. String TempUSER = UserGlobalVariable.getValue("mqttUser");
  2043. String TempPASSWD = UserGlobalVariable.getValue("mqttPasswd");
  2044. Log.i("TAG", "Mac#2115-> Mqtt: " + TempURL + " " + TempPASSWD);
  2045. customerMqttManager = new UserMqttManager(TempURL, TempUSER, TempPASSWD, UserGlobalVariable.getValue("imei"));
  2046. customerMqttManager.setMqttConnectionCallback(new UserMqttManager.MqttConnectionCallback() {
  2047. @Override
  2048. public void onConnectionChanged(boolean isConnected) {
  2049. if(isConnected){
  2050. UserGlobalVariable.Customer_Mqtt_Connect_Status = 1;
  2051. UserGlobalVariable.Customer_Mqtt_ReConnect_Flag = 0;
  2052. Log.i("TAG", "MAC#2116-> 客户端MQTT连接成功.");
  2053. }else {
  2054. UserGlobalVariable.Customer_Mqtt_Connect_Status = 0;
  2055. UserGlobalVariable.Customer_Mqtt_ReConnect_Flag = 1;
  2056. Log.i("TAG", "MAC#2116-> 客户端MQTT连接断开.");
  2057. }
  2058. }
  2059. @Override
  2060. public void onMessageReceived(String topic, String message, boolean retained) {
  2061. if(retained){
  2062. Log.i("TAG", "清除Retained消息");
  2063. customerMqttManager.publishNull(UserGlobalVariable.getValue("mqttSubTopic") + UserGlobalVariable.getValue("imei"));
  2064. }
  2065. if (!message.isEmpty()) {
  2066. JSONObject arrivedMessageJsonObject = null;
  2067. try {
  2068. arrivedMessageJsonObject = new JSONObject(message);
  2069. if (arrivedMessageJsonObject.has("cmd")) {
  2070. String cmdType = arrivedMessageJsonObject.get("cmd").toString();
  2071. boolean sendMessageToMcuFlag = false;
  2072. Log.i("TAG", "onMessageReceived: " + cmdType);
  2073. if(cmdType.toString().equals("ctrl")) {
  2074. if(arrivedMessageJsonObject.getJSONObject("ext").has("type")){
  2075. if(arrivedMessageJsonObject.getJSONObject("ext").getString("type").equals("takephoto")){
  2076. /* 此时正在"相机操作"界面时或相机正在执行拍照任务时 */
  2077. //20250414MARK01-3 服务器下发相机拍照时相机忙。
  2078. if (MvccCameraManager.getInstance().getCameraState()) {
  2079. Log.i(TAG_CAMERA_OPERATE,"Camera Is Busy #3!!!");
  2080. customerMqttManager.publish(UserGlobalVariable.getValue("mqttPubTopic") + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"ctrl\",\"type\":\"takephoto\",\"status\":\"3\"}",0);
  2081. } else {
  2082. UserGlobalVariable.Camera_TimingTakePhoto_Flag = true;
  2083. sendMessageToMcuFlag = true;
  2084. customerMqttManager.publish(UserGlobalVariable.getValue("mqttPubTopic") + UserGlobalVariable.getValue("imei"),"{\"cmd\":\"ctrl\",\"type\":\"takephoto\",\"status\":\"2\"}",0);
  2085. }
  2086. }
  2087. }else{
  2088. sendMessageToMcuFlag = true;
  2089. }
  2090. } else if(cmdType.toString().equals("paramconf")) {
  2091. sendMessageToMcuFlag = true;
  2092. } else if(cmdType.toString().equals("dtu_reboot")) {
  2093. sendMessageToMcuFlag = true;
  2094. }
  2095. if (sendMessageToMcuFlag) {
  2096. sendMessageToMcuFlag = false;
  2097. if(!SerialManager.getInstance().getUpgradingFlag()){
  2098. SerialManager.getInstance().write(message.getBytes());//串口下发界面操作指令(升级冲突#3)
  2099. }
  2100. }
  2101. }
  2102. } catch (JSONException e) {
  2103. // throw new RuntimeException(e);
  2104. }
  2105. }
  2106. }
  2107. @Override
  2108. public void onError(Throwable throwable) {
  2109. }
  2110. });
  2111. Log.i("MqttOperate","Mac#2236-> 连接客户Mqtt服务器 " + UserGlobalVariable.getValue("imei"));
  2112. customerMqttManager.mqttConnect(UserGlobalVariable.getValue("mqttSubTopic") + UserGlobalVariable.getValue("imei"));
  2113. } else {
  2114. if (customerMqttManager.isConnected()) {
  2115. if (UserGlobalVariable.Customer_Mqtt_McuDataToServer_Flag) {
  2116. UserGlobalVariable.Customer_Mqtt_McuDataToServer_Flag = false;
  2117. customerMqttManager.publish(UserGlobalVariable.getValue("mqttPubTopic") + UserGlobalVariable.getValue("imei"),UserGlobalVariable.Customer_Mqtt_McuDataToServer,0);
  2118. UserGlobalVariable.Customer_Mqtt_McuDataToServer = "";
  2119. Log.i("TAG", "MacMainMqttFunction: 向客户服务器发送数据.");
  2120. }
  2121. if (CustomerMqttHeartbeatToServerFlag) {
  2122. CustomerMqttHeartbeatToServerFlag = false;
  2123. MacAppCustomerMqttHeartbeatToServer();
  2124. }
  2125. } else {
  2126. if (UserGlobalVariable.Customer_Mqtt_ReConnect_Flag == 1) {
  2127. UserGlobalVariable.Customer_Mqtt_ReConnect_Flag = 2;
  2128. Log.i("TAG", "MAC#2240-> 客MQTT服务器重连.");
  2129. customerMqttManager.mqttConnect(UserGlobalVariable.getValue("mqttSubTopic") + UserGlobalVariable.getValue("imei"));
  2130. }
  2131. }
  2132. }
  2133. }
  2134. /******************************************** 主线程功能 ********************************************/
  2135. public class ThreadMainActivity extends Thread {
  2136. public void run() {
  2137. while(true) {
  2138. MacMainMqttFunction();
  2139. MacCustomerMqttFunction();
  2140. /* 获取手机状态信息 */
  2141. if(MacGetPhoneStateInfoFlag || !UserGlobalVariable.Android_Dev_GetIMEIResult){
  2142. MacGetPhoneStateInfoFlag = false;
  2143. MacGetPhoneStateInfo();
  2144. }
  2145. MainActivityMessageToFragment("MainActivityToFMac0","Operate","Refresh");
  2146. /* MCU固件升级 */
  2147. if (UserGlobalVariable.Upgrade_Mcu_Status) {
  2148. if (UserGlobalVariable.Upgrade_Mcu_FW_Download_Flag) {
  2149. UserGlobalVariable.Upgrade_Mcu_FW_Download_Flag = false;
  2150. try {
  2151. String ftpIP = MacUpgradeInfoJson.get("ftpIP").toString();
  2152. int ftpPort = Integer.parseInt(MacUpgradeInfoJson.get("ftpPort").toString());
  2153. String ftpUser = MacUpgradeInfoJson.get("ftpUser").toString();
  2154. String ftpPasswd = MacUpgradeInfoJson.get("ftpPasswd").toString();
  2155. String ftpFilePath = MacUpgradeInfoJson.get("ftpFilePath").toString();
  2156. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#04.00->> ftpIP : " + ftpIP);
  2157. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#04.00->> ftpPort : " + ftpPort);
  2158. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#04.00->> ftpUser : " + ftpUser);
  2159. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#04.00->> ftpPasswd : " + ftpPasswd);
  2160. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#04.00->> ftpFilePath: " + ftpFilePath);
  2161. FtpTransferManager upgradeFtpTrans = new FtpTransferManager(ftpIP, ftpPort, ftpUser, ftpPasswd, ftpFilePath);
  2162. boolean res = upgradeFtpTrans.downloadFile(String.valueOf(getFilesDir()),30);
  2163. upgradeFtpTrans.shutdown();
  2164. if(res){
  2165. File firmware = new File(getFilesDir(),"XCT.rbl");
  2166. new CustomYModemManager().startUpgrade(firmware);
  2167. UserGlobalVariable.Upgrade_Mcu_Process_Status = true;
  2168. UserGlobalVariable.Upgrade_Mcu_Timeout_Value = 0;
  2169. MqttCustomPublishFunction("{\"cmd\":\"upgrade\",\"type\":\"mcu\",\"status\":\"4\"}");
  2170. }else{
  2171. Log.i(TAG_UPGRADE_OPERATE,"MCU固件下载失败.");
  2172. UserGlobalVariable.Upgrade_Mcu_Status = false;
  2173. MqttCustomPublishFunction("{\"cmd\":\"upgrade\",\"type\":\"mcu\",\"status\":\"0\"}");
  2174. }
  2175. } catch (JSONException e) {
  2176. // throw new RuntimeException(e);
  2177. Log.i(TAG_UPGRADE_OPERATE,"MCU固件升级信息获取有误");
  2178. }
  2179. }
  2180. if (UserGlobalVariable.Upgrade_Mcu_Process_Status) {
  2181. if (SerialManager.getInstance().getUpgradingFlag()) {
  2182. Log.i(TAG_UPGRADE_OPERATE,"MCU YModem升级操作进行中." + UserGlobalVariable.Upgrade_Mcu_Timeout_Value);
  2183. UserGlobalVariable.Upgrade_Mcu_Timeout_Value ++;
  2184. if(UserGlobalVariable.Upgrade_Mcu_Timeout_Value > 360){
  2185. UserGlobalVariable.Upgrade_Mcu_Timeout_Value = 0;
  2186. Log.i(TAG_UPGRADE_OPERATE,"MCU YModem升级操作异常超时.");
  2187. SerialManager.getInstance().setUpgrading(false);
  2188. serialManager.setDataProcessor(customJsonProcessorManager);
  2189. UserGlobalVariable.Upgrade_Mcu_Process_Status = false;
  2190. String endCmd = "{\"cmd\":\"paramconf\",\"ext\":{\"Demo_mode\":0}}";
  2191. SerialManager.getInstance().write(endCmd.getBytes());
  2192. UserGlobalVariable.Upgrade_Mcu_Status = false;
  2193. MqttCustomPublishFunction("{\"cmd\":\"upgrade\",\"type\":\"mcu\",\"status\":\"5\"}");
  2194. }
  2195. } else {
  2196. Log.i(TAG_UPGRADE_OPERATE,"MCU YModem升级操作结束.");
  2197. serialManager.setDataProcessor(customJsonProcessorManager);
  2198. UserGlobalVariable.Upgrade_Mcu_Process_Status = false;
  2199. UserGlobalVariable.Upgrade_Mcu_Status = false;
  2200. if(UserGlobalVariable.Upgrade_Mcu_Timeout_Flag){
  2201. MqttCustomPublishFunction("{\"cmd\":\"upgrade\",\"type\":\"mcu\",\"status\":\"6\"}");
  2202. }else{
  2203. MqttCustomPublishFunction("{\"cmd\":\"upgrade\",\"type\":\"mcu\",\"status\":\"1\"}");
  2204. }
  2205. String endCmd = "{\"cmd\":\"paramconf\",\"ext\":{\"Demo_mode\":0}}";
  2206. SerialManager.getInstance().write(endCmd.getBytes());
  2207. UserGlobalVariable.Upgrade_Mcu_Timeout_Flag = false;
  2208. }
  2209. }
  2210. }
  2211. /* 自动拍照上传 */
  2212. if (UserGlobalVariable.Camera_TimingTakePhoto_Flag) {
  2213. UserGlobalVariable.Camera_TimingTakePhoto_Flag = false;
  2214. Log.i(TAG_CAMERA_OPERATE, "开始拍照上传");
  2215. AutoTakePhotoAndUploadThread();
  2216. }
  2217. /* 读取/设置相机参数 */
  2218. if(UserGlobalVariable.Camera_Set_Parameters_Flag){
  2219. UserGlobalVariable.Camera_Set_Parameters_Flag = false;
  2220. Log.i(TAG_CAMERA_OPERATE, "远程设置相机参数");
  2221. RemoteSetCameraParametersThread();
  2222. }
  2223. /* 自动上传缓存照片 */
  2224. AutoUploadPhotosToFTP();
  2225. /* 静默升级 */
  2226. if (UserGlobalVariable.Upgrade_APP_Operate_Flag) {
  2227. UserGlobalVariable.Upgrade_APP_Operate_Flag = false;
  2228. UserGlobalVariable.Upgrade_APP_Operate_Status = true;
  2229. String appUpgradeStart = "{\"cmd\":\"paramconf\",\"ext\":{\"Demo_mode\":1}}";
  2230. SerialManager.getInstance().write(appUpgradeStart.getBytes());
  2231. //删除本地缓存的旧安装包
  2232. MacAppUpgradeDeleteApkIfExists();
  2233. try {
  2234. String ftpIP = MacUpgradeInfoJson.get("ftpIP").toString();
  2235. int ftpPort = Integer.parseInt(MacUpgradeInfoJson.get("ftpPort").toString());
  2236. String ftpUser = MacUpgradeInfoJson.get("ftpUser").toString();
  2237. String ftpPasswd = MacUpgradeInfoJson.get("ftpPasswd").toString();
  2238. String ftpFilePath = MacUpgradeInfoJson.get("ftpFilePath").toString();
  2239. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.00->> ftpIP : " + ftpIP);
  2240. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.00->> ftpPort : " + ftpPort);
  2241. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.00->> ftpUser : " + ftpUser);
  2242. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.00->> ftpPasswd : " + ftpPasswd);
  2243. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.00->> ftpFilePath: " + ftpFilePath);
  2244. FtpTransferManager apkFileTransByFTP = new FtpTransferManager(ftpIP, ftpPort, ftpUser, ftpPasswd, ftpFilePath);
  2245. boolean res = apkFileTransByFTP.downloadFile(String.valueOf(getFilesDir()),180);
  2246. apkFileTransByFTP.shutdown();
  2247. if (res) {
  2248. MacExecuteShellSilentFlag = true;
  2249. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.00->> APK下载成功.");
  2250. MqttCustomPublishFunction("{\"cmd\":\"upgrade\",\"type\":\"app\",\"status\":\"1\"}");
  2251. }else{
  2252. MqttCustomPublishFunction("{\"cmd\":\"upgrade\",\"type\":\"app\",\"status\":\"0\"}");
  2253. }
  2254. /* 成功或失败都退出'演示模式',安卓设备不会立即断电,最短断电时间为数据上传周期后. */
  2255. appUpgradeStart = "{\"cmd\":\"paramconf\",\"ext\":{\"Demo_mode\":0}}";
  2256. SerialManager.getInstance().write(appUpgradeStart.getBytes());
  2257. UserGlobalVariable.Upgrade_APP_Operate_Status = false;
  2258. } catch (JSONException e) {
  2259. // throw new RuntimeException(e);
  2260. appUpgradeStart = "{\"cmd\":\"paramconf\",\"ext\":{\"Demo_mode\":0}}";
  2261. SerialManager.getInstance().write(appUpgradeStart.getBytes());
  2262. UserGlobalVariable.Upgrade_APP_Operate_Status = false;
  2263. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.00->> APP应用升级信息获取有误");
  2264. }
  2265. }
  2266. if (MacExecuteShellSilentFlag) {
  2267. MacExecuteShellSilentFlag = false;
  2268. /*if (USER_PLATFORM_TYPE == PLATFROM_TYPE_WANGFEI) {
  2269. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.01->> 网飞设备由天工平台安装.");
  2270. } else {*/
  2271. Log.i(TAG_UPGRADE_OPERATE,"Upgrade#02.01->> 执行安装操作.");
  2272. MacExecuteShellSilent(String.valueOf(new File(getFilesDir(),"XCT.apk")));
  2273. //}
  2274. }
  2275. /* 语音播放 */
  2276. MainActivityVoiceMediaPlayer(VoicePlayingID);
  2277. /* 线程延时 */
  2278. try {
  2279. Thread.sleep(1000);
  2280. } catch (InterruptedException e) {
  2281. throw new RuntimeException(e);
  2282. }
  2283. }
  2284. }
  2285. }
  2286. @Override
  2287. protected void onDestroy() {
  2288. super.onDestroy();
  2289. }
  2290. }