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 {
50 public void onLocationChanged(Location location) {
51 handler.obtainMessage(TelemetryService.MSG_LOCATION, location).sendToTarget();
54 public void onStatusChanged(String provider, int status, Bundle extras) {
57 public void onProviderEnabled(String provider) {
60 public void onProviderDisabled(String provider) {
63 public AltosLocationListener(Handler handler) {
64 this.handler = handler;
68 public class TelemetryService extends Service {
70 private static final String TAG = "TelemetryService";
71 private static final boolean D = true;
73 static final int MSG_REGISTER_CLIENT = 1;
74 static final int MSG_UNREGISTER_CLIENT = 2;
75 static final int MSG_CONNECT = 3;
76 static final int MSG_CONNECTED = 4;
77 static final int MSG_CONNECT_FAILED = 5;
78 static final int MSG_DISCONNECTED = 6;
79 static final int MSG_TELEMETRY = 7;
80 static final int MSG_SETFREQUENCY = 8;
81 static final int MSG_LOCATION = 9;
82 static final int MSG_CRC_ERROR = 10;
84 public static final int STATE_NONE = 0;
85 public static final int STATE_READY = 1;
86 public static final int STATE_CONNECTING = 2;
87 public static final int STATE_CONNECTED = 3;
89 // Unique Identification Number for the Notification.
90 // We use it on Notification start, and to cancel it.
91 private int NOTIFICATION = R.string.telemetry_service_label;
92 //private NotificationManager mNM;
94 // Timer - we wake up every now and then to decide if the service should stop
95 private Timer timer = new Timer();
97 ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
98 final Handler mHandler = new IncomingHandler(this);
99 final Messenger mMessenger = new Messenger(mHandler); // Target we publish for clients to send messages to IncomingHandler.
101 // Name of the connected device
102 private BluetoothDevice device = null;
103 private AltosBluetooth mAltosBluetooth = null;
104 private AltosConfigData mConfigData = null;
105 private TelemetryReader mTelemetryReader = null;
106 private TelemetryLogger mTelemetryLogger = null;
108 // internally track state of bluetooth connection
109 private int state = STATE_NONE;
111 // location listeners
113 private AltosLocationListener locationListener;
115 // Last data seen; send to UI when it starts
117 private AltosState last_state;
118 private Location last_location;
119 private int last_crc_errors;
121 // Handler of incoming messages from clients.
122 static class IncomingHandler extends Handler {
123 private final WeakReference<TelemetryService> service;
124 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
127 public void handleMessage(Message msg) {
128 TelemetryService s = service.get();
130 case MSG_REGISTER_CLIENT:
131 s.mClients.add(msg.replyTo);
133 // Now we try to send the freshly connected UI any relavant information about what
134 // we're talking to - Basically state and Config Data.
135 msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, s.state, -1, s.mConfigData));
136 // We also send any recent telemetry or location data that's cached
137 if (s.last_state != null) msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_TELEMETRY, s.last_state ));
138 if (s.last_location != null) msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_LOCATION , s.last_location ));
139 if (s.last_crc_errors != 0 ) msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_CRC_ERROR, s.last_crc_errors));
140 } catch (RemoteException e) {
141 s.mClients.remove(msg.replyTo);
143 if (D) Log.d(TAG, "Client bound to service");
145 case MSG_UNREGISTER_CLIENT:
146 s.mClients.remove(msg.replyTo);
147 if (D) Log.d(TAG, "Client unbound from service");
150 if (D) Log.d(TAG, "Connect command received");
151 s.device = (BluetoothDevice) msg.obj;
152 s.startAltosBluetooth();
155 if (D) Log.d(TAG, "Connected to device");
158 case MSG_CONNECT_FAILED:
159 if (D) Log.d(TAG, "Connection failed... retrying");
160 s.startAltosBluetooth();
162 case MSG_DISCONNECTED:
163 // Only do the following if we haven't been shutdown elsewhere..
164 if (s.device != null) {
165 if (D) Log.d(TAG, "Disconnected from " + s.device.getName());
166 s.stopAltosBluetooth();
170 // forward telemetry messages
171 s.last_state = (AltosState) msg.obj;
172 s.sendMessageToClients(Message.obtain(null, AltosDroid.MSG_TELEMETRY, msg.obj));
175 // forward location messages
176 s.last_location = (Location) msg.obj;
177 s.sendMessageToClients(Message.obtain(null, AltosDroid.MSG_LOCATION, msg.obj));
180 // forward crc error messages
181 s.last_crc_errors = (Integer) msg.obj;
182 s.sendMessageToClients(Message.obtain(null, AltosDroid.MSG_CRC_ERROR, msg.obj));
184 case MSG_SETFREQUENCY:
185 if (s.state == STATE_CONNECTED) {
187 s.mAltosBluetooth.set_radio_frequency((Double) msg.obj);
188 } catch (InterruptedException e) {
189 } catch (TimeoutException e) {
194 super.handleMessage(msg);
199 private void sendMessageToClients(Message m) {
200 for (int i=mClients.size()-1; i>=0; i--) {
202 mClients.get(i).send(m);
203 } catch (RemoteException e) {
209 private void stopAltosBluetooth() {
210 if (D) Log.d(TAG, "stopAltosBluetooth(): begin");
211 setState(STATE_READY);
212 if (mTelemetryReader != null) {
213 if (D) Log.d(TAG, "stopAltosBluetooth(): stopping TelemetryReader");
214 mTelemetryReader.interrupt();
216 mTelemetryReader.join();
217 } catch (InterruptedException e) {
219 mTelemetryReader = null;
221 if (mTelemetryLogger != null) {
222 if (D) Log.d(TAG, "stopAltosBluetooth(): stopping TelemetryLogger");
223 mTelemetryLogger.stop();
224 mTelemetryLogger = null;
226 if (mAltosBluetooth != null) {
227 if (D) Log.d(TAG, "stopAltosBluetooth(): stopping AltosBluetooth");
228 mAltosBluetooth.close();
229 mAltosBluetooth = null;
235 private void startAltosBluetooth() {
236 if (device == null) {
239 if (mAltosBluetooth == null) {
240 if (D) Log.d(TAG, String.format("startAltosBluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress()));
241 mAltosBluetooth = new AltosBluetooth(device, mHandler);
242 setState(STATE_CONNECTING);
244 // This is a bit of a hack - if it appears we're still connected, we treat this as a restart.
245 // So, to give a suitable delay to teardown/bringup, we just schedule a resend of a message
246 // to ourselves in a few seconds time that will ultimately call this method again.
247 // ... then we tear down the existing connection.
248 // We do it this way around so that we don't lose a reference to the device when this method
249 // is called on reception of MSG_CONNECT_FAILED in the handler above.
250 mHandler.sendMessageDelayed(Message.obtain(null, MSG_CONNECT, device), 3000);
251 stopAltosBluetooth();
255 private synchronized void setState(int s) {
256 if (D) Log.d(TAG, "setState(): " + state + " -> " + s);
259 // This shouldn't be required - mConfigData should be null for any non-connected
260 // state, but to be safe and to reduce message size
261 AltosConfigData acd = (state == STATE_CONNECTED) ? mConfigData : null;
263 sendMessageToClients(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, state, -1, acd));
266 private void connected() {
268 if (mAltosBluetooth == null)
269 throw new InterruptedException("no bluetooth");
270 mConfigData = mAltosBluetooth.config_data();
271 } catch (InterruptedException e) {
272 } catch (TimeoutException e) {
273 // If this timed out, then we really want to retry it, but
274 // probably safer to just retry the connection from scratch.
275 mHandler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
279 setState(STATE_CONNECTED);
281 mTelemetryReader = new TelemetryReader(mAltosBluetooth, mHandler);
282 mTelemetryReader.start();
284 mTelemetryLogger = new TelemetryLogger(this, mAltosBluetooth);
288 private void onTimerTick() {
289 if (D) Log.d(TAG, "Timer wakeup");
291 if (mClients.size() <= 0 && state != STATE_CONNECTED) {
294 } catch (Throwable t) {
295 Log.e(TAG, "Timer failed: ", t);
301 public void onCreate() {
302 // Create a reference to the NotificationManager so that we can update our notifcation text later
303 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
305 setState(STATE_READY);
307 // Start our timer - first event in 10 seconds, then every 10 seconds after that.
308 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 10000L, 10000L);
310 // Listen for GPS and Network position updates
311 locationListener = new AltosLocationListener(mHandler);
313 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
315 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
316 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
320 public int onStartCommand(Intent intent, int flags, int startId) {
321 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
323 CharSequence text = getText(R.string.telemetry_service_started);
325 // Create notification to be displayed while the service runs
326 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
328 // The PendingIntent to launch our activity if the user selects this notification
329 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
330 new Intent(this, AltosDroid.class), 0);
332 // Set the info for the views that show in the notification panel.
333 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
335 // Set the notification to be in the "Ongoing" section.
336 notification.flags |= Notification.FLAG_ONGOING_EVENT;
338 // Move us into the foreground.
339 startForeground(NOTIFICATION, notification);
341 // We want this service to continue running until it is explicitly
342 // stopped, so return sticky.
347 public void onDestroy() {
349 // Stop listening for location updates
350 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
351 locationManager.removeUpdates(locationListener);
353 // Stop the bluetooth Comms threads
354 stopAltosBluetooth();
356 // Demote us from the foreground, and cancel the persistent notification.
357 stopForeground(true);
360 if (timer != null) {timer.cancel();}
362 // Tell the user we stopped.
363 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
367 public IBinder onBind(Intent intent) {
368 return mMessenger.getBinder();