yy1717
2020-11-24 6e0f29b08a040d14576d7053c1206a8439936570
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
package com.anyun.exam.lib;
 
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Process;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Base64;
import android.util.Log;
 
import com.anyun.exam.lib.util.Bluetooth;
import com.anyun.exam.lib.util.BluetoothChatService;
import com.anyun.exam.lib.util.BluetoothChatServiceCallback;
import com.anyun.exam.lib.util.Constants;
import com.anyun.exam.lib.util.DESUtil;
import com.anyun.exam.lib.util.NetUtils;
import com.anyun.exam.lib.util.ProperUtil;
import com.anyun.exam.lib.util.Speaker;
import com.anyun.exam.lib.util.SpeakerCallback;
 
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
 
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
 
/**
 * MyApplication2
 * Created by lzw on 2019/6/5. 13:22:46
 * 邮箱:632393724@qq.com
 * All Rights Saved! Chongqing AnYun Tech co. LTD
 */
public class RemoteService extends Service {
    private static final String TAG = "RemoteService";
    /**服务是否销毁标志*/
    private AtomicBoolean mIsServiceDestroyed = new AtomicBoolean(false);
    private RemoteCallbackList<IListenerInterface> mListenerList = new RemoteCallbackList();
    private IListenerInterface mListener;
    private int msgId = 0;
    private Speaker speaker = null;
    private boolean ttsInitSucc = false;
    private int ringIndex = -1;
    private Uri ringUri = null;
 
    private Upgrade upgrade = null;
 
    private Bluetooth mBluetooth = null;
    private BluetoothChatService mChatService = null;
    private String mConnectedDeviceName = null;
    private String mTargetBluetooth = null;
    private String mTargetBluetoothAddr = null;
    private boolean mDiscoveryBluetooth = false;
 
    private IRemoteInterface.Stub iRemoteInterface = new IRemoteInterface.Stub(){
        @Override
        public void registListener(IListenerInterface i) throws RemoteException {
            //注册回调方法
            mListenerList.register(i);
        }
 
        @Override
        public void unRegistListener(IListenerInterface i) throws RemoteException {
            mListenerList.unregister(i);
        }
 
        @Override
        public void add() throws RemoteException {
                Log.i(TAG,"客户端调用服务端方法");
        }
 
        @Override
        public void SendCmd(int cmd, String value) throws RemoteException {
            if (cmd == 0x8100) {
                try {
                    byte [] file = value.getBytes("ISO-8859-1");
//                    Log.d(TAG, byte2hex(file));
                    MainProcBinMsgEntry(cmd, file, file.length);
                } catch (UnsupportedEncodingException e) {
                    Log.d(TAG, "UnsupportedEncodingException");
                }
            } else {
                Log.d(TAG, "Process " + Process.myPid() + " Thread " + Thread.currentThread().getId() + " RecvMsgFromMainProc cmd = " + String.format(" %04X ", cmd) + " length " + value.length());
                MainProcMsgEntry(cmd, value.trim());
            }
        }
    };
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return iRemoteInterface;
    }
 
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG,"onCreate()");
        speaker = new Speaker(/*getApplicationContext()*/this, new TTSCallback());
 
        new Thread(new StartNative()).start();
 
        new Thread(new TestThread()).start();
 
//        new Thread(new AutoUpdateMcuThread(this)).start();
 
        upgrade = Upgrade.getInstance(getApplicationContext());
        upgrade.CheckUpgrade();
 
        ringUri = GetRingIndex(this, "Antimony");
