2 * Copyright © 2012 Mike Beattie <mike@ethernal.org>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; version 2 of the License.
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
18 package org.altusmetrum.AltosDroid;
20 import java.lang.ref.WeakReference;
21 import java.util.ArrayList;
22 import java.util.concurrent.TimeoutException;
23 import java.util.Timer;
24 import java.util.TimerTask;
26 import android.app.Notification;
27 //import android.app.NotificationManager;
28 import android.app.PendingIntent;
29 import android.app.Service;
30 import android.bluetooth.BluetoothDevice;
31 import android.content.Intent;
32 import android.content.Context;
33 import android.os.Bundle;
34 import android.os.IBinder;
35 import android.os.Handler;
36 import android.os.Message;
37 import android.os.Messenger;
38 import android.os.RemoteException;
39 import android.util.Log;
40 import android.widget.Toast;
41 import android.location.Location;
42 import android.location.LocationManager;
43 import android.location.LocationListener;
45 import org.altusmetrum.altoslib_1.*;
47 class AltosLocationListener implements LocationListener {
48 TelemetryService service;
51 public void onLocationChanged(Location location) {
52 service.sendLocation(location);
55 public void onStatusChanged(String provider, int status, Bundle extras) {
58 public void onProviderEnabled(String provider) {
61 public void onProviderDisabled(String provider) {
64 public AltosLocationListener(TelemetryService service, boolean fine) {
66 this.service = service;
70 public class TelemetryService extends Service {
72 private static final String TAG = "TelemetryService";
73 private static final boolean D = true;
75 static final int MSG_REGISTER_CLIENT = 1;
76 static final int MSG_UNREGISTER_CLIENT = 2;
77 static final int MSG_CONNECT = 3;
78 static final int MSG_CONNECTED = 4;
79 static final int MSG_CONNECT_FAILED = 5;
80 static final int MSG_DISCONNECTED = 6;
81 static final int MSG_TELEMETRY = 7;
82 static final int MSG_SETFREQUENCY = 8;
83 static final int MSG_LOCATION = 9;
84 static final int MSG_CRC_ERROR = 10;
86 public static final int STATE_NONE = 0;
87 public static final int STATE_READY = 1;
88 public static final int STATE_CONNECTING = 2;
89 public static final int STATE_CONNECTED = 3;
91 // Unique Identification Number for the Notification.
92 // We use it on Notification start, and to cancel it.
93 private int NOTIFICATION = R.string.telemetry_service_label;
94 //private NotificationManager mNM;
96 // Timer - we wake up every now and then to decide if the service should stop
97 private Timer timer = new Timer();
99 ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
100 final Handler mHandler = new IncomingHandler(this);
101 final Messenger mMessenger = new Messenger(mHandler); // Target we publish for clients to send messages to IncomingHandler.
103 // Name of the connected device
104 private BluetoothDevice device = null;
105 private AltosBluetooth mAltosBluetooth = null;
106 private AltosConfigData mConfigData = null;
107 private TelemetryReader mTelemetryReader = null;
108 private TelemetryLogger mTelemetryLogger = null;
110 // internally track state of bluetooth connection
111 private int state = STATE_NONE;
113 // location listeners
115 private AltosLocationListener gpsListener;
116 private AltosLocationListener netListener;
118 // Last data seen; send to UI when it starts
120 private AltosState last_state;
121 private Location last_location;
122 private int last_crc_errors;
124 // Handler of incoming messages from clients.
125 static class IncomingHandler extends Handler {
126 private final WeakReference<TelemetryService> service;
127 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
130 public void handleMessage(Message msg) {
131 TelemetryService s = service.get();
133 case MSG_REGISTER_CLIENT:
134 s.mClients.add(msg.replyTo);
136 // Now we try to send the freshly connected UI any relavant information about what
137 // we're talking to - Basically state and Config Data.
138 msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, s.state, -1, s.mConfigData));
139 } catch (RemoteException e) {
140 s.mClients.remove(msg.replyTo);
142 if (D) Log.d(TAG, "Client bound to service");
143 if (s.last_state != null)
144 s.sendTelemetry(s.last_state);
145 if (s.last_location != null)
146 s.sendLocation(s.last_location);
147 if (s.last_crc_errors != 0)
148 s.sendCrcErrors(s.last_crc_errors);
150 case MSG_UNREGISTER_CLIENT:
151 s.mClients.remove(msg.replyTo);
152 if (D) Log.d(TAG, "Client unbound from service");
155 if (D) Log.d(TAG, "Connect command received");
156 s.device = (BluetoothDevice) msg.obj;
157 s.startAltosBluetooth();
160 if (D) Log.d(TAG, "Connected to device");
163 case MSG_CONNECT_FAILED:
164 if (D) Log.d(TAG, "Connection failed... retrying");
165 s.startAltosBluetooth();
167 case MSG_DISCONNECTED:
168 // Only do the following if we haven't been shutdown elsewhere..
169 if (s.device != null) {
170 if (D) Log.d(TAG, "Disconnected from " + s.device.getName());
171 s.stopAltosBluetooth();
175 s.sendMessageToClients(Message.obtain(null, AltosDroid.MSG_TELEMETRY, msg.obj));
177 case MSG_SETFREQUENCY:
178 if (s.state == STATE_CONNECTED) {
180 s.mAltosBluetooth.set_radio_frequency((Double) msg.obj);
181 } catch (InterruptedException e) {
182 } catch (TimeoutException e) {
187 super.handleMessage(msg);
192 public void sendTelemetry(AltosState state) {
194 mHandler.obtainMessage(MSG_TELEMETRY, state).sendToTarget();
197 public void sendLocation(Location location) {
198 last_location = location;
199 mHandler.obtainMessage(MSG_LOCATION, location).sendToTarget();
202 public void sendCrcErrors(int crc_errors) {
203 last_crc_errors = crc_errors;
204 mHandler.obtainMessage(MSG_CRC_ERROR, new Integer(crc_errors)).sendToTarget();
207 private void sendMessageToClients(Message m) {
208 for (int i=mClients.size()-1; i>=0; i--) {
210 mClients.get(i).send(m);
211 } catch (RemoteException e) {
217 private void stopAltosBluetooth() {
218 if (D) Log.d(TAG, "stopAltosBluetooth(): begin");
219 setState(STATE_READY);
220 if (mTelemetryReader != null) {
221 if (D) Log.d(TAG, "stopAltosBluetooth(): stopping TelemetryReader");
222 mTelemetryReader.interrupt();
224 mTelemetryReader.join();
225 } catch (InterruptedException e) {
227 mTelemetryReader = null;
229 if (mTelemetryLogger != null) {
230 if (D) Log.d(TAG, "stopAltosBluetooth(): stopping TelemetryLogger");
231 mTelemetryLogger.stop();
232 mTelemetryLogger = null;
234 if (mAltosBluetooth != null) {
235 if (D) Log.d(TAG, "stopAltosBluetooth(): stopping AltosBluetooth");
236 mAltosBluetooth.close();
237 mAltosBluetooth = null;
243 private void startAltosBluetooth() {
244 if (mAltosBluetooth == null) {
245 if (D) Log.d(TAG, String.format("startAltosBluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress()));
246 mAltosBluetooth = new AltosBluetooth(device, mHandler);
247 setState(STATE_CONNECTING);
249 // This is a bit of a hack - if it appears we're still connected, we treat this as a restart.
250 // So, to give a suitable delay to teardown/bringup, we just schedule a resend of a message
251 // to ourselves in a few seconds time that will ultimately call this method again.
252 // ... then we tear down the existing connection.
253 // We do it this way around so that we don't lose a reference to the device when this method
254 // is called on reception of MSG_CONNECT_FAILED in the handler above.
255 mHandler.sendMessageDelayed(Message.obtain(null, MSG_CONNECT, device), 3000);
256 stopAltosBluetooth();
260 private synchronized void setState(int s) {
261 if (D) Log.d(TAG, "setState(): " + state + " -> " + s);
264 // This shouldn't be required - mConfigData should be null for any non-connected
265 // state, but to be safe and to reduce message size
266 AltosConfigData acd = (state == STATE_CONNECTED) ? mConfigData : null;
268 sendMessageToClients(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, state, -1, acd));
271 private void connected() {
273 mConfigData = mAltosBluetooth.config_data();
274 } catch (InterruptedException e) {
275 } catch (TimeoutException e) {
276 // If this timed out, then we really want to retry it, but
277 // probably safer to just retry the connection from scratch.
278 mHandler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
282 setState(STATE_CONNECTED);
284 mTelemetryReader = new TelemetryReader(this, mAltosBluetooth, mHandler);
285 mTelemetryReader.start();
287 mTelemetryLogger = new TelemetryLogger(this, mAltosBluetooth);
291 private void onTimerTick() {
292 if (D) Log.d(TAG, "Timer wakeup");
294 if (mClients.size() <= 0 && state != STATE_CONNECTED) {
297 } catch (Throwable t) {
298 Log.e(TAG, "Timer failed: ", t);
304 public void onCreate() {
305 // Create a reference to the NotificationManager so that we can update our notifcation text later
306 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
308 setState(STATE_READY);
310 // Start our timer - first event in 10 seconds, then every 10 seconds after that.
311 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 10000L, 10000L);
313 // Listen for GPS and Network position updates
314 gpsListener = new AltosLocationListener(this, true);
315 netListener = new AltosLocationListener(this, false);
317 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
319 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsListener);
320 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, netListener);
324 public int onStartCommand(Intent intent, int flags, int startId) {
325 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
327 CharSequence text = getText(R.string.telemetry_service_started);
329 // Create notification to be displayed while the service runs
330 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
332 // The PendingIntent to launch our activity if the user selects this notification
333 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
334 new Intent(this, AltosDroid.class), 0);
336 // Set the info for the views that show in the notification panel.
337 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
339 // Set the notification to be in the "Ongoing" section.
340 notification.flags |= Notification.FLAG_ONGOING_EVENT;
342 // Move us into the foreground.
343 startForeground(NOTIFICATION, notification);
345 // We want this service to continue running until it is explicitly
346 // stopped, so return sticky.
351 public void onDestroy() {
353 // Stop listening for location updates
354 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
355 locationManager.removeUpdates(gpsListener);
356 locationManager.removeUpdates(netListener);
358 // Stop the bluetooth Comms threads
359 stopAltosBluetooth();
361 // Demote us from the foreground, and cancel the persistent notification.
362 stopForeground(true);
365 if (timer != null) {timer.cancel();}
367 // Tell the user we stopped.
368 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
372 public IBinder onBind(Intent intent) {
373 return mMessenger.getBinder();