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.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.ICHSubscribeClient;
  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.LoggingUtils;
  23. import com.emato.ich.utils.ResourceUtils;
  24. import com.emato.ich.utils.StringUtils;
  25. import com.fasterxml.jackson.core.JsonProcessingException;
  26. import com.fasterxml.jackson.core.type.TypeReference;
  27. import com.fasterxml.jackson.databind.ObjectMapper;
  28. import androidx.appcompat.app.AppCompatActivity;
  29. import android.provider.SyncStateContract;
  30. import android.util.Log;
  31. import android.view.KeyEvent;
  32. import androidx.navigation.NavController;
  33. import androidx.navigation.Navigation;
  34. import androidx.navigation.ui.AppBarConfiguration;
  35. import androidx.navigation.ui.NavigationUI;
  36. import com.emato.ich.databinding.ActivityMainBinding;
  37. import com.xuexiang.xupdate.XUpdate;
  38. import com.xuexiang.xupdate.aria.AriaDownloadServiceProxyImpl;
  39. import com.xuexiang.xupdate.aria.AriaDownloader;
  40. import com.xuexiang.xupdate.easy.EasyUpdate;
  41. import com.xuexiang.xupdate.easy.config.UpdateConfig;
  42. import com.xuexiang.xupdate.entity.UpdateEntity;
  43. import com.xuexiang.xupdate.proxy.impl.DefaultUpdateParser;
  44. import android.view.Menu;
  45. import android.view.MenuItem;
  46. import android.view.WindowManager;
  47. import org.eclipse.paho.client.mqttv3.MqttMessage;
  48. import org.jetbrains.annotations.NotNull;
  49. import java.io.File;
  50. import java.io.FileOutputStream;
  51. import java.io.IOException;
  52. import java.io.InputStream;
  53. import java.util.Arrays;
  54. import java.util.Collections;
  55. import java.util.Map;
  56. import java.util.concurrent.ConcurrentHashMap;
  57. import java.util.concurrent.CountDownLatch;
  58. import okhttp3.Call;
  59. import okhttp3.Callback;
  60. import okhttp3.Response;
  61. public class MainActivity extends AppCompatActivity {
  62. private AppBarConfiguration appBarConfiguration;
  63. private ActivityMainBinding binding;
  64. public ScanGunKeyEventHelper scanGunKeyEventHelper;
  65. private final Map<String, Bundle> bundleMap = new ConcurrentHashMap<>();
  66. private final Map<String, String> configMap = new ConcurrentHashMap<>();
  67. private static final String TAG = MainActivity.class.getName();
  68. @Override
  69. protected void onCreate(Bundle savedInstanceState) {
  70. super.onCreate(savedInstanceState);
  71. binding = ActivityMainBinding.inflate(getLayoutInflater());
  72. // 强制关闭输入法
  73. getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
  74. setContentView(binding.getRoot());
  75. // 自动重启
  76. ((CrashApplication) getApplication()).addActivity(MainActivity.this);
  77. // 获取系统配置
  78. getSystemConfig();
  79. ICHPublishClient ichPublishClient = ICHPublishClient.getInstance();
  80. ICHSubscribeClient ichSubscribeClient = ICHSubscribeClient.getInstance();
  81. ICHTopic.CLIENT_ID = BaseUtils.getClientId();
  82. // 订阅主题
  83. // ICHSubscribeClient ichSubscribeClient = ICHSubscribeClient.getInstance();
  84. openLocker(ichSubscribeClient, ichPublishClient);
  85. // 注册柜子信息
  86. cabinetInfoReport(ichPublishClient);
  87. // TODO 更新版本监听
  88. autoUpdateVersion(ichSubscribeClient);
  89. // TODO 监听shell命令脚本
  90. executeShell(ichSubscribeClient, ichPublishClient);
  91. }
  92. private void getSystemConfig(){
  93. ICSPClient.getSystemConfig("", BaseUtils.getClientId(), new Callback() {
  94. @Override
  95. public void onFailure(@NotNull Call call, @NotNull IOException e) {
  96. Log.e(TAG, "onFailure: 获取系统配置错误! 网络错误! ", e);
  97. LoggingUtils.sendErrorLog("业务异常: 获取系统配置错误! 网络错误! ", e);
  98. }
  99. @Override
  100. public void onResponse
  101. (@NotNull Call call, @NotNull Response response) throws IOException {
  102. try {
  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. Log.i(TAG, "onResponse: =====================>获取系统配置成功! ");
  115. } else {
  116. Log.w(TAG, "onResponse: code==>" + readValue.getCode() + ", msg==>" + readValue.getMsg());
  117. }
  118. } catch (RuntimeException e) {
  119. Log.e(TAG, "onResponse: 获取系统配置错误! 未知错误! ", e);
  120. }
  121. }
  122. });
  123. }
  124. private void autoUpdateVersion(ICHSubscribeClient ichSubscribeClient) {
  125. ichSubscribeClient.subscribe(String.format(ICHTopic.APK_UPDATE_PATH, BaseUtils.getClientId()), (msgId, msg) -> {
  126. try {
  127. // String path = new String(msg.getPayload());
  128. // 发起请求下载APK
  129. Log.i(TAG, "autoUpdateVersion: =====================>接收到服务器发来更新指令! 开始更新! ");
  130. UpdateConfig updateConfig = EasyUpdate.getUpdateConfig(getApplication());
  131. EasyUpdate.create(getBaseContext(), ICSPApi.GET_UPDATE_PATH.getUrl())
  132. .updateHttpService(AriaDownloader.getUpdateHttpService(getApplication()))
  133. .build()
  134. .update();
  135. // XUpdate.newBuild(this)
  136. // .updateUrl(ICSPApi.GET_UPDATE_PATH.getUrl())
  137. // .isAutoMode(true) // 如果需要完全无人干预,自动更新,需要root权限【静默安装需要】
  138. // .update();
  139. Log.i(TAG, "autoUpdateVersion: ====================================>更新中! ");
  140. // APKUpdateDownload.getInstance().downloadAPK(MainActivity.this, getApplication(), path);
  141. } catch (Exception e) {
  142. Log.e(TAG, "onCreate: =====================>更新版本监听失败! ", e);
  143. LoggingUtils.sendErrorLog("业务异常: 更新版本监听失败! ", e);
  144. }
  145. });
  146. }
  147. private UpdateEntity getUpdateEntityFromAssets() {
  148. // UpdateEntity updateEntity = new UpdateEntity();
  149. // updateEntity.setVersionCode(3);
  150. //
  151. //
  152. return new DefaultUpdateParser().parseJson(ResourceUtils.readStringFromAssert("update_test.json", getAssets()));
  153. }
  154. private void executeShell(ICHSubscribeClient ichSubscribeClient, ICHPublishClient ichPublishClient){
  155. ichSubscribeClient.subscribe(String.format(ICHTopic.EXECUTE_SHELL_SCRIPT, BaseUtils.getClientId()), (msgId, msg) -> {
  156. if (msg != null) {
  157. try {
  158. ShellVo shellVo = JacksonUtils.objectmapper.readValue(msg.getPayload(), ShellVo.class);
  159. ShellVo result = shellVo;
  160. if (shellVo != null && shellVo.getScript() != null && !"".equals(shellVo.getScript()) && shellVo.getScript().length() > 0) {
  161. Log.i(TAG, "executeShell: =====================>接到服务端传来命令: " + shellVo.getScript() + ", 参数: " + shellVo.getArgs());
  162. BaseUtils.executeShell(shellVo);
  163. } else {
  164. Log.i(TAG, "executeShell: =====================>接到服务端传来空命令, 不执行! ");
  165. result = new ShellVo();
  166. result.setResult("命令为空, 不可执行!");
  167. }
  168. MqttMessage mqttMessage = new MqttMessage();
  169. mqttMessage.setQos(1);
  170. mqttMessage.setPayload(JacksonUtils.objectmapper.writeValueAsString(result).getBytes());
  171. ichPublishClient.publish(String.format(ICHTopic.EXECUTE_SHELL_SCRIPT_RESPONSE, BaseUtils.getClientId()), mqttMessage);
  172. Log.i(TAG, "executeShell: =====================>发送命令执行结果成功! ");
  173. } catch (Exception e) {
  174. Log.e(TAG, "onCreate: 发送执行脚本结果失败! ", e);
  175. LoggingUtils.sendErrorLog("业务异常: 发送执行脚本结果失败! ", e);
  176. }
  177. }
  178. });
  179. }
  180. private void openLocker(ICHSubscribeClient ichSubscribeClient, ICHPublishClient ichPublishClient) {
  181. ichSubscribeClient.subscribe(ICHTopic.LOCK + BaseUtils.getClientId(), (s, msg) -> {
  182. String payload = new String(msg.getPayload());
  183. ObjectMapper objectMapper = JacksonUtils.objectmapper;
  184. Message message = objectMapper.readValue(payload, Message.class);
  185. Log.i(TAG, "onCreate: message id: " + s + "--------------消息体: " + message);
  186. Log.i(TAG, "openLocker: ==================>接到开锁消息: " + message);
  187. DeviceControl.unlockLocker(message.getSection(), message.getPort(), (var1, var2) -> {
  188. Log.i(TAG, "onCreate: 开锁返回码: " + var1 + "--------------返回消息: " + Arrays.asList(var2));
  189. MqttMessage mqttMessage;
  190. if (var1 != 0) {
  191. try {
  192. mqttMessage = wrapMessage(message, objectMapper);
  193. ichPublishClient.publish(String.format(ICHTopic.CALLBACK_FAILED, BaseUtils.getClientId()), mqttMessage);
  194. Log.i(TAG, "openLocker: ==================>发送开锁失败消息成功! 锁板id: " + message.getSection() + ", 端口: " + message.getPort());
  195. } catch (JsonProcessingException e) {
  196. Log.e(TAG, "onCreate: ---------------------序列化开锁错误消息失败! ", e);
  197. LoggingUtils.sendErrorLog("业务异常: 序列化开锁错误消息失败! ", e);
  198. } catch (Exception e) {
  199. Log.e(TAG, "onCreate: ---------------------未知错误! ", e);
  200. LoggingUtils.sendErrorLog("业务异常: 序列化开锁未知错误! ", e);
  201. }
  202. } else {
  203. // TODO 暂时不做 成功需要不断去请求查询锁是否关闭, 关闭后推送成功消息
  204. // AtomicBoolean atomicBoolean = new AtomicBoolean(true);
  205. // AtomicInteger atomicInteger = new AtomicInteger(5);
  206. // do {
  207. // try {
  208. // TimeUnit.SECONDS.sleep(30);
  209. // } catch (InterruptedException e) {
  210. // Log.e(TAG, "onCreate: 等待查询锁状态时线程中断! ", e);
  211. // }
  212. // DeviceControl.queryLocker(message.getSection(), message.getPort(), (var3, var4) -> {
  213. // List<String> strings = Arrays.asList(var4);
  214. // if (var3 == 0 && strings.size() > 0 && !strings.get(0).equals("locked")) {
  215. // atomicBoolean.set(false);
  216. // }
  217. // atomicInteger.decrementAndGet();
  218. // });
  219. // if (atomicInteger.get() <= 0) {
  220. // atomicBoolean.set(false);
  221. // }
  222. // } while(atomicBoolean.get());
  223. try {
  224. Log.i(TAG, "onCreate: =====================>开锁成功! 锁板id: " + message.getSection() + ", 端口: " + message.getPort());
  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. LoggingUtils.sendErrorLog("业务异常: 序列化开锁成功消息失败! ", e);
  235. } catch (RuntimeException e) {
  236. Log.e(TAG, "onCreate: ---------------------序列化开锁成功消息未知错误! ", e);
  237. LoggingUtils.sendErrorLog("业务异常: 开锁未知错误! ", e);
  238. }
  239. }
  240. });
  241. });
  242. }
  243. private void cabinetInfoReport(ICHPublishClient ichPublishClient){
  244. String appVersion = BaseUtils.getAppVersion(getApplicationContext());
  245. String androidVersion = BaseUtils.getVersionName();
  246. CountDownLatch countDownLatch = new CountDownLatch(10);
  247. Cabinet cabinet = DeviceControl.queryCabinetInfo(countDownLatch);
  248. try {
  249. countDownLatch.await();
  250. } catch (InterruptedException e) {
  251. e.printStackTrace();
  252. }
  253. cabinet.setClientId(BaseUtils.getClientId());
  254. cabinet.setSoftwareVersion(appVersion);
  255. cabinet.setAndroidVersion(androidVersion);
  256. cabinet.setSoftwareType("android");
  257. cabinet.setImei(BaseUtils.getIMEI(getApplicationContext()));
  258. cabinet.setMacIpv4(BaseUtils.getIp());
  259. cabinet.setMacIpv6("unknown");
  260. cabinet.setNetType("unknown");
  261. cabinet.setPlatType("S905");
  262. cabinet.setSim("unknown");
  263. cabinet.setWifiSSid("unknown");
  264. ObjectMapper objectMapper = JacksonUtils.objectmapper;
  265. try {
  266. String jsonData = objectMapper.writeValueAsString(cabinet);
  267. Log.i(TAG, "onCreate: jsonData===============>" + jsonData);
  268. MqttMessage message = new MqttMessage();
  269. message.setQos(1);
  270. message.setPayload(jsonData.getBytes());
  271. ichPublishClient.publish(String.format(ICHTopic.CABINET_INFO_REPORT, BaseUtils.getClientId()), message);
  272. Log.i(TAG, "cabinetInfoReport: ===============>上报柜子信息成功! ");
  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. }