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.os.Looper;
40 import android.util.Log;
41 import android.widget.Toast;
42 import android.location.Location;
43 import android.location.LocationManager;
44 import android.location.LocationListener;
45 import android.location.Criteria;
47 import org.altusmetrum.altoslib_4.*;
50 public class TelemetryService extends Service implements LocationListener {
52 private static final String TAG = "TelemetryService";
53 private static final boolean D = true;
55 static final int MSG_REGISTER_CLIENT = 1;
56 static final int MSG_UNREGISTER_CLIENT = 2;
57 static final int MSG_CONNECT = 3;
58 static final int MSG_CONNECTED = 4;
59 static final int MSG_CONNECT_FAILED = 5;
60 static final int MSG_DISCONNECTED = 6;
61 static final int MSG_TELEMETRY = 7;
62 static final int MSG_SETFREQUENCY = 8;
63 static final int MSG_CRC_ERROR = 9;
65 public static final int STATE_NONE = 0;
66 public static final int STATE_READY = 1;
67 public static final int STATE_CONNECTING = 2;
68 public static final int STATE_CONNECTED = 3;
70 // Unique Identification Number for the Notification.
71 // We use it on Notification start, and to cancel it.
72 private int NOTIFICATION = R.string.telemetry_service_label;
73 //private NotificationManager mNM;
75 // Timer - we wake up every now and then to decide if the service should stop
76 private Timer timer = new Timer();
78 ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
79 final Handler mHandler = new IncomingHandler(this);
80 final Messenger mMessenger = new Messenger(mHandler); // Target we publish for clients to send messages to IncomingHandler.
82 // Name of the connected device
83 private BluetoothDevice device = null;
84 private AltosBluetooth mAltosBluetooth = null;
85 private AltosConfigData mConfigData = null;
86 private TelemetryReader mTelemetryReader = null;
87 private TelemetryLogger mTelemetryLogger = null;
89 // internally track state of bluetooth connection
90 private int state = STATE_NONE;
92 // Last data seen; send to UI when it starts
94 private AltosState last_state;
95 private Location last_location;
96 private int last_crc_errors;
98 // Handler of incoming messages from clients.
99 static class IncomingHandler extends Handler {
100 private final WeakReference<TelemetryService> service;
101 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
104 public void handleMessage(Message msg) {
105 TelemetryService s = service.get();
107 case MSG_REGISTER_CLIENT:
108 s.mClients.add(msg.replyTo);
110 // Now we try to send the freshly connected UI any relavant information about what
111 // we're talking to - Basically state and Config Data.
112 msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, s.state, -1, s.mConfigData));
113 // We also send any recent telemetry or location data that's cached
114 if (s.last_state != null) msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_TELEMETRY, s.last_state ));
115 if (s.last_location != null) msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_LOCATION , s.last_location ));
116 if (s.last_crc_errors != 0 ) msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_CRC_ERROR, s.last_crc_errors));
117 } catch (RemoteException e) {
118 s.mClients.remove(msg.replyTo);
120 if (D) Log.d(TAG, "Client bound to service");
122 case MSG_UNREGISTER_CLIENT:
123 s.mClients.remove(msg.replyTo);
124 if (D) Log.d(TAG, "Client unbound from service");
127 if (D) Log.d(TAG, "Connect command received");
128 s.device = (BluetoothDevice) msg.obj;
129 s.startAltosBluetooth();
132 if (D) Log.d(TAG, "Connected to device");
135 case MSG_CONNECT_FAILED:
136 if (D) Log.d(TAG, "Connection failed... retrying");
137 s.startAltosBluetooth();
139 case MSG_DISCONNECTED:
140 // Only do the following if we haven't been shutdown elsewhere..
141 if (s.device != null) {
142 if (D) Log.d(TAG, "Disconnected from " + s.device.getName());
143 s.stopAltosBluetooth();
147 // forward telemetry messages
148 s.last_state = (AltosState) msg.obj;
149 s.sendMessageToClients(Message.obtain(null, AltosDroid.MSG_TELEMETRY, msg.obj));
152 // forward crc error messages
153 s.last_crc_errors = (Integer) msg.obj;
154 s.sendMessageToClients(Message.obtain(null, AltosDroid.MSG_CRC_ERROR, msg.obj));
156 case MSG_SETFREQUENCY:
157 if (s.state == STATE_CONNECTED) {
159 s.mAltosBluetooth.set_radio_frequency((Double) msg.obj);
160 } catch (InterruptedException e) {
161 } catch (TimeoutException e) {
166 super.handleMessage(msg);
171 private void sendMessageToClients(Message m) {
172 for (int i=mClients.size()-1; i>=0; i--) {
174 mClients.get(i).send(m);
175 } catch (RemoteException e) {
181 private void stopAltosBluetooth() {
182 if (D) Log.d(TAG, "stopAltosBluetooth(): begin");
183 setState(STATE_READY);
184 if (mTelemetryReader != null) {
185 if (D) Log.d(TAG, "stopAltosBluetooth(): stopping TelemetryReader");
186 mTelemetryReader.interrupt();
188 mTelemetryReader.join();
189 } catch (InterruptedException e) {
191 mTelemetryReader = null;
193 if (mTelemetryLogger != null) {
194 if (D) Log.d(TAG, "stopAltosBluetooth(): stopping TelemetryLogger");
195 mTelemetryLogger.stop();
196 mTelemetryLogger = null;
198 if (mAltosBluetooth != null) {
199 if (D) Log.d(TAG, "stopAltosBluetooth(): stopping AltosBluetooth");
200 mAltosBluetooth.close();
201 mAltosBluetooth = null;
207 private void startAltosBluetooth() {
208 if (device == null) {
211 if (mAltosBluetooth == null) {
212 if (D) Log.d(TAG, String.format("startAltosBluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress()));
213 mAltosBluetooth = new AltosBluetooth(device, mHandler);
214 setState(STATE_CONNECTING);
216 // This is a bit of a hack - if it appears we're still connected, we treat this as a restart.
217 // So, to give a suitable delay to teardown/bringup, we just schedule a resend of a message
218 // to ourselves in a few seconds time that will ultimately call this method again.
219 // ... then we tear down the existing connection.
220 // We do it this way around so that we don't lose a reference to the device when this method
221 // is called on reception of MSG_CONNECT_FAILED in the handler above.
222 mHandler.sendMessageDelayed(Message.obtain(null, MSG_CONNECT, device), 3000);
223 stopAltosBluetooth();
227 private synchronized void setState(int s) {
228 if (D) Log.d(TAG, "setState(): " + state + " -> " + s);
231 // This shouldn't be required - mConfigData should be null for any non-connected
232 // state, but to be safe and to reduce message size
233 AltosConfigData acd = (state == STATE_CONNECTED) ? mConfigData : null;
235 sendMessageToClients(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, state, -1, acd));
238 private void connected() {
240 if (mAltosBluetooth == null)
241 throw new InterruptedException("no bluetooth");
242 mConfigData = mAltosBluetooth.config_data();
243 } catch (InterruptedException e) {
244 } catch (TimeoutException e) {
245 // If this timed out, then we really want to retry it, but
246 // probably safer to just retry the connection from scratch.
247 mHandler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
251 setState(STATE_CONNECTED);
253 mTelemetryReader = new TelemetryReader(mAltosBluetooth, mHandler);
254 mTelemetryReader.start();
256 mTelemetryLogger = new TelemetryLogger(this, mAltosBluetooth);
260 private void onTimerTick() {
261 if (D) Log.d(TAG, "Timer wakeup");
263 if (mClients.size() <= 0 && state != STATE_CONNECTED) {
266 } catch (Throwable t) {
267 Log.e(TAG, "Timer failed: ", t);
273 public void onCreate() {
274 // Create a reference to the NotificationManager so that we can update our notifcation text later
275 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
277 setState(STATE_READY);
279 // Start our timer - first event in 10 seconds, then every 10 seconds after that.
280 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 10000L, 10000L);
282 // Listen for GPS and Network position updates
283 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
285 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
286 // locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
290 public int onStartCommand(Intent intent, int flags, int startId) {
291 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
293 CharSequence text = getText(R.string.telemetry_service_started);
295 // Create notification to be displayed while the service runs
296 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
298 // The PendingIntent to launch our activity if the user selects this notification
299 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
300 new Intent(this, AltosDroid.class), 0);
302 // Set the info for the views that show in the notification panel.
303 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
305 // Set the notification to be in the "Ongoing" section.
306 notification.flags |= Notification.FLAG_ONGOING_EVENT;
308 // Move us into the foreground.
309 startForeground(NOTIFICATION, notification);
311 // We want this service to continue running until it is explicitly
312 // stopped, so return sticky.
317 public void onDestroy() {
319 // Stop listening for location updates
320 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
322 // Stop the bluetooth Comms threads
323 stopAltosBluetooth();
325 // Demote us from the foreground, and cancel the persistent notification.
326 stopForeground(true);
329 if (timer != null) {timer.cancel();}
331 // Tell the user we stopped.
332 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
336 public IBinder onBind(Intent intent) {
337 return mMessenger.getBinder();
341 public void onLocationChanged(Location location) {
342 last_location = location;
343 sendMessageToClients(Message.obtain(null, AltosDroid.MSG_LOCATION, location));
346 public void onStatusChanged(String provider, int status, Bundle extras) {
349 public void onProviderEnabled(String provider) {
352 public void onProviderDisabled(String provider) {