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