code
stringlengths
3
1.18M
language
stringclasses
1 value
package com.google.android.apps.mytracks.services.sensors; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.services.sensors.ant.AntDirectSensorManager; import com.google.android.apps.mytracks.services.sensors.ant.AntSrmBridgeSensorManager; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; public class SensorManagerFactoryTest extends AndroidTestCase { private SharedPreferences sharedPreferences; @Override protected void setUp() throws Exception { super.setUp(); sharedPreferences = getContext().getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); // Let's use default values. sharedPreferences.edit().clear().apply(); } @SmallTest public void testDefaultSettings() throws Exception { assertNull(SensorManagerFactory.getSensorManager(getContext())); } @SmallTest public void testCreateZephyr() throws Exception { assertClassForName(ZephyrSensorManager.class, R.string.sensor_type_value_zephyr); } @SmallTest public void testCreateAnt() throws Exception { assertClassForName(AntDirectSensorManager.class, R.string.sensor_type_value_ant); } @SmallTest public void testCreateAntSRM() throws Exception { assertClassForName(AntSrmBridgeSensorManager.class, R.string.sensor_type_value_srm_ant_bridge); } private void assertClassForName(Class<?> c, int i) { sharedPreferences.edit() .putString(getContext().getString(R.string.sensor_type_key), getContext().getString(i)) .apply(); SensorManager sm = SensorManagerFactory.getSensorManager(getContext()); assertNotNull(sm); assertTrue(c.isInstance(sm)); } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.services.sensors.ant; import android.test.AndroidTestCase; public class AntStartupMessageTest extends AndroidTestCase { public void testParse() { byte[] rawMessage = { 0x12, }; AntStartupMessage message = new AntStartupMessage(rawMessage); assertEquals(0x12, message.getMessage()); } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.services.sensors.ant; import com.dsi.ant.AntDefine; import com.dsi.ant.AntMesg; import android.test.AndroidTestCase; public class AntChannelResponseMessageTest extends AndroidTestCase { public void testParse() { byte[] rawMessage = { 0, AntMesg.MESG_EVENT_ID, AntDefine.EVENT_RX_SEARCH_TIMEOUT }; AntChannelResponseMessage message = new AntChannelResponseMessage(rawMessage); assertEquals(0, message.getChannelNumber()); assertEquals(AntMesg.MESG_EVENT_ID, message.getMessageId()); assertEquals(AntDefine.EVENT_RX_SEARCH_TIMEOUT, message.getMessageCode()); } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.services.sensors.ant; import android.test.AndroidTestCase; public class AntChannelIdMessageTest extends AndroidTestCase { public void testParse() { byte[] rawMessage = { 0, // channel number 0x34, 0x12, // device number (byte) 0xaa, // device type id (byte) 0xbb, // transmission type }; AntChannelIdMessage message = new AntChannelIdMessage(rawMessage); assertEquals(0, message.getChannelNumber()); assertEquals(0x1234, message.getDeviceNumber()); assertEquals((byte) 0xaa, message.getDeviceTypeId()); assertEquals((byte) 0xbb, message.getTransmissionType()); } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.services.sensors.ant; import android.test.AndroidTestCase; public class AntMessageTest extends AndroidTestCase { private static class TestAntMessage extends AntMessage { public static short decodeShort(byte low, byte high) { return AntMessage.decodeShort(low, high); } } public void testDecode() { assertEquals(0x1234, TestAntMessage.decodeShort((byte) 0x34, (byte) 0x12)); } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.services.sensors.ant; import android.content.Context; import android.test.AndroidTestCase; import android.test.MoreAsserts; public class AntSensorManagerTest extends AndroidTestCase { private class TestAntSensorManager extends AntSensorManager { public TestAntSensorManager(Context context) { super(context); } public byte messageId; public byte[] messageData; @Override protected void setupAntSensorChannels() {} @SuppressWarnings("deprecation") @Override public void handleMessage(byte[] rawMessage) { super.handleMessage(rawMessage); } @SuppressWarnings("hiding") @Override public boolean handleMessage(byte messageId, byte[] messageData) { this.messageId = messageId; this.messageData = messageData; return true; } } private TestAntSensorManager sensorManager; @Override protected void setUp() throws Exception { super.setUp(); sensorManager = new TestAntSensorManager(getContext()); } public void testSimple() { byte[] rawMessage = { 0x03, // length 0x12, // message id 0x11, 0x22, 0x33, // body }; byte[] expectedBody = { 0x11, 0x22, 0x33 }; sensorManager.handleMessage(rawMessage); assertEquals((byte) 0x12, sensorManager.messageId); MoreAsserts.assertEquals(expectedBody, sensorManager.messageData); } public void testTooShort() { byte[] rawMessage = { 0x53, // length 0x12 // message id }; sensorManager.handleMessage(rawMessage); assertEquals(0, sensorManager.messageId); assertNull(sensorManager.messageData); } public void testLengthWrong() { byte[] rawMessage = { 0x53, // length 0x12, // message id 0x34, // body }; sensorManager.handleMessage(rawMessage); assertEquals(0, sensorManager.messageId); assertNull(sensorManager.messageData); } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.android.apps.mytracks.services.sensors.ant; import com.dsi.ant.AntMesg; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; public class AntDirectSensorManagerTest extends AndroidTestCase { private SharedPreferences sharedPreferences; private AntDirectSensorManager manager; public void setUp() { sharedPreferences = getContext().getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); // Let's use default values. sharedPreferences.edit().clear().apply(); manager = new AntDirectSensorManager(getContext()); } @SuppressWarnings("deprecation") @SmallTest public void testBroadcastData() { manager.setDeviceNumberHRM((short) 42); byte[] buff = new byte[11]; buff[0] = 9; buff[1] = AntMesg.MESG_BROADCAST_DATA_ID; buff[2] = 0; // HRM CHANNEL buff[10] = (byte) 220; manager.handleMessage(buff); Sensor.SensorDataSet sds = manager.getSensorDataSet(); assertNotNull(sds); assertTrue(sds.hasHeartRate()); assertEquals(Sensor.SensorState.SENDING, sds.getHeartRate().getState()); assertEquals(220, sds.getHeartRate().getValue()); assertFalse(sds.hasCadence()); assertFalse(sds.hasPower()); } @SuppressWarnings("deprecation") @SmallTest public void testChannelId() { byte[] buff = new byte[11]; buff[0] = 9; buff[1] = AntMesg.MESG_CHANNEL_ID_ID; buff[3] = 42; manager.handleMessage(buff); assertEquals(42, manager.getDeviceNumberHRM()); assertEquals(42, sharedPreferences.getInt( getContext().getString(R.string.ant_heart_rate_sensor_id_key), -1)); assertNull(manager.getSensorDataSet()); } @SuppressWarnings("deprecation") @SmallTest public void testResponseEvent() { assertEquals(Sensor.SensorState.NONE, manager.getSensorState()); byte[] buff = new byte[5]; buff[0] = 3; // length buff[1] = AntMesg.MESG_RESPONSE_EVENT_ID; buff[2] = 0; // channel buff[3] = AntMesg.MESG_UNASSIGN_CHANNEL_ID; buff[4] = 0; // code manager.handleMessage(buff); assertEquals(Sensor.SensorState.DISCONNECTED, manager.getSensorState()); assertNull(manager.getSensorDataSet()); } // TODO: Test timeout too. }
Java
package com.google.android.apps.mytracks.services.sensors; import java.util.Arrays; import com.google.android.apps.mytracks.content.Sensor; import junit.framework.TestCase; public class PolarMessageParserTest extends TestCase { PolarMessageParser parser = new PolarMessageParser(); // A complete and valid Polar HxM packet // FE08F701D1001104FE08F702D1001104 private final byte[] originalBuf = {(byte) 0xFE, 0x08, (byte) 0xF7, 0x01, (byte) 0xD1, 0x00, 0x11, 0x04, (byte) 0xFE, 0x08, (byte) 0xF7, 0x02, (byte) 0xD1, 0x00, 0x11, 0x04}; private byte[] buf; public void setUp() { buf = Arrays.copyOf(originalBuf, originalBuf.length); } public void testIsValid() { assertTrue(parser.isValid(buf)); } public void testIsValid_invalidHeader() { // Invalidate header. buf[0] = 0x03; assertFalse(parser.isValid(buf)); } public void testIsValid_invalidCheckbyte() { // Invalidate checkbyte. buf[2] = 0x03; assertFalse(parser.isValid(buf)); } public void testIsValid_invalidSequence() { // Invalidate sequence. buf[3] = 0x11; assertFalse(parser.isValid(buf)); } public void testParseBuffer() { buf[5] = 70; Sensor.SensorDataSet sds = parser.parseBuffer(buf); assertTrue(sds.hasHeartRate()); assertTrue(sds.getHeartRate().getState() == Sensor.SensorState.SENDING); assertEquals(70, sds.getHeartRate().getValue()); } public void testFindNextAlignment_offset() { // The first 4 bytes are garbage buf = new byte[originalBuf.length + 4]; buf[0] = 4; buf[1] = 2; buf[2] = 4; buf[3] = 2; // Then the valid message. System.arraycopy(originalBuf, 0, buf, 4, originalBuf.length); assertEquals(4, parser.findNextAlignment(buf)); } public void testFindNextAlignment_invalid() { buf[0] = 0; assertEquals(-1, parser.findNextAlignment(buf)); } }
Java
package com.google.android.apps.mytracks.services.sensors; import com.google.android.apps.mytracks.content.Sensor; import junit.framework.TestCase; public class ZephyrMessageParserTest extends TestCase { ZephyrMessageParser parser = new ZephyrMessageParser(); public void testIsValid() { byte[] smallBuf = new byte[59]; assertFalse(parser.isValid(smallBuf)); // A complete and valid Zephyr HxM packet byte[] buf = { 2,38,55,26,0,49,101,80,0,49,98,100,42,113,120,-53,-24,-60,-123,-61,117,-69,42,-75,74,-78,51,-79,27,-83,28,-88,28,-93,29,-98,25,-103,26,-108,26,-113,59,-118,0,0,0,0,0,0,-22,3,125,1,48,0,96,4,30,0 }; // Make buffer invalid buf[0] = buf[58] = buf[59] = 0; assertFalse(parser.isValid(buf)); buf[0] = 0x02; assertFalse(parser.isValid(buf)); buf[58] = 0x1E; assertFalse(parser.isValid(buf)); buf[59] = 0x03; assertTrue(parser.isValid(buf)); } public void testParseBuffer() { byte[] buf = new byte[60]; // Heart Rate (-1 =^ 255 unsigned byte) buf[12] = -1; // Battery Level buf[11] = 51; // Cadence (=^ 255*16 strides/min) buf[56] = -1; buf[57] = 15; Sensor.SensorDataSet sds = parser.parseBuffer(buf); assertTrue(sds.hasHeartRate()); assertTrue(sds.getHeartRate().getState() == Sensor.SensorState.SENDING); assertEquals(255, sds.getHeartRate().getValue()); assertTrue(sds.hasBatteryLevel()); assertTrue(sds.getBatteryLevel().getState() == Sensor.SensorState.SENDING); assertEquals(51, sds.getBatteryLevel().getValue()); assertTrue(sds.hasCadence()); assertTrue(sds.getCadence().getState() == Sensor.SensorState.SENDING); assertEquals(255, sds.getCadence().getValue()); } public void testFindNextAlignment() { byte[] buf = new byte[60]; assertEquals(-1, parser.findNextAlignment(buf)); buf[10] = 0x03; buf[11] = 0x02; assertEquals(10, parser.findNextAlignment(buf)); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.content.WaypointCreationRequest.WaypointType; import android.os.Parcel; import android.test.AndroidTestCase; /** * Tests for the WaypointCreationRequest class. * {@link WaypointCreationRequest} * * @author Sandor Dornbush */ public class WaypointCreationRequestTest extends AndroidTestCase { public void testTypeParceling() { WaypointCreationRequest original = WaypointCreationRequest.DEFAULT_MARKER; Parcel p = Parcel.obtain(); original.writeToParcel(p, 0); p.setDataPosition(0); WaypointCreationRequest copy = WaypointCreationRequest.CREATOR.createFromParcel(p); assertEquals(original.getType(), copy.getType()); assertNull(copy.getName()); assertNull(copy.getDescription()); assertNull(copy.getIconUrl()); } public void testAllAttributesParceling() { WaypointCreationRequest original = new WaypointCreationRequest(WaypointType.MARKER, "name", "description", "img.png"); Parcel p = Parcel.obtain(); original.writeToParcel(p, 0); p.setDataPosition(0); WaypointCreationRequest copy = WaypointCreationRequest.CREATOR.createFromParcel(p); assertEquals(original.getType(), copy.getType()); assertEquals("name", copy.getName()); assertEquals("description", copy.getDescription()); assertEquals("img.png", copy.getIconUrl()); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationFactory; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator; import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext; import android.content.Context; import android.location.Location; import android.test.AndroidTestCase; import android.test.RenamingDelegatingContext; import android.test.mock.MockContentResolver; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * A unit test for {@link MyTracksProviderUtilsImpl}. * * @author Bartlomiej Niechwiej */ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { private Context context; private MyTracksProviderUtils providerUtils; @Override protected void setUp() throws Exception { super.setUp(); MockContentResolver mockContentResolver = new MockContentResolver(); RenamingDelegatingContext targetContext = new RenamingDelegatingContext( getContext(), getContext(), "test."); context = new MockContext(mockContentResolver, targetContext); MyTracksProvider provider = new MyTracksProvider(); provider.attachInfo(context, null); mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider); setContext(context); providerUtils = MyTracksProviderUtils.Factory.get(context); } public void testLocationIterator_noPoints() { testIterator(1, 0, 1, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } public void testLocationIterator_customFactory() { final Location location = new Location("test_location"); final AtomicInteger counter = new AtomicInteger(); testIterator(1, 15, 4, false, new LocationFactory() { @Override public Location createLocation() { counter.incrementAndGet(); return location; } }); // Make sure we were called exactly as many times as we had track points. assertEquals(15, counter.get()); } public void testLocationIterator_nullFactory() { try { testIterator(1, 15, 4, false, null); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // Expected. } } public void testLocationIterator_noBatchAscending() { testIterator(1, 50, 100, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); testIterator(2, 50, 50, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } public void testLocationIterator_noBatchDescending() { testIterator(1, 50, 100, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); testIterator(2, 50, 50, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } public void testLocationIterator_batchAscending() { testIterator(1, 50, 11, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); testIterator(2, 50, 25, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } public void testLocationIterator_batchDescending() { testIterator(1, 50, 11, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); testIterator(2, 50, 25, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } public void testLocationIterator_largeTrack() { testIterator(1, 20000, 2000, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } private List<Location> testIterator(long trackId, int numPoints, int batchSize, boolean descending, LocationFactory locationFactory) { long lastPointId = initializeTrack(trackId, numPoints); ((MyTracksProviderUtilsImpl) providerUtils).setDefaultCursorBatchSize(batchSize); List<Location> locations = new ArrayList<Location>(numPoints); LocationIterator it = providerUtils.getLocationIterator(trackId, -1, descending, locationFactory); try { while (it.hasNext()) { Location loc = it.next(); assertNotNull(loc); locations.add(loc); // Make sure the IDs are returned in the right order. assertEquals(descending ? lastPointId - locations.size() + 1 : lastPointId - numPoints + locations.size(), it.getLocationId()); } assertEquals(numPoints, locations.size()); } finally { it.close(); } return locations; } private long initializeTrack(long id, int numPoints) { Track track = new Track(); track.setId(id); track.setName("Test: " + id); track.setNumberOfPoints(numPoints); providerUtils.insertTrack(track); track = providerUtils.getTrack(id); assertNotNull(track); Location[] locations = new Location[numPoints]; for (int i = 0; i < numPoints; ++i) { Location loc = new Location("test"); loc.setLatitude(37.0 + (double) i / 10000.0); loc.setLongitude(57.0 - (double) i / 10000.0); loc.setAccuracy((float) i / 100.0f); loc.setAltitude(i * 2.5); locations[i] = loc; } providerUtils.bulkInsertTrackPoints(locations, numPoints, id); // Load all inserted locations. long lastPointId = -1; int counter = 0; LocationIterator it = providerUtils.getLocationIterator(id, -1, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); try { while (it.hasNext()) { it.next(); lastPointId = it.getLocationId(); counter++; } } finally { it.close(); } assertTrue(numPoints == 0 || lastPointId > 0); assertEquals(numPoints, track.getNumberOfPoints()); assertEquals(numPoints, counter); return lastPointId; } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.content; import static com.google.android.testing.mocking.AndroidMock.anyInt; import static com.google.android.testing.mocking.AndroidMock.capture; import static com.google.android.testing.mocking.AndroidMock.eq; import static com.google.android.testing.mocking.AndroidMock.expect; import static com.google.android.testing.mocking.AndroidMock.isA; import static com.google.android.testing.mocking.AndroidMock.leq; import static com.google.android.testing.mocking.AndroidMock.same; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationFactory; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator; import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType; import com.google.android.apps.mytracks.content.TrackDataListener.ProviderState; import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext; import com.google.android.maps.mytracks.R; import com.google.android.testing.mocking.AndroidMock; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.ContentObserver; import android.database.Cursor; import android.database.MatrixCursor; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.location.Location; import android.location.LocationListener; import android.provider.BaseColumns; import android.test.AndroidTestCase; import android.test.RenamingDelegatingContext; import android.test.mock.MockContentResolver; import java.lang.reflect.Constructor; import java.util.EnumSet; import java.util.HashSet; import java.util.Set; import org.easymock.Capture; import org.easymock.IAnswer; /** * Tests for {@link TrackDataHub}. * * @author Rodrigo Damazio */ public class TrackDataHubTest extends AndroidTestCase { private static final long TRACK_ID = 42L; private static final int TARGET_POINTS = 50; private MyTracksProviderUtils providerUtils; private TrackDataHub hub; private TrackDataListeners listeners; private DataSourcesWrapper dataSources; private SharedPreferences prefs; private TrackDataListener listener1; private TrackDataListener listener2; private Capture<OnSharedPreferenceChangeListener> preferenceListenerCapture = new Capture<SharedPreferences.OnSharedPreferenceChangeListener>(); private MockContext context; private float declination; @Override protected void setUp() throws Exception { super.setUp(); MockContentResolver mockContentResolver = new MockContentResolver(); RenamingDelegatingContext targetContext = new RenamingDelegatingContext( getContext(), getContext(), "test."); context = new MockContext(mockContentResolver, targetContext); prefs = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); providerUtils = AndroidMock.createMock("providerUtils", MyTracksProviderUtils.class); dataSources = AndroidMock.createNiceMock("dataSources", DataSourcesWrapper.class); listeners = new TrackDataListeners(); hub = new TrackDataHub(context, listeners, prefs, providerUtils, TARGET_POINTS) { @Override protected DataSourcesWrapper newDataSources() { return dataSources; } @Override protected void runInListenerThread(Runnable runnable) { // Run everything in the same thread. runnable.run(); } @Override protected float getDeclinationFor(Location location, long timestamp) { return declination; } }; listener1 = AndroidMock.createStrictMock("listener1", TrackDataListener.class); listener2 = AndroidMock.createStrictMock("listener2", TrackDataListener.class); } @Override protected void tearDown() throws Exception { AndroidMock.reset(dataSources); // Expect everything to be unregistered. if (preferenceListenerCapture.hasCaptured()) { dataSources.unregisterOnSharedPreferenceChangeListener(preferenceListenerCapture.getValue()); } dataSources.removeLocationUpdates(isA(LocationListener.class)); dataSources.unregisterSensorListener(isA(SensorEventListener.class)); dataSources.unregisterContentObserver(isA(ContentObserver.class)); AndroidMock.expectLastCall().times(3); AndroidMock.replay(dataSources); hub.stop(); hub = null; super.tearDown(); } public void testTrackListen() { Capture<ContentObserver> observerCapture = new Capture<ContentObserver>(); Track track = new Track(); prefs.edit().putLong("recordingTrack", TRACK_ID) .putLong("selectedTrack", TRACK_ID).apply(); expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track); expectStart(); dataSources.registerContentObserver( eq(TracksColumns.CONTENT_URI), eq(false), capture(observerCapture)); // Expect the initial loading. // Both listeners (registered before and after start) should get the same data. listener1.onTrackUpdated(track); listener2.onTrackUpdated(track); replay(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.TRACK_UPDATES)); hub.start(); hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.TRACK_UPDATES)); verifyAndReset(); ContentObserver observer = observerCapture.getValue(); expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track); // Now expect an update. listener1.onTrackUpdated(track); listener2.onTrackUpdated(track); replay(); observer.onChange(false); verifyAndReset(); // Unregister one, get another update. expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track); listener2.onTrackUpdated(track); replay(); hub.unregisterTrackDataListener(listener1); observer.onChange(false); verifyAndReset(); // Unregister the other, expect internal unregistration dataSources.unregisterContentObserver(observer); replay(); hub.unregisterTrackDataListener(listener2); observer.onChange(false); verifyAndReset(); } private static class FixedSizeCursorAnswer implements IAnswer<Cursor> { private final int size; public FixedSizeCursorAnswer(int size) { this.size = size; } @Override public Cursor answer() throws Throwable { MatrixCursor cursor = new MatrixCursor(new String[] { BaseColumns._ID }); for (long i = 1; i <= size; i++) { cursor.addRow(new Object[] { i }); } return cursor; } } private static class FixedSizeLocationIterator implements LocationIterator { private final long startId; private final Location[] locs; private final Set<Integer> splitIndexSet = new HashSet<Integer>(); private int currentIdx = -1; public FixedSizeLocationIterator(long startId, int size) { this(startId, size, null); } public FixedSizeLocationIterator(long startId, int size, int... splitIndices) { this.startId = startId; this.locs = new Location[size]; for (int i = 0; i < size; i++) { Location loc = new Location("gps"); loc.setLatitude(-15.0 + i / 1000.0); loc.setLongitude(37 + i / 1000.0); loc.setAltitude(i); locs[i] = loc; } if (splitIndices != null) { for (int splitIdx : splitIndices) { splitIndexSet.add(splitIdx); Location splitLoc = locs[splitIdx]; splitLoc.setLatitude(100.0); splitLoc.setLongitude(200.0); } } } public void expectLocationsDelivered(TrackDataListener listener) { for (int i = 0; i < locs.length; i++) { if (splitIndexSet.contains(i)) { listener.onSegmentSplit(); } else { listener.onNewTrackPoint(locs[i]); } } } public void expectSampledLocationsDelivered( TrackDataListener listener, int sampleFrequency, boolean includeSampledOut) { for (int i = 0; i < locs.length; i++) { if (splitIndexSet.contains(i)) { listener.onSegmentSplit(); } else if (i % sampleFrequency == 0) { listener.onNewTrackPoint(locs[i]); } else if (includeSampledOut) { listener.onSampledOutTrackPoint(locs[i]); } } } @Override public boolean hasNext() { return currentIdx < (locs.length - 1); } @Override public Location next() { currentIdx++; return locs[currentIdx]; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public long getLocationId() { return startId + currentIdx; } @Override public void close() { // Do nothing } } public void testWaypointListen() { Capture<ContentObserver> observerCapture = new Capture<ContentObserver>(); prefs.edit().putLong("recordingTrack", TRACK_ID) .putLong("selectedTrack", TRACK_ID).apply(); Waypoint wpt1 = new Waypoint(), wpt2 = new Waypoint(), wpt3 = new Waypoint(), wpt4 = new Waypoint(); Location loc = new Location("gps"); loc.setLatitude(10.0); loc.setLongitude(8.0); wpt1.setLocation(loc); wpt2.setLocation(loc); wpt3.setLocation(loc); wpt4.setLocation(loc); expect(providerUtils.getWaypointsCursor( eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS))) .andStubAnswer(new FixedSizeCursorAnswer(2)); expect(providerUtils.createWaypoint(isA(Cursor.class))) .andReturn(wpt1) .andReturn(wpt2) .andReturn(wpt1) .andReturn(wpt2); expectStart(); dataSources.registerContentObserver( eq(WaypointsColumns.CONTENT_URI), eq(false), capture(observerCapture)); // Expect the initial loading. // Both listeners (registered before and after start) should get the same data. listener1.clearWaypoints(); listener1.onNewWaypoint(wpt1); listener1.onNewWaypoint(wpt2); listener1.onNewWaypointsDone(); listener2.clearWaypoints(); listener2.onNewWaypoint(wpt1); listener2.onNewWaypoint(wpt2); listener2.onNewWaypointsDone(); replay(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.WAYPOINT_UPDATES)); hub.start(); hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.WAYPOINT_UPDATES)); verifyAndReset(); ContentObserver observer = observerCapture.getValue(); expect(providerUtils.getWaypointsCursor( eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS))) .andStubAnswer(new FixedSizeCursorAnswer(3)); expect(providerUtils.createWaypoint(isA(Cursor.class))) .andReturn(wpt1) .andReturn(wpt2) .andReturn(wpt3); // Now expect an update. listener1.clearWaypoints(); listener2.clearWaypoints(); listener1.onNewWaypoint(wpt1); listener2.onNewWaypoint(wpt1); listener1.onNewWaypoint(wpt2); listener2.onNewWaypoint(wpt2); listener1.onNewWaypoint(wpt3); listener2.onNewWaypoint(wpt3); listener1.onNewWaypointsDone(); listener2.onNewWaypointsDone(); replay(); observer.onChange(false); verifyAndReset(); // Unregister one, get another update. expect(providerUtils.getWaypointsCursor( eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS))) .andStubAnswer(new FixedSizeCursorAnswer(4)); expect(providerUtils.createWaypoint(isA(Cursor.class))) .andReturn(wpt1) .andReturn(wpt2) .andReturn(wpt3) .andReturn(wpt4); // Now expect an update. listener2.clearWaypoints(); listener2.onNewWaypoint(wpt1); listener2.onNewWaypoint(wpt2); listener2.onNewWaypoint(wpt3); listener2.onNewWaypoint(wpt4); listener2.onNewWaypointsDone(); replay(); hub.unregisterTrackDataListener(listener1); observer.onChange(false); verifyAndReset(); // Unregister the other, expect internal unregistration dataSources.unregisterContentObserver(observer); replay(); hub.unregisterTrackDataListener(listener2); observer.onChange(false); verifyAndReset(); } public void testPointsListen() { Capture<ContentObserver> observerCapture = new Capture<ContentObserver>(); prefs.edit().putLong("recordingTrack", TRACK_ID) .putLong("selectedTrack", TRACK_ID).apply(); expectStart(); dataSources.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture)); FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L); listener1.clearTrackPoints(); locationIterator.expectLocationsDelivered(listener1); listener1.onNewTrackPointsDone(); replay(); hub.start(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES)); verifyAndReset(); // Register a second listener - it will get the same points as the previous one locationIterator = new FixedSizeLocationIterator(1, 10, 5); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L); listener2.clearTrackPoints(); locationIterator.expectLocationsDelivered(listener2); listener2.onNewTrackPointsDone(); replay(); hub.start(); hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.POINT_UPDATES)); verifyAndReset(); // Deliver more points - should go to both listeners, without clearing. ContentObserver observer = observerCapture.getValue(); locationIterator = new FixedSizeLocationIterator(11, 10, 1); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(20L); locationIterator.expectLocationsDelivered(listener1); locationIterator.expectLocationsDelivered(listener2); listener1.onNewTrackPointsDone(); listener2.onNewTrackPointsDone(); replay(); observer.onChange(false); verifyAndReset(); // Unregister listener1, switch tracks to ensure data is cleared/reloaded. locationIterator = new FixedSizeLocationIterator(101, 10); expect(providerUtils.getLocationIterator( eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID + 1)).andReturn(110L); listener2.clearTrackPoints(); locationIterator.expectLocationsDelivered(listener2); listener2.onNewTrackPointsDone(); replay(); hub.unregisterTrackDataListener(listener1); hub.loadTrack(TRACK_ID + 1); verifyAndReset(); } public void testPointsListen_beforeStart() { } public void testPointsListen_reRegister() { Capture<ContentObserver> observerCapture = new Capture<ContentObserver>(); prefs.edit().putLong("recordingTrack", TRACK_ID) .putLong("selectedTrack", TRACK_ID).apply(); expectStart(); dataSources.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture)); FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L); listener1.clearTrackPoints(); locationIterator.expectLocationsDelivered(listener1); listener1.onNewTrackPointsDone(); replay(); hub.start(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES)); verifyAndReset(); // Unregister ContentObserver observer = observerCapture.getValue(); dataSources.unregisterContentObserver(observer); replay(); hub.unregisterTrackDataListener(listener1); verifyAndReset(); // Register again, except only points since unregistered. dataSources.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture)); locationIterator = new FixedSizeLocationIterator(11, 10); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(20L); locationIterator.expectLocationsDelivered(listener1); listener1.onNewTrackPointsDone(); replay(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES)); verifyAndReset(); // Deliver more points - should still be incremental. locationIterator = new FixedSizeLocationIterator(21, 10, 1); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(21L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(30L); locationIterator.expectLocationsDelivered(listener1); listener1.onNewTrackPointsDone(); replay(); observer.onChange(false); verifyAndReset(); } public void testPointsListen_reRegisterTrackChanged() { Capture<ContentObserver> observerCapture = new Capture<ContentObserver>(); prefs.edit().putLong("recordingTrack", TRACK_ID) .putLong("selectedTrack", TRACK_ID).apply(); expectStart(); dataSources.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture)); FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L); listener1.clearTrackPoints(); locationIterator.expectLocationsDelivered(listener1); listener1.onNewTrackPointsDone(); replay(); hub.start(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES)); verifyAndReset(); // Unregister ContentObserver observer = observerCapture.getValue(); dataSources.unregisterContentObserver(observer); replay(); hub.unregisterTrackDataListener(listener1); verifyAndReset(); // Register again after track changed, expect all points. dataSources.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture)); locationIterator = new FixedSizeLocationIterator(1, 10); expect(providerUtils.getLocationIterator( eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID + 1)).andReturn(10L); listener1.clearTrackPoints(); locationIterator.expectLocationsDelivered(listener1); listener1.onNewTrackPointsDone(); replay(); hub.loadTrack(TRACK_ID + 1); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES)); verifyAndReset(); } public void testPointsListen_largeTrackSampling() { Capture<ContentObserver> observerCapture = new Capture<ContentObserver>(); prefs.edit().putLong("recordingTrack", TRACK_ID) .putLong("selectedTrack", TRACK_ID).apply(); expectStart(); dataSources.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture)); FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 200, 4, 25, 71, 120); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(200L); listener1.clearTrackPoints(); listener2.clearTrackPoints(); locationIterator.expectSampledLocationsDelivered(listener1, 4, false); locationIterator.expectSampledLocationsDelivered(listener2, 4, true); listener1.onNewTrackPointsDone(); listener2.onNewTrackPointsDone(); replay(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES)); hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.POINT_UPDATES, ListenerDataType.SAMPLED_OUT_POINT_UPDATES)); hub.start(); verifyAndReset(); } public void testPointsListen_resampling() { Capture<ContentObserver> observerCapture = new Capture<ContentObserver>(); prefs.edit().putLong("recordingTrack", TRACK_ID) .putLong("selectedTrack", TRACK_ID).apply(); expectStart(); dataSources.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture)); // Deliver 30 points (no sampling happens) FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 30, 5); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(30L); listener1.clearTrackPoints(); locationIterator.expectLocationsDelivered(listener1); listener1.onNewTrackPointsDone(); replay(); hub.start(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES)); verifyAndReset(); // Now deliver 30 more (incrementally sampled) ContentObserver observer = observerCapture.getValue(); locationIterator = new FixedSizeLocationIterator(31, 30); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(31L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(60L); locationIterator.expectSampledLocationsDelivered(listener1, 2, false); listener1.onNewTrackPointsDone(); replay(); observer.onChange(false); verifyAndReset(); // Now another 30 (triggers resampling) locationIterator = new FixedSizeLocationIterator(1, 90); expect(providerUtils.getLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(90L); listener1.clearTrackPoints(); locationIterator.expectSampledLocationsDelivered(listener1, 2, false); listener1.onNewTrackPointsDone(); replay(); observer.onChange(false); verifyAndReset(); } public void testLocationListen() { // TODO } public void testCompassListen() throws Exception { AndroidMock.resetToDefault(listener1); Sensor compass = newSensor(); expect(dataSources.getSensor(Sensor.TYPE_ORIENTATION)).andReturn(compass); Capture<SensorEventListener> listenerCapture = new Capture<SensorEventListener>(); dataSources.registerSensorListener(capture(listenerCapture), same(compass), anyInt()); Capture<LocationListener> locationListenerCapture = new Capture<LocationListener>(); dataSources.requestLocationUpdates(capture(locationListenerCapture)); SensorEvent event = newSensorEvent(); event.sensor = compass; // First, get a dummy heading update. listener1.onCurrentHeadingChanged(0.0); // Then, get a heading update without a known location (thus can't calculate declination). listener1.onCurrentHeadingChanged(42.0f); // Also expect location updates which are not relevant to us. listener1.onProviderStateChange(isA(ProviderState.class)); AndroidMock.expectLastCall().anyTimes(); replay(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.COMPASS_UPDATES, ListenerDataType.LOCATION_UPDATES)); hub.start(); SensorEventListener sensorListener = listenerCapture.getValue(); LocationListener locationListener = locationListenerCapture.getValue(); event.values[0] = 42.0f; sensorListener.onSensorChanged(event); verifyAndReset(); // Expect the heading update to include declination. listener1.onCurrentHeadingChanged(52.0); // Also expect location updates which are not relevant to us. listener1.onProviderStateChange(isA(ProviderState.class)); AndroidMock.expectLastCall().anyTimes(); listener1.onCurrentLocationChanged(isA(Location.class)); AndroidMock.expectLastCall().anyTimes(); replay(); // Now try injecting a location update, triggering a declination update. Location location = new Location("gps"); location.setLatitude(10.0); location.setLongitude(20.0); location.setAltitude(30.0); declination = 10.0f; locationListener.onLocationChanged(location); sensorListener.onSensorChanged(event); verifyAndReset(); listener1.onCurrentHeadingChanged(52.0); replay(); // Now try changing the known declination - it should still return the old declination, since // updates only happen sparsely. declination = 20.0f; sensorListener.onSensorChanged(event); verifyAndReset(); } private Sensor newSensor() throws Exception { Constructor<Sensor> constructor = Sensor.class.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } private SensorEvent newSensorEvent() throws Exception { Constructor<SensorEvent> constructor = SensorEvent.class.getDeclaredConstructor(int.class); constructor.setAccessible(true); return constructor.newInstance(3); } public void testDisplayPreferencesListen() throws Exception { String metricUnitsKey = context.getString(R.string.metric_units_key); String speedKey = context.getString(R.string.report_speed_key); prefs.edit() .putBoolean(metricUnitsKey, true) .putBoolean(speedKey, true) .apply(); Capture<OnSharedPreferenceChangeListener> listenerCapture = new Capture<OnSharedPreferenceChangeListener>(); dataSources.registerOnSharedPreferenceChangeListener(capture(listenerCapture)); expect(listener1.onUnitsChanged(true)).andReturn(false); expect(listener2.onUnitsChanged(true)).andReturn(false); expect(listener1.onReportSpeedChanged(true)).andReturn(false); expect(listener2.onReportSpeedChanged(true)).andReturn(false); replay(); hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.DISPLAY_PREFERENCES)); hub.start(); hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.DISPLAY_PREFERENCES)); verifyAndReset(); expect(listener1.onReportSpeedChanged(false)).andReturn(false); expect(listener2.onReportSpeedChanged(false)).andReturn(false); replay(); prefs.edit() .putBoolean(speedKey, false) .apply(); OnSharedPreferenceChangeListener listener = listenerCapture.getValue(); listener.onSharedPreferenceChanged(prefs, speedKey); AndroidMock.verify(dataSources, providerUtils, listener1, listener2); AndroidMock.reset(dataSources, providerUtils, listener1, listener2); expect(listener1.onUnitsChanged(false)).andReturn(false); expect(listener2.onUnitsChanged(false)).andReturn(false); replay(); prefs.edit() .putBoolean(metricUnitsKey, false) .apply(); listener.onSharedPreferenceChanged(prefs, metricUnitsKey); verifyAndReset(); } private void expectStart() { dataSources.registerOnSharedPreferenceChangeListener(capture(preferenceListenerCapture)); } private void replay() { AndroidMock.replay(dataSources, providerUtils, listener1, listener2); } private void verifyAndReset() { AndroidMock.verify(listener1, listener2, dataSources, providerUtils); AndroidMock.reset(listener1, listener2, dataSources, providerUtils); } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks; import android.graphics.Path; import android.graphics.PointF; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import junit.framework.Assert; /** * Elements for Tests for the MyTracks map overlay. * * @author Bartlomiej Niechwiej * @author Vangelis S. * * A mock class that intercepts {@code Path}'s and records calls to * {@code #moveTo()} and {@code #lineTo()}. */ public class MockPath extends Path { /** A list of disjoined path segments. */ public final List<List<PointF>> segments = new LinkedList<List<PointF>>(); /** The total number of points in this path. */ public int totalPoints; private List<PointF> currentSegment; @Override public void lineTo(float x, float y) { super.lineTo(x, y); Assert.assertNotNull(currentSegment); currentSegment.add(new PointF(x, y)); totalPoints++; } @Override public void moveTo(float x, float y) { super.moveTo(x, y); segments.add(currentSegment = new ArrayList<PointF>(Arrays.asList(new PointF(x, y)))); totalPoints++; } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks; import com.google.android.maps.GeoPoint; import com.google.android.maps.Projection; import android.graphics.Point; /** * Elements for Tests for the MyTracks map overlay. * * @author Bartlomiej Niechwiej * @author Vangelis S. * * A mock {@code Projection} that acts as the identity matrix. */ public class MockProjection implements Projection { @Override public Point toPixels(GeoPoint in, Point out) { return out; } @Override public float metersToEquatorPixels(float meters) { return meters; } @Override public GeoPoint fromPixels(int x, int y) { return new GeoPoint(y, x); } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.maps; import android.location.Location; /** * Tests for the MyTracks track path descriptors and painters. * * @author Vangelis S. */ public class TrackPathDescriptorDynamicSpeedTest extends TrackPathPainterTestCase { public void testDynamicSpeedTrackPathDescriptor() throws Exception { Location location = new Location("gps"); location.setLatitude(10); for (int i = 0; i < 100; ++i) { location = new Location("gps"); location.setLatitude(20 + i / 2); location.setLongitude(150 - i); myTracksOverlay.addLocation(location); } TrackPathPainter painter = new DynamicSpeedTrackPathPainter( getContext(), new DynamicSpeedTrackPathDescriptor(getContext())); myTracksOverlay.setTrackPathPainter(painter); int startLocationIdx = 0; Boolean alwaysVisible = true; assertNotNull(painter); painter.updatePath(myTracksOverlay.getMapProjection(mockView), myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible, myTracksOverlay.getPoints()); assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath()); painter.drawTrack(canvas); } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.maps; import android.location.Location; /** * Tests for the MyTracks track path descriptors and painters. * * @author Vangelis S. */ public class TrackPathDescriptorFixedSpeedTest extends TrackPathPainterTestCase { public void testFixedSpeedTrackPathDescriptor() throws Exception { Location location = new Location("gps"); location.setLatitude(10); for (int i = 0; i < 100; ++i) { location = new Location("gps"); location.setLatitude(20 + i / 2); location.setLongitude(150 - i); myTracksOverlay.addLocation(location); } TrackPathPainter painter = new DynamicSpeedTrackPathPainter( getContext(), new FixedSpeedTrackPathDescriptor(getContext())); myTracksOverlay.setTrackPathPainter(painter); int startLocationIdx = 0; Boolean alwaysVisible = true; assertNotNull(painter); painter.updatePath(myTracksOverlay.getMapProjection(mockView), myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible, myTracksOverlay.getPoints()); assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath()); painter.drawTrack(canvas); } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.maps; import android.location.Location; /** * Tests for the MyTracks track path descriptors and painters. * * @author Vangelis S. */ public class TrackPathPainterSingleColorTest extends TrackPathPainterTestCase { public void testSimpeColorTrackPathPainter() throws Exception { Location location = new Location("gps"); location.setLatitude(10); for (int i = 0; i < 100; ++i) { location = new Location("gps"); location.setLatitude(20 + i / 2); location.setLongitude(150 - i); myTracksOverlay.addLocation(location); } TrackPathPainter painter = new SingleColorTrackPathPainter(getContext()); myTracksOverlay.setTrackPathPainter(painter); int startLocationIdx = 0; Boolean alwaysVisible = true; assertNotNull(painter); painter.updatePath(myTracksOverlay.getMapProjection(mockView), myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible, myTracksOverlay.getPoints()); assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath()); painter.drawTrack(canvas); } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.maps; import com.google.android.apps.mytracks.MockMyTracksOverlay; import com.google.android.maps.MapView; import android.graphics.Canvas; import android.test.AndroidTestCase; /** * Tests for the MyTracks track path descriptors and painters. * * @author Vangelis S. */ public class TrackPathPainterTestCase extends AndroidTestCase { protected Canvas canvas; protected MockMyTracksOverlay myTracksOverlay; protected MapView mockView; @Override protected void setUp() throws Exception { super.setUp(); canvas = new Canvas(); myTracksOverlay = new MockMyTracksOverlay(getContext()); // Enable drawing. myTracksOverlay.setTrackDrawingEnabled(true); mockView = null; } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.maps; import com.google.android.apps.mytracks.Constants; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.location.Location; /** * Tests for the MyTracks track path painter factory. * * @author Vangelis S. */ public class TrackPathPainterFactoryTest extends TrackPathPainterTestCase { public void testTrackPathPainterFactory() throws Exception { Location location = new Location("gps"); location.setLatitude(10); for (int i = 0; i < 100; ++i) { location = new Location("gps"); location.setLatitude(20 + i / 2); location.setLongitude(150 - i); myTracksOverlay.addLocation(location); } Context context = getContext(); SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs == null) { return; } testTrackPathPainterFactorySpecific(context, prefs, R.string.display_track_color_value_none, SingleColorTrackPathPainter.class); testTrackPathPainterFactorySpecific(context, prefs, R.string.display_track_color_value_fixed, DynamicSpeedTrackPathPainter.class); testTrackPathPainterFactorySpecific(context, prefs, R.string.display_track_color_value_dynamic, DynamicSpeedTrackPathPainter.class); } private <T> void testTrackPathPainterFactorySpecific(Context context, SharedPreferences prefs, int track_color_mode, Class <?> c) { prefs.edit().putString(context.getString(R.string.track_color_mode_key), context.getString(track_color_mode)).apply(); int startLocationIdx = 0; Boolean alwaysVisible = true; TrackPathPainter painter = TrackPathPainterFactory.getTrackPathPainter(context); myTracksOverlay.setTrackPathPainter(painter); assertNotNull(painter); assertTrue(c.isInstance(painter)); painter.updatePath(myTracksOverlay.getMapProjection(mockView), myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible, myTracksOverlay.getPoints()); assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath()); painter.drawTrack(canvas); } }
Java
// Copyright 2009 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.stats; import com.google.android.apps.mytracks.Constants; import android.location.Location; import junit.framework.TestCase; /** * Test the the function of the TripStatisticsBuilder class. * * @author Sandor Dornbush */ public class TripStatisticsBuilderTest extends TestCase { private TripStatisticsBuilder builder = null; @Override protected void setUp() throws Exception { super.setUp(); builder = new TripStatisticsBuilder(System.currentTimeMillis()); } public void testAddLocationSimple() throws Exception { builder = new TripStatisticsBuilder(1000); TripStatistics stats = builder.getStatistics(); assertEquals(0.0, builder.getSmoothedElevation()); assertEquals(Double.POSITIVE_INFINITY, stats.getMinElevation()); assertEquals(Double.NEGATIVE_INFINITY, stats.getMaxElevation()); assertEquals(0.0, stats.getMaxSpeed()); assertEquals(Double.POSITIVE_INFINITY, stats.getMinGrade()); assertEquals(Double.NEGATIVE_INFINITY, stats.getMaxGrade()); assertEquals(0.0, stats.getTotalElevationGain()); assertEquals(0, stats.getMovingTime()); assertEquals(0.0, stats.getTotalDistance()); for (int i = 0; i < 100; i++) { Location l = new Location("test"); l.setAccuracy(1.0f); l.setLongitude(45.0); // Going up by 5 meters each time. l.setAltitude(i); // Moving by .1% of a degree latitude. l.setLatitude(i * .001); l.setSpeed(11.1f); // Each time slice is 10 seconds. long time = 1000 + 10000 * i; l.setTime(time); boolean moving = builder.addLocation(l, time); assertEquals((i != 0), moving); stats = builder.getStatistics(); assertEquals(10000 * i, stats.getTotalTime()); assertEquals(10000 * i, stats.getMovingTime()); assertEquals(i, builder.getSmoothedElevation(), Constants.ELEVATION_SMOOTHING_FACTOR / 2); assertEquals(0.0, stats.getMinElevation()); assertEquals(i, stats.getMaxElevation(), Constants.ELEVATION_SMOOTHING_FACTOR / 2); assertEquals(i, stats.getTotalElevationGain(), Constants.ELEVATION_SMOOTHING_FACTOR); if (i > Constants.SPEED_SMOOTHING_FACTOR) { assertEquals(11.1f, stats.getMaxSpeed(), 0.1); } if ((i > Constants.GRADE_SMOOTHING_FACTOR) && (i > Constants.ELEVATION_SMOOTHING_FACTOR)) { assertEquals(0.009, stats.getMinGrade(), 0.0001); assertEquals(0.009, stats.getMaxGrade(), 0.0001); } // 1 degree = 111 km // 1 timeslice = 0.001 degree = 111 m assertEquals(111.0 * i, stats.getTotalDistance(), 100); } } /** * Test that elevation works if the user is stable. */ public void testElevationSimple() throws Exception { for (double elevation = 0; elevation < 1000; elevation += 10) { builder = new TripStatisticsBuilder(System.currentTimeMillis()); for (int j = 0; j < 100; j++) { assertEquals(0.0, builder.updateElevation(elevation)); assertEquals(elevation, builder.getSmoothedElevation()); TripStatistics data = builder.getStatistics(); assertEquals(elevation, data.getMinElevation()); assertEquals(elevation, data.getMaxElevation()); assertEquals(0.0, data.getTotalElevationGain()); } } } public void testElevationGain() throws Exception { for (double i = 0; i < 1000; i++) { double expectedGain; if (i < (Constants.ELEVATION_SMOOTHING_FACTOR - 1)) { expectedGain = 0; } else if (i < Constants.ELEVATION_SMOOTHING_FACTOR) { expectedGain = 0.5; } else { expectedGain = 1.0; } assertEquals(expectedGain, builder.updateElevation(i)); assertEquals(i, builder.getSmoothedElevation(), 20); TripStatistics data = builder.getStatistics(); assertEquals(0.0, data.getMinElevation(), 0.0); assertEquals(i, data.getMaxElevation(), Constants.ELEVATION_SMOOTHING_FACTOR); assertEquals(i, data.getTotalElevationGain(), Constants.ELEVATION_SMOOTHING_FACTOR); } } public void testGradeSimple() throws Exception { for (double i = 0; i < 1000; i++) { // The value of the elevation does not matter. This is just to fill the // buffer. builder.updateElevation(i); builder.updateGrade(100, 100); if ((i > Constants.GRADE_SMOOTHING_FACTOR) && (i > Constants.ELEVATION_SMOOTHING_FACTOR)) { assertEquals(1.0, builder.getStatistics().getMaxGrade()); assertEquals(1.0, builder.getStatistics().getMinGrade()); } } for (double i = 0; i < 1000; i++) { // The value of the elevation does not matter. This is just to fill the // buffer. builder.updateElevation(i); builder.updateGrade(100, -100); if ((i > Constants.GRADE_SMOOTHING_FACTOR) && (i > Constants.ELEVATION_SMOOTHING_FACTOR)) { assertEquals(1.0, builder.getStatistics().getMaxGrade()); assertEquals(-1.0, builder.getStatistics().getMinGrade()); } } } public void testGradeIgnoreShort() throws Exception { for (double i = 0; i < 100; i++) { // The value of the elevation does not matter. This is just to fill the // buffer. builder.updateElevation(i); builder.updateGrade(1, 100); assertEquals(Double.NEGATIVE_INFINITY, builder.getStatistics().getMaxGrade()); assertEquals(Double.POSITIVE_INFINITY, builder.getStatistics().getMinGrade()); } } public void testUpdateSpeedIncludeZero() { for (int i = 0; i < 1000; i++) { builder.updateSpeed(i + 1000, 0.0, i, 4.0); assertEquals(0.0, builder.getStatistics().getMaxSpeed()); assertEquals((i + 1) * 1000, builder.getStatistics().getMovingTime()); } } public void testUpdateSpeedIngoreErrorCode() { builder.updateSpeed(12345000, 128.0, 12344000, 0.0); assertEquals(0.0, builder.getStatistics().getMaxSpeed()); assertEquals(1000, builder.getStatistics().getMovingTime()); } public void testUpdateSpeedIngoreLargeAcceleration() { builder.updateSpeed(12345000, 100.0, 12344000, 1.0); assertEquals(0.0, builder.getStatistics().getMaxSpeed()); assertEquals(1000, builder.getStatistics().getMovingTime()); } public void testUpdateSpeed() { for (int i = 0; i < 1000; i++) { builder.updateSpeed(i + 1000, 4.0, i, 4.0); assertEquals((i + 1) * 1000, builder.getStatistics().getMovingTime()); if (i > Constants.SPEED_SMOOTHING_FACTOR) { assertEquals(4.0, builder.getStatistics().getMaxSpeed()); } } } }
Java
/* * Copyright 2009 Google Inc. All Rights Reserved. */ package com.google.android.apps.mytracks.stats; import junit.framework.TestCase; /** * Test for the DoubleBuffer class. * * @author Sandor Dornbush */ public class DoubleBufferTest extends TestCase { /** * Tests that the constructor leaves the buffer in a valid state. */ public void testConstructor() { DoubleBuffer buffer = new DoubleBuffer(10); assertFalse(buffer.isFull()); assertEquals(0.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(0.0, averageAndVariance[0]); assertEquals(0.0, averageAndVariance[1]); } /** * Simple test with 10 of the same values. */ public void testBasic() { DoubleBuffer buffer = new DoubleBuffer(10); for (int i = 0; i < 9; i++) { buffer.setNext(1.0); assertFalse(buffer.isFull()); assertEquals(1.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(1.0, averageAndVariance[0]); assertEquals(0.0, averageAndVariance[1]); } buffer.setNext(1); assertTrue(buffer.isFull()); assertEquals(1.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(1.0, averageAndVariance[0]); assertEquals(0.0, averageAndVariance[1]); } /** * Tests with 5 entries of -10 and 5 entries of 10. */ public void testSplit() { DoubleBuffer buffer = new DoubleBuffer(10); for (int i = 0; i < 5; i++) { buffer.setNext(-10); assertFalse(buffer.isFull()); assertEquals(-10.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(-10.0, averageAndVariance[0]); assertEquals(0.0, averageAndVariance[1]); } for (int i = 1; i < 5; i++) { buffer.setNext(10); assertFalse(buffer.isFull()); double expectedAverage = ((i * 10.0) - 50.0) / (i + 5); assertEquals(buffer.toString(), expectedAverage, buffer.getAverage(), 0.01); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(expectedAverage, averageAndVariance[0]); } buffer.setNext(10); assertTrue(buffer.isFull()); assertEquals(0.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(0.0, averageAndVariance[0]); assertEquals(100.0, averageAndVariance[1]); } /** * Tests that reset leaves the buffer in a valid state. */ public void testReset() { DoubleBuffer buffer = new DoubleBuffer(10); for (int i = 0; i < 100; i++) { buffer.setNext(i); } assertTrue(buffer.isFull()); buffer.reset(); assertFalse(buffer.isFull()); assertEquals(0.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(0.0, averageAndVariance[0]); assertEquals(0.0, averageAndVariance[1]); } /** * Tests that if a lot of items are inserted the smoothing and looping works. */ public void testLoop() { DoubleBuffer buffer = new DoubleBuffer(10); for (int i = 0; i < 1000; i++) { buffer.setNext(i); assertEquals(i >= 9, buffer.isFull()); if (i > 10) { assertEquals(i - 4.5, buffer.getAverage()); } } } }
Java
/** * Copyright 2009 Google Inc. All Rights Reserved. */ package com.google.android.apps.mytracks.stats; import junit.framework.TestCase; import java.util.Random; /** * This class test the ExtremityMonitor class. * * @author Sandor Dornbush */ public class ExtremityMonitorTest extends TestCase { public ExtremityMonitorTest(String name) { super(name); } public void testInitialize() { ExtremityMonitor monitor = new ExtremityMonitor(); assertEquals(Double.POSITIVE_INFINITY, monitor.getMin()); assertEquals(Double.NEGATIVE_INFINITY, monitor.getMax()); } public void testSimple() { ExtremityMonitor monitor = new ExtremityMonitor(); assertTrue(monitor.update(0)); assertTrue(monitor.update(1)); assertEquals(0.0, monitor.getMin()); assertEquals(1.0, monitor.getMax()); assertFalse(monitor.update(1)); assertFalse(monitor.update(0.5)); } /** * Throws a bunch of random numbers between [0,1] at the monitor. */ public void testRandom() { ExtremityMonitor monitor = new ExtremityMonitor(); Random random = new Random(42); for (int i = 0; i < 1000; i++) { monitor.update(random.nextDouble()); } assertTrue(monitor.getMin() < 0.1); assertTrue(monitor.getMax() < 1.0); assertTrue(monitor.getMin() >= 0.0); assertTrue(monitor.getMax() > 0.9); } public void testReset() { ExtremityMonitor monitor = new ExtremityMonitor(); assertTrue(monitor.update(0)); assertTrue(monitor.update(1)); monitor.reset(); assertEquals(Double.POSITIVE_INFINITY, monitor.getMin()); assertEquals(Double.NEGATIVE_INFINITY, monitor.getMax()); assertTrue(monitor.update(0)); assertTrue(monitor.update(1)); assertEquals(0.0, monitor.getMin()); assertEquals(1.0, monitor.getMax()); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.stats; import junit.framework.TestCase; /** * Tests for {@link TripStatistics}. * This only tests non-trivial pieces of that class. * * @author Rodrigo Damazio */ public class TripStatisticsTest extends TestCase { private TripStatistics statistics; @Override protected void setUp() throws Exception { super.setUp(); statistics = new TripStatistics(); } public void testSetBounds() { // This is not a trivial setter, conversion happens in it statistics.setBounds(12345, -34567, 56789, -98765); assertEquals(12345, statistics.getLeft()); assertEquals(-34567, statistics.getTop()); assertEquals(56789, statistics.getRight()); assertEquals(-98765, statistics.getBottom()); } public void testMerge() { TripStatistics statistics2 = new TripStatistics(); statistics.setStartTime(1000L); // Resulting start time statistics.setStopTime(2500L); statistics2.setStartTime(3000L); statistics2.setStopTime(4000L); // Resulting stop time statistics.setTotalTime(1500L); statistics2.setTotalTime(1000L); // Result: 1500+1000 statistics.setMovingTime(700L); statistics2.setMovingTime(600L); // Result: 700+600 statistics.setTotalDistance(750.0); statistics2.setTotalDistance(350.0); // Result: 750+350 statistics.setTotalElevationGain(50.0); statistics2.setTotalElevationGain(850.0); // Result: 850+50 statistics.setMaxSpeed(60.0); // Resulting max speed statistics2.setMaxSpeed(30.0); statistics.setMaxElevation(1250.0); statistics.setMinElevation(1200.0); // Resulting min elevation statistics2.setMaxElevation(3575.0); // Resulting max elevation statistics2.setMinElevation(2800.0); statistics.setMaxGrade(15.0); statistics.setMinGrade(-25.0); // Resulting min grade statistics2.setMaxGrade(35.0); // Resulting max grade statistics2.setMinGrade(0.0); // Resulting bounds: -10000, 35000, 30000, -40000 statistics.setBounds(-10000, 20000, 30000, -40000); statistics2.setBounds(-5000, 35000, 0, 20000); statistics.merge(statistics2); assertEquals(1000L, statistics.getStartTime()); assertEquals(4000L, statistics.getStopTime()); assertEquals(2500L, statistics.getTotalTime()); assertEquals(1300L, statistics.getMovingTime()); assertEquals(1100.0, statistics.getTotalDistance()); assertEquals(900.0, statistics.getTotalElevationGain()); assertEquals(60.0, statistics.getMaxSpeed()); assertEquals(-10000, statistics.getLeft()); assertEquals(30000, statistics.getRight()); assertEquals(35000, statistics.getTop()); assertEquals(-40000, statistics.getBottom()); assertEquals(1200.0, statistics.getMinElevation()); assertEquals(3575.0, statistics.getMaxElevation()); assertEquals(-25.0, statistics.getMinGrade()); assertEquals(35.0, statistics.getMaxGrade()); } public void testGetAverageSpeed() { statistics.setTotalDistance(1000.0); statistics.setTotalTime(50000); // in milliseconds assertEquals(20.0, statistics.getAverageSpeed()); } public void testGetAverageMovingSpeed() { statistics.setTotalDistance(1000.0); statistics.setMovingTime(20000); // in milliseconds assertEquals(50.0, statistics.getAverageMovingSpeed()); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks; import com.google.android.apps.mytracks.services.ServiceUtils; import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.Instrumentation.ActivityMonitor; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.test.ActivityInstrumentationTestCase2; import android.widget.Button; import java.io.File; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; /** * A unit test for {@link MyTracks} activity. * * @author Bartlomiej Niechwiej */ public class MyTracksTest extends ActivityInstrumentationTestCase2<MyTracks>{ private SharedPreferences sharedPreferences; private TrackRecordingServiceConnection serviceConnection; public MyTracksTest() { super(MyTracks.class); } @Override protected void tearDown() throws Exception { clearSelectedAndRecordingTracks(); waitForIdle(); super.tearDown(); } public void testInitialization_mainAction() { // Make sure we can start MyTracks and the activity doesn't start recording. assertInitialized(); // Check if not recording. assertFalse(isRecording()); assertEquals(-1, getRecordingTrackId()); long selectedTrackId = getSharedPreferences().getLong( getActivity().getString(R.string.selected_track_key), -1); assertEquals(selectedTrackId, getActivity().getSelectedTrackId()); } public void testInitialization_viewActionWithNoData() { // Simulate start with ACTION_VIEW intent. Intent startIntent = new Intent(); startIntent.setAction(Intent.ACTION_VIEW); setActivityIntent(startIntent); assertInitialized(); // Check if not recording. assertFalse(isRecording()); assertEquals(-1, getRecordingTrackId()); long selectedTrackId = getSharedPreferences().getLong( getActivity().getString(R.string.selected_track_key), -1); assertEquals(selectedTrackId, getActivity().getSelectedTrackId()); } public void testInitialization_viewActionWithValidData() throws Exception { // Simulate start with ACTION_VIEW intent. Intent startIntent = new Intent(); startIntent.setAction(Intent.ACTION_VIEW); Uri uri = Uri.fromFile(File.createTempFile("valid", ".gpx", getActivity().getFilesDir())); // TODO: Add a valid GPX. startIntent.setData(uri); setActivityIntent(startIntent); assertInitialized(); // Check if not recording. assertFalse(isRecording()); assertEquals(-1, getRecordingTrackId()); long selectedTrackId = getSharedPreferences().getLong( getActivity().getString(R.string.selected_track_key), -1); assertEquals(selectedTrackId, getActivity().getSelectedTrackId()); // TODO: Finish this test. } public void testInitialization_viewActionWithInvalidData() throws Exception { // Simulate start with ACTION_VIEW intent. Intent startIntent = new Intent(); startIntent.setAction(Intent.ACTION_VIEW); Uri uri = Uri.fromFile(File.createTempFile("invalid", ".gpx", getActivity().getFilesDir())); startIntent.setData(uri); setActivityIntent(startIntent); assertInitialized(); // Check if not recording. assertFalse(isRecording()); assertEquals(-1, getRecordingTrackId()); long selectedTrackId = getSharedPreferences().getLong( getActivity().getString(R.string.selected_track_key), -1); assertEquals(selectedTrackId, getActivity().getSelectedTrackId()); // TODO: Finish this test. } public void testRecording_startAndStop() throws Exception { assertInitialized(); // Check if not recording. clearSelectedAndRecordingTracks(); waitForIdle(); assertFalse(isRecording()); assertEquals(-1, getRecordingTrackId()); long selectedTrackId = getSharedPreferences().getLong( getActivity().getString(R.string.selected_track_key), -1); assertEquals(selectedTrackId, getActivity().getSelectedTrackId()); // Start a new track. getActivity().startRecording(); serviceConnection.bindIfRunning(); long recordingTrackId = awaitRecordingStatus(5000, true); assertTrue(recordingTrackId >= 0); // Wait until we are done and make sure that selectedTrack = recordingTrack. waitForIdle(); assertEquals(recordingTrackId, getSharedPreferences().getLong( getActivity().getString(R.string.recording_track_key), -1)); selectedTrackId = getSharedPreferences().getLong( getActivity().getString(R.string.selected_track_key), -1); assertEquals(recordingTrackId, selectedTrackId); assertEquals(selectedTrackId, getActivity().getSelectedTrackId()); // Watch for MyTracksDetails activity. ActivityMonitor monitor = getInstrumentation().addMonitor( TrackDetails.class.getName(), null, false); // Now, stop the track and make sure that it is still selected, but // no longer recording. getActivity().stopRecording(); // Check if we got back MyTracksDetails activity. Activity activity = getInstrumentation().waitForMonitor(monitor); assertTrue(activity instanceof TrackDetails); // TODO: Update track name and other properties and test if they were // properly saved. // Simulate a click on Save button. final Button save = (Button) activity.findViewById(R.id.trackdetails_save); getActivity().runOnUiThread(new Runnable() { @Override public void run() { save.performClick(); } }); // Check the remaining properties. recordingTrackId = awaitRecordingStatus(5000, false); assertEquals(-1, recordingTrackId); assertEquals(recordingTrackId, getRecordingTrackId()); assertEquals(recordingTrackId, getSharedPreferences().getLong( getActivity().getString(R.string.recording_track_key), -1)); // Make sure this is the same track as the last recording track ID. assertEquals(selectedTrackId, getActivity().getSelectedTrackId()); } private void assertInitialized() { assertNotNull(getActivity()); serviceConnection = new TrackRecordingServiceConnection(getActivity(), null); } /** * Waits until the UI thread becomes idle. */ private void waitForIdle() throws InterruptedException { // Note: We can't use getInstrumentation().waitForIdleSync() here. final Object semaphore = new Object(); synchronized (semaphore) { final AtomicBoolean isIdle = new AtomicBoolean(); getInstrumentation().waitForIdle(new Runnable() { @Override public void run() { synchronized (semaphore) { isIdle.set(true); semaphore.notify(); } } }); while (!isIdle.get()) { semaphore.wait(); } } } /** * Clears {selected,recording}TrackId in the {@link #getSharedPreferences()}. */ private void clearSelectedAndRecordingTracks() { Editor editor = getSharedPreferences().edit(); editor.putLong(getActivity().getString(R.string.selected_track_key), -1); editor.putLong(getActivity().getString(R.string.recording_track_key), -1); editor.clear(); editor.apply(); } /** * Waits until the recording state changes to the given status. * * @param timeout the maximum time to wait, in milliseconds. * @param isRecording the final status to await. * @return the recording track ID. */ private long awaitRecordingStatus(long timeout, boolean isRecording) throws TimeoutException, InterruptedException { long startTime = System.nanoTime(); while (isRecording() != isRecording) { if (System.nanoTime() - startTime > timeout * 1000000) { throw new TimeoutException("Timeout while waiting for recording!"); } Thread.sleep(20); } waitForIdle(); assertEquals(isRecording, isRecording()); return getRecordingTrackId(); } private long getRecordingTrackId() { return getSharedPreferences().getLong(getActivity().getString(R.string.recording_track_key), -1); } private SharedPreferences getSharedPreferences() { if (sharedPreferences == null) { sharedPreferences = getActivity().getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); } return sharedPreferences; } private boolean isRecording() { return ServiceUtils.isRecording(getActivity(), serviceConnection.getServiceIfBound(), getSharedPreferences()); } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.testing; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory; import android.content.Context; /** * A fake factory for {@link MyTracksProviderUtils} which always returns a * predefined instance. * * @author Rodrigo Damazio */ public class TestingProviderUtilsFactory extends Factory { private MyTracksProviderUtils instance; public TestingProviderUtilsFactory(MyTracksProviderUtils instance) { this.instance = instance; } @Override protected MyTracksProviderUtils newForContext(Context context) { return instance; } public static Factory installWithInstance(MyTracksProviderUtils instance) { Factory oldFactory = Factory.getInstance(); Factory factory = new TestingProviderUtilsFactory(instance); MyTracksProviderUtils.Factory.overrideInstance(factory); return oldFactory; } public static void restoreOldFactory(Factory factory) { MyTracksProviderUtils.Factory.overrideInstance(factory); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks; import com.google.android.apps.mytracks.ChartValueSeries.ZoomSettings; import com.google.android.maps.mytracks.R; import android.graphics.Paint.Style; import android.test.AndroidTestCase; /** * @author Sandor Dornbush */ public class ChartValueSeriesTest extends AndroidTestCase { private ChartValueSeries series; @Override protected void setUp() throws Exception { series = new ChartValueSeries(getContext(), R.color.elevation_fill, R.color.elevation_border, new ZoomSettings(5, new int[] {100}), R.string.stat_elevation); } public void testInitialConditions() { assertEquals(0, series.getInterval()); assertEquals(1, series.getMaxLabelLength()); assertEquals(0, series.getMin()); assertEquals(0, series.getMax()); assertEquals(0.0, series.getSpread()); assertEquals(Style.STROKE, series.getPaint().getStyle()); assertEquals(getContext().getString(R.string.stat_elevation), series.getTitle()); assertTrue(series.isEnabled()); } public void testEnabled() { series.setEnabled(false); assertFalse(series.isEnabled()); } public void testSmallUpdates() { series.update(0); series.update(10); series.updateDimension(); assertEquals(100, series.getInterval()); assertEquals(3, series.getMaxLabelLength()); assertEquals(0, series.getMin()); assertEquals(100, series.getMax()); assertEquals(100.0, series.getSpread()); } public void testBigUpdates() { series.update(0); series.update(901); series.updateDimension(); assertEquals(100, series.getInterval()); assertEquals(5, series.getMaxLabelLength()); assertEquals(0, series.getMin()); assertEquals(1000, series.getMax()); assertEquals(1000.0, series.getSpread()); } public void testNotZeroBasedUpdates() { series.update(500); series.update(1401); series.updateDimension(); assertEquals(100, series.getInterval()); assertEquals(5, series.getMaxLabelLength()); assertEquals(500, series.getMin()); assertEquals(1500, series.getMax()); assertEquals(1000.0, series.getSpread()); } public void testZoomSettings_invalidArgs() { try { new ZoomSettings(0, new int[] {10, 50, 100}); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // OK. } try { new ZoomSettings(1, null); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // OK. } try { new ZoomSettings(1, new int[] {}); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // OK. } try { new ZoomSettings(1, new int[] {1, 3, 2}); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // OK. } } public void testZoomSettings_minAligned() { ZoomSettings settings = new ZoomSettings(5, new int[] {10, 50, 100}); assertEquals(10, settings.calculateInterval(0, 15)); assertEquals(10, settings.calculateInterval(0, 50)); assertEquals(50, settings.calculateInterval(0, 111)); assertEquals(50, settings.calculateInterval(0, 250)); assertEquals(100, settings.calculateInterval(0, 251)); assertEquals(100, settings.calculateInterval(0, 10000)); } public void testZoomSettings_minNotAligned() { ZoomSettings settings = new ZoomSettings(5, new int[] {10, 50, 100}); assertEquals(50, settings.calculateInterval(5, 55)); assertEquals(10, settings.calculateInterval(10, 60)); assertEquals(50, settings.calculateInterval(7, 250)); assertEquals(100, settings.calculateInterval(7, 257)); assertEquals(100, settings.calculateInterval(11, 10000)); // A regression test. settings = new ZoomSettings(5, new int[] {5, 10, 20}); assertEquals(10, settings.calculateInterval(-37.14, -11.89)); } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks; import com.google.android.maps.MapView; import com.google.android.maps.Projection; import android.content.Context; import android.graphics.Rect; /** * Elements for Tests for the MyTracks map overlay. * * @author Bartlomiej Niechwiej * @author Vangelis S. * * A mock version of {@code MapOverlay} that does not use * {@class MapView}. */ public class MockMyTracksOverlay extends MapOverlay { private Projection mockProjection; public MockMyTracksOverlay(Context context) { super(context); mockProjection = new MockProjection(); } @Override public Projection getMapProjection(MapView mapView) { return mockProjection; } @Override public Rect getMapViewRect(MapView mapView) { return new Rect(0, 0, 100, 100); } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.android.apps.mytracks.util; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.stats.TripStatistics; import java.util.Vector; import junit.framework.TestCase; /** * Tests for the Chart URL generator. * * @author Sandor Dornbush */ public class ChartURLGeneratorTest extends TestCase { public void testgetChartUrl() { Vector<Double> distances = new Vector<Double>(); Vector<Double> elevations = new Vector<Double>(); Track t = new Track(); TripStatistics stats = t.getStatistics(); stats.setMinElevation(0); stats.setMaxElevation(2000); stats.setTotalDistance(100); distances.add(0.0); elevations.add(10.0); distances.add(10.0); elevations.add(300.0); distances.add(20.0); elevations.add(800.0); distances.add(50.0); elevations.add(1900.0); distances.add(75.0); elevations.add(1200.0); distances.add(90.0); elevations.add(700.0); distances.add(100.0); elevations.add(70.0); String chart = ChartURLGenerator.getChartUrl(distances, elevations, t, "Title", true); assertEquals( "http://chart.apis.google.com/chart?&chs=600x350&cht=lxy&" + "chtt=Title&chxt=x,y&chxr=0,0,0,0|1,0.0,2100.0,300&chco=009A00&" + "chm=B,00AA00,0,0,0&chg=100000,14.285714285714286,1,0&" + "chd=e:AAGZMzf.v.5l..,ATJJYY55kkVVCI", chart); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.util; import junit.framework.TestCase; /** * Tests the API feature detection code in {@link ApiFeatures}. * This test requires Froyo+ to run. * * @author Rodrigo Damazio */ public class ApiFeaturesTest extends TestCase { private TestableApiFeatures features; private class TestableApiFeatures extends ApiFeatures { private int apiLevel; public void setApiLevel(int apiLevel) { this.apiLevel = apiLevel; } @Override protected int getApiLevel() { return apiLevel; } } @Override protected void setUp() throws Exception { super.setUp(); features = new TestableApiFeatures(); } public void testHasTextToSpeech() { features.setApiLevel(3); assertFalse(features.hasTextToSpeech()); for (int i = 4; i <= 8; i++) { features.setApiLevel(i); assertTrue(features.hasTextToSpeech()); } } public void testGetApiAdapter() { assertNotNull(features.getApiAdapter()); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.util; import com.google.android.apps.mytracks.Constants; import android.os.Environment; import java.io.File; import java.util.HashSet; import java.util.Set; import junit.framework.TestCase; /** * Tests for {@link FileUtils}. * * @author Rodrigo Damazio */ public class FileUtilsTest extends TestCase { private static final String ORIGINAL_NAME = "Swim\10ming-^across: the/ pacific (ocean)."; private static final String SANITIZED_NAME = "Swimming-across the pacific (ocean)."; private FileUtils fileUtils; private Set<String> existingFiles; @Override protected void setUp() throws Exception { super.setUp(); existingFiles = new HashSet<String>(); fileUtils = new FileUtils() { @Override protected boolean fileExists(File directory, String fullName) { return existingFiles.contains(fullName); } }; } public void testBuildExternalDirectoryPath() { String expectedName = Environment.getExternalStorageDirectory() + File.separator + Constants.SDCARD_TOP_DIR + File.separator + "a" + File.separator + "b" + File.separator + "c"; String dirName = fileUtils.buildExternalDirectoryPath("a", "b", "c"); assertEquals(expectedName, dirName); } public void testSanitizeName() { assertEquals(SANITIZED_NAME, fileUtils.sanitizeName(ORIGINAL_NAME)); } public void testBuildUniqueFileName_someExist() { existingFiles = new HashSet<String>(); existingFiles.add("Filename.ext"); existingFiles.add("Filename (1).ext"); existingFiles.add("Filename (2).ext"); existingFiles.add("Filename (3).ext"); existingFiles.add("Filename (4).ext"); String filename = fileUtils.buildUniqueFileName(null, "Filename", "ext"); assertEquals("Filename (5).ext", filename); } public void testBuildUniqueFileName_oneExists() { existingFiles.add("Filename.ext"); String filename = fileUtils.buildUniqueFileName(null, "Filename", "ext"); assertEquals("Filename (1).ext", filename); } public void testBuildUniqueFileName_noneExists() { String filename = fileUtils.buildUniqueFileName(null, "Filename", "ext"); assertEquals("Filename.ext", filename); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.util; import java.util.GregorianCalendar; import java.util.TimeZone; import junit.framework.TestCase; /** * Tests for {@link StringUtils}. * * @author Rodrigo Damazio */ public class StringUtilsTest extends TestCase { public void testParseXmlDateTime() { assertParseXmlDateTime("2010-05-04T03:02:01", 2010, 5, 4, 3, 2, 1, 0); } public void testParseXmlDateTime_fractional() { assertParseXmlDateTime("2010-05-04T03:02:01.3", 2010, 5, 4, 3, 2, 1, 300); assertParseXmlDateTime("2010-05-04T03:02:01.35", 2010, 5, 4, 3, 2, 1, 350); assertParseXmlDateTime("2010-05-04T03:02:01.352", 2010, 5, 4, 3, 2, 1, 352); assertParseXmlDateTime("2010-05-04T03:02:01.3525", 2010, 5, 4, 3, 2, 1, 352); } public void testParseXmlDateTime_timezone() { assertParseXmlDateTime("2010-05-04T03:02:01Z", 2010, 5, 4, 3, 2, 1, 0); assertParseXmlDateTime("2010-05-04T03:02:01+00:00", 2010, 5, 4, 3, 2, 1, 0); assertParseXmlDateTime("2010-05-04T03:02:01-00:00", 2010, 5, 4, 3, 2, 1, 0); assertParseXmlDateTime("2010-05-04T03:02:01+01:00", 2010, 5, 4, 2, 2, 1, 0); assertParseXmlDateTime("2010-05-04T03:02:01+10:30", 2010, 5, 3, 16, 32, 1, 0); assertParseXmlDateTime("2010-05-04T03:02:01-09:30", 2010, 5, 4, 12, 32, 1, 0); assertParseXmlDateTime("2010-05-04T03:02:01-05:00", 2010, 5, 4, 8, 2, 1, 0); } public void testParseXmlDateTime_fractionalAndTimezone() { assertParseXmlDateTime("2010-05-04T03:02:01.352Z", 2010, 5, 4, 3, 2, 1, 352); assertParseXmlDateTime("2010-05-04T03:02:01.47+00:00", 2010, 5, 4, 3, 2, 1, 470); assertParseXmlDateTime("2010-05-04T03:02:01.5791+03:00", 2010, 5, 4, 0, 2, 1, 579); assertParseXmlDateTime("2010-05-04T03:02:01.8-05:30", 2010, 5, 4, 8, 32, 1, 800); } private void assertParseXmlDateTime(String dateTime, int year, int month, int day, int hour, int min, int second, int millis) { long timestamp = StringUtils.parseXmlDateTime(dateTime); GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.set(year, month - 1, day, hour, min, second); calendar.set(GregorianCalendar.MILLISECOND, millis); assertEquals(calendar.getTimeInMillis(), timestamp); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.util; import junit.framework.TestCase; /** * A unit test for {@link ChartsExtendedEncoder}. * * @author Bartlomiej Niechwiej */ public class ChartsExtendedEncoderTest extends TestCase { public void testGetEncodedValue_validArguments() { // Valid arguments. assertEquals("AK", ChartsExtendedEncoder.getEncodedValue(10)); assertEquals("JO", ChartsExtendedEncoder.getEncodedValue(590)); assertEquals("AA", ChartsExtendedEncoder.getEncodedValue(0)); // 64^2 = 4096. assertEquals("..", ChartsExtendedEncoder.getEncodedValue(4095)); } public void testGetEncodedValue_invalidArguments() { // Invalid arguments. assertEquals("__", ChartsExtendedEncoder.getEncodedValue(4096)); assertEquals("__", ChartsExtendedEncoder.getEncodedValue(1234564096)); assertEquals("__", ChartsExtendedEncoder.getEncodedValue(-10)); assertEquals("__", ChartsExtendedEncoder.getEncodedValue(-12324435)); } public void testGetSeparator() { assertEquals(",", ChartsExtendedEncoder.getSeparator()); } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.io.sendtogoogle; import com.google.android.apps.mytracks.MyTracks; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.content.DialogInterface; import android.test.ActivityInstrumentationTestCase2; import android.view.View; import android.widget.ListAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.List; /** * Tests {@link ResultDialogFactory}. * * @author Matthew Simmons */ public class ResultDialogFactoryTest extends ActivityInstrumentationTestCase2<MyTracks> { public ResultDialogFactoryTest() { super(MyTracks.class); } private List<SendResult> makeResults(SendResult... results) { List<SendResult> resultsList = new ArrayList<SendResult>(); for (SendResult result : results) { resultsList.add(result); } return resultsList; } private DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) {} }; private MyTracks myTracks; protected void setUp() throws Exception { super.setUp(); myTracks = getActivity(); }; public void testSuccess_noShare() { List<SendResult> results = makeResults(new SendResult(SendType.MYMAPS, true), new SendResult(SendType.DOCS, true)); AlertDialog dialog = ResultDialogFactory.makeDialog( myTracks, results, clickListener, null, null); dialog.show(); ListView listView = (ListView) dialog.findViewById(R.id.send_to_google_result_list); ListAdapter listAdapter = listView.getAdapter(); assertEquals(2, listAdapter.getCount()); assertEquals(SendType.MYMAPS, ((SendResult) listAdapter.getItem(0)).getType()); assertEquals(SendType.DOCS, ((SendResult) listAdapter.getItem(1)).getType()); // Checking the return code of Dialog#getButton doesn't appear to be // sufficient, as a Button will be returned even if it doesn't appear in // the rendered dialog. assertEquals(View.VISIBLE, dialog.getButton(AlertDialog.BUTTON_POSITIVE).getVisibility()); assertEquals(View.GONE, dialog.getButton(AlertDialog.BUTTON_NEUTRAL).getVisibility()); assertEquals(View.VISIBLE, dialog.findViewById(R.id.send_to_google_result_comment).getVisibility()); assertEquals(View.GONE, dialog.findViewById(R.id.send_to_google_result_error).getVisibility()); // TODO: Test correct listener invocation. Neither TouchUtils#clickView // nor Button#performClick appear to cause listener invocation. This // might be Android bug // http://code.google.com/p/android/issues/detail?id=6564 } public void testSuccess_share() { List<SendResult> results = makeResults( new SendResult(SendType.MYMAPS, true), new SendResult(SendType.DOCS, true)); AlertDialog dialog = ResultDialogFactory.makeDialog( myTracks, results, clickListener, clickListener, null); dialog.show(); assertEquals(View.VISIBLE, dialog.getButton(AlertDialog.BUTTON_POSITIVE).getVisibility()); assertEquals(View.VISIBLE, dialog.getButton(AlertDialog.BUTTON_NEGATIVE).getVisibility()); } public void testFailure_noShare() { List<SendResult> results = makeResults(new SendResult(SendType.MYMAPS, true), new SendResult(SendType.DOCS, false)); AlertDialog dialog = ResultDialogFactory.makeDialog( myTracks, results, clickListener, null, null); dialog.show(); assertEquals(View.GONE, dialog.findViewById(R.id.send_to_google_result_comment).getVisibility()); assertEquals(View.VISIBLE, dialog.findViewById(R.id.send_to_google_result_error).getVisibility()); } public void testFailure_share() { List<SendResult> results = makeResults(new SendResult(SendType.MYMAPS, true), new SendResult(SendType.DOCS, false)); AlertDialog dialog = ResultDialogFactory.makeDialog( myTracks, results, clickListener, clickListener, null); dialog.show(); assertEquals(View.VISIBLE, dialog.getButton(AlertDialog.BUTTON_POSITIVE).getVisibility()); assertEquals(View.VISIBLE, dialog.getButton(AlertDialog.BUTTON_NEGATIVE).getVisibility()); } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.io.sendtogoogle; import com.google.android.maps.mytracks.R; import android.content.Context; import android.test.AndroidTestCase; import android.view.LayoutInflater; import android.view.View; import java.util.ArrayList; import java.util.List; /** * Tests {@link ResultListAdapter}. * * @author Matthew Simmons */ public class ResultListAdapterTest extends AndroidTestCase { private static class TestResultListAdapter extends ResultListAdapter { public View contentView; public int drawableId; public int nameId; public int urlId; public TestResultListAdapter(Context context, List<SendResult> results) { super(context, 0, results); } @Override protected void setImage(View content, int drawableId) { saveContentView(content); this.drawableId = drawableId; } @Override protected void setName(View content, int nameId) { saveContentView(content); this.nameId = nameId; } @Override protected void setUrl(View content, int urlId) { saveContentView(content); this.urlId = urlId; } @SuppressWarnings("hiding") private void saveContentView(View contentView) { if (this.contentView == null) { this.contentView = contentView; } else { AndroidTestCase.assertEquals(this.contentView, contentView); } } } private final SendType sendType = SendType.MYMAPS; private View inflateContentView(int viewId) { LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); return layoutInflater.inflate(viewId, null); } private List<SendResult> makeResult(SendType type, boolean success) { List<SendResult> results = new ArrayList<SendResult>(); results.add(new SendResult(type, success)); return results; } public void testSuccess_createsNewView() { TestResultListAdapter adapter = new TestResultListAdapter(getContext(), makeResult(sendType, true)); adapter.getView(0, null, null); assertEquals(R.drawable.success, adapter.drawableId); assertEquals(sendType.getServiceName(), adapter.nameId); assertEquals(sendType.getServiceUrl(), adapter.urlId); } public void testSuccess_reusesView() { View contentView = inflateContentView(R.layout.send_to_google_result_list_item); TestResultListAdapter adapter = new TestResultListAdapter(getContext(), makeResult(sendType, true)); adapter.getView(0, contentView, null); assertEquals(contentView, adapter.contentView); assertEquals(R.drawable.success, adapter.drawableId); assertEquals(sendType.getServiceName(), adapter.nameId); assertEquals(sendType.getServiceUrl(), adapter.urlId); } public void testFailure() { TestResultListAdapter adapter = new TestResultListAdapter(getContext(), makeResult(sendType, false)); adapter.getView(0, null, null); assertEquals(R.drawable.failure, adapter.drawableId); assertEquals(sendType.getServiceName(), adapter.nameId); assertEquals(sendType.getServiceUrl(), adapter.urlId); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.io.docs; import junit.framework.TestCase; /** * This class tests {@link DocsTagBuilder} * * @author Matthew Simmons */ public class DocsTagBuilderTest extends TestCase { public void testAppend() { assertEquals("<gsx:tag><![CDATA[value]]></gsx:tag>", new DocsTagBuilder(false).append("tag", "value").build()); } public void testMultiAppend() { String actual = new DocsTagBuilder(false) .append("tag1", "value1") .append("tag2", "value2") .build(); assertEquals("<gsx:tag1><![CDATA[value1]]></gsx:tag1>" + "<gsx:tag2><![CDATA[value2]]></gsx:tag2>", actual); } public void testAppendLargeUnits_imperial() { assertEquals("<gsx:tag><![CDATA[62.14]]></gsx:tag>", new DocsTagBuilder(false).appendLargeUnits("tag", 100.0).build()); } public void testAppendLargeUnits_metric() { assertEquals("<gsx:tag><![CDATA[100.00]]></gsx:tag>", new DocsTagBuilder(true).appendLargeUnits("tag", 100.0).build()); } public void testAppendSmallUnits_imperial() { assertEquals("<gsx:tag><![CDATA[328]]></gsx:tag>", new DocsTagBuilder(false).appendSmallUnits("tag", 100.0).build()); } public void testAppendSmallUnits_metric() { assertEquals("<gsx:tag><![CDATA[100]]></gsx:tag>", new DocsTagBuilder(true).appendSmallUnits("tag", 100.0).build()); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.io.docs; import com.google.android.apps.mytracks.io.gdata.GDataWrapper; import com.google.wireless.gdata.client.GDataServiceClient; import android.content.Context; import android.test.mock.MockContext; import junit.framework.TestCase; import java.io.IOException; /** * Tests for {@link DocsHelper}, with the exception of * {@link DocsHelper#addTrackRow}, which is in * {@link DocsHelper_AddTrackRowTest}. * * @author Matthew Simmons */ public class DocsHelperTest extends TestCase { private Context mockContext = new MockContext(); // TODO(simmonmt): Use AndroidMock to mock this class. We do it the hard // way because use of AndroidMock to mock GDataWrapper triggers a compile // error in an unrelated file. Specifically, it causes a NoClassDefFound // exception for com.google.wireless.gdata2.client.AuthenticationException, // (wrongly) attributed to the first source file in the project. Using the // @UsesMocks(GDataWrapper.class) annotation is enough -- you don't have to // touch AndroidMock at all to get this failure. // The bug is filed with Android Mock as // http://code.google.com/p/android-mock/issues/detail?id=3 private class MockGDataWrapper extends GDataWrapper<GDataServiceClient> { private final boolean returnValue; MockGDataWrapper(boolean returnValue) { this.returnValue = returnValue; } @Override public boolean runQuery(QueryFunction<GDataServiceClient> queryFunction) { return returnValue; } } public void testCreateSpreadsheet_noException() throws Exception { // Our mock GDataWrapper isn't able to affect the return value from // DocsHelper#createSpreadsheet. As such, we're only able to simulate the // case where there weren't any GData errors, but not spreadsheet ID was // actually returned. createSpreadsheet is defined to return null in that // situation. assertNull(new DocsHelper().createSpreadsheet( mockContext, new MockGDataWrapper(true), "sheetName")); } public void testCreateSpreadsheet_exception() throws Exception { try { new DocsHelper().createSpreadsheet( mockContext, new MockGDataWrapper(false), "sheetName"); fail(); } catch (IOException expected) {} } public void testRequestSpreadsheetId_noException() throws Exception { assertNull(new DocsHelper().requestSpreadsheetId( new MockGDataWrapper(true), "sheetName")); } public void testRequestSpreadsheetId_exception() throws Exception { try { new DocsHelper().requestSpreadsheetId(new MockGDataWrapper(false), "sheetName"); fail(); } catch (IOException expected) {} } public void testGetWorksheetId_noException() throws Exception { assertNull(new DocsHelper().getWorksheetId(new MockGDataWrapper(true), "sheetId")); } public void testGetWorksheetId_exception() throws Exception { try { new DocsHelper().getWorksheetId(new MockGDataWrapper(false), "sheetId"); fail(); } catch (IOException expected) {} } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.io.docs; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.io.AuthManager; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.maps.mytracks.R; import com.google.android.testing.mocking.AndroidMock; import com.google.android.testing.mocking.UsesMocks; import android.content.Context; import android.content.res.Resources; import android.test.mock.MockContext; import android.test.mock.MockResources; import java.io.IOException; import java.text.DateFormat; import java.util.Date; import junit.framework.TestCase; /** * Tests for {@link DocsHelper#addTrackRow} * * @author Matthew Simmons */ public class DocsHelper_AddTrackRowTest extends TestCase { private static final long TIME = 1288721514000L; private static final DateFormat DATE_FORMAT = DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT); private static class StringWritingDocsHelper extends DocsHelper { String writtenSheetUri = null; String writtenData = null; @Override protected void writeRowData(AuthManager trixAuth, String worksheetUri, String postText) { writtenSheetUri = worksheetUri; writtenData = postText; } } public void testAddTrackRow_imperial() throws Exception { StringWritingDocsHelper docsHelper = new StringWritingDocsHelper(); addTrackRow(docsHelper, false); String expectedData = "<entry xmlns='http://www.w3.org/2005/Atom' " + "xmlns:gsx='http://schemas.google.com/spreadsheets/2006/extended'>" + "<gsx:name><![CDATA[trackName]]></gsx:name>" + "<gsx:description><![CDATA[trackDescription]]></gsx:description>" + "<gsx:date><![CDATA[" + DATE_FORMAT.format(new Date(TIME)) + "]]></gsx:date>" + "<gsx:totaltime><![CDATA[0:00:05]]></gsx:totaltime>" + "<gsx:movingtime><![CDATA[0:00:04]]></gsx:movingtime>" + "<gsx:distance><![CDATA[12.43]]></gsx:distance>" + "<gsx:distanceunit><![CDATA[mile]]></gsx:distanceunit>" + "<gsx:averagespeed><![CDATA[8,947.75]]></gsx:averagespeed>" + "<gsx:averagemovingspeed><![CDATA[11,184.68]]>" + "</gsx:averagemovingspeed>" + "<gsx:maxspeed><![CDATA[3,355.40]]></gsx:maxspeed>" + "<gsx:speedunit><![CDATA[mph]]></gsx:speedunit>" + "<gsx:elevationgain><![CDATA[19,685]]></gsx:elevationgain>" + "<gsx:minelevation><![CDATA[-1,640]]></gsx:minelevation>" + "<gsx:maxelevation><![CDATA[1,804]]></gsx:maxelevation>" + "<gsx:elevationunit><![CDATA[feet]]></gsx:elevationunit>" + "<gsx:map>" + "<![CDATA[https://maps.google.com/maps/ms?msa=0&msid=trackMapId]]>" + "</gsx:map>" + "</entry>"; assertEquals( "https://spreadsheets.google.com/feeds/list/ssid/wsid/private/full", docsHelper.writtenSheetUri); assertEquals(expectedData, docsHelper.writtenData); } public void testAddTrackRow_metric() throws Exception { StringWritingDocsHelper docsHelper = new StringWritingDocsHelper(); addTrackRow(docsHelper, true); // The imperial test verifies that the tags come out in the proper order, // and with the proper names. We need only verify that the labels are // correct, and that at least one of the unit-dependent value tags is // correct. assertTrue(docsHelper.writtenData.contains( "<gsx:distanceunit><![CDATA[km]]></gsx:distanceunit>")); assertTrue(docsHelper.writtenData.contains( "<gsx:speedunit><![CDATA[kph]]></gsx:speedunit>")); assertTrue(docsHelper.writtenData.contains( "<gsx:elevationunit><![CDATA[meter]]></gsx:elevationunit>")); assertTrue(docsHelper.writtenData.contains( "<gsx:distance><![CDATA[20.00]]></gsx:distance>")); } /** Adds a row to the spreadsheet, using the provided helper. */ @UsesMocks({AuthManager.class, MockResources.class, Track.class}) private void addTrackRow(DocsHelper docsHelper, boolean useMetric) throws IOException { final Resources mockResources = AndroidMock.createMock(MockResources.class); if (useMetric) { AndroidMock.expect(mockResources.getString(R.string.unit_kilometer)) .andReturn("km"); AndroidMock.expect(mockResources.getString(R.string.unit_kilometer_per_hour)) .andReturn("kph"); AndroidMock.expect(mockResources.getString(R.string.unit_meter)) .andReturn("meter"); } else { AndroidMock.expect(mockResources.getString(R.string.unit_mile)) .andReturn("mile"); AndroidMock.expect(mockResources.getString(R.string.unit_mile_per_hour)) .andReturn("mph"); AndroidMock.expect(mockResources.getString(R.string.unit_feet)) .andReturn("feet"); } AndroidMock.replay(mockResources); Context mockContext = new MockContext() { @Override public Resources getResources() { return mockResources; } }; AuthManager mockAuthManager = AndroidMock.createMock(AuthManager.class); AndroidMock.replay(mockAuthManager); TripStatistics stats = new TripStatistics(); stats.setStartTime(TIME); stats.setTotalTime(5000); stats.setMovingTime(4000); stats.setTotalDistance(20000); stats.setMaxSpeed(1500); stats.setTotalElevationGain(6000); stats.setMinElevation(-500); stats.setMaxElevation(550); Track track = new Track(); track.setName("trackName"); track.setDescription("trackDescription"); track.setMapId("trackMapId"); track.setStatistics(stats); docsHelper.addTrackRow(mockContext, mockAuthManager, "ssid", "wsid", track, useMetric); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.io.backup; import com.google.android.apps.mytracks.content.ContentTypeIds; import android.content.ContentValues; import android.net.Uri; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import junit.framework.TestCase; /** * Tests for {@link DatabaseImporter}. * * @author Rodrigo Damazio */ public class DatabaseImporterTest extends TestCase { private static final Uri DESTINATION_URI = Uri.parse("http://www.google.com/"); private static final int TEST_BULK_SIZE = 10; private ArrayList<ContentValues> insertedValues; private class TestableDatabaseImporter extends DatabaseImporter { public TestableDatabaseImporter(boolean readNullFields) { super(DESTINATION_URI, null, readNullFields, TEST_BULK_SIZE); } @Override protected void doBulkInsert(ContentValues[] values) { insertedValues.ensureCapacity(insertedValues.size() + values.length); // We need to make a copy of the values since the objects are re-used for (ContentValues contentValues : values) { insertedValues.add(new ContentValues(contentValues)); } } } @Override protected void setUp() throws Exception { super.setUp(); insertedValues = new ArrayList<ContentValues>(); } public void testImportAllRows() throws Exception { testImportAllRows(false); } public void testImportAllRows_readNullFields() throws Exception { testImportAllRows(true); } private void testImportAllRows(boolean readNullFields) throws Exception { // Create a fake data stream to be read ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outputStream); writeFullHeader(writer); // Add the number of rows writer.writeInt(2); // Add a row with all fields present writer.writeLong(0x7F); writer.writeInt(42); writer.writeBoolean(true); writer.writeUTF("lolcat"); writer.writeFloat(3.1415f); writer.writeDouble(2.72); writer.writeLong(123456789L); writer.writeInt(4); writer.writeBytes("blob"); // Add a row with some missing fields writer.writeLong(0x15); writer.writeInt(42); if (readNullFields) writer.writeBoolean(false); writer.writeUTF("lolcat"); if (readNullFields) writer.writeFloat(0.0f); writer.writeDouble(2.72); if (readNullFields) writer.writeLong(0L); if (readNullFields) writer.writeInt(0); // empty blob writer.flush(); // Do the importing DatabaseImporter importer = new TestableDatabaseImporter(readNullFields); byte[] dataBytes = outputStream.toByteArray(); importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes))); assertEquals(2, insertedValues.size()); // Verify the first row ContentValues value = insertedValues.get(0); assertEquals(value.toString(), 7, value.size()); assertValue(42, "col1", value); assertValue(true, "col2", value); assertValue("lolcat", "col3", value); assertValue(3.1415f, "col4", value); assertValue(2.72, "col5", value); assertValue(123456789L, "col6", value); assertBlobValue("blob", "col7", value); // Verify the second row value = insertedValues.get(1); assertEquals(value.toString(), 3, value.size()); assertValue(42, "col1", value); assertValue("lolcat", "col3", value); assertValue(2.72, "col5", value); } public void testImportAllRows_noRows() throws Exception { // Create a fake data stream to be read ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outputStream); writeFullHeader(writer); // Add the number of rows writer.writeInt(0); writer.flush(); // Do the importing DatabaseImporter importer = new TestableDatabaseImporter(false); byte[] dataBytes = outputStream.toByteArray(); importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes))); assertTrue(insertedValues.isEmpty()); } public void testImportAllRows_emptyRows() throws Exception { testImportAllRowsWithEmptyRows(false); } public void testImportAllRows_emptyRowsWithNulls() throws Exception { testImportAllRowsWithEmptyRows(true); } private void testImportAllRowsWithEmptyRows(boolean readNullFields) throws Exception { // Create a fake data stream to be read ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outputStream); writeFullHeader(writer); // Add the number of rows writer.writeInt(3); // Add 2 rows with no fields for (int i = 0; i < 2; i++) { writer.writeLong(0); if (readNullFields) { writer.writeInt(0); writer.writeBoolean(false); writer.writeUTF(""); writer.writeFloat(0.0f); writer.writeDouble(0.0); writer.writeLong(0L); writer.writeInt(0); // empty blob } } // Add a row with some missing fields writer.writeLong(0x15); writer.writeInt(42); if (readNullFields) writer.writeBoolean(false); writer.writeUTF("lolcat"); if (readNullFields) writer.writeFloat(0.0f); writer.writeDouble(2.72); if (readNullFields) writer.writeLong(0L); if (readNullFields) writer.writeInt(0); // empty blob writer.flush(); // Do the importing DatabaseImporter importer = new TestableDatabaseImporter(readNullFields); byte[] dataBytes = outputStream.toByteArray(); importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes))); assertEquals(insertedValues.toString(), 3, insertedValues.size()); ContentValues value = insertedValues.get(0); assertEquals(value.toString(), 0, value.size()); value = insertedValues.get(1); assertEquals(value.toString(), 0, value.size()); // Verify the third row (only one with values) value = insertedValues.get(2); assertEquals(value.toString(), 3, value.size()); assertFalse(value.containsKey("col2")); assertFalse(value.containsKey("col4")); assertFalse(value.containsKey("col6")); assertValue(42, "col1", value); assertValue("lolcat", "col3", value); assertValue(2.72, "col5", value); } public void testImportAllRows_bulks() throws Exception { // Create a fake data stream to be read ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outputStream); // Add the header writer.writeInt(2); writer.writeUTF("col1"); writer.writeByte(ContentTypeIds.INT_TYPE_ID); writer.writeUTF("col2"); writer.writeByte(ContentTypeIds.STRING_TYPE_ID); // Add lots of rows (so the insertions are split in multiple bulks) int numRows = TEST_BULK_SIZE * 5 / 2; writer.writeInt(numRows); for (int i = 0; i < numRows; i++) { writer.writeLong(3); writer.writeInt(i); writer.writeUTF(Integer.toString(i * 2)); } writer.flush(); // Do the importing DatabaseImporter importer = new TestableDatabaseImporter(false); byte[] dataBytes = outputStream.toByteArray(); importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes))); // Verify the rows assertEquals(numRows, insertedValues.size()); for (int i = 0; i < numRows; i++) { ContentValues value = insertedValues.get(i); assertEquals(value.toString(), 2, value.size()); assertValue(i, "col1", value); assertValue(Integer.toString(i * 2), "col2", value); } } private void writeFullHeader(DataOutputStream writer) throws IOException { // Add the header writer.writeInt(7); writer.writeUTF("col1"); writer.writeByte(ContentTypeIds.INT_TYPE_ID); writer.writeUTF("col2"); writer.writeByte(ContentTypeIds.BOOLEAN_TYPE_ID); writer.writeUTF("col3"); writer.writeByte(ContentTypeIds.STRING_TYPE_ID); writer.writeUTF("col4"); writer.writeByte(ContentTypeIds.FLOAT_TYPE_ID); writer.writeUTF("col5"); writer.writeByte(ContentTypeIds.DOUBLE_TYPE_ID); writer.writeUTF("col6"); writer.writeByte(ContentTypeIds.LONG_TYPE_ID); writer.writeUTF("col7"); writer.writeByte(ContentTypeIds.BLOB_TYPE_ID); } private <T> void assertValue(T expectedValue, String name, ContentValues values) { @SuppressWarnings("unchecked") T value = (T) values.get(name); assertNotNull(value); assertEquals(expectedValue, value); } private void assertBlobValue(String expectedValue, String name, ContentValues values ){ byte[] blob = values.getAsByteArray(name); assertEquals(expectedValue, new String(blob)); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.io.backup; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import java.util.HashMap; import java.util.Map; import java.util.Set; import junit.framework.TestCase; /** * Tests for {@link PreferenceBackupHelper}. * * @author Rodrigo Damazio */ public class PreferenceBackupHelperTest extends TestCase { private Map<String, ?> preferenceValues; private SharedPreferences preferences; private PreferenceBackupHelper preferenceBackupHelper; /** * Mock shared preferences editor which does not persist state. */ private class MockPreferenceEditor implements SharedPreferences.Editor { private Map<String, Object> newPreferences = new HashMap<String, Object>(preferenceValues); @Override public Editor clear() { newPreferences.clear(); return this; } @Override public boolean commit() { apply(); return true; } @Override public void apply() { preferenceValues = newPreferences; } @Override public Editor putBoolean(String key, boolean value) { return put(key, value); } @Override public Editor putFloat(String key, float value) { return put(key, value); } @Override public Editor putInt(String key, int value) { return put(key, value); } @Override public Editor putLong(String key, long value) { return put(key, value); } @Override public Editor putString(String key, String value) { return put(key, value); } public Editor putStringSet(String key, Set<String> value) { return put(key, value); } private <T> Editor put(String key, T value) { newPreferences.put(key, value); return this; } @Override public Editor remove(String key) { newPreferences.remove(key); return this; } } /** * Mock shared preferences which does not persist state. */ private class MockPreferences implements SharedPreferences { @Override public boolean contains(String key) { return preferenceValues.containsKey(key); } @Override public Editor edit() { return new MockPreferenceEditor(); } @Override public Map<String, ?> getAll() { return preferenceValues; } @Override public boolean getBoolean(String key, boolean defValue) { return get(key, defValue); } @Override public float getFloat(String key, float defValue) { return get(key, defValue); } @Override public int getInt(String key, int defValue) { return get(key, defValue); } @Override public long getLong(String key, long defValue) { return get(key, defValue); } @Override public String getString(String key, String defValue) { return get(key, defValue); } public Set<String> getStringSet(String key, Set<String> defValue) { return get(key, defValue); } @Override public void registerOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener) { throw new UnsupportedOperationException(); } @Override public void unregisterOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener) { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") private <T> T get(String key, T defValue) { Object value = preferenceValues.get(key); if (value == null) return defValue; return (T) value; } } @Override protected void setUp() throws Exception { super.setUp(); preferenceValues = new HashMap<String, Object>(); preferences = new MockPreferences(); preferenceBackupHelper = new PreferenceBackupHelper(); } public void testExportImportPreferences() throws Exception { // Populate with some initial values Editor editor = preferences.edit(); editor.clear(); editor.putBoolean("bool1", true); editor.putBoolean("bool2", false); editor.putFloat("flt1", 3.14f); editor.putInt("int1", 42); editor.putLong("long1", 123456789L); editor.putString("str1", "lolcat"); editor.apply(); // Export it byte[] exported = preferenceBackupHelper.exportPreferences(preferences); // Mess with the previous values editor = preferences.edit(); editor.clear(); editor.putString("str2", "Shouldn't be there after restore"); editor.putBoolean("bool2", true); editor.apply(); // Import it back preferenceBackupHelper.importPreferences(exported, preferences); assertFalse(preferences.contains("str2")); assertTrue(preferences.getBoolean("bool1", false)); assertFalse(preferences.getBoolean("bool2", true)); assertEquals(3.14f, preferences.getFloat("flt1", 0.0f)); assertEquals(42, preferences.getInt("int1", 0)); assertEquals(123456789L, preferences.getLong("long1", 0)); assertEquals("lolcat", preferences.getString("str1", "")); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.io.backup; import com.google.android.apps.mytracks.content.ContentTypeIds; import android.database.MatrixCursor; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import junit.framework.TestCase; /** * Tests for {@link DatabaseDumper}. * * @author Rodrigo Damazio */ public class DatabaseDumperTest extends TestCase { /** * This class is the same as {@link MatrixCursor}, except this class * implements {@link #getBlob} ({@link MatrixCursor} leaves it * unimplemented). */ private class BlobAwareMatrixCursor extends MatrixCursor { public BlobAwareMatrixCursor(String[] columnNames) { super(columnNames); } @Override public byte[] getBlob(int columnIndex) { return getString(columnIndex).getBytes(); } } private static final String[] COLUMN_NAMES = { "intCol", "longCol", "floatCol", "doubleCol", "stringCol", "boolCol", "blobCol" }; private static final byte[] COLUMN_TYPES = { ContentTypeIds.INT_TYPE_ID, ContentTypeIds.LONG_TYPE_ID, ContentTypeIds.FLOAT_TYPE_ID, ContentTypeIds.DOUBLE_TYPE_ID, ContentTypeIds.STRING_TYPE_ID, ContentTypeIds.BOOLEAN_TYPE_ID, ContentTypeIds.BLOB_TYPE_ID }; private static final String[][] FAKE_DATA = { { "42", "123456789", "3.1415", "2.72", "lolcat", "1", "blob" }, { null, "123456789", "3.1415", "2.72", "lolcat", "1", "blob" }, { "42", null, "3.1415", "2.72", "lolcat", "1", "blob" }, { "42", "123456789", null, "2.72", "lolcat", "1", "blob" }, { "42", "123456789", "3.1415", null, "lolcat", "1", "blob" }, { "42", "123456789", "3.1415", "2.72", null, "1", "blob" }, { "42", "123456789", "3.1415", "2.72", "lolcat", null, "blob" }, { "42", "123456789", "3.1415", "2.72", "lolcat", "1", null }, }; private static final long[] EXPECTED_FIELD_SETS = { 0x7F, 0x7E, 0x7D, 0x7B, 0x77, 0x6F, 0x5F, 0x3F }; private BlobAwareMatrixCursor cursor; @Override protected void setUp() throws Exception { super.setUp(); // Add fake data to the cursor cursor = new BlobAwareMatrixCursor(COLUMN_NAMES); for (String[] row : FAKE_DATA) { cursor.addRow(row); } } public void testWriteAllRows_noNulls() throws Exception { testWriteAllRows(false); } public void testWriteAllRows_withNulls() throws Exception { testWriteAllRows(true); } private void testWriteAllRows(boolean hasNullFields) throws Exception { // Dump it DatabaseDumper dumper = new DatabaseDumper(COLUMN_NAMES, COLUMN_TYPES, hasNullFields); ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outStream ); dumper.writeAllRows(cursor, writer); // Read the results byte[] result = outStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(result); DataInputStream reader = new DataInputStream(inputStream); // Verify the header assertHeader(reader); // Verify the number of rows assertEquals(FAKE_DATA.length, reader.readInt()); // Row 0 -- everything populated assertEquals(EXPECTED_FIELD_SETS[0], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 1 -- no int assertEquals(EXPECTED_FIELD_SETS[1], reader.readLong()); if (hasNullFields) reader.readInt(); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 2 -- no long assertEquals(EXPECTED_FIELD_SETS[2], reader.readLong()); assertEquals(42, reader.readInt()); if (hasNullFields) reader.readLong(); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 3 -- no float assertEquals(EXPECTED_FIELD_SETS[3], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); if (hasNullFields) reader.readFloat(); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 4 -- no double assertEquals(EXPECTED_FIELD_SETS[4], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); if (hasNullFields) reader.readDouble(); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 5 -- no string assertEquals(EXPECTED_FIELD_SETS[5], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); if (hasNullFields) reader.readUTF(); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 6 -- no boolean assertEquals(EXPECTED_FIELD_SETS[6], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); if (hasNullFields) reader.readBoolean(); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 7 -- no blob assertEquals(EXPECTED_FIELD_SETS[7], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); if (hasNullFields) { int length = reader.readInt(); readBlob(reader, length); } } public void testFewerRows() throws Exception { // Dump only the first two rows DatabaseDumper dumper = new DatabaseDumper(COLUMN_NAMES, COLUMN_TYPES, false); ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outStream); dumper.writeHeaders(cursor, 2, writer); cursor.moveToFirst(); dumper.writeOneRow(cursor, writer); cursor.moveToNext(); dumper.writeOneRow(cursor, writer); // Read the results byte[] result = outStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(result); DataInputStream reader = new DataInputStream(inputStream); // Verify the header assertHeader(reader); // Verify the number of rows assertEquals(2, reader.readInt()); // Row 0 assertEquals(EXPECTED_FIELD_SETS[0], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 1 assertEquals(EXPECTED_FIELD_SETS[1], reader.readLong()); // Null field not read assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); } private void assertHeader(DataInputStream reader) throws IOException { assertEquals(COLUMN_NAMES.length, reader.readInt()); for (int i = 0; i < COLUMN_NAMES.length; i++) { assertEquals(COLUMN_NAMES[i], reader.readUTF()); assertEquals(COLUMN_TYPES[i], reader.readByte()); } } private String readBlob(InputStream reader, int length) throws Exception { if (length == 0) { return ""; } byte[] blob = new byte[length]; assertEquals(length, reader.read(blob)); return new String(blob); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.io.file; import static com.google.android.testing.mocking.AndroidMock.eq; import static com.google.android.testing.mocking.AndroidMock.expect; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory; import com.google.android.apps.mytracks.io.file.GpxImporter; import com.google.android.apps.mytracks.testing.TestingProviderUtilsFactory; import com.google.android.testing.mocking.AndroidMock; import com.google.android.testing.mocking.UsesMocks; import android.content.ContentUris; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.test.AndroidTestCase; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.SimpleTimeZone; import javax.xml.parsers.ParserConfigurationException; import org.easymock.Capture; import org.easymock.IArgumentMatcher; import org.xml.sax.SAXException; /** * Tests for the GPX importer. * * @author Steffen Horlacher */ public class GpxImporterTest extends AndroidTestCase { private static final String TRACK_NAME = "blablub"; private static final String TRACK_DESC = "s'Laebe isch koi Schlotzer"; private static final String TRACK_LAT_1 = "48.768364"; private static final String TRACK_LON_1 = "9.177886"; private static final String TRACK_ELE_1 = "324.0"; private static final String TRACK_TIME_1 = "2010-04-22T18:21:00Z"; private static final String TRACK_LAT_2 = "48.768374"; private static final String TRACK_LON_2 = "9.177816"; private static final String TRACK_ELE_2 = "333.0"; private static final String TRACK_TIME_2 = "2010-04-22T18:21:50.123"; private static final SimpleDateFormat DATE_FORMAT1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); private static final SimpleDateFormat DATE_FORMAT2 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'"); static { // We can't omit the timezones in the test, otherwise it'll use the local // timezone and fail depending on where the test runner is. SimpleTimeZone utc = new SimpleTimeZone(0, "UTC"); DATE_FORMAT1.setTimeZone(utc); DATE_FORMAT2.setTimeZone(utc); } // TODO: use real files from different sources with more track points. private static final String VALID_TEST_GPX = "<gpx><trk><name><![CDATA[" + TRACK_NAME + "]]></name><desc><![CDATA[" + TRACK_DESC + "]]></desc><trkseg>" + "<trkpt lat=\"" + TRACK_LAT_1 + "\" lon=\"" + TRACK_LON_1 + "\"><ele>" + TRACK_ELE_1 + "</ele><time>" + TRACK_TIME_1 + "</time></trkpt> +" + "<trkpt lat=\"" + TRACK_LAT_2 + "\" lon=\"" + TRACK_LON_2 + "\"><ele>" + TRACK_ELE_2 + "</ele><time>" + TRACK_TIME_2 + "</time></trkpt>" + "</trkseg></trk></gpx>"; // invalid xml private static final String INVALID_XML_TEST_GPX = VALID_TEST_GPX.substring( 0, VALID_TEST_GPX.length() - 50); private static final String INVALID_LOCATION_TEST_GPX = VALID_TEST_GPX .replaceAll(TRACK_LAT_1, "1000.0"); private static final String INVALID_TIME_TEST_GPX = VALID_TEST_GPX .replaceAll(TRACK_TIME_1, "invalid"); private static final String INVALID_ALTITUDE_TEST_GPX = VALID_TEST_GPX .replaceAll(TRACK_ELE_1, "invalid"); private static final String INVALID_LATITUDE_TEST_GPX = VALID_TEST_GPX .replaceAll(TRACK_LAT_1, "invalid"); private static final String INVALID_LONGITUDE_TEST_GPX = VALID_TEST_GPX .replaceAll(TRACK_LON_1, "invalid"); private static final long TRACK_ID = 1; private static final long TRACK_POINT_ID_1 = 1; private static final long TRACK_POINT_ID_2 = 2; private static final Uri TRACK_ID_URI = ContentUris.appendId( TracksColumns.CONTENT_URI.buildUpon(), TRACK_ID).build(); private MyTracksProviderUtils providerUtils; private Factory oldProviderUtilsFactory; @UsesMocks(MyTracksProviderUtils.class) @Override protected void setUp() throws Exception { super.setUp(); providerUtils = AndroidMock.createMock(MyTracksProviderUtils.class); oldProviderUtilsFactory = TestingProviderUtilsFactory.installWithInstance(providerUtils); } @Override protected void tearDown() throws Exception { TestingProviderUtilsFactory.restoreOldFactory(oldProviderUtilsFactory); super.tearDown(); } /** * Test import success. */ public void testImportSuccess() throws Exception { Capture<Track> trackParam = new Capture<Track>(); Location loc1 = new Location(LocationManager.GPS_PROVIDER); loc1.setTime(DATE_FORMAT2.parse(TRACK_TIME_1).getTime()); loc1.setLatitude(Double.parseDouble(TRACK_LAT_1)); loc1.setLongitude(Double.parseDouble(TRACK_LON_1)); loc1.setAltitude(Double.parseDouble(TRACK_ELE_1)); Location loc2 = new Location(LocationManager.GPS_PROVIDER); loc2.setTime(DATE_FORMAT1.parse(TRACK_TIME_2).getTime()); loc2.setLatitude(Double.parseDouble(TRACK_LAT_2)); loc2.setLongitude(Double.parseDouble(TRACK_LON_2)); loc2.setAltitude(Double.parseDouble(TRACK_ELE_2)); expect(providerUtils.insertTrack(AndroidMock.capture(trackParam))) .andReturn(TRACK_ID_URI); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(TRACK_POINT_ID_1).andReturn(TRACK_POINT_ID_2); // A flush happens after the first insertion to get the starting point ID, // which is why we get two calls expect(providerUtils.bulkInsertTrackPoints(LocationsMatcher.eqLoc(loc1), eq(1), eq(TRACK_ID))).andReturn(1); expect(providerUtils.bulkInsertTrackPoints(LocationsMatcher.eqLoc(loc2), eq(1), eq(TRACK_ID))).andReturn(1); providerUtils.updateTrack(AndroidMock.capture(trackParam)); AndroidMock.replay(providerUtils); InputStream is = new ByteArrayInputStream(VALID_TEST_GPX.getBytes()); GpxImporter.importGPXFile(is, providerUtils); AndroidMock.verify(providerUtils); // verify track parameter Track track = trackParam.getValue(); assertEquals(TRACK_NAME, track.getName()); assertEquals(TRACK_DESC, track.getDescription()); assertEquals(DATE_FORMAT2.parse(TRACK_TIME_1).getTime(), track.getStatistics() .getStartTime()); assertNotSame(-1, track.getStartId()); assertNotSame(-1, track.getStopId()); } /** * Test with invalid location - track should be deleted. */ public void testImportLocationFailure() throws ParserConfigurationException, IOException { testInvalidXML(INVALID_LOCATION_TEST_GPX); } /** * Test with invalid time - track should be deleted. */ public void testImportTimeFailure() throws ParserConfigurationException, IOException { testInvalidXML(INVALID_TIME_TEST_GPX); } /** * Test with invalid xml - track should be deleted. */ public void testImportXMLFailure() throws ParserConfigurationException, IOException { testInvalidXML(INVALID_XML_TEST_GPX); } /** * Test with invalid altitude - track should be deleted. */ public void testImportInvalidAltitude() throws ParserConfigurationException, IOException { testInvalidXML(INVALID_ALTITUDE_TEST_GPX); } /** * Test with invalid latitude - track should be deleted. */ public void testImportInvalidLatitude() throws ParserConfigurationException, IOException { testInvalidXML(INVALID_LATITUDE_TEST_GPX); } /** * Test with invalid longitude - track should be deleted. */ public void testImportInvalidLongitude() throws ParserConfigurationException, IOException { testInvalidXML(INVALID_LONGITUDE_TEST_GPX); } private void testInvalidXML(String xml) throws ParserConfigurationException, IOException { expect(providerUtils.insertTrack((Track) AndroidMock.anyObject())) .andReturn(TRACK_ID_URI); expect(providerUtils.bulkInsertTrackPoints((Location[]) AndroidMock.anyObject(), AndroidMock.anyInt(), AndroidMock.anyLong())).andStubReturn(1); expect(providerUtils.getLastLocationId(TRACK_ID)).andStubReturn(TRACK_POINT_ID_1); providerUtils.deleteTrack(TRACK_ID); AndroidMock.replay(providerUtils); InputStream is = new ByteArrayInputStream(xml.getBytes()); try { GpxImporter.importGPXFile(is, providerUtils); } catch (SAXException e) { // expected exception } AndroidMock.verify(providerUtils); } /** * Workaround because of capture bug 2617107 in easymock: * http://sourceforge.net * /tracker/?func=detail&aid=2617107&group_id=82958&atid=567837 */ private static class LocationsMatcher implements IArgumentMatcher { private final Location[] matchLocs; private LocationsMatcher(Location[] expected) { this.matchLocs = expected; } public static Location[] eqLoc(Location[] expected) { IArgumentMatcher matcher = new LocationsMatcher(expected); AndroidMock.reportMatcher(matcher); return null; } public static Location[] eqLoc(Location expected) { return eqLoc(new Location[] { expected}); } @Override public void appendTo(StringBuffer buf) { buf.append("eqLoc(").append(Arrays.toString(matchLocs)).append(")"); } @Override public boolean matches(Object obj) { if (! (obj instanceof Location[])) { return false; } Location[] locs = (Location[]) obj; if (locs.length < matchLocs.length) { return false; } // Only check the first elements (those that will be taken into account) for (int i = 0; i < matchLocs.length; i++) { if (!locationsMatch(locs[i], matchLocs[i])) { return false; } } return true; } private boolean locationsMatch(Location loc1, Location loc2) { return (loc1.getTime() == loc2.getTime()) && (loc1.getLatitude() == loc2.getLatitude()) && (loc1.getLongitude() == loc2.getLongitude()) && (loc1.getAltitude() == loc2.getAltitude()); } } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.io.file.KmlTrackWriter; import com.google.android.apps.mytracks.util.StringUtils; import android.location.Location; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.util.List; import java.util.Vector; /** * Tests for the KML track exporter. * * @author Rodrigo Damazio */ public class KmlTrackWriterTest extends TrackFormatWriterTest { private static final String FULL_TRACK_DESCRIPTION = "full track description"; /** * A fake version of {@link StringUtils} which returns a fixed track * description, thus not depending on the context. */ private class FakeStringUtils extends StringUtils { public FakeStringUtils() { super(null); } @Override public String generateTrackDescription(Track trackToDescribe, Vector<Double> distances, Vector<Double> elevations) { assertSame(KmlTrackWriterTest.super.track, trackToDescribe); assertTrue(distances.isEmpty()); assertTrue(elevations.isEmpty()); return FULL_TRACK_DESCRIPTION; } } public void testXmlOutput() throws Exception { KmlTrackWriter writer = new KmlTrackWriter(new FakeStringUtils()); String result = writeTrack(writer); Document doc = parseXmlDocument(result); Element kmlTag = getChildElement(doc, "kml"); Element docTag = getChildElement(kmlTag, "Document"); assertEquals(TRACK_NAME, getChildTextValue(docTag, "name")); assertEquals(TRACK_DESCRIPTION, getChildTextValue(docTag, "description")); // There are 5 placemarks - start, segments, end, waypoint 1, waypoint 2 List<Element> placemarkTags = getChildElements(docTag, "Placemark", 5); assertTagIsPlacemark(placemarkTags.get(0), "(Start)", TRACK_DESCRIPTION, location1); assertTagIsPlacemark(placemarkTags.get(2), "(End)", FULL_TRACK_DESCRIPTION, location4); assertTagIsPlacemark(placemarkTags.get(3), WAYPOINT1_NAME, WAYPOINT1_DESCRIPTION, location2); assertTagIsPlacemark(placemarkTags.get(4), WAYPOINT2_NAME, WAYPOINT2_DESCRIPTION, location3); Element trackPlacemarkTag = placemarkTags.get(1); assertEquals(TRACK_NAME, getChildTextValue(trackPlacemarkTag, "name")); assertEquals(TRACK_DESCRIPTION, getChildTextValue(trackPlacemarkTag, "description")); Element geometryTag = getChildElement(trackPlacemarkTag, "MultiGeometry"); List<Element> segmentTags = getChildElements(geometryTag, "LineString", 2); assertTagHasPoints(segmentTags.get(0), location1, location2); assertTagHasPoints(segmentTags.get(1), location3, location4); } /** * Asserts that the given XML tag is a placemark with the given properties. * * @param tag the tag to analyze * @param name the expected name for the placemark * @param description the expected description for the placemark * @param location the expected location of the placemark */ private void assertTagIsPlacemark(Element tag, String name, String description, Location location) { assertEquals(name, getChildTextValue(tag, "name")); assertEquals(description, getChildTextValue(tag, "description")); Element pointTag = getChildElement(tag, "Point"); String expectedCoords = location.getLongitude() + "," + location.getLatitude(); String actualCoords = getChildTextValue(pointTag, "coordinates"); assertEquals(expectedCoords, actualCoords); } /** * Asserts that the given tag has a "coordinates" subtag with the given * locations. * * @param tag the tag to analyze * @param locs the locations to expect in the coordinates */ private void assertTagHasPoints(Element tag, Location... locs) { StringBuilder expectedBuilder = new StringBuilder(); for (Location loc : locs) { expectedBuilder.append(loc.getLongitude()); expectedBuilder.append(','); expectedBuilder.append(loc.getLatitude()); expectedBuilder.append(','); expectedBuilder.append(loc.getAltitude()); expectedBuilder.append(' '); } String expectedCoordinates = expectedBuilder.toString().trim(); String actualCoordinates = getChildTextValue(tag, "coordinates").trim(); assertEquals(expectedCoordinates, actualCoordinates); } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.content.MyTracksLocation; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import android.test.AndroidTestCase; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Base class for track format writer tests, which sets up a fake track and * gives auxiliary methods for verifying XML output. * * @author Rodrigo Damazio */ public abstract class TrackFormatWriterTest extends AndroidTestCase { // All the user-provided strings have "]]>" to ensure that proper escaping is // being done. protected static final String TRACK_NAME = "Home]]>"; protected static final String TRACK_DESCRIPTION = "The long ]]> journey home"; protected static final String WAYPOINT1_NAME = "point]]>1"; protected static final String WAYPOINT1_DESCRIPTION = "point 1]]>description"; protected static final String WAYPOINT2_NAME = "point]]>2"; protected static final String WAYPOINT2_DESCRIPTION = "point 2]]>description"; private static final int BUFFER_SIZE = 10240; protected static final long TRACK_ID = 12345L; protected Track track; protected MyTracksLocation location1, location2, location3, location4; protected Waypoint wp1, wp2; @Override protected void setUp() throws Exception { super.setUp(); track = new Track(); track.setId(TRACK_ID); track.setName(TRACK_NAME); track.setDescription(TRACK_DESCRIPTION); location1 = new MyTracksLocation("mock"); location2 = new MyTracksLocation("mock"); location3 = new MyTracksLocation("mock"); location4 = new MyTracksLocation("mock"); populateLocations(location1, location2, location3, location4); wp1 = new Waypoint(); wp2 = new Waypoint(); wp1.setLocation(location2); wp1.setName(WAYPOINT1_NAME); wp1.setDescription(WAYPOINT1_DESCRIPTION); wp2.setLocation(location3); wp2.setName(WAYPOINT2_NAME); wp2.setDescription(WAYPOINT2_DESCRIPTION); } /** * Populates the given locations with coordinates and time. */ protected void populateLocations(MyTracksLocation... locs) { for (int i = 0; i < locs.length; i++) { MyTracksLocation loc = locs[i]; loc.setAltitude(i * 5000000); loc.setLatitude(i); loc.setLongitude(-i); loc.setTime(10000000 + i * 1000); Sensor.SensorData.Builder hr = Sensor.SensorData.newBuilder() .setValue(100 + i) .setState(Sensor.SensorState.SENDING); Sensor.SensorData.Builder power = Sensor.SensorData.newBuilder() .setValue(400 + i) .setState(Sensor.SensorState.SENDING); Sensor.SensorDataSet sds = Sensor.SensorDataSet.newBuilder().setHeartRate(hr.build()) .setPower(power) .build(); loc.setSensorData(sds); } } /** * Makes the right sequence of calls to the writer in order to write the fake * track in {@link #track}. * * @param writer the writer to write to * @return the written contents */ protected String writeTrack(TrackFormatWriter writer) throws Exception { OutputStream output = new ByteArrayOutputStream(BUFFER_SIZE); writer.prepare(track, output); writer.writeHeader(); writer.writeBeginTrack(location1); writer.writeOpenSegment(); writer.writeLocation(location1); writer.writeLocation(location2); writer.writeCloseSegment(); writer.writeOpenSegment(); writer.writeLocation(location3); writer.writeLocation(location4); writer.writeCloseSegment(); writer.writeEndTrack(location4); writer.writeWaypoint(wp1); writer.writeWaypoint(wp2); writer.writeFooter(); writer.close(); return output.toString(); } /** * Gets the text data contained inside a tag. * * @param parent the parent of the tag containing the text * @param elementName the name of the tag containing the text * @return the text contents */ protected String getChildTextValue(Element parent, String elementName) { Element child = getChildElement(parent, elementName); assertTrue(child.hasChildNodes()); NodeList children = child.getChildNodes(); int length = children.getLength(); assertTrue(length > 0); // The children may be a sucession of text elements, just concatenate them String result = ""; for (int i = 0; i < length; i++) { Text textNode = (Text) children.item(i); result += textNode.getNodeValue(); } return result; } /** * Returns all child elements of a given parent which have the given name. * * @param parent the parent to get children from * @param elementName the element name to look for * @param expectedChildren the number of children we're expected to find * @return a list of the found elements */ protected List<Element> getChildElements(Node parent, String elementName, int expectedChildren) { assertTrue(parent.hasChildNodes()); NodeList children = parent.getChildNodes(); int length = children.getLength(); List<Element> result = new ArrayList<Element>(); for (int i = 0; i < length; i++) { Node childNode = children.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE && childNode.getNodeName().equalsIgnoreCase(elementName)) { result.add((Element) childNode); } } assertTrue(children.toString(), result.size() == expectedChildren); return result; } /** * Returns the single child element of the given parent with the given type. * * @param parent the parent to get a child from * @param elementName the name of the child to look for * @return the child element */ protected Element getChildElement(Node parent, String elementName) { return getChildElements(parent, elementName, 1).get(0); } /** * Parses the given XML contents and returns a DOM {@link Document} for it. */ protected Document parseXmlDocument(String contents) throws FactoryConfigurationError, ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setCoalescing(true); // TODO: Somehow do XML validation on Android // builderFactory.setValidating(true); builderFactory.setNamespaceAware(true); builderFactory.setIgnoringComments(true); builderFactory.setIgnoringElementContentWhitespace(true); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); Document doc = documentBuilder.parse( new InputSource(new StringReader(contents))); return doc; } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.content.MyTracksLocation; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.util.FileUtils; import java.util.List; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Tests for the GPX track exporter. * * @author Sandor Dornbush */ public class TcxTrackWriterTest extends TrackFormatWriterTest { public void testXmlOutput() throws Exception { TrackFormatWriter writer = new TcxTrackWriter(getContext()); String result = writeTrack(writer); Document doc = parseXmlDocument(result); Element root = getChildElement(doc, "TrainingCenterDatabase"); Element activitiesTag = getChildElement(root, "Activities"); Element activityTag = getChildElement(activitiesTag, "Activity"); Element lapTag = getChildElement(activityTag, "Lap"); List<Element> segmentTags = getChildElements(lapTag, "Track", 2); Element segment1Tag = segmentTags.get(0); Element segment2Tag = segmentTags.get(1); List<Element> seg1PointTags = getChildElements(segment1Tag, "Trackpoint", 2); List<Element> seg2PointTags = getChildElements(segment2Tag, "Trackpoint", 2); assertTagsMatchPoints(seg1PointTags, location1, location2); assertTagsMatchPoints(seg2PointTags, location3, location4); } /** * Asserts that the given tags describe the given points, in the same order. */ private void assertTagsMatchPoints(List<Element> tags, MyTracksLocation... locs) { assertEquals(locs.length, tags.size()); for (int i = 0; i < locs.length; i++) { Element tag = tags.get(i); MyTracksLocation loc = locs[i]; assertTagMatchesLocation(tag, loc); } } /** * Asserts that the given tag describes the given location. */ private void assertTagMatchesLocation(Element tag, MyTracksLocation loc) { Element posTag = getChildElement(tag, "Position"); assertEquals(Double.toString(loc.getLatitude()), getChildTextValue(posTag, "LatitudeDegrees")); assertEquals(Double.toString(loc.getLongitude()), getChildTextValue(posTag, "LongitudeDegrees")); assertEquals(FileUtils.FILE_TIMESTAMP_FORMAT.format(loc.getTime()), getChildTextValue(tag, "Time")); assertEquals(Double.toString(loc.getAltitude()), getChildTextValue(tag, "AltitudeMeters")); assertTrue(loc.getSensorDataSet() != null); Sensor.SensorDataSet sds = loc.getSensorDataSet(); List<Element> bpm = getChildElements(tag, "HeartRateBpm", 1); assertEquals(Integer.toString(sds.getHeartRate().getValue()), getChildTextValue(bpm.get(0), "Value")); List<Element> ext = getChildElements(tag, "Extensions", 1); List<Element> tpx = getChildElements(ext.get(0), "TPX", 1); assertEquals(Integer.toString(sds.getPower().getValue()), getChildTextValue(tpx.get(0), "Watts")); } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.io.file; import java.io.File; /** * A simple, fake {@link TrackWriter} subclass with all methods mocked out. * Tests are expected to override {@link #writeTrack} and/or * {@link #writeTrackAsync}, at the very least. * * @author Matthew Simmons * */ public class MockTrackWriter implements TrackWriter { public OnCompletionListener onCompletionListener; public OnWriteListener onWriteListener; @Override public void setOnCompletionListener(OnCompletionListener onCompletionListener) { this.onCompletionListener = onCompletionListener; } @Override public void setOnWriteListener(OnWriteListener onWriteListener) { this.onWriteListener = onWriteListener; } @Override public void setDirectory(File directory) { throw new UnsupportedOperationException("not implemented"); } @Override public String getAbsolutePath() { throw new UnsupportedOperationException("not implemented"); } @Override public void writeTrackAsync() { throw new UnsupportedOperationException("not implemented"); } @Override public void writeTrack() { throw new UnsupportedOperationException("not implemented"); } @Override public void stopWriteTrack() { throw new UnsupportedOperationException("not implemented"); } @Override public boolean wasSuccess() { return false; } @Override public int getErrorMessage() { return 0; } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.io.file.GpxTrackWriter; import com.google.android.apps.mytracks.io.file.TrackFormatWriter; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.util.List; /** * Tests for the GPX track exporter. * * @author Rodrigo Damazio */ public class GpxTrackWriterTest extends TrackFormatWriterTest { public void testXmlOutput() throws Exception { TrackFormatWriter writer = new GpxTrackWriter(); String result = writeTrack(writer); Document doc = parseXmlDocument(result); Element gpxTag = getChildElement(doc, "gpx"); Element trackTag = getChildElement(gpxTag, "trk"); assertEquals(TRACK_NAME, getChildTextValue(trackTag, "name")); assertEquals(TRACK_DESCRIPTION, getChildTextValue(trackTag, "desc")); assertEquals(Long.toString(TRACK_ID), getChildTextValue(trackTag, "number")); List<Element> segmentTags = getChildElements(trackTag, "trkseg", 2); List<Element> segPointTags = getChildElements(segmentTags.get(0), "trkpt", 2); assertTagMatchesLocation(segPointTags.get(0), "0", "0", "1970-01-01T02:46:40Z", "0"); assertTagMatchesLocation(segPointTags.get(1), "1", "-1", "1970-01-01T02:46:41Z", "5000000"); segPointTags = getChildElements(segmentTags.get(1), "trkpt", 2); assertTagMatchesLocation(segPointTags.get(0), "2", "-2", "1970-01-01T02:46:42Z", "10000000"); assertTagMatchesLocation(segPointTags.get(1), "3", "-3", "1970-01-01T02:46:43Z", "15000000"); List<Element> waypointTags = getChildElements(gpxTag, "wpt", 2); Element wptTag = waypointTags.get(0); assertEquals(WAYPOINT1_NAME, getChildTextValue(wptTag, "name")); assertEquals(WAYPOINT1_DESCRIPTION, getChildTextValue(wptTag, "desc")); assertTagMatchesLocation(wptTag, "1", "-1", "1970-01-01T02:46:41Z", "5000000"); wptTag = waypointTags.get(1); assertEquals(WAYPOINT2_NAME, getChildTextValue(wptTag, "name")); assertEquals(WAYPOINT2_DESCRIPTION, getChildTextValue(wptTag, "desc")); assertTagMatchesLocation(wptTag, "2", "-2", "1970-01-01T02:46:42Z", "10000000"); } /** * Asserts that the given tag describes the location given by the * Strings lat, lon, time, and ele. */ private void assertTagMatchesLocation(Element tag, String lat, String lon, String time, String ele) { assertEquals(lat, tag.getAttribute("lat")); assertEquals(lon, tag.getAttribute("lon")); assertEquals(time, getChildTextValue(tag, "time")); assertEquals(ele, getChildTextValue(tag, "ele")); } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.file; /** * Tests for the CSV track exporter. * * @author Rodrigo Damazio */ public class CsvTrackWriterTest extends TrackFormatWriterTest { }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.io.file; import static com.google.android.testing.mocking.AndroidMock.expect; import com.google.android.apps.mytracks.io.file.TempFileCleaner; import com.google.android.testing.mocking.AndroidMock; import com.google.android.testing.mocking.UsesMocks; import android.test.AndroidTestCase; import java.io.File; /** * @author Sandor Dornbush */ public class TempFileCleanerTest extends AndroidTestCase { @UsesMocks({ File.class, }) public void test_noDir() { File dir = AndroidMock.createMock(File.class, "/no_file"); TempFileCleaner cleaner = new TempFileCleaner(0); expect(dir.exists()).andStubReturn(false); AndroidMock.replay(dir); assertEquals(0, cleaner.cleanTmpDirectory(dir)); AndroidMock.verify(dir); } public void test_emptyDir() { File dir = AndroidMock.createMock(File.class, "/no_file"); TempFileCleaner cleaner = new TempFileCleaner(0); expect(dir.exists()).andStubReturn(true); expect(dir.listFiles()).andStubReturn(new File[0]); AndroidMock.replay(dir); assertEquals(0, cleaner.cleanTmpDirectory(dir)); AndroidMock.verify(dir); } public void test_newFile() { File dir = AndroidMock.createMock(File.class, "/no_file"); long now = 100000000; TempFileCleaner cleaner = new TempFileCleaner(now); expect(dir.exists()).andStubReturn(true); File file = AndroidMock.createMock(File.class, "/no_file/foo"); expect(file.lastModified()).andStubReturn(now); File[] list = { file }; expect(dir.listFiles()).andStubReturn(list); AndroidMock.replay(dir, file); assertEquals(0, cleaner.cleanTmpDirectory(dir)); AndroidMock.verify(dir, file); } public void test_oldFile() { File dir = AndroidMock.createMock(File.class, "/no_file"); long now = 100000000; TempFileCleaner cleaner = new TempFileCleaner(now); expect(dir.exists()).andStubReturn(true); File file = AndroidMock.createMock(File.class, "/no_file/foo"); expect(file.lastModified()).andStubReturn(now - 3600001); expect(file.delete()).andStubReturn(true); File[] list = { file }; expect(dir.listFiles()).andStubReturn(list); AndroidMock.replay(dir, file); assertEquals(1, cleaner.cleanTmpDirectory(dir)); AndroidMock.verify(dir, file); } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.io.file; import android.app.ProgressDialog; import android.test.ActivityInstrumentationTestCase2; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; /** * Tests {@link WriteProgressController}. * * @author Matthew Simmons */ public class WriteProgressControllerTest extends ActivityInstrumentationTestCase2<SaveActivity> { public WriteProgressControllerTest() { super(SaveActivity.class); } private static void assertProgress(ProgressDialog dialog, int expectedProgress, int expectedMax) { assertEquals(expectedProgress, dialog.getProgress()); assertEquals(expectedMax, dialog.getMax()); } public void testSimple() throws Exception { final AtomicReference<ProgressDialog> dialogRef = new AtomicReference<ProgressDialog>(); final AtomicReference<Boolean> controllerDoneRef = new AtomicReference<Boolean>(); final Semaphore writerDone = new Semaphore(0); TrackWriter mockWriter = new MockTrackWriter() { @Override public void writeTrackAsync() { onWriteListener.onWrite(1000, 10000); assertProgress(dialogRef.get(), 1000, 10000); onCompletionListener.onComplete(); writerDone.release(); } }; final WriteProgressController controller = new WriteProgressController( getActivity(), mockWriter, SaveActivity.PROGRESS_DIALOG); controller.setOnCompletionListener(new WriteProgressController.OnCompletionListener() { @Override public void onComplete() { controllerDoneRef.set(true); } }); /* * The WriteProgressController constructor calls the mockWriter's * setOnCompletionListener method with a listener that dismisses the * progress dialog. However, this unit test only tests the * WriteProgressController and doesn't actually show any progress dialog. * Thus after the WriteProgressController is setup, we need to call the * mockWriter's setOnCompletionListener method again with an listener that * doesn't dismiss dialog. */ mockWriter.setOnCompletionListener(new TrackWriter.OnCompletionListener() { @Override public void onComplete() { controller.getOnCompletionListener().onComplete(); } }); dialogRef.set(controller.createProgressDialog()); controller.startWrite(); // wait for the writer to finish writerDone.acquire(); assertTrue(controllerDoneRef.get()); } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.file; import static org.easymock.EasyMock.expect; import com.google.android.apps.mytracks.content.MyTracksProvider; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext; import com.google.android.apps.mytracks.testing.TestingProviderUtilsFactory; import com.google.android.maps.mytracks.R; import android.content.Context; import android.location.Location; import android.test.AndroidTestCase; import android.test.RenamingDelegatingContext; import android.test.mock.MockContentResolver; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.OutputStream; import org.easymock.EasyMock; import org.easymock.IAnswer; import org.easymock.IArgumentMatcher; import org.easymock.IMocksControl; /** * Tests for the track writer. * * @author Rodrigo Damazio */ public class TrackWriterTest extends AndroidTestCase { /** * {@link TrackWriterImpl} subclass which mocks out methods called from * {@link TrackWriterImpl#openFile}. */ private static final class OpenFileTrackWriter extends TrackWriterImpl { private final ByteArrayOutputStream stream; private final boolean canWrite; /** * Constructor. * * @param stream the stream to return from * {@link TrackWriterImpl#newOutputStream}, or null to throw a * {@link FileNotFoundException} * @param canWrite the value that {@link TrackWriterImpl#canWriteFile} will * return */ private OpenFileTrackWriter(Context context, MyTracksProviderUtils providerUtils, Track track, TrackFormatWriter writer, ByteArrayOutputStream stream, boolean canWrite) { super(context, providerUtils, track, writer); this.stream = stream; this.canWrite = canWrite; } @Override protected boolean canWriteFile() { return canWrite; } @Override protected OutputStream newOutputStream(String fileName) throws FileNotFoundException { assertEquals(FULL_TRACK_NAME, fileName); if (stream == null) { throw new FileNotFoundException(); } return stream; } } /** * {@link TrackWriterImpl} subclass which mocks out methods called from * {@link TrackWriterImpl#writeTrack}. */ private final class WriteTracksTrackWriter extends TrackWriterImpl { private final boolean openResult; /** * Constructor. * * @param openResult the return value for {@link TrackWriterImpl#openFile} */ private WriteTracksTrackWriter(Context context, MyTracksProviderUtils providerUtils, Track track, TrackFormatWriter writer, boolean openResult) { super(context, providerUtils, track, writer); this.openResult = openResult; } @Override protected boolean openFile() { openFileCalls++; return openResult; } @Override void writeDocument() { writeDocumentCalls++; } @Override protected void runOnUiThread(Runnable runnable) { runnable.run(); } } private static final long TRACK_ID = 1234567L; private static final String EXTENSION = "ext"; private static final String TRACK_NAME = "Swimming across the pacific"; private static final String FULL_TRACK_NAME = "Swimming across the pacific.ext"; private Track track; private TrackFormatWriter formatWriter; private TrackWriterImpl writer; private IMocksControl mocksControl; private MyTracksProviderUtils providerUtils; private Factory oldProviderUtilsFactory; // State used in specific tests private int writeDocumentCalls; private int openFileCalls; @Override protected void setUp() throws Exception { super.setUp(); MockContentResolver mockContentResolver = new MockContentResolver(); RenamingDelegatingContext targetContext = new RenamingDelegatingContext( getContext(), getContext(), "test."); Context context = new MockContext(mockContentResolver, targetContext); MyTracksProvider provider = new MyTracksProvider(); provider.attachInfo(context, null); mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider); setContext(context); providerUtils = MyTracksProviderUtils.Factory.get(context); oldProviderUtilsFactory = TestingProviderUtilsFactory.installWithInstance(providerUtils); mocksControl = EasyMock.createStrictControl(); formatWriter = mocksControl.createMock(TrackFormatWriter.class); expect(formatWriter.getExtension()).andStubReturn(EXTENSION); track = new Track(); track.setName(TRACK_NAME); track.setId(TRACK_ID); } @Override protected void tearDown() throws Exception { TestingProviderUtilsFactory.restoreOldFactory(oldProviderUtilsFactory); super.tearDown(); } public void testWriteTrack() { writer = new WriteTracksTrackWriter(getContext(), providerUtils, track, formatWriter, true); // Expect the completion listener to be run TrackWriter.OnCompletionListener completionListener = mocksControl.createMock(TrackWriter.OnCompletionListener.class); completionListener.onComplete(); mocksControl.replay(); writer.setOnCompletionListener(completionListener); writer.writeTrack(); assertEquals(1, writeDocumentCalls); assertEquals(1, openFileCalls); mocksControl.verify(); } public void testWriteTrack_cancelled() throws Exception { final ByteArrayOutputStream stream = new ByteArrayOutputStream(); writer = new OpenFileTrackWriter( getContext(), providerUtils, track, formatWriter, stream, true); formatWriter.prepare(track, stream); final Location[] locs = { new Location("fake0"), new Location("fake1"), }; fillLocations(locs); assertEquals(locs.length, providerUtils.bulkInsertTrackPoints(locs, locs.length, TRACK_ID)); formatWriter.writeHeader(); formatWriter.writeBeginTrack(locEq(locs[0])); formatWriter.writeOpenSegment(); formatWriter.writeLocation(locEq(locs[0])); //EasyMock.expectLastCall().andThrow(new InterruptedException()); EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { throw new InterruptedException(); } }); mocksControl.replay(); writer.writeTrack(); mocksControl.verify(); assertFalse(writer.wasSuccess()); assertEquals(R.string.sd_card_canceled, writer.getErrorMessage()); } public void testWriteTrack_openFails() { writer = new WriteTracksTrackWriter(getContext(), providerUtils, track, formatWriter, false); // Expect the completion listener to be run TrackWriter.OnCompletionListener completionListener = mocksControl.createMock(TrackWriter.OnCompletionListener.class); completionListener.onComplete(); mocksControl.replay(); writer.setOnCompletionListener(completionListener); writer.writeTrack(); assertEquals(0, writeDocumentCalls); assertEquals(1, openFileCalls); mocksControl.verify(); } public void testOpenFile() { final ByteArrayOutputStream stream = new ByteArrayOutputStream(); writer = new OpenFileTrackWriter( getContext(), providerUtils, track, formatWriter, stream, true); formatWriter.prepare(track, stream); mocksControl.replay(); assertTrue(writer.openFile()); mocksControl.verify(); } public void testOpenFile_cantWrite() { final ByteArrayOutputStream stream = new ByteArrayOutputStream(); writer = new OpenFileTrackWriter( getContext(), providerUtils, track, formatWriter, stream, false); mocksControl.replay(); assertFalse(writer.openFile()); mocksControl.verify(); } public void testOpenFile_streamError() { writer = new OpenFileTrackWriter( getContext(), providerUtils, track, formatWriter, null, true); mocksControl.replay(); assertFalse(writer.openFile()); mocksControl.verify(); } public void testWriteDocument_emptyTrack() throws Exception { writer = new TrackWriterImpl(getContext(), providerUtils, track, formatWriter); // Set expected mock behavior formatWriter.writeHeader(); formatWriter.writeFooter(); formatWriter.close(); mocksControl.replay(); writer.writeDocument(); assertTrue(writer.wasSuccess()); mocksControl.verify(); } public void testWriteDocument() throws Exception { writer = new TrackWriterImpl(getContext(), providerUtils, track, formatWriter); final Location[] locs = { new Location("fake0"), new Location("fake1"), new Location("fake2"), new Location("fake3"), new Location("fake4"), new Location("fake5") }; Waypoint[] wps = { new Waypoint(), new Waypoint(), new Waypoint() }; // Fill locations with valid values fillLocations(locs); // Make location 3 invalid locs[2].setLatitude(100); assertEquals(locs.length, providerUtils.bulkInsertTrackPoints(locs, locs.length, TRACK_ID)); for (int i = 0; i < wps.length; ++i) { Waypoint wpt = wps[i]; wpt.setTrackId(TRACK_ID); assertNotNull(providerUtils.insertWaypoint(wpt)); wpt.setId(i + 1); } formatWriter.writeHeader(); // Expect reading/writing of the waypoints (except the first) formatWriter.writeWaypoint(wptEq(wps[1])); formatWriter.writeWaypoint(wptEq(wps[2])); // Begin the track formatWriter.writeBeginTrack(locEq(locs[0])); // Write locations 1-2 formatWriter.writeOpenSegment(); formatWriter.writeLocation(locEq(locs[0])); formatWriter.writeLocation(locEq(locs[1])); formatWriter.writeCloseSegment(); // Location 3 is not written - it's invalid // Write locations 4-6 formatWriter.writeOpenSegment(); formatWriter.writeLocation(locEq(locs[3])); formatWriter.writeLocation(locEq(locs[4])); formatWriter.writeLocation(locEq(locs[5])); formatWriter.writeCloseSegment(); // End the track formatWriter.writeEndTrack(locEq(locs[5])); formatWriter.writeFooter(); formatWriter.close(); mocksControl.replay(); writer.writeDocument(); assertTrue(writer.wasSuccess()); mocksControl.verify(); } private static Waypoint wptEq(final Waypoint wpt) { EasyMock.reportMatcher(new IArgumentMatcher() { @Override public boolean matches(Object wptObj2) { if (wptObj2 == null || wpt == null) return wpt == wptObj2; Waypoint wpt2 = (Waypoint) wptObj2; return wpt.getId() == wpt2.getId(); } @Override public void appendTo(StringBuffer buffer) { buffer.append("wptEq("); buffer.append(wpt); buffer.append(")"); } }); return null; } private static Location locEq(final Location loc) { EasyMock.reportMatcher(new IArgumentMatcher() { @Override public boolean matches(Object locObj2) { if (locObj2 == null || loc == null) return loc == locObj2; Location loc2 = (Location) locObj2; return loc.hasAccuracy() == loc2.hasAccuracy() && (!loc.hasAccuracy() || loc.getAccuracy() == loc2.getAccuracy()) && loc.hasAltitude() == loc2.hasAltitude() && (!loc.hasAltitude() || loc.getAltitude() == loc2.getAltitude()) && loc.hasBearing() == loc2.hasBearing() && (!loc.hasBearing() || loc.getBearing() == loc2.getBearing()) && loc.hasSpeed() == loc2.hasSpeed() && (!loc.hasSpeed() || loc.getSpeed() == loc2.getSpeed()) && loc.getLatitude() == loc2.getLatitude() && loc.getLongitude() == loc2.getLongitude() && loc.getTime() == loc2.getTime(); } @Override public void appendTo(StringBuffer buffer) { buffer.append("locEq("); buffer.append(loc); buffer.append(")"); } }); return null; } private void fillLocations(Location... locs) { assertTrue(locs.length < 90); for (int i = 0; i < locs.length; i++) { Location location = locs[i]; location.setLatitude(i + 1); location.setLongitude(i + 1); location.setTime(i + 1000); } } }
Java
package com.dsi.ant.exception; public class AntInterfaceException extends Exception { /** * */ private static final long serialVersionUID = -7278855366167722274L; public AntInterfaceException() { this("Unknown ANT Interface error"); } public AntInterfaceException(String string) { super(string); } }
Java
package com.dsi.ant.exception; import android.os.RemoteException; public class AntRemoteException extends AntInterfaceException { /** * */ private static final long serialVersionUID = 8950974759973459561L; public AntRemoteException(RemoteException e) { this("ANT Interface error, ANT Radio Service remote error: "+e.toString(), e); } public AntRemoteException(String string, RemoteException e) { super(string); this.initCause(e); } }
Java
package com.dsi.ant.exception; public class AntServiceNotConnectedException extends AntInterfaceException { /** * */ private static final long serialVersionUID = -2085081032170129309L; public AntServiceNotConnectedException() { this("ANT Interface error, ANT Radio Service not connected."); } public AntServiceNotConnectedException(String string) { super(string); } }
Java
/* * Copyright 2011 Dynastream Innovations Inc. * * 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.dsi.ant; /** * Defines version numbers * * @hide */ public class Version { ////////////////////////////////////////////// // Library Version Information ////////////////////////////////////////////// public static final int ANT_LIBRARY_VERSION_CODE = 6; public static final int ANT_LIBRARY_VERSION_MAJOR = 2; public static final int ANT_LIBRARY_VERSION_MINOR = 0; public static final String ANT_LIBRARY_VERSION_NAME = String.valueOf(ANT_LIBRARY_VERSION_MAJOR) + "." + String.valueOf(ANT_LIBRARY_VERSION_MINOR); }
Java
/* * Copyright 2010 Dynastream Innovations Inc. * * 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.dsi.ant; /** * The Android Ant API is not finalized, and *will* change. Use at your * own risk. * * Public API for controlling the Ant Service. * AntDefines contains definitions commonly used in ANT messaging. * * @hide */ public class AntDefine { ////////////////////////////////////////////// // Valid Configuration Values ////////////////////////////////////////////// public static final byte MIN_BIN = 0; public static final byte MAX_BIN = 10; public static final short MIN_DEVICE_ID = 0; public static final short MAX_DEVICE_ID = (short)65535; public static final short MIN_BUFFER_THRESHOLD = 0; public static final short MAX_BUFFER_THRESHOLD = 996; ////////////////////////////////////////////// // ANT Message Payload Size ////////////////////////////////////////////// public static final byte ANT_STANDARD_DATA_PAYLOAD_SIZE =((byte)8); ////////////////////////////////////////////// // ANT LIBRARY Extended Data Message Fields // NOTE: You must check the extended message // bitfield first to find out which fields // are present before accessing them! ////////////////////////////////////////////// public static final byte ANT_EXT_MESG_DEVICE_ID_FIELD_SIZE =((byte)4); //public static final byte ANT_EXT_STRING_SIZE =((byte)19); // this is the additional buffer space required required for setting USB Descriptor strings public static final byte ANT_EXT_STRING_SIZE =((byte)0); // changed to 0 as we will not be dealing with ANT USB parts. ////////////////////////////////////////////// // ANT Extended Data Message Bifield Definitions ////////////////////////////////////////////// public static final byte ANT_EXT_MESG_BITFIELD_DEVICE_ID =((byte)0x80); // first field after bitfield public static final byte ANT_EXT_MESG_BITFIELD_RSSI =((byte)0x40); // next field after ID, if there is one public static final byte ANT_EXT_MESG_BITFIELD_TIME_STAMP =((byte)0x20); // next field after RSSI, if there is one // 4 bits free reserved set to 0 public static final byte ANT_EXT_MESG_BIFIELD_EXTENSION =((byte)0x01); // extended message input bitfield defines public static final byte ANT_EXT_MESG_BITFIELD_OVERWRITE_SHARED_ADR =((byte)0x10); public static final byte ANT_EXT_MESG_BITFIELD_TRANSMISSION_TYPE =((byte)0x08); ////////////////////////////////////////////// // ID Definitions ////////////////////////////////////////////// public static final byte ANT_ID_SIZE =((byte)4); public static final byte ANT_ID_TRANS_TYPE_OFFSET =((byte)3); public static final byte ANT_ID_DEVICE_TYPE_OFFSET =((byte)2); public static final byte ANT_ID_DEVICE_NUMBER_HIGH_OFFSET =((byte)1); public static final byte ANT_ID_DEVICE_NUMBER_LOW_OFFSET =((byte)0); public static final byte ANT_ID_DEVICE_TYPE_PAIRING_FLAG =((byte)0x80); public static final byte ANT_TRANS_TYPE_SHARED_ADDR_MASK =((byte)0x03); public static final byte ANT_TRANS_TYPE_1_BYTE_SHARED_ADDRESS =((byte)0x02); public static final byte ANT_TRANS_TYPE_2_BYTE_SHARED_ADDRESS =((byte)0x03); ////////////////////////////////////////////// // Assign Channel Parameters ////////////////////////////////////////////// public static final byte PARAMETER_RX_NOT_TX =((byte)0x00); public static final byte PARAMETER_TX_NOT_RX =((byte)0x10); public static final byte PARAMETER_SHARED_CHANNEL =((byte)0x20); public static final byte PARAMETER_NO_TX_GUARD_BAND =((byte)0x40); public static final byte PARAMETER_ALWAYS_RX_WILD_CARD_SEARCH_ID =((byte)0x40); //Pre-AP2 public static final byte PARAMETER_RX_ONLY =((byte)0x40); ////////////////////////////////////////////// // Ext. Assign Channel Parameters ////////////////////////////////////////////// public static final byte EXT_PARAM_ALWAYS_SEARCH =((byte)0x01); public static final byte EXT_PARAM_FREQUENCY_AGILITY =((byte)0x04); ////////////////////////////////////////////// // Radio TX Power Definitions ////////////////////////////////////////////// public static final byte RADIO_TX_POWER_LVL_MASK =((byte)0x03); public static final byte RADIO_TX_POWER_LVL_0 =((byte)0x00); //(formerly: RADIO_TX_POWER_MINUS20DB); lowest public static final byte RADIO_TX_POWER_LVL_1 =((byte)0x01); //(formerly: RADIO_TX_POWER_MINUS10DB); public static final byte RADIO_TX_POWER_LVL_2 =((byte)0x02); //(formerly: RADIO_TX_POWER_MINUS5DB); public static final byte RADIO_TX_POWER_LVL_3 =((byte)0x03); //(formerly: RADIO_TX_POWER_0DB); highest ////////////////////////////////////////////// // Channel Status ////////////////////////////////////////////// public static final byte STATUS_CHANNEL_STATE_MASK =((byte)0x03); public static final byte STATUS_UNASSIGNED_CHANNEL =((byte)0x00); public static final byte STATUS_ASSIGNED_CHANNEL =((byte)0x01); public static final byte STATUS_SEARCHING_CHANNEL =((byte)0x02); public static final byte STATUS_TRACKING_CHANNEL =((byte)0x03); ////////////////////////////////////////////// // Standard capabilities defines ////////////////////////////////////////////// public static final byte CAPABILITIES_NO_RX_CHANNELS =((byte)0x01); public static final byte CAPABILITIES_NO_TX_CHANNELS =((byte)0x02); public static final byte CAPABILITIES_NO_RX_MESSAGES =((byte)0x04); public static final byte CAPABILITIES_NO_TX_MESSAGES =((byte)0x08); public static final byte CAPABILITIES_NO_ACKD_MESSAGES =((byte)0x10); public static final byte CAPABILITIES_NO_BURST_TRANSFER =((byte)0x20); ////////////////////////////////////////////// // Advanced capabilities defines ////////////////////////////////////////////// public static final byte CAPABILITIES_OVERUN_UNDERRUN =((byte)0x01); // Support for this functionality has been dropped public static final byte CAPABILITIES_NETWORK_ENABLED =((byte)0x02); public static final byte CAPABILITIES_AP1_VERSION_2 =((byte)0x04); // This Version of the AP1 does not support transmit and only had a limited release public static final byte CAPABILITIES_SERIAL_NUMBER_ENABLED =((byte)0x08); public static final byte CAPABILITIES_PER_CHANNEL_TX_POWER_ENABLED =((byte)0x10); public static final byte CAPABILITIES_LOW_PRIORITY_SEARCH_ENABLED =((byte)0x20); public static final byte CAPABILITIES_SCRIPT_ENABLED =((byte)0x40); public static final byte CAPABILITIES_SEARCH_LIST_ENABLED =((byte)0x80); ////////////////////////////////////////////// // Advanced capabilities 2 defines ////////////////////////////////////////////// public static final byte CAPABILITIES_LED_ENABLED =((byte)0x01); public static final byte CAPABILITIES_EXT_MESSAGE_ENABLED =((byte)0x02); public static final byte CAPABILITIES_SCAN_MODE_ENABLED =((byte)0x04); public static final byte CAPABILITIES_RESERVED =((byte)0x08); public static final byte CAPABILITIES_PROX_SEARCH_ENABLED =((byte)0x10); public static final byte CAPABILITIES_EXT_ASSIGN_ENABLED =((byte)0x20); public static final byte CAPABILITIES_FREE_1 =((byte)0x40); public static final byte CAPABILITIES_FIT1_ENABLED =((byte)0x80); ////////////////////////////////////////////// // Advanced capabilities 3 defines ////////////////////////////////////////////// public static final byte CAPABILITIES_SENSRCORE_ENABLED =((byte)0x01); public static final byte CAPABILITIES_RESERVED_1 =((byte)0x02); public static final byte CAPABILITIES_RESERVED_2 =((byte)0x04); public static final byte CAPABILITIES_RESERVED_3 =((byte)0x08); ////////////////////////////////////////////// // Burst Message Sequence ////////////////////////////////////////////// public static final byte CHANNEL_NUMBER_MASK =((byte)0x1F); public static final byte SEQUENCE_NUMBER_MASK =((byte)0xE0); public static final byte SEQUENCE_NUMBER_ROLLOVER =((byte)0x60); public static final byte SEQUENCE_FIRST_MESSAGE =((byte)0x00); public static final byte SEQUENCE_LAST_MESSAGE =((byte)0x80); public static final byte SEQUENCE_NUMBER_INC =((byte)0x20); ////////////////////////////////////////////// // Control Message Flags ////////////////////////////////////////////// public static final byte BROADCAST_CONTROL_BYTE =((byte)0x00); public static final byte ACKNOWLEDGED_CONTROL_BYTE =((byte)0xA0); ////////////////////////////////////////////// // Response / Event Codes ////////////////////////////////////////////// public static final byte RESPONSE_NO_ERROR =((byte)0x00); public static final byte NO_EVENT =((byte)0x00); public static final byte EVENT_RX_SEARCH_TIMEOUT =((byte)0x01); public static final byte EVENT_RX_FAIL =((byte)0x02); public static final byte EVENT_TX =((byte)0x03); public static final byte EVENT_TRANSFER_RX_FAILED =((byte)0x04); public static final byte EVENT_TRANSFER_TX_COMPLETED =((byte)0x05); public static final byte EVENT_TRANSFER_TX_FAILED =((byte)0x06); public static final byte EVENT_CHANNEL_CLOSED =((byte)0x07); public static final byte EVENT_RX_FAIL_GO_TO_SEARCH =((byte)0x08); public static final byte EVENT_CHANNEL_COLLISION =((byte)0x09); public static final byte EVENT_TRANSFER_TX_START =((byte)0x0A); // a pending transmit transfer has begun public static final byte EVENT_CHANNEL_ACTIVE =((byte)0x0F); public static final byte EVENT_TRANSFER_TX_NEXT_MESSAGE =((byte)0x11); // only enabled in FIT1 public static final byte CHANNEL_IN_WRONG_STATE =((byte)0x15); // returned on attempt to perform an action from the wrong channel state public static final byte CHANNEL_NOT_OPENED =((byte)0x16); // returned on attempt to communicate on a channel that is not open public static final byte CHANNEL_ID_NOT_SET =((byte)0x18); // returned on attempt to open a channel without setting the channel ID public static final byte CLOSE_ALL_CHANNELS =((byte)0x19); // returned when attempting to start scanning mode, when channels are still open public static final byte TRANSFER_IN_PROGRESS =((byte)0x1F); // returned on attempt to communicate on a channel with a TX transfer in progress public static final byte TRANSFER_SEQUENCE_NUMBER_ERROR =((byte)0x20); // returned when sequence number is out of order on a Burst transfer public static final byte TRANSFER_IN_ERROR =((byte)0x21); public static final byte TRANSFER_BUSY =((byte)0x22); public static final byte INVALID_MESSAGE_CRC =((byte)0x26); // returned if there is a framing error on an incomming message public static final byte MESSAGE_SIZE_EXCEEDS_LIMIT =((byte)0x27); // returned if a data message is provided that is too large public static final byte INVALID_MESSAGE =((byte)0x28); // returned when the message has an invalid parameter public static final byte INVALID_NETWORK_NUMBER =((byte)0x29); // returned when an invalid network number is provided public static final byte INVALID_LIST_ID =((byte)0x30); // returned when the provided list ID or size exceeds the limit public static final byte INVALID_SCAN_TX_CHANNEL =((byte)0x31); // returned when attempting to transmit on channel 0 when in scan mode public static final byte INVALID_PARAMETER_PROVIDED =((byte)0x33); // returned when an invalid parameter is specified in a configuration message public static final byte EVENT_SERIAL_QUE_OVERFLOW =((byte)0x34); public static final byte EVENT_QUE_OVERFLOW =((byte)0x35); // ANT event que has overflowed and lost 1 or more events public static final byte EVENT_CLK_ERROR =((byte)0x36); // debug event for XOSC16M on LE1 public static final byte SCRIPT_FULL_ERROR =((byte)0x40); // error writing to script, memory is full public static final byte SCRIPT_WRITE_ERROR =((byte)0x41); // error writing to script, bytes not written correctly public static final byte SCRIPT_INVALID_PAGE_ERROR =((byte)0x42); // error accessing script page public static final byte SCRIPT_LOCKED_ERROR =((byte)0x43); // the scripts are locked and can't be dumped public static final byte NO_RESPONSE_MESSAGE =((byte)0x50); // returned to the Command_SerialMessageProcess function, so no reply message is generated public static final byte RETURN_TO_MFG =((byte)0x51); // default return to any mesg when the module determines that the mfg procedure has not been fully completed public static final byte FIT_ACTIVE_SEARCH_TIMEOUT =((byte)0x60); // Fit1 only event added for timeout of the pairing state after the Fit module becomes active public static final byte FIT_WATCH_PAIR =((byte)0x61); // Fit1 only public static final byte FIT_WATCH_UNPAIR =((byte)0x62); // Fit1 only public static final byte USB_STRING_WRITE_FAIL =((byte)0x70); // Internal only events below this point public static final byte INTERNAL_ONLY_EVENTS =((byte)0x80); public static final byte EVENT_RX =((byte)0x80); // INTERNAL: Event for a receive message public static final byte EVENT_NEW_CHANNEL =((byte)0x81); // INTERNAL: EVENT for a new active channel public static final byte EVENT_PASS_THRU =((byte)0x82); // INTERNAL: Event to allow an upper stack events to pass through lower stacks public static final byte EVENT_BLOCKED =((byte)0xFF); // INTERNAL: Event to replace any event we do not wish to go out, will also zero the size of the Tx message /////////////////////////////////////////////////////// // Script Command Codes /////////////////////////////////////////////////////// public static final byte SCRIPT_CMD_FORMAT =((byte)0x00); public static final byte SCRIPT_CMD_DUMP =((byte)0x01); public static final byte SCRIPT_CMD_SET_DEFAULT_SECTOR =((byte)0x02); public static final byte SCRIPT_CMD_END_SECTOR =((byte)0x03); public static final byte SCRIPT_CMD_END_DUMP =((byte)0x04); public static final byte SCRIPT_CMD_LOCK =((byte)0x05); /////////////////////////////////////////////////////// // Reset Mesg Codes /////////////////////////////////////////////////////// public static final byte RESET_FLAGS_MASK =((byte)0xE0); public static final byte RESET_SUSPEND =((byte)0x80); // this must follow bitfield def public static final byte RESET_SYNC =((byte)0x40); // this must follow bitfield def public static final byte RESET_CMD =((byte)0x20); // this must follow bitfield def public static final byte RESET_WDT =((byte)0x02); public static final byte RESET_RST =((byte)0x01); public static final byte RESET_POR =((byte)0x00); }
Java
/* * Copyright 2010 Dynastream Innovations Inc. * * 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.dsi.ant; import com.dsi.ant.exception.AntInterfaceException; import com.dsi.ant.exception.AntRemoteException; import com.dsi.ant.exception.AntServiceNotConnectedException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.net.Uri; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import java.util.Arrays; /** * Public API for controlling the Ant Service. AntInterface is a proxy * object for controlling the Ant Service via IPC. Creating a AntInterface * object will create a binding with the Ant service. * * @hide */ public class AntInterface { /** The Log Tag. */ public static final String TAG = "ANTInterface"; /** Enable debug logging. */ public static boolean DEBUG = false; /** Search string to find ANT Radio Proxy Service in the Android Marketplace */ private static final String MARKET_SEARCH_TEXT_DEFAULT = "ANT Radio Service Dynastream Innovations Inc"; /** Name of the ANT Radio shared library */ private static final String ANT_LIBRARY_NAME = "com.dsi.ant.antradio_library"; /** Inter-process communication with the ANT Radio Proxy Service. */ private static IAnt_6 sAntReceiver = null; /** Singleton instance of this class. */ private static AntInterface INSTANCE; /** Used when obtaining a reference to the singleton instance. */ private static Object INSTANCE_LOCK = new Object(); /** The context to use. */ private Context sContext = null; /** Listens to changes to service connection status. */ private ServiceListener sServiceListener; /** Is the ANT Radio Proxy Service connected. */ private static boolean sServiceConnected = false; /** The version code (eg. 1) of ANTLib used by the ANT application service */ private static int mServiceLibraryVersionCode = 0; /** Has support for ANT already been checked */ private static boolean mCheckedAntSupported = false; /** Is ANT supported on this device */ private static boolean mAntSupported = false; /** * An interface for notifying AntInterface IPC clients when they have * been connected to the ANT service. * * @see ServiceEvent */ public interface ServiceListener { /** * Called to notify the client when this proxy object has been * connected to the ANT service. Clients must wait for * this callback before making IPC calls on the ANT * service. */ public void onServiceConnected(); /** * Called to notify the client that this proxy object has been * disconnected from the ANT service. Clients must not * make IPC calls on the ANT service after this callback. * This callback will currently only occur if the application hosting * the BluetoothAg service, but may be called more often in future. */ public void onServiceDisconnected(); } //Constructor /** * Instantiates a new ant interface. * * @param context the context * @param listener the listener * @since 1.0 */ private AntInterface(Context context, ServiceListener listener) { // This will be around as long as this process is sContext = context; sServiceListener = listener; } /** * Gets the single instance of AntInterface, creating it if it doesn't exist. * Only the initial request for an instance will have context and listener set to the requested objects. * * @param context the context used to bind to the remote service. * @param listener the listener to be notified of status changes. * @return the AntInterface instance. * @since 1.0 */ public static AntInterface getInstance(Context context,ServiceListener listener) { if(DEBUG) Log.d(TAG, "getInstance"); synchronized (INSTANCE_LOCK) { if(!hasAntSupport(context)) { if(DEBUG) Log.d(TAG, "getInstance: ANT not supported"); return null; } if (INSTANCE == null) { if(DEBUG) Log.d(TAG, "getInstance: Creating new instance"); INSTANCE = new AntInterface(context,listener); } else { if(DEBUG) Log.d(TAG, "getInstance: Using existing instance"); } if(!sServiceConnected) { if(DEBUG) Log.d(TAG, "getInstance: No connection to proxy service, attempting connection"); if(!INSTANCE.initService()) { Log.e(TAG, "getInstance: No connection to proxy service"); INSTANCE.destroy(); INSTANCE = null; } } return INSTANCE; } } /** * Go to market. * * @param pContext the context * @param pSearchText the search text * @since 1.2 */ public static void goToMarket(Context pContext, String pSearchText) { if(null == pSearchText) { goToMarket(pContext); } else { if(DEBUG) Log.i(TAG, "goToMarket: Search text = "+ pSearchText); Intent goToMarket = null; goToMarket = new Intent(Intent.ACTION_VIEW,Uri.parse("http://market.android.com/search?q=" + pSearchText)); goToMarket.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); pContext.startActivity(goToMarket); } } /** * Go to market. * * @param pContext the context * @since 1.2 */ public static void goToMarket(Context pContext) { if(DEBUG) Log.d(TAG, "goToMarket"); goToMarket(pContext, MARKET_SEARCH_TEXT_DEFAULT); } /** * Class for interacting with the ANT interface. */ private final ServiceConnection sIAntConnection = new ServiceConnection() { public void onServiceConnected(ComponentName pClassName, IBinder pService) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. We are communicating with our // service through an IDL interface, so get a client-side // representation of that from the raw service object. if(DEBUG) Log.d(TAG, "sIAntConnection onServiceConnected()"); sAntReceiver = IAnt_6.Stub.asInterface(pService); sServiceConnected = true; // Notify the attached application if it is registered if (sServiceListener != null) { sServiceListener.onServiceConnected(); } else { if(DEBUG) Log.d(TAG, "sIAntConnection onServiceConnected: No service listener registered"); } } public void onServiceDisconnected(ComponentName pClassName) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. if(DEBUG) Log.d(TAG, "sIAntConnection onServiceDisconnected()"); sAntReceiver = null; sServiceConnected = false; mServiceLibraryVersionCode = 0; // Notify the attached application if it is registered if (sServiceListener != null) { sServiceListener.onServiceDisconnected(); } else { if(DEBUG) Log.d(TAG, "sIAntConnection onServiceDisconnected: No service listener registered"); } // Try and rebind to the service INSTANCE.releaseService(); INSTANCE.initService(); } }; /** * Binds this activity to the ANT service. * * @return true, if successful */ private boolean initService() { if(DEBUG) Log.d(TAG, "initService() entered"); boolean ret = false; if(!sServiceConnected) { ret = sContext.bindService(new Intent(IAnt_6.class.getName()), sIAntConnection, Context.BIND_AUTO_CREATE); if(DEBUG) Log.i(TAG, "initService(): Bound with ANT service: " + ret); } else { if(DEBUG) Log.d(TAG, "initService: already initialised service"); ret = true; } return ret; } /** Unbinds this activity from the ANT service. */ private void releaseService() { if(DEBUG) Log.d(TAG, "releaseService() entered"); // TODO Make sure can handle multiple calls to onDestroy if(sServiceConnected) { sContext.unbindService(sIAntConnection); sServiceConnected = false; } if(DEBUG) Log.d(TAG, "releaseService() unbound."); } /** * True if this activity can communicate with the ANT service. * * @return true, if service is connected * @since 1.2 */ public boolean isServiceConnected() { return sServiceConnected; } /** * Destroy. * * @return true, if successful * @since 1.0 */ public boolean destroy() { if(DEBUG) Log.d(TAG, "destroy"); releaseService(); INSTANCE = null; return true; } ////------------------------------------------------- /** * Enable. * * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void enable() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.enable()) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Disable. * * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void disable() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.disable()) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Checks if is enabled. * * @return true, if is enabled. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public boolean isEnabled() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.isEnabled(); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT tx message. * * @param message the message * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTTxMessage(byte[] message) throws AntInterfaceException { if(DEBUG) Log.d(TAG, "ANTTxMessage"); if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTTxMessage(message)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT reset system. * * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTResetSystem() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTResetSystem()) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT unassign channel. * * @param channelNumber the channel number * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTUnassignChannel(byte channelNumber) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTUnassignChannel(channelNumber)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT assign channel. * * @param channelNumber the channel number * @param channelType the channel type * @param networkNumber the network number * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTAssignChannel(byte channelNumber, byte channelType, byte networkNumber) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTAssignChannel(channelNumber, channelType, networkNumber)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT set channel id. * * @param channelNumber the channel number * @param deviceNumber the device number * @param deviceType the device type * @param txType the tx type * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSetChannelId(byte channelNumber, short deviceNumber, byte deviceType, byte txType) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSetChannelId(channelNumber, deviceNumber, deviceType, txType)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT set channel period. * * @param channelNumber the channel number * @param channelPeriod the channel period * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSetChannelPeriod(byte channelNumber, short channelPeriod) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSetChannelPeriod(channelNumber, channelPeriod)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT set channel rf freq. * * @param channelNumber the channel number * @param radioFrequency the radio frequency * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSetChannelRFFreq(byte channelNumber, byte radioFrequency) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSetChannelRFFreq(channelNumber, radioFrequency)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT set channel search timeout. * * @param channelNumber the channel number * @param searchTimeout the search timeout * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSetChannelSearchTimeout(byte channelNumber, byte searchTimeout) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSetChannelSearchTimeout(channelNumber, searchTimeout)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT set low priority channel search timeout. * * @param channelNumber the channel number * @param searchTimeout the search timeout * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSetLowPriorityChannelSearchTimeout(byte channelNumber, byte searchTimeout) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSetLowPriorityChannelSearchTimeout(channelNumber, searchTimeout)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT set proximity search. * * @param channelNumber the channel number * @param searchThreshold the search threshold * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSetProximitySearch(byte channelNumber, byte searchThreshold) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSetProximitySearch(channelNumber, searchThreshold)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT set channel transmit power * @param channelNumber the channel number * @param txPower the transmit power level * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSetChannelTxPower(byte channelNumber, byte txPower) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSetChannelTxPower(channelNumber, txPower)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT add channel id. * * @param channelNumber the channel number * @param deviceNumber the device number * @param deviceType the device type * @param txType the tx type * @param listIndex the list index * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTAddChannelId(byte channelNumber, short deviceNumber, byte deviceType, byte txType, byte listIndex) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTAddChannelId(channelNumber, deviceNumber, deviceType, txType, listIndex)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT config list. * * @param channelNumber the channel number * @param listSize the list size * @param exclude the exclude * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTConfigList(byte channelNumber, byte listSize, byte exclude) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTConfigList(channelNumber, listSize, exclude)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT config event buffering. * * @param screenOnFlushTimerInterval the screen on flush timer interval * @param screenOnFlushBufferThreshold the screen on flush buffer threshold * @param screenOffFlushTimerInterval the screen off flush timer interval * @param screenOffFlushBufferThreshold the screen off flush buffer threshold * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.3 */ public void ANTConfigEventBuffering(short screenOnFlushTimerInterval, short screenOnFlushBufferThreshold, short screenOffFlushTimerInterval, short screenOffFlushBufferThreshold) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTConfigEventBuffering((int)screenOnFlushTimerInterval, (int)screenOnFlushBufferThreshold, (int)screenOffFlushTimerInterval, (int)screenOffFlushBufferThreshold)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT disable event buffering. * * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.1 */ public void ANTDisableEventBuffering() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTDisableEventBuffering()) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT open channel. * * @param channelNumber the channel number * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTOpenChannel(byte channelNumber) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTOpenChannel(channelNumber)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT close channel. * * @param channelNumber the channel number * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTCloseChannel(byte channelNumber) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTCloseChannel(channelNumber)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT request message. * * @param channelNumber the channel number * @param messageID the message id * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTRequestMessage(byte channelNumber, byte messageID) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTRequestMessage(channelNumber, messageID)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT send broadcast data. * * @param channelNumber the channel number * @param txBuffer the tx buffer * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSendBroadcastData(byte channelNumber, byte[] txBuffer) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSendBroadcastData(channelNumber, txBuffer)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT send acknowledged data. * * @param channelNumber the channel number * @param txBuffer the tx buffer * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSendAcknowledgedData(byte channelNumber, byte[] txBuffer) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSendAcknowledgedData(channelNumber, txBuffer)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT send burst transfer packet. * * @param control the control * @param txBuffer the tx buffer * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSendBurstTransferPacket(byte control, byte[] txBuffer) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSendBurstTransferPacket(control, txBuffer)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Transmits the given data on channelNumber as part of a burst message. * * @param channelNumber Which channel to transmit on. * @param txBuffer The data to send. * @param initialPacket Which packet in the burst sequence does the data begin in, 1 is the first. * @param containsEndOfBurst Is this the last of the data to be sent in burst. * @return The number of bytes still to be sent (approximately). 0 if success. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException */ public int ANTSendBurstTransfer(byte channelNumber, byte[] txBuffer) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.ANTSendBurstTransfer(channelNumber, txBuffer); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT send partial burst. * * @param channelNumber the channel number * @param txBuffer the tx buffer * @param initialPacket the initial packet * @param containsEndOfBurst the contains end of burst * @return The number of bytes still to be sent (approximately). 0 if success. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public int ANTSendPartialBurst(byte channelNumber, byte[] txBuffer, int initialPacket, boolean containsEndOfBurst) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.ANTTransmitBurst(channelNumber, txBuffer, initialPacket, containsEndOfBurst); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Returns the version code (eg. 1) of ANTLib used by the ANT application service * * @return the service library version code, or 0 on error. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.2 */ public int getServiceLibraryVersionCode() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } if(mServiceLibraryVersionCode == 0) { try { mServiceLibraryVersionCode = sAntReceiver.getServiceLibraryVersionCode(); } catch(RemoteException e) { throw new AntRemoteException(e); } } return mServiceLibraryVersionCode; } /** * Returns the version name (eg "1.0") of ANTLib used by the ANT application service * * @return the service library version name, or null on error. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.2 */ public String getServiceLibraryVersionName() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.getServiceLibraryVersionName(); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Take control of the ANT Radio. * * @return True if control has been granted, false if another application has control or the request failed. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.5 */ public boolean claimInterface() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.claimInterface(); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Give up control of the ANT Radio. * * @return True if control has been given up, false if this application did not have control. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.5 */ public boolean releaseInterface() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.releaseInterface(); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Claims the interface if it is available. If not the user will be prompted (on the notification bar) if a force claim should be done. * If the ANT Interface is claimed, an AntInterfaceIntent.ANT_INTERFACE_CLAIMED_ACTION intent will be sent, with the current applications pid. * * @param String appName The name if this application, to show to the user. * @returns false if a claim interface request notification already exists. * @throws IllegalArgumentException * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.5 */ public boolean requestForceClaimInterface(String appName) throws AntInterfaceException { if((null == appName) || ("".equals(appName))) { throw new IllegalArgumentException(); } if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.requestForceClaimInterface(appName); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Clears the notification asking the user if they would like to seize control of the ANT Radio. * * @returns false if this process is not requesting to claim the interface. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.5 */ public boolean stopRequestForceClaimInterface() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.stopRequestForceClaimInterface(); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Check if the calling application has control of the ANT Radio. * * @return True if control is currently granted. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.5 */ public boolean hasClaimedInterface() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.hasClaimedInterface(); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Check if this device has support for ANT. * * @return True if the device supports ANT (may still require ANT Radio Service be installed). * @since 1.5 */ public static boolean hasAntSupport(Context pContext) { if(!mCheckedAntSupported) { mAntSupported = Arrays.asList(pContext.getPackageManager().getSystemSharedLibraryNames()).contains(ANT_LIBRARY_NAME); mCheckedAntSupported = true; } return mAntSupported; } }
Java
/* * Copyright 2010 Dynastream Innovations Inc. * * 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.dsi.ant; /** * Public API for controlling the Ant Service. * AntMesg contains definitions for ANT message IDs * * @hide */ public class AntMesg { ///////////////////////////////////////////////////////////////////////////// // HCI VS Message Format // Messages are in the format: // // Outgoing ANT messages (host -> ANT chip) // 01 D1 FD XX YY YY II JJ ------ // ^ ^ ^ ^ // | HCI framing | | ANT Mesg | // // where: 01 is the 1 byte HCI packet Identifier (HCI Command packet) // D1 FD is the 2 byte HCI op code (0xFDD1 stored in little endian) // XX is the 1 byte Length of all parameters in bytes (number of bytes in the HCI packet after this byte) // YY YY is the 2 byte Parameter describing the length of the entire ANT message (II JJ ------) stored in little endian // II is the 1 byte size of the ANT message (0-249) // JJ is the 1 byte ID of the ANT message (1-255, 0 is invalid) // ------ is the data of the ANT message (0-249 bytes of data) // // Incoming HCI Command Complete for ANT message command (host <- ANT chip) // 04 0E 04 01 D1 FD ZZ // // where: 04 is the 1 byte HCI packet Identifier (HCI Event packet) // 0E is the 1 byte HCI event (Command Complete) // 04 is the 1 byte Length of all parameters in bytes (there are 4 bytes) // 01 is the 1 byte Number of parameters in the packet (there is 1 parameter) // D1 FD is the 2 byte HCI Op code of the command (0xFDD1 stored in little endian) // ZZ is the 1 byte response to the command (0x00 - Command Successful // 0x1F - Returned if the receive message queue of the ANT chip is full, the command should be retried // Other - Any other non-zero response code indicates an error) // // Incoming ANT messages (host <- ANT chip) // 04 FF XX 00 05 YY YY II JJ ------ // ^ ^ ^ ^ // | HCI framing | | ANT Mesg | // // where: 04 is the 1 byte HCI packet Identifier (HCI Event packet) // FF is the 1 byte HCI event code (0xFF Vendor Specific event) // XX is the 1 byte Length of all parameters in bytes (number of bytes in the HCI packet after this byte) // 00 05 is the 2 byte vendor specific event code for ANT messages (0x0500 stored in little endian) // YY YY is the 2 byte Parameter describing the length of the entire ANT message (II JJ ------) stored in little endian // II is the 1 byte size of the ANT message (0-249) // JJ is the 1 byte ID of the ANT message (1-255, 0 is invalid) // ------ is the data of the ANT message (0-249 bytes of data) // ///////////////////////////////////////////////////////////////////////////// public static final byte MESG_SYNC_SIZE =((byte)0); // Ant messages are embedded in HCI messages we do not include a sync byte public static final byte MESG_SIZE_SIZE =((byte)1); public static final byte MESG_ID_SIZE =((byte)1); public static final byte MESG_CHANNEL_NUM_SIZE =((byte)1); public static final byte MESG_EXT_MESG_BF_SIZE =((byte)1); // NOTE: this could increase in the future public static final byte MESG_CHECKSUM_SIZE =((byte)0); // Ant messages are embedded in HCI messages we do not include a checksum public static final byte MESG_DATA_SIZE =((byte)9); // The largest serial message is an ANT data message with all of the extended fields public static final byte MESG_ANT_MAX_PAYLOAD_SIZE =AntDefine.ANT_STANDARD_DATA_PAYLOAD_SIZE; public static final byte MESG_MAX_EXT_DATA_SIZE =(AntDefine.ANT_EXT_MESG_DEVICE_ID_FIELD_SIZE + AntDefine.ANT_EXT_STRING_SIZE); // ANT device ID (4 bytes) + Padding for ANT EXT string size(19 bytes) public static final byte MESG_MAX_DATA_SIZE =(MESG_ANT_MAX_PAYLOAD_SIZE + MESG_EXT_MESG_BF_SIZE + MESG_MAX_EXT_DATA_SIZE); // ANT data payload (8 bytes) + extended bitfield (1 byte) + extended data (10 bytes) public static final byte MESG_MAX_SIZE_VALUE =(MESG_MAX_DATA_SIZE + MESG_CHANNEL_NUM_SIZE); // this is the maximum value that the serial message size value is allowed to be public static final byte MESG_BUFFER_SIZE =(MESG_SIZE_SIZE + MESG_ID_SIZE + MESG_CHANNEL_NUM_SIZE + MESG_MAX_DATA_SIZE + MESG_CHECKSUM_SIZE); public static final byte MESG_FRAMED_SIZE =(MESG_ID_SIZE + MESG_CHANNEL_NUM_SIZE + MESG_MAX_DATA_SIZE); public static final byte MESG_HEADER_SIZE =(MESG_SYNC_SIZE + MESG_SIZE_SIZE + MESG_ID_SIZE); public static final byte MESG_FRAME_SIZE =(MESG_HEADER_SIZE + MESG_CHECKSUM_SIZE); public static final byte MESG_MAX_SIZE =(MESG_MAX_DATA_SIZE + MESG_FRAME_SIZE); public static final byte MESG_SIZE_OFFSET =(MESG_SYNC_SIZE); public static final byte MESG_ID_OFFSET =(MESG_SYNC_SIZE + MESG_SIZE_SIZE); public static final byte MESG_DATA_OFFSET =(MESG_HEADER_SIZE); public static final byte MESG_RECOMMENDED_BUFFER_SIZE =((byte) 64); // This is the recommended size for serial message buffers if there are no RAM restrictions on the system ////////////////////////////////////////////// // Message ID's ////////////////////////////////////////////// public static final byte MESG_INVALID_ID =((byte)0x00); public static final byte MESG_EVENT_ID =((byte)0x01); public static final byte MESG_VERSION_ID =((byte)0x3E); public static final byte MESG_RESPONSE_EVENT_ID =((byte)0x40); public static final byte MESG_UNASSIGN_CHANNEL_ID =((byte)0x41); public static final byte MESG_ASSIGN_CHANNEL_ID =((byte)0x42); public static final byte MESG_CHANNEL_MESG_PERIOD_ID =((byte)0x43); public static final byte MESG_CHANNEL_SEARCH_TIMEOUT_ID =((byte)0x44); public static final byte MESG_CHANNEL_RADIO_FREQ_ID =((byte)0x45); public static final byte MESG_NETWORK_KEY_ID =((byte)0x46); public static final byte MESG_RADIO_TX_POWER_ID =((byte)0x47); public static final byte MESG_RADIO_CW_MODE_ID =((byte)0x48); public static final byte MESG_SYSTEM_RESET_ID =((byte)0x4A); public static final byte MESG_OPEN_CHANNEL_ID =((byte)0x4B); public static final byte MESG_CLOSE_CHANNEL_ID =((byte)0x4C); public static final byte MESG_REQUEST_ID =((byte)0x4D); public static final byte MESG_BROADCAST_DATA_ID =((byte)0x4E); public static final byte MESG_ACKNOWLEDGED_DATA_ID =((byte)0x4F); public static final byte MESG_BURST_DATA_ID =((byte)0x50); public static final byte MESG_CHANNEL_ID_ID =((byte)0x51); public static final byte MESG_CHANNEL_STATUS_ID =((byte)0x52); public static final byte MESG_RADIO_CW_INIT_ID =((byte)0x53); public static final byte MESG_CAPABILITIES_ID =((byte)0x54); public static final byte MESG_STACKLIMIT_ID =((byte)0x55); public static final byte MESG_SCRIPT_DATA_ID =((byte)0x56); public static final byte MESG_SCRIPT_CMD_ID =((byte)0x57); public static final byte MESG_ID_LIST_ADD_ID =((byte)0x59); public static final byte MESG_ID_LIST_CONFIG_ID =((byte)0x5A); public static final byte MESG_OPEN_RX_SCAN_ID =((byte)0x5B); public static final byte MESG_EXT_CHANNEL_RADIO_FREQ_ID =((byte)0x5C); // OBSOLETE: (for 905 radio) public static final byte MESG_EXT_BROADCAST_DATA_ID =((byte)0x5D); public static final byte MESG_EXT_ACKNOWLEDGED_DATA_ID =((byte)0x5E); public static final byte MESG_EXT_BURST_DATA_ID =((byte)0x5F); public static final byte MESG_CHANNEL_RADIO_TX_POWER_ID =((byte)0x60); public static final byte MESG_GET_SERIAL_NUM_ID =((byte)0x61); public static final byte MESG_GET_TEMP_CAL_ID =((byte)0x62); public static final byte MESG_SET_LP_SEARCH_TIMEOUT_ID =((byte)0x63); public static final byte MESG_SET_TX_SEARCH_ON_NEXT_ID =((byte)0x64); public static final byte MESG_SERIAL_NUM_SET_CHANNEL_ID_ID =((byte)0x65); public static final byte MESG_RX_EXT_MESGS_ENABLE_ID =((byte)0x66); public static final byte MESG_RADIO_CONFIG_ALWAYS_ID =((byte)0x67); public static final byte MESG_ENABLE_LED_FLASH_ID =((byte)0x68); public static final byte MESG_XTAL_ENABLE_ID =((byte)0x6D); public static final byte MESG_STARTUP_MESG_ID =((byte)0x6F); public static final byte MESG_AUTO_FREQ_CONFIG_ID =((byte)0x70); public static final byte MESG_PROX_SEARCH_CONFIG_ID =((byte)0x71); public static final byte MESG_EVENT_BUFFERING_CONFIG_ID =((byte)0x74); public static final byte MESG_CUBE_CMD_ID =((byte)0x80); public static final byte MESG_GET_PIN_DIODE_CONTROL_ID =((byte)0x8D); public static final byte MESG_PIN_DIODE_CONTROL_ID =((byte)0x8E); public static final byte MESG_FIT1_SET_AGC_ID =((byte)0x8F); public static final byte MESG_FIT1_SET_EQUIP_STATE_ID =((byte)0x91); // *** CONFLICT: w/ Sensrcore, Fit1 will never have sensrcore enabled // Sensrcore Messages public static final byte MESG_SET_CHANNEL_INPUT_MASK_ID =((byte)0x90); public static final byte MESG_SET_CHANNEL_DATA_TYPE_ID =((byte)0x91); public static final byte MESG_READ_PINS_FOR_SECT_ID =((byte)0x92); public static final byte MESG_TIMER_SELECT_ID =((byte)0x93); public static final byte MESG_ATOD_SETTINGS_ID =((byte)0x94); public static final byte MESG_SET_SHARED_ADDRESS_ID =((byte)0x95); public static final byte MESG_ATOD_EXTERNAL_ENABLE_ID =((byte)0x96); public static final byte MESG_ATOD_PIN_SETUP_ID =((byte)0x97); public static final byte MESG_SETUP_ALARM_ID =((byte)0x98); public static final byte MESG_ALARM_VARIABLE_MODIFY_TEST_ID =((byte)0x99); public static final byte MESG_PARTIAL_RESET_ID =((byte)0x9A); public static final byte MESG_OVERWRITE_TEMP_CAL_ID =((byte)0x9B); public static final byte MESG_SERIAL_PASSTHRU_SETTINGS_ID =((byte)0x9C); public static final byte MESG_BIST_ID =((byte)0xAA); public static final byte MESG_UNLOCK_INTERFACE_ID =((byte)0xAD); public static final byte MESG_SERIAL_ERROR_ID =((byte)0xAE); public static final byte MESG_SET_ID_STRING_ID =((byte)0xAF); public static final byte MESG_PORT_GET_IO_STATE_ID =((byte)0xB4); public static final byte MESG_PORT_SET_IO_STATE_ID =((byte)0xB5); public static final byte MESG_SLEEP_ID =((byte)0xC5); public static final byte MESG_GET_GRMN_ESN_ID =((byte)0xC6); public static final byte MESG_SET_USB_INFO_ID =((byte)0xC7); public static final byte MESG_COMMAND_COMPLETE_RESPONSE_ID =((byte)0xC8); ////////////////////////////////////////////// // Command complete results ////////////////////////////////////////////// public static final byte MESG_COMMAND_COMPLETE_SUCCESS =((byte)0x00); public static final byte MESG_COMMAND_COMPLETE_RETRY =((byte)0x1F); ////////////////////////////////////////////// // Message Sizes ////////////////////////////////////////////// public static final byte MESG_INVALID_SIZE =((byte)0); public static final byte MESG_VERSION_SIZE =((byte)13); public static final byte MESG_RESPONSE_EVENT_SIZE =((byte)3); public static final byte MESG_CHANNEL_STATUS_SIZE =((byte)2); public static final byte MESG_UNASSIGN_CHANNEL_SIZE =((byte)1); public static final byte MESG_ASSIGN_CHANNEL_SIZE =((byte)3); public static final byte MESG_CHANNEL_ID_SIZE =((byte)5); public static final byte MESG_CHANNEL_MESG_PERIOD_SIZE =((byte)3); public static final byte MESG_CHANNEL_SEARCH_TIMEOUT_SIZE =((byte)2); public static final byte MESG_CHANNEL_RADIO_FREQ_SIZE =((byte)2); public static final byte MESG_CHANNEL_RADIO_TX_POWER_SIZE =((byte)2); public static final byte MESG_NETWORK_KEY_SIZE =((byte)9); public static final byte MESG_RADIO_TX_POWER_SIZE =((byte)2); public static final byte MESG_RADIO_CW_MODE_SIZE =((byte)3); public static final byte MESG_RADIO_CW_INIT_SIZE =((byte)1); public static final byte MESG_SYSTEM_RESET_SIZE =((byte)1); public static final byte MESG_OPEN_CHANNEL_SIZE =((byte)1); public static final byte MESG_CLOSE_CHANNEL_SIZE =((byte)1); public static final byte MESG_REQUEST_SIZE =((byte)2); public static final byte MESG_CAPABILITIES_SIZE =((byte)6); public static final byte MESG_STACKLIMIT_SIZE =((byte)2); public static final byte MESG_SCRIPT_DATA_SIZE =((byte)10); public static final byte MESG_SCRIPT_CMD_SIZE =((byte)3); public static final byte MESG_ID_LIST_ADD_SIZE =((byte)6); public static final byte MESG_ID_LIST_CONFIG_SIZE =((byte)3); public static final byte MESG_OPEN_RX_SCAN_SIZE =((byte)1); public static final byte MESG_EXT_CHANNEL_RADIO_FREQ_SIZE =((byte)3); public static final byte MESG_RADIO_CONFIG_ALWAYS_SIZE =((byte)2); public static final byte MESG_RX_EXT_MESGS_ENABLE_SIZE =((byte)2); public static final byte MESG_SET_TX_SEARCH_ON_NEXT_SIZE =((byte)2); public static final byte MESG_SET_LP_SEARCH_TIMEOUT_SIZE =((byte)2); public static final byte MESG_SERIAL_NUM_SET_CHANNEL_ID_SIZE =((byte)3); public static final byte MESG_ENABLE_LED_FLASH_SIZE =((byte)2); public static final byte MESG_GET_SERIAL_NUM_SIZE =((byte)4); public static final byte MESG_GET_TEMP_CAL_SIZE =((byte)4); public static final byte MESG_XTAL_ENABLE_SIZE =((byte)1); public static final byte MESG_STARTUP_MESG_SIZE =((byte)1); public static final byte MESG_AUTO_FREQ_CONFIG_SIZE =((byte)4); public static final byte MESG_PROX_SEARCH_CONFIG_SIZE =((byte)2); public static final byte MESG_GET_PIN_DIODE_CONTROL_SIZE =((byte)1); public static final byte MESG_PIN_DIODE_CONTROL_ID_SIZE =((byte)2); public static final byte MESG_FIT1_SET_EQUIP_STATE_SIZE =((byte)2); public static final byte MESG_FIT1_SET_AGC_SIZE =((byte)3); public static final byte MESG_BIST_SIZE =((byte)6); public static final byte MESG_UNLOCK_INTERFACE_SIZE =((byte)1); public static final byte MESG_SET_SHARED_ADDRESS_SIZE =((byte)3); public static final byte MESG_GET_GRMN_ESN_SIZE =((byte)5); public static final byte MESG_PORT_SET_IO_STATE_SIZE =((byte)5); public static final byte MESG_EVENT_BUFFERING_CONFIG_SIZE =((byte)6); public static final byte MESG_SLEEP_SIZE =((byte)1); public static final byte MESG_EXT_DATA_SIZE =((byte)13); protected AntMesg() { } }
Java
/* * Copyright 2010 Dynastream Innovations Inc. * * 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.dsi.ant; /** * Manages the ANT Interface * * @hide */ public interface AntInterfaceIntent { public static final String STATUS = "com.dsi.ant.rx.intent.STATUS"; public static final String ANT_MESSAGE = "com.dsi.ant.intent.ANT_MESSAGE"; public static final String ANT_INTERFACE_CLAIMED_PID = "com.dsi.ant.intent.ANT_INTERFACE_CLAIMED_PID"; public static final String ANT_ENABLED_ACTION = "com.dsi.ant.intent.action.ANT_ENABLED"; public static final String ANT_DISABLED_ACTION = "com.dsi.ant.intent.action.ANT_DISABLED"; public static final String ANT_RESET_ACTION = "com.dsi.ant.intent.action.ANT_RESET"; public static final String ANT_INTERFACE_CLAIMED_ACTION = "com.dsi.ant.intent.action.ANT_INTERFACE_CLAIMED_ACTION"; public static final String ANT_RX_MESSAGE_ACTION = "com.dsi.ant.intent.action.ANT_RX_MESSAGE_ACTION"; }
Java
/* * Copyright 2008 Google Inc. * * 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.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.TrackDataHub; import android.app.Application; /** * MyTracksApplication for keeping global state. * * @author jshih@google.com (Jimmy Shih) */ public class MyTracksApplication extends Application { private TrackDataHub trackDataHub; /** * Gets the application's TrackDataHub. * * Note: use synchronized to make sure only one instance is created per application. */ public synchronized TrackDataHub getTrackDataHub() { if (trackDataHub == null) { trackDataHub = TrackDataHub.newInstance(getApplicationContext()); } return trackDataHub; } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.android.apps.mytracks; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.ChartView.Mode; import com.google.android.apps.mytracks.content.MyTracksLocation; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.content.Sensor.SensorDataSet; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TrackDataHub; import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType; import com.google.android.apps.mytracks.content.TrackDataListener; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.services.tasks.StatusAnnouncerFactory; import com.google.android.apps.mytracks.stats.DoubleBuffer; import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.location.Location; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.widget.LinearLayout; import android.widget.ZoomControls; import java.util.ArrayList; import java.util.EnumSet; /** * An activity that displays a chart from the track point provider. * * @author Sandor Dornbush * @author Rodrigo Damazio */ public class ChartActivity extends Activity implements TrackDataListener { private static final int CHART_SETTINGS_DIALOG = 1; private final DoubleBuffer elevationBuffer = new DoubleBuffer(Constants.ELEVATION_SMOOTHING_FACTOR); private final DoubleBuffer speedBuffer = new DoubleBuffer(Constants.SPEED_SMOOTHING_FACTOR); private final ArrayList<double[]> pendingPoints = new ArrayList<double[]>(); private TrackDataHub dataHub; // Stats gathered from received data. private double profileLength = 0; private long startTime = -1; private Location lastLocation; private double trackMaxSpeed; // Modes of operation private boolean metricUnits; private boolean reportSpeed; /* * UI elements: */ private ChartView chartView; private MenuItem chartSettingsMenuItem; private LinearLayout busyPane; private ZoomControls zoomControls; /** * A runnable that can be posted to the UI thread. It will remove the spinner * (if any), enable/disable zoom controls and orange pointer as appropriate * and redraw. */ private final Runnable updateChart = new Runnable() { @Override public void run() { // Get a local reference in case it's set to null concurrently with this. TrackDataHub localDataHub = dataHub; if (localDataHub == null || isFinishing()) { return; } busyPane.setVisibility(View.GONE); zoomControls.setIsZoomInEnabled(chartView.canZoomIn()); zoomControls.setIsZoomOutEnabled(chartView.canZoomOut()); chartView.setShowPointer(localDataHub.isRecordingSelected()); chartView.invalidate(); } }; @Override protected void onCreate(Bundle savedInstanceState) { Log.w(TAG, "ChartActivity.onCreate"); super.onCreate(savedInstanceState); // The volume we want to control is the Text-To-Speech volume int volumeStream = new StatusAnnouncerFactory(ApiFeatures.getInstance()).getVolumeStream(); setVolumeControlStream(volumeStream); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mytracks_charts); ViewGroup layout = (ViewGroup) findViewById(R.id.elevation_chart); chartView = new ChartView(this); LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); layout.addView(chartView, params); busyPane = (LinearLayout) findViewById(R.id.elevation_busypane); zoomControls = (ZoomControls) findViewById(R.id.elevation_zoom); zoomControls.setOnZoomInClickListener(new View.OnClickListener() { @Override public void onClick(View v) { zoomIn(); } }); zoomControls.setOnZoomOutClickListener(new View.OnClickListener() { @Override public void onClick(View v) { zoomOut(); } }); } @Override protected void onResume() { super.onResume(); dataHub = ((MyTracksApplication) getApplication()).getTrackDataHub(); dataHub.registerTrackDataListener(this, EnumSet.of( ListenerDataType.SELECTED_TRACK_CHANGED, ListenerDataType.TRACK_UPDATES, ListenerDataType.POINT_UPDATES, ListenerDataType.SAMPLED_OUT_POINT_UPDATES, ListenerDataType.WAYPOINT_UPDATES, ListenerDataType.DISPLAY_PREFERENCES)); } @Override protected void onPause() { dataHub.unregisterTrackDataListener(this); dataHub = null; super.onPause(); } private void zoomIn() { chartView.zoomIn(); zoomControls.setIsZoomInEnabled(chartView.canZoomIn()); zoomControls.setIsZoomOutEnabled(chartView.canZoomOut()); } private void zoomOut() { chartView.zoomOut(); zoomControls.setIsZoomInEnabled(chartView.canZoomIn()); zoomControls.setIsZoomOutEnabled(chartView.canZoomOut()); } private void setMode(Mode newMode) { if (chartView.getMode() != newMode) { chartView.setMode(newMode); dataHub.reloadDataForListener(this); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); chartSettingsMenuItem = menu.add(0, Constants.MENU_CHART_SETTINGS, 0, R.string.menu_chart_view_chart_settings); chartSettingsMenuItem.setIcon(R.drawable.chart_settings); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case Constants.MENU_CHART_SETTINGS: showDialog(CHART_SETTINGS_DIALOG); return true; } return super.onOptionsItemSelected(item); } @Override protected Dialog onCreateDialog(int id) { if (id == CHART_SETTINGS_DIALOG) { final ChartSettingsDialog settingsDialog = new ChartSettingsDialog(this); settingsDialog.setOnClickListener(new OnClickListener() { @Override public void onClick(DialogInterface arg0, int which) { if (which != DialogInterface.BUTTON_POSITIVE) { return; } for (int i = 0; i < ChartView.NUM_SERIES; i++) { chartView.setChartValueSeriesEnabled(i, settingsDialog.isSeriesEnabled(i)); } setMode(settingsDialog.getMode()); chartView.postInvalidate(); } }); return settingsDialog; } return super.onCreateDialog(id); } @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); if (id == CHART_SETTINGS_DIALOG) { prepareSettingsDialog((ChartSettingsDialog) dialog); } } private void prepareSettingsDialog(ChartSettingsDialog settingsDialog) { settingsDialog.setMode(chartView.getMode()); for (int i = 0; i < ChartView.NUM_SERIES; i++) { settingsDialog.setSeriesEnabled(i, chartView.isChartValueSeriesEnabled(i)); } } /** * Given a location, creates a new data point for the chart. A data point is * an array double[3 or 6], where: * data[0] = the time or distance * data[1] = the elevation * data[2] = the speed * and possibly: * data[3] = power * data[4] = cadence * data[5] = heart rate * * This must be called in order for each point. * * @param location the location to get data for (this method takes ownership of that location) * @param result the resulting point to fill out */ private void fillDataPoint(Location location, double result[]) { double timeOrDistance = Double.NaN, elevation = Double.NaN, speed = Double.NaN, power = Double.NaN, cadence = Double.NaN, heartRate = Double.NaN; if (location instanceof MyTracksLocation && ((MyTracksLocation) location).getSensorDataSet() != null) { SensorDataSet sensorData = ((MyTracksLocation) location).getSensorDataSet(); if (sensorData.hasPower() && sensorData.getPower().getState() == Sensor.SensorState.SENDING && sensorData.getPower().hasValue()) { power = sensorData.getPower().getValue(); } if (sensorData.hasCadence() && sensorData.getCadence().getState() == Sensor.SensorState.SENDING && sensorData.getCadence().hasValue()) { cadence = sensorData.getCadence().getValue(); } if (sensorData.hasHeartRate() && sensorData.getHeartRate().getState() == Sensor.SensorState.SENDING && sensorData.getHeartRate().hasValue()) { heartRate = sensorData.getHeartRate().getValue(); } } // TODO: Account for segment splits? Mode mode = chartView.getMode(); switch (mode) { case BY_DISTANCE: timeOrDistance = profileLength / 1000.0; if (lastLocation != null) { double d = lastLocation.distanceTo(location); if (metricUnits) { profileLength += d; } else { profileLength += d * UnitConversions.KM_TO_MI; } } break; case BY_TIME: if (startTime == -1) { // Base case startTime = location.getTime(); } timeOrDistance = (location.getTime() - startTime); break; default: Log.w(TAG, "ChartActivity unknown mode: " + mode); } elevationBuffer.setNext(metricUnits ? location.getAltitude() : location.getAltitude() * UnitConversions.M_TO_FT); elevation = elevationBuffer.getAverage(); if (lastLocation == null) { if (Math.abs(location.getSpeed() - 128) > 1) { speedBuffer.setNext(location.getSpeed()); } } else if (TripStatisticsBuilder.isValidSpeed( location.getTime(), location.getSpeed(), lastLocation.getTime(), lastLocation.getSpeed(), speedBuffer) && (location.getSpeed() <= trackMaxSpeed)) { speedBuffer.setNext(location.getSpeed()); } speed = speedBuffer.getAverage() * 3.6; if (!metricUnits) { speed *= UnitConversions.KM_TO_MI; } if (!reportSpeed) { if (speed != 0) { // Format as hours per unit speed = (60.0 / speed); } else { speed = Double.NaN; } } // Keep a copy so the location can be reused. lastLocation = location; if (result != null) { result[0] = timeOrDistance; result[1] = elevation; result[2] = speed; result[3] = power; result[4] = cadence; result[5] = heartRate; } } @Override public void onProviderStateChange(ProviderState state) { // We don't care. } @Override public void onCurrentLocationChanged(Location loc) { // We don't care. } @Override public void onCurrentHeadingChanged(double heading) { // We don't care. } @Override public void onSelectedTrackChanged(Track track, boolean isRecording) { runOnUiThread(new Runnable() { @Override public void run() { busyPane.setVisibility(View.VISIBLE); } }); } @Override public void onTrackUpdated(Track track) { if (track == null || track.getStatistics() == null) { trackMaxSpeed = 0.0; return; } trackMaxSpeed = track.getStatistics().getMaxSpeed(); } @Override public void clearTrackPoints() { profileLength = 0; lastLocation = null; startTime = -1; elevationBuffer.reset(); chartView.reset(); speedBuffer.reset(); pendingPoints.clear(); runOnUiThread(new Runnable() { @Override public void run() { chartView.resetScroll(); } }); } @Override public void onNewTrackPoint(Location loc) { if (LocationUtils.isValidLocation(loc)) { double[] point = new double[6]; fillDataPoint(loc, point); pendingPoints.add(point); } } @Override public void onSampledOutTrackPoint(Location loc) { // Still account for the point in the smoothing buffers. fillDataPoint(loc, null); } @Override public void onSegmentSplit() { // Do nothing. } @Override public void onNewTrackPointsDone() { chartView.addDataPoints(pendingPoints); pendingPoints.clear(); runOnUiThread(updateChart); } @Override public void clearWaypoints() { chartView.clearWaypoints(); } @Override public void onNewWaypoint(Waypoint wpt) { chartView.addWaypoint(wpt); } @Override public void onNewWaypointsDone() { runOnUiThread(updateChart); } @Override public boolean onUnitsChanged(boolean metric) { boolean changed = metric != this.metricUnits; if (!changed) return false; this.metricUnits = metric; chartView.setMetricUnits(metric); return true; // Reload data } @SuppressWarnings("hiding") @Override public boolean onReportSpeedChanged(boolean reportSpeed) { boolean changed = reportSpeed != this.reportSpeed; if (!changed) return false; this.reportSpeed = reportSpeed; chartView.setReportSpeed(reportSpeed, this); return true; // Reload data } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.MenuItem; /** * Manage the application menus. * * @author Sandor Dornbush */ class MenuManager { private final MyTracks activity; public MenuManager(MyTracks activity) { this.activity = activity; } public boolean onCreateOptionsMenu(Menu menu) { activity.getMenuInflater().inflate(R.menu.main, menu); return true; } public void onPrepareOptionsMenu(Menu menu, boolean hasRecorded, boolean isRecording, boolean hasSelectedTrack) { menu.findItem(R.id.menu_markers) .setEnabled(hasRecorded && hasSelectedTrack); menu.findItem(R.id.menu_record_track) .setEnabled(!isRecording) .setVisible(!isRecording); menu.findItem(R.id.menu_stop_recording) .setEnabled(isRecording) .setVisible(isRecording); } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_record_track: { activity.startRecording(); return true; } case R.id.menu_stop_recording: { activity.stopRecording(); return true; } case R.id.menu_tracks: { activity.startActivityForResult(new Intent(activity, TrackList.class), Constants.SHOW_TRACK); return true; } case R.id.menu_markers: { Intent startIntent = new Intent(activity, WaypointsList.class); startIntent.putExtra("trackid", activity.getSelectedTrackId()); activity.startActivityForResult(startIntent, Constants.SHOW_WAYPOINT); return true; } case R.id.menu_sensor_state: { return startActivity(SensorStateActivity.class); } case R.id.menu_settings: { return startActivity(SettingsActivity.class); } case R.id.menu_aggregated_statistics: { return startActivity(AggregatedStatsActivity.class); } case R.id.menu_help: { return startActivity(WelcomeActivity.class); } } return false; } private boolean startActivity(Class<? extends Activity> activityClass) { activity.startActivity(new Intent(activity, activityClass)); return true; } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks; import static android.content.Intent.ACTION_BOOT_COMPLETED; import static com.google.android.apps.mytracks.Constants.RESUME_TRACK_EXTRA_NAME; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.services.TrackRecordingService; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * This class handles MyTracks related broadcast messages. * * One example of a broadcast message that this class is interested in, * is notification about the phone boot. We may want to resume a previously * started tracking session if the phone crashed (hopefully not), or the user * decided to swap the battery or some external event occurred which forced * a phone reboot. * * This class simply delegates to {@link TrackRecordingService} to make a * decision whether to continue with the previous track (if any), or just * abandon it. * * @author Bartlomiej Niechwiej */ public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "BootReceiver.onReceive: " + intent.getAction()); if (ACTION_BOOT_COMPLETED.equals(intent.getAction())) { Intent startIntent = new Intent(context, TrackRecordingService.class); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); context.startService(startIntent); } else { Log.w(TAG, "BootReceiver: unsupported action"); } } }
Java
/* * Copyright 2008 Google Inc. * * 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.google.android.apps.mytracks; /** * Interface that allows to set a progress dialog message and progress value * in percent. * * @author Leif Hendrik Wilden */ public interface ProgressIndicator { public void setProgressMessage(String message); public void clearProgressMessage(); public void setProgressValue(int percent); }
Java
/* * Copyright 2009 Google Inc. * * 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.google.android.apps.mytracks; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.content.WaypointsColumns; import com.google.android.apps.mytracks.services.ITrackRecordingService; import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.os.RemoteException; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.view.Window; import android.widget.AdapterView; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.Toast; /** * Activity which shows the list of waypoints in a track. * * @author Leif Hendrik Wilden */ public class WaypointsList extends ListActivity implements View.OnClickListener { private int contextPosition = -1; private long trackId = -1; private long selectedWaypointId = -1; private ListView listView = null; private Button insertWaypointButton = null; private Button insertStatisticsButton = null; private long recordingTrackId = -1; private MyTracksProviderUtils providerUtils; private TrackRecordingServiceConnection serviceConnection; private Cursor waypointsCursor = null; private final OnCreateContextMenuListener contextMenuListener = new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.setHeaderTitle(R.string.marker_list_context_menu_title); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; contextPosition = info.position; selectedWaypointId = WaypointsList.this.listView.getAdapter() .getItemId(contextPosition); Waypoint waypoint = providerUtils.getWaypoint(info.id); if (waypoint != null) { int type = waypoint.getType(); menu.add(0, Constants.MENU_SHOW, 0, R.string.marker_list_show_on_map); menu.add(0, Constants.MENU_EDIT, 0, R.string.marker_list_edit_marker); menu.add(0, Constants.MENU_DELETE, 0, R.string.marker_list_delete_marker).setEnabled( recordingTrackId < 0 || type == Waypoint.TYPE_WAYPOINT || info.id != providerUtils.getLastWaypointId(recordingTrackId)); } } }; @Override protected void onListItemClick(ListView l, View v, int position, long id) { editWaypoint(id); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { if (!super.onMenuItemSelected(featureId, item)) { switch (item.getItemId()) { case Constants.MENU_SHOW: { Intent result = new Intent(); result.putExtra("trackid", trackId); result.putExtra(WaypointDetails.WAYPOINT_ID_EXTRA, selectedWaypointId); setResult(RESULT_OK, result); finish(); return true; } case Constants.MENU_EDIT: { editWaypoint(selectedWaypointId); return true; } case Constants.MENU_DELETE: { deleteWaypoint(selectedWaypointId); } } } return false; } private void editWaypoint(long waypointId) { Intent intent = new Intent(this, WaypointDetails.class); intent.putExtra("trackid", trackId); intent.putExtra(WaypointDetails.WAYPOINT_ID_EXTRA, waypointId); startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); providerUtils = MyTracksProviderUtils.Factory.get(this); serviceConnection = new TrackRecordingServiceConnection(this, null); // We don't need a window title bar: requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mytracks_waypoints_list); listView = getListView(); listView.setOnCreateContextMenuListener(contextMenuListener); insertWaypointButton = (Button) findViewById(R.id.waypointslist_btn_insert_waypoint); insertWaypointButton.setOnClickListener(this); insertStatisticsButton = (Button) findViewById(R.id.waypointslist_btn_insert_statistics); insertStatisticsButton.setOnClickListener(this); SharedPreferences preferences = getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); // TODO: Get rid of selected and recording track IDs long selectedTrackId = -1; if (preferences != null) { recordingTrackId = preferences.getLong(getString(R.string.recording_track_key), -1); selectedTrackId = preferences.getLong(getString(R.string.selected_track_key), -1); } boolean selectedRecording = selectedTrackId > 0 && selectedTrackId == recordingTrackId; insertWaypointButton.setEnabled(selectedRecording); insertStatisticsButton.setEnabled(selectedRecording); if (getIntent() != null && getIntent().getExtras() != null) { trackId = getIntent().getExtras().getLong("trackid", -1); } else { trackId = -1; } final long firstWaypointId = providerUtils.getFirstWaypointId(trackId); waypointsCursor = getContentResolver().query( WaypointsColumns.CONTENT_URI, null, WaypointsColumns.TRACKID + "=" + trackId + " AND " + WaypointsColumns._ID + "!=" + firstWaypointId, null, null); startManagingCursor(waypointsCursor); setListAdapter(); } @Override protected void onResume() { super.onResume(); serviceConnection.bindIfRunning(); } @Override protected void onDestroy() { serviceConnection.unbind(); super.onDestroy(); } @Override public void onClick(View v) { WaypointCreationRequest request; switch (v.getId()) { case R.id.waypointslist_btn_insert_waypoint: request = WaypointCreationRequest.DEFAULT_MARKER; break; case R.id.waypointslist_btn_insert_statistics: request = WaypointCreationRequest.DEFAULT_STATISTICS; break; default: return; } long id = insertWaypoint(request); if (id < 0) { Toast.makeText(this, R.string.marker_insert_error, Toast.LENGTH_LONG).show(); Log.e(Constants.TAG, "Failed to insert marker."); return; } Intent intent = new Intent(this, WaypointDetails.class); intent.putExtra(WaypointDetails.WAYPOINT_ID_EXTRA, id); startActivity(intent); } private long insertWaypoint(WaypointCreationRequest request) { try { ITrackRecordingService trackRecordingService = serviceConnection.getServiceIfBound(); if (trackRecordingService != null) { long waypointId = trackRecordingService.insertWaypoint(request); if (waypointId >= 0) { Toast.makeText(this, R.string.marker_insert_success, Toast.LENGTH_LONG).show(); return waypointId; } } else { Log.e(TAG, "Not connected to service, not inserting waypoint"); } } catch (RemoteException e) { Log.e(Constants.TAG, "Cannot insert marker.", e); } catch (IllegalStateException e) { Log.e(Constants.TAG, "Cannot insert marker.", e); } return -1; } private void setListAdapter() { // Get a cursor with all tracks SimpleCursorAdapter adapter = new SimpleCursorAdapter( this, R.layout.mytracks_marker_item, waypointsCursor, new String[] { WaypointsColumns.NAME, WaypointsColumns.TIME, WaypointsColumns.CATEGORY, WaypointsColumns.TYPE }, new int[] { R.id.waypointslist_item_name, R.id.waypointslist_item_time, R.id.waypointslist_item_category, R.id.waypointslist_item_icon }); final int timeIdx = waypointsCursor.getColumnIndexOrThrow(WaypointsColumns.TIME); final int typeIdx = waypointsCursor.getColumnIndexOrThrow(WaypointsColumns.TYPE); adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if (columnIndex == timeIdx) { long time = cursor.getLong(timeIdx); TextView textView = (TextView) view; textView.setText(String.format("%tc", time)); textView.setVisibility( textView.getText().length() < 1 ? View.GONE : View.VISIBLE); } else if (columnIndex == typeIdx) { int type = cursor.getInt(typeIdx); ImageView imageView = (ImageView) view; imageView.setImageDrawable(getResources().getDrawable( type == Waypoint.TYPE_STATISTICS ? R.drawable.ylw_pushpin : R.drawable.blue_pushpin)); } else { TextView textView = (TextView) view; textView.setText(cursor.getString(columnIndex)); textView.setVisibility( textView.getText().length() < 1 ? View.GONE : View.VISIBLE); } return true; } }); setListAdapter(adapter); } /** * Deletes the way point with the given id. * Prompts the user if he want to really delete it. */ public void deleteWaypoint(final long waypointId) { AlertDialog dialog = null; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.marker_list_delete_marker_confirm_message)); builder.setTitle(getString(R.string.generic_confirm_title)); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setPositiveButton(getString(R.string.generic_yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); providerUtils.deleteWaypoint(waypointId, new StringUtils(WaypointsList.this)); } }); builder.setNegativeButton(getString(R.string.generic_no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); dialog = builder.create(); dialog.show(); } }
Java
/* * Copyright 2008 Google Inc. * * 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.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Handler; import android.os.Message; import android.util.Log; /** * A utility class that can be used to delete all tracks and track points * from the provider, including asking for confirmation from the user via * a dialog. * * @author Leif Hendrik Wilden */ public class DeleteAllTracks extends Handler { private final Context context; private final Runnable done; public DeleteAllTracks(Context context, Runnable done) { this.context = context; this.done = done; } @Override public void handleMessage(Message msg) { super.handleMessage(msg); AlertDialog dialog = null; AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage( context.getString(R.string.track_list_delete_all_confirm_message)); builder.setTitle(context.getString(R.string.generic_confirm_title)); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setPositiveButton(context.getString(R.string.generic_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); Log.w(Constants.TAG, "deleting all!"); MyTracksProviderUtils.Factory.get(context).deleteAllTracks(); SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); Editor editor = prefs.edit(); // TODO: Go through data manager editor.putLong(context.getString(R.string.selected_track_key), -1); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); if (done != null) { Handler h = new Handler(); h.post(done); } } }); builder.setNegativeButton(context.getString(R.string.generic_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); dialog = builder.create(); dialog.show(); } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.android.apps.mytracks.services; /** * This is a simple location listener policy that will always dictate the same * polling interval. * * @author Sandor Dornbush */ public class AbsoluteLocationListenerPolicy implements LocationListenerPolicy { /** * The interval to request for gps signal. */ private final long interval; /** * @param interval The interval to request for gps signal */ public AbsoluteLocationListenerPolicy(final long interval) { this.interval = interval; } /** * @return The interval given in the constructor */ public long getDesiredPollingInterval() { return interval; } /** * Discards the idle time. */ public void updateIdleTime(long idleTime) { } /** * Returns the minimum distance between updates. * Get all updates to properly measure moving time. */ public int getMinDistance() { return 0; } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.services.tasks; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.services.TrackRecordingService; import com.google.android.apps.mytracks.util.UnitConversions; import android.util.Log; /** * Execute a task on a time or distance schedule. * * @author Sandor Dornbush */ public class PeriodicTaskExecutor { /** * The frequency of the task. * A value greater than zero is a frequency in time. * A value less than zero is considered a frequency in distance. */ private int taskFrequency = 0; /** * The next distance when the task should execute. */ private double nextTaskDistance = 0; /** * Time based executor. */ private TimerTaskExecutor timerExecutor = null; private boolean metricUnits; private final TrackRecordingService service; private final PeriodicTaskFactory factory; private PeriodicTask task; public PeriodicTaskExecutor(TrackRecordingService service, PeriodicTaskFactory factory) { this.service = service; this.factory = factory; } /** * Restores the manager. */ public void restore() { // TODO: Decouple service from this class once and forever. if (!service.isRecording()) { return; } if (!isTimeFrequency()) { if (timerExecutor != null) { timerExecutor.shutdown(); timerExecutor = null; } } if (taskFrequency == 0) { return; } // Try to make the task. task = factory.create(service); // Returning null is ok. if (task == null) { return; } task.start(); if (isTimeFrequency()) { if (timerExecutor == null) { timerExecutor = new TimerTaskExecutor(task, service); } timerExecutor.scheduleTask(taskFrequency * 60000L); } else { // For distance based splits. calculateNextTaskDistance(); } } /** * Shuts down the manager. */ public void shutdown() { if (task != null) { task.shutdown(); task = null; } if (timerExecutor != null) { timerExecutor.shutdown(); timerExecutor = null; } } /** * Calculates the next distance when the task should execute. */ void calculateNextTaskDistance() { // TODO: Decouple service from this class once and forever. if (!service.isRecording() || task == null) { return; } if (!isDistanceFrequency()) { nextTaskDistance = Double.MAX_VALUE; Log.d(TAG, "SplitManager: Distance splits disabled."); return; } double distance = service.getTripStatistics().getTotalDistance() / 1000; if (!metricUnits) { distance *= UnitConversions.KM_TO_MI; } // The index will be negative since the frequency is negative. int index = (int) (distance / taskFrequency); index -= 1; nextTaskDistance = taskFrequency * index; Log.d(TAG, "SplitManager: Next split distance: " + nextTaskDistance); } /** * Updates executer with new trip statistics. */ public void update() { if (!isDistanceFrequency() || task == null) { return; } // Convert the distance in meters to km or mi. double distance = service.getTripStatistics().getTotalDistance() / 1000.0; if (!metricUnits) { distance *= UnitConversions.KM_TO_MI; } if (distance > nextTaskDistance) { task.run(service); calculateNextTaskDistance(); } } private boolean isTimeFrequency() { return taskFrequency > 0; } private boolean isDistanceFrequency() { return taskFrequency < 0; } /** * Sets the task frequency. * &lt; 0 Use the absolute value as a distance in the current measurement km * or mi * 0 Turn off the task * &gt; 0 Use the value as a time in minutes * @param taskFrequency The frequency in time or distance */ public void setTaskFrequency(int taskFrequency) { Log.d(TAG, "setTaskFrequency: taskFrequency = " + taskFrequency); this.taskFrequency = taskFrequency; restore(); } public void setMetricUnits(boolean metricUnits) { this.metricUnits = metricUnits; calculateNextTaskDistance(); } double getNextTaskDistance() { return nextTaskDistance; } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.services.tasks; import static com.google.android.apps.mytracks.Constants.TAG; import android.content.Context; import android.media.AudioManager; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener; import android.util.Log; import java.util.HashMap; /** * This class will periodically announce the user's trip statistics for Froyo and future handsets. * This class will request and release audio focus. * * @author Sandor Dornbush */ public class FroyoStatusAnnouncerTask extends StatusAnnouncerTask { private final static HashMap<String, String> SPEECH_PARAMS = new HashMap<String, String>(); static { SPEECH_PARAMS.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "not_used"); } private final AudioManager audioManager; private final OnUtteranceCompletedListener utteranceListener = new OnUtteranceCompletedListener() { @Override public void onUtteranceCompleted(String utteranceId) { int result = audioManager.abandonAudioFocus(null); if (result == AudioManager.AUDIOFOCUS_REQUEST_FAILED) { Log.w(TAG, "FroyoStatusAnnouncerTask: Failed to relinquish audio focus"); } } }; public FroyoStatusAnnouncerTask(Context context) { super(context); audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); } @Override protected void onTtsReady() { super.onTtsReady(); tts.setOnUtteranceCompletedListener(utteranceListener); } @Override protected synchronized void speakAnnouncement(String announcement) { int result = audioManager.requestAudioFocus(null, TextToSpeech.Engine.DEFAULT_STREAM, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK); if (result == AudioManager.AUDIOFOCUS_REQUEST_FAILED) { Log.w(TAG, "FroyoStatusAnnouncerTask: Request for audio focus failed."); } // We don't care about the utterance id. // It is supplied here to force onUtteranceCompleted to be called. tts.speak(announcement, TextToSpeech.QUEUE_FLUSH, SPEECH_PARAMS); } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.android.apps.mytracks.services.tasks; import static com.google.android.apps.mytracks.Constants.TAG; import android.util.Log; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import com.google.android.apps.mytracks.services.TrackRecordingService; /** * This class will periodically perform a task. * * @author Sandor Dornbush */ public class TimerTaskExecutor { private final PeriodicTask task; private final TrackRecordingService service; /** * A timer to schedule the announcements. * This is non-null if the task is in started (scheduled) state. */ private Timer timer; public TimerTaskExecutor(PeriodicTask task, TrackRecordingService service) { this.task = task; this.service = service; } /** * Schedules the task at the given interval. * * @param interval The interval in milliseconds */ public void scheduleTask(long interval) { // TODO: Decouple service from this class once and forever. if (!service.isRecording()) { return; } if (timer != null) { timer.cancel(); timer.purge(); } else { // First start, or we were previously shut down. task.start(); } timer = new Timer(); if (interval <= 0) { return; } long now = System.currentTimeMillis(); long next = service.getTripStatistics().getStartTime(); if (next < now) { next = now + interval - ((now - next) % interval); } Date start = new Date(next); Log.i(TAG, task.getClass().getSimpleName() + " scheduled to start at " + start + " every " + interval + " milliseconds."); timer.scheduleAtFixedRate(new PeriodicTimerTask(), start, interval); } /** * Cleans up this object. */ public void shutdown() { Log.i(TAG, task.getClass().getSimpleName() + " shutting down."); if (timer != null) { timer.cancel(); timer.purge(); timer = null; task.shutdown(); } } /** * The timer task to announce the trip status. */ private class PeriodicTimerTask extends TimerTask { @Override public void run() { task.run(service); } } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.services.tasks; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.services.TrackRecordingService; import android.content.Context; /** * A simple task to insert statistics markers periodically. * @author Sandor Dornbush */ public class SplitTask implements PeriodicTask { private SplitTask() { } @Override public void run(TrackRecordingService service) { service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS); } @Override public void shutdown() { } @Override public void start() { } /** * Create new SplitTasks. */ public static class Factory implements PeriodicTaskFactory { @Override public PeriodicTask create(Context context) { return new SplitTask(); } } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.services.tasks; import com.google.android.apps.mytracks.util.ApiFeatures; import android.content.Context; import android.media.AudioManager; /** * Factory which wraps construction and setup of text-to-speech announcements in * an API-level-safe way. * * @author Rodrigo Damazio */ public class StatusAnnouncerFactory implements PeriodicTaskFactory { private final boolean hasTts; public StatusAnnouncerFactory(ApiFeatures apiFeatures) { this.hasTts = apiFeatures.hasTextToSpeech(); } @Override public PeriodicTask create(Context context) { if (hasTts) { return ApiFeatures.getInstance().getApiAdapter().getStatusAnnouncerTask(context); } else { return null; } } /** * Returns the appropriate volume stream for controlling announcement * volume. */ public int getVolumeStream() { if (hasTts) { return StatusAnnouncerTask.getVolumeStream(); } else { return AudioManager.USE_DEFAULT_STREAM_TYPE; } } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.android.apps.mytracks.services.tasks; import com.google.android.apps.mytracks.services.TrackRecordingService; /** * This is interface for a task that will be executed on some schedule. * * @author Sandor Dornbush */ public interface PeriodicTask { /** * Sets up this task for subsequent calls to the run method. */ public void start(); /** * This method will be called periodically. */ public void run(TrackRecordingService service); /** * Shuts down this task and clean up resources. */ public void shutdown(); }
Java
/* * Copyright 2009 Google Inc. * * 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.google.android.apps.mytracks.services.tasks; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.services.TrackRecordingService; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import com.google.common.annotations.VisibleForTesting; import android.content.Context; import android.content.SharedPreferences; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import java.util.Locale; /** * This class will periodically announce the user's trip statistics. * * @author Sandor Dornbush */ public class StatusAnnouncerTask implements PeriodicTask { /** * The rate at which announcements are spoken. */ // @VisibleForTesting static final float TTS_SPEECH_RATE = 0.9f; /** * A pointer to the service context. */ private final Context context; /** * The interface to the text to speech engine. */ protected TextToSpeech tts; /** * The response received from the TTS engine after initialization. */ private int initStatus = TextToSpeech.ERROR; /** * Whether the TTS engine is ready. */ private boolean ready = false; /** * Whether we're allowed to speak right now. */ private boolean speechAllowed; /** * Listener which updates {@link #speechAllowed} when the phone state changes. */ private final PhoneStateListener phoneListener = new PhoneStateListener() { @Override public void onCallStateChanged(int state, String incomingNumber) { speechAllowed = state == TelephonyManager.CALL_STATE_IDLE; if (!speechAllowed && tts != null && tts.isSpeaking()) { // If we're already speaking, stop it. tts.stop(); } } }; public StatusAnnouncerTask(Context context) { this.context = context; } /** * {@inheritDoc} * * Announces the trip status. */ @Override public void run(TrackRecordingService service) { if (service == null) { Log.e(TAG, "StatusAnnouncer TrackRecordingService not initialized"); return; } runWithStatistics(service.getTripStatistics()); } /** * This method exists as a convenience for testing code, allowing said code * to avoid needing to instantiate an entire {@link TrackRecordingService} * just to test the announcer. */ // @VisibleForTesting void runWithStatistics(TripStatistics statistics) { if (statistics == null) { Log.e(TAG, "StatusAnnouncer stats not initialized."); return; } synchronized (this) { checkReady(); if (!ready) { Log.e(TAG, "StatusAnnouncer Tts not ready."); return; } } if (!speechAllowed) { Log.i(Constants.TAG, "Not making announcement - not allowed at this time"); return; } String announcement = getAnnouncement(statistics); Log.d(Constants.TAG, "Announcement: " + announcement); speakAnnouncement(announcement); } protected void speakAnnouncement(String announcement) { tts.speak(announcement, TextToSpeech.QUEUE_FLUSH, null); } /** * Builds the announcement string. * * @return The string that will be read to the user */ // @VisibleForTesting protected String getAnnouncement(TripStatistics stats) { boolean metricUnits = true; boolean reportSpeed = true; SharedPreferences preferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (preferences != null) { metricUnits = preferences.getBoolean(context.getString(R.string.metric_units_key), true); reportSpeed = preferences.getBoolean(context.getString(R.string.report_speed_key), true); } double d = stats.getTotalDistance() / 1000; // d is in kilometers double s = stats.getAverageMovingSpeed() * 3.6; // s is in kilometers per hour if (d == 0) { return context.getString(R.string.voice_total_distance_zero); } if (!metricUnits) { d *= UnitConversions.KM_TO_MI; s *= UnitConversions.KMH_TO_MPH; } if (!reportSpeed) { s = 3600000.0 / s; // converts from speed to pace } // Makes sure s is not NaN. if (Double.isNaN(s)) { s = 0; } String speed; if (reportSpeed) { int speedId = metricUnits ? R.plurals.voiceSpeedKilometersPerHour : R.plurals.voiceSpeedMilesPerHour; speed = context.getResources().getQuantityString(speedId, getQuantityCount(s), s); } else { int paceId = metricUnits ? R.string.voice_pace_per_kilometer : R.string.voice_pace_per_mile; speed = String.format(context.getString(paceId), getAnnounceTime((long) s)); } int totalDistanceId = metricUnits ? R.plurals.voiceTotalDistanceKilometers : R.plurals.voiceTotalDistanceMiles; String totalDistance = context.getResources().getQuantityString( totalDistanceId, getQuantityCount(d), d); return context.getString( R.string.voice_template, totalDistance, getAnnounceTime(stats.getMovingTime()), speed); } /** * Gets the plural count to be used by getQuantityString. getQuantityString * only supports integer quantities, not a double quantity like "2.2". * <p> * As a temporary workaround, we convert a double quantity to an integer * quantity. If the double quantity is exactly 0, 1, or 2, then we can return * these integer quantities. Otherwise, we cast the double quantity to an * integer quantity. However, we need to make sure that if the casted value is * 0, 1, or 2, we don't return those, instead, return the next biggest integer * 3. * * @param d the double value */ private int getQuantityCount(double d) { if (d == 0) { return 0; } else if (d == 1) { return 1; } else if (d == 2) { return 2; } else { int count = (int) d; return count < 3 ? 3 : count; } } @Override public void start() { Log.i(Constants.TAG, "Starting TTS"); if (tts == null) { // We can't have this class also be the listener, otherwise it's unsafe to // reference it in Cupcake (even if we don't instantiate it). tts = newTextToSpeech(context, new OnInitListener() { @Override public void onInit(int status) { onTtsInit(status); } }); } speechAllowed = true; // Register ourselves as a listener so we won't speak during a call. listenToPhoneState(phoneListener, PhoneStateListener.LISTEN_CALL_STATE); } /** * Called when the TTS engine is initialized. */ private void onTtsInit(int status) { Log.i(TAG, "TrackRecordingService.TTS init: " + status); synchronized (this) { // TTS should be valid here but NPE exceptions were reported to the market. initStatus = status; checkReady(); } } /** * Ensures that the TTS is ready (finishing its initialization if needed). */ private void checkReady() { synchronized (this) { if (ready) { // Already done; return; } ready = initStatus == TextToSpeech.SUCCESS && tts != null; Log.d(TAG, "Status announcer ready: " + ready); if (ready) { onTtsReady(); } } } /** * Finishes the TTS engine initialization. * Called once (and only once) when the TTS engine is ready. */ protected void onTtsReady() { // Force the language to be the same as the string we will be speaking, // if that's available. Locale speechLanguage = Locale.getDefault(); int languageAvailability = tts.isLanguageAvailable(speechLanguage); if (languageAvailability == TextToSpeech.LANG_MISSING_DATA || languageAvailability == TextToSpeech.LANG_NOT_SUPPORTED) { // English is probably supported. // TODO: Somehow use announcement strings from English too. Log.w(TAG, "Default language not available, using English."); speechLanguage = Locale.ENGLISH; } tts.setLanguage(speechLanguage); // Slow down the speed just a bit as it is hard to hear when exercising. tts.setSpeechRate(TTS_SPEECH_RATE); } @Override public void shutdown() { // Stop listening to phone state. listenToPhoneState(phoneListener, PhoneStateListener.LISTEN_NONE); if (tts != null) { tts.shutdown(); tts = null; } Log.i(Constants.TAG, "TTS shut down"); } /** * Wrapper for instantiating a {@link TextToSpeech} object, which causes * several issues during testing. */ // @VisibleForTesting protected TextToSpeech newTextToSpeech(Context ctx, OnInitListener onInitListener) { return new TextToSpeech(ctx, onInitListener); } /** * Wrapper for calls to the 100%-unmockable {@link TelephonyManager#listen}. */ // @VisibleForTesting protected void listenToPhoneState(PhoneStateListener listener, int events) { TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (telephony != null) { telephony.listen(listener, events); } } /** * Returns the volume stream to use for controlling announcement volume. */ public static int getVolumeStream() { return TextToSpeech.Engine.DEFAULT_STREAM; } /** * Gets a string to announce the time. * * @param time the time */ @VisibleForTesting String getAnnounceTime(long time) { int[] parts = StringUtils.getTimeParts(time); String seconds = context.getResources().getQuantityString( R.plurals.voiceSeconds, parts[0], parts[0]); String minutes = context.getResources().getQuantityString( R.plurals.voiceMinutes, parts[1], parts[1]); String hours = context.getResources().getQuantityString( R.plurals.voiceHours, parts[2], parts[2]); StringBuilder sb = new StringBuilder(); if (parts[2] != 0) { sb.append(hours); sb.append(" "); sb.append(minutes); } else { sb.append(minutes); sb.append(" "); sb.append(seconds); } return sb.toString(); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.services.tasks; import android.content.Context; /** * An interface for classes that can create periodic tasks. * * @author Sandor Dornbush */ public interface PeriodicTaskFactory { /** * Creates a periodic task which does voice announcements. * * @return the task, or null if task is not supported */ PeriodicTask create(Context context); }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.services; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.widgets.TrackWidgetProvider; import com.google.android.maps.mytracks.R; import android.app.IntentService; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; /** * A service to control starting and stopping of a recording. This service, * through the AndroidManifest.xml, is configured to only allow components of * the same application to invoke it. Thus this service can be used my MyTracks * app widget, {@link TrackWidgetProvider}, but not by other applications. This * application delegates starting and stopping a recording to * {@link TrackRecordingService} using RPC calls. * * @author jshih@google.com (Jimmy Shih) */ public class ControlRecordingService extends IntentService implements ServiceConnection { private ITrackRecordingService trackRecordingService; private boolean connected = false; public ControlRecordingService() { super(ControlRecordingService.class.getSimpleName()); } @Override public void onCreate() { super.onCreate(); Intent newIntent = new Intent(this, TrackRecordingService.class); startService(newIntent); bindService(newIntent, this, 0); } @Override public void onServiceConnected(ComponentName name, IBinder service) { trackRecordingService = ITrackRecordingService.Stub.asInterface(service); notifyConnected(); } @Override public void onServiceDisconnected(ComponentName name) { connected = false; } /** * Notifies all threads that connection to {@link TrackRecordingService} is * available. */ private synchronized void notifyConnected() { connected = true; notifyAll(); } /** * Waits until the connection to {@link TrackRecordingService} is available. */ private synchronized void waitConnected() { while (!connected) { try { wait(); } catch (InterruptedException e) { // can safely ignore } } } @Override protected void onHandleIntent(Intent intent) { waitConnected(); String action = intent.getAction(); if (action != null) { try { if (action.equals(getString(R.string.track_action_start))) { trackRecordingService.startNewTrack(); } else if (action.equals(getString(R.string.track_action_end))) { trackRecordingService.endCurrentTrack(); } } catch (RemoteException e) { Log.d(TAG, "ControlRecordingService onHandleIntent RemoteException", e); } } unbindService(this); connected = false; } @Override public void onDestroy() { super.onDestroy(); if (connected) { unbindService(this); connected = false; } } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.services; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.util.Log; /** * A class that manages reading the shared preferences for the service. * * @author Sandor Dornbush */ public class PreferenceManager implements OnSharedPreferenceChangeListener { private TrackRecordingService service; private SharedPreferences sharedPreferences; private final String announcementFrequencyKey; private final String autoResumeTrackCurrentRetryKey; private final String autoResumeTrackTimeoutKey; private final String maxRecordingDistanceKey; private final String metricUnitsKey; private final String minRecordingDistanceKey; private final String minRecordingIntervalKey; private final String minRequiredAccuracyKey; private final String recordingTrackKey; private final String selectedTrackKey; private final String splitFrequencyKey; public PreferenceManager(TrackRecordingService service) { this.service = service; this.sharedPreferences = service.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (sharedPreferences == null) { Log.w(Constants.TAG, "TrackRecordingService: Couldn't get shared preferences."); throw new IllegalStateException("Couldn't get shared preferences"); } sharedPreferences.registerOnSharedPreferenceChangeListener(this); announcementFrequencyKey = service.getString(R.string.announcement_frequency_key); autoResumeTrackCurrentRetryKey = service.getString(R.string.auto_resume_track_current_retry_key); autoResumeTrackTimeoutKey = service.getString(R.string.auto_resume_track_timeout_key); maxRecordingDistanceKey = service.getString(R.string.max_recording_distance_key); metricUnitsKey = service.getString(R.string.metric_units_key); minRecordingDistanceKey = service.getString(R.string.min_recording_distance_key); minRecordingIntervalKey = service.getString(R.string.min_recording_interval_key); minRequiredAccuracyKey = service.getString(R.string.min_required_accuracy_key); recordingTrackKey = service.getString(R.string.recording_track_key); selectedTrackKey = service.getString(R.string.selected_track_key); splitFrequencyKey = service.getString(R.string.split_frequency_key); // Refresh all properties. onSharedPreferenceChanged(sharedPreferences, null); } /** * Notifies that preferences have changed. * Call this with key == null to update all preferences in one call. * * @param key the key that changed (may be null to update all preferences) */ @Override public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { if (service == null) { Log.w(Constants.TAG, "onSharedPreferenceChanged: a preference change (key = " + key + ") after a call to shutdown()"); return; } if (key == null || key.equals(minRecordingDistanceKey)) { int minRecordingDistance = sharedPreferences.getInt( minRecordingDistanceKey, Constants.DEFAULT_MIN_RECORDING_DISTANCE); service.setMinRecordingDistance(minRecordingDistance); Log.d(Constants.TAG, "TrackRecordingService: minRecordingDistance = " + minRecordingDistance); } if (key == null || key.equals(maxRecordingDistanceKey)) { service.setMaxRecordingDistance(sharedPreferences.getInt( maxRecordingDistanceKey, Constants.DEFAULT_MAX_RECORDING_DISTANCE)); } if (key == null || key.equals(minRecordingIntervalKey)) { int minRecordingInterval = sharedPreferences.getInt( minRecordingIntervalKey, Constants.DEFAULT_MIN_RECORDING_INTERVAL); switch (minRecordingInterval) { case -2: // Battery Miser // min: 30 seconds // max: 5 minutes // minDist: 5 meters Choose battery life over moving time accuracy. service.setLocationListenerPolicy( new AdaptiveLocationListenerPolicy(30000, 300000, 5)); break; case -1: // High Accuracy // min: 1 second // max: 30 seconds // minDist: 0 meters get all updates to properly measure moving time. service.setLocationListenerPolicy( new AdaptiveLocationListenerPolicy(1000, 30000, 0)); break; default: service.setLocationListenerPolicy( new AbsoluteLocationListenerPolicy(minRecordingInterval * 1000)); } } if (key == null || key.equals(minRequiredAccuracyKey)) { service.setMinRequiredAccuracy(sharedPreferences.getInt( minRequiredAccuracyKey, Constants.DEFAULT_MIN_REQUIRED_ACCURACY)); } if (key == null || key.equals(announcementFrequencyKey)) { service.setAnnouncementFrequency( sharedPreferences.getInt(announcementFrequencyKey, -1)); } if (key == null || key.equals(autoResumeTrackTimeoutKey)) { service.setAutoResumeTrackTimeout(sharedPreferences.getInt( autoResumeTrackTimeoutKey, Constants.DEFAULT_AUTO_RESUME_TRACK_TIMEOUT)); } if (key == null || key.equals(recordingTrackKey)) { long recordingTrackId = sharedPreferences.getLong(recordingTrackKey, -1); // Only read the id if it is valid. // Setting it to -1 should only happen in // TrackRecordingService.endCurrentTrack() if (recordingTrackId > 0) { service.setRecordingTrackId(recordingTrackId); } } if (key == null || key.equals(splitFrequencyKey)) { service.setSplitFrequency( sharedPreferences.getInt(splitFrequencyKey, 0)); } if (key == null || key.equals(metricUnitsKey)) { service.setMetricUnits( sharedPreferences.getBoolean(metricUnitsKey, true)); } } public void setAutoResumeTrackCurrentRetry(int retryAttempts) { Editor editor = sharedPreferences.edit(); editor.putInt(autoResumeTrackCurrentRetryKey, retryAttempts); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); } public void setRecordingTrack(long id) { Editor editor = sharedPreferences.edit(); editor.putLong(recordingTrackKey, id); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); } public void setSelectedTrack(long id) { Editor editor = sharedPreferences.edit(); editor.putLong(selectedTrackKey, id); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); } public void shutdown() { sharedPreferences.unregisterOnSharedPreferenceChangeListener(this); service = null; } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.android.apps.mytracks.services; /** * A LocationListenerPolicy that will change based on how long the user has been * stationary. * * This policy will dictate a policy based on a min, max and idle time. * The policy will dictate an interval bounded by min and max whic is half of * the idle time. * * @author Sandor Dornbush */ public class AdaptiveLocationListenerPolicy implements LocationListenerPolicy { /** * Smallest interval this policy will dictate, in milliseconds. */ private final long minInterval; /** * Largest interval this policy will dictate, in milliseconds. */ private final long maxInterval; private final int minDistance; /** * The time the user has been at the current location, in milliseconds. */ private long idleTime; /** * Creates a policy that will be bounded by the given min and max. * * @param min Smallest interval this policy will dictate, in milliseconds * @param max Largest interval this policy will dictate, in milliseconds */ public AdaptiveLocationListenerPolicy(long min, long max, int minDistance) { this.minInterval = min; this.maxInterval = max; this.minDistance = minDistance; } /** * @return An interval bounded by min and max which is half of the idle time */ public long getDesiredPollingInterval() { long desiredInterval = idleTime / 2; // Round to avoid setting the interval too often. desiredInterval = (desiredInterval / 1000) * 1000; return Math.max(Math.min(maxInterval, desiredInterval), minInterval); } public void updateIdleTime(long newIdleTime) { this.idleTime = newIdleTime; } /** * Returns the minimum distance between updates. */ public int getMinDistance() { return minDistance; } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.services; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.util.SystemUtils; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.IBinder.DeathRecipient; import android.os.RemoteException; import android.util.Log; /** * Wrapper for the connection to the track recording service. * This handles connection/disconnection internally, only returning a real * service for use if one is available and connected. * * @author Rodrigo Damazio */ public class TrackRecordingServiceConnection { private ITrackRecordingService boundService; private final DeathRecipient deathRecipient = new DeathRecipient() { @Override public void binderDied() { Log.d(TAG, "Service died"); setBoundService(null); } }; private final ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { Log.i(TAG, "Connected to service"); try { service.linkToDeath(deathRecipient, 0); } catch (RemoteException e) { Log.e(TAG, "Failed to bind a death recipient", e); } setBoundService(ITrackRecordingService.Stub.asInterface(service)); } @Override public void onServiceDisconnected(ComponentName className) { Log.i(TAG, "Disconnected from service"); setBoundService(null); } }; private final Context context; private final Runnable bindChangedCallback; /** * Constructor. * * @param context the current context * @param bindChangedCallback a callback to be executed when the state of the * service binding changes */ public TrackRecordingServiceConnection(Context context, Runnable bindChangedCallback) { this.context = context; this.bindChangedCallback = bindChangedCallback; } /** * Binds to the service, starting it if necessary. */ public void startAndBind() { bindService(true); } /** * Binds to the service, only if it's already running. */ public void bindIfRunning() { bindService(false); } /** * Unbinds from and stops the service. */ public void stop() { unbind(); Log.d(TAG, "Stopping service"); Intent intent = new Intent(context, TrackRecordingService.class); context.stopService(intent); } /** * Unbinds from the service (but leaves it running). */ public void unbind() { Log.d(TAG, "Unbinding from the service"); try { context.unbindService(serviceConnection); } catch (IllegalArgumentException e) { // Means we weren't bound, which is ok. } setBoundService(null); } /** * Returns the service if connected to it, or null if not connected. */ public ITrackRecordingService getServiceIfBound() { checkBindingAlive(); return boundService; } private void checkBindingAlive() { if (boundService != null && !boundService.asBinder().isBinderAlive()) { setBoundService(null); } } private void bindService(boolean startIfNeeded) { if (boundService != null) { // Already bound. return; } if (!startIfNeeded && !ServiceUtils.isServiceRunning(context)) { // Not running, start not requested. Log.d(TAG, "Service not running, not binding to it."); return; } if (startIfNeeded) { Log.i(TAG, "Starting the service"); Intent intent = new Intent(context, TrackRecordingService.class); context.startService(intent); } Log.i(TAG, "Binding to the service"); Intent intent = new Intent(context, TrackRecordingService.class); int flags = SystemUtils.isRelease(context) ? 0 : Context.BIND_DEBUG_UNBIND; context.bindService(intent, serviceConnection, flags); } private void setBoundService(ITrackRecordingService service) { boundService = service; if (bindChangedCallback != null) { bindChangedCallback.run(); } } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.android.apps.mytracks.services; /** * This is an interface for classes that will manage the location listener policy. * Different policy options are: * Absolute * Addaptive * * @author Sandor Dornbush */ public interface LocationListenerPolicy { /** * Returns the polling time this policy would like at this time. * * @return The polling that this policy dictates */ public long getDesiredPollingInterval(); /** * Returns the minimum distance between updates. */ public int getMinDistance(); /** * Notifies the amount of time the user has been idle at their current * location. * * @param idleTime The time that the user has been idle at this spot */ public void updateIdleTime(long idleTime); }
Java
/* * Copyright 2008 Google Inc. * * 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.google.android.apps.mytracks.services; import static com.google.android.apps.mytracks.Constants.RESUME_TRACK_EXTRA_NAME; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.MyTracks; import com.google.android.apps.mytracks.content.MyTracksLocation; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.content.Sensor.SensorDataSet; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.content.WaypointsColumns; import com.google.android.apps.mytracks.services.sensors.SensorManager; import com.google.android.apps.mytracks.services.sensors.SensorManagerFactory; import com.google.android.apps.mytracks.services.tasks.PeriodicTaskExecutor; import com.google.android.apps.mytracks.services.tasks.SplitTask; import com.google.android.apps.mytracks.services.tasks.StatusAnnouncerFactory; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.ApiLevelAdapter; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.maps.mytracks.R; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.os.Binder; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.os.Process; import android.util.Log; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * A background service that registers a location listener and records track * points. Track points are saved to the MyTracksProvider. * * @author Leif Hendrik Wilden */ public class TrackRecordingService extends Service { static final int MAX_AUTO_RESUME_TRACK_RETRY_ATTEMPTS = 3; private NotificationManager notificationManager; private LocationManager locationManager; private WakeLock wakeLock; private int minRecordingDistance = Constants.DEFAULT_MIN_RECORDING_DISTANCE; private int maxRecordingDistance = Constants.DEFAULT_MAX_RECORDING_DISTANCE; private int minRequiredAccuracy = Constants.DEFAULT_MIN_REQUIRED_ACCURACY; private int autoResumeTrackTimeout = Constants.DEFAULT_AUTO_RESUME_TRACK_TIMEOUT; private long recordingTrackId = -1; private long currentWaypointId = -1; /** The timer posts a runnable to the main thread via this handler. */ private final Handler handler = new Handler(); /** * Utilities to deal with the database. */ private MyTracksProviderUtils providerUtils; private TripStatisticsBuilder statsBuilder; private TripStatisticsBuilder waypointStatsBuilder; /** * Current length of the recorded track. This length is calculated from the * recorded points (as compared to each location fix). It's used to overlay * waypoints precisely in the elevation profile chart. */ private double length; /** * Status announcer executor. */ private PeriodicTaskExecutor announcementExecutor; private PeriodicTaskExecutor splitExecutor; private SensorManager sensorManager; private PreferenceManager prefManager; /** * The interval in milliseconds that we have requested to be notified of gps * readings. */ private long currentRecordingInterval; /** * The policy used to decide how often we should request gps updates. */ private LocationListenerPolicy locationListenerPolicy = new AbsoluteLocationListenerPolicy(0); private LocationListener locationListener = new LocationListener() { @Override public void onProviderDisabled(String provider) { // Do nothing } @Override public void onProviderEnabled(String provider) { // Do nothing } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // Do nothing } @Override public void onLocationChanged(final Location location) { if (executorService.isShutdown() || executorService.isTerminated()) { return; } executorService.submit( new Runnable() { @Override public void run() { onLocationChangedAsync(location); } }); } }; /** * Task invoked by a timer periodically to make sure the location listener is * still registered. */ private TimerTask checkLocationListener = new TimerTask() { @Override public void run() { // It's always safe to assume that if isRecording() is true, it implies // that onCreate() has finished. if (isRecording()) { handler.post(new Runnable() { public void run() { Log.d(Constants.TAG, "Re-registering location listener with TrackRecordingService."); unregisterLocationListener(); registerLocationListener(); } }); } } }; /** * This timer invokes periodically the checkLocationListener timer task. */ private final Timer timer = new Timer(); /** * Is the phone currently moving? */ private boolean isMoving = true; /** * The most recent recording track. */ private Track recordingTrack; /** * Is the service currently recording a track? */ private boolean isRecording; /** * Last good location the service has received from the location listener */ private Location lastLocation; /** * Last valid location (i.e. not a marker) that was recorded. */ private Location lastValidLocation; /** * A service to run tasks outside of the main thread. */ private ExecutorService executorService; private ServiceBinder binder = new ServiceBinder(this); /* * Application lifetime events: */ /* * Note that this service, through the AndroidManifest.xml, is configured to * allow both MyTracks and third party apps to invoke it. For the onCreate * callback, we cannot tell whether the caller is MyTracks or a third party * app, thus it cannot start/stop a recording or write/update MyTracks * database. However, it can resume a recording. */ @Override public void onCreate() { super.onCreate(); Log.d(TAG, "TrackRecordingService.onCreate"); providerUtils = MyTracksProviderUtils.Factory.get(this); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); setUpTaskExecutors(); executorService = Executors.newSingleThreadExecutor(); prefManager = new PreferenceManager(this); registerLocationListener(); /* * After 5 min, check every minute that location listener still is * registered and spit out additional debugging info to the logs: */ timer.schedule(checkLocationListener, 1000 * 60 * 5, 1000 * 60); // Try to restore previous recording state in case this service has been // restarted by the system, which can sometimes happen. recordingTrack = getRecordingTrack(); if (recordingTrack != null) { restoreStats(recordingTrack); isRecording = true; } else { if (recordingTrackId != -1) { // Make sure we have consistent state in shared preferences. Log.w(TAG, "TrackRecordingService.onCreate: " + "Resetting an orphaned recording track = " + recordingTrackId); } prefManager.setRecordingTrack(recordingTrackId = -1); } showNotification(); } /* * Note that this service, through the AndroidManifest.xml, is configured to * allow both MyTracks and third party apps to invoke it. For the onStart * callback, we cannot tell whether the caller is MyTracks or a third party * app, thus it cannot start/stop a recording or write/update MyTracks * database. However, it can resume a recording. */ @Override public void onStart(Intent intent, int startId) { handleStartCommand(intent, startId); } /* * Note that this service, through the AndroidManifest.xml, is configured to * allow both MyTracks and third party apps to invoke it. For the * onStartCommand callback, we cannot tell whether the caller is MyTracks or a * third party app, thus it cannot start/stop a recording or write/update * MyTracks database. However, it can resume a recording. */ @Override public int onStartCommand(Intent intent, int flags, int startId) { handleStartCommand(intent, startId); return START_STICKY; } private void handleStartCommand(Intent intent, int startId) { Log.d(TAG, "TrackRecordingService.handleStartCommand: " + startId); if (intent == null) { return; } // Check if called on phone reboot with resume intent. if (intent.getBooleanExtra(RESUME_TRACK_EXTRA_NAME, false)) { resumeTrack(startId); } } private boolean isTrackInProgress() { return recordingTrackId != -1 || isRecording; } private void resumeTrack(int startId) { Log.d(TAG, "TrackRecordingService: requested resume"); // Make sure that the current track exists and is fresh enough. if (recordingTrack == null || !shouldResumeTrack(recordingTrack)) { Log.i(TAG, "TrackRecordingService: Not resuming, because the previous track (" + recordingTrack + ") doesn't exist or is too old"); isRecording = false; prefManager.setRecordingTrack(recordingTrackId = -1); stopSelfResult(startId); return; } Log.i(TAG, "TrackRecordingService: resuming"); } @Override public IBinder onBind(Intent intent) { Log.d(TAG, "TrackRecordingService.onBind"); return binder; } @Override public boolean onUnbind(Intent intent) { Log.d(TAG, "TrackRecordingService.onUnbind"); return super.onUnbind(intent); } @Override public void onDestroy() { Log.d(TAG, "TrackRecordingService.onDestroy"); isRecording = false; showNotification(); prefManager.shutdown(); prefManager = null; checkLocationListener.cancel(); checkLocationListener = null; timer.cancel(); timer.purge(); unregisterLocationListener(); shutdownTaskExecutors(); if (sensorManager != null) { sensorManager.shutdown(); sensorManager = null; } // Make sure we have no indirect references to this service. locationManager = null; notificationManager = null; providerUtils = null; binder.detachFromService(); binder = null; // This should be the last operation. releaseWakeLock(); // Shutdown the executor service last to avoid sending events to a dead executor. executorService.shutdown(); super.onDestroy(); } private void setAutoResumeTrackRetries(int retryAttempts) { Log.d(TAG, "Updating auto-resume retry attempts to: " + retryAttempts); prefManager.setAutoResumeTrackCurrentRetry(retryAttempts); } private boolean shouldResumeTrack(Track track) { Log.d(TAG, "shouldResumeTrack: autoResumeTrackTimeout = " + autoResumeTrackTimeout); // Check if we haven't exceeded the maximum number of retry attempts. SharedPreferences sharedPreferences = getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); int retries = sharedPreferences.getInt( getString(R.string.auto_resume_track_current_retry_key), 0); Log.d(TAG, "shouldResumeTrack: Attempting to auto-resume the track (" + (retries + 1) + "/" + MAX_AUTO_RESUME_TRACK_RETRY_ATTEMPTS + ")"); if (retries >= MAX_AUTO_RESUME_TRACK_RETRY_ATTEMPTS) { Log.i(TAG, "shouldResumeTrack: Not resuming because exceeded the maximum " + "number of auto-resume retries"); return false; } // Increase number of retry attempts. setAutoResumeTrackRetries(retries + 1); // Check for special cases. if (autoResumeTrackTimeout == 0) { // Never resume. Log.d(TAG, "shouldResumeTrack: Auto-resume disabled (never resume)"); return false; } else if (autoResumeTrackTimeout == -1) { // Always resume. Log.d(TAG, "shouldResumeTrack: Auto-resume forced (always resume)"); return true; } // Check if the last modified time is within the acceptable range. long lastModified = track.getStatistics() != null ? track.getStatistics().getStopTime() : 0; Log.d(TAG, "shouldResumeTrack: lastModified = " + lastModified + ", autoResumeTrackTimeout: " + autoResumeTrackTimeout); return lastModified > 0 && System.currentTimeMillis() - lastModified <= autoResumeTrackTimeout * 60L * 1000L; } /* * Setup/shutdown methods. */ /** * Tries to acquire a partial wake lock if not already acquired. Logs errors * and gives up trying in case the wake lock cannot be acquired. */ private void acquireWakeLock() { try { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); if (pm == null) { Log.e(TAG, "TrackRecordingService: Power manager not found!"); return; } if (wakeLock == null) { wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); if (wakeLock == null) { Log.e(TAG, "TrackRecordingService: Could not create wake lock (null)."); return; } } if (!wakeLock.isHeld()) { wakeLock.acquire(); if (!wakeLock.isHeld()) { Log.e(TAG, "TrackRecordingService: Could not acquire wake lock."); } } } catch (RuntimeException e) { Log.e(TAG, "TrackRecordingService: Caught unexpected exception: " + e.getMessage(), e); } } /** * Releases the wake lock if it's currently held. */ private void releaseWakeLock() { if (wakeLock != null && wakeLock.isHeld()) { wakeLock.release(); wakeLock = null; } } /** * Shows the notification message and icon in the notification bar. */ private void showNotification() { final ApiLevelAdapter apiLevelAdapter = ApiFeatures.getInstance().getApiAdapter(); if (isRecording) { Notification notification = new Notification( R.drawable.arrow_320, null /* tickerText */, System.currentTimeMillis()); PendingIntent contentIntent = PendingIntent.getActivity( this, 0 /* requestCode */, new Intent(this, MyTracks.class), 0 /* flags */); notification.setLatestEventInfo(this, getString(R.string.my_tracks_app_name), getString(R.string.track_record_notification), contentIntent); notification.flags += Notification.FLAG_NO_CLEAR; apiLevelAdapter.startForeground(this, notificationManager, 1, notification); } else { apiLevelAdapter.stopForeground(this, notificationManager, 1); } } private void setUpTaskExecutors() { announcementExecutor = new PeriodicTaskExecutor( this, new StatusAnnouncerFactory(ApiFeatures.getInstance())); splitExecutor = new PeriodicTaskExecutor(this, new SplitTask.Factory()); } private void shutdownTaskExecutors() { Log.d(TAG, "TrackRecordingService.shutdownExecuters"); try { announcementExecutor.shutdown(); } finally { announcementExecutor = null; } try { splitExecutor.shutdown(); } finally { splitExecutor = null; } } private void registerLocationListener() { if (locationManager == null) { Log.e(TAG, "TrackRecordingService: Do not have any location manager."); return; } Log.d(TAG, "Preparing to register location listener w/ TrackRecordingService..."); try { long desiredInterval = locationListenerPolicy.getDesiredPollingInterval(); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, desiredInterval, locationListenerPolicy.getMinDistance(), // , 0 /* minDistance, get all updates to properly time pauses */ locationListener); currentRecordingInterval = desiredInterval; Log.d(TAG, "...location listener now registered w/ TrackRecordingService @ " + currentRecordingInterval); } catch (RuntimeException e) { Log.e(TAG, "Could not register location listener: " + e.getMessage(), e); } } private void unregisterLocationListener() { if (locationManager == null) { Log.e(TAG, "TrackRecordingService: Do not have any location manager."); return; } locationManager.removeUpdates(locationListener); Log.d(TAG, "Location listener now unregistered w/ TrackRecordingService."); } private String getDefaultActivityType(Context context) { SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); return prefs.getString(context.getString(R.string.default_activity_key), ""); } /* * Recording lifecycle. */ private long startNewTrack() { Log.d(TAG, "TrackRecordingService.startNewTrack"); if (isTrackInProgress()) { return -1L; } long startTime = System.currentTimeMillis(); acquireWakeLock(); Track track = new Track(); TripStatistics trackStats = track.getStatistics(); trackStats.setStartTime(startTime); track.setStartId(-1); Uri trackUri = providerUtils.insertTrack(track); recordingTrackId = Long.parseLong(trackUri.getLastPathSegment()); track.setId(recordingTrackId); track.setName(new DefaultTrackNameFactory(this).newTrackName( recordingTrackId, startTime)); track.setCategory(getDefaultActivityType(this)); isRecording = true; isMoving = true; providerUtils.updateTrack(track); statsBuilder = new TripStatisticsBuilder(startTime); statsBuilder.setMinRecordingDistance(minRecordingDistance); waypointStatsBuilder = new TripStatisticsBuilder(startTime); waypointStatsBuilder.setMinRecordingDistance(minRecordingDistance); currentWaypointId = insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS); length = 0; showNotification(); registerLocationListener(); sensorManager = SensorManagerFactory.getSensorManager(this); if (sensorManager != null) { sensorManager.onStartTrack(); } // Reset the number of auto-resume retries. setAutoResumeTrackRetries(0); // Persist the current recording track. prefManager.setRecordingTrack(recordingTrackId); // Notify the world that we're now recording. sendTrackBroadcast( R.string.track_started_broadcast_action, recordingTrackId); announcementExecutor.restore(); splitExecutor.restore(); return recordingTrackId; } private void restoreStats(Track track) { Log.d(TAG, "Restoring stats of track with ID: " + track.getId()); TripStatistics stats = track.getStatistics(); statsBuilder = new TripStatisticsBuilder(stats.getStartTime()); statsBuilder.setMinRecordingDistance(minRecordingDistance); length = 0; lastValidLocation = null; Waypoint waypoint = providerUtils.getFirstWaypoint(recordingTrackId); if (waypoint != null && waypoint.getStatistics() != null) { currentWaypointId = waypoint.getId(); waypointStatsBuilder = new TripStatisticsBuilder( waypoint.getStatistics()); } else { // This should never happen, but we got to do something so life goes on: waypointStatsBuilder = new TripStatisticsBuilder(stats.getStartTime()); currentWaypointId = -1; } waypointStatsBuilder.setMinRecordingDistance(minRecordingDistance); Cursor cursor = null; try { cursor = providerUtils.getLocationsCursor( recordingTrackId, -1, Constants.MAX_LOADED_TRACK_POINTS, true); if (cursor != null) { if (cursor.moveToLast()) { do { Location location = providerUtils.createLocation(cursor); if (LocationUtils.isValidLocation(location)) { statsBuilder.addLocation(location, location.getTime()); if (lastValidLocation != null) { length += location.distanceTo(lastValidLocation); } lastValidLocation = location; } } while (cursor.moveToPrevious()); } statsBuilder.getStatistics().setMovingTime(stats.getMovingTime()); statsBuilder.pauseAt(stats.getStopTime()); statsBuilder.resumeAt(System.currentTimeMillis()); } else { Log.e(TAG, "Could not get track points cursor."); } } catch (RuntimeException e) { Log.e(TAG, "Error while restoring track.", e); } finally { if (cursor != null) { cursor.close(); } } announcementExecutor.restore(); splitExecutor.restore(); } private void onLocationChangedAsync(Location location) { Log.d(TAG, "TrackRecordingService.onLocationChanged"); try { // Don't record if the service has been asked to pause recording: if (!isRecording) { Log.w(TAG, "Not recording because recording has been paused."); return; } // This should never happen, but just in case (we really don't want the // service to crash): if (location == null) { Log.w(TAG, "Location changed, but location is null."); return; } // Don't record if the accuracy is too bad: if (location.getAccuracy() > minRequiredAccuracy) { Log.d(TAG, "Not recording. Bad accuracy."); return; } // At least one track must be available for appending points: recordingTrack = getRecordingTrack(); if (recordingTrack == null) { Log.d(TAG, "Not recording. No track to append to available."); return; } // Update the idle time if needed. locationListenerPolicy.updateIdleTime(statsBuilder.getIdleTime()); addLocationToStats(location); if (currentRecordingInterval != locationListenerPolicy.getDesiredPollingInterval()) { registerLocationListener(); } Location lastRecordedLocation = providerUtils.getLastLocation(); double distanceToLastRecorded = Double.POSITIVE_INFINITY; if (lastRecordedLocation != null) { distanceToLastRecorded = location.distanceTo(lastRecordedLocation); } double distanceToLast = Double.POSITIVE_INFINITY; if (lastLocation != null) { distanceToLast = location.distanceTo(lastLocation); } boolean hasSensorData = sensorManager != null && sensorManager.isEnabled() && sensorManager.getSensorDataSet() != null && sensorManager.isDataValid(); // If the user has been stationary for two recording just record the first // two and ignore the rest. This code will only have an effect if the // maxRecordingDistance = 0 if (distanceToLast == 0 && !hasSensorData) { if (isMoving) { Log.d(TAG, "Found two identical locations."); isMoving = false; if (lastLocation != null && lastRecordedLocation != null && !lastRecordedLocation.equals(lastLocation)) { // Need to write the last location. This will happen when // lastRecordedLocation.distance(lastLocation) < // minRecordingDistance if (!insertLocation(lastLocation, lastRecordedLocation, recordingTrackId)) { return; } } } else { Log.d(TAG, "Not recording. More than two identical locations."); } } else if (distanceToLastRecorded > minRecordingDistance || hasSensorData) { if (lastLocation != null && !isMoving) { // Last location was the last stationary location. Need to go back and // add it. if (!insertLocation(lastLocation, lastRecordedLocation, recordingTrackId)) { return; } isMoving = true; } // If separation from last recorded point is too large insert a // separator to indicate end of a segment: boolean startNewSegment = lastRecordedLocation != null && lastRecordedLocation.getLatitude() < 90 && distanceToLastRecorded > maxRecordingDistance && recordingTrack.getStartId() >= 0; if (startNewSegment) { // Insert a separator point to indicate start of new track: Log.d(TAG, "Inserting a separator."); Location separator = new Location(LocationManager.GPS_PROVIDER); separator.setLongitude(0); separator.setLatitude(100); separator.setTime(lastRecordedLocation.getTime()); providerUtils.insertTrackPoint(separator, recordingTrackId); } if (!insertLocation(location, lastRecordedLocation, recordingTrackId)) { return; } } else { Log.d(TAG, String.format( "Not recording. Distance to last recorded point (%f m) is less than" + " %d m.", distanceToLastRecorded, minRecordingDistance)); // Return here so that the location is NOT recorded as the last location. return; } } catch (Error e) { // Probably important enough to rethrow. Log.e(TAG, "Error in onLocationChanged", e); throw e; } catch (RuntimeException e) { // Safe usually to trap exceptions. Log.e(TAG, "Trapping exception in onLocationChanged", e); throw e; } lastLocation = location; } /** * Inserts a new location in the track points db and updates the corresponding * track in the track db. * * @param location the location to be inserted * @param lastRecordedLocation the last recorded location before this one (or * null if none) * @param trackId the id of the track * @return true if successful. False if SQLite3 threw an exception. */ private boolean insertLocation(Location location, Location lastRecordedLocation, long trackId) { // Keep track of length along recorded track (needed when a waypoint is // inserted): if (LocationUtils.isValidLocation(location)) { if (lastValidLocation != null) { length += location.distanceTo(lastValidLocation); } lastValidLocation = location; } // Insert the new location: try { Location locationToInsert = location; if (sensorManager != null && sensorManager.isEnabled()) { SensorDataSet sd = sensorManager.getSensorDataSet(); if (sd != null && sensorManager.isDataValid()) { locationToInsert = new MyTracksLocation(location, sd); } } Uri pointUri = providerUtils.insertTrackPoint(locationToInsert, trackId); int pointId = Integer.parseInt(pointUri.getLastPathSegment()); // Update the current track: if (lastRecordedLocation != null && lastRecordedLocation.getLatitude() < 90) { ContentValues values = new ContentValues(); TripStatistics stats = statsBuilder.getStatistics(); if (recordingTrack.getStartId() < 0) { values.put(TracksColumns.STARTID, pointId); recordingTrack.setStartId(pointId); } values.put(TracksColumns.STOPID, pointId); values.put(TracksColumns.STOPTIME, System.currentTimeMillis()); values.put(TracksColumns.NUMPOINTS, recordingTrack.getNumberOfPoints() + 1); values.put(TracksColumns.MINLAT, stats.getBottom()); values.put(TracksColumns.MAXLAT, stats.getTop()); values.put(TracksColumns.MINLON, stats.getLeft()); values.put(TracksColumns.MAXLON, stats.getRight()); values.put(TracksColumns.TOTALDISTANCE, stats.getTotalDistance()); values.put(TracksColumns.TOTALTIME, stats.getTotalTime()); values.put(TracksColumns.MOVINGTIME, stats.getMovingTime()); values.put(TracksColumns.AVGSPEED, stats.getAverageSpeed()); values.put(TracksColumns.AVGMOVINGSPEED, stats.getAverageMovingSpeed()); values.put(TracksColumns.MAXSPEED, stats.getMaxSpeed()); values.put(TracksColumns.MINELEVATION, stats.getMinElevation()); values.put(TracksColumns.MAXELEVATION, stats.getMaxElevation()); values.put(TracksColumns.ELEVATIONGAIN, stats.getTotalElevationGain()); values.put(TracksColumns.MINGRADE, stats.getMinGrade()); values.put(TracksColumns.MAXGRADE, stats.getMaxGrade()); getContentResolver().update(TracksColumns.CONTENT_URI, values, "_id=" + recordingTrack.getId(), null); updateCurrentWaypoint(); } } catch (SQLiteException e) { // Insert failed, most likely because of SqlLite error code 5 // (SQLite_BUSY). This is expected to happen extremely rarely (if our // listener gets invoked twice at about the same time). Log.w(TAG, "Caught SQLiteException: " + e.getMessage(), e); return false; } announcementExecutor.update(); splitExecutor.update(); return true; } private void updateCurrentWaypoint() { if (currentWaypointId >= 0) { ContentValues values = new ContentValues(); TripStatistics waypointStats = waypointStatsBuilder.getStatistics(); values.put(WaypointsColumns.STARTTIME, waypointStats.getStartTime()); values.put(WaypointsColumns.LENGTH, length); values.put(WaypointsColumns.DURATION, System.currentTimeMillis() - statsBuilder.getStatistics().getStartTime()); values.put(WaypointsColumns.TOTALDISTANCE, waypointStats.getTotalDistance()); values.put(WaypointsColumns.TOTALTIME, waypointStats.getTotalTime()); values.put(WaypointsColumns.MOVINGTIME, waypointStats.getMovingTime()); values.put(WaypointsColumns.AVGSPEED, waypointStats.getAverageSpeed()); values.put(WaypointsColumns.AVGMOVINGSPEED, waypointStats.getAverageMovingSpeed()); values.put(WaypointsColumns.MAXSPEED, waypointStats.getMaxSpeed()); values.put(WaypointsColumns.MINELEVATION, waypointStats.getMinElevation()); values.put(WaypointsColumns.MAXELEVATION, waypointStats.getMaxElevation()); values.put(WaypointsColumns.ELEVATIONGAIN, waypointStats.getTotalElevationGain()); values.put(WaypointsColumns.MINGRADE, waypointStats.getMinGrade()); values.put(WaypointsColumns.MAXGRADE, waypointStats.getMaxGrade()); getContentResolver().update(WaypointsColumns.CONTENT_URI, values, "_id=" + currentWaypointId, null); } } private void addLocationToStats(Location location) { if (LocationUtils.isValidLocation(location)) { long now = System.currentTimeMillis(); statsBuilder.addLocation(location, now); waypointStatsBuilder.addLocation(location, now); } } /* * Application lifetime events: ============================ */ public long insertWaypoint(WaypointCreationRequest request) { if (!isRecording()) { throw new IllegalStateException( "Unable to insert waypoint marker while not recording!"); } if (request == null) { request = WaypointCreationRequest.DEFAULT_MARKER; } Waypoint wpt = new Waypoint(); switch (request.getType()) { case MARKER: buildMarker(wpt, request); break; case STATISTICS: buildStatisticsMarker(wpt); break; } wpt.setTrackId(recordingTrackId); wpt.setLength(length); if (lastLocation == null || statsBuilder == null || statsBuilder.getStatistics() == null) { // A null location is ok, and expected on track start. // Make it an impossible location. Location l = new Location(""); l.setLatitude(100); l.setLongitude(180); wpt.setLocation(l); } else { wpt.setLocation(lastLocation); wpt.setDuration(lastLocation.getTime() - statsBuilder.getStatistics().getStartTime()); } Uri uri = providerUtils.insertWaypoint(wpt); return Long.parseLong(uri.getLastPathSegment()); } private void buildMarker(Waypoint wpt, WaypointCreationRequest request) { wpt.setType(Waypoint.TYPE_WAYPOINT); if (request.getIconUrl() == null) { wpt.setIcon(getString(R.string.marker_waypoint_icon_url)); } else { wpt.setIcon(request.getIconUrl()); } if (request.getName() == null) { wpt.setName(getString(R.string.marker_type_waypoint)); } else { wpt.setName(request.getName()); } if (request.getDescription() != null) { wpt.setDescription(request.getDescription()); } } /** * Build a statistics marker. * A statistics marker holds the stats for the* last segment up to this marker. * * @param waypoint The waypoint which will be populated with stats data. */ private void buildStatisticsMarker(Waypoint waypoint) { StringUtils utils = new StringUtils(TrackRecordingService.this); // Set stop and total time in the stats data final long time = System.currentTimeMillis(); waypointStatsBuilder.pauseAt(time); // Override the duration - it's not the duration from the last waypoint, but // the duration from the beginning of the whole track waypoint.setDuration(time - statsBuilder.getStatistics().getStartTime()); // Set the rest of the waypoint data waypoint.setType(Waypoint.TYPE_STATISTICS); waypoint.setName(getString(R.string.marker_type_statistics)); waypoint.setStatistics(waypointStatsBuilder.getStatistics()); waypoint.setDescription(utils.generateWaypointDescription(waypoint)); waypoint.setIcon(getString(R.string.marker_statistics_icon_url)); waypoint.setStartId(providerUtils.getLastLocationId(recordingTrackId)); // Create a new stats keeper for the next marker. waypointStatsBuilder = new TripStatisticsBuilder(time); } private void endCurrentTrack() { Log.d(TAG, "TrackRecordingService.endCurrentTrack"); if (!isTrackInProgress()) { return; } announcementExecutor.shutdown(); splitExecutor.shutdown(); isRecording = false; Track recordedTrack = providerUtils.getTrack(recordingTrackId); if (recordedTrack != null) { TripStatistics stats = recordedTrack.getStatistics(); stats.setStopTime(System.currentTimeMillis()); stats.setTotalTime(stats.getStopTime() - stats.getStartTime()); long lastRecordedLocationId = providerUtils.getLastLocationId(recordingTrackId); ContentValues values = new ContentValues(); if (lastRecordedLocationId >= 0 && recordedTrack.getStopId() >= 0) { values.put(TracksColumns.STOPID, lastRecordedLocationId); } values.put(TracksColumns.STOPTIME, stats.getStopTime()); values.put(TracksColumns.TOTALTIME, stats.getTotalTime()); getContentResolver().update(TracksColumns.CONTENT_URI, values, "_id=" + recordedTrack.getId(), null); } showNotification(); long recordedTrackId = recordingTrackId; prefManager.setRecordingTrack(recordingTrackId = -1); if (sensorManager != null) { sensorManager.shutdown(); sensorManager = null; } releaseWakeLock(); // Notify the world that we're no longer recording. sendTrackBroadcast( R.string.track_stopped_broadcast_action, recordedTrackId); stopSelf(); } private void sendTrackBroadcast(int actionResId, long trackId) { Intent broadcastIntent = new Intent() .setAction(getString(actionResId)) .putExtra(getString(R.string.track_id_broadcast_extra), trackId); sendBroadcast(broadcastIntent, getString(R.string.permission_notification_value)); SharedPreferences sharedPreferences = getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (sharedPreferences.getBoolean(getString(R.string.allow_access_key), false)) { sendBroadcast(broadcastIntent, getString(R.string.broadcast_notifications_permission)); } } /* * Data/state access. */ private Track getRecordingTrack() { if (recordingTrackId < 0) { return null; } return providerUtils.getTrack(recordingTrackId); } public boolean isRecording() { return isRecording; } public TripStatistics getTripStatistics() { return statsBuilder.getStatistics(); } Location getLastLocation() { return lastLocation; } long getRecordingTrackId() { return recordingTrackId; } void setRecordingTrackId(long recordingTrackId) { this.recordingTrackId = recordingTrackId; } void setMaxRecordingDistance(int maxRecordingDistance) { this.maxRecordingDistance = maxRecordingDistance; } void setMinRecordingDistance(int minRecordingDistance) { this.minRecordingDistance = minRecordingDistance; if (statsBuilder != null && waypointStatsBuilder != null) { statsBuilder.setMinRecordingDistance(minRecordingDistance); waypointStatsBuilder.setMinRecordingDistance(minRecordingDistance); } } void setMinRequiredAccuracy(int minRequiredAccuracy) { this.minRequiredAccuracy = minRequiredAccuracy; } void setLocationListenerPolicy(LocationListenerPolicy locationListenerPolicy) { this.locationListenerPolicy = locationListenerPolicy; } void setAutoResumeTrackTimeout(int autoResumeTrackTimeout) { this.autoResumeTrackTimeout = autoResumeTrackTimeout; } void setAnnouncementFrequency(int announcementFrequency) { announcementExecutor.setTaskFrequency(announcementFrequency); } void setSplitFrequency(int frequency) { splitExecutor.setTaskFrequency(frequency); } void setMetricUnits(boolean metric) { announcementExecutor.setMetricUnits(metric); splitExecutor.setMetricUnits(metric); } /** * TODO: There is a bug in Android that leaks Binder instances. This bug is * especially visible if we have a non-static class, as there is no way to * nullify reference to the outer class (the service). * A workaround is to use a static class and explicitly clear service * and detach it from the underlying Binder. With this approach, we minimize * the leak to 24 bytes per each service instance. * * For more details, see the following bug: * http://code.google.com/p/android/issues/detail?id=6426. */ private static class ServiceBinder extends ITrackRecordingService.Stub { private TrackRecordingService service; private DeathRecipient deathRecipient; public ServiceBinder(TrackRecordingService service) { this.service = service; } // Logic for letting the actual service go up and down. @Override public boolean isBinderAlive() { // Pretend dead if the service went down. return service != null; } @Override public boolean pingBinder() { return isBinderAlive(); } @Override public void linkToDeath(DeathRecipient recipient, int flags) { deathRecipient = recipient; } @Override public boolean unlinkToDeath(DeathRecipient recipient, int flags) { if (!isBinderAlive()) { return false; } deathRecipient = null; return true; } /** * Clears the reference to the outer class to minimize the leak. */ private void detachFromService() { this.service = null; attachInterface(null, null); if (deathRecipient != null) { deathRecipient.binderDied(); } } /** * Checks if the service is available. If not, throws an * {@link IllegalStateException}. */ private void checkService() { if (service == null) { throw new IllegalStateException("The service has been already detached!"); } } /** * Returns true if the RPC caller is from the same application or if the * "Allow access" setting indicates that another app can invoke this service's * RPCs. */ private boolean canAccess() { // As a precondition for access, must check if the service is available. checkService(); if (Process.myPid() == Binder.getCallingPid()) { return true; } else { SharedPreferences sharedPreferences = service.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); return sharedPreferences.getBoolean(service.getString(R.string.allow_access_key), false); } } // Service method delegates. @Override public boolean isRecording() { if (!canAccess()) { return false; } return service.isRecording(); } @Override public long getRecordingTrackId() { if (!canAccess()) { return -1L; } return service.recordingTrackId; } @Override public long startNewTrack() { if (!canAccess()) { return -1L; } return service.startNewTrack(); } /** * Inserts a waypoint marker in the track being recorded. * * @param request Details of the waypoint to insert * @return the unique ID of the inserted marker */ public long insertWaypoint(WaypointCreationRequest request) { if (!canAccess()) { return -1L; } return service.insertWaypoint(request); } @Override public void endCurrentTrack() { if (!canAccess()) { return; } service.endCurrentTrack(); } @Override public void recordLocation(Location loc) { if (!canAccess()) { return; } service.locationListener.onLocationChanged(loc); } @Override public byte[] getSensorData() { if (!canAccess()) { return null; } if (service.sensorManager == null) { Log.d(TAG, "No sensor manager for data."); return null; } if (service.sensorManager.getSensorDataSet() == null) { Log.d(TAG, "Sensor data set is null."); return null; } return service.sensorManager.getSensorDataSet().toByteArray(); } @Override public int getSensorState() { if (!canAccess()) { return Sensor.SensorState.NONE.getNumber(); } if (service.sensorManager == null) { Log.d(TAG, "No sensor manager for data."); return Sensor.SensorState.NONE.getNumber(); } return service.sensorManager.getSensorState().getNumber(); } } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.services; import com.google.android.apps.mytracks.Constants; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import java.text.DateFormat; import java.util.Date; /** * Creates a default track name based on the current default track name policy. * * @author Matthew Simmons */ class DefaultTrackNameFactory { private final Context context; DefaultTrackNameFactory(Context context) { this.context = context; } /** * Creates a new track name. * * @param trackId The ID for the current track. * @param startTime The start time, in milliseconds since the epoch, of the * current track. * @return The new track name. */ String newTrackName(long trackId, long startTime) { if (useTimestampTrackName()) { DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); return formatter.format(new Date(startTime)); } else { return String.format(context.getString(R.string.track_name_format), trackId); } } /** Determines whether the preferences allow a timestamp-based track name */ protected boolean useTimestampTrackName() { SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); return prefs.getBoolean( context.getString(R.string.timestamp_track_name_key), true); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.services.sensors; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.maps.mytracks.R; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Context; import android.content.SharedPreferences; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.widget.Toast; import java.util.ArrayList; /** * Manage the connection to a bluetooth sensor. * * @author Sandor Dornbush */ public class BluetoothSensorManager extends SensorManager { // Local Bluetooth adapter private static final BluetoothAdapter bluetoothAdapter = getDefaultBluetoothAdapter(); // Member object for the sensor threads and connections. private BluetoothConnectionManager connectionManager = null; // Name of the connected device private String connectedDeviceName = null; private Context context = null; private Sensor.SensorDataSet sensorDataSet = null; private MessageParser parser; public BluetoothSensorManager( Context context, MessageParser parser) { this.context = context; this.parser = parser; // If BT is not available or not enabled quit. if (!isEnabled()) { return; } setupSensor(); } private void setupSensor() { Log.d(Constants.TAG, "setupSensor()"); // Initialize the BluetoothSensorAdapter to perform bluetooth connections. connectionManager = new BluetoothConnectionManager(messageHandler, parser); } /** * Code for assigning the local bluetooth adapter * * @return The default bluetooth adapter, if one is available, NULL if it isn't. */ private static BluetoothAdapter getDefaultBluetoothAdapter() { // Check if the calling thread is the main application thread, // if it is, do it directly. if (Thread.currentThread().equals(Looper.getMainLooper().getThread())) { return BluetoothAdapter.getDefaultAdapter(); } // If the calling thread, isn't the main application thread, // then get the main application thread to return the default adapter. final ArrayList<BluetoothAdapter> adapters = new ArrayList<BluetoothAdapter>(1); final Object mutex = new Object(); Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { adapters.add(BluetoothAdapter.getDefaultAdapter()); synchronized (mutex) { mutex.notify(); } } }); while (adapters.isEmpty()) { synchronized (mutex) { try { mutex.wait(1000L); } catch (InterruptedException e) { Log.e(TAG, "Interrupted while waiting for default bluetooth adapter", e); } } } if (adapters.get(0) == null) { Log.w(TAG, "No bluetooth adapter found!"); } return adapters.get(0); } public boolean isEnabled() { return bluetoothAdapter != null && bluetoothAdapter.isEnabled(); } public void setupChannel() { if (!isEnabled() || connectionManager == null) { Log.w(Constants.TAG, "Disabled manager onStartTrack"); return; } SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); String address = prefs.getString(context.getString(R.string.bluetooth_sensor_key), null); if (address == null) { return; } Log.w(Constants.TAG, "Connecting to bluetooth sensor: " + address); // Get the BluetoothDevice object BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address); // Attempt to connect to the device connectionManager.connect(device); // Performing this check in onResume() covers the case in which BT was // not enabled during onStart(), so we were paused to enable it... // onResume() will be called when ACTION_REQUEST_ENABLE activity returns. if (connectionManager != null) { // Only if the state is STATE_NONE, do we know that we haven't started // already if (connectionManager.getState() == Sensor.SensorState.NONE) { // Start the Bluetooth sensor services Log.w(Constants.TAG, "Disabled manager onStartTrack"); connectionManager.start(); } } } public void onDestroy() { // Stop the Bluetooth sensor services if (connectionManager != null) { connectionManager.stop(); } } public Sensor.SensorDataSet getSensorDataSet() { return sensorDataSet; } public Sensor.SensorState getSensorState() { return (connectionManager == null) ? Sensor.SensorState.NONE : connectionManager.getState(); } // The Handler that gets information back from the BluetoothSensorService private final Handler messageHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { switch (msg.what) { case BluetoothConnectionManager.MESSAGE_STATE_CHANGE: // TODO should we update the SensorManager state var? Log.i(Constants.TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1); break; case BluetoothConnectionManager.MESSAGE_WRITE: break; case BluetoothConnectionManager.MESSAGE_READ: byte[] readBuf = null; try { readBuf = (byte[]) msg.obj; sensorDataSet = parser.parseBuffer(readBuf); Log.d(Constants.TAG, "MESSAGE_READ: " + sensorDataSet.toString()); } catch (IllegalArgumentException iae) { sensorDataSet = null; Log.i(Constants.TAG, "Got bad sensor data: " + new String(readBuf, 0, readBuf.length), iae); } catch (RuntimeException re) { sensorDataSet = null; Log.i(Constants.TAG, "Unexpected exception on read.", re); } break; case BluetoothConnectionManager.MESSAGE_DEVICE_NAME: // save the connected device's name connectedDeviceName = msg.getData().getString(BluetoothConnectionManager.DEVICE_NAME); Toast.makeText(context.getApplicationContext(), "Connected to " + connectedDeviceName, Toast.LENGTH_SHORT) .show(); break; } } }; }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.services.sensors; import android.content.Context; public class ZephyrSensorManager extends BluetoothSensorManager { public ZephyrSensorManager(Context context) { super(context, new ZephyrMessageParser()); } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.services.sensors; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.maps.mytracks.R; import android.content.Context; /** * A collection of methods for message parsers. * * @author Sandor Dornbush * @author Nico Laum */ public class SensorUtils { private SensorUtils() { } /** * Extract one unsigned short from a big endian byte array. * * @param buffer the buffer to extract the short from * @param index the first byte to be interpreted as part of the short * @return The unsigned short at the given index in the buffer */ public static int unsignedShortToInt(byte[] buffer, int index) { int r = (buffer[index] & 0xFF) << 8; r |= buffer[index + 1] & 0xFF; return r; } /** * Extract one unsigned short from a little endian byte array. * * @param buffer the buffer to extract the short from * @param index the first byte to be interpreted as part of the short * @return The unsigned short at the given index in the buffer */ public static int unsignedShortToIntLittleEndian(byte[] buffer, int index) { int r = buffer[index] & 0xFF; r |= (buffer[index + 1] & 0xFF) << 8; return r; } /** * Returns CRC8 (polynomial 0x8C) from byte array buffer[start] to * (excluding) buffer[start + length] * * @param buffer the byte array of data (payload) * @param start the position in the byte array where the payload begins * @param length the length * @return CRC8 value */ public static byte getCrc8(byte[] buffer, int start, int length) { byte crc = 0x0; for (int i = start; i < (start + length); i++) { crc = crc8PushByte(crc, buffer[i]); } return crc; } /** * Updates a CRC8 value by using the next byte passed to this method * * @param crc int of crc value * @param add the next byte to add to the CRC8 calculation */ private static byte crc8PushByte(byte crc, byte add) { crc = (byte) (crc ^ add); for (int i = 0; i < 8; i++) { if ((crc & 0x1) != 0x0) { // Using a 0xFF bit assures that 0-bits are introduced during the shift operation. // Otherwise, implicit casts to signed int could shift in 1-bits if the signed bit is 1. crc = (byte) (((crc & 0xFF) >> 1) ^ 0x8C); } else { crc = (byte) ((crc & 0xFF) >> 1); } } return crc; } public static String getStateAsString(Sensor.SensorState state, Context c) { switch (state) { case NONE: return c.getString(R.string.sensor_type_value_none); case CONNECTING: return c.getString(R.string.sensor_state_connecting); case CONNECTED: return c.getString(R.string.sensor_state_connected); case DISCONNECTED: return c.getString(R.string.sensor_state_disconnected); case SENDING: return c.getString(R.string.sensor_state_sending); default: return ""; } } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.services.sensors; import java.util.Timer; import java.util.TimerTask; import android.util.Log; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Sensor; /** * Manage the connection to a sensor. * * @author Sandor Dornbush */ public abstract class SensorManager { /** * The maximum age where the data is considered valid. */ public static final long MAX_AGE = 5000; /** * Time to wait after a time out to retry. */ public static final int RETRY_PERIOD = 30000; private Sensor.SensorState sensorState = Sensor.SensorState.NONE; private long sensorStateTimestamp = 0; /** * A task to run periodically to check to see if connection was lost. */ private TimerTask checkSensorManager = new TimerTask() { @Override public void run() { Log.i(Constants.TAG, "SensorManager state: " + getSensorState()); switch (getSensorState()) { case CONNECTING: long age = System.currentTimeMillis() - getSensorStateTimestamp(); if (age > 2 * RETRY_PERIOD) { Log.i(Constants.TAG, "Retrying connecting SensorManager."); setupChannel(); } break; case DISCONNECTED: Log.i(Constants.TAG, "Re-registering disconnected SensoManager."); setupChannel(); break; } } }; /** * This timer invokes periodically the checkLocationListener timer task. */ private final Timer timer = new Timer(); /** * Is the sensor that this manages enabled. * @return true if the sensor is enabled */ public abstract boolean isEnabled(); /** * This is called when my tracks starts recording a new track. * This is the place to open connections to the sensor. */ public void onStartTrack() { setupChannel(); timer.schedule(checkSensorManager, RETRY_PERIOD, RETRY_PERIOD); } /** * This method is used to set up any necessary connections to underlying * sensor hardware. */ protected abstract void setupChannel(); public void shutdown() { timer.cancel(); onDestroy(); } /** * This is called when my tracks stops recording. * This is the place to shutdown any open connections. */ public abstract void onDestroy(); /** * Return the last sensor reading. * @return The last reading from the sensor. */ public abstract Sensor.SensorDataSet getSensorDataSet(); public void setSensorState(Sensor.SensorState sensorState) { this.sensorState = sensorState; } /** * Return the current sensor state. * @return The current sensor state. */ public Sensor.SensorState getSensorState() { return sensorState; } public long getSensorStateTimestamp() { return sensorStateTimestamp; } /** * @return True if the data is recent enough to be considered valid. */ public boolean isDataValid() { return (System.currentTimeMillis() - getSensorDataSet().getCreationTime()) < MAX_AGE; } }
Java
/* * Copyright (C) 2010 Google Inc. * * 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.google.android.apps.mytracks.services.sensors; import com.google.android.apps.mytracks.content.Sensor; /** * An interface for parsing a byte array to a SensorData object. * * @author Sandor Dornbush */ public interface MessageParser { public int getFrameSize(); public Sensor.SensorDataSet parseBuffer(byte[] readBuff); public boolean isValid(byte[] buffer); public int findNextAlignment(byte[] buffer); }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.services.sensors.ant; import com.dsi.ant.AntDefine; import com.dsi.ant.AntInterface; import android.content.Context; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; /** * Utility methods for ANT functionality. * * Prefer use of this class to importing DSI ANT classes into code outside of * the sensors package. */ public class AntUtils { private AntUtils() {} /** Returns true if this device supports ANT sensors. */ public static boolean hasAntSupport(Context context) { return AntInterface.hasAntSupport(context); } /** * Finds the names of in the messages with the given value */ public static String antMessageToString(byte msg) { return findConstByteInClass(AntDefine.class, msg, "MESG_.*_ID"); } /** * Finds the names of in the events with the given value */ public static String antEventToStr(byte event) { return findConstByteInClass(AntDefine.class, event, ".*EVENT.*"); } /** * Finds a set of constant static byte field declarations in the class that have the given value * and whose name match the given pattern * @param cl class to search in * @param value value of constant static byte field declarations to match * @param regexPattern pattern to match against the name of the field * @return a set of the names of fields, expressed as a string */ private static String findConstByteInClass(Class<?> cl, byte value, String regexPattern) { Field[] fields = cl.getDeclaredFields(); Set<String> fieldSet = new HashSet<String>(); for (Field f : fields) { try { if (f.getType() == Byte.TYPE && (f.getModifiers() & Modifier.STATIC) != 0 && f.getName().matches(regexPattern) && f.getByte(null) == value) { fieldSet.add(f.getName()); } } catch (IllegalArgumentException e) { // ignore } catch (IllegalAccessException e) { // ignore } } return fieldSet.toString(); } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.services.sensors.ant; /** * This class decodes and encapsulates an ANT Channel ID message. * (ANT Message ID 0x51, Protocol & Usage guide v4.2 section 9.5.7.2) * * @author Matthew Simmons */ public class AntChannelIdMessage extends AntMessage { private byte channelNumber; private short deviceNumber; private byte deviceTypeId; private byte transmissionType; public AntChannelIdMessage(byte[] messageData) { channelNumber = messageData[0]; deviceNumber = decodeShort(messageData[1], messageData[2]); deviceTypeId = messageData[3]; transmissionType = messageData[4]; } /** Returns the channel number */ public byte getChannelNumber() { return channelNumber; } /** Returns the device number */ public short getDeviceNumber() { return deviceNumber; } /** Returns the device type */ public byte getDeviceTypeId() { return deviceTypeId; } /** Returns the transmission type */ public byte getTransmissionType() { return transmissionType; } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.services.sensors.ant; import static com.google.android.apps.mytracks.Constants.TAG; import com.dsi.ant.AntDefine; import com.dsi.ant.AntMesg; import com.dsi.ant.exception.AntInterfaceException; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.SystemUtils; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; /** * A sensor manager to the PC7 SRM ANT+ bridge. * * @author Sandor Dornbush * @author Umran Abdulla */ public class AntSrmBridgeSensorManager extends AntSensorManager { /* * These constants are defined by the ANT+ spec. */ public static final byte CHANNEL_NUMBER = 0; public static final byte NETWORK_NUMBER = 0; public static final byte DEVICE_TYPE = 12; public static final byte NETWORK_ID = 1; public static final short CHANNEL_PERIOD = 8192; public static final byte RF_FREQUENCY = 50; private static final int INDEX_MESSAGE_TYPE = 1; private static final int INDEX_MESSAGE_ID = 2; private static final int INDEX_MESSAGE_POWER = 3; private static final int INDEX_MESSAGE_SPEED = 5; private static final int INDEX_MESSAGE_CADENCE = 7; private static final int INDEX_MESSAGE_BPM = 8; private static final int MSG_INITIAL = 5; private static final int MSG_DATA = 6; private short deviceNumber; public AntSrmBridgeSensorManager(Context context) { super(context); Log.i(TAG, "new ANT SRM Bridge Sensor Manager created"); deviceNumber = WILDCARD; // First read the the device id that we will be pairing with. SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs != null) { deviceNumber = (short) prefs.getInt(context.getString( R.string.ant_srm_bridge_sensor_id_key), 0); } Log.i(TAG, "Will pair with device: " + deviceNumber); } @Override protected boolean handleMessage(byte messageId, byte[] messageData) { if (super.handleMessage(messageId, messageData)) { return true; } if (!SystemUtils.isRelease(context)) { Log.d(TAG, "Received ANT msg: " + AntUtils.antMessageToString(messageId) + "(" + messageId + ")"); } int channel = messageData[0] & AntDefine.CHANNEL_NUMBER_MASK; switch (channel) { case CHANNEL_NUMBER: decodeChannelMsg(messageId, messageData); break; default: Log.d(TAG, "Unhandled message: " + channel); } return true; } /** * Decode an ant device message. * @param messageData The byte array received from the device. */ private void decodeChannelMsg(int messageId, byte[] messageData) { switch (messageId) { case AntMesg.MESG_BROADCAST_DATA_ID: handleBroadcastData(messageData); break; case AntMesg.MESG_RESPONSE_EVENT_ID: handleMessageResponse(messageData); break; case AntMesg.MESG_CHANNEL_ID_ID: handleChannelId(messageData); break; default: Log.e(TAG, "Unexpected message id: " + messageId); } } private void handleBroadcastData(byte[] antMessage) { if (deviceNumber == WILDCARD) { try { getAntReceiver().ANTRequestMessage(CHANNEL_NUMBER, AntMesg.MESG_CHANNEL_ID_ID); } catch (AntInterfaceException e) { Log.e(TAG, "ANT error handling broadcast data", e); } Log.d(TAG, "Requesting channel id id."); } setSensorState(Sensor.SensorState.CONNECTED); int messageType = antMessage[INDEX_MESSAGE_TYPE] & 0xFF; Log.d(TAG, "Received message-type=" + messageType); switch (messageType) { case MSG_INITIAL: break; case MSG_DATA: parseDataMsg(antMessage); break; } } private void parseDataMsg(byte[] msg) { int messageId = msg[INDEX_MESSAGE_ID] & 0xFF; Log.d(TAG, "Received message-id=" + messageId); int powerVal = (((msg[INDEX_MESSAGE_POWER] & 0xFF) << 8) | (msg[INDEX_MESSAGE_POWER+1] & 0xFF)); @SuppressWarnings("unused") int speedVal = (((msg[INDEX_MESSAGE_SPEED] & 0xFF) << 8) | (msg[INDEX_MESSAGE_SPEED+1] & 0xFF)); int cadenceVal = (msg[INDEX_MESSAGE_CADENCE] & 0xFF); int bpmVal = (msg[INDEX_MESSAGE_BPM] & 0xFF); long time = System.currentTimeMillis(); Sensor.SensorData.Builder power = Sensor.SensorData.newBuilder() .setValue(powerVal) .setState(Sensor.SensorState.SENDING); /* * Although speed is available from the SRM Bridge, MyTracks doesn't use the value, and * computes speed from the GPS location data. */ // Sensor.SensorData.Builder speed = Sensor.SensorData.newBuilder().setValue(speedVal).setState( // Sensor.SensorState.SENDING); Sensor.SensorData.Builder cadence = Sensor.SensorData.newBuilder() .setValue(cadenceVal) .setState(Sensor.SensorState.SENDING); Sensor.SensorData.Builder bpm = Sensor.SensorData.newBuilder() .setValue(bpmVal) .setState(Sensor.SensorState.SENDING); sensorData = Sensor.SensorDataSet.newBuilder() .setCreationTime(time) .setPower(power) .setCadence(cadence) .setHeartRate(bpm) .build(); } void handleChannelId(byte[] rawMessage) { AntChannelIdMessage message = new AntChannelIdMessage(rawMessage); deviceNumber = message.getDeviceNumber(); Log.d(TAG, "Found device id: " + deviceNumber); SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putInt(context.getString(R.string.ant_srm_bridge_sensor_id_key), deviceNumber); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); } private void handleMessageResponse(byte[] rawMessage) { AntChannelResponseMessage message = new AntChannelResponseMessage(rawMessage); if (!SystemUtils.isRelease(context)) { Log.d(TAG, "Received ANT Response: " + AntUtils.antMessageToString(message.getMessageId()) + "(" + message.getMessageId() + ")" + ", Code: " + AntUtils.antEventToStr(message.getMessageCode()) + "(" + message.getMessageCode() + ")"); } switch (message.getMessageId()) { case AntMesg.MESG_EVENT_ID: if (message.getMessageCode() == AntDefine.EVENT_RX_SEARCH_TIMEOUT) { // Search timeout Log.w(TAG, "Search timed out. Unassigning channel."); try { getAntReceiver().ANTUnassignChannel((byte) 0); } catch (AntInterfaceException e) { Log.e(TAG, "ANT error unassigning channel", e); } } break; case AntMesg.MESG_UNASSIGN_CHANNEL_ID: setSensorState(Sensor.SensorState.DISCONNECTED); Log.i(TAG, "Disconnected from the sensor: " + getSensorState()); break; } } @Override protected void setupAntSensorChannels() { Log.i(TAG, "Setting up ANT sensor channels"); setupAntSensorChannel( NETWORK_NUMBER, CHANNEL_NUMBER, deviceNumber, DEVICE_TYPE, (byte) 0x01, CHANNEL_PERIOD, RF_FREQUENCY, (byte) 0); } public short getDeviceNumber() { return deviceNumber; } void setDeviceNumber(short deviceNumber) { this.deviceNumber = deviceNumber; } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.android.apps.mytracks.services.sensors.ant; import static com.google.android.apps.mytracks.Constants.TAG; import com.dsi.ant.AntDefine; import com.dsi.ant.AntMesg; import com.dsi.ant.exception.AntInterfaceException; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; /** * A sensor manager to connect ANT+ sensors. * This can include heart rate monitors. * * @author Sandor Dornbush */ public class AntDirectSensorManager extends AntSensorManager { /* * These constants are defined by the ANT+ heart rate monitor spec. */ public static final byte HRM_CHANNEL = 0; public static final byte NETWORK_NUMBER = 1; public static final byte HEART_RATE_DEVICE_TYPE = 120; public static final byte POWER_DEVICE_TYPE = 11; public static final byte MANUFACTURER_ID = 1; public static final short CHANNEL_PERIOD = 8070; public static final byte RF_FREQUENCY = 57; private short deviceNumberHRM; public AntDirectSensorManager(Context context) { super(context); deviceNumberHRM = WILDCARD; // First read the the device id that we will be pairing with. SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs != null) { deviceNumberHRM = (short) prefs.getInt(context.getString(R.string.ant_heart_rate_sensor_id_key), 0); } Log.i(TAG, "Will pair with heart rate monitor: " + deviceNumberHRM); } @Override protected boolean handleMessage(byte messageId, byte[] messageData) { if (super.handleMessage(messageId, messageData)) { return true; } int channel = messageData[0] & AntDefine.CHANNEL_NUMBER_MASK; switch (channel) { case HRM_CHANNEL: antDecodeHRM(messageId, messageData); break; default: Log.d(TAG, "Unhandled message: " + channel); } return true; } /** * Decode an ant heart rate monitor message. * @param messageData The byte array received from the heart rate monitor. */ private void antDecodeHRM(int messageId, byte[] messageData) { switch (messageId) { case AntMesg.MESG_BROADCAST_DATA_ID: handleBroadcastData(messageData); break; case AntMesg.MESG_RESPONSE_EVENT_ID: handleMessageResponse(messageData); break; case AntMesg.MESG_CHANNEL_ID_ID: handleChannelId(messageData); break; default: Log.e(TAG, "Unexpected message id: " + messageId); } } private void handleBroadcastData(byte[] antMessage) { if (deviceNumberHRM == WILDCARD) { try { getAntReceiver().ANTRequestMessage(HRM_CHANNEL, AntMesg.MESG_CHANNEL_ID_ID); } catch (AntInterfaceException e) { Log.e(TAG, "ANT error handling broadcast data", e); } Log.d(TAG, "Requesting channel id id."); } setSensorState(Sensor.SensorState.CONNECTED); int bpm = (int) antMessage[8] & 0xFF; Sensor.SensorData.Builder b = Sensor.SensorData.newBuilder() .setValue(bpm) .setState(Sensor.SensorState.SENDING); sensorData = Sensor.SensorDataSet.newBuilder() .setCreationTime(System.currentTimeMillis()) .setHeartRate(b) .build(); } void handleChannelId(byte[] rawMessage) { AntChannelIdMessage message = new AntChannelIdMessage(rawMessage); deviceNumberHRM = message.getDeviceNumber(); Log.i(TAG, "Found device id: " + deviceNumberHRM); SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putInt(context.getString(R.string.ant_heart_rate_sensor_id_key), deviceNumberHRM); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); } private void handleMessageResponse(byte[] rawMessage) { AntChannelResponseMessage message = new AntChannelResponseMessage(rawMessage); switch (message.getMessageId()) { case AntMesg.MESG_EVENT_ID: if (message.getMessageCode() == AntDefine.EVENT_RX_SEARCH_TIMEOUT) { // Search timeout Log.w(TAG, "Search timed out. Unassigning channel."); try { getAntReceiver().ANTUnassignChannel((byte) 0); } catch (AntInterfaceException e) { Log.e(TAG, "ANT error unassigning channel", e); } setSensorState(Sensor.SensorState.DISCONNECTED); } break; case AntMesg.MESG_UNASSIGN_CHANNEL_ID: setSensorState(Sensor.SensorState.DISCONNECTED); Log.i(TAG, "Disconnected from the sensor: " + getSensorState()); break; } } @Override protected void setupAntSensorChannels() { setupAntSensorChannel(NETWORK_NUMBER, HRM_CHANNEL, deviceNumberHRM, HEART_RATE_DEVICE_TYPE, (byte) 0x01, CHANNEL_PERIOD, RF_FREQUENCY, (byte) 0); } public short getDeviceNumberHRM() { return deviceNumberHRM; } void setDeviceNumberHRM(short deviceNumberHRM) { this.deviceNumberHRM = deviceNumberHRM; } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.services.sensors.ant; /** * This is a common superclass for ANT message subclasses. * * @author Matthew Simmons */ public class AntMessage { protected AntMessage() {} /** Build a short value from its constituent bytes */ protected static short decodeShort(byte b0, byte b1) { int value = b0 & 0xFF; value |= (b1 & 0xFF) << 8; return (short)value; } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.services.sensors.ant; /** * This class decodes and encapsulates an ANT Channel Response / Event message. * (ANT Message ID 0x40, Protocol & Usage guide v4.2 section 9.5.6.1) * * @author Matthew Simmons */ public class AntChannelResponseMessage extends AntMessage { private byte channelNumber; private byte messageId; private byte messageCode; public AntChannelResponseMessage(byte[] messageData) { channelNumber = messageData[0]; messageId = messageData[1]; messageCode = messageData[2]; } /** Returns the channel number */ public byte getChannelNumber() { return channelNumber; } /** Returns the ID of the message being responded to */ public byte getMessageId() { return messageId; } /** Returns the code for a specific response or event */ public byte getMessageCode() { return messageCode; } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.android.apps.mytracks.services.sensors.ant; import static com.google.android.apps.mytracks.Constants.TAG; import com.dsi.ant.AntDefine; import com.dsi.ant.AntInterface; import com.dsi.ant.AntInterfaceIntent; import com.dsi.ant.AntMesg; import com.dsi.ant.exception.AntInterfaceException; import com.dsi.ant.exception.AntServiceNotConnectedException; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.content.Sensor.SensorDataSet; import com.google.android.apps.mytracks.services.sensors.SensorManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; /** * This is the common superclass for ANT-based sensors. It handles tasks which * apply to the ANT framework as a whole, such as framework initialization and * destruction. Subclasses are expected to handle the initialization and * management of individual sensors. * * Implementation: * * The initialization process is somewhat complicated. This is due in part to * the asynchronous nature of ANT Radio Service initialization, and in part due * to an apparent bug in that service. The following is an overview of the * initialization process. * * Initialization begins in {@link #setupChannel}, which is invoked by the * {@link SensorManager} when track recording begins. {@link #setupChannel} * asks the ANT Radio Service (via {@link AntInterface}) to start, using a * {@link AntInterface.ServiceListener} to indicate when the service has * connected. {@link #serviceConnected} claims and enables the Radio Service, * and then resets it to a known state for our use. Completion of reset is * indicated by receipt of a startup message (see {@link AntStartupMessage}). * Once we've received that message, the ANT service is ready for use, and we * can start sensor-specific initialization using * {@link #setupAntSensorChannels}. The initialization of each sensor will * usually result in a call to {@link #setupAntSensorChannel}. * * @author Sandor Dornbush */ public abstract class AntSensorManager extends SensorManager { // Pairing protected static final short WILDCARD = 0; private AntInterface antReceiver; /** * The data from the sensors. */ protected SensorDataSet sensorData; protected Context context; private static final boolean DEBUGGING = false; /** Receives and logs all status ANT intents. */ private final BroadcastReceiver statusReceiver = new BroadcastReceiver() { @Override public void onReceive(Context ctx, Intent intent) { String antAction = intent.getAction(); Log.i(TAG, "enter status onReceive" + antAction); } }; /** Receives all data ANT intents. */ private final BroadcastReceiver dataReceiver = new BroadcastReceiver() { @Override public void onReceive(Context ctx, Intent intent) { String antAction = intent.getAction(); Log.i(TAG, "enter data onReceive" + antAction); if (antAction != null && antAction.equals(AntInterfaceIntent.ANT_RX_MESSAGE_ACTION)) { byte[] antMessage = intent.getByteArrayExtra(AntInterfaceIntent.ANT_MESSAGE); if (DEBUGGING) { Log.d(TAG, "Received RX message " + messageToString(antMessage)); } handleMessage(antMessage); } } }; /** * ANT uses this listener to tell us when it has bound to the ANT Radio * Service. We can't start sending ANT commands until we've been notified * (via this listener) that the Radio Service has connected. */ private AntInterface.ServiceListener antServiceListener = new AntInterface.ServiceListener() { @Override public void onServiceConnected() { serviceConnected(); } @Override public void onServiceDisconnected() { Log.d(TAG, "ANT interface reports disconnection"); } }; public AntSensorManager(Context context) { this.context = context; // We register for ANT intents early because we want to have a record of // the status intents in the log as we start up. registerForAntIntents(); } @Override public void onDestroy() { Log.i(TAG, "destroying AntSensorManager"); cleanAntInterface(); unregisterForAntIntents(); } @Override public SensorDataSet getSensorDataSet() { return sensorData; } @Override public boolean isEnabled() { return true; } public AntInterface getAntReceiver() { return antReceiver; } /** * This is the interface used by the {@link SensorManager} to tell this * class when to start. It handles initialization of the ANT framework, * eventually resulting in sensor-specific initialization via * {@link #setupAntSensorChannels}. */ @Override protected final void setupChannel() { setup(); } private synchronized void setup() { // We handle this unpleasantly because the UI should've checked for ANT // support before it even instantiated this class. if (!AntInterface.hasAntSupport(context)) { throw new IllegalStateException("device does not have ANT support"); } cleanAntInterface(); antReceiver = AntInterface.getInstance(context, antServiceListener); if (antReceiver == null) { Log.e(TAG, "Failed to get ANT Receiver"); return; } setSensorState(Sensor.SensorState.CONNECTING); } /** * Cleans up the ANT+ receiver interface, by releasing the interface * and destroying it. */ private void cleanAntInterface() { Log.i(TAG, "Destroying AntSensorManager"); if (antReceiver == null) { Log.e(TAG, "no ANT receiver"); return; } try { antReceiver.releaseInterface(); antReceiver.destroy(); antReceiver = null; } catch (AntServiceNotConnectedException e) { Log.i(TAG, "ANT service not connected", e); } catch (AntInterfaceException e) { Log.e(TAG, "failed to release ANT interface", e); } catch (RuntimeException e) { Log.e(TAG, "run-time exception when cleaning the ANT interface", e); } } /** * This method is invoked via the ServiceListener when we're connected to * the ANT service. If we're just starting up, this is our first opportunity * to initiate any ANT commands. */ private synchronized void serviceConnected() { Log.d(TAG, "ANT service connected"); if (antReceiver == null) { Log.e(TAG, "no ANT receiver"); return; } try { if (!antReceiver.claimInterface()) { Log.e(TAG, "failed to claim ANT interface"); return; } if (!antReceiver.isEnabled()) { // Make sure not to call AntInterface.enable() again, if it has been // already called before Log.i(TAG, "Powering on Radio"); antReceiver.enable(); } else { Log.i(TAG, "Radio already enabled"); } } catch (AntInterfaceException e) { Log.e(TAG, "failed to enable ANT", e); } try { // We expect this call to throw an exception due to a bug in the ANT // Radio Service. It won't actually fail, though, as we'll get the // startup message (see {@link AntStartupMessage}) one normally expects // after a reset. Channel initialization can proceed once we receive // that message. antReceiver.ANTResetSystem(); } catch (AntInterfaceException e) { Log.e(TAG, "failed to reset ANT (expected exception)", e); } } /** * Process a raw ANT message. * @param antMessage the ANT message, including the size and message ID bytes * @deprecated Use {@link #handleMessage(byte, byte[])} instead. */ protected void handleMessage(byte[] antMessage) { int len = antMessage[0]; if (len != antMessage.length - 2 || antMessage.length <= 2) { Log.e(TAG, "Invalid message: " + messageToString(antMessage)); return; } byte messageId = antMessage[1]; // Arrays#copyOfRange doesn't exist?? byte[] messageData = new byte[antMessage.length - 2]; System.arraycopy(antMessage, 2, messageData, 0, antMessage.length - 2); handleMessage(messageId, messageData); } /** * Process a raw ANT message. * @param messageId the message ID. See the ANT Message Protocol and Usage * guide, section 9.3. * @param messageData the ANT message, without the size and message ID bytes. * @return true if this method has taken responsibility for the passed * message; false otherwise. */ protected boolean handleMessage(byte messageId, byte[] messageData) { if (messageId == AntMesg.MESG_STARTUP_MESG_ID) { Log.d(TAG, String.format( "Received startup message (reason %02x); initializing channel", new AntStartupMessage(messageData).getMessage())); setupAntSensorChannels(); return true; } return false; } /** * Subclasses define this method to perform sensor-specific initialization. * When this method is called, the ANT framework has been enabled, and is * ready for use. */ protected abstract void setupAntSensorChannels(); /** * Used by subclasses to set up an ANT channel for a single sensor. A given * subclass may invoke this method multiple times if the subclass is * responsible for more than one sensor. * * @return true on success */ protected boolean setupAntSensorChannel(byte networkNumber, byte channelNumber, short deviceNumber, byte deviceType, byte txType, short channelPeriod, byte radioFreq, byte proxSearch) { if (antReceiver == null) { Log.e(TAG, "no ANT receiver"); return false; } try { // Assign as slave channel on selected network (0 = public, 1 = ANT+, 2 = // ANTFS) antReceiver.ANTAssignChannel(channelNumber, AntDefine.PARAMETER_RX_NOT_TX, networkNumber); antReceiver.ANTSetChannelId(channelNumber, deviceNumber, deviceType, txType); antReceiver.ANTSetChannelPeriod(channelNumber, channelPeriod); antReceiver.ANTSetChannelRFFreq(channelNumber, radioFreq); // Disable high priority search antReceiver.ANTSetChannelSearchTimeout(channelNumber, (byte) 0); // Set search timeout to 30 seconds (low priority search)) antReceiver.ANTSetLowPriorityChannelSearchTimeout(channelNumber, (byte) 12); if (deviceNumber == WILDCARD) { // Configure proximity search, if using wild card search antReceiver.ANTSetProximitySearch(channelNumber, proxSearch); } antReceiver.ANTOpenChannel(channelNumber); return true; } catch (AntInterfaceException e) { Log.e(TAG, "failed to setup ANT channel", e); return false; } } private void registerForAntIntents() { Log.i(TAG, "Registering for ant intents."); // Register for ANT intent broadcasts. IntentFilter statusIntentFilter = new IntentFilter(); statusIntentFilter.addAction(AntInterfaceIntent.ANT_ENABLED_ACTION); statusIntentFilter.addAction(AntInterfaceIntent.ANT_DISABLED_ACTION); statusIntentFilter.addAction(AntInterfaceIntent.ANT_INTERFACE_CLAIMED_ACTION); statusIntentFilter.addAction(AntInterfaceIntent.ANT_RESET_ACTION); context.registerReceiver(statusReceiver, statusIntentFilter); IntentFilter dataIntentFilter = new IntentFilter(); dataIntentFilter.addAction(AntInterfaceIntent.ANT_RX_MESSAGE_ACTION); context.registerReceiver(dataReceiver, dataIntentFilter); } private void unregisterForAntIntents() { Log.i(TAG, "Unregistering ANT Intents."); try { context.unregisterReceiver(statusReceiver); } catch (IllegalArgumentException e) { Log.w(TAG, "Failed to unregister ANT status receiver", e); } try { context.unregisterReceiver(dataReceiver); } catch (IllegalArgumentException e) { Log.w(TAG, "Failed to unregister ANT data receiver", e); } } private String messageToString(byte[] message) { StringBuilder out = new StringBuilder(); for (byte b : message) { out.append(String.format("%s%02x", (out.length() == 0 ? "" : " "), b)); } return out.toString(); } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.google.android.apps.mytracks.services.sensors.ant; /** * A enum which stores static data about ANT sensors. * * @author Matthew Simmons */ public enum AntSensor { SENSOR_HEART_RATE (Constants.ANT_DEVICE_TYPE_HRM), SENSOR_CADENCE (Constants.ANT_DEVICE_TYPE_CADENCE), SENSOR_SPEED (Constants.ANT_DEVICE_TYPE_SPEED), SENSOR_POWER (Constants.ANT_DEVICE_TYPE_POWER); private static class Constants { public static byte ANT_DEVICE_TYPE_POWER = 11; public static byte ANT_DEVICE_TYPE_HRM = 120; public static byte ANT_DEVICE_TYPE_CADENCE = 122; public static byte ANT_DEVICE_TYPE_SPEED = 123; }; private final byte deviceType; private AntSensor(byte deviceType) { this.deviceType = deviceType; } public byte getDeviceType() { return deviceType; } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.services.sensors.ant; /** * This class decodes and encapsulates an ANT Startup message. * (ANT Message ID 0x6f, Protocol & Usage guide v4.2 section 9.5.3.1) * * @author Matthew Simmons */ public class AntStartupMessage extends AntMessage { private byte message; public AntStartupMessage(byte[] messageData) { message = messageData[0]; } /** Returns the cause of the startup */ public byte getMessage() { return message; } }
Java
/* * Copyright (C) 2010 Google Inc. * * 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.google.android.apps.mytracks.services.sensors; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.util.ApiFeatures; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.UUID; /** * This class does all the work for setting up and managing Bluetooth * connections with other devices. It has a thread that listens for incoming * connections, a thread for connecting with a device, and a thread for * performing data transmissions when connected. * * @author Sandor Dornbush */ public class BluetoothConnectionManager { // Unique UUID for this application private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private MessageParser parser; // Member fields private final BluetoothAdapter adapter; private final Handler handler; private ConnectThread connectThread; private ConnectedThread connectedThread; private Sensor.SensorState state; // Message types sent from the BluetoothSenorService Handler public static final int MESSAGE_STATE_CHANGE = 1; public static final int MESSAGE_READ = 2; public static final int MESSAGE_WRITE = 3; public static final int MESSAGE_DEVICE_NAME = 4; // Key names received from the BluetoothSenorService Handler public static final String DEVICE_NAME = "device_name"; /** * Constructor. Prepares a new BluetoothSensor session. * * @param handler A Handler to send messages back to the UI Activity * @param parser A message parser */ public BluetoothConnectionManager(Handler handler, MessageParser parser) { this.adapter = BluetoothAdapter.getDefaultAdapter(); this.state = Sensor.SensorState.NONE; this.handler = handler; this.parser = parser; } /** * Set the current state of the sensor connection * * @param state An integer defining the current connection state */ private synchronized void setState(Sensor.SensorState state) { // TODO pretty print this. Log.d(Constants.TAG, "setState(" + state + ")"); this.state = state; // Give the new state to the Handler so the UI Activity can update handler.obtainMessage(MESSAGE_STATE_CHANGE, state.getNumber(), -1).sendToTarget(); } /** * Return the current connection state. */ public synchronized Sensor.SensorState getState() { return state; } /** * Start the sensor service. Specifically start AcceptThread to begin a session * in listening (server) mode. Called by the Activity onResume() */ public synchronized void start() { Log.d(Constants.TAG, "BluetoothConnectionManager.start()"); // Cancel any thread attempting to make a connection if (connectThread != null) { connectThread.cancel(); connectThread = null; } // Cancel any thread currently running a connection if (connectedThread != null) { connectedThread.cancel(); connectedThread = null; } setState(Sensor.SensorState.NONE); } /** * Start the ConnectThread to initiate a connection to a remote device. * * @param device The BluetoothDevice to connect */ public synchronized void connect(BluetoothDevice device) { Log.d(Constants.TAG, "connect to: " + device); // Cancel any thread attempting to make a connection if (state == Sensor.SensorState.CONNECTING) { if (connectThread != null) { connectThread.cancel(); connectThread = null; } } // Cancel any thread currently running a connection if (connectedThread != null) { connectedThread.cancel(); connectedThread = null; } // Start the thread to connect with the given device connectThread = new ConnectThread(device); connectThread.start(); setState(Sensor.SensorState.CONNECTING); } /** * Start the ConnectedThread to begin managing a Bluetooth connection * * @param socket The BluetoothSocket on which the connection was made * @param device The BluetoothDevice that has been connected */ public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) { Log.d(Constants.TAG, "connected"); // Cancel the thread that completed the connection if (connectThread != null) { connectThread.cancel(); connectThread = null; } // Cancel any thread currently running a connection if (connectedThread != null) { connectedThread.cancel(); connectedThread = null; } // Start the thread to manage the connection and perform transmissions connectedThread = new ConnectedThread(socket); connectedThread.start(); // Send the name of the connected device back to the UI Activity Message msg = handler.obtainMessage(MESSAGE_DEVICE_NAME); Bundle bundle = new Bundle(); bundle.putString(DEVICE_NAME, device.getName()); msg.setData(bundle); handler.sendMessage(msg); setState(Sensor.SensorState.CONNECTED); } /** * Stop all threads */ public synchronized void stop() { Log.d(Constants.TAG, "stop()"); if (connectThread != null) { connectThread.cancel(); connectThread = null; } if (connectedThread != null) { connectedThread.cancel(); connectedThread = null; } setState(Sensor.SensorState.NONE); } /** * Write to the ConnectedThread in an unsynchronized manner * * @param out The bytes to write * @see ConnectedThread#write(byte[]) */ public void write(byte[] out) { // Create temporary object ConnectedThread r; // Synchronize a copy of the ConnectedThread synchronized (this) { if (state != Sensor.SensorState.CONNECTED) { return; } r = connectedThread; } // Perform the write unsynchronized r.write(out); } /** * Indicate that the connection attempt failed and notify the UI Activity. */ private void connectionFailed() { setState(Sensor.SensorState.DISCONNECTED); Log.i(Constants.TAG, "Bluetooth connection failed."); } /** * Indicate that the connection was lost and notify the UI Activity. */ private void connectionLost() { setState(Sensor.SensorState.DISCONNECTED); Log.i(Constants.TAG, "Bluetooth connection lost."); } /** * This thread runs while attempting to make an outgoing connection with a * device. It runs straight through; the connection either succeeds or fails. */ private class ConnectThread extends Thread { private final BluetoothSocket socket; private final BluetoothDevice device; public ConnectThread(BluetoothDevice device) { setName("ConnectThread-" + device.getName()); this.device = device; BluetoothSocket tmp = null; // Get a BluetoothSocket for a connection with the // given BluetoothDevice try { tmp = getSocket(); } catch (IOException e) { Log.e(Constants.TAG, "create() failed", e); } socket = tmp; } private BluetoothSocket getSocket() throws IOException { if (ApiFeatures.getInstance().hasBluetoothDeviceCreateInsecureRfcommSocketToServiceRecord()) { try { return device.createInsecureRfcommSocketToServiceRecord(SPP_UUID); } catch (IOException e) { Log.e(Constants.TAG, "Unable to get insecure connect.", e); } } else { try { Class<? extends BluetoothDevice> c = device.getClass(); Method insecure = c.getMethod("createInsecureRfcommSocket", Integer.class); insecure.setAccessible(true); return (BluetoothSocket) insecure.invoke(device, 1); } catch (SecurityException e) { Log.e(Constants.TAG, "Unable to get insecure connect.", e); } catch (NoSuchMethodException e) { Log.e(Constants.TAG, "Unable to get insecure connect.", e); } catch (IllegalArgumentException e) { Log.e(Constants.TAG, "Unable to get insecure connect.", e); } catch (IllegalAccessException e) { Log.e(Constants.TAG, "Unable to get insecure connect.", e); } catch (InvocationTargetException e) { Log.e(Constants.TAG, "Unable to get insecure connect.", e); } } return device.createRfcommSocketToServiceRecord(SPP_UUID); } @Override public void run() { Log.d(Constants.TAG, "BEGIN mConnectThread"); // Always cancel discovery because it will slow down a connection adapter.cancelDiscovery(); // Make a connection to the BluetoothSocket try { // This is a blocking call and will only return on a // successful connection or an exception socket.connect(); } catch (IOException e) { connectionFailed(); // Close the socket try { socket.close(); } catch (IOException e2) { Log.e(Constants.TAG, "unable to close() socket during connection failure", e2); } // Start the service over to restart listening mode BluetoothConnectionManager.this.start(); return; } // Reset the ConnectThread because we're done synchronized (BluetoothConnectionManager.this) { connectThread = null; } // Start the connected thread connected(socket, device); } public void cancel() { try { socket.close(); } catch (IOException e) { Log.e(Constants.TAG, "close() of connect socket failed", e); } } } /** * This thread runs during a connection with a remote device. It handles all * incoming and outgoing transmissions. */ private class ConnectedThread extends Thread { private final BluetoothSocket btSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) { Log.d(Constants.TAG, "create ConnectedThread"); btSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the BluetoothSocket input and output streams try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { Log.e(Constants.TAG, "temp sockets not created", e); } mmInStream = tmpIn; mmOutStream = tmpOut; } @Override public void run() { Log.i(Constants.TAG, "BEGIN mConnectedThread"); byte[] buffer = new byte[parser.getFrameSize()]; int bytes; int offset = 0; // Keep listening to the InputStream while connected while (true) { try { // Read from the InputStream bytes = mmInStream.read(buffer, offset, parser.getFrameSize() - offset); if (bytes < 0) { throw new IOException("EOF reached"); } offset += bytes; if (offset != parser.getFrameSize()) { // partial frame received, call read() again to receive the rest continue; } // check if its a valid frame if (!parser.isValid(buffer)) { int index = parser.findNextAlignment(buffer); if (index > 0) { // re-align offset = parser.getFrameSize() - index; System.arraycopy(buffer, index, buffer, 0, offset); Log.w(Constants.TAG, "Misaligned data, found new message at " + index + " recovering..."); continue; } Log.w(Constants.TAG, "Could not find valid data, dropping data"); offset = 0; continue; } offset = 0; // Send copy of the obtained bytes to the UI Activity. // Avoids memory inconsistency issues. handler.obtainMessage(MESSAGE_READ, bytes, -1, buffer.clone()) .sendToTarget(); } catch (IOException e) { Log.e(Constants.TAG, "disconnected", e); connectionLost(); break; } } } /** * Write to the connected OutStream. * * @param buffer The bytes to write */ public void write(byte[] buffer) { try { mmOutStream.write(buffer); // Share the sent message back to the UI Activity handler.obtainMessage(MESSAGE_WRITE, -1, -1, buffer).sendToTarget(); } catch (IOException e) { Log.e(Constants.TAG, "Exception during write", e); } } public void cancel() { try { btSocket.close(); } catch (IOException e) { Log.e(Constants.TAG, "close() of connect socket failed", e); } } } }
Java
/* * Copyright 2010 Google Inc. * * 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.google.android.apps.mytracks.services.sensors; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.util.ApiFeatures; import java.util.Arrays; /** * An implementation of a Sensor MessageParser for Zephyr. * * @author Sandor Dornbush * @author Dominik Ršttsches */ public class ZephyrMessageParser implements MessageParser { public static final int ZEPHYR_HXM_BYTE_STX = 0; public static final int ZEPHYR_HXM_BYTE_CRC = 58; public static final int ZEPHYR_HXM_BYTE_ETX = 59; private static final byte[] CADENCE_BUG_FW_ID = {0x1A, 0x00, 0x31, 0x65, 0x50, 0x00, 0x31, 0x62}; private StrideReadings strideReadings; @Override public Sensor.SensorDataSet parseBuffer(byte[] buffer) { Sensor.SensorDataSet.Builder sds = Sensor.SensorDataSet.newBuilder() .setCreationTime(System.currentTimeMillis()); Sensor.SensorData.Builder heartrate = Sensor.SensorData.newBuilder() .setValue(buffer[12] & 0xFF) .setState(Sensor.SensorState.SENDING); sds.setHeartRate(heartrate); Sensor.SensorData.Builder batteryLevel = Sensor.SensorData.newBuilder() .setValue(buffer[11]) .setState(Sensor.SensorState.SENDING); sds.setBatteryLevel(batteryLevel); setCadence(sds, buffer); return sds.build(); } private void setCadence(Sensor.SensorDataSet.Builder sds, byte[] buffer) { // Device Firmware ID, Firmware Version, Hardware ID, Hardware Version // 0x1A00316550003162 produces erroneous values for Cadence and needs // a workaround based on the stride counter. // Firmware values range from field 3 to 10 (inclusive) of the byte buffer. byte[] hardwareFirmwareId = ApiFeatures.getInstance().getApiAdapter() .copyByteArray(buffer, 3, 11); Sensor.SensorData.Builder cadence = Sensor.SensorData.newBuilder(); if (Arrays.equals(hardwareFirmwareId, CADENCE_BUG_FW_ID)) { if (strideReadings == null) { strideReadings = new StrideReadings(); } strideReadings.updateStrideReading(buffer[54] & 0xFF); if (strideReadings.getCadence() != StrideReadings.CADENCE_NOT_AVAILABLE) { cadence.setValue(strideReadings.getCadence()).setState(Sensor.SensorState.SENDING); } } else { cadence .setValue(SensorUtils.unsignedShortToIntLittleEndian(buffer, 56) / 16) .setState(Sensor.SensorState.SENDING); } sds.setCadence(cadence); } @Override public boolean isValid(byte[] buffer) { // Check STX (Start of Text), ETX (End of Text) and CRC Checksum return buffer.length > ZEPHYR_HXM_BYTE_ETX && buffer[ZEPHYR_HXM_BYTE_STX] == 0x02 && buffer[ZEPHYR_HXM_BYTE_ETX] == 0x03 && SensorUtils.getCrc8(buffer, 3, 55) == buffer[ZEPHYR_HXM_BYTE_CRC]; } @Override public int getFrameSize() { return 60; } @Override public int findNextAlignment(byte[] buffer) { // TODO test or understand this code. for (int i = 0; i < buffer.length - 1; i++) { if (buffer[i] == 0x03 && buffer[i+1] == 0x02) { return i; } } return -1; } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.android.apps.mytracks.services.sensors; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.services.sensors.ant.AntDirectSensorManager; import com.google.android.apps.mytracks.services.sensors.ant.AntSrmBridgeSensorManager; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; /** * A factory of SensorManagers. * * @author Sandor Dornbush */ public class SensorManagerFactory { private SensorManagerFactory() { } /** * Get a new sensor manager. * @param context Context to fetch system preferences. * @return The sensor manager that corresponds to the sensor type setting. */ public static SensorManager getSensorManager(Context context) { SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs == null) { return null; } context = context.getApplicationContext(); String sensor = prefs.getString(context.getString(R.string.sensor_type_key), null); Log.i(Constants.TAG, "Creating sensor of type: " + sensor); if (sensor == null) { return null; } else if (sensor.equals(context.getString(R.string.sensor_type_value_ant))) { return new AntDirectSensorManager(context); } else if (sensor.equals(context.getString(R.string.sensor_type_value_srm_ant_bridge))) { return new AntSrmBridgeSensorManager(context); } else if (sensor.equals(context.getString(R.string.sensor_type_value_zephyr))) { return new ZephyrSensorManager(context); } else if (sensor.equals(context.getString(R.string.sensor_type_value_polar))) { return new PolarSensorManager(context); } else { Log.w(Constants.TAG, "Unable to find sensor type: " + sensor); return null; } } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.services.sensors; import com.google.android.apps.mytracks.content.Sensor; /** * An implementation of a Sensor MessageParser for Polar Wearlink Bluetooth HRM. * * Polar Bluetooth Wearlink packet example; * Hdr Len Chk Seq Status HeartRate RRInterval_16-bits * FE 08 F7 06 F1 48 03 64 * where; * Hdr always = 254 (0xFE), * Chk = 255 - Len * Seq range 0 to 15 * Status = Upper nibble may be battery voltage * bit 0 is Beat Detection flag. * * Additional packet examples; * FE 08 F7 06 F1 48 03 64 * FE 0A F5 06 F1 48 03 64 03 70 * * @author John R. Gerthoffer */ public class PolarMessageParser implements MessageParser { private int lastHeartRate = 0; /** * Applies Polar packet validation rules to buffer. * Polar packets are checked for following; * offset 0 = header byte, 254 (0xFE). * offset 1 = packet length byte, 8, 10, 12, 14. * offset 2 = check byte, 255 - packet length. * offset 3 = sequence byte, range from 0 to 15. * * @param buffer an array of bytes to parse * @param i buffer offset to beginning of packet. * @return whether buffer has a valid packet at offset i */ private boolean packetValid (byte[] buffer, int i) { boolean headerValid = (buffer[i] & 0xFF) == 0xFE; boolean checkbyteValid = (buffer[i + 2] & 0xFF) == (0xFF - (buffer[i + 1] & 0xFF)); boolean sequenceValid = (buffer[i + 3] & 0xFF) < 16; return headerValid && checkbyteValid && sequenceValid; } @Override public Sensor.SensorDataSet parseBuffer(byte[] buffer) { int heartRate = 0; boolean heartrateValid = false; // Minimum length Polar packets is 8, so stop search 8 bytes before buffer ends. for (int i = 0; i < buffer.length - 8; i++) { heartrateValid = packetValid(buffer,i); if (heartrateValid) { heartRate = buffer[i + 5] & 0xFF; break; } } // If our buffer is corrupted, use decaying last good value. if(!heartrateValid) { heartRate = (int) (lastHeartRate * 0.8); if(heartRate < 50) heartRate = 0; } lastHeartRate = heartRate; // Remember good value for next time. // Heart Rate Sensor.SensorData.Builder b = Sensor.SensorData.newBuilder() .setValue(heartRate) .setState(Sensor.SensorState.SENDING); Sensor.SensorDataSet sds = Sensor.SensorDataSet.newBuilder() .setCreationTime(System.currentTimeMillis()) .setHeartRate(b) .build(); return sds; } /** * Applies packet validation rules to buffer * * @param buffer an array of bytes to parse * @return whether buffer has a valid packet starting at index zero */ @Override public boolean isValid(byte[] buffer) { return packetValid(buffer,0); } /** * Polar uses variable packet sizes; 8, 10, 12, 14 and rarely 16. * The most frequent are 8 and 10. * We will wait for 16 bytes. * This way, we are assured of getting one good one. * * @return the size of buffer needed to parse a good packet */ @Override public int getFrameSize() { return 16; } /** * Searches buffer for the beginning of a valid packet. * * @param buffer an array of bytes to parse * @return index to beginning of good packet, or -1 if none found. */ @Override public int findNextAlignment(byte[] buffer) { // Minimum length Polar packets is 8, so stop search 8 bytes before buffer ends. for (int i = 0; i < buffer.length - 8; i++) { if (packetValid(buffer,i)) { return i; } } return -1; } }
Java
/* * Copyright 2011 Google Inc. * * 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.google.android.apps.mytracks.services.sensors; import android.content.Context; /** * PolarSensorManager - A sensor manager for Polar heart rate monitors. */ public class PolarSensorManager extends BluetoothSensorManager { public PolarSensorManager(Context context) { super(context, new PolarMessageParser()); } }
Java