altosdroid: really don't need to store a local copy of the device name
[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
51         public static final int STATE_NONE       = 0;
52         public static final int STATE_READY      = 1;
53         public static final int STATE_CONNECTING = 2;
54         public static final int STATE_CONNECTED  = 3;
55
56         // Key names received from the TelemetryService Handler
57         public static final String KEY_DEVNAME = "key_devname";
58         public static final String KEY_TOAST   = "key_toast";
59
60         // Unique Identification Number for the Notification.
61         // We use it on Notification start, and to cancel it.
62         private int NOTIFICATION = R.string.telemetry_service_label;
63         //private NotificationManager mNM;
64
65         ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
66         final Handler   mHandler   = new IncomingHandler(this);
67         final Messenger mMessenger = new Messenger(mHandler); // Target we publish for clients to send messages to IncomingHandler.
68
69         // Name of the connected device
70         private BluetoothDevice device = null;
71         private AltosBluetooth mAltosBluetooth = null;
72         private int state = STATE_NONE;
73         LinkedBlockingQueue<AltosLine> telem;
74
75         // Handler of incoming messages from clients.
76         static class IncomingHandler extends Handler {
77                 private final WeakReference<TelemetryService> service;
78                 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
79
80                 @Override
81                 public void handleMessage(Message msg) {
82                         TelemetryService s = service.get();
83                         switch (msg.what) {
84                         case MSG_REGISTER_CLIENT:
85                                 s.mClients.add(msg.replyTo);
86                                 try {
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.sendMessageToClients(Message.obtain(null, AltosDroid.MSG_DEVNAME, s.device.getName()));
105                                 s.setState(STATE_CONNECTED);
106                                 s.mAltosBluetooth.add_monitor(s.telem);
107                                 break;
108                         default:
109                                 super.handleMessage(msg);
110                         }
111                 }
112         }
113
114         private void sendMessageToClients(Message m) {
115                 for (int i=mClients.size()-1; i>=0; i--) {
116                         try {
117                                 mClients.get(i).send(m);
118                         } catch (RemoteException e) {
119                                 mClients.remove(i);
120                         }
121                 }
122         }
123
124         private void stopAltosBluetooth() {
125                 if (D) Log.i(TAG, "Stopping BT");
126                 setState(STATE_READY);
127                 if (mAltosBluetooth != null) {
128                         if (D) Log.i(TAG, "Closing AltosBluetooth");
129                         mAltosBluetooth.close();
130                         mAltosBluetooth = null;
131                 }
132                 device = null;
133                 telem.clear();
134         }
135
136         private void startAltosBluetooth() {
137                 if (mAltosBluetooth == null) {
138                         if (D) Log.i(TAG, "Connecting to " + device.getName());
139                         mAltosBluetooth = new AltosBluetooth(device, mHandler);
140                         setState(STATE_CONNECTING);
141                 } else {
142                         stopAltosBluetooth();
143                         mHandler.sendMessageDelayed(Message.obtain(null, MSG_CONNECT, device), 1000);
144                 }
145         }
146
147         private synchronized void setState(int s) {
148                 if (D) Log.d(TAG, "setState() " + state + " -> " + s);
149                 state = s;
150
151                 sendMessageToClients(Message.obtain(null, AltosDroid.MSG_STATE_CHANGE, state, -1));
152         }
153
154         @Override
155         public void onCreate() {
156                 // Create a reference to the NotificationManager so that we can update our notifcation text later
157                 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
158
159                 telem = new LinkedBlockingQueue<AltosLine>();
160                 setState(STATE_READY);
161         }
162
163         @Override
164         public int onStartCommand(Intent intent, int flags, int startId) {
165                 Log.i("TelemetryService", "Received start id " + startId + ": " + intent);
166
167                 CharSequence text = getText(R.string.telemetry_service_started);
168
169                 // Create notification to be displayed while the service runs
170                 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
171
172                 // The PendingIntent to launch our activity if the user selects this notification
173                 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
174                                 new Intent(this, AltosDroid.class), 0);
175
176                 // Set the info for the views that show in the notification panel.
177                 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
178
179                 // Set the notification to be in the "Ongoing" section.
180                 notification.flags |= Notification.FLAG_ONGOING_EVENT;
181
182                 // Move us into the foreground.
183                 startForeground(NOTIFICATION, notification);
184
185                 // We want this service to continue running until it is explicitly
186                 // stopped, so return sticky.
187                 return START_STICKY;
188         }
189
190         @Override
191         public void onDestroy() {
192
193                 // Stop the bluetooth Comms threads
194                 stopAltosBluetooth();
195
196                 // Demote us from the foreground, and cancel the persistent notification.
197                 stopForeground(true);
198
199                 // Tell the user we stopped.
200                 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
201         }
202
203         @Override
204         public IBinder onBind(Intent intent) {
205                 return mMessenger.getBinder();
206         }
207
208
209 }