Bump java lib versions to 13
[fw/altos] / altosdroid / src / org / altusmetrum / AltosDroid / AltosDroid.java
1 /*
2  * Copyright © 2012-2013 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; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
17  */
18
19 package org.altusmetrum.AltosDroid;
20
21 import java.lang.ref.WeakReference;
22 import java.text.*;
23 import java.util.*;
24 import java.io.*;
25
26 import android.app.Activity;
27 import android.app.PendingIntent;
28 import android.bluetooth.BluetoothAdapter;
29 import android.bluetooth.BluetoothDevice;
30 import android.content.Intent;
31 import android.content.Context;
32 import android.content.ComponentName;
33 import android.content.ServiceConnection;
34 import android.content.DialogInterface;
35 import android.os.IBinder;
36 import android.os.Bundle;
37 import android.os.Handler;
38 import android.os.Message;
39 import android.os.Messenger;
40 import android.os.RemoteException;
41 import android.content.res.Resources;
42 import android.support.v4.app.FragmentActivity;
43 import android.support.v4.app.FragmentManager;
44 import android.util.DisplayMetrics;
45 import android.view.*;
46 import android.widget.*;
47 import android.app.AlertDialog;
48 import android.location.Location;
49 import android.location.LocationManager;
50 import android.location.LocationListener;
51 import android.hardware.usb.*;
52 import android.graphics.*;
53 import android.graphics.drawable.*;
54
55 import org.altusmetrum.altoslib_13.*;
56
57 class SavedState {
58         long    received_time;
59         int     state;
60         boolean locked;
61         String  callsign;
62         int     serial;
63         int     flight;
64         int     rssi;
65
66         SavedState(AltosState state) {
67                 received_time = state.received_time;
68                 this.state = state.state();
69                 if (state.gps != null)
70                         locked = state.gps.locked;
71                 else
72                         locked = false;
73                 callsign = state.cal_data().callsign;
74                 serial = state.cal_data().serial;
75                 flight = state.cal_data().flight;
76                 rssi = state.rssi;
77         }
78 }
79
80 class Tracker implements CharSequence, Comparable {
81         int     serial;
82         String  call;
83         double  frequency;
84
85         String  display;
86
87         public Tracker(int serial, String call, double frequency) {
88                 if (call == null)
89                         call = "none";
90
91                 this.serial = serial;
92                 this.call = call;
93                 this.frequency = frequency;
94                 if (frequency == 0.0)
95                         display = "Auto";
96                 else if (frequency == AltosLib.MISSING) {
97                         display = String.format("%-8.8s  %6d", call, serial);
98                 } else {
99                         display = String.format("%-8.8s %7.3f %6d", call, frequency, serial);
100                 }
101         }
102
103         public Tracker(AltosState s) {
104                 this(s == null ? 0 : s.cal_data().serial,
105                      s == null ? null : s.cal_data().callsign,
106                      s == null ? 0.0 : s.frequency);
107         }
108
109         /* CharSequence */
110         public char charAt(int index) {
111                 return display.charAt(index);
112         }
113
114         public int length() {
115                 return display.length();
116         }
117
118         public CharSequence subSequence(int start, int end) throws IndexOutOfBoundsException {
119                 return display.subSequence(start, end);
120         }
121
122         public String toString() {
123                 return display.toString();
124         }
125
126         /* Comparable */
127         public int compareTo (Object other) {
128                 Tracker o = (Tracker) other;
129                 if (frequency == 0.0) {
130                         if (o.frequency == 0.0)
131                                 return 0;
132                         return -1;
133                 }
134                 if (o.frequency == 0.0)
135                         return 1;
136
137                 int     a = serial - o.serial;
138                 int     b = call.compareTo(o.call);
139                 int     c = (int) Math.signum(frequency - o.frequency);
140
141                 if (b != 0)
142                         return b;
143                 if (c != 0)
144                         return c;
145                 return a;
146         }
147 }
148
149 public class AltosDroid extends FragmentActivity implements AltosUnitsListener, LocationListener {
150
151         // Actions sent to the telemetry server at startup time
152
153         public static final String ACTION_BLUETOOTH = "org.altusmetrum.AltosDroid.BLUETOOTH";
154         public static final String ACTION_USB = "org.altusmetrum.AltosDroid.USB";
155
156         // Message types received by our Handler
157
158         public static final int MSG_STATE           = 1;
159         public static final int MSG_UPDATE_AGE      = 2;
160         public static final int MSG_IDLE_MODE       = 3;
161         public static final int MSG_IGNITER_STATUS  = 4;
162
163         // Intent request codes
164         public static final int REQUEST_CONNECT_DEVICE = 1;
165         public static final int REQUEST_ENABLE_BT      = 2;
166         public static final int REQUEST_PRELOAD_MAPS   = 3;
167         public static final int REQUEST_IDLE_MODE      = 5;
168         public static final int REQUEST_IGNITERS       = 6;
169         public static final int REQUEST_SETUP          = 7;
170
171         public static final String EXTRA_IDLE_MODE = "idle_mode";
172         public static final String EXTRA_IDLE_RESULT = "idle_result";
173         public static final String EXTRA_TELEMETRY_SERVICE = "telemetry_service";
174
175         // Setup result bits
176         public static final int SETUP_BAUD = 1;
177         public static final int SETUP_UNITS = 2;
178         public static final int SETUP_MAP_SOURCE = 4;
179         public static final int SETUP_MAP_TYPE = 8;
180
181         public static FragmentManager   fm;
182
183         private BluetoothAdapter mBluetoothAdapter = null;
184
185         // Flight state values
186         private TextView mCallsignView;
187         private TextView mRSSIView;
188         private TextView mSerialView;
189         private TextView mFlightView;
190         private RelativeLayout mStateLayout;
191         private TextView mStateView;
192         private TextView mAgeView;
193         private boolean  mAgeViewOld;
194         private int mAgeNewColor;
195         private int mAgeOldColor;
196
197         public static final String      tab_pad_name = "pad";
198         public static final String      tab_flight_name = "flight";
199         public static final String      tab_recover_name = "recover";
200         public static final String      tab_map_name = "map";
201
202         // field to display the version at the bottom of the screen
203         private TextView mVersion;
204
205         private boolean idle_mode = false;
206
207         public Location location = null;
208
209         private AltosState      state;
210         private SavedState      saved_state;
211
212         // Tabs
213         TabHost         mTabHost;
214         AltosViewPager  mViewPager;
215         TabsAdapter     mTabsAdapter;
216         ArrayList<AltosDroidTab> mTabs = new ArrayList<AltosDroidTab>();
217         int             tabHeight;
218
219         // Timer and Saved flight state for Age calculation
220         private Timer timer;
221
222         TelemetryState  telemetry_state;
223         Tracker[]       trackers;
224
225
226         UsbDevice       pending_usb_device;
227         boolean         start_with_usb;
228
229         // Service
230         private boolean mIsBound   = false;
231         private Messenger mService = null;
232         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
233
234         // Text to Speech
235         private AltosVoice mAltosVoice = null;
236
237         // The Handler that gets information back from the Telemetry Service
238         static class IncomingHandler extends Handler {
239                 private final WeakReference<AltosDroid> mAltosDroid;
240                 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
241
242                 @Override
243                 public void handleMessage(Message msg) {
244                         AltosDroid ad = mAltosDroid.get();
245
246                         switch (msg.what) {
247                         case MSG_STATE:
248                                 if (msg.obj == null) {
249                                         AltosDebug.debug("telemetry_state null!");
250                                         return;
251                                 }
252                                 ad.update_state((TelemetryState) msg.obj);
253                                 break;
254                         case MSG_UPDATE_AGE:
255                                 ad.update_age();
256                                 break;
257                         case MSG_IDLE_MODE:
258                                 ad.idle_mode = (Boolean) msg.obj;
259                                 ad.update_state(null);
260                                 break;
261                         }
262                 }
263         };
264
265
266         private ServiceConnection mConnection = new ServiceConnection() {
267                 public void onServiceConnected(ComponentName className, IBinder service) {
268                         mService = new Messenger(service);
269                         try {
270                                 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
271                                 msg.replyTo = mMessenger;
272                                 mService.send(msg);
273                         } catch (RemoteException e) {
274                                 // In this case the service has crashed before we could even do anything with it
275                         }
276                         if (pending_usb_device != null) {
277                                 try {
278                                         mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, pending_usb_device));
279                                         pending_usb_device = null;
280                                 } catch (RemoteException e) {
281                                 }
282                         }
283                 }
284
285                 public void onServiceDisconnected(ComponentName className) {
286                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
287                         mService = null;
288                 }
289         };
290
291         void doBindService() {
292                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
293                 mIsBound = true;
294         }
295
296         void doUnbindService() {
297                 if (mIsBound) {
298                         // If we have received the service, and hence registered with it, then now is the time to unregister.
299                         if (mService != null) {
300                                 try {
301                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
302                                         msg.replyTo = mMessenger;
303                                         mService.send(msg);
304                                 } catch (RemoteException e) {
305                                         // There is nothing special we need to do if the service has crashed.
306                                 }
307                         }
308                         // Detach our existing connection.
309                         unbindService(mConnection);
310                         mIsBound = false;
311                 }
312         }
313
314         public void registerTab(AltosDroidTab mTab) {
315                 mTabs.add(mTab);
316         }
317
318         public void unregisterTab(AltosDroidTab mTab) {
319                 mTabs.remove(mTab);
320         }
321
322         public void units_changed(boolean imperial_units) {
323                 for (AltosDroidTab mTab : mTabs)
324                         mTab.units_changed(imperial_units);
325         }
326
327         void update_title(TelemetryState telemetry_state) {
328                 switch (telemetry_state.connect) {
329                 case TelemetryState.CONNECT_CONNECTED:
330                         if (telemetry_state.config != null) {
331                                 String str = String.format("S/N %d %6.3f MHz%s", telemetry_state.config.serial,
332                                                            telemetry_state.frequency, idle_mode ? " (idle)" : "");
333                                 if (telemetry_state.telemetry_rate != AltosLib.ao_telemetry_rate_38400)
334                                         str = str.concat(String.format(" %d bps",
335                                                                        AltosLib.ao_telemetry_rate_values[telemetry_state.telemetry_rate]));
336                                 setTitle(str);
337                         } else {
338                                 setTitle(R.string.title_connected_to);
339                         }
340                         break;
341                 case TelemetryState.CONNECT_CONNECTING:
342                         if (telemetry_state.address != null)
343                                 setTitle(String.format("Connecting to %s...", telemetry_state.address.name));
344                         else
345                                 setTitle("Connecting to something...");
346                         break;
347                 case TelemetryState.CONNECT_DISCONNECTED:
348                 case TelemetryState.CONNECT_NONE:
349                         setTitle(R.string.title_not_connected);
350                         break;
351                 }
352         }
353
354         void start_timer() {
355                 if (timer == null) {
356                         timer = new Timer();
357                         timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 1000L, 1000L);
358                 }
359         }
360
361         void stop_timer() {
362                 if (timer != null) {
363                         timer.cancel();
364                         timer.purge();
365                         timer = null;
366                 }
367         }
368
369         int     selected_serial = 0;
370         int     current_serial;
371         long    switch_time;
372
373         void set_switch_time() {
374                 switch_time = System.currentTimeMillis();
375                 selected_serial = 0;
376         }
377
378         boolean registered_units_listener;
379
380         void update_state(TelemetryState new_telemetry_state) {
381
382                 if (new_telemetry_state != null)
383                         telemetry_state = new_telemetry_state;
384
385                 if (selected_serial != 0)
386                         current_serial = selected_serial;
387
388                 if (current_serial == 0)
389                         current_serial = telemetry_state.latest_serial;
390
391                 if (!registered_units_listener) {
392                         registered_units_listener = true;
393                         AltosPreferences.register_units_listener(this);
394                 }
395
396                 int     num_trackers = 0;
397                 for (AltosState s : telemetry_state.states.values()) {
398                         num_trackers++;
399                 }
400
401                 trackers = new Tracker[num_trackers + 1];
402
403                 int n = 0;
404                 trackers[n++] = new Tracker(0, "auto", 0.0);
405
406                 for (AltosState s : telemetry_state.states.values())
407                         trackers[n++] = new Tracker(s);
408
409                 Arrays.sort(trackers);
410
411                 update_title(telemetry_state);
412
413                 AltosState      state = null;
414                 boolean         aged = true;
415
416                 if (telemetry_state.states.containsKey(current_serial)) {
417                         state = telemetry_state.states.get(current_serial);
418                         int age = state_age(state.received_time);
419                         if (age < 20)
420                                 aged = false;
421                         if (current_serial == selected_serial)
422                                 aged = false;
423                         else if (switch_time != 0 && (switch_time - state.received_time) > 0)
424                                 aged = true;
425                 }
426
427                 if (aged) {
428                         AltosState      newest_state = null;
429                         int             newest_age = 0;
430
431                         for (int serial : telemetry_state.states.keySet()) {
432                                 AltosState      existing = telemetry_state.states.get(serial);
433                                 int             existing_age = state_age(existing.received_time);
434
435                                 if (newest_state == null || existing_age < newest_age) {
436                                         newest_state = existing;
437                                         newest_age = existing_age;
438                                 }
439                         }
440
441                         if (newest_state != null)
442                                 state = newest_state;
443                 }
444
445                 update_ui(telemetry_state, state, telemetry_state.quiet);
446
447                 start_timer();
448         }
449
450         boolean same_string(String a, String b) {
451                 if (a == null) {
452                         if (b == null)
453                                 return true;
454                         return false;
455                 } else {
456                         if (b == null)
457                                 return false;
458                         return a.equals(b);
459                 }
460         }
461
462
463         private int blend_component(int a, int b, double r, int shift, int mask) {
464                 return ((int) (((a >> shift) & mask) * r + ((b >> shift) & mask) * (1 - r)) & mask) << shift;
465         }
466         private int blend_color(int a, int b, double r) {
467                 return (blend_component(a, b, r, 0, 0xff) |
468                         blend_component(a, b, r, 8, 0xff) |
469                         blend_component(a, b, r, 16, 0xff) |
470                         blend_component(a, b, r, 24, 0xff));
471         }
472
473         int state_age(long received_time) {
474                 return (int) ((System.currentTimeMillis() - received_time + 500) / 1000);
475         }
476
477         void set_screen_on(int age) {
478                 if (age < 60)
479                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
480                 else
481                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
482         }
483
484         void update_age() {
485                 if (saved_state != null) {
486                         int age = state_age(saved_state.received_time);
487
488                         double age_scale = age / 100.0;
489
490                         if (age_scale > 1.0)
491                                 age_scale = 1.0;
492
493                         mAgeView.setTextColor(blend_color(mAgeOldColor, mAgeNewColor, age_scale));
494
495                         set_screen_on(age);
496
497                         String  text;
498                         if (age < 60)
499                                 text = String.format("%ds", age);
500                         else if (age < 60 * 60)
501                                 text = String.format("%dm", age / 60);
502                         else if (age < 60 * 60 * 24)
503                                 text = String.format("%dh", age / (60 * 60));
504                         else
505                                 text = String.format("%dd", age / (24 * 60 * 60));
506                         mAgeView.setText(text);
507                 }
508         }
509
510         void update_ui(TelemetryState telem_state, AltosState state, boolean quiet) {
511
512                 this.state = state;
513
514                 int prev_state = AltosLib.ao_flight_invalid;
515
516                 AltosGreatCircle from_receiver = null;
517
518                 if (saved_state != null)
519                         prev_state = saved_state.state;
520
521                 if (state != null) {
522                         set_screen_on(state_age(state.received_time));
523
524                         if (state.state() == AltosLib.ao_flight_stateless) {
525                                 boolean prev_locked = false;
526                                 boolean locked = false;
527
528                                 if(state.gps != null)
529                                         locked = state.gps.locked;
530                                 if (saved_state != null)
531                                         prev_locked = saved_state.locked;
532                                 if (prev_locked != locked) {
533                                         String currentTab = mTabHost.getCurrentTabTag();
534                                         if (locked) {
535                                                 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
536                                         } else {
537                                                 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_pad_name);
538                                         }
539                                 }
540                         } else {
541                                 if (prev_state != state.state()) {
542                                         String currentTab = mTabHost.getCurrentTabTag();
543                                         switch (state.state()) {
544                                         case AltosLib.ao_flight_boost:
545                                                 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
546                                                 break;
547                                         case AltosLib.ao_flight_landed:
548                                                 if (currentTab.equals(tab_flight_name)) mTabHost.setCurrentTabByTag(tab_recover_name);
549                                                 break;
550                                         case AltosLib.ao_flight_stateless:
551                                                 if (currentTab.equals(tab_pad_name)) mTabHost.setCurrentTabByTag(tab_flight_name);
552                                                 break;
553                                         }
554                                 }
555                         }
556
557                         if (location != null && state.gps != null && state.gps.locked) {
558                                 double altitude = 0;
559                                 if (location.hasAltitude())
560                                         altitude = location.getAltitude();
561                                 from_receiver = new AltosGreatCircle(location.getLatitude(),
562                                                                      location.getLongitude(),
563                                                                      altitude,
564                                                                      state.gps.lat,
565                                                                      state.gps.lon,
566                                                                      state.gps.alt);
567                         }
568
569                         if (saved_state == null || !same_string(saved_state.callsign, state.cal_data().callsign)) {
570                                 mCallsignView.setText(state.cal_data().callsign);
571                         }
572                         if (saved_state == null || state.cal_data().serial != saved_state.serial) {
573                                 if (state.cal_data().serial == AltosLib.MISSING)
574                                         mSerialView.setText("");
575                                 else
576                                         mSerialView.setText(String.format("%d", state.cal_data().serial));
577                         }
578                         if (saved_state == null || state.cal_data().flight != saved_state.flight) {
579                                 if (state.cal_data().flight == AltosLib.MISSING)
580                                         mFlightView.setText("");
581                                 else
582                                         mFlightView.setText(String.format("%d", state.cal_data().flight));
583                         }
584                         if (saved_state == null || state.state() != saved_state.state) {
585                                 if (state.state() == AltosLib.ao_flight_stateless) {
586                                         mStateLayout.setVisibility(View.GONE);
587                                 } else {
588                                         mStateView.setText(state.state_name());
589                                         mStateLayout.setVisibility(View.VISIBLE);
590                                 }
591                         }
592                         if (saved_state == null || state.rssi != saved_state.rssi) {
593                                 if (state.rssi == AltosLib.MISSING)
594                                         mRSSIView.setText("");
595                                 else
596                                         mRSSIView.setText(String.format("%d", state.rssi));
597                         }
598                         saved_state = new SavedState(state);
599                 }
600
601                 for (AltosDroidTab mTab : mTabs)
602                         mTab.update_ui(telem_state, state, from_receiver, location, mTab == mTabsAdapter.currentItem());
603
604                 AltosDebug.debug("quiet %b\n", quiet);
605                 if (mAltosVoice != null)
606                         mAltosVoice.tell(telem_state, state, from_receiver, location, (AltosDroidTab) mTabsAdapter.currentItem(), quiet);
607
608         }
609
610         private void onTimerTick() {
611                 try {
612                         mMessenger.send(Message.obtain(null, MSG_UPDATE_AGE));
613                 } catch (RemoteException e) {
614                 }
615         }
616
617         static String pos(double p, String pos, String neg) {
618                 String  h = pos;
619                 if (p == AltosLib.MISSING)
620                         return "";
621                 if (p < 0) {
622                         h = neg;
623                         p = -p;
624                 }
625                 int deg = (int) Math.floor(p);
626                 double min = (p - Math.floor(p)) * 60.0;
627                 return String.format("%d°%9.4f\" %s", deg, min, h);
628         }
629
630         static String number(String format, double value) {
631                 if (value == AltosLib.MISSING)
632                         return "";
633                 return String.format(format, value);
634         }
635
636         static String integer(String format, int value) {
637                 if (value == AltosLib.MISSING)
638                         return "";
639                 return String.format(format, value);
640         }
641
642         private View create_tab_view(String label) {
643                 LayoutInflater inflater = (LayoutInflater) this.getLayoutInflater();
644                 View tab_view = inflater.inflate(R.layout.tab_layout, null);
645                 TextView text_view = (TextView) tab_view.findViewById (R.id.tabLabel);
646                 text_view.setText(label);
647                 return tab_view;
648         }
649
650         @Override
651         public void onCreate(Bundle savedInstanceState) {
652                 super.onCreate(savedInstanceState);
653                 AltosDebug.init(this);
654                 AltosDebug.debug("+++ ON CREATE +++");
655
656                 // Initialise preferences
657                 AltosDroidPreferences.init(this);
658
659                 fm = getSupportFragmentManager();
660
661                 // Set up the window layout
662                 setContentView(R.layout.altosdroid);
663
664                 // Create the Tabs and ViewPager
665                 mTabHost = (TabHost)findViewById(android.R.id.tabhost);
666                 mTabHost.setup();
667
668                 mViewPager = (AltosViewPager)findViewById(R.id.pager);
669                 mViewPager.setOffscreenPageLimit(4);
670
671                 mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
672
673                 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_pad_name).setIndicator(create_tab_view("Pad")), TabPad.class, null);
674                 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_flight_name).setIndicator(create_tab_view("Flight")), TabFlight.class, null);
675                 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_recover_name).setIndicator(create_tab_view("Recover")), TabRecover.class, null);
676                 mTabsAdapter.addTab(mTabHost.newTabSpec(tab_map_name).setIndicator(create_tab_view("Map")), TabMap.class, null);
677
678                 // Display the Version
679                 mVersion = (TextView) findViewById(R.id.version);
680                 mVersion.setText("Version: " + BuildInfo.version +
681                                  (AltosVersion.has_google_maps_api_key() ? " maps" : "") +
682                                  " Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
683                                  " (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
684
685                 mCallsignView  = (TextView) findViewById(R.id.callsign_value);
686                 mRSSIView      = (TextView) findViewById(R.id.rssi_value);
687                 mSerialView    = (TextView) findViewById(R.id.serial_value);
688                 mFlightView    = (TextView) findViewById(R.id.flight_value);
689                 mStateLayout   = (RelativeLayout) findViewById(R.id.state_container);
690                 mStateView     = (TextView) findViewById(R.id.state_value);
691                 mAgeView       = (TextView) findViewById(R.id.age_value);
692                 mAgeNewColor   = mAgeView.getTextColors().getDefaultColor();
693                 mAgeOldColor   = getResources().getColor(R.color.old_color);
694         }
695
696         private void ensureBluetooth() {
697                 // Get local Bluetooth adapter
698                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
699
700                 /* if there is a BT adapter and it isn't turned on, then turn it on */
701                 if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
702                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
703                         startActivityForResult(enableIntent, AltosDroid.REQUEST_ENABLE_BT);
704                 }
705         }
706
707         private boolean check_usb() {
708                 UsbDevice       device = AltosUsb.find_device(this, AltosLib.product_basestation);
709
710                 if (device != null) {
711                         Intent          i = new Intent(this, AltosDroid.class);
712                         PendingIntent   pi = PendingIntent.getActivity(this, 0, new Intent("hello world", null, this, AltosDroid.class), 0);
713
714                         if (AltosUsb.request_permission(this, device, pi)) {
715                                 connectUsb(device);
716                         }
717                         start_with_usb = true;
718                         return true;
719                 }
720
721                 start_with_usb = false;
722
723                 return false;
724         }
725
726         private void noticeIntent(Intent intent) {
727
728                 /* Ok, this is pretty convenient.
729                  *
730                  * When a USB device is plugged in, and our 'hotplug'
731                  * intent registration fires, we get an Intent with
732                  * EXTRA_DEVICE set.
733                  *
734                  * When we start up and see a usb device and request
735                  * permission to access it, that queues a
736                  * PendingIntent, which has the EXTRA_DEVICE added in,
737                  * along with the EXTRA_PERMISSION_GRANTED field as
738                  * well.
739                  *
740                  * So, in both cases, we get the device name using the
741                  * same call. We check to see if access was granted,
742                  * in which case we ignore the device field and do our
743                  * usual startup thing.
744                  */
745
746                 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
747                 boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
748
749                 AltosDebug.debug("intent %s device %s granted %s", intent, device, granted);
750
751                 if (!granted)
752                         device = null;
753
754                 if (device != null) {
755                         AltosDebug.debug("intent has usb device " + device.toString());
756                         connectUsb(device);
757                 } else {
758
759                         /* 'granted' is only false if this intent came
760                          * from the request_permission call and
761                          * permission was denied. In which case, we
762                          * don't want to loop forever...
763                          */
764                         if (granted) {
765                                 AltosDebug.debug("check for a USB device at startup");
766                                 if (check_usb())
767                                         return;
768                         }
769                         AltosDebug.debug("Starting by looking for bluetooth devices");
770                         ensureBluetooth();
771                 }
772         }
773
774         @Override
775         public void onStart() {
776                 super.onStart();
777                 AltosDebug.debug("++ ON START ++");
778
779                 set_switch_time();
780
781                 noticeIntent(getIntent());
782
783                 // Start Telemetry Service
784                 String  action = start_with_usb ? ACTION_USB : ACTION_BLUETOOTH;
785
786                 startService(new Intent(action, null, AltosDroid.this, TelemetryService.class));
787
788                 doBindService();
789
790                 if (mAltosVoice == null)
791                         mAltosVoice = new AltosVoice(this);
792
793         }
794
795         @Override
796         public void onNewIntent(Intent intent) {
797                 super.onNewIntent(intent);
798                 AltosDebug.debug("onNewIntent");
799                 noticeIntent(intent);
800         }
801
802         @Override
803         public void onResume() {
804                 super.onResume();
805                 AltosDebug.debug("+ ON RESUME +");
806
807                 // Listen for GPS and Network position updates
808                 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
809                 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
810
811                 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
812
813                 if (location != null)
814                         AltosDebug.debug("Resume, location is %f,%f\n",
815                                          location.getLatitude(),
816                                          location.getLongitude());
817
818                 update_ui(telemetry_state, state, true);
819         }
820
821         @Override
822         public void onPause() {
823                 super.onPause();
824                 AltosDebug.debug("- ON PAUSE -");
825                 // Stop listening for location updates
826                 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
827         }
828
829         @Override
830         public void onStop() {
831                 super.onStop();
832                 AltosDebug.debug("-- ON STOP --");
833         }
834
835         @Override
836         public void onDestroy() {
837                 super.onDestroy();
838                 AltosDebug.debug("--- ON DESTROY ---");
839
840                 doUnbindService();
841                 if (mAltosVoice != null) {
842                         mAltosVoice.stop();
843                         mAltosVoice = null;
844                 }
845                 stop_timer();
846         }
847
848         protected void onActivityResult(int requestCode, int resultCode, Intent data) {
849                 AltosDebug.debug("onActivityResult " + resultCode);
850                 switch (requestCode) {
851                 case REQUEST_CONNECT_DEVICE:
852                         // When DeviceListActivity returns with a device to connect to
853                         if (resultCode == Activity.RESULT_OK) {
854                                 connectDevice(data);
855                         }
856                         break;
857                 case REQUEST_ENABLE_BT:
858                         // When the request to enable Bluetooth returns
859                         if (resultCode == Activity.RESULT_OK) {
860                                 // Bluetooth is now enabled, so set up a chat session
861                                 //setupChat();
862                                 AltosDebug.debug("BT enabled");
863                                 bluetoothEnabled(data);
864                         } else {
865                                 // User did not enable Bluetooth or an error occured
866                                 AltosDebug.debug("BT not enabled");
867                         }
868                         break;
869                 case REQUEST_IDLE_MODE:
870                         if (resultCode == Activity.RESULT_OK)
871                                 idle_mode(data);
872                         break;
873                 case REQUEST_IGNITERS:
874                         break;
875                 case REQUEST_SETUP:
876                         if (resultCode == Activity.RESULT_OK)
877                                 note_setup_changes(data);
878                         break;
879                 }
880         }
881
882         private void note_setup_changes(Intent data) {
883                 int changes = data.getIntExtra(SetupActivity.EXTRA_SETUP_CHANGES, 0);
884
885                 if ((changes & SETUP_BAUD) != 0) {
886                         try {
887                                 mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD,
888                                                              AltosPreferences.telemetry_rate(1)));
889                         } catch (RemoteException re) {
890                         }
891                 }
892                 if ((changes & SETUP_UNITS) != 0) {
893                         /* nothing to do here */
894                 }
895                 if ((changes & SETUP_MAP_SOURCE) != 0) {
896                         /* nothing to do here */
897                 }
898                 if ((changes & SETUP_MAP_TYPE) != 0) {
899                         /* nothing to do here */
900                 }
901                 set_switch_time();
902         }
903
904         private void connectUsb(UsbDevice device) {
905                 if (mService == null)
906                         pending_usb_device = device;
907                 else {
908                         // Attempt to connect to the device
909                         try {
910                                 mService.send(Message.obtain(null, TelemetryService.MSG_OPEN_USB, device));
911                                 AltosDebug.debug("Sent OPEN_USB message");
912                         } catch (RemoteException e) {
913                                 AltosDebug.debug("connect device message failed");
914                         }
915                 }
916         }
917
918         private void bluetoothEnabled(Intent data) {
919                 try {
920                         mService.send(Message.obtain(null, TelemetryService.MSG_BLUETOOTH_ENABLED, null));
921                 } catch (RemoteException e) {
922                         AltosDebug.debug("send BT enabled message failed");
923                 }
924         }
925
926         private void connectDevice(Intent data) {
927                 // Attempt to connect to the device
928                 try {
929                         String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
930                         String name = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
931
932                         AltosDebug.debug("Connecting to " + address + " " + name);
933                         DeviceAddress   a = new DeviceAddress(address, name);
934                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, a));
935                         AltosDebug.debug("Sent connecting message");
936                 } catch (RemoteException e) {
937                         AltosDebug.debug("connect device message failed");
938                 }
939         }
940
941         private void disconnectDevice(boolean remember) {
942                 try {
943                         mService.send(Message.obtain(null, TelemetryService.MSG_DISCONNECT, (Boolean) remember));
944                 } catch (RemoteException e) {
945                 }
946         }
947
948         private void idle_mode(Intent data) {
949                 int type = data.getIntExtra(IdleModeActivity.EXTRA_IDLE_RESULT, -1);
950                 Message msg;
951
952                 AltosDebug.debug("intent idle_mode %d", type);
953                 switch (type) {
954                 case IdleModeActivity.IDLE_MODE_CONNECT:
955                         msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_START);
956                         try {
957                                 mService.send(msg);
958                         } catch (RemoteException re) {
959                         }
960                         break;
961                 case IdleModeActivity.IDLE_MODE_DISCONNECT:
962                         msg = Message.obtain(null, TelemetryService.MSG_MONITOR_IDLE_STOP);
963                         try {
964                                 mService.send(msg);
965                         } catch (RemoteException re) {
966                         }
967                         break;
968                 case IdleModeActivity.IDLE_MODE_REBOOT:
969                         msg = Message.obtain(null, TelemetryService.MSG_REBOOT);
970                         try {
971                                 mService.send(msg);
972                         } catch (RemoteException re) {
973                         }
974                         break;
975                 case IdleModeActivity.IDLE_MODE_IGNITERS:
976                         Intent serverIntent = new Intent(this, IgniterActivity.class);
977                         startActivityForResult(serverIntent, REQUEST_IGNITERS);
978                         break;
979                 }
980         }
981
982         @Override
983         public boolean onCreateOptionsMenu(Menu menu) {
984                 MenuInflater inflater = getMenuInflater();
985                 inflater.inflate(R.menu.option_menu, menu);
986                 return true;
987         }
988
989         void setFrequency(double freq) {
990                 try {
991                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
992                         set_switch_time();
993                 } catch (RemoteException e) {
994                 }
995         }
996
997         void setFrequency(AltosFrequency frequency) {
998                 setFrequency (frequency.frequency);
999         }
1000
1001         void setBaud(int baud) {
1002                 try {
1003                         mService.send(Message.obtain(null, TelemetryService.MSG_SETBAUD, baud));
1004                         set_switch_time();
1005                 } catch (RemoteException e) {
1006                 }
1007         }
1008
1009         void setBaud(String baud) {
1010                 try {
1011                         int     value = Integer.parseInt(baud);
1012                         int     rate = AltosLib.ao_telemetry_rate_38400;
1013                         switch (value) {
1014                         case 2400:
1015                                 rate = AltosLib.ao_telemetry_rate_2400;
1016                                 break;
1017                         case 9600:
1018                                 rate = AltosLib.ao_telemetry_rate_9600;
1019                                 break;
1020                         case 38400:
1021                                 rate = AltosLib.ao_telemetry_rate_38400;
1022                                 break;
1023                         }
1024                         setBaud(rate);
1025                 } catch (NumberFormatException e) {
1026                 }
1027         }
1028
1029         void select_tracker(int serial) {
1030                 int i;
1031
1032                 AltosDebug.debug("select tracker %d\n", serial);
1033
1034                 if (serial == selected_serial) {
1035                         AltosDebug.debug("%d already selected\n", serial);
1036                         return;
1037                 }
1038
1039                 if (serial != 0) {
1040                         for (i = 0; i < trackers.length; i++)
1041                                 if (trackers[i].serial == serial)
1042                                         break;
1043
1044                         if (i == trackers.length) {
1045                                 AltosDebug.debug("attempt to select unknown tracker %d\n", serial);
1046                                 return;
1047                         }
1048                 }
1049
1050                 current_serial = selected_serial = serial;
1051                 update_state(null);
1052         }
1053
1054         void touch_trackers(Integer[] serials) {
1055                 AlertDialog.Builder builder_tracker = new AlertDialog.Builder(this);
1056                 builder_tracker.setTitle("Select Tracker");
1057
1058                 final Tracker[] my_trackers = new Tracker[serials.length + 1];
1059
1060                 my_trackers[0] = new Tracker(null);
1061
1062                 for (int i = 0; i < serials.length; i++) {
1063                         AltosState      s = telemetry_state.states.get(serials[i]);
1064                         my_trackers[i+1] = new Tracker(s);
1065                 }
1066                 builder_tracker.setItems(my_trackers,
1067                                          new DialogInterface.OnClickListener() {
1068                                                  public void onClick(DialogInterface dialog, int item) {
1069                                                          if (item == 0)
1070                                                                  select_tracker(0);
1071                                                          else
1072                                                                  select_tracker(my_trackers[item].serial);
1073                                                  }
1074                                          });
1075                 AlertDialog alert_tracker = builder_tracker.create();
1076                 alert_tracker.show();
1077         }
1078
1079         void delete_track(int serial) {
1080                 try {
1081                         mService.send(Message.obtain(null, TelemetryService.MSG_DELETE_SERIAL, (Integer) serial));
1082                 } catch (Exception ex) {
1083                 }
1084         }
1085
1086         @Override
1087         public boolean onOptionsItemSelected(MenuItem item) {
1088                 Intent serverIntent = null;
1089                 switch (item.getItemId()) {
1090                 case R.id.connect_scan:
1091                         ensureBluetooth();
1092                         // Launch the DeviceListActivity to see devices and do scan
1093                         serverIntent = new Intent(this, DeviceListActivity.class);
1094                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
1095                         return true;
1096                 case R.id.disconnect:
1097                         /* Disconnect the device
1098                          */
1099                         disconnectDevice(false);
1100                         return true;
1101                 case R.id.quit:
1102                         AltosDebug.debug("R.id.quit");
1103                         disconnectDevice(true);
1104                         finish();
1105                         return true;
1106                 case R.id.setup:
1107                         serverIntent = new Intent(this, SetupActivity.class);
1108                         startActivityForResult(serverIntent, REQUEST_SETUP);
1109                         return true;
1110                 case R.id.select_freq:
1111                         // Set the TBT radio frequency
1112
1113                         final AltosFrequency[] frequencies = AltosPreferences.common_frequencies();
1114                         String[] frequency_strings = new String[frequencies.length];
1115                         for (int i = 0; i < frequencies.length; i++)
1116                                 frequency_strings[i] = frequencies[i].toString();
1117
1118                         AlertDialog.Builder builder_freq = new AlertDialog.Builder(this);
1119                         builder_freq.setTitle("Pick a frequency");
1120                         builder_freq.setItems(frequency_strings,
1121                                          new DialogInterface.OnClickListener() {
1122                                                  public void onClick(DialogInterface dialog, int item) {
1123                                                          setFrequency(frequencies[item]);
1124                                                  }
1125                                          });
1126                         AlertDialog alert_freq = builder_freq.create();
1127                         alert_freq.show();
1128                         return true;
1129                 case R.id.select_tracker:
1130                         if (trackers != null) {
1131                                 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1132                                 builder_serial.setTitle("Select a tracker");
1133                                 builder_serial.setItems(trackers,
1134                                                         new DialogInterface.OnClickListener() {
1135                                                                 public void onClick(DialogInterface dialog, int item) {
1136                                                                         System.out.printf("select item %d %s\n", item, trackers[item].display);
1137                                                                         if (item == 0)
1138                                                                                 select_tracker(0);
1139                                                                         else
1140                                                                                 select_tracker(trackers[item].serial);
1141                                                                 }
1142                                                         });
1143                                 AlertDialog alert_serial = builder_serial.create();
1144                                 alert_serial.show();
1145
1146                         }
1147                         return true;
1148                 case R.id.delete_track:
1149                         if (trackers != null) {
1150                                 AlertDialog.Builder builder_serial = new AlertDialog.Builder(this);
1151                                 builder_serial.setTitle("Delete a track");
1152                                 final Tracker[] my_trackers = new Tracker[trackers.length - 1];
1153                                 for (int i = 0; i < trackers.length - 1; i++)
1154                                         my_trackers[i] = trackers[i+1];
1155                                 builder_serial.setItems(my_trackers,
1156                                                         new DialogInterface.OnClickListener() {
1157                                                                 public void onClick(DialogInterface dialog, int item) {
1158                                                                         delete_track(my_trackers[item].serial);
1159                                                                 }
1160                                                         });
1161                                 AlertDialog alert_serial = builder_serial.create();
1162                                 alert_serial.show();
1163
1164                         }
1165                         return true;
1166                 case R.id.idle_mode:
1167                         serverIntent = new Intent(this, IdleModeActivity.class);
1168                         serverIntent.putExtra(EXTRA_IDLE_MODE, idle_mode);
1169                         startActivityForResult(serverIntent, REQUEST_IDLE_MODE);
1170                         return true;
1171                 }
1172                 return false;
1173         }
1174
1175         static String direction(AltosGreatCircle from_receiver,
1176                                 Location receiver) {
1177                 if (from_receiver == null)
1178                         return null;
1179
1180                 if (receiver == null)
1181                         return null;
1182
1183                 if (!receiver.hasBearing())
1184                         return null;
1185
1186                 float   bearing = receiver.getBearing();
1187                 float   heading = (float) from_receiver.bearing - bearing;
1188
1189                 while (heading <= -180.0f)
1190                         heading += 360.0f;
1191                 while (heading > 180.0f)
1192                         heading -= 360.0f;
1193
1194                 int iheading = (int) (heading + 0.5f);
1195
1196                 if (-1 < iheading && iheading < 1)
1197                         return "ahead";
1198                 else if (iheading < -179 || 179 < iheading)
1199                         return "backwards";
1200                 else if (iheading < 0)
1201                         return String.format("left %d°", -iheading);
1202                 else
1203                         return String.format("right %d°", iheading);
1204         }
1205
1206         public void onLocationChanged(Location location) {
1207                 this.location = location;
1208                 AltosDebug.debug("Location changed to %f,%f",
1209                                  location.getLatitude(),
1210                                  location.getLongitude());
1211                 update_ui(telemetry_state, state, false);
1212         }
1213
1214         public void onStatusChanged(String provider, int status, Bundle extras) {
1215                 AltosDebug.debug("Location status now %d\n", status);
1216         }
1217
1218         public void onProviderEnabled(String provider) {
1219                 AltosDebug.debug("Location provider enabled %s\n", provider);
1220         }
1221
1222         public void onProviderDisabled(String provider) {
1223                 AltosDebug.debug("Location provider disabled %s\n", provider);
1224         }
1225 }