1
0

MainActivity.java 17 KB

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