MainActivity.java 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727
  1. package nl.digitalthings.mebarista;
  2. /* Hint: If you are connecting to a Bluetooth serial board then try using
  3. * the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB. However
  4. * if you are connecting to an Android peer then please generate your own unique UUID. */
  5. import java.io.BufferedReader;
  6. import java.io.File;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.InputStreamReader;
  11. import java.io.OutputStream;
  12. import java.io.OutputStreamWriter;
  13. import java.io.PrintWriter;
  14. import java.net.URI;
  15. import java.net.URL;
  16. import java.net.URLConnection;
  17. import java.text.DecimalFormat;
  18. import java.util.ArrayList;
  19. import java.util.List;
  20. import java.util.Timer;
  21. import java.util.TimerTask;
  22. import android.Manifest;
  23. import android.app.AlertDialog;
  24. import android.bluetooth.BluetoothAdapter;
  25. import android.content.ActivityNotFoundException;
  26. import android.content.ComponentName;
  27. import android.content.DialogInterface;
  28. import android.content.ServiceConnection;
  29. import android.content.SharedPreferences;
  30. import android.content.pm.PackageManager;
  31. import android.content.res.Configuration;
  32. import android.graphics.Bitmap;
  33. import android.graphics.Color;
  34. import android.hardware.Camera;
  35. import android.hardware.display.DisplayManager;
  36. import android.hardware.display.VirtualDisplay;
  37. import android.media.CamcorderProfile;
  38. import android.media.MediaRecorder;
  39. import android.media.MediaScannerConnection;
  40. import android.media.projection.MediaProjection;
  41. import android.media.projection.MediaProjectionManager;
  42. import android.net.Uri;
  43. import android.os.Build;
  44. import android.os.Bundle;
  45. import android.os.Environment;
  46. import android.os.Handler;
  47. import android.os.IBinder;
  48. import android.os.Message;
  49. import android.os.Messenger;
  50. import android.app.Activity;
  51. import android.content.Context;
  52. import android.content.Intent;
  53. import android.os.StrictMode;
  54. import android.os.SystemClock;
  55. import android.preference.Preference;
  56. import android.preference.PreferenceManager;
  57. import android.support.v4.content.ContextCompat;
  58. import android.util.DisplayMetrics;
  59. import android.util.Log;
  60. import android.view.Menu;
  61. import android.view.MenuItem;
  62. import android.view.MotionEvent;
  63. import android.view.Surface;
  64. import android.view.SurfaceHolder;
  65. import android.view.SurfaceView;
  66. import android.view.View;
  67. import android.view.ViewGroup;
  68. import android.view.Window;
  69. import android.view.WindowManager;
  70. import android.webkit.WebSettings;
  71. import android.webkit.WebView;
  72. import android.webkit.WebViewClient;
  73. import android.widget.Button;
  74. import android.widget.ImageView;
  75. import android.widget.LinearLayout;
  76. import android.widget.ProgressBar;
  77. import android.widget.RelativeLayout;
  78. import android.widget.ShareActionProvider;
  79. import android.widget.TextView;
  80. import android.widget.Toast;
  81. import android.widget.Toolbar;
  82. import org.achartengine.ChartFactory;
  83. import org.achartengine.GraphicalView;
  84. import org.achartengine.tools.ZoomEvent;
  85. import org.achartengine.tools.ZoomListener;
  86. import org.xml.sax.SAXException;
  87. import javax.xml.parsers.ParserConfigurationException;
  88. public class MainActivity extends Activity
  89. implements View.OnClickListener, ZoomListener, SurfaceHolder.Callback {
  90. private static final String TAG = "MainActivity";
  91. private static final String TAG_SC = "ScreenCapture";
  92. // Constants
  93. private static final int REQUEST_ENABLE_BT = 105;
  94. public static final int MESSAGE_READ = 106;
  95. public static final int DEVICE_ON = 107;
  96. public static final int DEVICE_OFF = 108;
  97. public static final int MESSAGE_TOAST = 109;
  98. public static final int UPDATE = 110;
  99. public static final int SPINNER_ON = 111;
  100. public static final int SPINNER_OFF = 112;
  101. // Controls
  102. private TextView btemp, setpoint, logging;
  103. private ImageView indicator;
  104. private ImageView background;
  105. private GraphicalView mChartView;
  106. private Gauge meter1, meter2;
  107. private LinearLayout tempcontrol;
  108. private View video;
  109. private ProgressBar progress_bar;
  110. private WebView installation_manual;
  111. private Button minbutton, plusbutton;
  112. // State
  113. private long last_message;
  114. private Timer indicator_watchdog_timer;
  115. private int teller;
  116. private boolean lock_graph;
  117. boolean piddisabled = true;
  118. double curSetpoint;
  119. boolean logging_enabled = false;
  120. int time_scale = 1000;
  121. private Timer handleintentTimer;
  122. private ShareActionProvider mShareActionProvider;
  123. // Util
  124. SharedPreferences sharedPrefs;
  125. // Shot timer
  126. private long startTime = 0L;
  127. private Handler customHandler = new Handler();
  128. int preinfusionDelay = 0;
  129. // Video
  130. // http://stackoverflow.com/questions/1817742/how-can-i-capture-a-video-recording-on-android
  131. // TODO: remove recorder, just use camera preview
  132. MediaRecorder mMediaRecorder, recorder;
  133. SurfaceHolder holder;
  134. boolean recording = false;
  135. // Screen recording
  136. // https://android.googlesource.com/platform/development/+/bf1e262/samples/ApiDemos/src/com/example/android/apis/media/projection/MediaProjectionDemo.java
  137. // http://www.truiton.com/2015/05/capture-record-android-screen-using-mediaprojection-apis/
  138. private static class Resolution {
  139. int x;
  140. int y;
  141. public Resolution(int x, int y) {
  142. this.x = x;
  143. this.y = y;
  144. }
  145. @Override
  146. public String toString() {
  147. return x + "x" + y;
  148. }
  149. }
  150. private static final int SCREEN_RECORDING_REQUEST_CODE = 666;
  151. private static final List<Resolution> RESOLUTIONS = new ArrayList<Resolution>() {{
  152. add(new Resolution(1280, 720));
  153. add(new Resolution(640, 360));
  154. add(new Resolution(960, 540));
  155. add(new Resolution(1366, 768));
  156. add(new Resolution(1600, 900));
  157. }};
  158. private int mScreenDensity;
  159. private MediaProjectionManager mProjectionManager;
  160. private int mDisplayWidth;
  161. private int mDisplayHeight;
  162. private boolean mScreenSharing;
  163. private MediaProjection mMediaProjection;
  164. private VirtualDisplay mVirtualDisplay;
  165. private Surface mSurface;
  166. private SurfaceView mSurfaceView;
  167. private boolean cameraToggleStatus = false;
  168. // Video
  169. private void prepareRecorder() {
  170. Log.i(TAG, "prepareRecorder");
  171. recorder.setPreviewDisplay(holder.getSurface());
  172. try {
  173. recorder.prepare();
  174. } catch (IllegalStateException e) {
  175. e.printStackTrace();
  176. finish();
  177. } catch (IOException e) {
  178. e.printStackTrace();
  179. finish();
  180. }
  181. }
  182. private void initRecorder() {
  183. Log.i(TAG, "initRecorder");
  184. //recorder.setCamera(Camera.open( 0 ) );
  185. CamcorderProfile cpHigh = CamcorderProfile
  186. .get(CamcorderProfile.QUALITY_HIGH);
  187. recorder = new MediaRecorder();
  188. //recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
  189. recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
  190. recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
  191. recorder.setProfile(cpHigh);
  192. recorder.setOutputFile(Environment.getExternalStorageDirectory().getPath() + "/videocapture_example.mp4");
  193. recorder.setMaxDuration(50000); // 50 seconds
  194. recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
  195. background.setVisibility(View.INVISIBLE);
  196. prepareRecorder();
  197. recorder.start();
  198. }
  199. Camera camera;
  200. public void surfaceCreated(SurfaceHolder holder) {
  201. Log.i(TAG, "surfaceCreated");
  202. // prepareRecorder();
  203. camera = Camera.open();
  204. try {
  205. camera.setPreviewDisplay(holder);
  206. camera.startPreview();
  207. // previewRunning = true;
  208. } catch (IOException e) {
  209. Log.e(TAG, e.getMessage());
  210. e.printStackTrace();
  211. }
  212. }
  213. public void surfaceChanged(SurfaceHolder holder, int format, int width,
  214. int height) {
  215. Log.i(TAG, "surfaceChanged");
  216. }
  217. public void surfaceDestroyed(SurfaceHolder holder) {
  218. Log.i(TAG, "surfaceDestroyed");
  219. if (recording) {
  220. recorder.stop();
  221. recording = false;
  222. recorder.release();
  223. }
  224. if (camera != null) {
  225. Log.i(TAG, "Camera released in surfaceDestroyed");
  226. camera.release();
  227. camera = null;
  228. }
  229. finish(); // ??
  230. }
  231. static float clamp(float v, float mn, float mx) {
  232. return Math.min(Math.max(v, mn), mx);
  233. }
  234. private Runnable updateTimerThread = new Runnable() {
  235. public void run() {
  236. float shotTime = (SystemClock.uptimeMillis() - startTime) / 1000.0f;
  237. meter2.setValue(clamp(shotTime - preinfusionDelay, 0, 30));
  238. customHandler.postDelayed(this, 500);
  239. }
  240. };
  241. // This handler checks the last time a message was received
  242. // If it was too long ago, the indicator will be switched to off
  243. // and the readings will be grayed?
  244. final Handler indicator_watchdog = new Handler() {
  245. @Override
  246. public void handleMessage(Message msg) {
  247. if (System.currentTimeMillis() - last_message > 3000) {
  248. indicator.setImageResource(R.drawable.silvia_off);
  249. btemp.setText("---,-- °");
  250. setpoint.setText("---,-- °");
  251. meter1.setValue(0);
  252. // bConnection.reset();
  253. }
  254. }
  255. };
  256. // Bookkeep when the graph handles touch events: do not repaint when in touchevent
  257. @Override
  258. public boolean dispatchTouchEvent(MotionEvent event) {
  259. int eventaction = event.getAction();
  260. switch (eventaction) {
  261. case MotionEvent.ACTION_DOWN:
  262. // finger touches the screen
  263. lock_graph = true;
  264. break;
  265. case MotionEvent.ACTION_MOVE:
  266. // finger moves on the screen
  267. break;
  268. case MotionEvent.ACTION_UP:
  269. // finger leaves the screen
  270. lock_graph = false;
  271. break;
  272. }
  273. super.dispatchTouchEvent(event);
  274. return false;
  275. }
  276. private void ShotTimer_show() {
  277. final float scale = getBaseContext().getResources().getDisplayMetrics().density;
  278. ViewGroup.LayoutParams lp = meter1.getLayoutParams();
  279. lp.width = (int) (175 * scale);
  280. lp.height = (int) (175 * scale);
  281. meter1.setLayoutParams(lp);
  282. meter2.setVisibility(View.VISIBLE);
  283. }
  284. private void ShotTimer_hide() {
  285. final float scale = getBaseContext().getResources().getDisplayMetrics().density;
  286. ViewGroup.LayoutParams lp = meter1.getLayoutParams();
  287. meter2.setValue(0f);
  288. lp.width = (int) (200 * scale);
  289. lp.height = (int) (200 * scale);
  290. meter1.setLayoutParams(lp);
  291. meter2.setVisibility(View.GONE);
  292. }
  293. private final Handler mHandler = new Handler() {
  294. @Override
  295. public void handleMessage(Message msg) {
  296. String message = (String) msg.obj;
  297. if (message == null)
  298. return;
  299. String parts[] = message.split(" ");
  300. switch (msg.what) {
  301. case SPINNER_ON:
  302. Log.i( TAG, "Showing spinner" );
  303. progress_bar.setVisibility( View.VISIBLE );
  304. break;
  305. case SPINNER_OFF:
  306. Log.i( TAG, "Hiding spinner" );
  307. progress_bar.setVisibility( View.GONE );
  308. break;
  309. case DEVICE_ON:
  310. // Change indicator to on
  311. indicator.setImageResource(R.drawable.silvia_on);
  312. setTitle("meBarista: " + (String) msg.obj);
  313. break;
  314. case UPDATE:
  315. mChartView.repaint();
  316. break;
  317. case DEVICE_OFF:
  318. // Change indicator to off
  319. indicator.setImageResource(R.drawable.silvia_off);
  320. // Clear all readings
  321. break;
  322. case MESSAGE_TOAST:
  323. Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show();
  324. break;
  325. case MESSAGE_READ:
  326. last_message = System.currentTimeMillis();
  327. indicator.setImageResource(R.drawable.silvia_on);
  328. if( logging_enabled ) {
  329. log( message );
  330. }
  331. // Graph is not enabled?
  332. if (findViewById( R.id.graph ) == null)
  333. break;
  334. if (message.startsWith("pid ")) {
  335. try {
  336. float res = Integer.parseInt(parts[1]) + Integer.parseInt(parts[2]) + Integer.parseInt(parts[3]);
  337. if (parts.length >= 5)
  338. res += Integer.parseInt(parts[4]);
  339. res = res / 65535 * 100.0f;
  340. meter1.setValue(Math.min(res, 100.0f));
  341. //System.out.println( "updated graph" );
  342. return;
  343. } catch (Exception e) {
  344. Log.e(TAG, "Failed to parse PID message");
  345. }
  346. }
  347. if (message.startsWith("dem ")) {
  348. time_scale = Integer.parseInt(parts[1]);
  349. }
  350. if (message.startsWith("sht ")) {
  351. try {
  352. int shottime = Integer.parseInt(parts[2]);
  353. if (shottime == 0) {
  354. meter2.setValue(0f);
  355. ShotTimer_show();
  356. startTime = SystemClock.uptimeMillis();
  357. // Setting can be changed from multiple locations: get it here
  358. preinfusionDelay = 0;
  359. if (sharedPrefs.getBoolean("pref_pinbl", false)) {
  360. preinfusionDelay = sharedPrefs.getInt("pref_piprd", 0);
  361. }
  362. System.out.println("PI Delay" + preinfusionDelay);
  363. customHandler.postDelayed(updateTimerThread, 1000);
  364. } else {
  365. customHandler.removeCallbacks(updateTimerThread);
  366. float st_secs = shottime / time_scale - preinfusionDelay;
  367. meter2.setValue(clamp(st_secs, 0, 30));
  368. customHandler.postDelayed(new Runnable() {
  369. public void run() {
  370. ShotTimer_hide();
  371. }
  372. }, 30 * 1000);
  373. }
  374. } catch (Exception e) {
  375. Log.e(TAG, "Failed to parse SHT message");
  376. }
  377. }
  378. if (message.startsWith("T ") || message.startsWith("tmp ")) {
  379. try {
  380. // renderer.setPanLimits( new double[] { 0, max( mBoundService.teller, 100 ), -10, 120 } );
  381. if (!lock_graph &&
  382. mBoundService.teller > mBoundService.renderer.getXAxisMin() &&
  383. mBoundService.teller <= mBoundService.renderer.getXAxisMax() + 50) {
  384. double cur_width = mBoundService.renderer.getXAxisMax() - mBoundService.renderer.getXAxisMin();
  385. mBoundService.renderer.setXAxisMin(mBoundService.teller - cur_width);
  386. mBoundService.renderer.setXAxisMax(mBoundService.teller);
  387. //mBoundService.renderer.setXAxisMin( mBoundService.gdataset.getSeries()[0].getMinX() );
  388. //mBoundService.renderer.setXAxisMax( mBoundService.gdataset.getSeries()[0].getMaxX() );
  389. }
  390. double[] panlimits = mBoundService.renderer.getPanLimits();
  391. //panlimits[0] = mBoundService.gdataset.getSeries()[0].getMinX() - 30 ;
  392. panlimits[1] = mBoundService.teller + 30;
  393. mBoundService.renderer.setPanLimits(panlimits);
  394. double[] zoomlimits = mBoundService.renderer.getZoomLimits();
  395. //panlimits[0] = mBoundService.gdataset.getSeries()[0].getMinX() - 30 ;
  396. zoomlimits[1] = Math.max(600, mBoundService.teller + 30);
  397. mBoundService.renderer.setZoomLimits(zoomlimits);
  398. double yrange = mBoundService.renderer.getYAxisMax() - mBoundService.renderer.getYAxisMin();
  399. if ((int) yrange == 150)
  400. mBoundService.renderer.setZoomEnabled(true, false);
  401. String[] parts2 = message.replaceAll("T ", "").replaceAll("tmp ", "").replaceAll("\n", "").split(" ");
  402. if (parts2.length >= 3) {
  403. // Double.parseDouble(parts[1]) / 100.0
  404. DecimalFormat f = new DecimalFormat("#0.00");
  405. double temp = Double.parseDouble(parts2[2]) / 100.0;
  406. double sp = Double.parseDouble(parts2[1]) / 100.0;
  407. btemp.setText(f.format(temp) + " °");
  408. setpoint.setText(f.format(sp) + " °");
  409. curSetpoint = sp;
  410. }
  411. if (!lock_graph /* &&
  412. mBoundService.teller > mBoundService.renderer.getXAxisMin() &&
  413. mBoundService.teller <= mBoundService.renderer.getXAxisMax() + 5 */)
  414. mChartView.repaint();
  415. } catch (Exception e) {
  416. Log.e(TAG, "Failed to parse TMP message");
  417. }
  418. }
  419. break;
  420. default:
  421. break;
  422. }
  423. }
  424. };
  425. public void execute2(Context context) {
  426. // Don't create the graph if it is disabled in the preference
  427. SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
  428. if (!sharedPref.getBoolean("pref_ui_graph_enable", true))
  429. return;
  430. RelativeLayout layout = (RelativeLayout) findViewById(R.id.achart);
  431. mChartView = ChartFactory.getTimeChartView(this, mBoundService.gdataset, mBoundService.renderer, "mm:ss");
  432. mChartView.setId(R.id.graph);
  433. //mChartView.setVisibility(View.INVISIBLE);
  434. layout.addView(mChartView);
  435. //
  436. // , new LayoutParams(LayoutParams.MATCH_PARENT,
  437. // LayoutParams.MATCH_PARENT, LayoutParams.));
  438. }
  439. private BaristaService mBoundService;
  440. private Messenger mBoundMsg;
  441. private ServiceConnection mConnection = new ServiceConnection() {
  442. public void onServiceConnected(ComponentName className, IBinder service) {
  443. // This is called when the connection with the service has been
  444. // established, giving us the service object we can use to
  445. // interact with the service. Because we have bound to a explicit
  446. // service that we know is running in our own process, we can
  447. // cast its IBinder to a concrete class and directly access it.
  448. mBoundService = ((BaristaService.LocalBinder) service).getService();
  449. mBoundService.setHandler(mHandler, MainActivity.this);
  450. // Tell the user about this for our demo.
  451. //Toast.makeText(Binding.this, R.string.local_service_connected,
  452. // Toast.LENGTH_SHORT).show();
  453. execute2(MainActivity.this);
  454. // mBoundService.fillChartWithDemoData();
  455. service_call( "scan" );
  456. }
  457. public void onServiceDisconnected(ComponentName className) {
  458. // This is called when the connection with the service has been
  459. // unexpectedly disconnected -- that is, its process crashed.
  460. // Because it is running in our same process, we should never
  461. // see this happen.
  462. mBoundService = null;
  463. //Toast.makeText(Binding.this, R.string.local_service_disconnected,
  464. // Toast.LENGTH_SHORT).show();
  465. }
  466. };
  467. void doBindService() {
  468. // Establish a connection with the service. We use an explicit
  469. // class name because we want a specific service implementation that
  470. // we know will be running in our own process (and thus won't be
  471. // supporting component replacement by other applications).
  472. bindService(new Intent(MainActivity.this,
  473. BaristaService.class), mConnection, Context.BIND_AUTO_CREATE);
  474. //mIsBound = true;
  475. }
  476. void doUnbindService() {
  477. //if (mIsBound) {
  478. // Detach our existing connection.
  479. unbindService(mConnection);
  480. // mIsBound = false;
  481. //}
  482. }
  483. /**
  484. * Handler of incoming messages from service.
  485. */
  486. class IncomingHandler extends Handler {
  487. @Override
  488. public void handleMessage(Message msg) {
  489. switch (msg.what) {
  490. case BaristaService.UPDATE:
  491. // mCallbackText.setText("Received from service: " + msg.arg1);
  492. mChartView.repaint();
  493. break;
  494. default:
  495. super.handleMessage(msg);
  496. }
  497. }
  498. }
  499. final Messenger mMessenger = new Messenger(new IncomingHandler());
  500. @Override
  501. protected void onResume() {
  502. sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
  503. background.setVisibility(sharedPrefs.getBoolean("pref_ui_background", true) ? View.VISIBLE : View.INVISIBLE);
  504. if (sharedPrefs.getBoolean("pref_ui_screenwake", false))
  505. getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  506. else
  507. getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  508. logging_enabled = sharedPrefs.getBoolean("pref_ui_logging", false);
  509. if (mBoundService != null)
  510. mBoundService.showSecondSensor(sharedPrefs.getBoolean("pref_ui_second_sensor", false));
  511. super.onResume();
  512. }
  513. @Override
  514. protected void onDestroy() {
  515. Log.i( TAG, "onDestroy" );
  516. if( mBoundService != null && mBoundService.blehandler != null && mBoundService.blehandler.mBluetoothGatt != null ) {
  517. mBoundService.blehandler.mBluetoothGatt.disconnect();
  518. mBoundService.blehandler.mBluetoothGatt.close();
  519. }
  520. doUnbindService();
  521. Intent i = new Intent(this, BaristaService.class);
  522. getApplicationContext().stopService(i);
  523. if (sharedPrefs.getBoolean("pref_bt_disable", false)) {
  524. BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  525. if (mBluetoothAdapter.isEnabled())
  526. mBluetoothAdapter.disable();
  527. }
  528. super.onDestroy();
  529. }
  530. private void prefTestFloat( SharedPreferences sharedPrefs, SharedPreferences.Editor editor, String key ) {
  531. try {
  532. float val = sharedPrefs.getFloat(key, -42);
  533. }
  534. catch( Exception e ) {
  535. editor.remove(key);
  536. }
  537. }
  538. protected void onCreate_Preferences() {
  539. sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
  540. SharedPreferences.Editor editor = sharedPrefs.edit();
  541. PreferenceManager.setDefaultValues( getApplication(), R.xml.preference, true );
  542. // Android: boolean-preferences with their default set to 'false'
  543. // don't get initialized. DO IT OURSELVES
  544. // SOL: http://stackoverflow.com/questions/2874276/initialize-preference-from-xml-in-the-main-activity
  545. if (!sharedPrefs.contains("pref_pinbl"))
  546. editor.putBoolean("pref_pinbl", false);
  547. if (!sharedPrefs.contains("pref_tmpcntns"))
  548. editor.putBoolean("pref_tmpcntns", false);
  549. if (!sharedPrefs.contains("pref_grndr_cnt"))
  550. editor.putInt("pref_grndr_cnt", 0);
  551. if (!sharedPrefs.contains("pref_tmron"))
  552. editor.putInt("pref_tmron", 0);
  553. if (!sharedPrefs.contains("pref_tmroff"))
  554. editor.putInt("pref_tmroff", 0);
  555. if (!sharedPrefs.contains("pref_o0"))
  556. editor.putString("pref_o0", "112");
  557. if (!sharedPrefs.contains("pref_o1"))
  558. editor.putString( "pref_o1", "98" );
  559. if (!sharedPrefs.contains("pref_o2"))
  560. editor.putString( "pref_o2", "118" );
  561. prefTestFloat( sharedPrefs, editor, "pref_tmpsp" );
  562. prefTestFloat( sharedPrefs, editor, "pref_tmpstm" );
  563. prefTestFloat( sharedPrefs, editor, "pref_tmppap" );
  564. prefTestFloat( sharedPrefs, editor, "pref_pd1p" );
  565. prefTestFloat( sharedPrefs, editor, "pref_pd1i" );
  566. prefTestFloat( sharedPrefs, editor, "pref_pd1d" );
  567. prefTestFloat( sharedPrefs, editor, "pref_pd1imn" );
  568. prefTestFloat( sharedPrefs, editor, "pref_pd1imx" );
  569. editor.commit();
  570. }
  571. @Override
  572. protected void onCreate(Bundle savedInstanceState) {
  573. onCreate_Preferences();
  574. super.onCreate(savedInstanceState);
  575. // Why is this here ?
  576. StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
  577. .permitAll().build();
  578. StrictMode.setThreadPolicy(policy);
  579. // deprecated : requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
  580. setContentView(R.layout.activity_main);
  581. logging_enabled = sharedPrefs.getBoolean("pref_ui_logging", false);
  582. setpoint = (TextView) findViewById(R.id.SetPoint);
  583. btemp = (TextView) findViewById(R.id.BTemp);
  584. indicator = (ImageView) findViewById(R.id.Indicator);
  585. logging = (TextView) findViewById(R.id.logging);
  586. background = (ImageView) findViewById(R.id.background);
  587. tempcontrol = (LinearLayout) findViewById(R.id.tempcontrol);
  588. video = findViewById(R.id.video);
  589. progress_bar = (ProgressBar) findViewById( R.id.progress );
  590. teller = 0;
  591. minbutton = (Button) findViewById(R.id.MinButton);
  592. minbutton.setOnClickListener(this);
  593. plusbutton = (Button) findViewById(R.id.PlusButton);
  594. plusbutton.setOnClickListener(this);
  595. meter1 = (Gauge) findViewById(R.id.power);
  596. meter2 = (Gauge) findViewById(R.id.shottimer);
  597. meter1.setTranslationX(20f);
  598. meter1.setTranslationY(-40f);
  599. meter2.setTranslationX(-165f + 20f);
  600. meter2.setTranslationY(-45f + -40f);
  601. tempcontrol.setTranslationY(-40f);
  602. // Against material design guidelines, ugly
  603. //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  604. // getActionBar().setDisplayShowHomeEnabled(true);
  605. // }
  606. //getActionBar().setLogo(R.mipmap.ic_launcher);
  607. //getActionBar().setDisplayUseLogoEnabled(true);
  608. //meter1.setValue(-50);
  609. //meter1.setValue(-50);
  610. if (!sharedPrefs.getBoolean("pref_ui_background", true))
  611. background.setVisibility(View.INVISIBLE);
  612. //background.setImageDrawable( null );
  613. if (sharedPrefs.getBoolean("pref_ui_screenwake", false))
  614. getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  615. // Enable Bluetooth when it is not enabled!
  616. BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  617. if ( mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled() ) {
  618. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  619. startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
  620. }
  621. // http://stackoverflow.com/questions/32708374/bluetooth-le-scanfilters-dont-work-on-android-m
  622. // http://developer.radiusnetworks.com/2015/09/29/is-your-beacon-app-ready-for-android-6.html
  623. final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
  624. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  625. // Android M Permission check

  626. if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  627. final AlertDialog.Builder builder = new AlertDialog.Builder(this);
  628. builder.setTitle("This app needs location access");
  629. builder.setMessage("Please grant location access so meBarista can communicate with your meCoffee in the background.");
  630. builder.setPositiveButton(android.R.string.ok, null);
  631. builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
  632. @Override
  633. public void onDismiss(DialogInterface dialog) {
  634. requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
  635. }
  636. });
  637. builder.show();
  638. }
  639. }
  640. // Start the Barista background service
  641. Intent i = new Intent(this, BaristaService.class);
  642. // i.putExtra("action", "scan");
  643. getApplicationContext().startService(i);
  644. doBindService();
  645. handleintentTimer = new Timer();
  646. handleintentTimer.schedule(new TimerTask() {
  647. @Override
  648. public void run() {
  649. MainActivity.this.runOnUiThread(new Runnable() {
  650. public void run() {
  651. handleintent();
  652. }
  653. });
  654. }
  655. }, 1000);
  656. // Start watchdog timer to detect if connection is lost
  657. indicator_watchdog_timer = new Timer();
  658. indicator_watchdog_timer.schedule(new TimerTask() {
  659. @Override
  660. public void run() {
  661. indicator_watchdog.sendEmptyMessage(0);
  662. }
  663. }, 0, 1000);
  664. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  665. ScreenRecording_onCreate();
  666. }
  667. else
  668. {
  669. MenuItem item = (MenuItem) findViewById(R.id.menu_item_video);
  670. if( item != null )
  671. item.setVisible(false);
  672. this.invalidateOptionsMenu();
  673. }
  674. setProgressBarIndeterminateVisibility(true);
  675. /* TODO: switch to specific function
  676. add menu item
  677. installation_manual = (WebView) findViewById(R.id.installation_manual);
  678. WebSettings webSettings = installation_manual.getSettings();
  679. webSettings.setJavaScriptEnabled(true);
  680. installation_manual.setWebViewClient(new WebViewClient());
  681. installation_manual.loadUrl( "https://mecoffee.nl/mecoffee/installation/?embedded=true" );
  682. */
  683. }
  684. @Override
  685. public boolean onCreateOptionsMenu(Menu menu) {
  686. // Inflate the menu; this adds items to the action bar if it is present.
  687. getMenuInflater().inflate(R.menu.activity_main, menu);
  688. return true;
  689. }
  690. @Override
  691. public void onClick(View v) {
  692. switch (v.getId()) {
  693. case R.id.MinButton:
  694. mBoundService.write(("cmd set tmpsp " + (int) ((curSetpoint - 0.5) * 100) + "\n")); // TODO: remove nl
  695. break;
  696. case R.id.PlusButton:
  697. mBoundService.write(("cmd set tmpsp " + (int) ((curSetpoint + 0.5) * 100) + "\n")); // TODO: remove nl
  698. break;
  699. default:
  700. break;
  701. }
  702. }
  703. // Installation manual
  704. private boolean IM_Open( ) {
  705. /*
  706. if( installation_manual == null ) {
  707. installation_manual = (WebView) findViewById(R.id.installation_manual);
  708. WebSettings webSettings = installation_manual.getSettings();
  709. webSettings.setJavaScriptEnabled(true);
  710. installation_manual.setWebViewClient(new WebViewClient());
  711. installation_manual.loadUrl("https://mecoffee.nl/mecoffee/installation/?embedded=true");
  712. }
  713. installation_manual.setVisibility(WebView.VISIBLE);
  714. meter1.setVisibility(WebView.INVISIBLE);
  715. meter2.setVisibility(WebView.INVISIBLE);
  716. // logging.setVisibility(WebView.INVISIBLE);
  717. btemp.setTextColor(Color.BLACK);
  718. setpoint.setTextColor(Color.BLACK);
  719. //minbutton.setTextColor(Color.BLACK); ziet er niet uit
  720. //plusbutton.setTextColor(Color.BLACK);
  721. */
  722. return true;
  723. }
  724. private boolean IM_Close( ) {
  725. installation_manual.setVisibility( WebView.INVISIBLE );
  726. meter1.setVisibility(WebView.VISIBLE);
  727. btemp.setTextColor(Color.WHITE);
  728. setpoint.setTextColor(Color.WHITE);
  729. //minbutton.setTextColor(Color.WHITE); ziet er niet uit
  730. //plusbutton.setTextColor(Color.WHITE);
  731. return true;
  732. }
  733. private boolean rest_post() {
  734. Toast.makeText(MainActivity.this, "Please wait for your upload to finish...", Toast.LENGTH_LONG).show();
  735. String mecoffee_url = "Something went wrong with uploading the file...";
  736. // http://stackoverflow.com/questions/2793150/using-java-net-urlconnection-to-fire-and-handle-http-requests
  737. try {
  738. String param = "value";
  739. String charset = "utf-8";
  740. String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
  741. String CRLF = "\r\n"; // Line separator required by multipart/form-data.
  742. URLConnection connection = new URL("https://mecoffee.nl/share/post.php").openConnection();
  743. connection.setDoOutput(true);
  744. connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
  745. OutputStream output = connection.getOutputStream();
  746. PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
  747. // Send normal param.
  748. writer.append("--" + boundary).append(CRLF);
  749. writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
  750. writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
  751. writer.append(CRLF).append(param).append(CRLF).flush();
  752. // Send text file.
  753. writer.append("--" + boundary).append(CRLF);
  754. writer.append("Content-Disposition: form-data; name=\"logfile\"; filename=\"" + "logfile" + "\"").append(CRLF);
  755. writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
  756. writer.append(CRLF).flush();
  757. // Files.copy(textFile.toPath(), output);
  758. output.write(mBoundService.log.toString().getBytes());
  759. output.flush(); // Important before continuing with writer!
  760. writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
  761. // End of multipart/form-data.
  762. writer.append("--" + boundary + "--").append(CRLF).flush();
  763. // connection.connect();
  764. InputStream in = connection.getInputStream();
  765. BufferedReader reader = new BufferedReader(new InputStreamReader(in, charset));
  766. for (String line; (line = reader.readLine()) != null; ) {
  767. mecoffee_url = line; //System.out.println(line);
  768. }
  769. } catch (Exception e) {
  770. System.out.println("ex" + e.getMessage());
  771. }
  772. Intent i = new Intent(Intent.ACTION_SEND);
  773. i.setType("text/plain");
  774. i.putExtra(Intent.EXTRA_SUBJECT, "My meCoffee log...");
  775. i.putExtra(Intent.EXTRA_TEXT, "See my espresso log at " + mecoffee_url + "\n\n");
  776. try {
  777. startActivity(Intent.createChooser(i, "Share your meCoffee experience..."));
  778. } catch (ActivityNotFoundException ex) {
  779. Toast.makeText(MainActivity.this, "There are clients installed.", Toast.LENGTH_SHORT).show();
  780. }
  781. return false;
  782. }
  783. public void processRecording() {
  784. String file_location = "/sdcard/Download/screenrecording.mp4";
  785. // http://stackoverflow.com/questions/18603524/share-intent-does-not-work-for-uploading-video-to-youtube
  786. // http://stackoverflow.com/questions/15965246/how-to-upload-video-to-youtube-in-android
  787. MediaScannerConnection.scanFile(this, new String[]{file_location}, null,
  788. new MediaScannerConnection.OnScanCompletedListener() {
  789. public void onScanCompleted(String path, Uri uri) {
  790. Log.d(TAG, "onScanCompleted uri " + uri);
  791. Intent shareIntent = new Intent(
  792. Intent.ACTION_SEND);
  793. shareIntent.setType("video/*");
  794. shareIntent.putExtra(
  795. Intent.EXTRA_SUBJECT, "meCoffee in action on %s");
  796. shareIntent.putExtra(
  797. Intent.EXTRA_TITLE, "meCoffee in action to %s");
  798. shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
  799. shareIntent
  800. .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
  801. startActivity(Intent.createChooser(shareIntent,
  802. /* getString(R.string.str_share_this_video) */ "Do you want to share your video ?"));
  803. }
  804. });
  805. }
  806. // https://developer.android.com/training/permissions/requesting.html
  807. final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
  808. final int PERMISSION_REQUEST_CAMERA = 2;
  809. final int PERMISSION_REQUEST_MICROPHONE = 3;
  810. final int PERMISSION_REQUEST_STORAGE = 4;
  811. @Override
  812. public void onRequestPermissionsResult(int requestCode,
  813. String permissions[], int[] grantResults) {
  814. switch (requestCode) {
  815. case PERMISSION_REQUEST_COARSE_LOCATION: {
  816. // If request is cancelled, the result arrays are empty.
  817. if (grantResults.length > 0
  818. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  819. // permission was granted, yay! Do the
  820. // contacts-related task you need to do.
  821. Log.i(TAG, "Permission Coarse Location granted.");
  822. // TODO:
  823. } else {
  824. // permission denied, boo! Disable the
  825. // functionality that depends on this permission.
  826. }
  827. return;
  828. }
  829. case PERMISSION_REQUEST_CAMERA: {
  830. // If request is cancelled, the result arrays are empty.
  831. if (grantResults.length > 0
  832. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  833. // permission was granted, yay! Do the
  834. // contacts-related task you need to do.
  835. Log.i(TAG, "Permission Camera granted.");
  836. do_the_permission_dance();
  837. } else {
  838. // permission denied, boo! Disable the
  839. // functionality that depends on this permission.
  840. }
  841. return;
  842. }
  843. case PERMISSION_REQUEST_MICROPHONE: {
  844. // If request is cancelled, the result arrays are empty.
  845. if (grantResults.length > 0
  846. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  847. // permission was granted, yay! Do the
  848. // contacts-related task you need to do.
  849. Log.i(TAG, "Permission Microphone granted.");
  850. do_the_permission_dance();
  851. // TODO:
  852. } else {
  853. // permission denied, boo! Disable the
  854. // functionality that depends on this permission.
  855. }
  856. return;
  857. }
  858. case PERMISSION_REQUEST_STORAGE: {
  859. // If request is cancelled, the result arrays are empty.
  860. if (grantResults.length > 0
  861. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  862. // permission was granted, yay! Do the
  863. // contacts-related task you need to do.
  864. Log.i(TAG, "Permission Storage granted, starting video from onRequestPermissionsResult.");
  865. // This is the last permission to be granted to video recording
  866. // It is the only way to get here too: start video recording
  867. cameraToggle();
  868. } else {
  869. // permission denied, boo! Disable the
  870. // functionality that depends on this permission.
  871. }
  872. return;
  873. }
  874. // other 'case' lines to check for other
  875. // permissions this app might request
  876. }
  877. }
  878. public boolean do_the_permission_dance() {
  879. boolean we_are_good = true;
  880. // Android M Permission check

  881. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  882. // Camera
  883. if (this.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
  884. we_are_good = false;
  885. final AlertDialog.Builder builder = new AlertDialog.Builder(this);
  886. builder.setTitle("To display video, meBarista needs access to your camera");
  887. builder.setMessage("Please grant camera access so meBarista can continue into augmented reality.");
  888. builder.setPositiveButton(android.R.string.ok, null);
  889. builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
  890. @Override
  891. public void onDismiss(DialogInterface dialog) {
  892. requestPermissions(new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CAMERA);
  893. // do_the_permission_dance();
  894. }
  895. });
  896. builder.show();
  897. return we_are_good;
  898. }
  899. // Microphone
  900. if (this.checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
  901. we_are_good = false;
  902. final AlertDialog.Builder builder = new AlertDialog.Builder(this);
  903. builder.setTitle("To add sound to your video, meBarista needs access to your microphone");
  904. builder.setMessage("Please grant microphone access so meBarista can hear your delicious espresso being poured into your cup.");
  905. builder.setPositiveButton(android.R.string.ok, null);
  906. builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
  907. @Override
  908. public void onDismiss(DialogInterface dialog) {
  909. requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSION_REQUEST_MICROPHONE);
  910. // do_the_permission_dance();
  911. }
  912. });
  913. builder.show();
  914. return we_are_good;
  915. }
  916. // Storage
  917. if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
  918. we_are_good = false;
  919. final AlertDialog.Builder builder = new AlertDialog.Builder(this);
  920. builder.setTitle("To save or share your video, meBarista needs access to your storage");
  921. builder.setMessage("Please grant storage access so meBarista can get on your cloud.");
  922. builder.setPositiveButton(android.R.string.ok, null);
  923. builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
  924. @Override
  925. public void onDismiss(DialogInterface dialog) {
  926. requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_STORAGE);
  927. }
  928. });
  929. builder.show();
  930. return we_are_good;
  931. }
  932. }
  933. return we_are_good;
  934. }
  935. public boolean cameraToggle() {
  936. if (!do_the_permission_dance())
  937. return false;
  938. // Start and stop video preview & screen recording
  939. if ( cameraToggleStatus == true ) {
  940. Log.i(TAG, "Video stop");
  941. stopScreenSharing();
  942. if( camera != null ) {
  943. camera.setPreviewCallback(null);
  944. camera.stopPreview();
  945. }
  946. if (camera != null) {
  947. Log.i(TAG, "Camera released by GUI action");
  948. // If you don't remove the callback, the activity will minimize
  949. holder.removeCallback(this);
  950. camera.release();
  951. camera = null;
  952. }
  953. background.setVisibility(View.VISIBLE);
  954. video.setVisibility(View.INVISIBLE);
  955. processRecording();
  956. cameraToggleStatus = false;
  957. return true;
  958. }
  959. Log.i(TAG, "Video start");
  960. background.setVisibility(View.INVISIBLE);
  961. video.setVisibility(View.VISIBLE);
  962. SurfaceView cameraView = (SurfaceView) video;
  963. holder = cameraView.getHolder();
  964. holder.addCallback(this);
  965. holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
  966. camera = Camera.open(); // TODO: try java.lang.RuntimeException
  967. if( camera != null ) {
  968. try {
  969. camera.setPreviewDisplay(holder);
  970. } catch (IOException e) {
  971. e.printStackTrace();
  972. }
  973. camera.startPreview();
  974. }
  975. shareScreen();
  976. cameraToggleStatus = true;
  977. return true;
  978. }
  979. private void service_call( String s ) {
  980. Intent i = new Intent(this, BaristaService.class);
  981. i.putExtra("action", s );
  982. startService(i);
  983. }
  984. @Override
  985. public boolean onOptionsItemSelected(MenuItem item) {
  986. switch (item.getItemId()) {
  987. //case R.id.menu_item_screenrecord:
  988. // Log.i(TAG, "Toggle screenrecord");
  989. // if( mScreenSharing )
  990. // stopScreenSharing();
  991. // else
  992. // shareScreen();
  993. // break;
  994. case R.id.menu_item_video:
  995. // Request permissions, bail out if not met
  996. cameraToggle();
  997. break;
  998. case R.id.menu_settings:
  999. Intent a = new Intent(MainActivity.this, SettingsActivity.class);
  1000. startActivity(a);
  1001. break;
  1002. case R.id.menu_scan:
  1003. Intent i2 = new Intent(this, BaristaService.class);
  1004. i2.putExtra("action", "scan");
  1005. startService(i2);
  1006. break;
  1007. case R.id.menu_fw_reset:
  1008. service_call( "fw_reset" );
  1009. break;
  1010. case R.id.menu_fw_stop:
  1011. service_call("fw_stop");
  1012. break;
  1013. case R.id.menu_fw_start:
  1014. service_call("fw_start");
  1015. break;
  1016. case R.id.menu_fw_close:
  1017. service_call("fw_close");
  1018. break;
  1019. case R.id.menu_fw_open:
  1020. service_call("fw_open");
  1021. break;
  1022. case R.id.menu_fw_flash:
  1023. service_call("fw_flash");
  1024. break;
  1025. case R.id.menu_demo:
  1026. mBoundService.fillChartWithDemoData();
  1027. // Set start viewport for demo
  1028. mBoundService.renderer.setXAxisMin(0);
  1029. mBoundService.renderer.setXAxisMax(600);
  1030. mBoundService.renderer.setYAxisMin(10);
  1031. mBoundService.renderer.setYAxisMax(140);
  1032. mChartView.repaint();
  1033. break;
  1034. case R.id.menu_item_share:
  1035. rest_post();
  1036. break;
  1037. /*
  1038. case R.id.menu_im:
  1039. if( installation_manual == null || installation_manual.getVisibility() != WebView.VISIBLE ) {
  1040. IM_Open();
  1041. item.setTitle( "Back to meBarista" );
  1042. }
  1043. else {
  1044. IM_Close( );
  1045. item.setTitle( "Installation manual" );
  1046. }
  1047. break;
  1048. */
  1049. }
  1050. return true;
  1051. }
  1052. public void log(String line) {
  1053. final String out = line;
  1054. //if( ! ( out.contains("address") || out.contains("Address") ) )
  1055. // return ;
  1056. //if( !out.contains( "Memory address to load" ) )
  1057. // return ;
  1058. runOnUiThread(new Runnable() {
  1059. @Override
  1060. public void run() {
  1061. logging.setText((out + "\n" + logging.getText()).substring(0, Math.min(logging.getText().length() + out.length() + 1, 250)));
  1062. }
  1063. });
  1064. }
  1065. @Override
  1066. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  1067. super.onActivityResult(requestCode, resultCode, data);
  1068. switch (requestCode) {
  1069. case REQUEST_ENABLE_BT:
  1070. break;
  1071. case SCREEN_RECORDING_REQUEST_CODE:
  1072. Log.i(TAG_SC, "onActivityResult: getting MediaProjection");
  1073. // So we got permission: get the MediaProjection
  1074. mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
  1075. // and run shareScreen again, which will continue this time
  1076. shareScreen();
  1077. break;
  1078. default:
  1079. break;
  1080. }
  1081. }
  1082. // Implement zoomListener
  1083. public void zoomReset() {
  1084. }
  1085. public void zoomApplied(ZoomEvent e) {
  1086. if (e.isZoomIn()) {
  1087. mBoundService.renderer.setZoomEnabled(true, true);
  1088. mBoundService.renderer.setYAxisMax(140);
  1089. mBoundService.renderer.setYAxisMin(10);
  1090. }
  1091. }
  1092. void handleintent() {
  1093. // Check if we were started with a specific intent:
  1094. Uri intent_uri = getIntent().getData();
  1095. if (intent_uri == null)
  1096. return;
  1097. String datastr = intent_uri.toString();
  1098. if (datastr == null)
  1099. return;
  1100. if (datastr.equals("supportticket")) {
  1101. supportticket();
  1102. this.setIntent(null);
  1103. }
  1104. if (datastr.equals("flashfirmware_V4")) {
  1105. setIntent( null );
  1106. // http://stackoverflow.com/questions/4116110/clearing-intent/38864614#38864614
  1107. flashfirmware( "meCoffee-V4.hex" );
  1108. }
  1109. if (datastr.equals("flashfirmware_V9")) {
  1110. setIntent( null );
  1111. // http://stackoverflow.com/questions/4116110/clearing-intent/38864614#38864614
  1112. flashfirmware( "meCoffee-V9.hex" );
  1113. }
  1114. if (datastr.equals("flashfirmware_V10")) {
  1115. setIntent( null );
  1116. // http://stackoverflow.com/questions/4116110/clearing-intent/38864614#38864614
  1117. flashfirmware( "meCoffee-V10.hex" );
  1118. }
  1119. return;
  1120. }
  1121. void supportticket() {
  1122. SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
  1123. Intent i = new Intent(Intent.ACTION_SEND);
  1124. i.setType("message/rfc822");
  1125. i.putExtra(Intent.EXTRA_EMAIL, new String[]{sharedPref.getString("pref_support_email", "")});
  1126. i.putExtra(Intent.EXTRA_SUBJECT, "My espresso machine is acting weird...");
  1127. i.putExtra(Intent.EXTRA_TEXT, "can you take a look?\n\nkind regards,\n\n");
  1128. // Take screenshot
  1129. RelativeLayout page = (RelativeLayout) findViewById(R.id.root2);
  1130. page.setDrawingCacheEnabled(true);
  1131. page.buildDrawingCache();
  1132. Bitmap bmp = Bitmap.createBitmap(page.getDrawingCache(true));
  1133. page.destroyDrawingCache();
  1134. page.setDrawingCacheEnabled(false);
  1135. File file = new File(getApplicationContext().getFilesDir(), "screenshot.png");
  1136. file.setReadable(true, false);
  1137. if (file.exists()) {
  1138. file.delete();
  1139. file = new File(getApplicationContext().getFilesDir(), "screenshot.png");
  1140. file.setReadable(true, false);
  1141. //Log.e("file exist", "" + file + ",Bitmap= " + filename);
  1142. }
  1143. try {
  1144. // FileOutputStream out = new FileOutputStream(file);
  1145. FileOutputStream out = openFileOutput("screenshot.png", Context.MODE_WORLD_READABLE);
  1146. bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
  1147. out.flush();
  1148. out.close();
  1149. } catch (Exception e) {
  1150. e.printStackTrace();
  1151. }
  1152. i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
  1153. try {
  1154. startActivity(Intent.createChooser(i, "Send mail..."));
  1155. } catch (ActivityNotFoundException ex) {
  1156. Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
  1157. }
  1158. return;
  1159. }
  1160. void flashfirmware( String firmware_file ) {
  1161. Intent i_fw = new Intent(this, BaristaService.class);
  1162. // moet dit wel? mBoundService.stop();
  1163. logging.setText("firmware intent");
  1164. i_fw.putExtra("action", "firmware");
  1165. i_fw.putExtra( "firmware_file", firmware_file );
  1166. startService(i_fw);
  1167. }
  1168. // Screen recording
  1169. void ScreenRecording_onCreate() {
  1170. if (mSurfaceView != null)
  1171. return;
  1172. // From the onCreate
  1173. DisplayMetrics metrics = new DisplayMetrics();
  1174. getWindowManager().getDefaultDisplay().getMetrics(metrics);
  1175. mScreenDensity = metrics.densityDpi;
  1176. // mSurfaceView = (SurfaceView) findViewById(R.id.screenrecording);
  1177. mSurfaceView = new SurfaceView(this);
  1178. mSurface = mSurfaceView.getHolder().getSurface();
  1179. mProjectionManager =
  1180. (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
  1181. // From ResolutionSelector
  1182. Resolution r = RESOLUTIONS.get(0); // (Resolution) parent.getItemAtPosition(pos);
  1183. ViewGroup.LayoutParams lp = mSurfaceView.getLayoutParams();
  1184. if (getResources().getConfiguration().orientation
  1185. == Configuration.ORIENTATION_LANDSCAPE) {
  1186. mDisplayHeight = r.y;
  1187. mDisplayWidth = r.x;
  1188. } else {
  1189. mDisplayHeight = r.x;
  1190. mDisplayWidth = r.y;
  1191. }
  1192. if (false) {
  1193. lp.height = mDisplayHeight;
  1194. lp.width = mDisplayWidth;
  1195. mSurfaceView.setLayoutParams(lp);
  1196. }
  1197. }
  1198. private void shareScreen() {
  1199. if (mSurface == null) {
  1200. return;
  1201. }
  1202. if (mMediaProjection == null) {
  1203. // startActivityForResult( mProjectionManager.getScreenCaptureIntent(), PERMISSION_CODE );
  1204. // Log.i( TAG, "Started Screen Capture" );
  1205. Log.i(TAG_SC, "Request permission for MediaProjection");
  1206. startActivityForResult(mProjectionManager.createScreenCaptureIntent(), SCREEN_RECORDING_REQUEST_CODE);
  1207. return;
  1208. }
  1209. Log.i(TAG_SC, "Started");
  1210. mScreenSharing = true;
  1211. // TODO: not sure if belongs here
  1212. ScreenRecording_initRecorder();
  1213. mVirtualDisplay = createVirtualDisplay();
  1214. Log.i(TAG_SC, "Start MediaRecorder");
  1215. mMediaRecorder.start();
  1216. }
  1217. private void stopScreenSharing() {
  1218. Log.i(TAG_SC, "Stopped");
  1219. mScreenSharing = false;
  1220. if (mVirtualDisplay == null) {
  1221. return;
  1222. }
  1223. Log.i(TAG_SC, "Stop MediaRecorder");
  1224. try {
  1225. mMediaRecorder.stop();
  1226. } catch (Exception e) {
  1227. e.printStackTrace();
  1228. }
  1229. mMediaRecorder.reset();
  1230. mMediaRecorder = null;
  1231. mVirtualDisplay.release();
  1232. mVirtualDisplay = null;
  1233. }
  1234. private VirtualDisplay createVirtualDisplay() {
  1235. return mMediaProjection.createVirtualDisplay("ScreenSharingDemo",
  1236. mDisplayWidth, mDisplayHeight, mScreenDensity,
  1237. DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
  1238. mMediaRecorder.getSurface(), null /*Callbacks*/, null /*Handler*/);
  1239. }
  1240. private void ScreenRecording_initRecorder() {
  1241. try {
  1242. mMediaRecorder = new MediaRecorder();
  1243. mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
  1244. mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
  1245. mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
  1246. mMediaRecorder.setOutputFile(Environment
  1247. .getExternalStoragePublicDirectory(Environment
  1248. .DIRECTORY_DOWNLOADS) + "/screenrecording.mp4");
  1249. Log.i(TAG_SC, "Dimensions: " + mDisplayWidth + "x" + mDisplayHeight);
  1250. mMediaRecorder.setVideoSize(mDisplayWidth, mDisplayHeight);
  1251. mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
  1252. mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
  1253. mMediaRecorder.setVideoEncodingBitRate(1024 * 1000);
  1254. mMediaRecorder.setVideoFrameRate(30);
  1255. //int rotation = getWindowManager().getDefaultDisplay().getRotation();
  1256. //int orientation = ORIENTATIONS.get(rotation + 90);
  1257. //mMediaRecorder.setOrientationHint(orientation);
  1258. mMediaRecorder.prepare();
  1259. } catch (IOException e) {
  1260. e.printStackTrace();
  1261. }
  1262. }
  1263. }