1
0

MainActivity.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. // APKUpdateDownload.getInstance().downloadAPK(MainActivity.this, getApplication(), path);
  187. } catch (Exception e) {
  188. Log.e(TAG, "onCreate: 更新版本监听失败! ", e);
  189. }
  190. });
  191. }
  192. private void executeShell(ICHPublishClient ichPublishClient){
  193. ichPublishClient.subscribe(String.format(ICHTopic.EXECUTE_SHELL_SCRIPT, BaseUtils.getClientId()), (msgId, msg) -> {
  194. if (msg != null) {
  195. try {
  196. ShellVo shellVo = JacksonUtils.objectmapper.readValue(msg.getPayload(), ShellVo.class);
  197. ShellVo result = shellVo;
  198. if (shellVo != null && shellVo.getScript() != null && "".equals(shellVo.getScript()) && shellVo.getScript().length() > 0) {
  199. BaseUtils.executeShell(shellVo);
  200. } else {
  201. result = new ShellVo();
  202. result.setResult("命令为空, 不可执行!");
  203. }
  204. MqttMessage mqttMessage = new MqttMessage();
  205. mqttMessage.setQos(1);
  206. mqttMessage.setPayload(JacksonUtils.objectmapper.writeValueAsString(result).getBytes());
  207. ichPublishClient.publish(String.format(ICHTopic.EXECUTE_SHELL_SCRIPT_RESPONSE, BaseUtils.getClientId()), mqttMessage);
  208. } catch (Exception e) {
  209. Log.e(TAG, "onCreate: 发送执行脚本结果失败! ", e);
  210. }
  211. }
  212. });
  213. }
  214. private void openLocker(ICHPublishClient ichPublishClient) {
  215. ichPublishClient.subscribe(ICHTopic.LOCK + BaseUtils.getClientId(), (s, msg) -> {
  216. String payload = new String(msg.getPayload());
  217. ObjectMapper objectMapper = JacksonUtils.objectmapper;
  218. Message message = objectMapper.readValue(payload, Message.class);
  219. Log.i(TAG, "onCreate: message id: " + s + "--------------消息体: " + message);
  220. DeviceControl.unlockLocker(message.getSection(), message.getPort(), (var1, var2) -> {
  221. Log.i(TAG, "onCreate: 开锁返回码: " + var1 + "--------------返回消息: " + Arrays.asList(var2));
  222. MqttMessage mqttMessage;
  223. if (var1 != 0) {
  224. try {
  225. mqttMessage = wrapMessage(message, objectMapper);
  226. ichPublishClient.publish(String.format(ICHTopic.CALLBACK_FAILED, BaseUtils.getClientId()), mqttMessage);
  227. } catch (JsonProcessingException e) {
  228. Log.e(TAG, "onCreate: ---------------------序列化开锁错误消息失败! ", e);
  229. } catch (Exception e) {
  230. Log.e(TAG, "onCreate: ---------------------未知错误! ", e);
  231. }
  232. } else {
  233. // TODO 暂时不做 成功需要不断去请求查询锁是否关闭, 关闭后推送成功消息
  234. Log.i(TAG, "onCreate: -------------------------开锁成功");
  235. // AtomicBoolean atomicBoolean = new AtomicBoolean(true);
  236. // AtomicInteger atomicInteger = new AtomicInteger(5);
  237. // do {
  238. // try {
  239. // TimeUnit.SECONDS.sleep(30);
  240. // } catch (InterruptedException e) {
  241. // Log.e(TAG, "onCreate: 等待查询锁状态时线程中断! ", e);
  242. // }
  243. // DeviceControl.queryLocker(message.getSection(), message.getPort(), (var3, var4) -> {
  244. // List<String> strings = Arrays.asList(var4);
  245. // if (var3 == 0 && strings.size() > 0 && !strings.get(0).equals("locked")) {
  246. // atomicBoolean.set(false);
  247. // }
  248. // atomicInteger.decrementAndGet();
  249. // });
  250. // if (atomicInteger.get() <= 0) {
  251. // atomicBoolean.set(false);
  252. // }
  253. // } while(atomicBoolean.get());
  254. try {
  255. mqttMessage = wrapMessage(message, objectMapper);
  256. // if (atomicInteger.get() <= 0) {
  257. // message.setCause("长时间未关闭柜门!");
  258. // mqttMessage.setPayload(objectMapper.writeValueAsBytes(message));
  259. // ichPublishClient.publish(String.format(ICHTopic.CALLBACK_FAILED, BaseUtils.getClientId()), mqttMessage);
  260. // }
  261. ichPublishClient.publish(String.format(ICHTopic.CALLBACK_SUCCESS, BaseUtils.getClientId()), mqttMessage);
  262. } catch (JsonProcessingException e) {
  263. Log.e(TAG, "onCreate: ---------------------序列化开锁成功消息失败! ", e);
  264. } catch (RuntimeException e) {
  265. Log.e(TAG, "onCreate: ---------------------未知错误! ", e);
  266. }
  267. }
  268. });
  269. });
  270. }
  271. private void cabinetInfoReport(ICHPublishClient ichPublishClient){
  272. String appVersion = BaseUtils.getAppVersion(getApplicationContext());
  273. String androidVersion = BaseUtils.getVersionName();
  274. CountDownLatch countDownLatch = new CountDownLatch(10);
  275. Cabinet cabinet = DeviceControl.queryCabinetInfo(countDownLatch);
  276. try {
  277. countDownLatch.await();
  278. } catch (InterruptedException e) {
  279. e.printStackTrace();
  280. }
  281. cabinet.setClientId(BaseUtils.getClientId());
  282. cabinet.setSoftwareVersion(appVersion);
  283. cabinet.setAndroidVersion(androidVersion);
  284. cabinet.setSoftwareType("android");
  285. cabinet.setImei(BaseUtils.getIMEI(getApplicationContext()));
  286. cabinet.setMacIpv4(BaseUtils.getIp());
  287. cabinet.setMacIpv6("unknown");
  288. cabinet.setNetType("111");
  289. cabinet.setPlatType("S905");
  290. cabinet.setSim("111");
  291. cabinet.setWifiSSid("111");
  292. ObjectMapper objectMapper = JacksonUtils.objectmapper;
  293. try {
  294. String jsonData = objectMapper.writeValueAsString(cabinet);
  295. Log.i(TAG, "onCreate: jsonData===============>" + jsonData);
  296. MqttMessage message = new MqttMessage();
  297. message.setQos(1);
  298. message.setPayload(jsonData.getBytes());
  299. ichPublishClient.publish(String.format(ICHTopic.CABINET_INFO_REPORT, BaseUtils.getClientId()), message);
  300. } catch (JsonProcessingException e) {
  301. Log.e(TAG, "onCreate: 解析成JSON失败!", e);
  302. }
  303. }
  304. @Override
  305. public boolean dispatchKeyEvent(KeyEvent event) {
  306. if (null != scanGunKeyEventHelper) {
  307. scanGunKeyEventHelper.analysisKeyEvent(event);
  308. }
  309. return true;
  310. }
  311. @Override
  312. public boolean onCreateOptionsMenu(Menu menu) {
  313. // Inflate the menu; this adds items to the action bar if it is present.
  314. // getMenuInflater().inflate(R.menu.menu_main, menu);
  315. return true;
  316. }
  317. @Override
  318. public boolean onOptionsItemSelected(MenuItem item) {
  319. // Handle action bar item clicks here. The action bar will
  320. // automatically handle clicks on the Home/Up button, so long
  321. // as you specify a parent activity in AndroidManifest.xml.
  322. // int id = item.getItemId();
  323. // //noinspection SimplifiableIfStatement
  324. // if (id == R.id.action_settings) {
  325. // return true;
  326. // }
  327. return super.onOptionsItemSelected(item);
  328. }
  329. @Override
  330. public boolean onSupportNavigateUp() {
  331. NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
  332. return NavigationUI.navigateUp(navController, appBarConfiguration)
  333. || super.onSupportNavigateUp();
  334. }
  335. private MqttMessage wrapMessage(Message message, ObjectMapper objectMapper) throws JsonProcessingException {
  336. MqttMessage mqttMessage = new MqttMessage();
  337. Message failedMsg = new Message();
  338. // TODO 失败原因枚举
  339. failedMsg.setCause("失败原因枚举");
  340. failedMsg.setMessageId(message.getMessageId());
  341. failedMsg.setClientId(message.getClientId());
  342. failedMsg.setCmd(message.getCmd());
  343. failedMsg.setDatetime(message.getDatetime());
  344. failedMsg.setPort(message.getPort());
  345. failedMsg.setScene(message.getScene());
  346. failedMsg.setSection(message.getSection());
  347. mqttMessage.setQos(1);
  348. mqttMessage.setPayload(objectMapper.writeValueAsBytes(failedMsg));
  349. return mqttMessage;
  350. }
  351. public Map<String, Bundle> getBundleMap() {
  352. return bundleMap;
  353. }
  354. public Map<String, String> getConfigMap() {
  355. return configMap;
  356. }
  357. }