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