Bläddra i källkod

添加了短信服务,意外开关门,温度过高,设备失灵,调用短信服务

DESKTOP-SADJPBG\47462 5 år sedan
förälder
incheckning
823ebcb30f

+ 4 - 3
app/build.gradle

xqd
@@ -68,7 +68,8 @@ dependencies {
     debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.2'
     debugImplementation 'com.squareup.leakcanary:leakcanary-support-fragment:1.6.2'
     implementation 'com.github.maybesix:Android-XHLibrary:v1.0.0'
-
-    implementation  'com.tencent.bugly:crashreport:3.1.0'
-    implementation  'com.tencent.bugly:nativecrashreport:latest.release'
+    implementation 'com.tencent.bugly:crashreport:3.1.0'
+    implementation 'com.tencent.bugly:nativecrashreport:latest.release'
+    implementation files('src/main/libs/aliyun-java-sdk-core-4.1.0.jar')
+    implementation files('src/main/libs/aliyun-java-sdk-dysmsapi-1.0.0.jar')
 }

+ 10 - 1
app/src/main/java/com/siwei/recyclebox/application/AppApplication.java

xqd xqd xqd xqd xqd
@@ -18,6 +18,7 @@ import android.util.Log;
 
 import com.alibaba.fastjson.JSONObject;
 import com.alibaba.fastjson.TypeReference;
+import com.aliyun.alink.apiclient.constants.MethodType;
 import com.aliyun.alink.dm.api.DeviceInfo;
 import com.aliyun.alink.dm.model.ResponseModel;
 import com.aliyun.alink.linkkit.api.ILinkKitConnectListener;
@@ -38,6 +39,11 @@ import com.aliyun.alink.linksdk.tmp.device.payload.ValueWrapper;
 import com.aliyun.alink.linksdk.tmp.listener.IPublishResourceListener;
 import com.aliyun.alink.linksdk.tools.AError;
 import com.aliyun.alink.linksdk.tools.ALog;
+import com.aliyuncs.DefaultAcsClient;
+import com.aliyuncs.IAcsClient;
+import com.aliyuncs.exceptions.ClientException;
+import com.aliyuncs.profile.DefaultProfile;
+import com.aliyuncs.profile.IClientProfile;
 import com.siwei.recyclebox.BuildConfig;
 import com.siwei.recyclebox.deviceUtils.SerialPortUtil;
 import com.siwei.recyclebox.ui.main.MainActivity;
@@ -90,6 +96,8 @@ public class AppApplication extends BaseApplication implements CustomActivityOnC
     private Handler mHandler=new Handler(msg ->{
         return true;
     });
+
+
     private void initAliIoT(DeviceInfo deviceInfo){
         /**
          * 设置设备三元组信息
@@ -106,7 +114,7 @@ public class AppApplication extends BaseApplication implements CustomActivityOnC
          */
         Map<String, ValueWrapper> propertyValues = new HashMap<>();
         //心跳包 interval 单位秒
-        MqttConfigure.setKeepAliveInterval(300);
+        MqttConfigure.setKeepAliveInterval(60);
         // 示例
         // propertyValues.put("LightSwitch", new ValueWrapper.BooleanValueWrapper(0));
         IoTMqttClientConfig clientConfig = new IoTMqttClientConfig(deviceInfo.productKey, deviceInfo.deviceName, deviceInfo.deviceSecret);
@@ -165,6 +173,7 @@ public class AppApplication extends BaseApplication implements CustomActivityOnC
         myDeviceInfo.productSecret = "Nc4Y4KsjofejCy27";
         System.out.println(MainViewModel.getDeviceId(this)+"----------------------------+");
         myDeviceInfo.deviceName = MainViewModel.getDeviceId(this);
+        SPUtils.getInstance().put("IMEI",MainViewModel.getDeviceId(this));
 //        myDeviceInfo.deviceName="123456";
 //        SPUtils.getInstance().put("deviceSecret","lzR12lxbbuV3c4tZMxrIPl1Vh9K9Ssv4");//存
         String secret = SPUtils.getInstance().getString("deviceSecret");//读

+ 43 - 5
app/src/main/java/com/siwei/recyclebox/deviceUtils/OtherDevice.java

xqd xqd xqd xqd xqd xqd xqd
@@ -3,9 +3,12 @@ package com.siwei.recyclebox.deviceUtils;
 import android.hardware.usb.UsbManager;
 import android.speech.tts.TextToSpeech;
 import android.util.Log;
+
+import com.aliyuncs.exceptions.ClientException;
 import com.siwei.recyclebox.ui.main.MainViewModel;
 import com.hoho.android.usbserial.driver.UsbSerialDriver;
 import com.hoho.android.usbserial.driver.UsbSerialPort;
+import com.siwei.recyclebox.ui.main.WarnActivity;
 
 import android.os.Handler;
 
@@ -128,8 +131,14 @@ public class OtherDevice extends BaseDeviceEntity {
             MainViewModel.reportDeviceEvent("queryMagDoor");
             return 0;
         }catch ( Exception e ){
-            e.printStackTrace();
+
             MainViewModel.reportDeviceEvent("queryMagDoor");
+            try {
+                WarnActivity.SendSmsResponse("queryMagDoor门磁");
+            } catch (ClientException ex) {
+                ex.printStackTrace();
+            }
+            e.printStackTrace();
             Log.e(TAG,"读取门磁错误",e);
             return 3;
         }
@@ -206,9 +215,15 @@ public class OtherDevice extends BaseDeviceEntity {
             MainViewModel.reportDeviceEvent("queryInfrared");
             return 0;
         }catch ( Exception e ){
-            e.printStackTrace();
+
             MainViewModel.reportDeviceEvent("queryInfrared");
+            try {
+                WarnActivity.SendSmsResponse("queryInfrared红外线");
+            } catch (ClientException ex) {
+                ex.printStackTrace();
+            }
             Log.e(TAG,"读取红外线读数错误",e);
+            e.printStackTrace();
             return 3;
         }
     }
