Java tutorial
/** * Copyright 2014 Nest Labs Inc. All Rights Reserved. * 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.nestapi.codelab.demo; import android.app.Activity; import android.app.FragmentManager; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleAdapter; import com.nestapi.lib.API.*; import com.nestapi.lib.AuthManager; import com.nestapi.lib.ClientMetadata; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class MainActivity extends Activity implements NestAPI.AuthenticationListener, Listener.StructureListener, Listener.ThermostatListener, Listener.CameraListener, Listener.SmokeCOAlarmListener, NestDelegate { private static final String TAG = MainActivity.class.getSimpleName(); private static final String THERMOSTAT_KEY = "thermostat_key"; private static final String CAMERA_KEY = "camera_key"; private static final String SMOKE_CO_ALARM_KEY = "smoke_co_alarm_key"; private static final String STRUCTURE_KEY = "structure_key"; private static final String THERMOSTAT_FRAGMENT_TAG = "Thermostat Fragment"; private static final String CAMERA_FRAGMENT_TAG = "Camera Fragment"; private static final String PROTECT_FRAGMENT_TAG = "Protect Fragment"; private static final String DEVICE_TEMPLATE = "Device"; private static final String STRUCTURE_TEMPLATE = "Structure"; private static final String ID_TEMPLATE = "Id"; private static final int AUTH_TOKEN_REQUEST_CODE = 101; private Listener mUpdateListener; private NestAPI mNestApi; private AccessToken mToken; private Thermostat mThermostat; private Camera mCamera; private SmokeCOAlarm mSmokeCOAlarm; private Structure mStructure; private ThermostatFragment mThermostatFragment; private CameraFragment mCameraFragment; private SmokeCOAlarmFragment mSmokeCOAlarmFragment; private FragmentManager fragmentManager; private List<Structure> mStructures; private ListView mDrawerList; private ArrayList<HashMap<String, String>> devicesList; private SimpleAdapter adapter; private List<Camera> mCameras; private List<SmokeCOAlarm> mSmokeCOAlarms; private List<Thermostat> mThermostats; private android.support.v4.widget.DrawerLayout mDrawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mCameras = new ArrayList<Camera>(); mSmokeCOAlarms = new ArrayList<SmokeCOAlarm>(); mThermostats = new ArrayList<Thermostat>(); mThermostatFragment = new ThermostatFragment(); fragmentManager = getFragmentManager(); fragmentManager.beginTransaction().add(R.id.container, mThermostatFragment, THERMOSTAT_FRAGMENT_TAG) .commit(); mNestApi = NestAPI.getInstance(); mToken = Settings.loadAuthToken(this); if (mToken != null) { authenticate(mToken); } else { obtainAccessToken(); } mDrawerList = (ListView) findViewById(R.id.left_drawer); devicesList = new ArrayList<HashMap<String, String>>(); adapter = new SimpleAdapter(this, devicesList, android.R.layout.simple_list_item_2, new String[] { DEVICE_TEMPLATE, STRUCTURE_TEMPLATE }, new int[] { android.R.id.text1, android.R.id.text2 }); mDrawerList.setAdapter(adapter); mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); if (savedInstanceState != null) { mThermostat = savedInstanceState.getParcelable(THERMOSTAT_KEY); mCamera = savedInstanceState.getParcelable(CAMERA_KEY); mSmokeCOAlarm = savedInstanceState.getParcelable(SMOKE_CO_ALARM_KEY); mStructure = savedInstanceState.getParcelable(STRUCTURE_KEY); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(THERMOSTAT_KEY, mThermostat); outState.putParcelable(CAMERA_KEY, mCamera); outState.putParcelable(SMOKE_CO_ALARM_KEY, mSmokeCOAlarm); outState.putParcelable(STRUCTURE_KEY, mStructure); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK || requestCode != AUTH_TOKEN_REQUEST_CODE) { return; } if (AuthManager.hasAccessToken(data)) { mToken = AuthManager.getAccessToken(data); Settings.saveAuthToken(this, mToken); Log.v(TAG, "Main Activity parsed auth token: " + mToken.getToken() + " expires: " + mToken.getExpiresIn()); authenticate(mToken); } else { Log.e(TAG, "Unable to resolve access token from payload."); } } @Override public void onAuthenticationSuccess() { Log.v(TAG, "Authentication succeeded."); fetchData(); } @Override public void onAuthenticationFailure(int errorCode) { Log.v(TAG, "Authentication failed with error: " + errorCode); } @Override protected void onStop() { super.onStop(); mNestApi.removeUpdateListener(mUpdateListener); } @Override public void onThermostatUpdated(Thermostat thermostat) { Log.v(TAG, String.format("Thermostat (%s) updated.", thermostat.getDeviceID())); int index = getDeviceIndexById(thermostat); if (index == -1) { mThermostats.add(thermostat); } else { mThermostats.set(index, thermostat); } if (mThermostat == null || mThermostat.getDeviceID().equals(thermostat.getDeviceID())) { mThermostat = thermostat; if (mThermostatFragment != null) { mThermostatFragment.updateView(); } } } @Override public void onCameraUpdated(@NonNull Camera camera) { Log.v(TAG, String.format("Camera (%s) updated.", camera.getDeviceID())); int index = getDeviceIndexById(camera); if (index == -1) { mCameras.add(camera); } else { mCameras.set(index, camera); } if (mCamera == null || mCamera.getDeviceID().equals(camera.getDeviceID())) { mCamera = camera; if (mCameraFragment != null) { mCameraFragment.updateView(); } } } @Override public void onSmokeCOAlarmUpdated(@NonNull SmokeCOAlarm smokeCOAlarm) { Log.v(TAG, String.format("Camera (%s) updated.", smokeCOAlarm.getDeviceID())); int index = getDeviceIndexById(smokeCOAlarm); if (index == -1) { mSmokeCOAlarms.add(smokeCOAlarm); } else { mSmokeCOAlarms.set(index, smokeCOAlarm); } if (mSmokeCOAlarm == null || mSmokeCOAlarm.getDeviceID().equals(smokeCOAlarm.getDeviceID())) { mSmokeCOAlarm = smokeCOAlarm; if (mSmokeCOAlarmFragment != null) { mSmokeCOAlarmFragment.updateView(); } } } @Override public void onStructureUpdated(Structure structure) { Log.v(TAG, String.format("Structure (%s) updated.", structure.getStructureID())); if (mStructure == null || mStructure.getStructureID().equals(structure.getStructureID())) { mStructure = structure; if (mThermostatFragment != null) { mThermostatFragment.updateView(); } if (mCameraFragment != null) { mCameraFragment.updateView(); } if (mSmokeCOAlarmFragment != null) { mSmokeCOAlarmFragment.updateView(); } } mStructures = mNestApi.getStructures(); updateDrawer(); } @Override public NestAPI getNestAPI() { return mNestApi; } @Override public Thermostat getThermostat() { return mThermostat; } @Override public Camera getCamera() { return mCamera; } @Override public SmokeCOAlarm getSmokeCOAlarm() { return mSmokeCOAlarm; } @Override public Structure getStructure() { return mStructure; } private void obtainAccessToken() { Log.v(TAG, "starting auth flow..."); final ClientMetadata metadata = new ClientMetadata.Builder().setClientID(Constants.CLIENT_ID) .setClientSecret(Constants.CLIENT_SECRET).setRedirectURL(Constants.REDIRECT_URL).build(); AuthManager.launchAuthFlow(this, AUTH_TOKEN_REQUEST_CODE, metadata); } private void authenticate(AccessToken token) { Log.v(TAG, "Authenticating..."); NestAPI.getInstance().authenticate(token, this); } private void fetchData() { Log.v(TAG, "Fetching data..."); mUpdateListener = new Listener.Builder().setStructureListener(this).setThermostatListener(this) .setCameraListener(this).setSmokeCOAlarmListener(this).build(); mNestApi.addUpdateListener(mUpdateListener); } private int getDeviceIndexById(BaseDevice device) { for (BaseDevice tempDevice : mCameras) { if (tempDevice.getDeviceID().equals(device.getDeviceID())) { return mCameras.indexOf(tempDevice); } } for (BaseDevice tempDevice : mThermostats) { if (tempDevice.getDeviceID().equals(device.getDeviceID())) { return mThermostats.indexOf(tempDevice); } } for (BaseDevice tempDevice : mSmokeCOAlarms) { if (tempDevice.getDeviceID().equals(device.getDeviceID())) { return mSmokeCOAlarms.indexOf(tempDevice); } } return -1; } private BaseDevice findDevice(String id) { for (Camera camera : mCameras) { if (camera.getDeviceID().equals(id)) { return camera; } } for (Thermostat thermostat : mThermostats) { if (thermostat.getDeviceID().equals(id)) { return thermostat; } } for (SmokeCOAlarm smokeCOAlarm : mSmokeCOAlarms) { if (smokeCOAlarm.getDeviceID().equals(id)) { return smokeCOAlarm; } } return null; } private Structure findStructure(String id) { for (Structure structure : mStructures) { if (structure.getStructureID().equals(id)) { return structure; } } return null; } private void clearFragments() { mCameraFragment = null; mSmokeCOAlarmFragment = null; mThermostatFragment = null; } private void updateDrawer() { devicesList.clear(); HashMap<String, String> map; for (Structure structure : mStructures) { for (String thermostat : structure.getThermostatIDs()) { map = new HashMap<String, String>(); map.put(DEVICE_TEMPLATE, findDevice(thermostat).getNameLong()); map.put(STRUCTURE_TEMPLATE, structure.getName()); map.put(ID_TEMPLATE, thermostat); devicesList.add(map); } for (String camera : structure.getCameras()) { map = new HashMap<String, String>(); map.put(DEVICE_TEMPLATE, findDevice(camera).getNameLong()); map.put(STRUCTURE_TEMPLATE, structure.getName()); map.put(ID_TEMPLATE, camera); devicesList.add(map); } for (String alarm : structure.getSmokeCOAlarms()) { map = new HashMap<String, String>(); map.put(DEVICE_TEMPLATE, findDevice(alarm).getNameLong()); map.put(STRUCTURE_TEMPLATE, structure.getName()); map.put(ID_TEMPLATE, alarm); devicesList.add(map); } } adapter.notifyDataSetChanged(); } private void selectItem(int position) { BaseDevice device = findDevice(devicesList.get(position).get(ID_TEMPLATE)); mStructure = findStructure(device.getStructureID()); boolean isThermostat = device instanceof Thermostat; boolean isCamera = device instanceof Camera; boolean isSmokeCOAlarm = device instanceof SmokeCOAlarm; clearFragments(); if (isThermostat) { mThermostat = (Thermostat) device; mThermostatFragment = new ThermostatFragment(); fragmentManager.beginTransaction().replace(R.id.container, mThermostatFragment, THERMOSTAT_FRAGMENT_TAG) .commit(); } else if (isCamera) { mCamera = (Camera) device; mCameraFragment = new CameraFragment(); fragmentManager.beginTransaction().replace(R.id.container, mCameraFragment, CAMERA_FRAGMENT_TAG) .commit(); } else if (isSmokeCOAlarm) { mSmokeCOAlarm = (SmokeCOAlarm) device; mSmokeCOAlarmFragment = new SmokeCOAlarmFragment(); fragmentManager.beginTransaction().replace(R.id.container, mSmokeCOAlarmFragment, PROTECT_FRAGMENT_TAG) .commit(); } mDrawerLayout.closeDrawer(mDrawerList); } private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } } }