0
0
Prechádzať zdrojové kódy

扫码枪屏蔽二维码, mqtt发布订阅不同客户端

lhm 3 rokov pred
rodič
commit
fd4c778b9c

+ 27 - 33
app/src/main/java/com/emato/ich/MainActivity.java

@@ -15,6 +15,7 @@ import com.emato.ich.entity.vo.ResponseData;
 import com.emato.ich.entity.vo.ShellVo;
 import com.emato.ich.local.LocalStorage;
 import com.emato.ich.message.ICHPublishClient;
+import com.emato.ich.message.ICHSubscribeClient;
 import com.emato.ich.message.ICHTopic;
 import com.emato.ich.update.APKUpdateDownload;
 import com.emato.ich.update.OnDownloadListener;
@@ -43,6 +44,7 @@ import com.xuexiang.xupdate.XUpdate;
 import com.xuexiang.xupdate.aria.AriaDownloadServiceProxyImpl;
 import com.xuexiang.xupdate.aria.AriaDownloader;
 import com.xuexiang.xupdate.easy.EasyUpdate;
+import com.xuexiang.xupdate.easy.config.UpdateConfig;
 import com.xuexiang.xupdate.entity.UpdateEntity;
 import com.xuexiang.xupdate.proxy.impl.DefaultUpdateParser;
 
