yy
2021-02-22 f1ad19e7a828a7969bbce7d2db461b9bdfd71ab6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
package safeluck.drive.evaluation;
 
 
import android.Manifest;
import android.app.AlertDialog;
import com.anyun.basecommonlib.MyLog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
 
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
 
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.work.Data;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
 
 
import me.yokeyword.fragmentation.SupportActivity;
import safeluck.drive.evaluation.DB.appstatusdb.AppStatus;
import safeluck.drive.evaluation.DB.appstatusdb.AppStatusViewModel;
import safeluck.drive.evaluation.DB.rtktb.RTKConfig;
import safeluck.drive.evaluation.DB.rtktb.RTKConfigUpdateWorker;
import safeluck.drive.evaluation.DB.rtktb.RTKConfigViewModel;
import safeluck.drive.evaluation.DB.signalConfigdb.SignalConfigViewModel;
import safeluck.drive.evaluation.bean.AbsInitialData;
import safeluck.drive.evaluation.bean.ExamPlatformData;
import safeluck.drive.evaluation.bean.SignalConfigRemote;
import safeluck.drive.evaluation.cEventCenter.CEventCenter;
import safeluck.drive.evaluation.cEventCenter.ICEventListener;
import safeluck.drive.evaluation.customview.MyDialog;
import safeluck.drive.evaluation.fragment.HomeFragment;
 
import com.anyun.exam.lib.AYSdk;
import com.anyun.im_lib.listener.IMSConnectStatusCallback;
import com.google.gson.Gson;
import com.safeluck.aykj.utils.BytesUtils;
 
import org.json.JSONException;
import org.json.JSONObject;
 
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
 
import safeluck.drive.evaluation.im.IMSClientBootstrap;
import safeluck.drive.evaluation.im.MessageProcessor;
import safeluck.drive.evaluation.platformMessage.JKMessage0100;
import safeluck.drive.evaluation.platformMessage.JKMessage0101;
import safeluck.drive.evaluation.platformMessage.PlatFormConstant;
import safeluck.drive.evaluation.util.CThreadPoolExecutor;
import safeluck.drive.evaluation.util.DataInitKt;
import safeluck.drive.evaluation.util.FileUtil;
import safeluck.drive.evaluation.util.PermissionManager;
import safeluck.drive.evaluation.util.SPUtils;
import safeluck.drive.evaluation.util.Utils;
import safeluck.drive.evaluation.viewmodels.AuthMapViewmodel;
import safeluck.drive.evaluation.viewmodels.ExamPlatformModel;
import safeluck.drive.evaluation.viewmodels.TimeViewModel;
 
public class MainActivity extends SupportActivity implements IMSConnectStatusCallback, View.OnClickListener {
 
    private static final int PERMISSIONS_REQUEST_CODE = 1001;
    private String TAG = MainActivity.class.getCanonicalName();
    SignalConfigViewModel signalConfigViewModel;
    private PermissionManager mPermissionsManager;
    private RTKConfig mRTKConfig;//RTK配置信息
    private ImageView iv_rtk_status;
    private Gson gson = new Gson();
    String[] PERMISSIONS = new String[]{ Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.WRITE_EXTERNAL_STORAGE};
    RTKConfigViewModel rtkConfigViewModel;
    public ExamPlatformModel examPlatformModel;
 
    private TextView tv_sat_num,tv_work_platform,tv_network_time,
            tv_qf,tv_ble_status;
 
    public Button  btn_return;
    public View viewtitle;
 
