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