altosdroid: whitespace cleanup
[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         void doBindService() {
154                 bindService(new Intent(this, TelemetryService.class), mConnection, Context.BIND_AUTO_CREATE);
155                 mIsBound = true;
156         }
157
158         void doUnbindService() {
159                 if (mIsBound) {
160                         // If we have received the service, and hence registered with it, then now is the time to unregister.
161                         if (mService != null) {
162                                 try {
163                                         Message msg = Message.obtain(null, TelemetryService.MSG_UNREGISTER_CLIENT);
164                                         msg.replyTo = mMessenger;
165                                         mService.send(msg);
166                                 } catch (RemoteException e) {
167                                         // There is nothing special we need to do if the service has crashed.
168                                 }
169                         }
170                         // Detach our existing connection.
171                         unbindService(mConnection);
172                         mIsBound = false;
173                 }
174         }
175
176         void update_ui(AltosState state) {
177                 mCallsignView.setText(state.data.callsign);
178                 mRSSIView.setText(String.format("%d", state.data.rssi));
179                 mSerialView.setText(String.format("%d", state.data.serial));
180                 mFlightView.setText(String.format("%d", state.data.flight));
181                 mStateView.setText(state.data.state());
182                 mSpeedView.setText(String.format("%6.0f m/s", state.speed()));
183                 mAccelView.setText(String.format("%6.0f m/s²", state.acceleration));
184                 mRangeView.setText(String.format("%6.0f m", state.range));
185                 mHeightView.setText(String.format("%6.0f m", state.height));
186                 mElevationView.setText(String.format("%3.0f°", state.elevation));
187                 if (state.from_pad != null)
188                         mBearingView.setText(String.format("%3.0f°", state.from_pad.bearing));
189                 mLatitudeView.setText(pos(state.gps.lat, "N", "S"));
190                 mLongitudeView.setText(pos(state.gps.lon, "W", "E"));
191
192                 mAltosVoice.tell(state);
193         }
194
195         static String pos(double p, String pos, String neg) {
196                 String  h = pos;
197                 if (p < 0) {
198                         h = neg;
199                         p = -p;
200                 }
201                 int deg = (int) Math.floor(p);
202                 double min = (p - Math.floor(p)) * 60.0;
203                 return String.format("%d° %9.6f\" %s", deg, min, h);
204         }
205
206         @Override
207         public void onCreate(Bundle savedInstanceState) {
208                 super.onCreate(savedInstanceState);
209                 if(D) Log.e(TAG, "+++ ON CREATE +++");
210
211                 // Get local Bluetooth adapter
212                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
213
214                 // If the adapter is null, then Bluetooth is not supported
215                 if (mBluetoothAdapter == null) {
216                         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
217                         finish();
218                         return;
219                 }
220
221                 // Initialise preferences
222                 prefs = new AltosDroidPreferences(this);
223                 AltosPreferences.init(prefs);
224
225                 // Set up the window layout
226                 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
227                 setContentView(R.layout.altosdroid);
228                 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
229
230                 // Set up the custom title
231                 mTitle = (TextView) findViewById(R.id.title_left_text);
232                 mTitle.setText(R.string.app_name);
233                 mTitle = (TextView) findViewById(R.id.title_right_text);
234
235                 // Display the Version
236                 mVersion = (TextView) findViewById(R.id.version);
237                 mVersion.setText("Version: " + BuildInfo.version +
238                                  "  Built: " + BuildInfo.builddate + " " + BuildInfo.buildtime + " " + BuildInfo.buildtz +
239                                  "  (" + BuildInfo.branch + "-" + BuildInfo.commitnum + "-" + BuildInfo.commithash + ")");
240
241                 mCallsignView  = (TextView) findViewById(R.id.callsign_value);
242                 mRSSIView      = (TextView) findViewById(R.id.rssi_value);
243                 mSerialView    = (TextView) findViewById(R.id.serial_value);
244                 mFlightView    = (TextView) findViewById(R.id.flight_value);
245                 mStateView     = (TextView) findViewById(R.id.state_value);
246                 mSpeedView     = (TextView) findViewById(R.id.speed_value);
247                 mAccelView     = (TextView) findViewById(R.id.accel_value);
248                 mRangeView     = (TextView) findViewById(R.id.range_value);
249                 mHeightView    = (TextView) findViewById(R.id.height_value);
250                 mElevationView = (TextView) findViewById(R.id.elevation_value);
251                 mBearingView   = (TextView) findViewById(R.id.bearing_value);
252                 mLatitudeView  = (TextView) findViewById(R.id.latitude_value);
253                 mLongitudeView = (TextView) findViewById(R.id.longitude_value);
254
255                 mAltosVoice = new AltosVoice(this);
256         }
257
258         @Override
259         public void onStart() {
260                 super.onStart();
261                 if(D) Log.e(TAG, "++ ON START ++");
262
263                 if (!mBluetoothAdapter.isEnabled()) {
264                         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
265                         startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
266                 }
267
268                 // Start Telemetry Service
269                 startService(new Intent(AltosDroid.this, TelemetryService.class));
270
271                 doBindService();
272         }
273
274         @Override
275         public synchronized void onResume() {
276                 super.onResume();
277                 if(D) Log.e(TAG, "+ ON RESUME +");
278         }
279
280         @Override
281         public synchronized void onPause() {
282                 super.onPause();
283                 if(D) Log.e(TAG, "- ON PAUSE -");
284         }
285
286         @Override
287         public void onStop() {
288                 super.onStop();
289                 if(D) Log.e(TAG, "-- ON STOP --");
290
291                 doUnbindService();
292         }
293
294         @Override
295         public void onDestroy() {
296                 super.onDestroy();
297                 if(D) Log.e(TAG, "--- ON DESTROY ---");
298
299                 mAltosVoice.stop();
300         }
301
302         public void onActivityResult(int requestCode, int resultCode, Intent data) {
303                 if(D) Log.d(TAG, "onActivityResult " + resultCode);
304                 switch (requestCode) {
305                 case REQUEST_CONNECT_DEVICE:
306                         // When DeviceListActivity returns with a device to connect to
307                         if (resultCode == Activity.RESULT_OK) {
308                                 connectDevice(data);
309                         }
310                         break;
311                 case REQUEST_ENABLE_BT:
312                         // When the request to enable Bluetooth returns
313                         if (resultCode == Activity.RESULT_OK) {
314                                 // Bluetooth is now enabled, so set up a chat session
315                                 //setupChat();
316                         } else {
317                                 // User did not enable Bluetooth or an error occured
318                                 Log.e(TAG, "BT not enabled");
319                                 stopService(new Intent(AltosDroid.this, TelemetryService.class));
320                                 Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show();
321                                 finish();
322                         }
323                         break;
324                 }
325         }
326
327         private void connectDevice(Intent data) {
328                 // Get the device MAC address
329                 String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
330                 // Get the BLuetoothDevice object
331                 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
332                 // Attempt to connect to the device
333                 try {
334                         if (D) Log.d(TAG, "Connecting to " + device.getName());
335                         mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
336                 } catch (RemoteException e) {
337                 }
338         }
339
340         @Override
341         public boolean onCreateOptionsMenu(Menu menu) {
342                 MenuInflater inflater = getMenuInflater();
343                 inflater.inflate(R.menu.option_menu, menu);
344                 return true;
345         }
346
347         void setFrequency(double freq) {
348                 try {
349                         mService.send(Message.obtain(null, TelemetryService.MSG_SETFREQUENCY, freq));
350                 } catch (RemoteException e) {
351                 }
352         }
353
354         void setFrequency(String freq) {
355                 try {
356                         setFrequency (Double.parseDouble(freq.substring(11, 17)));
357                 } catch (NumberFormatException e) {
358                 }
359         }
360
361         @Override
362         public boolean onOptionsItemSelected(MenuItem item) {
363                 Intent serverIntent = null;
364                 switch (item.getItemId()) {
365                 case R.id.connect_scan:
366                         // Launch the DeviceListActivity to see devices and do scan
367                         serverIntent = new Intent(this, DeviceListActivity.class);
368                         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
369                         return true;
370                 case R.id.select_freq:
371                         // Set the TBT radio frequency
372
373                         final String[] frequencies = {
374                                 "Channel 0 (434.550MHz)",
375                                 "Channel 1 (434.650MHz)",
376                                 "Channel 2 (434.750MHz)",
377                                 "Channel 3 (434.850MHz)",
378                                 "Channel 4 (434.950MHz)",
379                                 "Channel 5 (435.050MHz)",
380                                 "Channel 6 (435.150MHz)",
381                                 "Channel 7 (435.250MHz)",
382                                 "Channel 8 (435.350MHz)",
383                                 "Channel 9 (435.450MHz)"
384                         };
385
386                         AlertDialog.Builder builder = new AlertDialog.Builder(this);
387                         builder.setTitle("Pick a frequency");
388                         builder.setItems(frequencies,
389                                          new DialogInterface.OnClickListener() {
390                                                  public void onClick(DialogInterface dialog, int item) {
391                                                          setFrequency(frequencies[item]);
392                                                  }
393                                          });
394                         AlertDialog alert = builder.create();
395                         alert.show();
396                         return true;
397                 }
398                 return false;
399         }
400
401 }