    private ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
   private AuthMapViewmodel authMapViewmodel;
    String des ="蓝牙关闭";
    private ICEventListener icEventListener = new ICEventListener() {
        @Override
        public void onCEvent(String topic, int msgCode, int resultCode, Object obj) {
 
            if (msgCode == Constant.RTK_PLATFORM_REGISTER_STATUS) {
                try {
                    JSONObject jsonObject = new JSONObject((String) obj);
                    String rtkLoginPwd = jsonObject.getString("password");
                    int reg_code = jsonObject.getInt("register_code");
                    if (mRTKConfig != null) {
 
                        mRTKConfig.setPassword(rtkLoginPwd);
                        mRTKConfig.setRegistered(reg_code);
                        rtkConfigViewModel.insertRTKConfig(mRTKConfig);
                    }else{
                        MyLog.i(TAG,"mRTKConfig == null");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            if (msgCode == Constant.ID_SM_BLUETOOTH_BRIEF){
                if (tv_ble_status != null){
                    try {
                        String str = (String) obj;
                        Log.i(TAG,"shou=="+str);
                        JSONObject jsonObject = new JSONObject(str);
                        int bleStatus = jsonObject.getInt("bluetooth_status");
 
 
                        switch (bleStatus){
                            case 0:
                                des ="蓝牙关闭";
                                break;
                            case 1:
                                des ="蓝牙打开";
 
                                break;
                            case 2:
                                des ="蓝牙未连接";
                                break;
                            case 3:
 
                                des ="蓝牙连接";
                                String mac = jsonObject.getString("bluetooth_addr");
                                SPUtils.put(getApplicationContext(),SPUtils.BLUETOOTH_MAC,mac);
                                break;
                        }
                        tv_ble_status.post(new Runnable() {
                            @Override
                            public void run() {
                                tv_ble_status.setText(des);
                            }
                        });
 
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
 
 
                }
            }
 
        }
    };
    private boolean hasSendInitData;
    private List<SignalConfigRemote> signalConfiglist = new ArrayList<>();
    private int permissionCount = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //全屏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        hideBottomUIMenu();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        //初始化tts
        ExamPlatformData.getInstance().initTTS(getApplicationContext());
        viewtitle = findViewById(R.id.top_title);
        btn_return = findViewById(R.id.btn_return);
 
 
        btn_return.setOnClickListener(this);
        iv_rtk_status = findViewById(R.id.iv_rtk_connect);
        tv_work_platform = findViewById(R.id.platform);
 
        tv_sat_num = findViewById(R.id.tv_sat_num_instatus);
        tv_ble_status = findViewById(R.id.tv_ble_status);
        tv_qf = findViewById(R.id.tv_qf);
        iv_rtk_status.getDrawable().setLevel(0);
        tv_network_time = findViewById(R.id.network_time);
 
 
        tv_network_time.setText(Utils.getHHmm());
 
 
 
 
        AppStatusViewModel appStatusViewModel = ViewModelProviders.of(this).get(AppStatusViewModel.class);
        appStatusViewModel.getAppStatus().observe(this, new Observer<AppStatus>() {
            @Override
            public void onChanged(AppStatus appStatus) {
                if (appStatus != null){
                    Log.i(TAG, "onChanged: "+appStatus.toString());
                    iv_rtk_status.getDrawable().setLevel(appStatus.getRtk_connect_status());
                    tv_work_platform.setText(getString(R.string.platform_status,ExamPlatformData.getInstance().getExamplatformStatusStr(
                            ExamPlatformData.getInstance().getExamplatformStatus()
                    )));
                    tv_sat_num.setText(String.valueOf(appStatus.getSat_num()).length()==1?"0"+appStatus.getSat_num():String.valueOf(appStatus.getSat_num()));
                    tv_qf.setText(getResources().getStringArray(R.array.qf_status)[appStatus.getQf()<5?appStatus.getQf():0]);
                }
            }
        });
 
        TimeViewModel timeViewModel = ViewModelProviders.of(this).get(TimeViewModel.class);
        timeViewModel.getLiveDataTime().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                tv_network_time.setText(s);
            }
        });
 
        authMapViewmodel = ViewModelProviders.of(this).get(AuthMapViewmodel.class);
        authMapViewmodel.getAuthValue().observe(this, new Observer<Integer>() {
 
 
            @Override
            public void onChanged(Integer integer) {
                Log.i(TAG,"AuthMapViewmodel auth="+integer.intValue());
                if (integer.intValue() == Constant.BLUETOOTH_CONNECT){
                    MyLog.i(TAG,"Bluetooth connected,auth permission and sn != null");
                    String sn = ExamPlatformData.getInstance().getMcuSN();
                    if (!TextUtils.isEmpty(sn)){
 
                    MyLog.i("权限允许,蓝牙已连接,获得到的sn="+sn+" sendInitData");
                    hasSendInitData = true;
                    AbsInitialData.getInstance().sendInitialData();
                    }else{
                        MyLog.i(TAG,"权限允许,蓝牙已连接,获得到的sn=null,不能发送初始数据");
                        hasSendInitData= false;
                    }
 
                }
            }
        });
        // TODO
        //  进行tcp连接
        final String userId = "100002";
        final String token = "token_" + userId;
         examPlatformModel= ViewModelProviders.of(this).get(ExamPlatformModel.class);
        examPlatformModel.getDataChange().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                Log.i(TAG, "ExamPlatformModel onChanged: integer=="+integer);
                if (integer == 1){
                    MyLog.i("重新连接考试平台");
                }else{
 
                }
 
 
                String str = ExamPlatformData.getInstance().getPlatformIP();
                String hosts = "[{\"host\":"+str+","+ "\"port\":"+ExamPlatformData.getInstance().getPlatformPort()+"}]";
                MyLog.i("hosts="+hosts);
                IMSClientBootstrap.getInstance().close();
                IMSClientBootstrap.getInstance().init(userId,token,hosts,1,MainActivity.this);
            }
        });
 
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                ExamPlatformData.getInstance().setTimeArrive_10s(true);
            }
        },10,10, TimeUnit.SECONDS);
 
 
        rtkConfigViewModel  = ViewModelProviders.of(this).get(RTKConfigViewModel.class);
        rtkConfigViewModel.getRTKConfig().observe(this, new Observer<RTKConfig>() {
            @Override
            public void onChanged(RTKConfig rtkConfig) {
 
                MyLog.i(TAG, "RTKConfig Changed: " + (rtkConfig != null ? rtkConfig.toString() : "null"));
 
                if (rtkConfig != null)
                    mRTKConfig = rtkConfig;
 
                synchronized (MainActivity.this){
                        if (ExamPlatformData.getInstance().isCanWriteSD()){
//                            AbsInitialData.getInstance().resethasSendInitData();
                            AbsInitialData.getInstance().sendInitialData();
                            MyLog.i("rtkConfig 更新sn后发送初始数据");
                        }
                }
 
            }
        });
 
 
 
        mPermissionsManager = new PermissionManager(this) {
            @Override
            public void authorized(int requestCode) {
                Log.d(TAG, "requestCode = " + requestCode+Build.VERSION.SDK_INT);
                permissionCount++;
                Log.i(TAG,"fingerPrint="+Build.FINGERPRINT);
                if (Build.FINGERPRINT.contains(Constant.OUR_SYS_IMAGE)){
                    MyLog.i(TAG,"自己的系统");
                    setSDAuthAndSendJudgeArg();
                    return;
                }
                if (permissionCount == PERMISSIONS.length-1){
                    setSDAuthAndSendJudgeArg();
                }
 
            }
 
            @Override
            public void noAuthorization(int requestCode, String[] lackPermissions) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示");
                builder.setMessage("缺少" + lackPermissions + "权限");
                builder.setPositiveButton("设置权限", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PermissionManager.startAppSettings(getApplicationContext());
                    }
                });
                builder.create().show();
            }
 
            @Override
            public void ignore() {
                Log.d(TAG, "requestCode ignore");
            }
        };
 
 
        MyLog.i(TAG, "onCreate");
 
        //加载根Fragment
        if (findFragment(HomeFragment.class) == null) {
            loadRootFragment(R.id.fl_container, HomeFragment.newInstance());
        }
 
        CEventCenter.onBindEvent(true, icEventListener, Constant.BIND_CONNECT_RTK_TOPIC);//收到rtk连接 登录结果
 
    }
 
    private void setSDAuthAndSendJudgeArg() {
        ExamPlatformData.getInstance().setCanWriteSD(true);
        //只要app不销毁(重启)只会请求一次,但是确保PERMISSIONS最后一个元素是writeSD
 
 
        //需要延迟再发送,因为发送蓝牙已连接在前(先不判断蓝牙状态,只要有sn,12/10),收到sn在后,所以延迟发送3 ,可以取得sn
        scheduledExecutorService.schedule(()->{  authMapViewmodel.setAuthValue(3);},2,TimeUnit.SECONDS);
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
 
        CEventCenter.onBindEvent(false, icEventListener, Constant.BIND_CONNECT_RTK_TOPIC);
        Log.i(TAG, "onDestroy: ");
    }
 
 
    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG,"mPermissionManager check");
        mPermissionsManager.checkPermissions(PERMISSIONS_REQUEST_CODE, PERMISSIONS);
    }
 
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mPermissionsManager.recheckPermissions(PERMISSIONS_REQUEST_CODE, permissions, grantResults);
    }
 
    private boolean listContainsSameValue(List<Integer> indexs) {
        for (int i = 0; i < indexs.size(); i++) {
            //可以默认是0  0不判断是否有相同的index
            if (indexs.get(i) == 0){
                continue;
            }
            for (int j=i+1;j<indexs.size();j++){
 
                if (indexs.get(i) == indexs.get(j)){
                    return true;
                }
            }
        }
        return false;
    }
 
    @Override
    public void onConnecting() {
 
        MyLog.i(TAG,"TCP onConnecting");
    }
 
    @Override
    public void onConnected() {
        ExamPlatformData.getInstance().setExamplatformStatus(ExamPlatformData.TCP_CONNECTED);
        MyLog.i("TCP连接成功");
        //TODO 判断SPUtils 是否保存有des密码;如果没有则进行注册JKMessage0100,如果有密码则进行鉴权JKMessage0101
        String hexPwd = (String) SPUtils.get(this,SPUtils.DES_HEX_PWD,"");
        hexPwd="";
        MessageProcessor.getInstance().addBeatHeart(20);
        if (TextUtils.isEmpty(hexPwd)){
 
            MyLog.i(PlatFormConstant.TAG,"密码不存在,进行注册,发送注册消息");
 
            JKMessage0100 jkRegisterMessage = new JKMessage0100();
            if (mRTKConfig!=null){
                jkRegisterMessage.proviceid = mRTKConfig.getProvince();
                jkRegisterMessage.cityid = mRTKConfig.getCity();
                jkRegisterMessage.imei = mRTKConfig.getImei();
                jkRegisterMessage.model = mRTKConfig.getModel();
                jkRegisterMessage.sn = mRTKConfig.getSn();
            }
 
 
            byte[] str = jkRegisterMessage.toBytes();
            MessageProcessor.getInstance().sendMessage(jkRegisterMessage);
            Log.i(TAG, "onClick: "+ BytesUtils.bytesToHexString(str)+" ============");
        }else{
            MyLog.i(PlatFormConstant.TAG,"密码存在,已注册过,直接发鉴权消息");
            JKMessage0101 jkMessage0101 = new JKMessage0101();
            String des = hexPwd;
            long time =  System.currentTimeMillis()/1000;
            int unsignedInt = Utils.parseUnsignedInt(String.valueOf(time),10);
            MyLog.i(String.format("总秒数(long)=%d,装换成unsigned int= %d",time,unsignedInt));
            jkMessage0101.timestamp = unsignedInt;
 
 
            byte[] miwen = Utils.encrypt(com.anyun.im_lib.util.ByteUtil.intGetBytes(unsignedInt),des);
            MyLog.i(PlatFormConstant.TAG,"鉴权密文="+BytesUtils.bytesToHexString(miwen)+" time="+unsignedInt);
            jkMessage0101.des = BytesUtils.bytesToHexString(miwen);
 
            MessageProcessor.getInstance().sendMessage(jkMessage0101);
        }
    }
 
    @Override
    public void onConnectFailed() {
        ExamPlatformData.getInstance().setExamplatformStatus(ExamPlatformData.TCP_DISCONNECT);
        MyLog.i(TAG,"TCP连接失败");
    }
    /**
     * 隐藏虚拟按键,并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键,并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }
 
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_return:
                onBackPressed();
                break;
        }
    }
}