//        PlayRing(this, ringUri);
        LimitMaxMinVolume();
 
        Log.d(TAG, "基带版本 " + getBaseband_Ver());
 
        String ver = getBaseband_Ver();
 
        mBluetooth = Bluetooth.getInstance(getApplicationContext(), mHandler);
        mBluetooth.OpenBluetooth();
        // Initialize the BluetoothChatService to perform mBluetooth connections
        mChatService = new BluetoothChatService(this, mHandler);
    }
 
    class AutoUpdateMcuThread implements Runnable {
        private Context context;
 
        public AutoUpdateMcuThread(Context context) {
            this.context = context;
        }
 
        @Override
        public void run() {
            Properties proper = ProperUtil.getProperties(getApplicationContext());
            if (proper != null) {
                String assetVer = proper.getProperty("mcuVersion");
 
                if (assetVer != null) {
                    try {
                        InputStream inputStream = context.getAssets().open("dfu.bin");
 
                        if (inputStream != null) {
                            int fileLength = inputStream.available();
                            Log.d(TAG, "AutoUpdateMcu " + fileLength);
 
                            if (fileLength > 0) {
                                byte[] temp = new byte[fileLength];
                                inputStream.read(temp);
 
                                UpgradeMcu(assetVer, temp);
                            }
                            inputStream.close();
                        }
                    } catch (IOException e) {
 
                    }
                }
            }
 
        }
    }
 
    private void LimitMaxMinVolume() {
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if (audioManager != null) {
            int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_RING);
            int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
            Log.d(TAG, String.format("Ring音量 = %d Max = %d", currentVolume, maxVolume));
 
            if (currentVolume < maxVolume - 1) {
                Log.d(TAG, "调至默认Ring音量");
                audioManager.setStreamVolume(AudioManager.STREAM_RING, maxVolume - 1, 0);
            }
        }
    }
 
    public String getBaseband_Ver(){
        String Version = "";
        try {
            Class cl = Class.forName("android.os.SystemProperties");
            Object invoker = cl.newInstance();
            Method m = cl.getMethod("get", new Class[] { String.class,String.class });
            Object result = m.invoke(invoker, new Object[]{"gsm.version.baseband", "no message"});
            Version = (String)result;
        } catch (Exception e) {
 
        }
        return Version;
    }
 
    private Uri GetRingIndex(Context context, String ring) {
        RingtoneManager ringtoneManager= new RingtoneManager(context); // 铃声管理器
        ringtoneManager.setType(RingtoneManager.TYPE_NOTIFICATION);
        for (int i = 0; i < ringtoneManager.getCursor().getCount(); i++) {
            if (ringtoneManager.getRingtone(i).getTitle(context).equals(ring)) {
                Log.d(TAG, "得到铃声 " + i);
                return ringtoneManager.getRingtoneUri(i);
            }
        }
        return null;
    }
 
    public void PlayRing(Context context, Uri src) {
        if (src == null)
            return;
        
        final MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(context, src);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
            mediaPlayer.setLooping(false);
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    // 在播放完毕被回调
                    Log.d(TAG, "播放完成");
                    mediaPlayer.stop();
                    mediaPlayer.release();
                }
            });
 
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    // 装载完毕回调
                    Log.d(TAG, "装载完毕回调");
                    mediaPlayer.start();
                }
            });
 
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }
 
    class TestThread implements Runnable {
        @Override
        public void run() {
            try {
                Thread.sleep(30000);
 
//                Ota ota = new Ota();
//                ota.excuteUpdateZip(getApplicationContext(), "");
            } catch (InterruptedException e) {
 
            }
        }
    }
 
    class StartNative implements Runnable {
        @Override
        public void run() {
            startNative();
        }
    }
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG,"onDestroy");
 
        if (mChatService != null) {
            mChatService.stop();
        }
        if (mBluetooth != null) {
            mBluetooth.CloseBluetooth();
            mBluetooth.unRegisterReceiver();
        }
 
        mIsServiceDestroyed.set(true);
 
        Log.d(TAG, "onDestory executed 进程 " + Process.myPid());
        Process.killProcess(Process.myPid());
    }
 
    private void onMessageArrived(int cmd, String json) {
 
        Log.d(TAG, "SendMsgToMainProc cmd = " + String.format("%04X", cmd) + " json = " + json);
        int N = mListenerList.getRegisteredCallbackCount();
 
        synchronized(this) {
            mListenerList.beginBroadcast();
            for (int i = 0; i < N; i++) {
                mListener = mListenerList.getBroadcastItem(i);
                if (mListener != null) {
                    try {
                        mListener.onMessageArrived(cmd, json);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
            mListenerList.finishBroadcast();
        }
    }
 
    public void SendMsgToMainProc(int cmd, String value) {
        if (!mIsServiceDestroyed.get()){
            onMessageArrived(cmd, value);
        }
    }
 
    public String javaDESEncrypt(String plaintext, String key) {
        try {
            byte []des = DESUtil.encrypt(plaintext.getBytes("utf-8"), key);
            return Base64.encodeToString(des, Base64.DEFAULT);
        } catch (Exception e) {
 
        }
        return null;
    }
 
    public byte[] javaDESEncrypt(byte []plaintext, byte []key) {
        try {
            return DESUtil.encrypt(plaintext, key);
        } catch (Exception e) {
 
        }
        return null;
    }
 
    public void PlayBreakRing() {
        if (ringUri != null) {
            PlayRing(this, ringUri);
        }
    }
 
    public void TextSpeak(String text, int id) {
        if (speaker != null && ttsInitSucc) {
            speaker.speak(text, Integer.toString(id));
        } else {
            TextSpeakEnd(id);
        }
    }
 
    public void TextSpeakInitCallback(boolean ret) {
        ttsInitSucc = ret;
    }
 
    private String byte2hex(byte [] buffer){
        StringBuilder h = new StringBuilder();
 
        Log.d(TAG, "byte buffer length = " + buffer.length);
 
        for(int i = 0; i < buffer.length; i++){
            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if(temp.length() == 1){
                temp = "0" + temp;
            }
            h.append(temp);
            h.append(" ");
        }
 
        return h.toString();
    }
 
    class TTSCallback implements SpeakerCallback {
        @Override
        public void PlayInit(boolean ret) {
            Log.d(TAG, "TTS引擎初始化成功");
            ttsInitSucc = ret;
        }
 
        @Override
        public void PlayStart(String s) {
            Log.d(TAG, "TTS引擎播放开始");
        }
 
        @Override
        public void PlayDone(String s) {
            Log.d(TAG, "TTS引擎播放结束");
            TextSpeakEnd(Integer.valueOf(s));
        }
 
        @Override
        public void PlayError(String s) {
            Log.d(TAG, "TTS引擎播放出错");
            TextSpeakEnd(Integer.valueOf(s));
        }
    }
 
    public void ConnectBluetooth(String name, String pin) {
        if (mBluetooth != null && mChatService != null) {
            mBluetooth.SetPin(pin);
            mTargetBluetooth = name;
            if (isMac(name)) {
                mTargetBluetoothAddr = name;
                handlerConnectBluetooth.removeCallbacks(runnableConnectBluetooth);
                handlerConnectBluetooth.postDelayed(runnableConnectBluetooth, 500);
            } else {
                mDiscoveryBluetooth = true;
                mBluetooth.doDiscovery(name);
            }
        }
    }
 
    Handler handlerConnectBluetooth = new Handler();
    Runnable runnableConnectBluetooth = new Runnable() {
        @Override
        public void run() {
            if (mChatService != null && mTargetBluetoothAddr != null) {
                mChatService.connect(mTargetBluetoothAddr, true);
            }
        }
    };
 
    public boolean isMac(String addr) {
        String pattern = "^([0-9A-Fa-f]{2})(:[0-9A-Fa-f]{2}){5}$";
        return Pattern.matches(pattern, addr);
    }
 
    public void WriteBluetooth(byte []data) {
        if (mChatService != null && mChatService.getState() == BluetoothChatService.STATE_CONNECTED) {
            mChatService.write(data);
        }
    }
 
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.MESSAGE_BLUETOOTH_STATUS:
                    if (msg.arg1 == 1) {
                        Log.d(TAG, "蓝牙开启");
//                        mBluetooth.doDiscovery();
                        if (mChatService != null) {
//                            mChatService.connect("00:1D:43:9A:E0:79", true);
//                            mChatService.connect("00:1A:7D:DA:71:11", true);
                        }
                        BluetoothStatusChange(1);
                    } else {
                        Log.d(TAG, "蓝牙关闭");
                        BluetoothStatusChange(0);
                    }
                    break;
                case Constants.MESSAGE_BLUETOOTH_FOUND:
                    String btaddr = msg.getData().getString(Constants.DEVICE_ADDRESS);
                    Log.d(TAG, "发现设备 " + btaddr);
                    if (mDiscoveryBluetooth) {
                        mTargetBluetoothAddr = btaddr;
                    }
                    break;
                case Constants.MESSAGE_BLUETOOTH_DISCOVERY_FINISHED:
                    Log.d(TAG, "搜索结束");
                    if (mDiscoveryBluetooth) {
                        handlerConnectBluetooth.removeCallbacks(runnableConnectBluetooth);
                        handlerConnectBluetooth.postDelayed(runnableConnectBluetooth, 500);
                    }
                    mDiscoveryBluetooth = false;
                    break;
                case Constants.MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case BluetoothChatService.STATE_CONNECTED:
                            Log.d(TAG, "蓝牙已连接");
                            BluetoothStatusChange(3);
                            break;
                        case BluetoothChatService.STATE_CONNECTING:
                            Log.d(TAG, "蓝牙连接中...");
                            break;
                        case BluetoothChatService.STATE_LISTEN:
                            Log.d(TAG, "蓝牙监听");
                            BluetoothStatusChange(2);
                            break;
                        case BluetoothChatService.STATE_NONE:
                            Log.d(TAG, "蓝牙无效");
                            BluetoothStatusChange(2);
                            handlerConnectBluetooth.removeCallbacks(runnableConnectBluetooth);
                            handlerConnectBluetooth.postDelayed(runnableConnectBluetooth, 5000);
                            break;
                    }
                    break;
                case Constants.MESSAGE_WRITE:
                    break;
                case Constants.MESSAGE_READ:
//                    Log.d(TAG, String.format("蓝牙数据 length = %d 线程 %d", msg.arg1, Thread.currentThread().getId()));
                    BluetoothDataComeIn((byte[]) msg.obj, msg.arg1);
                    /*if (ndkUtils != null) {
                        byte[] readBuf = (byte[]) msg.obj;
                        ndkUtils.bluetoothMoreData(readBuf, msg.arg1);
                    }*/
                    break;
                case Constants.MESSAGE_DEVICE_NAME:
                    // save the connected device's name
                    mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
                    Log.d(TAG, "MESSAGE_DEVICE_NAME: " + mConnectedDeviceName);
                    break;
                case Constants.MESSAGE_TOAST:
                    break;
                    default:break;
            }
        }
    };
 
    class DataCallback implements BluetoothChatServiceCallback {
        @Override
        public void iDataComeIn(byte []data, int length) {
 
        }
    }
 
    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }
 
    public native void startNative();
    public native void MainProcMsgEntry(int cmd, String value);
    public native void MainProcBinMsgEntry(int cmd, byte []data, int length);
    public native void UpgradeMcu(String vercode, byte []rom);
    public native void TextSpeakEnd(int id);
    public native void BluetoothStatusChange(int status);
    public native void BluetoothDataComeIn(byte []data, int length);
}