MainActivity.java 18 KB

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