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