42198b6ba7c4d759df8fda1f52f86ccee1df7ac9
[fw/altos] / altosdroid / src / org / altusmetrum / AltosDroid / TelemetryService.java
1 /*
2  * Copyright © 2012 Mike Beattie <mike@ethernal.org>
3  *
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.
7  *
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.
12  *
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.
16  */
17
18 package org.altusmetrum.AltosDroid;
19
20 import java.lang.ref.WeakReference;
21 import java.util.ArrayList;
22
23 import android.app.Notification;
24 //import android.app.NotificationManager;
25 import android.app.PendingIntent;
26 import android.app.Service;
27 import android.bluetooth.BluetoothDevice;
28 import android.content.Intent;
29 //import android.os.Bundle;
30 import android.os.IBinder;
31 import android.os.Handler;
32 import android.os.Message;
33 import android.os.Messenger;
34 import android.os.RemoteException;
35 import android.util.Log;
36 import android.widget.Toast;
37
38 //import org.altusmetrum.AltosLib.*;
39
40 public class TelemetryService extends Service {
41
42         private static final String TAG = "TelemetryService";
43         private static final boolean D = true;
44
45         static final int MSG_REGISTER_CLIENT   = 1;
46         static final int MSG_UNREGISTER_CLIENT = 2;
47         static final int MSG_CONNECT           = 3;
48         static final int MSG_CONNECTED         = 4;
49         static final int MSG_CONNECT_FAILED    = 5;
50         static final int MSG_DISCONNECTED      = 6;
51         static final int MSG_TELEMETRY         = 7;
52
53         public static final int STATE_NONE       = 0;
54         public static final int STATE_READY      = 1;
55         public static final int STATE_CONNECTING = 2;
56         public static final int STATE_CONNECTED  = 3;
57
58         // Unique Identification Number for the Notification.
59         // We use it on Notification start, and to cancel it.
60         private int NOTIFICATION = R.string.telemetry_service_label;
61         //private NotificationManager mNM;
62
63         ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
64         final Handler   mHandler   = new IncomingHandler(this);
65         final Messenger mMessenger = new Messenger(mHandler); // Target we publish for clients to send messages to IncomingHandler.
66
67         // Name of the connected device
68         private BluetoothDevice device = null;
69         private AltosBluetooth mAltosBluetooth = null;
70         private TelemetryReader mTelemetryReader = null;
71
72         private int state = STATE_NONE;
73
74         // Handler of incoming messages from clients.
75         static class IncomingHandler extends Handler {
76                 private final WeakReference<TelemetryService> service;
77                 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
78
79                 @Override
80                 public void handleMessage(Message msg) {
81                         TelemetryService s = service.get();
82                         switch (msg.what) {
83                         case MSG_REGISTER_CLIENT:
84                                 s.mClients.add(msg.replyTo);
85                                 try {
86                                         msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_DEVNAME, s.device.getName()));
87                                         msg.replyTo.send(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, s.state, -1));
88                                 } catch (RemoteException e) {
89                                         s.mClients.remove(msg.replyTo);
90                                 }
91                                 if (D) Log.d(TAG, "Client bound to service");
92                                 break;
93                         case MSG_UNREGISTER_CLIENT:
94                                 s.mClients.remove(msg.replyTo);
95                                 if (D) Log.d(TAG, "Client unbound from service");
96                                 break;
97                         case MSG_CONNECT:
98                                 if (D) Log.d(TAG, "Connect command received");
99                                 s.device = (BluetoothDevice) msg.obj;
100                                 s.startAltosBluetooth();
101                                 break;
102                         case MSG_CONNECTED:
103                                 if (D) Log.d(TAG, "Connected to device");
104                                 s.connected();
105                                 break;
106                         case MSG_CONNECT_FAILED:
107                                 if (D) Log.d(TAG, "Connection failed... retrying");
108                                 s.startAltosBluetooth();
109                                 break;
110                         case MSG_DISCONNECTED:
111                                 if (D) Log.d(TAG, "Disconnected from " + s.device.getName());
112                                 s.stopAltosBluetooth();
113                                 break;
114                         case MSG_TELEMETRY:
115                                 s.sendMessageToClients(Message.obtain(null, AltosDroid.MSG_TELEMETRY, msg.obj));
116                                 break;
117                         default:
118                                 super.handleMessage(msg);
119                         }
120                 }
121         }
122
123         private void sendMessageToClients(Message m) {
124                 for (int i=mClients.size()-1; i>=0; i--) {
125                         try {
126                                 mClients.get(i).send(m);
127                         } catch (RemoteException e) {
128                                 mClients.remove(i);
129                         }
130                 }
131         }
132
133         private void stopAltosBluetooth() {
134                 if (D) Log.i(TAG, "Stopping BT");
135                 setState(STATE_READY);
136                 if (mTelemetryReader != null) {
137                         mTelemetryReader.interrupt();
138                         try {
139                                 mTelemetryReader.join();
140                         } catch (InterruptedException e) {
141                         }
142                         mTelemetryReader = null;
143                 }
144                 if (mAltosBluetooth != null) {
145                         if (D) Log.i(TAG, "Closing AltosBluetooth");
146                         mAltosBluetooth.close();
147                         mAltosBluetooth = null;
148                 }
149                 device = null;
150         }
151
152         private void startAltosBluetooth() {
153                 if (mAltosBluetooth == null) {
154                         if (D) Log.i(TAG, "Connecting to " + device.getName());
155                         mAltosBluetooth = new AltosBluetooth(device, mHandler);
156                         setState(STATE_CONNECTING);
157                 } else {
158                         stopAltosBluetooth();
159                         mHandler.sendMessageDelayed(Message.obtain(null, MSG_CONNECT, device), 1000);
160                 }
161         }
162
163         private synchronized void setState(int s) {
164                 if (D) Log.d(TAG, "setState() " + state + " -> " + s);
165                 state = s;
166
167                 sendMessageToClients(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, state, -1));
168         }
169
170         private void connected() {
171                 sendMessageToClients(Message.obtain(null, AltosDroid.MSG_DEVNAME, device.getName()));
172                 setState(STATE_CONNECTED);
173                 mTelemetryReader = new TelemetryReader(mAltosBluetooth, mHandler);
174                 mTelemetryReader.start();
175         }
176
177
178         @Override
179         public void onCreate() {
180                 // Create a reference to the NotificationManager so that we can update our notifcation text later
181                 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
182
183                 setState(STATE_READY);
184         }
185
186         @Override
187         public int onStartCommand(Intent intent, int flags, int startId) {
188                 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
189
190                 CharSequence text = getText(R.string.telemetry_service_started);
191
192                 // Create notification to be displayed while the service runs
193                 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
194
195                 // The PendingIntent to launch our activity if the user selects this notification
196                 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
197                                 new Intent(this, AltosDroid.class), 0);
198
199                 // Set the info for the views that show in the notification panel.
200                 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
201
202                 // Set the notification to be in the "Ongoing" section.
203                 notification.flags |= Notification.FLAG_ONGOING_EVENT;
204
205                 // Move us into the foreground.
206                 startForeground(NOTIFICATION, notification);
207
208                 // We want this service to continue running until it is explicitly
209                 // stopped, so return sticky.
210                 return START_STICKY;
211         }
212
213         @Override
214         public void onDestroy() {
215
216                 // Stop the bluetooth Comms threads
217                 stopAltosBluetooth();
218
219                 // Demote us from the foreground, and cancel the persistent notification.
220                 stopForeground(true);
221
222                 // Tell the user we stopped.
223                 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
224         }
225
226         @Override
227         public IBinder onBind(Intent intent) {
228                 return mMessenger.getBinder();
229         }
230
231
232 }