SmartControlService.java 30.4 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
package com.qnbar.smc.service;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.bluetoothle.BLEBroadcastReceiver;
import com.bluetoothle.GREENBluetoothLeService;
import com.bluetoothle.greencity.GREENBLE;
import com.bluetoothle.greencity.GREENCITYBLEProtocolFactory;
import com.gimi.common.cinema.db.NewDBManager;
import com.gimi.common.cinema.model.Constant;
import com.gimi.common.cinema.model.LocalMovieMessage;
import com.gimi.common.cinema.model.MessageEvent;
import com.gimi.common.cinema.model.RoomInfo;
import com.gimi.common.cinema.model.RoomQrCodeInfo;
import com.gimi.common.cinema.model.RoomStatusInfo;
import com.gimi.common.cinema.model.SambaMsg;
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.OpenMMUtils;
import com.gimi.common.cinema.utils.ResUtils;
import com.gimi.common.cinema.utils.SambaFileCharge;
import com.gimi.common.cinema.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.qnbar.smc.model.Light;
import com.qnbar.smc.model.Lights;
import com.telink.bluetooth.LeBluetooth;
import com.telink.bluetooth.TelinkLog;
import com.telink.bluetooth.event.DeviceEvent;
import com.telink.bluetooth.event.MeshEvent;
import com.telink.bluetooth.event.NotificationEvent;
import com.telink.bluetooth.event.ServiceEvent;
import com.telink.bluetooth.light.ConnectionStatus;
import com.telink.bluetooth.light.DeviceInfo;
import com.telink.bluetooth.light.LeAutoConnectParameters;
import com.telink.bluetooth.light.LeRefreshNotifyParameters;
import com.telink.bluetooth.light.LightAdapter;
import com.telink.bluetooth.light.OnlineStatusNotificationParser;
import com.telink.bluetooth.light.Parameters;
import com.telink.bluetooth.light.model.Mesh;
import com.telink.util.Event;
import com.telink.util.EventListener;
import com.xgimi.gimicinema.R;
import com.xgimi.gimicinema.activity.AdsPreVideoPlayerActivity;
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.CountService;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public class SmartControlService extends BaseService implements EventListener<String>, SmartControlContract.View {
    public static final String TAG = "SmartControlService";

    public static final int ORDER_PLAY_COMPLETE = 0x1101;

    private Context mContext;
    private boolean hasSystemFeatureBluetoothLe = true;
    private BLEBroadcastReceiver bleBroadcastReceiver = new BLEBroadcastReceiver();
    private SmartControlContract.Presenter presenter;
    //___________________________________________
    private RoomStatusInfo roomStatusInfo;
    private RoomInfo roomInfo;
    private RoomQrCodeInfo info;
    private String lockMac = "";
    private boolean needReport = false;
    //___________________________________________
    private boolean initGetOderInfo;
    private RoomStatusInfo lastCompleteRoomStatusInfo;
    private int openDoorServerTime = 0;

    private void initLock() {
        // 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            hasSystemFeatureBluetoothLe = false;
            Toast.makeText(this, "手机不支持蓝牙ble协议,无法使用蓝牙开门功能", Toast.LENGTH_SHORT).show();
        } else {
            startService(new Intent(this, GREENBluetoothLeService.class));
        }
    }


    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        mContext = this;
        new SmartControlPresenter(this);
        mApplication = (FangTangApplication) getApplication();
        mApplication.doInit();
        Log.d(TAG, "onStartCommand");

        initLight();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
            Log.d("room-info", "SmartControlService register");
        } else {
            Log.d("room-info", "SmartControlService has register");
        }
        initLock();
        if (hasSystemFeatureBluetoothLe) {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(BLEBroadcastReceiver.ACTION_BLE_ERROR);
            intentFilter.addAction(BLEBroadcastReceiver.ACTION_SHAKING_BLE_ERROR);
            intentFilter.addAction(BLEBroadcastReceiver.ACTION_WRITTEN_SUCCESS);
            registerReceiver(bleBroadcastReceiver, intentFilter);
        }

        if (!LeBluetooth.getInstance().isEnabled()) {
            LeBluetooth.getInstance().enable(getApplicationContext());
        }
        updateLastCompleteMovieInfo();

        // 监听各种事件
        mApplication.addEventListener(DeviceEvent.STATUS_CHANGED, this);
        mApplication.addEventListener(NotificationEvent.ONLINE_STATUS, this);
        mApplication.addEventListener(ServiceEvent.SERVICE_CONNECTED, this);
        mApplication.addEventListener(MeshEvent.OFFLINE, this);
        mApplication.addEventListener(MeshEvent.ERROR, this);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                SmartControlService.this.autoConnect();
            }
        }, 3 * 1000);
        presenter.updateRoomInfo(this);
