altosdroid: make AltosDroid.pos() static
[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
22 import android.app.Activity;
23 import android.bluetooth.BluetoothAdapter;
24 import android.bluetooth.BluetoothDevice;
25 import android.content.Intent;
26 import android.content.Context;
27 import android.content.ComponentName;
28 import android.content.ServiceConnection;
29 import android.content.DialogInterface;
30 import android.os.IBinder;
31 import android.os.Bundle;
32 import android.os.Handler;
33 import android.os.Message;
34 import android.os.Messenger;
35 import android.os.RemoteException;
36 import android.util.Log;
37 import android.view.Menu;
38 import android.view.MenuInflater;
39 import android.view.MenuItem;
40 import android.view.Window;
41 import android.widget.TextView;
42 import android.widget.Toast;
43 import android.app.AlertDialog;
44
45 import org.altusmetrum.altoslib_1.*;
46
47 public class AltosDroid extends Activity {
48         // Debugging
49         private static final String TAG = "AltosDroid";
50         private static final boolean D = true;
51
52         // Message types received by our Handler
53         public static final int MSG_STATE_CHANGE    = 1;
54         public static final int MSG_TELEMETRY       = 2;
55
56         // Intent request codes
57         private static final int REQUEST_CONNECT_DEVICE = 1;
58         private static final int REQUEST_ENABLE_BT      = 2;
59
60         // Layout Views
61         private TextView mTitle;
62
63         // Flight state values
64         private TextView mCallsignView;
65         private TextView mRSSIView;
66         private TextView mSerialView;
67         private TextView mFlightView;
68         private TextView mStateView;
69         private TextView mSpeedView;
70         private TextView mAccelView;
71         private TextView mRangeView;
72         private TextView mHeightView;
73         private TextView mElevationView;
74         private TextView mBearingView;
75         private TextView mLatitudeView;
76         private TextView mLongitudeView;
77
78         // field to display the version at the bottom of the screen
79         private TextView mVersion;
80
81         // Service
82         private boolean mIsBound   = false;
83         private Messenger mService = null;
84         final Messenger mMessenger = new Messenger(new IncomingHandler(this));
85
86         // Preferences
87         private AltosDroidPreferences prefs = null;
88
89         // TeleBT Config data
90         private AltosConfigData mConfigData = null;
91         // Local Bluetooth adapter
92         private BluetoothAdapter mBluetoothAdapter = null;
93
94         // Text to Speech
95         private AltosVoice mAltosVoice = null;
96
97         // The Handler that gets information back from the Telemetry Service
98         static class IncomingHandler extends Handler {
99                 private final WeakReference<AltosDroid> mAltosDroid;
100                 IncomingHandler(AltosDroid ad) { mAltosDroid = new WeakReference<AltosDroid>(ad); }
101
102                 @Override
103                 public void handleMessage(Message msg) {
104                         AltosDroid ad = mAltosDroid.get();
105                         switch (msg.what) {
106                         case MSG_STATE_CHANGE:
107                                 if(D) Log.d(TAG, "MSG_STATE_CHANGE: " + msg.arg1);
108                                 switch (msg.arg1) {
109                                 case TelemetryService.STATE_CONNECTED:
110                                         ad.mConfigData = (AltosConfigData) msg.obj;
111                                         String str = String.format(" %s S/N: %d", ad.mConfigData.product, ad.mConfigData.serial);
112                                         ad.mTitle.setText(R.string.title_connected_to);
113                                         ad.mTitle.append(str);
114                                         Toast.makeText(ad.getApplicationContext(), "Connected to " + str, Toast.LENGTH_SHORT).show();
115                                         ad.mAltosVoice.speak("Connected");
116                                         break;
117                                 case TelemetryService.STATE_CONNECTING:
118                                         ad.mTitle.setText(R.string.title_connecting);
119                                         break;
120                                 case TelemetryService.STATE_READY:
121                                 case TelemetryService.STATE_NONE:
122                                         ad.mConfigData = null;
123                                         ad.mTitle.setText(R.string.title_not_connected);
124                                         break;
125                                 }
126                                 break;
127                         case MSG_TELEMETRY:
128                                 ad.update_ui((AltosState) msg.obj);
129                                 break;
130                         }
131                 }
132         };
133
134
135         private ServiceConnection mConnection = new ServiceConnection() {
136                 public void onServiceConnected(ComponentName className, IBinder service) {
137                         mService = new Messenger(service);
138                         try {
139                                 Message msg = Message.obtain(null, TelemetryService.MSG_REGISTER_CLIENT);
140                                 msg.replyTo = mMessenger;
141                                 mService.send(msg);
142                         } catch (RemoteException e) {
143                                 // In this case the service has crashed before we could even do anything with it
144                         }
145                 }
146
147                 public void onServiceDisconnected(ComponentName className) {
148                         // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
149                         mService = null;
150                 }
151         };
152
153
154         void doBindService() {
155                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
156                 mIsBound = true;
157         }
158
159         void doUnbindService() {
160                 if (mIsBound) {
161                         // If we have received the service, and hence registered with it, then now is the time to unregister.
162                         if (mService != null) {
163                                 try {
164                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
165                                         msg.replyTo = mMessenger;
166                                         mService.send(msg);
167                                 } catch (RemoteException e) {
168                                         // There is nothing special we need to do if the service has crashed.
169                                 }
170                         }
171                         // Detach our existing connection.
172                         unbindService(mConnection);
173                         mIsBound = false;
174                 }
175         }
176
177         void update_ui(AltosState state) {
178                 mCallsignView.setText(state.data.callsign);
179                 mRSSIView.setText(String.format("%d", state.data.rssi));
180                 mSerialView.setText(String.format("%d", state.data.serial));
181                 mFlightView.setText(String.format("%d", state.data.flight));
182                 mStateView.setText(state.data.state());
183                 mSpeedView.setText(String.format("%6.0f m/s", state.speed()));
184                 mAccelView.setText(String.format("%6.0f m/s²", state.acceleration));
185                 mRangeView.setText(String.format("%6.0f m", state.range));
186                 mHeightView.setText(String.format("%6.0f m", state.height));
187                 mElevationView.setText(String.format("%3.0f°", state.elevation));
188                 if (state.from_pad != null)
189                         mBearingView.setText(String.format("%3.0f°", state.from_pad.bearing));
190                 mLatitudeView.setText(pos(state.gps.lat, "N", "S"));
191                 mLongitudeView.setText(pos(state.gps.lon, "W", "E"));
192
193                 mAltosVoice.tell(state);
194         }
195
196         static String pos(double p, String pos, String neg) {
197                 String  h = pos;
198                 if (p < 0) {
199                         h = neg;
200                         p = -p;
201                 }
202                 int deg = (int) Math.floor(p);
203                 double min = (p - Math.floor(p)) * 60.0;
204                 return String.format("%d° %9.6f\" %s", deg, min, h);
205         }
206
207         @Override
208         public void onCreate(Bundle savedInstanceState) {
209                 super.onCreate(savedInstanceState);
210                 if(D) Log.e(TAG, "+++ ON CREATE +++");
211
212                 // Get local Bluetooth adapter
213                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
214
215                 // If the adapter is null, then Bluetooth is not supported
216                 if (mBluetoothAdapter == null) {
217                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
218                         finish();
219                         return;
220                 }
221
222                 // Initialise preferences
223                 prefs = new AltosDroidPreferences(this);
224                 AltosPreferences.init(prefs);
225
226                 // Set up the window layout
227                 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
228                 setContentView(R.layout.altosdroid);
229                 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
230
231                 // Set up the custom title
232                 mTitle = (TextView) findViewById(R.id.title_left_text);
233                 mTitle.setText(R.string.app_name);
234                 mTitle = (TextView) findViewById(R.id.title_right_text);
235
236                 // Display the Version
237                 mVersion = (TextView) findViewById(R.id.version);
238                 mVersion.setText("Version: " + BuildInfo.version +
239                                  "  Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
240                                  "  (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
241
242                 mCallsignView  = (TextView) findViewById(R.id.callsign_value);
243                 mRSSIView      = (TextView) findViewById(R.id.rssi_value);
244                 mSerialView    = (TextView) findViewById(R.id.serial_value);
245                 mFlightView    = (TextView) findViewById(R.id.flight_value);
246                 mStateView     = (TextView) findViewById(R.id.state_value);
247                 mSpeedView     = (TextView) findViewById(R.id.speed_value);
248                 mAccelView     = (TextView) findViewById(R.id.accel_value);
249                 mRangeView     = (TextView) findViewById(R.id.range_value);
250                 mHeightView    = (TextView) findViewById(R.id.height_value);
251                 mElevationView = (TextView) findViewById(R.id.elevation_value);
252                 mBearingView   = (TextView) findViewById(R.id.bearing_value);
253                 mLatitudeView  = (TextView) findViewById(R.id.latitude_value);
254                 mLongitudeView = (TextView) findViewById(R.id.longitude_value);
255
256                 mAltosVoice = new AltosVoice(this);
257         }
258
259         @Override
260         public void onStart() {
261                 super.onStart();
262                 if(D) Log.e(TAG, "++ ON START ++");
263
264                 if (!mBluetoothAdapter.isEnabled()) {
265                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
266                         startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
267                 }
268
269                 // Start Telemetry Service
270                 startService(new Intent(AltosDroid.this, TelemetryService.class));
271
272                 doBindService();
273         }
274
275         @Override
276         public synchronized void onResume() {
277                 super.onResume();
278                 if(D) Log.e(TAG, "+ ON RESUME +");
279         }
280
281         @Override
282         public synchronized void onPause() {
283                 super.onPause();
284                 if(D) Log.e(TAG, "- ON PAUSE -");
285         }
286
287         @Override
288         public void onStop() {
289                 super.onStop();
290                 if(D) Log.e(TAG, "-- ON STOP --");
291
292                 doUnbindService();
293         }
294
295         @Override
296         public void onDestroy() {
297                 super.onDestroy();
298                 if(D) Log.e(TAG, "--- ON DESTROY ---");
299
300                 mAltosVoice.stop();
301         }
302
303         public void onActivityResult(int requestCode, int resultCode, Intent data) {
304                 if(D) Log.d(TAG, "onActivityResult " + resultCode);
305                 switch (requestCode) {
306                 case REQUEST_CONNECT_DEVICE:
307                         // When DeviceListActivity returns with a device to connect to
308                         if (resultCode == Activity.RESULT_OK) {
309                                 connectDevice(data);
310                         }
311                         break;
312                 case REQUEST_ENABLE_BT:
313                         // When the request to enable Bluetooth returns
314                         if (resultCode == Activity.RESULT_OK) {
315                                 // Bluetooth is now enabled, so set up a chat session
316                                 //setupChat();
317                         } else {
318                                 // User did not enable Bluetooth or an error occured
319                                 Log.e(TAG, "BT not enabled");
320                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
321                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
322                                 finish();
323                         }
324                         break;
325                 }
326         }
327
328         private void connectDevice(Intent data) {
329                 // Get the device MAC address
330                 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
331                 // Get the BLuetoothDevice object
332                 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
333                 // Attempt to connect to the device
334                 try {
335                         if (D) Log.d(TAG, "Connecting to " + device.getName());
336                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
337                 } catch (RemoteException e) {
338                 }
339         }
340
341         @Override
342         public boolean onCreateOptionsMenu(Menu menu) {
343                 MenuInflater inflater = getMenuInflater();
344                 inflater.inflate(R.menu.option_menu, menu);
345                 return true;
346         }
347
348         void setFrequency(double freq) {
349                 try {
350                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
351                 } catch (RemoteException e) {
352                 }
353         }
354
355         void setFrequency(String freq) {
356                 try {
357                         setFrequency (Double.parseDouble(freq.substring(11, 17)));
358                 } catch (NumberFormatException e) {
359                 }
360         }
361
362         @Override
363         public boolean onOptionsItemSelected(MenuItem item) {
364                 Intent serverIntent = null;
365                 switch (item.getItemId()) {
366                 case R.id.connect_scan:
367                         // Launch the DeviceListActivity to see devices and do scan
368                         serverIntent = new Intent(this, DeviceListActivity.class);
369                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
370                         return true;
371                 case R.id.select_freq:
372                         // Set the TBT radio frequency
373
374                         final String[] frequencies = {
375                                 "Channel 0 (434.550MHz)",
376                                 "Channel 1 (434.650MHz)",
377                                 "Channel 2 (434.750MHz)",
378                                 "Channel 3 (434.850MHz)",
379                                 "Channel 4 (434.950MHz)",
380                                 "Channel 5 (435.050MHz)",
381                                 "Channel 6 (435.150MHz)",
382                                 "Channel 7 (435.250MHz)",
383                                 "Channel 8 (435.350MHz)",
384                                 "Channel 9 (435.450MHz)"
385                         };
386
387                         AlertDialog.Builder builder = new AlertDialog.Builder(this);
388                         builder.setTitle("Pick a frequency");
389                         builder.setItems(frequencies,
390                                          new DialogInterface.OnClickListener() {
391                                                  public void onClick(DialogInterface dialog, int item) {
392                                                          setFrequency(frequencies[item]);
393                                                  }
394                                          });
395                         AlertDialog alert = builder.create();
396                         alert.show();
397                         return true;
398                 }
399                 return false;
400         }
401
402 }