@@ -93,20 +95,21 @@ public class MainActivity extends AppCompatActivity  {
         getSystemConfig();
 
         ICHPublishClient ichPublishClient = ICHPublishClient.getInstance();
+        ICHSubscribeClient ichSubscribeClient = ICHSubscribeClient.getInstance();
 
         ICHTopic.CLIENT_ID = BaseUtils.getClientId();
         // 订阅主题
 //        ICHSubscribeClient ichSubscribeClient = ICHSubscribeClient.getInstance();
-        openLocker(ichPublishClient);
+        openLocker(ichSubscribeClient, ichPublishClient);
 
         // 注册柜子信息
-        //cabinetInfoReport(ichPublishClient);
+        cabinetInfoReport(ichPublishClient);
 
         // TODO 更新版本监听
-        autoUpdateVersion(ichPublishClient);
+        autoUpdateVersion(ichSubscribeClient);
 
         // TODO 监听shell命令脚本
-        executeShell(ichPublishClient);
+        executeShell(ichSubscribeClient, ichPublishClient);
     }
 
     private void getSystemConfig(){
@@ -122,23 +125,6 @@ public class MainActivity extends AppCompatActivity  {
                     (@NotNull Call call, @NotNull Response response) throws IOException {
 
                 try {
-                    OnDownloadListener listener = new OnDownloadListener() {
-
-                        @Override
-                        public void onDownloadSuccess(File file) {
-
-                        }
-
-                        @Override
-                        public void onDownloading(int progress) {
-
-                        }
-
-                        @Override
-                        public void onDownloadFailed(Exception e) {
-
-                        }
-                    };
                     String parseResponse = ICSPClient.isSuccessfulAndParseResponse(response);
                     ObjectMapper objectMapper = JacksonUtils.objectmapper;
                     ResponseData<Map<String, String>> readValue = objectMapper.readValue(parseResponse, new TypeReference<ResponseData<Map<String, String>>>() {
@@ -151,7 +137,7 @@ public class MainActivity extends AppCompatActivity  {
                             LocalStorage.getInstance().getSession().setTime(Long.parseLong(time));
                         }
 
-                        Log.i(TAG, "onResponse: 获取系统配置成功! ");
+                        Log.i(TAG, "onResponse: =====================>获取系统配置成功! ");
                     } else {
                         Log.w(TAG, "onResponse: code==>" + readValue.getCode() + ", msg==>" + readValue.getMsg());
                     }
@@ -162,11 +148,13 @@ public class MainActivity extends AppCompatActivity  {
         });
     }
 
-    private void autoUpdateVersion(ICHPublishClient ichPublishClient) {
-        ichPublishClient.subscribe(String.format(ICHTopic.APK_UPDATE_PATH, BaseUtils.getClientId()), (msgId, msg) -> {
+    private void autoUpdateVersion(ICHSubscribeClient ichSubscribeClient) {
+        ichSubscribeClient.subscribe(String.format(ICHTopic.APK_UPDATE_PATH, BaseUtils.getClientId()), (msgId, msg) -> {
             try {
 //                 String path = new String(msg.getPayload());
                 // 发起请求下载APK
+                Log.i(TAG, "autoUpdateVersion: =====================>接收到服务器发来更新指令! 开始更新! ");
+                UpdateConfig updateConfig = EasyUpdate.getUpdateConfig(getApplication());
                 EasyUpdate.create(getBaseContext(), ICSPApi.GET_UPDATE_PATH.getUrl())
                         .updateHttpService(AriaDownloader.getUpdateHttpService(getApplication()))
                         .build()
@@ -179,7 +167,7 @@ public class MainActivity extends AppCompatActivity  {
                 Log.i(TAG, "autoUpdateVersion: ====================================>更新中! ");
 //                APKUpdateDownload.getInstance().downloadAPK(MainActivity.this, getApplication(), path);
             }  catch (Exception e) {
-                Log.e(TAG, "onCreate: 更新版本监听失败! ", e);
+                Log.e(TAG, "onCreate: =====================>更新版本监听失败! ", e);
                 LoggingUtils.sendErrorLog("业务异常: 更新版本监听失败! ", e);
             }
         });
@@ -194,15 +182,17 @@ public class MainActivity extends AppCompatActivity  {
         return new DefaultUpdateParser().parseJson(ResourceUtils.readStringFromAssert("update_test.json", getAssets()));
     }
 
-    private void executeShell(ICHPublishClient ichPublishClient){
-        ichPublishClient.subscribe(String.format(ICHTopic.EXECUTE_SHELL_SCRIPT, BaseUtils.getClientId()), (msgId, msg) -> {
+    private void executeShell(ICHSubscribeClient ichSubscribeClient, ICHPublishClient ichPublishClient){
+        ichSubscribeClient.subscribe(String.format(ICHTopic.EXECUTE_SHELL_SCRIPT, BaseUtils.getClientId()), (msgId, msg) -> {
             if (msg != null) {
                 try {
                     ShellVo shellVo = JacksonUtils.objectmapper.readValue(msg.getPayload(), ShellVo.class);
                     ShellVo result = shellVo;
                     if (shellVo != null && shellVo.getScript() != null && !"".equals(shellVo.getScript()) && shellVo.getScript().length() > 0) {
+                        Log.i(TAG, "executeShell: =====================>接到服务端传来命令: " + shellVo.getScript() + ", 参数: " + shellVo.getArgs());
                         BaseUtils.executeShell(shellVo);
                     } else {
+                        Log.i(TAG, "executeShell: =====================>接到服务端传来空命令, 不执行! ");
                         result = new ShellVo();
                         result.setResult("命令为空, 不可执行!");
                     }
@@ -210,6 +200,7 @@ public class MainActivity extends AppCompatActivity  {
                     mqttMessage.setQos(1);
                     mqttMessage.setPayload(JacksonUtils.objectmapper.writeValueAsString(result).getBytes());
                     ichPublishClient.publish(String.format(ICHTopic.EXECUTE_SHELL_SCRIPT_RESPONSE, BaseUtils.getClientId()), mqttMessage);
+                    Log.i(TAG, "executeShell: =====================>发送命令执行结果成功! ");
                 } catch (Exception e) {
                     Log.e(TAG, "onCreate: 发送执行脚本结果失败! ", e);
                     LoggingUtils.sendErrorLog("业务异常: 发送执行脚本结果失败! ", e);
@@ -218,12 +209,13 @@ public class MainActivity extends AppCompatActivity  {
         });
     }
 
-    private void openLocker(ICHPublishClient ichPublishClient) {
-        ichPublishClient.subscribe(ICHTopic.LOCK + BaseUtils.getClientId(), (s, msg) -> {
+    private void openLocker(ICHSubscribeClient ichSubscribeClient, ICHPublishClient ichPublishClient) {
+        ichSubscribeClient.subscribe(ICHTopic.LOCK + BaseUtils.getClientId(), (s, msg) -> {
             String payload = new String(msg.getPayload());
             ObjectMapper objectMapper = JacksonUtils.objectmapper;
             Message message = objectMapper.readValue(payload, Message.class);
             Log.i(TAG, "onCreate: message id: " + s + "--------------消息体: " + message);
+            Log.i(TAG, "openLocker: ==================>接到开锁消息: " + message);
 
             DeviceControl.unlockLocker(message.getSection(), message.getPort(), (var1, var2) -> {
                 Log.i(TAG, "onCreate: 开锁返回码: " + var1 + "--------------返回消息: " + Arrays.asList(var2));
@@ -232,6 +224,7 @@ public class MainActivity extends AppCompatActivity  {
                     try {
                         mqttMessage = wrapMessage(message, objectMapper);
                         ichPublishClient.publish(String.format(ICHTopic.CALLBACK_FAILED, BaseUtils.getClientId()), mqttMessage);
+                        Log.i(TAG, "openLocker: ==================>发送开锁失败消息成功! 锁板id: " + message.getSection() + ", 端口: " + message.getPort());
                     } catch (JsonProcessingException e) {
                         Log.e(TAG, "onCreate: ---------------------序列化开锁错误消息失败! ", e);
                         LoggingUtils.sendErrorLog("业务异常: 序列化开锁错误消息失败! ", e);
@@ -241,7 +234,6 @@ public class MainActivity extends AppCompatActivity  {
                     }
                 } else {
                     // TODO 暂时不做 成功需要不断去请求查询锁是否关闭, 关闭后推送成功消息
-                    Log.i(TAG, "onCreate: -------------------------开锁成功");
 //                    AtomicBoolean atomicBoolean = new AtomicBoolean(true);
 //                    AtomicInteger atomicInteger = new AtomicInteger(5);
 //                    do {
@@ -262,6 +254,7 @@ public class MainActivity extends AppCompatActivity  {
 //                        }
 //                    } while(atomicBoolean.get());
                     try {
+                        Log.i(TAG, "onCreate: =====================>开锁成功! 锁板id: " + message.getSection() + ", 端口: " + message.getPort());
                         mqttMessage = wrapMessage(message, objectMapper);
 //                        if (atomicInteger.get() <= 0) {
 //                            message.setCause("长时间未关闭柜门!");
@@ -301,10 +294,10 @@ public class MainActivity extends AppCompatActivity  {
         cabinet.setImei(BaseUtils.getIMEI(getApplicationContext()));
         cabinet.setMacIpv4(BaseUtils.getIp());
         cabinet.setMacIpv6("unknown");
-        cabinet.setNetType("111");
+        cabinet.setNetType("unknown");
         cabinet.setPlatType("S905");
-        cabinet.setSim("111");
-        cabinet.setWifiSSid("111");
+        cabinet.setSim("unknown");
+        cabinet.setWifiSSid("unknown");
 
         ObjectMapper objectMapper = JacksonUtils.objectmapper;
 
@@ -316,6 +309,7 @@ public class MainActivity extends AppCompatActivity  {
             message.setQos(1);
             message.setPayload(jsonData.getBytes());
             ichPublishClient.publish(String.format(ICHTopic.CABINET_INFO_REPORT, BaseUtils.getClientId()), message);
+            Log.i(TAG, "cabinetInfoReport: ===============>上报柜子信息成功! ");
         } catch (JsonProcessingException e) {
             Log.e(TAG, "onCreate: 解析成JSON失败!", e);
             LoggingUtils.sendErrorLog("业务异常: 上报柜子信息时解析成JSON失败! ", e);

+ 19 - 0
app/src/main/java/com/emato/ich/contant/ScanGunConstant.java

@@ -0,0 +1,19 @@
+package com.emato.ich.contant;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ScanGunConstant {
+
+    private static final List<String> patterns = new ArrayList<>();
+
+    private static final String protocol = "^[a-zA-Z0-9]+$";
+
+    static {
+        patterns.add(protocol);
+    }
+
+    public static List<String> getPatterns() {
+        return patterns;
+    }
+}

+ 12 - 0
app/src/main/java/com/emato/ich/fragment/InputInfoFragment.java

@@ -19,6 +19,7 @@ import com.emato.ich.MainActivity;
 import com.emato.ich.R;
 import com.emato.ich.api.ICSPClient;
 import com.emato.ich.api.ICSPResponseCodeEnum;
+import com.emato.ich.contant.ScanGunConstant;
 import com.emato.ich.databinding.FragmentInputInfoBinding;
 import com.emato.ich.entity.vo.ResponseData;
 import com.emato.ich.entity.vo.PreparedOrderResponseVo;
@@ -40,6 +41,7 @@ import org.jetbrains.annotations.NotNull;
 import java.io.IOException;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
 import okhttp3.Call;
@@ -95,6 +97,16 @@ public class InputInfoFragment extends Fragment {
                 // 扫码成功回调
                 Log.d(TAG, "onScanSuccess: " + s);
 
+                if (!StringUtils.isNullOrEmpty(s)) {
+                    for (String pattern : ScanGunConstant.getPatterns()) {
+                        Matcher matcher = Pattern.compile(pattern).matcher(s);
+                        if (!matcher.matches()) {
+                            ToastUtils.make(getContext(), "请将条形码置于扫码枪前! ");
+                            return;
+                        }
+                    }
+                }
+
                 if (mailNoLock.get() == 1) {
                     Editable text = binding.mailNo.getText();
                     text.clear();

+ 3 - 14
app/src/main/java/com/emato/ich/message/ICHPublishClient.java

@@ -40,8 +40,8 @@ public class ICHPublishClient {
 
     // 初始化客户端实例
     private ICHPublishClient() {
-//        String clientId = BaseUtils.getClientId() + "publish";
-        String clientId = BaseUtils.getClientId();
+        String clientId = BaseUtils.getClientId() + "_publish";
+//        String clientId = BaseUtils.getClientId();
         try {
             Log.i(TAG, "ICHPublishClient: 创建客户端实例开始!");
             client = new MqttClient(ICSPConstant.MQTT_SERVER_ADDRESS, clientId, new MemoryPersistence());
@@ -62,7 +62,7 @@ public class ICHPublishClient {
         options.setUserName(userName);
         options.setPassword(password.toCharArray());
         // 连接超时时间
-        options.setConnectionTimeout(10);
+        options.setConnectionTimeout(30);
         // 设置心跳间隔时间
         options.setKeepAliveInterval(30);
         // TODO 设置发布回调
@@ -105,15 +105,4 @@ public class ICHPublishClient {
             LoggingUtils.sendErrorLog("业务异常: 消息推送失败! ", e);
         }
     }
-
-    public void subscribe(String topicName, IMqttMessageListener iMqttMessageListener) {
-        try {
-            topic = client.getTopic(topicName);
-            Log.i(TAG, "subscribe: 开始消息监听! topicName: " + topicName);
-            client.subscribe(topicName, iMqttMessageListener);
-        } catch (MqttException e) {
-            Log.e(TAG, "subscribe: 消息监听失败! topicName: " + topicName, e);
-            LoggingUtils.sendErrorLog("业务异常: 消息监听失败! topicName: " + topicName, e);
-        }
-    }
 }

+ 6 - 3
app/src/main/java/com/emato/ich/message/ICHSubscribeClient.java

@@ -19,7 +19,6 @@ import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
 /**
  * 订阅客户端
  */
-@Deprecated
 public class ICHSubscribeClient {
 
     public static final String TAG = "ICHSubscribeClient";
@@ -41,7 +40,7 @@ public class ICHSubscribeClient {
 
 
     private ICHSubscribeClient() {
-        String clientId = BaseUtils.getClientId() + "subscribe";
+        String clientId = BaseUtils.getClientId() + "_subscribe";
         try {
             Log.i(TAG, "ICHSubscribeClient: 开始创建消息服务器订阅客户端实例!");
             client = new MqttClient(ICSPConstant.MQTT_SERVER_ADDRESS, clientId, new MemoryPersistence());
@@ -60,7 +59,7 @@ public class ICHSubscribeClient {
         options.setUserName(userName);
         options.setPassword(password.toCharArray());
         // 连接超时时间
-        options.setConnectionTimeout(10);
+        options.setConnectionTimeout(30);
         // 设置心跳间隔时间
         options.setKeepAliveInterval(30);
         // TODO 设置连接回调
@@ -68,16 +67,19 @@ public class ICHSubscribeClient {
             @Override
             public void connectionLost(Throwable cause) {
                 // TODO 重连
+                Log.e(TAG, "connectionLost: cause: ", cause);
             }
 
             @Override
             public void messageArrived(String topic, MqttMessage message) throws Exception {
                 // TODO MQTT服务器成功接收消息后,返回消息并调用此方法
+                Log.i(TAG, "messageArrived: topic: " + topic + ", msg: " + message.getId() + "--" + new String(message.getPayload()));
             }
 
             @Override
             public void deliveryComplete(IMqttDeliveryToken token) {
                 // TODO 接收到已经发布的 QoS 1 或 QoS 2 消息的传递令牌时调用
+                Log.i(TAG, "deliveryComplete: token---" + token.toString() + "---" + topic.getName());
             }
         });
         try {
@@ -96,6 +98,7 @@ public class ICHSubscribeClient {
             client.subscribe(topicName, iMqttMessageListener);
         } catch (MqttException e) {
             Log.e(TAG, "subscribe: 消息监听失败! topicName: " + topicName, e);
+            LoggingUtils.sendErrorLog("业务异常: 消息监听失败! topicName: " + topicName, e);
         }
     }
 }