SocketService1.java 28.8 KB
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 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
package com.qnbar.smc.service;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.gimi.common.cinema.model.MessageEvent;
import com.gimi.common.cinema.model.RoomInfo;
import com.gimi.common.cinema.utils.ActivityCollector;
import com.gimi.common.cinema.utils.CToast;
import com.gimi.common.cinema.utils.LogUtils;
import com.gimi.common.cinema.utils.NetStatusUtils;
import com.gimi.common.cinema.utils.ShellUtils;
import com.gimi.common.cinema.utils.SystemUtils;
import com.gimi.common.cinema.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.qnbar.smc.model.Lights;
import com.qnbar.smc.socketProtocol.MainRequest;
import com.qnbar.smc.socketProtocol.MainResponse;
import com.qnbar.smc.socketProtocol.fromServer.EquipmentControl;
import com.qnbar.smc.socketProtocol.fromServer.OpenDoor;
import com.qnbar.smc.socketProtocol.fromServer.ReportEquStatus;
import com.qnbar.smc.socketProtocol.fromServer.VerifyCode;
import com.qnbar.smc.socketProtocol.toServer.EquipmentStatus;
import com.qnbar.smc.socketProtocol.toServer.Heartbeat;
import com.qnbar.smc.socketProtocol.toServer.SocketSendMsg;
import com.qnbar.smc.utils.LightOperationUtils;
import com.telink.bluetooth.light.ConnectionStatus;
import com.telink.bluetooth.light.DeviceInfo;
import com.xgimi.gimicinema.ICinemaControl;
import com.xgimi.gimicinema.activity.AdsPreVideoPlayerActivity;
import com.xgimi.gimicinema.activity.MainActivity;
import com.xgimi.gimicinema.activity.QrCodeShowActivity;
import com.xgimi.gimicinema.activity.SimpleAdsPlayer2;
import com.xgimi.gimicinema.application.FangTangApplication;
import com.xgimi.gimicinema.poll.PollingUtils;
import com.xgimi.gimicinema.service.CinemaControlService;
import com.xgimi.gimicinema.service.CountService;
import com.xgimi.smartscreen.encrypt.AuthCode;
import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class SocketService1 extends BaseService {
    private static final String TAG = "BackService";
    private static final long HEART_BEAT_RATE = 2 * 1000;
    private final long READ_THREAD_DEFAULT_SLEEP_MTIME = 100;
    public static final int JUST_OPEN_DOOR = 1701;
    public static final int USER_OPEN_DOOR_AND_GET_MOVIE = 1703;
    public static final int USER_OPEN_DOOR = 1704;
    private static final int HEART_BEAT_SUCCESS = 9997;
    private static final int RETURN_VERIFY_CODE = 9998;
    private static final int VERIFY_SUCCESS = 9999;
    private static final int SUCCESS_MESSAGE = 10000;
    private static final int CONTAIN_MESSAGE = 10001;
    private static final int AUTHENTICATION_FAILED = 10002; //连接(认证)失败
    private static final int CONNECTION_BEFORE_AUTHENTICATION = 10003;//还未注册连接就进行认证
    private static final int NOT_SEND_ROOM_SN = 10004;//终端编号未传
    private static final int HEART_BEAR_ERROR = 10005; //心跳异常,没有找到房间连接信息
    private static final int HEART_BEAT_ERROR_SYMBOL = 10006;//心跳异常,连接标识符不一致
    private static final int ROOM_SN_CONNECTED = 10010;//room_sn 已连接,不能再连接
    private static final int OPEN_DOOR = 50001;//开门命令
    private static final int CLEAN_OVER = 50002;//
    private static final int REPORT_EQU_STATUS = 50003;//返回设备状态信息
    private static final int SET_EQU_STATUS = 50004;//返回设备状态信息

    private static final int HEART_BEAT = 20025;
    private static final int CMD_REPORT_EQU_STATUS = 20030;//上报设备状态信息

    //    online
    public static final String SERVER_HOST_ONLINE = "conn.ft.qnbar.com";// "192.168.1.21";//
    public static final int SERVER_PORT_ONLINE = 8899;

    //    develop
    public static final String SERVER_HOST_DEVELOP = "10.10.4.6";// "192.168.1.21";//
    public static final int SERVER_PORT_DEVELOP = 9501;
    //    test
    public static final String SERVER_HOST = "10.10.4.6";// "192.168.1.21";//
    public static final int SERVER_PORT = 8899;

    private String serverHost = SERVER_HOST;
    private int serverPort = SERVER_PORT;

    public int heartbeatNum = 0;

    public static final String END_SYMBOL = "\\r\\n\\r\\n";//心跳包内容
    public String testRoomSn = "c";

    private Gson gson = new Gson();
    private Socket socket = null;
    StringBuilder readingMsg = new StringBuilder();

    // For heart Beat
    private Handler mHandler = new Handler();

    AtomicBoolean sendRegister = new AtomicBoolean(false);
    AtomicInteger heartBeatErrorCount = new AtomicInteger(0);

    public ICinemaControl iPlayer = null;
    private ServiceConnection conn = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            LogUtils.i("bind cinema control service success");
            iPlayer = ICinemaControl.Stub.asInterface(service);
        }

        public void onServiceDisconnected(ComponentName className) {
            LogUtils.i("cinema control service error");
        }
    };

    public Runnable heartBeatRunnable = new Runnable() {

        @Override
        public void run() {
            mHandler.postDelayed(this, HEART_BEAT_RATE);
            //就发送一个HEART_BEAT_STRING过去 如果发送失败,就重新初始化一个socket
            Heartbeat heartbeat = new Heartbeat();
            if (heartbeatNum > 10) {
                heartbeat.setLightStatus(getLightStatus());
                heartbeat.setPlayStatus(getPlayStatus());
                heartbeat.setVolume(getAudioVolume() / 6 + 1);
            } else {
                heartbeatNum++;
            }
            heartbeat.setRoom_sn(testRoomSn);
            MainRequest rep = new MainRequest();
            rep.setCmd(HEART_BEAT);
            rep.setData(heartbeat);
            String msg = gson.toJson(rep);
            boolean isSuccess = sendMsg(msg + END_SYMBOL);
            if (!isSuccess) {
                LogUtils.i(TAG, "send heart beat error restart");
            }
        }
    };
    int mainChargeCount = 0;
    private Runnable startMainRunnable = new Runnable() {
        @Override
        public void run() {
            if (ActivityCollector.getActivity(MainActivity.class) == null) {
                LogUtils.i(TAG, "do start main activity");
                Intent intent = new Intent(context, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            } else {
                LogUtils.i(TAG, "already start main activity");
            }
        }
    };

    private Context context = this;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.i(TAG, "onCreate");
        bindService(new Intent(SocketService1.this, CinemaControlService.class), conn, Context.BIND_AUTO_CREATE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        LogUtils.i(TAG, "onStartCommand");
        int ftTest = Utils.getInt(this, "ft-test", 0);
        switch (ftTest) {
            case 0:
                serverHost = SERVER_HOST_ONLINE;
                serverPort = SERVER_PORT_ONLINE;
                break;
            case 1:
                serverHost = SERVER_HOST_DEVELOP;
                serverPort = SERVER_PORT_DEVELOP;
                break;
            case 2:
                serverHost = SERVER_HOST;
                serverPort = SERVER_PORT;
                break;
        }

        String roomInfoStr = Utils.getString(this, "room-info");
        if (TextUtils.isEmpty(roomInfoStr)) {
            LogUtils.i("room-info", "room info not exist");
            Toast.makeText(this, "没有获取到房间信息,请查看后台配置", Toast.LENGTH_SHORT).show();
            return super.onStartCommand(intent, flags, startId);
        }

        LogUtils.i("room-info", "room info not null");
        RoomInfo roomInfo;
        try {
            roomInfo = gson.fromJson(roomInfoStr, RoomInfo.class);
            LogUtils.i("room-info", "room info room_sn update");
            testRoomSn = roomInfo.getData().getRoom_sn();
        } catch (JsonSyntaxException e) {
            LogUtils.i("room-info", "room gson parse exception return");
            Toast.makeText(this, "房间信息配置出错,请重新进入应用获取", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            return super.onStartCommand(intent, flags, startId);
        }
        new InitSocketThread().start();
        new ReadThread().start();
        return START_STICKY;
    }

    ///begin socket operation
    private synchronized void initSocket() throws IOException {//初始化Socket
        if (socket != null && socket.isConnected()) {
            return;
        }
        boolean networkConnected = NetStatusUtils.isNetworkConnected(context);
        boolean availableByPing = NetStatusUtils.isAvailableByPing("www.baidu.com");
        boolean availableByPing1 = NetStatusUtils.isAvailableByPing(serverHost);
        boolean availableByPing2 = NetStatusUtils.isAvailableByPing("192.168.200.241");
        LogUtils.i(TAG, "init socket serverHost:serverPort:" + serverHost + ":" + serverPort);
        LogUtils.i(TAG, "networkConnected:" + networkConnected + ":baidu:" + availableByPing + ",serverHost:" + availableByPing1 + ",serverIp:" + availableByPing2);
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                CToast.makeText(context, "开始连接服务器", 10 * 1000).show();
            }
        });
        socket = new Socket(serverHost, serverPort);
        socket.setSoTimeout(100);
        readingMsg.setLength(0);
    }


    private synchronized boolean sendMsg(String msg) {
        if (socket == null || !socket.isConnected()) {
            return false;
        }
        if (!msg.contains("20025")) {
            LogUtils.i(TAG, "send msg:" + msg);
        } else {
            if (heartBeatErrorCount.getAndIncrement() > 3) {
                LogUtils.i(TAG, "heartBeatErrorCount:" + heartBeatErrorCount.get());
                clearConnect();
                return false;
            }
            LogUtils.d(TAG, "send heart beat msg:" + msg);
        }
        Socket soc = socket;
        try {
            if (!soc.isClosed() && !soc.isOutputShutdown()) {
                OutputStream os = soc.getOutputStream();
                os.write(msg.getBytes());
                os.flush();
            } else {
                return false;
            }
        } catch (IOException e) {
            LogUtils.e(TAG, "error" + e.getMessage());
            e.printStackTrace();
            clearConnect();
            return false;
        }
        return true;
    }

    private synchronized void releaseLastSocket() {
        try {
            if (null != socket) {
                socket.close();
            }
        } catch (IOException e) {
            LogUtils.e(TAG, "error" + e.getMessage());
            e.printStackTrace();
        } finally {
            socket = null;
            readingMsg.setLength(0);
        }
    }

    private synchronized boolean recvMsg(StringBuilder msg) {
        if (null == socket || !socket.isConnected()) {
            return false;
        }
        try {
            if (readingMsg.length() > 0) {
                int pos = readingMsg.indexOf(END_SYMBOL);
                if (pos != -1) {
                    msg.setLength(0);
                    msg.append(readingMsg.substring(0, pos));
                    readingMsg.delete(0, pos + END_SYMBOL.length());
                    LogUtils.d("recvMsg", "from last:" + msg.length() + ":" + msg);
                    return true;
                }
            }
            InputStream is = socket.getInputStream();
            byte[] buffer = new byte[1024];
            int length = 0;
            int msgId = 0;
            while (!socket.isClosed()
                    && !socket.isInputShutdown()
                    && ((length = is.read(buffer)) > 0)) {
                String tmp = new String(Arrays.copyOf(buffer, length));
                readingMsg.append(tmp);
                int pos = readingMsg.indexOf(END_SYMBOL);
                if (pos != -1) {
                    msg.setLength(0);
                    msg.append(readingMsg.substring(0, pos));
                    readingMsg.delete(0, pos + END_SYMBOL.length());
                    return true;
                }
                msgId++;
            }
        } catch (InterruptedIOException e) {
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            LogUtils.e(TAG, e.getMessage());
            clearConnect();
            return false;
        }
        return false;
    }

    private synchronized void clearConnect() {
        LogUtils.i(TAG, "clearConnect");
        mHandler.removeCallbacks(heartBeatRunnable);
        sendRegister.set(false);
        heartBeatErrorCount.set(0);
        releaseLastSocket();
    }
    ///end socket operation

    class InitSocketThread extends Thread {
        @Override
        public void run() {
            while (!isInterrupted()) {
                try {
                    initSocket();
                } catch (IOException e) {
                    e.printStackTrace();
                    LogUtils.e(TAG, "init socket thread error,restart again after " + HEART_BEAT_RATE / 1000 + " seconds");
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                    LogUtils.e(TAG, "error" + e1.getMessage());
                    e1.printStackTrace();
                }
            }
        }
    }

    // Thread to read content from Socket
    class ReadThread extends Thread {
        private long sleepTime = 0;

        @Override
        public void run() {
            StringBuilder message = new StringBuilder();
            while (!isInterrupted()) {
                if (!sendRegister.get()) {
                    SocketSendMsg ssm = new SocketSendMsg().contractRegisterMsg(testRoomSn);
                    String msg = gson.toJson(ssm) + END_SYMBOL;
                    LogUtils.i(TAG, "send register mes:" + msg);
                    if (!sendMsg(msg)) {
                        try {
                            Thread.sleep(READ_THREAD_DEFAULT_SLEEP_MTIME);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        continue;
                    }
                    sendRegister.set(true);
                }

                sleepTime = READ_THREAD_DEFAULT_SLEEP_MTIME;
                while (recvMsg(message)) {
                    sleepTime = READ_THREAD_DEFAULT_SLEEP_MTIME;
                    LogUtils.d(TAG, "recv msg:" + message);
                    MainResponse socketResponse;
                    try {
                        socketResponse = gson.fromJson(message.toString(), MainResponse.class);
                        if (socketResponse.getCode() != HEART_BEAT_SUCCESS) {
                            LogUtils.i(TAG, "recv msg:" + message);
                        }
                    } catch (JsonSyntaxException e) {
                        LogUtils.e(TAG, "invalid msg:", message + e.getMessage());
                        e.printStackTrace();
                        clearConnect();
                        break;
                    }

                    switch (socketResponse.getCode()) {
                        case SUCCESS_MESSAGE:
                            heartBeatErrorCount.set(0);
                            Log.d(TAG, "SUCCESS_MESSAGE");
                            break;
                        case VERIFY_SUCCESS:
                            mHandler.post(heartBeatRunnable);
                            LogUtils.i(TAG, "verify success start heart beat");
                            break;
                        case HEART_BEAT_SUCCESS:
                            LogUtils.d(TAG, "HEART_BEAT_SUCCESS,MainActivity Launched:" + ActivityCollector.isActivityExist(MainActivity.class));
                            heartBeatErrorCount.set(0);
                            //每成功5次心跳判定是否启动main activity
                            if (++mainChargeCount == 5) {
                                mainChargeCount = 0;
                                if (heartBeatErrorCount.get() < 3) {
                                    LogUtils.i(TAG, "heart beat regular");
                                }
                                if (!ActivityCollector.isActivityExist(MainActivity.class)) {
                                    LogUtils.i(TAG, "charge start main activity");
                                    mHandler.postDelayed(startMainRunnable, 3 * 1000);
                                }
                            }
                            break;
                        case HEART_BEAT_ERROR_SYMBOL:
                        case ROOM_SN_CONNECTED:
                            String msg1 = socketResponse.getCode() == HEART_BEAT_ERROR_SYMBOL ? "HEART_BEAT_ERROR_SYMBOL" : "ROOM_SN_CONNECTED";
                            LogUtils.e(TAG, msg1);
                            clearConnect();
                            break;
                        case RETURN_VERIFY_CODE:
                            LogUtils.i(TAG, "RETURN_VERIFY_CODE");
                            if (!TextUtils.isEmpty(socketResponse.getData())) {
                                VerifyCode verifyResponse = gson.fromJson(socketResponse.getData(), VerifyCode.class);
                                if (!TextUtils.isEmpty(verifyResponse.getVerify())) {
                                    String verifyMsg = AuthCode.getDecodeStr(verifyResponse.getVerify());
                                    SocketSendMsg ssm = new SocketSendMsg().contractVerifyMsg(testRoomSn, verifyMsg);
                                    String msg = gson.toJson(ssm) + END_SYMBOL;
                                    sendMsg(msg);
                                }
                            }
                            break;
                        case CONTAIN_MESSAGE:
                            heartBeatErrorCount.set(0);
                            LogUtils.i(TAG, "CONTAIN_MESSAGE");
                            serverCommandDeal(socketResponse);
                            break;
                        default:
                            clearConnect();
                            LogUtils.i(TAG, "default msg clearConnect:" + socketResponse.toString());
                    }
                }
                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    continue;
                }
            }
        }
    }

    private void sendMessage(int type, String msg) {
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setEventId(type);
        messageEvent.setMessage(msg);
        EventBus.getDefault().post(messageEvent);
    }

    @Override
    public void onDestroy() {
        LogUtils.i(TAG, "socket service destroy");
        super.onDestroy();
    }

    /**
     * 处理服务器发送的命令
     *
     * @param socketResponse
     */
    private void serverCommandDeal(MainResponse socketResponse) {
        switch (socketResponse.getCmd()) {
            case OPEN_DOOR://开门
                if (socketResponse.getData() != null) {
                    OpenDoor openDoorResponse = gson.fromJson(socketResponse.getData(), OpenDoor.class);
                    openDoor(openDoorResponse);
                }
                break;
            case CLEAN_OVER://清洁完成处理
                LogUtils.i("LightOperationUtils", "admin clean over close light");
                LightOperationUtils.setLightValue(5);
                LightOperationUtils.close();
                new SystemUtils().closeFtLed(context.getApplicationContext());
                sendMessage(QrCodeShowActivity.KILL_SELF, "finish the QR CODE activity when clean over");
                if (ActivityCollector.isActivityExist(SimpleAdsPlayer2.class)) {
                    ActivityCollector.getActivity(SimpleAdsPlayer2.class).finish();
                }
                if (ActivityCollector.isActivityExist(AdsPreVideoPlayerActivity.class)) {
                    ActivityCollector.getActivity(AdsPreVideoPlayerActivity.class).finish();
                }
                if (ActivityCollector.isActivityExist(QrCodeShowActivity.class)) {
                    ActivityCollector.getActivity(QrCodeShowActivity.class).finish();
                }
                try {
                    PollingUtils.stopPollingService(context, CountService.class, CountService.STATUS_ACTION);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case REPORT_EQU_STATUS:
                //获取声音,灯光,播放暂停状态并上报
                //获取serverId
                ReportEquStatus rps = gson.fromJson(socketResponse.getData(), ReportEquStatus.class);
                reportEquStatus(rps.getServerId(), 0);
                break;
            case SET_EQU_STATUS://设置声音,灯光,播放暂停
                LogUtils.i("ReportInfo", "收到控制命令:" + socketResponse.getData());
                EquipmentControl equc = gson.fromJson(socketResponse.getData(), EquipmentControl.class);
                setEquipmentStatus(equc);
                break;
        }
    }

    private void openDoor(OpenDoor openDoorResponse) {
        switch (openDoorResponse.getUser()) {
            //10用户,20管理员,默认值为0
            case 10:
                new SystemUtils().openFtLed(context.getApplicationContext());
                if (TextUtils.isEmpty(((FangTangApplication) getApplication()).getCurrentPlayUrl())) {
                    LightOperationUtils.open();
                    LightOperationUtils.setLightValue(Utils.getInt(context, "brightness", 50));
                }
                sendMessage(QrCodeShowActivity.KILL_SELF, "finish the QR CODE activity when new user come in");
                if (openDoorResponse.getFirst() == 1) {
                    sendMessage(USER_OPEN_DOOR_AND_GET_MOVIE, "user first open the door");
                } else {
                    sendMessage(USER_OPEN_DOOR, "user open the door");
                }
                break;
            case 20:
                LogUtils.i(TAG, "admin open the door,del the log");
                LogUtils.delLog();
                if (TextUtils.isEmpty(((FangTangApplication) getApplication()).getCurrentPlayUrl())) {
                    LogUtils.i("LightOperationUtils", "admin open light");
                    LightOperationUtils.open();
                    LightOperationUtils.setLightValue(Utils.getInt(context, "brightness", 50));
                }
                sendMessage(JUST_OPEN_DOOR, "administrator open the door");
                break;
            case 0:
                sendMessage(JUST_OPEN_DOOR, "get zero none user or administrator open the door");
                break;
            default:
                sendMessage(JUST_OPEN_DOOR, "none user or administrator open the door");
                break;
        }
    }

    private void reportEquStatus(String serverId, int lightSet) {
        //填充返回数据
        int volume = getAudioVolume() / 6 + 1;
        int playStatus = getPlayStatus();
        int lightStatus;
        if (lightSet == 1 || lightSet == 2) {
            lightStatus = lightSet;
        } else {
            lightStatus = getLightStatus();
        }

        EquipmentStatus equStatus = new EquipmentStatus();
        equStatus.setLightStatus(lightStatus);
        equStatus.setPlayStatus(playStatus);
        equStatus.setVolume(volume);
        equStatus.setServerId(serverId);
        equStatus.setRoom_sn(testRoomSn);

        MainRequest rep = new MainRequest();
        rep.setCmd(CMD_REPORT_EQU_STATUS);
        rep.setData(equStatus);
        String msg = gson.toJson(rep) + END_SYMBOL;
        sendMsg(msg);
        Log.d("ReportInfo", msg);
    }

    private static final int SERVER_CMD_OPEN_LIGHT = 1;
    private static final int SERVER_CMD_CLOSE_LIGHT = 2;

    private void setLight(int op) {
        if (op == SERVER_CMD_OPEN_LIGHT) {//打开灯光
            Log.d("setEqu", "打开灯光");
            if (iPlayer != null) {
                try {
                    iPlayer.openLight();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        } else if (op == SERVER_CMD_CLOSE_LIGHT) {//关闭灯光
            Log.d("setEqu", "关闭灯光");
            if (iPlayer != null) {
                try {
                    iPlayer.closeLight();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void playCtl(int op) {
        int status = -1;

        if (iPlayer == null) {
            LogUtils.i("iPlayer is null");
            return;
        }
        try {
            status = iPlayer.getCurrentStatus();
        } catch (RemoteException e) {
            e.printStackTrace();
        }

        if (op == 1 && status == 2) {
            Log.d("setEqu", "开始播放");
            ShellUtils.execCommand("input keyevent 23", false);
        } else if (op == 2 && status == 1) {
            Log.d("setEqu", "暂停播放");
            ShellUtils.execCommand("input keyevent 23", false);
        }
    }

    private void setEquipmentStatus(EquipmentControl equc) {
        setLight(equc.getLightCtl());
        playCtl(equc.getPlayCtl());
        setAudioVolume(equc.getAudioCtl());
        reportEquStatus(equc.getServerId(), equc.getLightCtl());
    }

    public int getAudioVolume() {
        AudioManager mAudioManager;
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        return mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    }

    public int getPlayStatus() {
        int playStatus = 0;
        if (iPlayer == null) {
            return playStatus;
        }
        try {
            playStatus = iPlayer.getCurrentStatus();
            Log.d("ReportInfo", "playStatus:" + playStatus);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        if (playStatus == 0) {
            boolean bool = ActivityCollector.isActivityExist(AdsPreVideoPlayerActivity.class);
            Log.d("ReportInfo", "广告状态:" + bool);
            if (bool) {
                playStatus = 3;
            }
        }
        return playStatus;
    }

    public int getLightStatus() {
        int lightStatus = 2;
        try {
            DeviceInfo connectDevice = ((FangTangApplication) getApplication()).
                    getConnectDevice();
            if (connectDevice == null) {
                LogUtils.i(TAG, "connectDevice is null");
                return lightStatus;
            }
            ConnectionStatus stu = Lights.getInstance().
                    getByMeshAddress(connectDevice.meshAddress).status;
            if (stu == ConnectionStatus.ON) {
                Log.d("ReportInfo", "lightStatus==1");
                lightStatus = 1;
            } else {
                Log.d("ReportInfo", "lightStatus:" + stu);
            }
        } catch (Exception e) {
            e.printStackTrace();
            lightStatus = 0;//获取失败
        }
        return lightStatus;
    }

    private int setAudioVolume(int volume) {
        AudioManager mAudioManager;
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int now = getAudioVolume() / 6;

        if (volume == 0) {
            return now;
        } else {
            volume--;
        }

        if (volume > now) {//加音量
            Log.d("setEqu", "加音量" + now + ":" + volume);
            while (now < volume) {
                mAudioManager.adjustStreamVolume(
                        AudioManager.STREAM_MUSIC,
                        AudioManager.ADJUST_RAISE,
                        AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
                now++;
            }
        } else if (volume < now) {//减音量
            Log.d("setEqu", "减音量" + now + ":" + volume);
            while (now > volume) {
                mAudioManager.adjustStreamVolume(
                        AudioManager.STREAM_MUSIC,
                        AudioManager.ADJUST_LOWER,
                        AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
                now--;
            }
        }

        return now;
    }

}