@@ -224,14 +239,21 @@ public class OtherDevice extends BaseDeviceEntity {
                     SPUtils.getInstance().put("RunningState","0");
                     SPUtils.getInstance().put("RodSwitch","0");
                     //门  66后面 01 表示杆 01表示伸杆  1c表示多少秒  02 1c 表示电流
-                    byte[] pushRodOrderBytes = new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x01, 0x01,0x0B, (byte) 0xff,0x1C, (byte) 0xCC, (byte) 0xDD};
+                    System.out.println("------------push rod------------------------");
+                    byte[] pushRodOrderBytes = new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x01, 0x01,(byte)0x0B, (byte) 0x02, (byte) 0x1c, (byte) 0xCC, (byte) 0xDD};
                     port.write(pushRodOrderBytes, 100);
+                    System.out.println("bytes:"+ByteUtil.bytesToString(pushRodOrderBytes));
 //                    byte[] pushRodOrderBytes2 = new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x01, 0x01,0x1c, (byte) 0xFF,0x1c, (byte) 0xCC, (byte) 0xDD};
 //                    port.write(pushRodOrderBytes2, 100);
                     getRodOpenNumber();
                     byte[] response = new byte[ 12];
                     port.read(response,200);
+                    byte[] readPushOrderBytes=new byte[]{(byte)0xAA, (byte) 0xBB,0x0A, 0x01, 0x55 ,0x01 , (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
+                    port.write(readPushOrderBytes, 100);
+                    byte[] responseRead = new byte[ 12];
+                    port.read(responseRead,200);
                     System.out.println("push response:"+ByteUtil.bytesToString(response));
+                    System.out.println("pushRead response:"+ByteUtil.bytesToString(responseRead));
 //                    SPUtils.getInstance().put("infraredNum1",0);
 //                    SPUtils.getInstance().getInt("infraredNum1",0);
                     long curr=System.currentTimeMillis();
@@ -241,7 +263,7 @@ public class OtherDevice extends BaseDeviceEntity {
                         if (infrared == 1) {//有障碍物
                             //停止关门
                             Log.i(TAG, "停止关门");
-                            port.write(new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x01, 0x03, (byte) 0x02, 0x05, (byte) 0x1C, (byte) 0xCC, (byte) 0xDD}, 200);
+                            port.write(new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x01, 0x03, (byte) 0x02, 0x02, (byte) 0x1C, (byte) 0xCC, (byte) 0xDD}, 200);
                             int num=SPUtils.getInstance().getInt("infraredNum1")+1;
                             SPUtils.getInstance().put("infraredNum1",num);
                             if(num<3){
@@ -269,6 +291,11 @@ public class OtherDevice extends BaseDeviceEntity {
                     }
                 }catch (Exception e ){
                     MainViewModel.reportDeviceEvent("pushRod");
+                    try {
+                        WarnActivity.SendSmsResponse("pushRod关门");
+                    } catch (ClientException ex) {
+                        ex.printStackTrace();
+                    }
                     e.printStackTrace();
                     Log.i(TAG,"关门失败");
                 }
@@ -287,14 +314,25 @@ public class OtherDevice extends BaseDeviceEntity {
                     SPUtils.getInstance().put("RunningState","0");
                     SPUtils.getInstance().put("RodSwitch","1");
                     //伸杆  66后面 01 表示杆 02表示缩杆  1c表示多少秒  02 1c 表示电流
-                    byte[] pullRodOrderBytes = new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x01, 0x02,0x0B, (byte) 0xff, (byte) 0x1C, (byte) 0xCC, (byte) 0xDD};
+                    byte[] pullRodOrderBytes = new byte[]{(byte) 0xAA, (byte) 0xBB, 0x0A, 0x01, 0x66, 0x01, 0x02,0x0B, (byte) 0xff, (byte) 0x1c, (byte) 0xCC, (byte) 0xDD};
                     int writeLen = port.write(pullRodOrderBytes, 100);
                     System.out.println("pullRod "+writeLen);
                     byte[] response = new byte[12];
                     port.read(response,200);
+
+                    byte[] readPullOrderBytes=new byte[]{(byte)0xAA, (byte) 0xBB,0x0A, 0x01, 0x55 ,0x01 , (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD};
+                    port.write(readPullOrderBytes, 100);
+                    byte[] responseRead = new byte[ 12];
+                    port.read(responseRead,200);
+                    System.out.println("pullRead response:"+ByteUtil.bytesToString(responseRead));
                     System.out.println("response:"+ByteUtil.bytesToString(response));
                 }catch ( Exception e ){
                     MainViewModel.reportDeviceEvent("pullRod");
+                    try {
+                        WarnActivity.SendSmsResponse("pullRod开门");
+                    } catch (ClientException ex) {
+                        ex.printStackTrace();
+                    }
                     e.printStackTrace();
                     Log.i(TAG,"开门失败");
                 }

+ 1 - 1
app/src/main/java/com/siwei/recyclebox/deviceUtils/WeightDevice.java

xqd
@@ -59,7 +59,7 @@ public class WeightDevice extends BaseDeviceEntity {
                 weightBytes[3] = responseCache[4];
                 int weightInt = ByteUtil.bytes2Int(weightBytes);
                 weightInt=weightInt*5*2;
-                System.out.println("称重读数:"+weightBytes);
+                System.out.println("称重读数:"+weightInt);
                 if(weightInt>=327670){
                     weightInt=0;
                 }

+ 39 - 0
app/src/main/java/com/siwei/recyclebox/service/WarnService.java

xqd
@@ -0,0 +1,39 @@
+package com.siwei.recyclebox.service;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+import android.util.Log;
+
+public class WarnService extends Service {
+
+    @Override
+    public IBinder onBind(Intent arg0) {
+        return null;
+    }
+
+    @Override
+    public int onStartCommand(Intent intent, int flags, int startId) {
+        // Let it continue running until it is stopped.
+//        Toast.makeText(this, "服务已经启动", Toast.LENGTH_LONG).show();
+        Log.i("","服务已经启动");
+        return START_STICKY;
+    }
+
+    @Override
+    public void onDestroy() {
+
+//            Intent intent=new Intent(this,WarnService.class);
+//            this.startService(intent);
+
+//        Intent mStartActivity = new Intent(this, MainActivity.class);
+//        int mPendingIntentId = 123456;
+//        PendingIntent mPendingIntent = PendingIntent.getActivity(this, mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
+//        AlarmManager mgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
+//        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
+//        System.exit(0);
+        super.onDestroy();
+//        Toast.makeText(this, "服务已经停止", Toast.LENGTH_LONG).show();
+//        Log.i("","服务已经停止");
+    }
+}

+ 62 - 79
app/src/main/java/com/siwei/recyclebox/ui/main/MainViewModel.java

xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd xqd
@@ -171,11 +171,6 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
             System.out.println("btnClickqueryCurrent");
             Integer queryCurrentData=SerialPortUtil.getInstance().getOtherDevice().queryCurrent();
             textqueryCurrentData.set(String.valueOf(queryCurrentData));
-//            int[] a=new int[2];
-//            for(int i=0;i<5;i++){
-//                a[i]=i;
-//            }
-//            avgWeight();
         }
     };
     public void onSerialPortDataReceived(ComPortData comPortData) {
@@ -377,7 +372,6 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
             System.out.println("btnClickPushRod");
 //            mHandler.sendEmptyMessage(2);
 //            SerialPortUtil.getInstance().getOtherDevice().pushRod();//关门
-
             pushRodMethodNonet();
         }
     };
