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) {
53 public void onStatusChanged(String provider, int status, Bundle extras) {
56 public void onProviderEnabled(String provider) {
59 public void onProviderDisabled(String provider) {
62 public AltosLocationListener(boolean fine) {
67 public class TelemetryService extends Service {
69 private static final String TAG = "TelemetryService";
70 private static final boolean D = true;
72 static final int MSG_REGISTER_CLIENT = 1;
73 static final int MSG_UNREGISTER_CLIENT = 2;
74 static final int MSG_CONNECT = 3;
75 static final int MSG_CONNECTED = 4;
76 static final int MSG_CONNECT_FAILED = 5;
77 static final int MSG_DISCONNECTED = 6;
78 static final int MSG_TELEMETRY = 7;
79 static final int MSG_SETFREQUENCY = 8;
81 public static final int STATE_NONE = 0;
82 public static final int STATE_READY = 1;
83 public static final int STATE_CONNECTING = 2;
84 public static final int STATE_CONNECTED = 3;
86 // Unique Identification Number for the Notification.
87 // We use it on Notification start, and to cancel it.
88 private int NOTIFICATION = R.string.telemetry_service_label;
89 //private NotificationManager mNM;
91 // Timer - we wake up every now and then to decide if the service should stop
92 private Timer timer = new Timer();
94 ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
95 final Handler mHandler = new IncomingHandler(this);
96 final Messenger mMessenger = new Messenger(mHandler); // Target we publish for clients to send messages to IncomingHandler.
98 // Name of the connected device
99 private BluetoothDevice device = null;
100 private AltosBluetooth mAltosBluetooth = null;
101 private AltosConfigData mConfigData = null;
102 private TelemetryReader mTelemetryReader = null;
103 private TelemetryLogger mTelemetryLogger = null;
105 // internally track state of bluetooth connection
106 private int state = STATE_NONE;
108 // location listeners
110 private AltosLocationListener gpsListener;
111 private AltosLocationListener netListener;
113 // Handler of incoming messages from clients.
114 static class IncomingHandler extends Handler {
115 private final WeakReference<TelemetryService> service;
116 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
119 public void handleMessage(Message msg) {
120 TelemetryService s = service.get();
122 case MSG_REGISTER_CLIENT:
123 s.mClients.add(msg.replyTo);
125 // Now we try to send the freshly connected UI any relavant information about what
126 // we're talking to - Basically state and Config Data.
127 msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, s.state, -1, s.mConfigData));
128 } catch (RemoteException e) {
129 s.mClients.remove(msg.replyTo);
131 if (D) Log.d(TAG, "Client bound to service");
133 case MSG_UNREGISTER_CLIENT:
134 s.mClients.remove(msg.replyTo);
135 if (D) Log.d(TAG, "Client unbound from service");
138 if (D) Log.d(TAG, "Connect command received");
139 s.device = (BluetoothDevice) msg.obj;
140 s.startAltosBluetooth();
143 if (D) Log.d(TAG, "Connected to device");
146 case MSG_CONNECT_FAILED:
147 if (D) Log.d(TAG, "Connection failed... retrying");
148 s.startAltosBluetooth();
150 case MSG_DISCONNECTED:
151 // Only do the following if we haven't been shutdown elsewhere..
152 if (s.device != null) {
153 if (D) Log.d(TAG, "Disconnected from " + s.device.getName());
154 s.stopAltosBluetooth();
158 s.sendMessageToClients(Message.obtain(null, AltosDroid.MSG_TELEMETRY, msg.obj));
160 case MSG_SETFREQUENCY:
161 if (s.state == STATE_CONNECTED) {
163 s.mAltosBluetooth.set_radio_frequency((Double) msg.obj);
164 } catch (InterruptedException e) {
165 } catch (TimeoutException e) {
170 super.handleMessage(msg);
175 private void sendMessageToClients(Message m) {
176 for (int i=mClients.size()-1; i>=0; i--) {
178 mClients.get(i).send(m);
179 } catch (RemoteException e) {
185 private void stopAltosBluetooth() {
186 if (D) Log.d(TAG, "stopAltosBluetooth(): begin");
187 setState(STATE_READY);
188 if (mTelemetryReader != null) {
189 if (D) Log.d(TAG, "stopAltosBluetooth(): stopping TelemetryReader");
190 mTelemetryReader.interrupt();
192 mTelemetryReader.join();
193 } catch (InterruptedException e) {
195 mTelemetryReader = null;
197 if (mTelemetryLogger != null) {
198 if (D) Log.d(TAG, "stopAltosBluetooth(): stopping TelemetryLogger");
199 mTelemetryLogger.stop();
200 mTelemetryLogger = null;
202 if (mAltosBluetooth != null) {
203 if (D) Log.d(TAG, "stopAltosBluetooth(): stopping AltosBluetooth");
204 mAltosBluetooth.close();
205 mAltosBluetooth = null;
211 private void startAltosBluetooth() {
212 if (mAltosBluetooth == null) {
213 if (D) Log.d(TAG, String.format("startAltosBluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress()));
214 mAltosBluetooth = new AltosBluetooth(device, mHandler);
215 setState(STATE_CONNECTING);
217 // This is a bit of a hack - if it appears we're still connected, we treat this as a restart.
218 // So, to give a suitable delay to teardown/bringup, we just schedule a resend of a message
219 // to ourselves in a few seconds time that will ultimately call this method again.
220 // ... then we tear down the existing connection.
221 // We do it this way around so that we don't lose a reference to the device when this method
222 // is called on reception of MSG_CONNECT_FAILED in the handler above.
223 mHandler.sendMessageDelayed(Message.obtain(null, MSG_CONNECT, device), 3000);
224 stopAltosBluetooth();
228 private synchronized void setState(int s) {
229 if (D) Log.d(TAG, "setState(): " + state + " -> " + s);
232 // This shouldn't be required - mConfigData should be null for any non-connected
233 // state, but to be safe and to reduce message size
234 AltosConfigData acd = (state == STATE_CONNECTED) ? mConfigData : null;
236 sendMessageToClients(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, state, -1, acd));
239 private void connected() {
241 mConfigData = mAltosBluetooth.config_data();
242 } catch (InterruptedException e) {
243 } catch (TimeoutException e) {
244 // If this timed out, then we really want to retry it, but
245 // probably safer to just retry the connection from scratch.
246 mHandler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
250 setState(STATE_CONNECTED);
252 mTelemetryReader = new TelemetryReader(mAltosBluetooth, mHandler);
253 mTelemetryReader.start();
255 mTelemetryLogger = new TelemetryLogger(this, mAltosBluetooth);
259 private void onTimerTick() {
260 if (D) Log.d(TAG, "Timer wakeup");
262 if (mClients.size() <= 0 && state != STATE_CONNECTED) {
265 } catch (Throwable t) {
266 Log.e(TAG, "Timer failed: ", t);
272 public void onCreate() {
273 // Create a reference to the NotificationManager so that we can update our notifcation text later
274 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
276 setState(STATE_READY);
278 // Start our timer - first event in 10 seconds, then every 10 seconds after that.
279 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 10000L, 10000L);
281 // Listen for GPS and Network position updates
282 gpsListener = new AltosLocationListener(true);
283 netListener = new AltosLocationListener(false);
285 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
287 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsListener);
288 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, netListener);
292 public int onStartCommand(Intent intent, int flags, int startId) {
293 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
295 CharSequence text = getText(R.string.telemetry_service_started);
297 // Create notification to be displayed while the service runs
298 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
300 // The PendingIntent to launch our activity if the user selects this notification
301 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
302 new Intent(this, AltosDroid.class), 0);
304 // Set the info for the views that show in the notification panel.
305 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
307 // Set the notification to be in the "Ongoing" section.
308 notification.flags |= Notification.FLAG_ONGOING_EVENT;
310 // Move us into the foreground.
311 startForeground(NOTIFICATION, notification);
313 // We want this service to continue running until it is explicitly
314 // stopped, so return sticky.
319 public void onDestroy() {
321 // Stop listening for location updates
322 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
323 locationManager.removeUpdates(gpsListener);
324 locationManager.removeUpdates(netListener);
326 // Stop the bluetooth Comms threads
327 stopAltosBluetooth();
329 // Demote us from the foreground, and cancel the persistent notification.
330 stopForeground(true);
333 if (timer != null) {timer.cancel();}
335 // Tell the user we stopped.
336 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
340 public IBinder onBind(Intent intent) {
341 return mMessenger.getBinder();