MainActivity.java 17 KB

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