@@ -558,9 +552,8 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
             @Override
             public void run() {
                 avgWeight();
-
             }
-        },1000);
+        },500);
 
         mHandler.postDelayed(new Runnable() {
             @Override
@@ -625,35 +618,40 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
         Thread thread=new Thread(new Runnable() {
             @Override
             public void run() {
+                Log.i("avgWeight()","---运行次数");
                 int weight = 0;
-                int[] arr=new int[10];
+                int[] arr=new int[5];
                 int n;
-                for(n=0;n<10;n++){
+                for(n=0;n<5;n++){
                         arr[n]=SerialPortUtil.getInstance().getWeightDevice().readWeight();
+//                    try {
+//                        sleep(200);
+//                    } catch (InterruptedException e) {
+//                        e.printStackTrace();
+//                    }
 //                    arr[n]=n;
                     Log.i("n=", String.valueOf(n));
 //                arr[n]=SerialPortUtil.getInstance().getOtherDevice().readWeight();
                     Log.i("weight=", String.valueOf(arr[n]));
                     weight=arr[n]+weight;
-                    if(n==9){
-                        int dvalue1 = Math.abs(arr[9]-arr[8]);
-                        int dvalue2 = Math.abs(arr[9]-arr[7]);
+                    if(n==3){
+                        Log.i("weight=", Arrays.toString(arr));
+                        int dvalue1 = Math.abs(arr[3]-arr[2]);
+                        int dvalue2 = Math.abs(arr[3]-arr[1]);
                         if(dvalue1<30&&dvalue2<30){
-                            Log.i("weight n-1=", String.valueOf(arr[9]));
-                            SPUtils.getInstance().put("avgWeight",arr[9]);
+                            Log.i("weight n-1=", String.valueOf(arr[3]));
+                            SPUtils.getInstance().put("avgWeight最后读数",arr[3]);
                         }else {
-                            double v = weight / 10;
+                            double v = weight / 5;
                             int avg = new Double(v).intValue();
                             Log.i("weight avg=", String.valueOf(avg));
-                            SPUtils.getInstance().put("avgWeight",avg);
+                            SPUtils.getInstance().put("avgWeight平均数",avg);
                         }
                     }
                 }
             }
         });
         thread.start();
-
-
     }
 
 
@@ -661,7 +659,6 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
         //无网下关门
         SPUtils.getInstance().put("infraredNum1",0);
         SerialPortUtil.getInstance().getOtherDevice().pushRod();//关门
-//        avgWeight();
         mHandler.postDelayed(new Runnable() {
             @Override
             public void run() {
@@ -822,7 +819,7 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
                                 public void run() {
                                     try{
                                         long curr=System.currentTimeMillis();
-                                        while(System.currentTimeMillis()-curr<300000) {
+                                        while(System.currentTimeMillis()-curr<1800000) {
                                             Thread.sleep(1000);
                                             Integer magDoorSwitch=SerialPortUtil.getInstance().getOtherDevice().queryMagDoor();//通过门磁感应判断收运门是否关闭
                                             if(magDoorSwitch==0){
@@ -1042,13 +1039,14 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
     public void reportProperty(int num) {
         Log.i(TAG,"上报数据");
         try{
-
 //            SerialPortUtil.getInstance().getWeightDevice().weightClear();//去皮清零
     //                SerialPortUtil.getInstance().getOtherDevice().clearWeight();//去皮清零
             Integer weight = 0;
             if(num==1){
+                Log.i("num=1","读一次称重");
                 weight = SerialPortUtil.getInstance().getWeightDevice().readWeight();//读称重
             }else if(num==2){
+                Log.i("num=2","读平均称重或最后");
                 weight=SPUtils.getInstance().getInt("avgWeight");
             }
 
@@ -1157,7 +1155,7 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
    /*
    * 上报给蓝牙的数据格式
    * */
-    public JSONObject reportDataMethod(int num){
+    public JSONObject reportDataMethod(){
         Integer capacity=0;
         capacity=SerialPortUtil.getInstance().getOtherDevice().getDistance();//超声波距离/
         Integer magDoorSwitch=0;
@@ -1165,12 +1163,8 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
         Integer currentTemperature=0;
         currentTemperature=SerialPortUtil.getInstance().getOtherDevice().geTemperature();//温度
         Integer weight = 0;
-        if(num==2){
-            weight=SerialPortUtil.getInstance().getWeightDevice().readWeight();
-            //        weight=SerialPortUtil.getInstance().getOtherDevice().readWeight();//称重
-        }else if(num==1){
-            weight=SPUtils.getInstance().getInt("avgWeight");
-        }
+        weight=SerialPortUtil.getInstance().getWeightDevice().readWeight();
+        //        weight=SerialPortUtil.getInstance().getOtherDevice().readWeight();//称重
 
         String  text = "称重 " + weight.toString() + ";距离 " + capacity.toString() + "mm;温度 " + currentTemperature+"度;门磁 "+magDoorSwitch+";杆状态 "+";锁状态 "+lockSwitch;
         Log.i(TAG, text + "=textReportData---------------------");
@@ -1270,13 +1264,13 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
     * 加密传给蓝牙的数据格式
     * */
     @RequiresApi(api = Build.VERSION_CODES.O)
-    public String reportDataMethodEncrypt(int num) {
+    public String reportDataMethodEncrypt() {
         JSONObject reportData =new JSONObject();
         reportData.put("T",SPUtils.getInstance().getString("type"));
         //加密数据
         String base64Str="";
         try {
-            base64Str= DemoOne.encrypt(reportDataMethod(num).toString()+"@", "1234567890123456", "0987654321098765");//加密数据
+            base64Str= DemoOne.encrypt(reportDataMethod().toString()+"@", "1234567890123456", "0987654321098765");//加密数据
         } catch (Exception e) {
             e.printStackTrace();
         }
@@ -1341,7 +1335,7 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
             @Override
             public void run() {
                 publish();
-//                publishRepeat();
+                publishRepeat();
 
             }
         },600000);
@@ -1486,28 +1480,35 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
 
     private void publishRepeat(){
         //每隔一段时间检测磁控和温度 如果异常就上报(前提是有网条件下)
-        Integer currentTemperature=SerialPortUtil.getInstance().getOtherDevice().geTemperature();//温度
-        Integer magDoorSwitch=SerialPortUtil.getInstance().getOtherDevice().queryMagDoor();
-        if(currentTemperature>100){
-            SPUtils.getInstance().put("RunningState","2");//温度过高
-            Log.i(TAG,"温度过高");
-            Integer networkInt=netWorkInfo();
-            if(networkInt!=0){
-                reportProperty(1);
-            }
-        }
-        if(magDoorSwitch==1){
-            if(SPUtils.getInstance().getString("magDoorSwitch").equals("0")){
-                SPUtils.getInstance().put("RunningState","3");
-                Log.i(TAG,"收运门意外打开");
-                Integer networkInt=netWorkInfo();
-                if(networkInt!=0){
-                    reportProperty(1);
+        Thread thread=new Thread(new Runnable() {
+            @Override
+            public void run() {
+                Integer currentTemperature=SerialPortUtil.getInstance().getOtherDevice().geTemperature();//温度
+                Integer magDoorSwitch=SerialPortUtil.getInstance().getOtherDevice().queryMagDoor();
+                if(currentTemperature>100){
+                    SPUtils.getInstance().put("RunningState","2");//温度过高
+                    Log.i(TAG,"温度过高");
+                    Integer networkInt=netWorkInfo();
+                    if(networkInt!=0){
+                        reportProperty(1);
+                    }
+                }
+                if(magDoorSwitch==1){
+                    if(SPUtils.getInstance().getString("magDoorSwitch").equals("0")){
+                        SPUtils.getInstance().put("RunningState","3");
+                        Log.i(TAG,"收运门意外打开");
+                        Integer networkInt=netWorkInfo();
+                        if(networkInt!=0){
+                            reportProperty(1);
+                        }
+                    }
+                }
+                if(currentTemperature<100&magDoorSwitch==0) {
+                    SPUtils.getInstance().put("RunningState","0");
                 }
             }
-        }
-        if(currentTemperature<100&magDoorSwitch==0) {
-        SPUtils.getInstance().put("RunningState","0");}
+        });
+        thread.start();
         mHandler.postDelayed(new Runnable() {
             @Override
             public void run() {
@@ -1586,7 +1587,6 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
                 @RequiresApi(api = Build.VERSION_CODES.O)
                 @Override
                 public void run() {
-
                     String response=SPUtils.getInstance().getString("response");
 //                    +"asasasa15s1a5s1a651sa51s6a51s6a51s5a1s65a1sa51sa651sa561sa51s5a1s6a51s65a1s"
 //                    response="{\"encryptData\":\"81ypl9FQ9YyoyLyjPpd6BpvC0kT+QDGvKt9eQU8YjFhMuMpVsAMwSw/+kOFDhKKp8JEbFWKM3vTDZp5HhxIl0GloODH5RAutIFDNcLP1c13OrIfeFMmaOivV63omw5CbAMBQp0nuMXPbzHICiZ2HFJhcA0Ahm0g+R+4ze74ku4Ojbor+3s3Q4G3pF+6tnJelR/P4ovA81Ls0dvc1aBSC15hPjkD94j4mAsariqcj328zDQE9oXFb7I5k7z5jkAAVB4cm0qxnk/Np+KoEA1DU0TtQEjvN18Ak/kEND7hk5fU2xGcCmS6OMzltUk4Z3acaydWDaAfvZnChP/wUwXBcVmRdK50tgq8/70xhUWZT5WycOYmov7cO/F7gK1aP/u8hCNztYkG+sXyReXfHfFWk/0AtbT19+wUoyVgaihUfKI/knNSjqunBnVjksNKqRIKqWAUdQIarlxo+V7zdwsBcMnHQBCVeSGdG3OPfaEVMEOFopjOB7q7YLPd93AhYr/x9eQc6tRaZOR1dVgiq3hpxOD3uDCcumDjK88XcyvaD/EYV7rEukd8bTOF6lVEy3iCx+AT9GTqm123";
@@ -1661,7 +1661,7 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
                                                 if(numInt== finalTimeInt){
                                                     pushRodMethodNonet();
                                                     SPUtils.getInstance().put("type","close");
-                                                    String response=reportDataMethodEncrypt(1);
+                                                    String response=reportDataMethodEncrypt();
                                                     SPUtils.getInstance().put("response",response);
                                                     onCharacteristicReadRequest(device,  requestId, offset, characteristic);
                                                     break;
@@ -1707,13 +1707,16 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
                                                 public void run() {
                                                     try{
                                                     long curr=System.currentTimeMillis();
-                                                    while(System.currentTimeMillis()-curr<300000) {
+                                                    while(System.currentTimeMillis()-curr<1800000) {
                                                         Thread.sleep(1000);
                                                         Integer magDoorSwitch=SerialPortUtil.getInstance().getOtherDevice().queryMagDoor();//通过门磁感应判断收运门是否关闭
                                                         if(magDoorSwitch==0){
                                                             SerialPortUtil.getInstance().getWeightDevice().weightClear();//若关闭,称重清零
                                                             SPUtils.getInstance().put("magDoorSwitch","0");
 //                                                            SerialPortUtil.getInstance().getOtherDevice().clearWeight();
+                                                            String response=reportDataMethodEncrypt();
+                                                            SPUtils.getInstance().put("response",response);
+                                                            onCharacteristicReadRequest(device,  requestId, offset, characteristic);
                                                             break;
                                                         }
                                                     }
@@ -1731,38 +1734,18 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
                             }
                         }
                     if(requestStr.equals("close")){
-//                        avgWeight();
                         pushRodMethodNonet();
                             Log.i(TAG,"++++++收到321");
                             Log.i(TAG,"+++++关门");
                         SPUtils.getInstance().put("type","close");
-//                        mHandler.postDelayed(new Runnable() {
-//                            @Override
-//                            public void run() {
-//                                SPUtils.getInstance().put("type","close");
-//                                String response=reportDataMethodEncrypt(2);
-//                                SPUtils.getInstance().put("response",response);
-//                                onCharacteristicReadRequest(device,  requestId, offset, characteristic);
-//                            }
-//                        },3500);
-                        String response=reportDataMethodEncrypt(2);
+                        String response=reportDataMethodEncrypt();
                         SPUtils.getInstance().put("response",response);
                         onCharacteristicReadRequest(device,  requestId, offset, characteristic);
                     }
                     if(requestStr.equals("close2")){
-//                        avgWeight();
                         Log.i(TAG,"+++++收运门关");
                         SPUtils.getInstance().put("type","close");
-//                        mHandler.postDelayed(new Runnable() {
-////                            @Override
-////                            public void run() {
-////                                SPUtils.getInstance().put("type","close");
-////                                String response=reportDataMethodEncrypt(2);
-////                                SPUtils.getInstance().put("response",response);
-////                                onCharacteristicReadRequest(device,  requestId, offset, characteristic);
-////                            }
-////                        },3500);
-                        String response=reportDataMethodEncrypt(2);
+                        String response=reportDataMethodEncrypt();
                         SPUtils.getInstance().put("response",response);
                         onCharacteristicReadRequest(device,  requestId, offset, characteristic);
                     }
@@ -1772,7 +1755,7 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
                         Log.i(TAG,"+++++开门请求");
                         Log.i(TAG,"+++++requestStrlength"+requestStr.length());
                         SPUtils.getInstance().put("type","open");
-                        String response=reportDataMethodEncrypt(2);
+                        String response=reportDataMethodEncrypt();
                         SPUtils.getInstance().put("response",response);
                         onCharacteristicReadRequest(device,  requestId, offset, characteristic);
                     }
@@ -1782,7 +1765,7 @@ public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnS
                         Log.i(TAG,"+++++开门请求");
                         Log.i(TAG,"+++++requestStrlength"+requestStr.length());
                         SPUtils.getInstance().put("type","open");
-                        String response=reportDataMethodEncrypt(2);
+                        String response=reportDataMethodEncrypt();
                         SPUtils.getInstance().put("response",response);
                         onCharacteristicReadRequest(device,  requestId, offset, characteristic);
                     }

+ 167 - 0
app/src/main/java/com/siwei/recyclebox/ui/main/WarnActivity.java

xqd
@@ -0,0 +1,167 @@
+package com.siwei.recyclebox.ui.main;
+
+import android.annotation.SuppressLint;
+import android.app.Application;
+import android.content.Intent;
+import android.os.Build;
+import android.os.Handler;
+import android.os.Message;
+import android.support.annotation.NonNull;
+import android.support.annotation.RequiresApi;
+import android.util.Log;
+
+import com.alibaba.fastjson.JSONObject;
+import com.aliyun.alink.apiclient.constants.MethodType;
+import com.aliyun.alink.linksdk.tmp.device.asynctask.MessageHandler;
+import com.aliyuncs.DefaultAcsClient;
+import com.aliyuncs.IAcsClient;
+import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
+import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
+import com.aliyuncs.exceptions.ClientException;
+import com.aliyuncs.profile.DefaultProfile;
+import com.aliyuncs.profile.IClientProfile;
+import com.siwei.recyclebox.deviceUtils.SerialPortUtil;
+import com.siwei.recyclebox.service.WarnService;
+
+import java.util.Timer;
+import java.util.TimerTask;
+
+import me.goldze.mvvmhabit.utils.SPUtils;
+
+
+public class WarnActivity extends MainViewModel{
+    String TAG="WarnActicity";
+
+    private final Timer timer=new Timer();
+    private TimerTask task;
+
+    @SuppressLint("HandlerLeak")
+//    Handler handler=new Handler(){
+//        public void handleMessage(Message msg){
+//            super.handleMessage(msg);
+//        }
+//    };
+    Handler handler=new Handler(msg -> {
+        return true;
+    });
+    @RequiresApi(api = Build.VERSION_CODES.O)
+    public void onCreate(){
+        super.onCreate();
+        Intent service=new Intent(getApplication(), WarnService.class);
+        getApplication().startService(service);
+        task =new TimerTask(){
+            public void run(){
+                publishRepeat();
+            }
+        };
+        timer.schedule(task,60000,60000);
+    }
+    public WarnActivity(@NonNull Application application) {
+        super(application);
+    }
+
+
+    private void publishRepeat(){
+        //每隔一段时间检测磁控和温度 如果异常就上报(前提是有网条件下)
+//        Thread thread=new Thread(new Runnable() {
+//            @Override
+//            public void run() {
+                Integer currentTemperature= SerialPortUtil.getInstance().getOtherDevice().geTemperature();//温度
+                Integer magDoorSwitch=SerialPortUtil.getInstance().getOtherDevice().queryMagDoor();
+                if(currentTemperature>90){
+                    SPUtils.getInstance().put("RunningState","2");//温度过高
+                    Log.i(TAG,"温度过高");
+                    Integer networkInt=netWorkInfo();
+                    if(networkInt!=0){
+                        reportProperty(1);
+                        //短信通知
+                        try {
+                            SendSmsResponse("温度过高");
+                        } catch (ClientException e) {
+                            e.printStackTrace();
+                        }
+                    }
+                }
+                if(magDoorSwitch==1){
+                    if(SPUtils.getInstance().getString("magDoorSwitch").equals("0")){
+                        SPUtils.getInstance().put("RunningState","3");
+                        Log.i(TAG,"收运门意外打开");
+                        Integer networkInt=netWorkInfo();
+                        if(networkInt!=0){
+                            reportProperty(1);
+                            //短信通知
+                            try {
+                                SendSmsResponse("收运门意外打开");
+                            } catch (ClientException e) {
+                                e.printStackTrace();
+                            }
+                        }
+                    }
+                }
+                if(currentTemperature<100&magDoorSwitch==0) {
+                    SPUtils.getInstance().put("RunningState","0");
+                }
+//            }
+//        });
+//        thread.start();
+//        mHandler.postDelayed(new Runnable() {
+//            @Override
+//            public void run() {
+//                publishRepeat();
+//            }
+//        }, 300000);
+    }
+
+    public static void SendSmsResponse(String event) throws ClientException {
+
+        //设置超时时间-可自行调整
+        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
+        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
+//初始化ascClient需要的几个参数
+        final String product = "Dysmsapi";//短信API产品名称(短信产品名固定,无需修改)
+        final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名(接口地址固定,无需修改)
+//替换成你的AK
+        final String accessKeyId = "yourAccessKeyId";//你的accessKeyId,参考本文档步骤2
+        final String accessKeySecret = "yourAccessKeySecret";//你的accessKeySecret,参考本文档步骤2
+//初始化ascClient,暂时不支持多region(请勿修改)
+        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
+                accessKeySecret);
+        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
+        IAcsClient acsClient = new DefaultAcsClient(profile);
+
+
+        //组装请求对象
+        SendSmsRequest request = new SendSmsRequest();
+        //使用post提交
+//        request.setMethod(MethodType.POST);
+        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式;发送国际/港澳台消息时,接收号码格式为国际区号+号码,如“85200000000”
+        request.setPhoneNumbers("18116680579");
+        //必填:短信签名-可在短信控制台中找到
+        request.setSignName("云通信");
+        //必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
+        request.setTemplateCode("SMS_185241516");
+        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
+        //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
+
+        JSONObject jsono=new JSONObject();
+        jsono.put("DeviceId", SPUtils.getInstance().getString("IMEI"));
+        jsono.put("DeviceName", event);
+        request.setTemplateParam(String.valueOf(jsono));
+        //可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
+        //request.setSmsUpExtendCode("90997");
+
+        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
+//        request.setOutId("yourOutId");
+        //请求失败这里会抛ClientException异常
+        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
+        System.out.println("短信接口返回的数据----------------");
+        System.out.println("Code=" + sendSmsResponse.getCode());
+        System.out.println("Message=" + sendSmsResponse.getMessage());
+        System.out.println("RequestId=" + sendSmsResponse.getRequestId());
+        System.out.println("BizId=" + sendSmsResponse.getBizId());
+        if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
+//请求成功
+            Log.i("TAG","短信发送成功");
+        }
+    }
+}

BIN
app/src/main/libs/aliyun-java-sdk-core-4.1.0.jar


BIN
app/src/main/libs/aliyun-java-sdk-dysmsapi-1.0.0.jar


+ 1 - 1
app/src/main/res/layout/activity_main.xml

xqd
@@ -75,7 +75,7 @@
                     android:layout_width="120dp"
                     android:layout_height="96dp"
                     android:onClick="@{viewModal.btnClickReport}"
-                    android:text="数据上报"
+                    android:text="数据上报4"
                     android:textSize="24sp" />
                 </LinearLayout>
                 <LinearLayout

+ 4 - 2
config.gradle

xqd
@@ -6,8 +6,10 @@ ext {
             applicationId    : "com.goldze.mvvmhabit",
             minSdkVersion    : 21,
             targetSdkVersion : 25,
-            versionCode      : 1,
-            versionName      : "1.0",
+            versionCode      : 4,
+            versionName      : "4.0",
+//            versionCode      : 1,
+//            versionName      : "1.0",
     ]
     //version配置
     versions = [