0
0

MainActivity.java 17 KB

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