MainActivity.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. package com.emato.ich;
  2. import android.os.Bundle;
  3. import com.cherry.sdk.controller.utils.ScanGunKeyEventHelper;
  4. import com.emato.ich.api.ICSPApi;
  5. import com.emato.ich.api.ICSPClient;
  6. import com.emato.ich.api.ICSPConstant;
  7. import com.emato.ich.api.ICSPResponseCodeEnum;
  8. import com.emato.ich.api.SystemConfigConstant;
  9. import com.emato.ich.crash.CrashApplication;
  10. import com.emato.ich.device.DeviceControl;
  11. import com.emato.ich.entity.Cabinet;
  12. import com.emato.ich.entity.Message;
  13. import com.emato.ich.entity.vo.ResponseData;
  14. import com.emato.ich.entity.vo.ShellVo;
  15. import com.emato.ich.local.LocalStorage;
  16. import com.emato.ich.message.ICHPublishClient;
  17. import com.emato.ich.message.ICHTopic;
  18. import com.emato.ich.update.APKUpdateDownload;
  19. import com.emato.ich.update.OnDownloadListener;
  20. import com.emato.ich.utils.BaseUtils;
  21. import com.emato.ich.utils.JacksonUtils;
  22. import com.emato.ich.utils.StringUtils;
  23. import com.fasterxml.jackson.core.JsonProcessingException;
  24. import com.fasterxml.jackson.core.type.TypeReference;
  25. import com.fasterxml.jackson.databind.ObjectMapper;
  26. import androidx.appcompat.app.AppCompatActivity;
  27. import android.util.Log;
  28. import android.view.KeyEvent;
  29. import androidx.navigation.NavController;
  30. import androidx.navigation.Navigation;
  31. import androidx.navigation.ui.AppBarConfiguration;
  32. import androidx.navigation.ui.NavigationUI;
  33. import com.emato.ich.databinding.ActivityMainBinding;
  34. import com.xuexiang.xupdate.XUpdate;
  35. import android.view.Menu;
  36. import android.view.MenuItem;
  37. import android.view.WindowManager;
  38. import org.eclipse.paho.client.mqttv3.MqttMessage;
  39. import org.jetbrains.annotations.NotNull;
  40. import java.io.File;
  41. import java.io.FileOutputStream;
  42. import java.io.IOException;
  43. import java.io.InputStream;
  44. import java.util.Arrays;
  45. import java.util.Collections;
  46. import java.util.Map;
  47. import java.util.concurrent.ConcurrentHashMap;
  48. import java.util.concurrent.CountDownLatch;
  49. import okhttp3.Call;
  50. import okhttp3.Callback;
  51. import okhttp3.Response;
  52. public class MainActivity extends AppCompatActivity {
  53. private AppBarConfiguration appBarConfiguration;
  54. private ActivityMainBinding binding;
  55. public ScanGunKeyEventHelper scanGunKeyEventHelper;
  56. private final Map<String, Bundle> bundleMap = new ConcurrentHashMap<>();
  57. private final Map<String, String> configMap = new ConcurrentHashMap<>();
  58. private static final String TAG = MainActivity.class.getName();
  59. @Override
  60. protected void onCreate(Bundle savedInstanceState) {
  61. super.onCreate(savedInstanceState);
  62. binding = ActivityMainBinding.inflate(getLayoutInflater());
  63. // 强制关闭输入法
  64. getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
  65. setContentView(binding.getRoot());
  66. // 自动重启
  67. ((CrashApplication) getApplication()).addActivity(MainActivity.this);
  68. // 获取系统配置
  69. getSystemConfig();
  70. ICHPublishClient ichPublishClient = ICHPublishClient.getInstance();
  71. ICHTopic.CLIENT_ID = BaseUtils.getClientId();
  72. // 订阅主题
  73. // ICHSubscribeClient ichSubscribeClient = ICHSubscribeClient.getInstance();
  74. openLocker(ichPublishClient);
  75. // 注册柜子信息
  76. cabinetInfoReport(ichPublishClient);
  77. // TODO 更新版本监听
  78. autoUpdateVersion(ichPublishClient);
  79. // TODO 监听shell命令脚本
  80. executeShell(ichPublishClient);
  81. }
  82. private void getSystemConfig(){
  83. ICSPClient.getSystemConfig("", BaseUtils.getClientId(), new Callback() {
  84. @Override
  85. public void onFailure(@NotNull Call call, @NotNull IOException e) {
  86. Log.e(TAG, "onFailure: 获取系统配置错误! 网络错误! ", e);
  87. }
  88. @Override
  89. public void onResponse
  90. (@NotNull Call call, @NotNull Response response) throws IOException {
  91. try {
  92. OnDownloadListener listener = new OnDownloadListener() {
  93. @Override
  94. public void onDownloadSuccess(File file) {
  95. }
  96. @Override
  97. public void onDownloading(int progress) {
  98. }
  99. @Override
  100. public void onDownloadFailed(Exception e) {
  101. }
  102. };
  103. String parseResponse = ICSPClient.isSuccessfulAndParseResponse(response);
  104. ObjectMapper objectMapper = JacksonUtils.objectmapper;
  105. ResponseData<Map<String, String>> readValue = objectMapper.readValue(parseResponse, new TypeReference<ResponseData<Map<String, String>>>() {
  106. });
  107. if (null != readValue && readValue.getCode().equals(ICSPResponseCodeEnum.OK.getCode())) {
  108. configMap.putAll(readValue.getData());
  109. // 系统配置的session过期时间
  110. String time = configMap.get(SystemConfigConstant.deliverer_token_expire_seconds);
  111. if (!StringUtils.isNullOrEmpty(time)) {
  112. LocalStorage.getInstance().getSession().setTime(Long.parseLong(time));
  113. }
  114. String qrcode_url = configMap.get(SystemConfigConstant.cabinet_take_object_qrcode_url);
  115. try {
  116. ICSPClient.download(qrcode_url, new Callback() {
  117. @Override
  118. public void onFailure(@NotNull Call call, @NotNull IOException e) {
  119. }
  120. @Override
  121. public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
  122. InputStream is = null;
  123. byte[] buf = new byte[2048];
  124. int len = 0;
  125. FileOutputStream fos = null;
  126. final String destFileDir = "res/drawable/";
  127. String destFileName = "e_mp_qrcode_8x8.jpg";
  128. //储存下载文件的目录
  129. File dir = new File(getApplication().getFilesDir().getAbsolutePath() + "/" +destFileDir);
  130. if (!dir.exists()) {
  131. dir.mkdirs();
  132. }
  133. // destFileName = apk_url.substring(apk_url.lastIndexOf('/'), apk_url.length() - 1);
  134. File file = new File(dir, destFileName);
  135. try {
  136. is = response.body().byteStream();
  137. long total = response.body().contentLength();
  138. fos = new FileOutputStream(file);
  139. long sum = 0;
  140. while ((len = is.read(buf)) != -1) {
  141. fos.write(buf, 0, len);
  142. sum += len;
  143. int progress = (int) (sum * 1.0f / total * 100);
  144. //下载中更新进度条
  145. listener.onDownloading(progress);
  146. }
  147. fos.flush();
  148. //下载完成
  149. listener.onDownloadSuccess(file);
  150. } catch (Exception e) {
  151. listener.onDownloadFailed(e);
  152. }finally {
  153. try {
  154. if (is != null) {
  155. is.close();
  156. }
  157. if (fos != null) {
  158. fos.close();
  159. }
  160. } catch (IOException e) {
  161. }
  162. }
  163. }
  164. }, listener);
  165. } catch (Exception e) {
  166. }
  167. Log.i(TAG, "onResponse: 获取系统配置成功! ");
  168. } else {
  169. Log.w(TAG, "onResponse: code==>" + readValue.getCode() + ", msg==>" + readValue.getMsg());
  170. }
  171. } catch (RuntimeException e) {
  172. Log.e(TAG, "onResponse: 获取系统配置错误! 未知错误! ", e);
  173. }
  174. }
  175. });
  176. }
  177. private void autoUpdateVersion(ICHPublishClient ichPublishClient) {
  178. ichPublishClient.subscribe(String.format(ICHTopic.APK_UPDATE_PATH, BaseUtils.getClientId()), (msgId, msg) -> {
  179. try {
  180. // String path = new String(msg.getPayload());
  181. // 发起请求下载APK
  182. XUpdate.newBuild(this)
  183. .updateUrl(ICSPApi.GET_UPDATE_PATH.getUrl())
  184. .isAutoMode(true) // 如果需要完全无人干预,自动更新,需要root权限【静默安装需要】
  185. .update();
  186. Log.i(TAG, "autoUpdateVersion: ====================================>更新完成! ");
  187. // APKUpdateDownload.getInstance().downloadAPK(MainActivity.this, getApplication(), path);
  188. } catch (Exception e) {
  189. Log.e(TAG, "onCreate: 更新版本监听失败! ", e);
  190. }
  191. });
  192. }
  193. private void executeShell(ICHPublishClient ichPublishClient){
  194. ichPublishClient.subscribe(String.format(ICHTopic.EXECUTE_SHELL_SCRIPT, BaseUtils.getClientId()), (msgId, msg) -> {
  195. if (msg != null) {
  196. try {
  197. ShellVo shellVo = JacksonUtils.objectmapper.readValue(msg.getPayload(), ShellVo.class);
  198. ShellVo result = shellVo;
  199. if (shellVo != null && shellVo.getScript() != null && "".equals(shellVo.getScript()) && shellVo.getScript().length() > 0) {
  200. BaseUtils.executeShell(shellVo);
  201. } else {
  202. result = new ShellVo();
  203. result.setResult("命令为空, 不可执行!");
  204. }
  205. MqttMessage mqttMessage = new MqttMessage();
  206. mqttMessage.setQos(1);
  207. mqttMessage.setPayload(JacksonUtils.objectmapper.writeValueAsString(result).getBytes());
  208. ichPublishClient.publish(String.format(ICHTopic.EXECUTE_SHELL_SCRIPT_RESPONSE, BaseUtils.getClientId()), mqttMessage);
  209. } catch (Exception e) {
  210. Log.e(TAG, "onCreate: 发送执行脚本结果失败! ", e);
  211. }
  212. }
  213. });
  214. }
  215. private void openLocker(ICHPublishClient ichPublishClient) {
  216. ichPublishClient.subscribe(ICHTopic.LOCK + BaseUtils.getClientId(), (s, msg) -> {
  217. String payload = new String(msg.getPayload());
  218. ObjectMapper objectMapper = JacksonUtils.objectmapper;
  219. Message message = objectMapper.readValue(payload, Message.class);
  220. Log.i(TAG, "onCreate: message id: " + s + "--------------消息体: " + message);
  221. DeviceControl.unlockLocker(message.getSection(), message.getPort(), (var1, var2) -> {
  222. Log.i(TAG, "onCreate: 开锁返回码: " + var1 + "--------------返回消息: " + Arrays.asList(var2));
  223. MqttMessage mqttMessage;
  224. if (var1 != 0) {
  225. try {
  226. mqttMessage = wrapMessage(message, objectMapper);
  227. ichPublishClient.publish(String.format(ICHTopic.CALLBACK_FAILED, BaseUtils.getClientId()), mqttMessage);
  228. } catch (JsonProcessingException e) {
  229. Log.e(TAG, "onCreate: ---------------------序列化开锁错误消息失败! ", e);
  230. } catch (Exception e) {
  231. Log.e(TAG, "onCreate: ---------------------未知错误! ", e);
  232. }
  233. } else {
  234. // TODO 暂时不做 成功需要不断去请求查询锁是否关闭, 关闭后推送成功消息
  235. Log.i(TAG, "onCreate: -------------------------开锁成功");
  236. // AtomicBoolean atomicBoolean = new AtomicBoolean(true);
  237. // AtomicInteger atomicInteger = new AtomicInteger(5);
  238. // do {
  239. // try {
  240. // TimeUnit.SECONDS.sleep(30);
  241. // } catch (InterruptedException e) {
  242. // Log.e(TAG, "onCreate: 等待查询锁状态时线程中断! ", e);
  243. // }
  244. // DeviceControl.queryLocker(message.getSection(), message.getPort(), (var3, var4) -> {
  245. // List<String> strings = Arrays.asList(var4);
  246. // if (var3 == 0 && strings.size() > 0 && !strings.get(0).equals("locked")) {
  247. // atomicBoolean.set(false);
  248. // }
  249. // atomicInteger.decrementAndGet();
  250. // });
  251. // if (atomicInteger.get() <= 0) {
  252. // atomicBoolean.set(false);
  253. // }
  254. // } while(atomicBoolean.get());
  255. try {
  256. mqttMessage = wrapMessage(message, objectMapper);
  257. // if (atomicInteger.get() <= 0) {
  258. // message.setCause("长时间未关闭柜门!");
  259. // mqttMessage.setPayload(objectMapper.writeValueAsBytes(message));
  260. // ichPublishClient.publish(String.format(ICHTopic.CALLBACK_FAILED, BaseUtils.getClientId()), mqttMessage);
  261. // }
  262. ichPublishClient.publish(String.format(ICHTopic.CALLBACK_SUCCESS, BaseUtils.getClientId()), mqttMessage);
  263. } catch (JsonProcessingException e) {
  264. Log.e(TAG, "onCreate: ---------------------序列化开锁成功消息失败! ", e);
  265. } catch (RuntimeException e) {
  266. Log.e(TAG, "onCreate: ---------------------未知错误! ", e);
  267. }
  268. }
  269. });
  270. });
  271. }
  272. private void cabinetInfoReport(ICHPublishClient ichPublishClient){
  273. String appVersion = BaseUtils.getAppVersion(getApplicationContext());
  274. String androidVersion = BaseUtils.getVersionName();
  275. CountDownLatch countDownLatch = new CountDownLatch(10);
  276. Cabinet cabinet = DeviceControl.queryCabinetInfo(countDownLatch);
  277. try {
  278. countDownLatch.await();
  279. } catch (InterruptedException e) {
  280. e.printStackTrace();
  281. }
  282. cabinet.setClientId(BaseUtils.getClientId());
  283. cabinet.setSoftwareVersion(appVersion);
  284. cabinet.setAndroidVersion(androidVersion);
  285. cabinet.setSoftwareType("android");
  286. cabinet.setImei(BaseUtils.getIMEI(getApplicationContext()));
  287. cabinet.setMacIpv4(BaseUtils.getIp());
  288. cabinet.setMacIpv6("unknown");
  289. cabinet.setNetType("111");
  290. cabinet.setPlatType("S905");
  291. cabinet.setSim("111");
  292. cabinet.setWifiSSid("111");
  293. ObjectMapper objectMapper = JacksonUtils.objectmapper;
  294. try {
  295. String jsonData = objectMapper.writeValueAsString(cabinet);
  296. Log.i(TAG, "onCreate: jsonData===============>" + jsonData);
  297. MqttMessage message = new MqttMessage();
  298. message.setQos(1);
  299. message.setPayload(jsonData.getBytes());
  300. ichPublishClient.publish(String.format(ICHTopic.CABINET_INFO_REPORT, BaseUtils.getClientId()), message);
  301. } catch (JsonProcessingException e) {
  302. Log.e(TAG, "onCreate: 解析成JSON失败!", e);
  303. }
  304. }
  305. @Override
  306. public boolean dispatchKeyEvent(KeyEvent event) {
  307. if (null != scanGunKeyEventHelper) {
  308. scanGunKeyEventHelper.analysisKeyEvent(event);
  309. }
  310. return true;
  311. }
  312. @Override
  313. public boolean onCreateOptionsMenu(Menu menu) {
  314. // Inflate the menu; this adds items to the action bar if it is present.
  315. // getMenuInflater().inflate(R.menu.menu_main, menu);
  316. return true;
  317. }
  318. @Override
  319. public boolean onOptionsItemSelected(MenuItem item) {
  320. // Handle action bar item clicks here. The action bar will
  321. // automatically handle clicks on the Home/Up button, so long
  322. // as you specify a parent activity in AndroidManifest.xml.
  323. // int id = item.getItemId();
  324. // //noinspection SimplifiableIfStatement
  325. // if (id == R.id.action_settings) {
  326. // return true;
  327. // }
  328. return super.onOptionsItemSelected(item);
  329. }
  330. @Override
  331. public boolean onSupportNavigateUp() {
  332. NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
  333. return NavigationUI.navigateUp(navController, appBarConfiguration)
  334. || super.onSupportNavigateUp();
  335. }
  336. private MqttMessage wrapMessage(Message message, ObjectMapper objectMapper) throws JsonProcessingException {
  337. MqttMessage mqttMessage = new MqttMessage();
  338. Message failedMsg = new Message();
  339. // TODO 失败原因枚举
  340. failedMsg.setCause("失败原因枚举");
  341. failedMsg.setMessageId(message.getMessageId());
  342. failedMsg.setClientId(message.getClientId());
  343. failedMsg.setCmd(message.getCmd());
  344. failedMsg.setDatetime(message.getDatetime());
  345. failedMsg.setPort(message.getPort());
  346. failedMsg.setScene(message.getScene());
  347. failedMsg.setSection(message.getSection());
  348. mqttMessage.setQos(1);
  349. mqttMessage.setPayload(objectMapper.writeValueAsBytes(failedMsg));
  350. return mqttMessage;
  351. }
  352. public Map<String, Bundle> getBundleMap() {
  353. return bundleMap;
  354. }
  355. public Map<String, String> getConfigMap() {
  356. return configMap;
  357. }
  358. }