//        presenter.getOrderInfo(this);
        return START_STICKY;
    }

    private void updateLastCompleteMovieInfo() {
        try {
            lastCompleteRoomStatusInfo = new Gson().fromJson(Utils.getString(this, "oder-play-completed"), RoomStatusInfo.class);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        Log.d("room-info", "lastCompleteRoomStatusInfo null:" + (lastCompleteRoomStatusInfo == null));
    }

    @Override
    public void onDestroy() {
        Log.d("room-info", "SmartControlService onDestroy");
        if (hasSystemFeatureBluetoothLe) {
            unregisterReceiver(bleBroadcastReceiver);
        }
        unregisterReceiver(mReceiver);
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public SmartControlService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    private boolean reportSuccess;
    private int reportCount = 0;
    private long lastRequest = 0;
    private String countMsg = "";
    private Runnable reportRunnable = new Runnable() {
        @Override
        public void run() {
            if (reportSuccess || reportCount++ > 5) {
                //success or report 5 times reset status and count
                Log.d("room-info", "reportResult:" + reportSuccess + ",reportCount:" + reportCount);
                reportCount = 0;
                reportSuccess = false;
                return;
            }
            Log.d("room-info", "report the open door status");
            if (roomStatusInfo == null || roomStatusInfo.getData() == null) {
                Log.d("room-info", "report room status null");
            } else {
                presenter.reportOpenDoorStatus(roomStatusInfo.getData().getOrder_sn());
            }
            mHandler.postDelayed(this, 10 * 1000);
        }
    };

    private void openDoor() {
        updateLastCompleteMovieInfo();
        presenter.getSysTime(this);
        LogUtils.i("room-info", "openDoor called");
        bleBroadcastReceiver.setResponseObj(new GREENCITYBLEProtocolFactory.GREENCITYBleDataWritten() {
            @Override
            public void writeSuccess() {
                bleBroadcastReceiver.setResponseObj(null);
                Toast.makeText(SmartControlService.this, "开门成功", Toast.LENGTH_SHORT).show();
                if (needReport) {
                    mHandler.postDelayed(reportRunnable, 2 * 1000);
                    LogUtils.i("room-info", "user open door ,report the open success status");
                }
                LogUtils.i("room-info", "open success");
            }

            @Override
            public void writeFailure(String error) {
                LogUtils.i("room-info", "open failure," + error);
                bleBroadcastReceiver.setResponseObj(null);
                Toast.makeText(SmartControlService.this, "开门失败," + error, Toast.LENGTH_SHORT).show();
            }

        });
        if (!TextUtils.isEmpty(lockMac)) {
            String openCMD = "Open the door";
            GREENBLE.send(this, lockMac, openCMD.getBytes());
        } else {
            if (needReport) {
                mHandler.postDelayed(reportRunnable, 2 * 1000);
                LogUtils.i("room-info", "user open door ,report the open success status");
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent) {
        switch (messageEvent.getEventId()) {
            case SocketService1.JUST_OPEN_DOOR:
                //check qr code is showing
                needReport = false;
                openDoor();
                if (ActivityCollector.isActivityExist(QrCodeShowActivity.class)
                        || ActivityCollector.isActivityExist(SimpleAdsPlayer2.class)
                        || !TextUtils.isEmpty(((FangTangApplication) FangTangApplication.getInstance()).getCurrentPlayUrl())) {
                    break;
                }
                Log.i("event bus", "open door" + messageEvent.getMessage());
                //异常2清理时段管理扫码进入,没有显示清洁码
                if (messageEvent.getMessage().startsWith("administrator")) {
                    if (roomStatusInfo != null) {
                        int spaceTime = openDoorServerTime - roomStatusInfo.getData().getEnd_time();
                        if (spaceTime < 20 && spaceTime > 0) {
                            if (!ActivityCollector.isActivityExist(QrCodeShowActivity.class)) {
                                Log.i("event bus", "admin open door show qr code activity");
                                Intent intent = new Intent(this, QrCodeShowActivity.class)
                                        .putExtra("room_sn", roomInfo.getData().getRoom_sn())
                                        .putExtra("order_sn", roomStatusInfo.getData().getOrder_sn());
                                if ("count_service".equals(countMsg)) {
                                    intent.putExtra("count_call", true);
                                }
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                break;
                            }
                            //异常3 观景时段内 没有放电影
//                            if (roomStatusInfo.getData().getEnd_time() > openDoorServerTime
//                                    && openDoorServerTime > roomStatusInfo.getData().getBegin_time()
//                                    && TextUtils.isEmpty(((FangTangApplication) FangTangApplication.getInstance()).getCurrentPlayUrl())) {
//                                presenter.getOrderInfo(this);
//                            }
                        }
                    }
                }
                break;
            case SocketService1.USER_OPEN_DOOR_AND_GET_MOVIE:
                needReport = true;
                openDoor();
                presenter.getOrderInfo(this);
                Log.i("event bus", "user open door" + messageEvent.getMessage());
                break;
            case SocketService1.USER_OPEN_DOOR:
                needReport = true;
                openDoor();
                Log.i("event bus", "user open door" + messageEvent.getMessage());
//                if (rightSn) {
//                    down();
//                }
                //用户时段已在播放映后广告,不再获取订单信息
                if (ActivityCollector.isActivityExist(SimpleAdsPlayer2.class)
                        || ActivityCollector.isActivityExist(AdsPreVideoPlayerActivity.class)) {
                    break;
                }
                //check the movie
                if (TextUtils.isEmpty(mApplication.getCurrentPlayUrl())) {
                    presenter.getOrderInfo(this);
                } else {
                    if (roomStatusInfo == null || roomStatusInfo.getData() == null) {
                        presenter.getOrderInfo(this);
                        break;
                    }
                    if (!TextUtils.isEmpty(roomStatusInfo.getData().getFilm_hash())) {
                        LocalMovieMessage lmm = new NewDBManager(this).queryPlayMovie(roomStatusInfo.getData().getFilm_hash());
                        if (lmm == null) {
                            Log.e("room-info", "movie not exits");
                            break;
                        }
                        if (!roomStatusInfo.getData().getFilm_hash().equals(lmm.getMd5())) {
                            //当前播放电影信息不正确正在重新拉取
                            show("当前播放电影信息不正确正在重新拉取");
                            presenter.getOrderInfo(this);
                        }
                    } else {
                        presenter.getOrderInfo(this);
                        break;
                    }
                }
                break;
            case CountService.COUNT_DOWN_ZERO:
//                if (info == null || info.getData() == null) {
//                    break;
//                }
                Log.i("room-info", "COUNT_DOWN_ZERO stop polling finish some activity,jump to qr code activity");
                try {
                    PollingUtils.stopPollingService(this, CountService.class, CountService.STATUS_ACTION);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (ActivityCollector.isActivityExist(SimpleAdsPlayer2.class)) {
                    ActivityCollector.getActivity(SimpleAdsPlayer2.class).finish();
                }
                Intent intent = new Intent(this, QrCodeShowActivity.class)
//                        .putExtra("qr", info.getData().getCode())
                        .putExtra("room_sn", roomInfo.getData().getRoom_sn())
                        .putExtra("order_sn", roomStatusInfo.getData().getOrder_sn());
                if ("count_service".equals(countMsg)) {
                    intent.putExtra("count_call", true);
                }
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                roomStatusInfo = null;
//                if (roomStatusInfo != null && roomStatusInfo.getData() != null & roomInfo != null && roomInfo.getData() != null) {
//                    if (System.currentTimeMillis() - lastRequest > 3000) {
//                        lastRequest = System.currentTimeMillis();
//                        countMsg = messageEvent.getMessage();
//                        presenter.getCleanQrCode(roomStatusInfo.getData().getOrder_sn(), roomInfo.getData().getRoom_sn());
//                    }
//                } else {
//                    String msg = "roomStatusInfo is Null:" + (roomStatusInfo == null) +
//                            ",roomInfo is Null:" + (roomInfo == null);
//                    Log.d("room-info", msg);
//                    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
//                }
                break;
            case ORDER_PLAY_COMPLETE:
                if (roomStatusInfo != null && roomStatusInfo.getData() != null & roomInfo != null && roomInfo.getData() != null) {
                    if (System.currentTimeMillis() - lastRequest > 3000) {
                        lastRequest = System.currentTimeMillis();
                        countMsg = messageEvent.getMessage();
                        presenter.getCleanQrCode(roomStatusInfo.getData().getOrder_sn(), roomInfo.getData().getRoom_sn());
                    }
                } else {
                    String msg = "roomStatusInfo is Null:" + (roomStatusInfo == null) +
                            ",roomInfo is Null:" + (roomInfo == null);
                    Log.i("room-info", msg);
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                }
                LogUtils.i("room-info", messageEvent.getMessage());
                Utils.saveString(this, "oder-play-completed", new Gson().toJson(roomStatusInfo));
//                playEndAds();
                break;
            default:
                Log.d("room-info", messageEvent.getMessage());
        }
    }

    //lights
    private FangTangApplication mApplication;
    private int connectMeshAddress;
    private Handler mHandler = new Handler();

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);

                switch (state) {
                    case BluetoothAdapter.STATE_ON:
                        Log.d(TAG, "蓝牙开启");
                        TelinkLightService.Instance().idleMode(true);
                        autoConnect();
                        break;
                    case BluetoothAdapter.STATE_OFF:
                        Log.d(TAG, "蓝牙关闭");
                        break;
                }
            }
        }
    };

    public void initLight() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY - 1);
        registerReceiver(mReceiver, filter);
    }

    /**
     * 自动重连
     */
    private void autoConnect() {
        if (TelinkLightService.Instance() != null) {
            Log.d(TAG, "connect not null");
            if (TelinkLightService.Instance().getMode() != LightAdapter.MODE_AUTO_CONNECT_MESH) {
                Lights.getInstance().clear();
                if (mApplication.isEmptyMesh())
                    return;
                Mesh mesh = mApplication.getMesh();
                //自动重连参数
                LeAutoConnectParameters connectParams = Parameters.createAutoConnectParameters();
                connectParams.setMeshName(mesh.name);
                connectParams.setPassword(mesh.password);
                connectParams.autoEnableNotification(true);
                //自动重连
                TelinkLightService.Instance().autoConnect(connectParams);
            } else {
                Log.d(TAG, "connect null");
            }

            //刷新Notify参数
            LeRefreshNotifyParameters refreshNotifyParams = Parameters.createRefreshNotifyParameters();
            refreshNotifyParams.setRefreshRepeatCount(2);
            refreshNotifyParams.setRefreshInterval(2000);
            //开启自动刷新Notify
            TelinkLightService.Instance().autoRefreshNotify(refreshNotifyParams);
        }
    }


    private void show(String msg) {
//        Log.d(TAG, "show: " + msg);
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private void onDeviceStatusChanged(DeviceEvent event) {

        DeviceInfo deviceInfo = event.getArgs();

        switch (deviceInfo.status) {
            case LightAdapter.STATUS_LOGIN:
                connectMeshAddress = mApplication.getConnectDevice().meshAddress;
                show("灯光配对成功");
                break;
            case LightAdapter.STATUS_CONNECTING:
                show("与灯光配对");
                break;
            case LightAdapter.STATUS_LOGOUT:
                show("灯光断开");
                break;
            default:
                break;
        }
    }

    private void onServiceConnected(ServiceEvent event) {
        autoConnect();
    }

    private void onServiceDisconnected(ServiceEvent event) {

    }

    private void onMeshOffline(MeshEvent event) {
        List<Light> lights = Lights.getInstance().get();
        for (Light light : lights) {
            light.status = ConnectionStatus.OFFLINE;
            light.updateIcon();
        }
    }

    private void onMeshError(MeshEvent event) {
        show("蓝牙出问题了,重启蓝牙试试!!");
    }

    /**
     * 处理{@link NotificationEvent#ONLINE_STATUS}事件
     *
     * @param event event bus trans
     */
    private void onOnlineStatusNotify(NotificationEvent event) {
        TelinkLog.d("Thread ID : " + Thread.currentThread().getId());
        List<OnlineStatusNotificationParser.DeviceNotificationInfo> notificationInfoList;
        //noinspection unchecked
        notificationInfoList = (List<OnlineStatusNotificationParser.DeviceNotificationInfo>) event.parse();

        if (notificationInfoList == null || notificationInfoList.size() <= 0)
            return;

        for (OnlineStatusNotificationParser.DeviceNotificationInfo notificationInfo : notificationInfoList) {
            int meshAddress = notificationInfo.meshAddress;
            int brightness = notificationInfo.brightness;
            Light light = Lights.getInstance().getByMeshAddress(meshAddress);
            if (light == null) {
                light = new Light();
                Lights.getInstance().add(light);
            }
            light.meshAddress = meshAddress;
            light.brightness = brightness;
            light.status = notificationInfo.connectStatus;
            light.updateIcon();
        }
    }

    /**
     * 事件处理方法
     *
     * @param event
     */
    @Override
    public void performed(Event<String> event) {
        switch (event.getType()) {
            case NotificationEvent.ONLINE_STATUS:
                onOnlineStatusNotify((NotificationEvent) event);
                break;
            case DeviceEvent.STATUS_CHANGED:
                onDeviceStatusChanged((DeviceEvent) event);
                break;
            case MeshEvent.OFFLINE:
                onMeshOffline((MeshEvent) event);
                break;
            case MeshEvent.ERROR:
                onMeshError((MeshEvent) event);
                break;
            case ServiceEvent.SERVICE_CONNECTED:
                onServiceConnected((ServiceEvent) event);
                break;
            case ServiceEvent.SERVICE_DISCONNECTED:
                onServiceDisconnected((ServiceEvent) event);
                break;
        }
    }

    @Override
    public void setPresenter(SmartControlContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showMsg() {

    }

    @Override
    public void notifyGetRoomInfo(RoomInfo info) {
        this.roomInfo = info;
        if (!TextUtils.isEmpty(info.getData().getMac_address())) {
            lockMac = info.getData().getMac_address();
        } else {
            show("没有配置门禁相关网信息,使用默认信息");
        }
    }

    @Override
    public void notifyUpdateRoomInfo(RoomInfo info) {
        this.roomInfo = info;
        this.roomInfo = info;
        if (!TextUtils.isEmpty(info.getData().getMac_address())) {
            lockMac = info.getData().getMac_address();
        } else {
            show("没有配置门禁相关网信息,使用默认信息");
        }
        Log.d("room-info", "start socket service");
        try {
            Thread.sleep(3 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Intent intent = new Intent();
        ComponentName componentName = new ComponentName("com.xgimi.gimicinema", "com.qnbar.smc.service.SocketService1");
        intent.setComponent(componentName);
        startService(intent);
    }

    @Override
    public void reportResult(boolean b) {
        this.reportSuccess = b;
    }

    @Override
    public void updateOrderInfo(RoomStatusInfo orderInfo) {
        this.roomStatusInfo = orderInfo;
        Log.d("room-info", "update order info");
        RoomStatusInfo.DataEntity data = orderInfo.getData();
        int offset = data.getNow_time() - data.getBegin_time();

        int durationMinutes = data.getEnd_time() - data.getNow_time();
        LogUtils.i("room-info", orderInfo.toString());
        if (durationMinutes <= 1) {
            return;
        }
        Constant.count = durationMinutes + 1;
        PollingUtils.startPollingService(this, 60, CountService.class, CountService.STATUS_ACTION);

        //异常1,若在观影时间内,非正常关闭,扫描更新订单后播放广告,显示清洁码
        if (lastCompleteRoomStatusInfo != null) {
            if (lastCompleteRoomStatusInfo.getData().getOrder_sn().equals(roomStatusInfo.getData().getOrder_sn())) {
                if (openDoorServerTime > roomStatusInfo.getData().getBegin_time() && openDoorServerTime < roomStatusInfo.getData().getEnd_time()) {
                    playEndAds();
                }
                return;
            }
        }

        LocalMovieMessage localMovieMessages = null;
        if (!TextUtils.isEmpty(data.getFilm_hash())) {
            localMovieMessages = new NewDBManager(this).queryPlayMovie(data.getFilm_hash());
            if (localMovieMessages == null) {
                LogUtils.e("room-info", "file not exists:" + orderInfo.toString());
                CToast.makeText(this, "没有找到电影信息,请联系客服", 90 * 1000).show();
            }
        }
        if (nextNeedReport) {
            mHandler.postDelayed(reportRunnable, 2 * 1000);
        }
        if (localMovieMessages != null) {
            LogUtils.i("room-info", "play movie" + localMovieMessages.toString());
            String showMsg;
            if (offset > 0) {
                showMsg = String.format(ResUtils.getResResult(mContext,
                        R.string.welcome, R.string.ads_promote,
                        R.string.delay_time_fill_time,
                        R.string.play_movie_fill_name),
                        offset, roomStatusInfo.getData().getFilm_name());
            } else {
                showMsg = String.format(ResUtils.getResResult(mContext, R.string.welcome, R.string.ads_promote, R.string.play_movie_fill_name), roomStatusInfo.getData().getFilm_name());
            }
            CToast.makeText(this, showMsg, 100 * 1000).show();
            if (!nextNeedReport) {
                OpenMMUtils.openMMWithAds(this, localMovieMessages.getPlayPath(), null);
            } else {
                OpenMMUtils.openPlayer(this, localMovieMessages.getPlayPath(), null, 0);
            }
        } else {
            LogUtils.e("room-info", "file not exists:" + orderInfo.toString());
            show("没有找到电影");
        }
    }

    private boolean nextNeedReport = false;//标记连场情况是否需要报告成功开门信息

    @Override
    public void prepareRoomQrCodeInfo(RoomQrCodeInfo qrCodeInfo) {
        this.info = qrCodeInfo;
        if (info != null && info.getData() != null) {
            LogUtils.i(TAG, "order_sn is null,play end ads");
            if (TextUtils.isEmpty(info.getData().getOrder_sn())) {
                playEndAds();
            } else {
                nextNeedReport = true;
                LogUtils.i(TAG, "order_sn not null:" + qrCodeInfo.toString());
                String showMsg = ResUtils.getResResult(mContext, R.string.ads_promote, R.string.play_next_fill_name);
                CToast.makeText(mContext, showMsg, 30 * 1000).show();
                presenter.getNextOrderInfo(SmartControlService.this, info.getData().getOrder_sn());
            }
        } else {
            LogUtils.e("info != null && info.getData() != null");
        }
    }

    @Override
    public void updateInitGetOrderInfo(boolean b) {
        initGetOderInfo = b;
        nextNeedReport = b;
    }

    @Override
    public void setOpenDoorTime(int i) {
        openDoorServerTime = i;
    }

    private void playEndAds() {
        SharedPreferences sharedPreferences = getSharedPreferences(Constant.XML_NAME, Context.MODE_PRIVATE);
        SambaMsg sambaMsg = Utils.getSambaMsg(sharedPreferences);
        String adsVideoPath;
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        adsVideoPath = sambaMsg.getLocalPath() + "qnyk.mp4";
        if (!SambaFileCharge.fileExist(adsVideoPath)) {
            return;
        }
        if (roomStatusInfo != null && roomStatusInfo.getData() != null && roomInfo != null && roomInfo.getData() != null) {
            if (Constant.count > 30) {
                String showMsg = ResUtils.getResResult(mContext, R.string.ads_promote, R.string.end_ads);
                CToast.makeText(mContext, showMsg, 30 * 1000).show();
            }
            Intent intentAds = new Intent(this.getApplicationContext(), SimpleAdsPlayer2.class);
            intentAds.putExtra("ads_path", adsVideoPath);
            intentAds
                    .putExtra("room_sn", roomInfo.getData().getRoom_sn())
                    .putExtra("order_sn", roomStatusInfo.getData().getOrder_sn());
            intentAds.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intentAds);
        }
    }
}