SimpleLightDemo.java 11 KB
package com.qnbar.smc;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import com.qnbar.smc.model.Light;
import com.qnbar.smc.model.Lights;
import com.qnbar.smc.service.TelinkLightService;
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.BuildUtils;
import com.telink.util.Event;
import com.telink.util.EventListener;
import com.xgimi.gimicinema.R;
import com.xgimi.gimicinema.application.FangTangApplication;

import java.util.List;

public class SimpleLightDemo extends Activity implements EventListener<String> {
    private final static String TAG = SimpleLightDemo.class.getSimpleName();
    private FangTangApplication mApplication;
    private int connectMeshAddress;

    private Handler mDelayHandler = 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;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApplication = (FangTangApplication) getApplication();
        mApplication.doInit();
        mApplication.addEventListener(NotificationEvent.GET_GROUP, this);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

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

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
        int result = BuildUtils.assetSdkVersion("4.4");
        Log.d(TAG, " Version : " + result);

        // 监听各种事件
        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() {
                SimpleLightDemo.this.autoConnect();
            }
        }, 3 * 1000);

    }

    @Override
    protected void onResume() {
        super.onResume();
        //检查是否支持蓝牙设备
        if (!LeBluetooth.getInstance().isSupport(getApplicationContext())) {
            Toast.makeText(this, "ble not support", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        if (!LeBluetooth.getInstance().isEnabled()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("开启蓝牙,体验智能灯!");
            builder.setNeutralButton("cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            builder.setNegativeButton("enable", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    LeBluetooth.getInstance().enable(getApplicationContext());
                }
            });
            builder.show();
        }

        DeviceInfo deviceInfo = mApplication.getConnectDevice();

        if (deviceInfo != null) {
            connectMeshAddress = mApplication.getConnectDevice().meshAddress & 0xFF;
        }

        Log.d(TAG, "onResume");

    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
        //移除事件
        mApplication.removeEventListener(this);
        TelinkLightService.Instance().disableAutoRefreshNotify();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
        unregisterReceiver(mReceiver);
        mApplication.doDestroy();
        mDelayHandler.removeCallbacksAndMessages(null);
        Lights.getInstance().clear();
    }

    /**
     * 自动重连
     */
    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 onDeviceStatusChanged(DeviceEvent event) {
        DeviceInfo deviceInfo = event.getArgs();
        switch (deviceInfo.status) {
            case LightAdapter.STATUS_LOGIN:
                connectMeshAddress = mApplication.getConnectDevice().meshAddress;
                show("login success");
                break;
            case LightAdapter.STATUS_CONNECTING:
                show("login");
                break;
            case LightAdapter.STATUS_LOGOUT:
                show("disconnect");
                break;
            default:
                break;
        }
    }

    /**
     * 处理{@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();
        }
    }

    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) {
        new AlertDialog.Builder(this).setMessage("蓝牙出问题了,重启蓝牙试试!!").show();
    }

    /**
     * 事件处理方法
     *
     * @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;
        }
    }

    public void openLight(View view) {
        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");
        }
    }

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

    private void show(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

}