CinemaControlService.java 10.3 KB
/*
 * Copyright 2016 wugian
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xgimi.gimicinema.service;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.qnbar.smc.model.Light;
import com.qnbar.smc.model.Lights;
import com.qnbar.smc.service.TelinkLightService;
import com.telink.bluetooth.light.ConnectionStatus;
import com.telink.bluetooth.light.DeviceInfo;
import com.xgimi.gimicinema.ICinemaControl;
import com.xgimi.gimicinema.ICinemaSMC;
import com.xgimi.gimicinema.application.FangTangApplication;

import java.util.ArrayList;
import java.util.List;

public class CinemaControlService extends Service {
    private ArrayList<String> movies = new ArrayList<>();
    private long duration = 0;
    private long currentPosition = 0;
    private int currentState = 0;
    private String currentPath = null;

    private final ICinemaControl.Stub cinemaControl = new ICinemaControl.Stub() {

        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public void setMovieDuration(long duration) throws RemoteException {
//            Log.d("aidl", "setMovieDuration: " + duration);
            CinemaControlService.this.duration = duration;
        }

        @Override
        public long getMovieDuration() throws RemoteException {
            return duration;
        }

        @Override
        public void setCurrentMoviePosition(long duration) throws RemoteException {
//            Log.d("aidl", "setCurrentMoviePosition: " + duration);
            currentPosition = duration;
        }

        @Override
        public long getCurrentMoviePosition() throws RemoteException {
            return currentPosition;
        }

        @Override
        public int getCurrentStatus() throws RemoteException {
            return currentState;
        }

        //TODO 当状态改变时上报服务器状态,开始播放时,启动轮询上报当前状态及时间
        @Override
        public void setCurrentStatus(int state) throws RemoteException {
            Log.d("aidl", "setCurrentStatus: " + state);
            if (TelinkLightService.Instance() == null) {
                return;
            }
            if (state != currentState) {
                currentState = state;
                Log.d("aidl", "state change," + currentPath + "," + duration + "," + currentPosition);
                Log.d("aidl", "state change cinemaSMC not null");
//                if (true) {
//                    return;
//                }
                switch (state) {
                    case 0://空闲
//                        open();
                        fadeIn();
                        break;
                    case 1://播放
                        fadeOut();
//                        close();
                        break;
                    case 2://暂停
//                        open();
                        fadeIn();
                        break;
                }
            }
        }

        @Override
        public void addPlayPath(String path) throws RemoteException {
            movies.add(path);//strict contract
        }

        @Override
        public void setCurrentPlayPath(String path) throws RemoteException {
//            Log.d("aidl", "setCurrentPlayPath: " + path);
            CinemaControlService.this.currentPath = path;
        }

        @Override
        public String getCurrentPath() throws RemoteException {
            return CinemaControlService.this.currentPath;
        }

        @Override
        public List<String> getPlayList() throws RemoteException {
            return movies;
        }

        @Override
        public void setPlayList(List<String> movies) throws RemoteException {
            CinemaControlService.this.movies.clear();
            if (movies == null || movies.size() == 0) {
                return;
            }
            CinemaControlService.this.movies.addAll(movies);
        }
    };

    public CinemaControlService() {
    }

    private int value;
    private Handler handler = new Handler();
    private Runnable closeRunnable = new Runnable() {
        @Override
        public void run() {
            setLightValue(value);
            if (value-- == 50) {
                handler.postDelayed(this, 4 * 1000);
            } else {
                if (value == 0) {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            close();
                        }
                    }, 3 * 1000);
                } else {
                    handler.postDelayed(this, 200);
                }
            }
        }
    };

    private Runnable openRunnable = new Runnable() {
        @Override
        public void run() {
            if (value++ == 0) {
                open();
                handler.postDelayed(this, 4 * 1000);
            } else {
                setLightValue(value);
                if (value != 50) {
                    handler.postDelayed(this, 200);
                }
            }
        }
    };

    private FangTangApplication mApplication;

    @Override
    public void onCreate() {
        super.onCreate();
        if (!mBound) {
            attemptToBindService();
        }
        mApplication = (FangTangApplication) getApplication();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return cinemaControl;
    }

    //由AIDL文件生成的Java类
    private ICinemaSMC cinemaSMC = null;

    //标志当前与服务端连接状况的布尔值,false为未连接,true为连接中
    private boolean mBound = false;


    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            cinemaSMC = ICinemaSMC.Stub.asInterface(service);
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
        }
    };

    /**
     * 尝试与服务端建立连接
     */
    private void attemptToBindService() {
        Intent intent = new Intent();
        intent.setPackage("com.qnbar.smc");
        intent.setAction("com.xgimi.cinemasmc");
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

//    private boolean isSMCRun(Context context) {
//        return isServiceRunning(context, "com.qnbar.smc.service.SMCService");
//    }
//
//    private boolean isServiceRunning(Context context, String className) {
//        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//        boolean isRunning = false;
//        List serviceList = activityManager.getRunningServices(2147483647);
//        if (serviceList.size() <= 0) {
//            return false;
//        } else {
//            Iterator i$ = serviceList.iterator();
//
//            while (i$.hasNext()) {
//                ActivityManager.RunningServiceInfo aServiceList = (ActivityManager.RunningServiceInfo) i$.next();
//                if (aServiceList.service.getClassName().equals(className)) {
//                    isRunning = true;
//                    break;
//                }
//            }
//
//            Log.i("SystemUtils", "service is running?==" + isRunning);
//            return isRunning;
//        }
//    }

    private void open() {
        byte opcode = (byte) 0xD0;
        int address = 0xFFFF;
        byte[] params = new byte[]{0x01, 0x00, 0x00};
        if (TelinkLightService.Instance().sendCommandNoResponse(opcode, address, params)) {
//            show("open all success");
        }
    }

    private void close() {
        byte opcode = (byte) 0xD0;
        int address = 0xFFFF;
        byte[] params = new byte[]{0x00, 0x00, 0x00};
        if (TelinkLightService.Instance().sendCommandNoResponse(opcode, address, params)) {
//            show("open all success");
        }
    }

    private void fadeIn() {
        DeviceInfo connectDevice = mApplication.getConnectDevice();
        if (connectDevice == null) {
            Log.d("aidl", "connect device is null");
            return;
        }
        Light byMeshAddress = Lights.getInstance().getByMeshAddress(connectDevice.meshAddress);
        if (byMeshAddress.status == ConnectionStatus.ON) {
            return;
        }
//        int status = mApplication.getConnectDevice().status;
//        Log.d("status_charge", "fadeIn: " + status);
        value = 0;
        handler.post(openRunnable);
    }

    private void fadeOut() {
        DeviceInfo connectDevice = mApplication.getConnectDevice();
        if (connectDevice == null) {
            Log.d("aidl", "connect device is null");
            return;
        }
        Light byMeshAddress = Lights.getInstance().getByMeshAddress(connectDevice.meshAddress);
        if (byMeshAddress.status == ConnectionStatus.OFF) {
            return;
        }
//        int status = connectDevice.status;
//        Log.d("status_charge", "fadeOut: " + status);
        value = 50;
        handler.post(closeRunnable);
    }

    private void setLightValue(int value) {
        int addr = 0xFFFF;
        //change group brightness or color temperature
//            addr = 0x8003;
        byte opcode;
        byte[] params;

        opcode = (byte) 0xD2;
        params = new byte[]{(byte) value};
        TelinkLightService.Instance().sendCommandNoResponse(opcode, addr, params, true);


        opcode = (byte) 0xE2;
        params = new byte[]{0x05, (byte) value};
        TelinkLightService.Instance().sendCommandNoResponse(opcode, addr, params, true);
    }
}