altosdroid: Run even without Bluetooth
[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.concurrent.TimeoutException;
22 import java.util.*;
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.bluetooth.BluetoothAdapter;
30 import android.hardware.usb.*;
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.os.Looper;
40 import android.widget.Toast;
41 import android.location.Criteria;
42
43 import org.altusmetrum.altoslib_10.*;
44
45 public class TelemetryService extends Service {
46
47         static final int MSG_REGISTER_CLIENT   = 1;
48         static final int MSG_UNREGISTER_CLIENT = 2;
49         static final int MSG_CONNECT           = 3;
50         static final int MSG_OPEN_USB          = 4;
51         static final int MSG_CONNECTED         = 5;
52         static final int MSG_CONNECT_FAILED    = 6;
53         static final int MSG_DISCONNECTED      = 7;
54         static final int MSG_TELEMETRY         = 8;
55         static final int MSG_SETFREQUENCY      = 9;
56         static final int MSG_CRC_ERROR         = 10;
57         static final int MSG_SETBAUD           = 11;
58         static final int MSG_DISCONNECT        = 12;
59         static final int MSG_DELETE_SERIAL     = 13;
60         static final int MSG_BLUETOOTH_ENABLED = 14;
61
62         // Unique Identification Number for the Notification.
63         // We use it on Notification start, and to cancel it.
64         private int NOTIFICATION = R.string.telemetry_service_label;
65         //private NotificationManager mNM;
66
67         ArrayList<Messenger> clients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
68         final Handler   handler   = new IncomingHandler(this);
69         final Messenger messenger = new Messenger(handler); // Target we publish for clients to send messages to IncomingHandler.
70
71         // Name of the connected device
72         DeviceAddress address;
73         private AltosDroidLink  altos_link  = null;
74         private TelemetryReader telemetry_reader = null;
75         private TelemetryLogger telemetry_logger = null;
76
77         // Local Bluetooth adapter
78         private BluetoothAdapter bluetooth_adapter = null;
79
80         // Last data seen; send to UI when it starts
81         private TelemetryState  telemetry_state;
82
83         // Handler of incoming messages from clients.
84         static class IncomingHandler extends Handler {
85                 private final WeakReference<TelemetryService> service;
86                 IncomingHandler(TelemetryService s) { service = new WeakReference<TelemetryService>(s); }
87
88                 @Override
89                 public void handleMessage(Message msg) {
90                         DeviceAddress address;
91
92                         TelemetryService s = service.get();
93                         AltosDroidLink bt = null;
94                         if (s == null)
95                                 return;
96                         switch (msg.what) {
97
98                                 /* Messages from application */
99                         case MSG_REGISTER_CLIENT:
100                                 s.add_client(msg.replyTo);
101                                 break;
102                         case MSG_UNREGISTER_CLIENT:
103                                 s.remove_client(msg.replyTo);
104                                 break;
105                         case MSG_CONNECT:
106                                 AltosDebug.debug("Connect command received");
107                                 address = (DeviceAddress) msg.obj;
108                                 AltosDroidPreferences.set_active_device(address);
109                                 s.start_altos_bluetooth(address, false);
110                                 break;
111                         case MSG_OPEN_USB:
112                                 AltosDebug.debug("Open USB command received");
113                                 UsbDevice device = (UsbDevice) msg.obj;
114                                 s.start_usb(device);
115                                 break;
116                         case MSG_DISCONNECT:
117                                 AltosDebug.debug("Disconnect command received");
118                                 s.address = null;
119                                 s.disconnect(true);
120                                 break;
121                         case MSG_DELETE_SERIAL:
122                                 AltosDebug.debug("Delete Serial command received");
123                                 s.delete_serial((Integer) msg.obj);
124                                 break;
125                         case MSG_SETFREQUENCY:
126                                 AltosDebug.debug("MSG_SETFREQUENCY");
127                                 s.telemetry_state.frequency = (Double) msg.obj;
128                                 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
129                                         try {
130                                                 s.altos_link.set_radio_frequency(s.telemetry_state.frequency);
131                                                 s.altos_link.save_frequency();
132                                         } catch (InterruptedException e) {
133                                         } catch (TimeoutException e) {
134                                         }
135                                 }
136                                 s.send_to_clients();
137                                 break;
138                         case MSG_SETBAUD:
139                                 AltosDebug.debug("MSG_SETBAUD");
140                                 s.telemetry_state.telemetry_rate = (Integer) msg.obj;
141                                 if (s.telemetry_state.connect == TelemetryState.CONNECT_CONNECTED) {
142                                         s.altos_link.set_telemetry_rate(s.telemetry_state.telemetry_rate);
143                                         s.altos_link.save_telemetry_rate();
144                                 }
145                                 s.send_to_clients();
146                                 break;
147
148                                 /*
149                                  *Messages from AltosBluetooth
150                                  */
151                         case MSG_CONNECTED:
152                                 AltosDebug.debug("MSG_CONNECTED");
153                                 bt = (AltosDroidLink) msg.obj;
154
155                                 if (bt != s.altos_link) {
156                                         AltosDebug.debug("Stale message");
157                                         break;
158                                 }
159                                 AltosDebug.debug("Connected to device");
160                                 try {
161                                         s.connected();
162                                 } catch (InterruptedException ie) {
163                                 }
164                                 break;
165                         case MSG_CONNECT_FAILED:
166                                 AltosDebug.debug("MSG_CONNECT_FAILED");
167                                 bt = (AltosDroidLink) msg.obj;
168
169                                 if (bt != s.altos_link) {
170                                         AltosDebug.debug("Stale message");
171                                         break;
172                                 }
173                                 if (s.address != null) {
174                                         AltosDebug.debug("Connection failed... retrying");
175                                         s.start_altos_bluetooth(s.address, true);
176                                 } else {
177                                         s.disconnect(true);
178                                 }
179                                 break;
180                         case MSG_DISCONNECTED:
181
182                                 /* This can be sent by either AltosDroidLink or TelemetryReader */
183                                 AltosDebug.debug("MSG_DISCONNECTED");
184                                 bt = (AltosDroidLink) msg.obj;
185
186                                 if (bt != s.altos_link) {
187                                         AltosDebug.debug("Stale message");
188                                         break;
189                                 }
190                                 if (s.address != null) {
191                                         AltosDebug.debug("Connection lost... retrying");
192                                         s.start_altos_bluetooth(s.address, true);
193                                 } else {
194                                         s.disconnect(true);
195                                 }
196                                 break;
197
198                                 /*
199                                  * Messages from TelemetryReader
200                                  */
201                         case MSG_TELEMETRY:
202                                 s.telemetry((AltosTelemetry) msg.obj);
203                                 break;
204                         case MSG_CRC_ERROR:
205                                 // forward crc error messages
206                                 s.telemetry_state.crc_errors = (Integer) msg.obj;
207                                 s.send_to_clients();
208                                 break;
209                         case MSG_BLUETOOTH_ENABLED:
210                                 AltosDebug.debug("TelemetryService notes that BT is now enabled");
211                                 address = AltosDroidPreferences.active_device();
212                                 if (address != null && !address.address.startsWith("USB"))
213                                         s.start_altos_bluetooth(address, false);
214                                 break;
215                         default:
216                                 super.handleMessage(msg);
217                         }
218                 }
219         }
220
221         /* Handle telemetry packet
222          */
223         private void telemetry(AltosTelemetry telem) {
224                 AltosState      state;
225
226                 if (telemetry_state.states.containsKey(telem.serial))
227                         state = telemetry_state.states.get(telem.serial).clone();
228                 else
229                         state = new AltosState();
230                 telem.update_state(state);
231                 telemetry_state.states.put(telem.serial, state);
232                 if (state != null) {
233                         AltosPreferences.set_state(telem.serial, state, null);
234                 }
235                 send_to_clients();
236         }
237
238         /* Construct the message to deliver to clients
239          */
240         private Message message() {
241                 if (telemetry_state == null)
242                         AltosDebug.debug("telemetry_state null!");
243                 if (telemetry_state.states == null)
244                         AltosDebug.debug("telemetry_state.states null!");
245                 return Message.obtain(null, AltosDroid.MSG_STATE, telemetry_state);
246         }
247
248         /* A new friend has connected
249          */
250         private void add_client(Messenger client) {
251
252                 clients.add(client);
253                 AltosDebug.debug("Client bound to service");
254
255                 /* On connect, send the current state to the new client
256                  */
257                 send_to_client(client);
258
259                 /* If we've got an address from a previous session, then
260                  * go ahead and try to reconnect to the device
261                  */
262                 if (address != null && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
263                         AltosDebug.debug("Reconnecting now...");
264                         start_altos_bluetooth(address, false);
265                 }
266         }
267
268         /* A client has disconnected, clean up
269          */
270         private void remove_client(Messenger client) {
271                 clients.remove(client);
272                 AltosDebug.debug("Client unbound from service");
273
274                 /* When the list of clients is empty, stop the service if
275                  * we have no current telemetry source
276                  */
277
278                  if (clients.isEmpty() && telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED) {
279                          AltosDebug.debug("No clients, no connection. Stopping\n");
280                          stopSelf();
281                  }
282         }
283
284         private void send_to_client(Messenger client) {
285                 Message m = message();
286                 try {
287                         client.send(m);
288                 } catch (RemoteException e) {
289                         AltosDebug.error("Client %s disappeared", client.toString());
290                         remove_client(client);
291                 }
292         }
293
294         private void send_to_clients() {
295                 for (Messenger client : clients)
296                         send_to_client(client);
297         }
298
299         private void disconnect(boolean notify) {
300                 AltosDebug.debug("disconnect(): begin");
301
302                 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
303                 telemetry_state.address = null;
304
305                 if (altos_link != null)
306                         altos_link.closing();
307
308                 stop_receiver_voltage_timer();
309
310                 if (telemetry_reader != null) {
311                         AltosDebug.debug("disconnect(): stopping TelemetryReader");
312                         telemetry_reader.interrupt();
313                         try {
314                                 telemetry_reader.join();
315                         } catch (InterruptedException e) {
316                         }
317                         telemetry_reader = null;
318                 }
319                 if (telemetry_logger != null) {
320                         AltosDebug.debug("disconnect(): stopping TelemetryLogger");
321                         telemetry_logger.stop();
322                         telemetry_logger = null;
323                 }
324                 if (altos_link != null) {
325                         AltosDebug.debug("disconnect(): stopping AltosDroidLink");
326                         altos_link.close();
327                         altos_link = null;
328                 }
329                 telemetry_state.config = null;
330                 if (notify) {
331                         AltosDebug.debug("disconnect(): send message to clients");
332                         send_to_clients();
333                         if (clients.isEmpty()) {
334                                 AltosDebug.debug("disconnect(): no clients, terminating");
335                                 stopSelf();
336                         }
337                 }
338         }
339
340         private void start_usb(UsbDevice device) {
341                 AltosUsb        d = new AltosUsb(this, device, handler);
342
343                 if (d != null) {
344                         disconnect(false);
345                         altos_link = d;
346                         try {
347                                 connected();
348                         } catch (InterruptedException ie) {
349                         }
350                 }
351         }
352
353         private void delete_serial(int serial) {
354                 telemetry_state.states.remove((Integer) serial);
355                 AltosPreferences.remove_state(serial);
356                 send_to_clients();
357         }
358
359         private void start_altos_bluetooth(DeviceAddress address, boolean pause) {
360                 if (bluetooth_adapter == null || !bluetooth_adapter.isEnabled())
361                         return;
362
363                 disconnect(false);
364
365                 // Get the BluetoothDevice object
366                 BluetoothDevice device = bluetooth_adapter.getRemoteDevice(address.address);
367
368                 this.address = address;
369                 AltosDebug.debug("start_altos_bluetooth(): Connecting to %s (%s)", device.getName(), device.getAddress());
370                 altos_link = new AltosBluetooth(device, handler, pause);
371                 telemetry_state.connect = TelemetryState.CONNECT_CONNECTING;
372                 telemetry_state.address = address;
373                 send_to_clients();
374         }
375
376         // Timer for receiver battery voltage monitoring
377         Timer receiver_voltage_timer;
378
379         private void update_receiver_voltage() {
380                 if (altos_link != null) {
381                         try {
382                                 double  voltage = altos_link.monitor_battery();
383                                 telemetry_state.receiver_battery = voltage;
384                         } catch (InterruptedException ie) {
385                         }
386                 }
387         }
388
389         private void stop_receiver_voltage_timer() {
390                 if (receiver_voltage_timer != null) {
391                         receiver_voltage_timer.cancel();
392                         receiver_voltage_timer.purge();
393                         receiver_voltage_timer = null;
394                 }
395         }
396
397         private void start_receiver_voltage_timer() {
398                 if (receiver_voltage_timer == null && altos_link.has_monitor_battery()) {
399                         receiver_voltage_timer = new Timer();
400                         receiver_voltage_timer.scheduleAtFixedRate(new TimerTask() { public void run() {update_receiver_voltage();}}, 1000L, 10000L);
401                 }
402         }
403
404         private void connected() throws InterruptedException {
405                 AltosDebug.debug("connected top");
406                 AltosDebug.check_ui("connected\n");
407                 try {
408                         if (altos_link == null)
409                                 throw new InterruptedException("no bluetooth");
410                         telemetry_state.config = altos_link.config_data();
411                         altos_link.set_radio_frequency(telemetry_state.frequency);
412                         altos_link.set_telemetry_rate(telemetry_state.telemetry_rate);
413                 } catch (TimeoutException e) {
414                         // If this timed out, then we really want to retry it, but
415                         // probably safer to just retry the connection from scratch.
416                         AltosDebug.debug("connected timeout");
417                         if (address != null) {
418                                 AltosDebug.debug("connected timeout, retrying");
419                                 start_altos_bluetooth(address, true);
420                         } else {
421                                 handler.obtainMessage(MSG_CONNECT_FAILED).sendToTarget();
422                                 disconnect(true);
423                         }
424                         return;
425                 }
426
427                 AltosDebug.debug("connected bluetooth configured");
428                 telemetry_state.connect = TelemetryState.CONNECT_CONNECTED;
429                 telemetry_state.address = address;
430
431                 telemetry_reader = new TelemetryReader(altos_link, handler);
432                 telemetry_reader.start();
433
434                 AltosDebug.debug("connected TelemetryReader started");
435
436                 telemetry_logger = new TelemetryLogger(this, altos_link);
437
438                 start_receiver_voltage_timer();
439
440                 AltosDebug.debug("Notify UI of connection");
441
442                 send_to_clients();
443         }
444
445
446         @Override
447         public void onCreate() {
448
449                 AltosDebug.init(this);
450
451                 // Initialise preferences
452                 AltosDroidPreferences.init(this);
453
454                 // Get local Bluetooth adapter
455                 bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
456
457                 telemetry_state = new TelemetryState();
458
459                 // Create a reference to the NotificationManager so that we can update our notifcation text later
460                 //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
461
462                 telemetry_state.connect = TelemetryState.CONNECT_DISCONNECTED;
463                 telemetry_state.address = null;
464
465                 /* Pull the saved state information out of the preferences database
466                  */
467                 ArrayList<Integer> serials = AltosPreferences.list_states();
468
469                 telemetry_state.latest_serial = AltosPreferences.latest_state();
470
471                 for (int serial : serials) {
472                         AltosSavedState saved_state = AltosPreferences.state(serial);
473                         if (saved_state != null) {
474                                 if (serial == 0) {
475                                         serial = saved_state.state.serial;
476                                         AltosPreferences.set_state(serial, saved_state.state, saved_state.listener_state);
477                                         AltosPreferences.remove_state(0);
478                                 }
479                                 if (telemetry_state.latest_serial == 0)
480                                         telemetry_state.latest_serial = serial;
481
482                                 AltosDebug.debug("recovered old state serial %d flight %d\n",
483                                                  serial,
484                                                  saved_state.state.flight);
485                                 if (saved_state.state.gps != null)
486                                         AltosDebug.debug("\tposition %f,%f\n",
487                                                          saved_state.state.gps.lat,
488                                                          saved_state.state.gps.lon);
489                                 telemetry_state.states.put(serial, saved_state.state);
490                         }
491                 }
492         }
493
494         @Override
495         public int onStartCommand(Intent intent, int flags, int startId) {
496                 AltosDebug.debug("Received start id %d: %s", startId, intent);
497
498                 CharSequence text = getText(R.string.telemetry_service_started);
499
500                 // Create notification to be displayed while the service runs
501                 Notification notification = new Notification(R.drawable.am_status_c, text, 0);
502
503                 // The PendingIntent to launch our activity if the user selects this notification
504                 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
505                                 new Intent(this, AltosDroid.class), 0);
506
507                 // Set the info for the views that show in the notification panel.
508                 notification.setLatestEventInfo(this, getText(R.string.telemetry_service_label), text, contentIntent);
509
510                 // Set the notification to be in the "Ongoing" section.
511                 notification.flags |= Notification.FLAG_ONGOING_EVENT;
512
513                 // Move us into the foreground.
514                 startForeground(NOTIFICATION, notification);
515
516                 /* Start bluetooth if we don't have a connection already */
517                 if (intent != null &&
518                     (telemetry_state.connect == TelemetryState.CONNECT_NONE ||
519                      telemetry_state.connect == TelemetryState.CONNECT_DISCONNECTED))
520                 {
521                         String  action = intent.getAction();
522
523                         if (action.equals(AltosDroid.ACTION_BLUETOOTH)) {
524                                 DeviceAddress address = AltosDroidPreferences.active_device();
525                                 if (address != null && !address.address.startsWith("USB"))
526                                         start_altos_bluetooth(address, false);
527                         }
528                 }
529
530                 // We want this service to continue running until it is explicitly
531                 // stopped, so return sticky.
532                 return START_STICKY;
533         }
534
535         @Override
536         public void onDestroy() {
537
538                 // Stop the bluetooth Comms threads
539                 disconnect(true);
540
541                 // Demote us from the foreground, and cancel the persistent notification.
542                 stopForeground(true);
543
544                 // Tell the user we stopped.
545                 Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show();
546         }
547
548         @Override
549         public IBinder onBind(Intent intent) {
550                 return messenger.getBinder();
551         }
552 }