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.*;
48 public class TelemetryService extends Service implements LocationListener {
50 private static final String TAG = "TelemetryService";
51 private static final boolean D = true;
53 static final int MSG_REGISTER_CLIENT = 1;
54 static final int MSG_UNREGISTER_CLIENT = 2;
55 static final int MSG_CONNECT = 3;
56 static final int MSG_CONNECTED = 4;
57 static final int MSG_CONNECT_FAILED = 5;
58 static final int MSG_DISCONNECTED = 6;
59 static final int MSG_TELEMETRY = 7;
60 static final int MSG_SETFREQUENCY = 8;
61 static final int MSG_CRC_ERROR = 9;
63 public static final int STATE_NONE = 0;
64 public static final int STATE_READY = 1;
65 public static final int STATE_CONNECTING = 2;
66 public static final int STATE_CONNECTED = 3;
68 // Unique Identification Number for the Notification.
69 // We use it on Notification start, and to cancel it.
70 private int NOTIFICATION = R.string.telemetry_service_label;
71 //private NotificationManager mNM;
73 // Timer - we wake up every now and then to decide if the service should stop
74 private Timer timer = new Timer();
76 ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
77 final Handler mHandler = new IncomingHandler(this);
78 final Messenger mMessenger = new Messenger(mHandler); // Target we publish for clients to send messages to IncomingHandler.
80 // Name of the connected device
81 private BluetoothDevice device = null;
82 private AltosBluetooth mAltosBluetooth = null;
83 private AltosConfigData mConfigData = null;
84 private TelemetryReader mTelemetryReader = null;
85 private TelemetryLogger mTelemetryLogger = null;
87 // internally track state of bluetooth connection
88 private int state = STATE_NONE;
90 // Last data seen; send to UI when it starts
92 private AltosState last_state;
93 private Location last_location;
94 private int last_crc_errors;
96 // Handler of incoming messages from clients.
97 static class IncomingHandler extends Handler {
98 private final WeakReference<TelemetryService> service;
99 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
102 public void handleMessage(Message msg) {
103 TelemetryService s = service.get();
105 case MSG_REGISTER_CLIENT:
106 s.mClients.add(msg.replyTo);
108 // Now we try to send the freshly connected UI any relavant information about what
109 // we're talking to - Basically state and Config Data.
110 msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, s.state, -1, s.mConfigData));
111 // We also send any recent telemetry or location data that's cached
112 if (s.last_state != null) msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_TELEMETRY, s.last_state ));
113 if (s.last_location != null) msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_LOCATION , s.last_location ));
114 if (s.last_crc_errors != 0 ) msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_CRC_ERROR, s.last_crc_errors));
115 } catch (RemoteException e) {
116 s.mClients.remove(msg.replyTo);
118 if (D) Log.d(TAG, "Client bound to service");
120 case MSG_UNREGISTER_CLIENT:
121 s.mClients.remove(msg.replyTo);
122 if (D) Log.d(TAG, "Client unbound from service");
125 if (D) Log.d(TAG, "Connect command received");
126 s.device = (BluetoothDevice) msg.obj;
127 s.startAltosBluetooth();
130 if (D) Log.d(TAG, "Connected to device");
133 case MSG_CONNECT_FAILED:
134 if (D) Log.d(TAG, "Connection failed... retrying");
135 s.startAltosBluetooth();
137 case MSG_DISCONNECTED:
138 // Only do the following if we haven't been shutdown elsewhere..
139 if (s.device != null) {
140 if (D) Log.d(TAG, "Disconnected from " + s.device.getName());
141 s.stopAltosBluetooth();
145 // forward telemetry messages
146 s.last_state = (AltosState) msg.obj;
147 s.sendMessageToClients(Message.obtain(null, AltosDroid.MSG_TELEMETRY, msg.obj));
150 // forward crc error messages
151 s.last_crc_errors = (Integer) msg.obj;
152 s.sendMessageToClients(Message.obtain(null, AltosDroid.MSG_CRC_ERROR, msg.obj));
154 case MSG_SETFREQUENCY:
155 if (s.state == STATE_CONNECTED) {
157 s.mAltosBluetooth.set_radio_frequency((Double) msg.obj);
158 } catch (InterruptedException e) {
159 } catch (TimeoutException e) {
164 super.handleMessage(msg);
169 private void sendMessageToClients(Message m) {
170 for (int i=mClients.size()-1; i>=0; i--) {
172 mClients.get(i).send(m);
173 } catch (RemoteException e) {
179 private void stopAltosBluetooth() {
180 if (D) Log.d(TAG, "stopAltosBluetooth(): begin");
181 setState(STATE_READY);
182 if (mTelemetryReader != null) {
183 if (D) Log.d(TAG, "stopAltosBluetooth(): stopping TelemetryReader");
184 mTelemetryReader.interrupt();
186 mTelemetryReader.join();
187 } catch (InterruptedException e) {
189 mTelemetryReader = null;
191 if (mTelemetryLogger != null) {
192 if (D) Log.d(TAG, "stopAltosBluetooth(): stopping TelemetryLogger");
193 mTelemetryLogger.stop();
194 mTelemetryLogger = null;
196 if (mAltosBluetooth != null) {
197 if (D) Log.d(TAG, "stopAltosBluetooth(): stopping AltosBluetooth");
198 mAltosBluetooth.close();
199 mAltosBluetooth = null;
205 private void startAltosBluetooth() {
206 if (device == null) {
209 if (mAltosBluetooth == null) {
210 if (D) Log.d(TAG, String.format("startAltosBluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress()));
211 mAltosBluetooth = new AltosBluetooth(device, mHandler);
212 setState(STATE_CONNECTING);
214 // This is a bit of a hack - if it appears we're still connected, we treat this as a restart.
215 // So, to give a suitable delay to teardown/bringup, we just schedule a resend of a message
216 // to ourselves in a few seconds time that will ultimately call this method again.
217 // ... then we tear down the existing connection.
218 // We do it this way around so that we don't lose a reference to the device when this method
219 // is called on reception of MSG_CONNECT_FAILED in the handler above.
220 mHandler.sendMessageDelayed(Message.obtain(null, MSG_CONNECT, device), 3000);
221 stopAltosBluetooth();
225 private synchronized void setState(int s) {
226 if (D) Log.d(TAG, "setState(): " + state + " -> " + s);
229 // This shouldn't be required - mConfigData should be null for any non-connected
230 // state, but to be safe and to reduce message size
231 AltosConfigData acd = (state == STATE_CONNECTED) ? mConfigData : null;
233 sendMessageToClients(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, state, -1, acd));
236 private void connected() {
238 if (mAltosBluetooth == null)
239 throw new InterruptedException("no bluetooth");
240 mConfigData = mAltosBluetooth.config_data();
241 } catch (InterruptedException e) {
242 } catch (TimeoutException e) {
243 // If this timed out, then we really want to retry it, but
244 // probably safer to just retry the connection from scratch.
245 mHandler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
249 setState(STATE_CONNECTED);
251 mTelemetryReader = new TelemetryReader(mAltosBluetooth, mHandler);
252 mTelemetryReader.start();
254 mTelemetryLogger = new TelemetryLogger(this, mAltosBluetooth);
258 private void onTimerTick() {
259 if (D) Log.d(TAG, "Timer wakeup");
261 if (mClients.size() <= 0 && state != STATE_CONNECTED) {
264 } catch (Throwable t) {
265 Log.e(TAG, "Timer failed: ", t);
271 public void onCreate() {
272 // Create a reference to the NotificationManager so that we can update our notifcation text later
273 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
275 setState(STATE_READY);
277 // Start our timer - first event in 10 seconds, then every 10 seconds after that.
278 timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 10000L, 10000L);
280 // Listen for GPS and Network position updates
281 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
283 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
284 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
288 public int onStartCommand(Intent intent, int flags, int startId) {
289 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
291 CharSequence text = getText(R.string.telemetry_service_started);
293 // Create notification to be displayed while the service runs
294 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
296 // The PendingIntent to launch our activity if the user selects this notification
297 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
298 new Intent(this, AltosDroid.class), 0);
300 // Set the info for the views that show in the notification panel.
301 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
303 // Set the notification to be in the "Ongoing" section.
304 notification.flags |= Notification.FLAG_ONGOING_EVENT;
306 // Move us into the foreground.
307 startForeground(NOTIFICATION, notification);
309 // We want this service to continue running until it is explicitly
310 // stopped, so return sticky.
315 public void onDestroy() {
317 // Stop listening for location updates
318 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
320 // Stop the bluetooth Comms threads
321 stopAltosBluetooth();
323 // Demote us from the foreground, and cancel the persistent notification.
324 stopForeground(true);
327 if (timer != null) {timer.cancel();}
329 // Tell the user we stopped.
330 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
334 public IBinder onBind(Intent intent) {
335 return mMessenger.getBinder();
339 public void onLocationChanged(Location location) {
340 last_location = location;
341 sendMessageToClients(Message.obtain(null, AltosDroid.MSG_LOCATION, location));
344 public void onStatusChanged(String provider, int status, Bundle extras) {
347 public void onProviderEnabled(String provider) {
350 public void onProviderDisabled(String provider) {