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