1
0

MainActivity.java 18 KB

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