MainActivity.java 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773
  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. float preinfusionDelay = 0, preinfusionPump = 0; // This is a float because SliderPreference returns a float
  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 st_secs = (SystemClock.uptimeMillis() - startTime) /* 1000.0f */;
  237. if( sharedPrefs.getBoolean("pref_pinbl", false) ) {
  238. if( st_secs >= preinfusionPump && st_secs <= preinfusionPump + preinfusionDelay )
  239. st_secs = preinfusionPump;
  240. if( st_secs > preinfusionPump + preinfusionDelay )
  241. st_secs -= preinfusionDelay;
  242. }
  243. st_secs /= 1000.0f;
  244. meter2.setValue( clamp( st_secs, 0, 45) );
  245. customHandler.postDelayed( this, 500 );
  246. }
  247. };
  248. // This handler checks the last time a message was received
  249. // If it was too long ago, the indicator will be switched to off
  250. // and the readings will be grayed?
  251. final Handler indicator_watchdog = new Handler() {
  252. @Override
  253. public void handleMessage(Message msg) {
  254. if (System.currentTimeMillis() - last_message > 3000) {
  255. indicator.setImageResource(R.drawable.silvia_off);
  256. btemp.setText("---,-- °");
  257. setpoint.setText("---,-- °");
  258. meter1.setValue(0);
  259. // bConnection.reset();
  260. }
  261. }
  262. };
  263. // Bookkeep when the graph handles touch events: do not repaint when in touchevent
  264. @Override
  265. public boolean dispatchTouchEvent(MotionEvent event) {
  266. int eventaction = event.getAction();
  267. switch (eventaction) {
  268. case MotionEvent.ACTION_DOWN:
  269. // finger touches the screen
  270. lock_graph = true;
  271. break;
  272. case MotionEvent.ACTION_MOVE:
  273. // finger moves on the screen
  274. break;
  275. case MotionEvent.ACTION_UP:
  276. // finger leaves the screen
  277. lock_graph = false;
  278. break;
  279. }
  280. super.dispatchTouchEvent(event);
  281. return false;
  282. }
  283. private void ShotTimer_show() {
  284. final float scale = getBaseContext().getResources().getDisplayMetrics().density;
  285. ViewGroup.LayoutParams lp = meter1.getLayoutParams();
  286. lp.width = (int) (175 * scale);
  287. lp.height = (int) (175 * scale);
  288. meter1.setLayoutParams(lp);
  289. meter2.setVisibility(View.VISIBLE);
  290. }
  291. private void ShotTimer_hide() {
  292. final float scale = getBaseContext().getResources().getDisplayMetrics().density;
  293. ViewGroup.LayoutParams lp = meter1.getLayoutParams();
  294. meter2.setValue(0f);
  295. lp.width = (int) (200 * scale);
  296. lp.height = (int) (200 * scale);
  297. meter1.setLayoutParams(lp);
  298. meter2.setVisibility(View.GONE);
  299. }
  300. private final Handler mHandler = new Handler() {
  301. @Override
  302. public void handleMessage(Message msg) {
  303. String message = (String) msg.obj;
  304. if (message == null)
  305. return;
  306. String parts[] = message.split(" ");
  307. switch (msg.what) {
  308. case SPINNER_ON:
  309. Log.i( TAG, "Showing spinner" );
  310. progress_bar.setVisibility( View.VISIBLE );
  311. break;
  312. case SPINNER_OFF:
  313. Log.i( TAG, "Hiding spinner" );
  314. progress_bar.setVisibility( View.GONE );
  315. break;
  316. case DEVICE_ON:
  317. // Change indicator to on
  318. indicator.setImageResource(R.drawable.silvia_on);
  319. setTitle("meBarista: " + (String) msg.obj);
  320. break;
  321. case UPDATE:
  322. mChartView.repaint();
  323. break;
  324. case DEVICE_OFF:
  325. // Change indicator to off
  326. indicator.setImageResource(R.drawable.silvia_off);
  327. // Clear all readings
  328. break;
  329. case MESSAGE_TOAST:
  330. Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show();
  331. break;
  332. case MESSAGE_READ:
  333. last_message = System.currentTimeMillis();
  334. indicator.setImageResource(R.drawable.silvia_on);
  335. if( logging_enabled ) {
  336. log( message );
  337. }
  338. // Graph is not enabled?
  339. if (findViewById( R.id.graph ) == null)
  340. break;
  341. if (message.startsWith("pid ")) {
  342. try {
  343. float res = Integer.parseInt(parts[1]) + Integer.parseInt(parts[2]) + Integer.parseInt(parts[3]);
  344. if (parts.length >= 5)
  345. res += Integer.parseInt(parts[4]);
  346. res = res / 65535 * 100.0f;
  347. meter1.setValue(Math.min(res, 100.0f));
  348. //System.out.println( "updated graph" );
  349. return;
  350. } catch (Exception e) {
  351. Log.e(TAG, "Failed to parse PID message");
  352. }
  353. }
  354. if (message.startsWith("dem ")) {
  355. time_scale = Integer.parseInt(parts[1]);
  356. }
  357. if (message.startsWith("sht ")) {
  358. /* try { */
  359. int shottime = Integer.parseInt(parts[2]);
  360. if (shottime == 0) {
  361. meter2.setValue(0f);
  362. ShotTimer_show();
  363. startTime = SystemClock.uptimeMillis();
  364. // Setting can be changed from multiple locations: get it here
  365. preinfusionDelay = 0;
  366. preinfusionPump = 0;
  367. if (sharedPrefs.getBoolean("pref_pinbl", false)) {
  368. preinfusionPump = sharedPrefs.getFloat( "pref_pistrt", 0);
  369. preinfusionDelay = sharedPrefs.getFloat("pref_piprd", 0);
  370. if( mBoundService.legacy ) {
  371. preinfusionDelay = preinfusionDelay * 1000;
  372. preinfusionPump = preinfusionPump * 1000;
  373. }
  374. }
  375. System.out.println("PI Delay " + preinfusionDelay);
  376. customHandler.postDelayed(updateTimerThread, 1000);
  377. } else {
  378. customHandler.removeCallbacks(updateTimerThread);
  379. // if shottime <= pipump : check setting if to increase
  380. // if shottime > pipump : check setting for piprd
  381. System.out.println( "Shot timer update " + shottime );
  382. // Init with normal use case : no PI
  383. float st_secs = shottime;
  384. // Adjust for PI
  385. if( sharedPrefs.getBoolean("pref_pinbl", false) ) {
  386. if( st_secs >= preinfusionPump && st_secs <= preinfusionPump + preinfusionDelay )
  387. st_secs = preinfusionPump;
  388. if( st_secs > preinfusionPump + preinfusionDelay )
  389. st_secs -= preinfusionDelay;
  390. }
  391. // Convert millisecs to seconds
  392. st_secs /= 1000.0f;
  393. meter2.setValue( clamp(st_secs, 0, 45) );
  394. // Set timer to hide gauge after 30 secs
  395. customHandler.postDelayed(new Runnable() {
  396. public void run() {
  397. ShotTimer_hide();
  398. }
  399. }, 30 * 1000);
  400. }
  401. /* } catch (Exception e) {
  402. Log.e(TAG, "Failed to parse SHT message" + e.getMessage());
  403. } */
  404. }
  405. if (message.startsWith("T ") || message.startsWith("tmp ")) {
  406. try {
  407. // renderer.setPanLimits( new double[] { 0, max( mBoundService.teller, 100 ), -10, 120 } );
  408. if (!lock_graph &&
  409. mBoundService.teller > mBoundService.renderer.getXAxisMin() &&
  410. mBoundService.teller <= mBoundService.renderer.getXAxisMax() + 50) {
  411. double cur_width = mBoundService.renderer.getXAxisMax() - mBoundService.renderer.getXAxisMin();
  412. mBoundService.renderer.setXAxisMin(mBoundService.teller - cur_width);
  413. mBoundService.renderer.setXAxisMax(mBoundService.teller);
  414. //mBoundService.renderer.setXAxisMin( mBoundService.gdataset.getSeries()[0].getMinX() );
  415. //mBoundService.renderer.setXAxisMax( mBoundService.gdataset.getSeries()[0].getMaxX() );
  416. }
  417. double[] panlimits = mBoundService.renderer.getPanLimits();
  418. //panlimits[0] = mBoundService.gdataset.getSeries()[0].getMinX() - 30 ;
  419. panlimits[1] = mBoundService.teller + 30;
  420. mBoundService.renderer.setPanLimits(panlimits);
  421. double[] zoomlimits = mBoundService.renderer.getZoomLimits();
  422. //panlimits[0] = mBoundService.gdataset.getSeries()[0].getMinX() - 30 ;
  423. zoomlimits[1] = Math.max(600, mBoundService.teller + 30);
  424. mBoundService.renderer.setZoomLimits(zoomlimits);
  425. double yrange = mBoundService.renderer.getYAxisMax() - mBoundService.renderer.getYAxisMin();
  426. if ((int) yrange == 150)
  427. mBoundService.renderer.setZoomEnabled(true, false);
  428. String[] parts2 = message.replaceAll("T ", "").replaceAll("tmp ", "").replaceAll("\n", "").split(" ");
  429. if (parts2.length >= 3) {
  430. // Double.parseDouble(parts[1]) / 100.0
  431. DecimalFormat f = new DecimalFormat("#0.00");
  432. double temp = Double.parseDouble(parts2[2]) / 100.0;
  433. double sp = Double.parseDouble(parts2[1]) / 100.0;
  434. btemp.setText(f.format(temp) + " °");
  435. setpoint.setText(f.format(sp) + " °");
  436. curSetpoint = sp;
  437. }
  438. if (!lock_graph /* &&
  439. mBoundService.teller > mBoundService.renderer.getXAxisMin() &&
  440. mBoundService.teller <= mBoundService.renderer.getXAxisMax() + 5 */)
  441. mChartView.repaint();
  442. } catch (Exception e) {
  443. Log.e(TAG, "Failed to parse TMP message");
  444. }
  445. }
  446. break;
  447. default:
  448. break;
  449. }
  450. }
  451. };
  452. public void execute2(Context context) {
  453. // Don't create the graph if it is disabled in the preference
  454. SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
  455. if (!sharedPref.getBoolean("pref_ui_graph_enable", true))
  456. return;
  457. RelativeLayout layout = (RelativeLayout) findViewById(R.id.achart);
  458. mChartView = ChartFactory.getTimeChartView(this, mBoundService.gdataset, mBoundService.renderer, "mm:ss");
  459. mChartView.setId(R.id.graph);
  460. //mChartView.setVisibility(View.INVISIBLE);
  461. layout.addView(mChartView);
  462. //
  463. // , new LayoutParams(LayoutParams.MATCH_PARENT,
  464. // LayoutParams.MATCH_PARENT, LayoutParams.));
  465. }
  466. private BaristaService mBoundService;
  467. private Messenger mBoundMsg;
  468. private ServiceConnection mConnection = new ServiceConnection() {
  469. public void onServiceConnected(ComponentName className, IBinder service) {
  470. // This is called when the connection with the service has been
  471. // established, giving us the service object we can use to
  472. // interact with the service. Because we have bound to a explicit
  473. // service that we know is running in our own process, we can
  474. // cast its IBinder to a concrete class and directly access it.
  475. mBoundService = ((BaristaService.LocalBinder) service).getService();
  476. mBoundService.setHandler(mHandler, MainActivity.this);
  477. // Tell the user about this for our demo.
  478. //Toast.makeText(Binding.this, R.string.local_service_connected,
  479. // Toast.LENGTH_SHORT).show();
  480. execute2(MainActivity.this);
  481. // mBoundService.fillChartWithDemoData();
  482. service_call( "scan" );
  483. }
  484. public void onServiceDisconnected(ComponentName className) {
  485. // This is called when the connection with the service has been
  486. // unexpectedly disconnected -- that is, its process crashed.
  487. // Because it is running in our same process, we should never
  488. // see this happen.
  489. mBoundService = null;
  490. //Toast.makeText(Binding.this, R.string.local_service_disconnected,
  491. // Toast.LENGTH_SHORT).show();
  492. }
  493. };
  494. void doBindService() {
  495. // Establish a connection with the service. We use an explicit
  496. // class name because we want a specific service implementation that
  497. // we know will be running in our own process (and thus won't be
  498. // supporting component replacement by other applications).
  499. bindService(new Intent(MainActivity.this,
  500. BaristaService.class), mConnection, Context.BIND_AUTO_CREATE);
  501. //mIsBound = true;
  502. }
  503. void doUnbindService() {
  504. //if (mIsBound) {
  505. // Detach our existing connection.
  506. unbindService(mConnection);
  507. // mIsBound = false;
  508. //}
  509. }
  510. /**
  511. * Handler of incoming messages from service.
  512. */
  513. class IncomingHandler extends Handler {
  514. @Override
  515. public void handleMessage(Message msg) {
  516. switch (msg.what) {
  517. case BaristaService.UPDATE:
  518. // mCallbackText.setText("Received from service: " + msg.arg1);
  519. mChartView.repaint();
  520. break;
  521. default:
  522. super.handleMessage(msg);
  523. }
  524. }
  525. }
  526. final Messenger mMessenger = new Messenger(new IncomingHandler());
  527. @Override
  528. protected void onResume() {
  529. sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
  530. background.setVisibility(sharedPrefs.getBoolean("pref_ui_background", true) ? View.VISIBLE : View.INVISIBLE);
  531. if (sharedPrefs.getBoolean("pref_ui_screenwake", false))
  532. getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  533. else
  534. getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  535. logging_enabled = sharedPrefs.getBoolean("pref_ui_logging", false);
  536. if (mBoundService != null)
  537. mBoundService.showSecondSensor(sharedPrefs.getBoolean("pref_ui_second_sensor", false));
  538. super.onResume();
  539. }
  540. @Override
  541. protected void onDestroy() {
  542. Log.i( TAG, "onDestroy" );
  543. if( mBoundService != null && mBoundService.blehandler != null && mBoundService.blehandler.mBluetoothGatt != null ) {
  544. mBoundService.blehandler.mBluetoothGatt.disconnect();
  545. mBoundService.blehandler.mBluetoothGatt.close();
  546. }
  547. doUnbindService();
  548. Intent i = new Intent(this, BaristaService.class);
  549. getApplicationContext().stopService(i);
  550. if (sharedPrefs.getBoolean("pref_bt_disable", false)) {
  551. BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  552. if (mBluetoothAdapter.isEnabled())
  553. mBluetoothAdapter.disable();
  554. }
  555. super.onDestroy();
  556. }
  557. private void prefTestFloat( SharedPreferences sharedPrefs, SharedPreferences.Editor editor, String key ) {
  558. try {
  559. float val = sharedPrefs.getFloat(key, -42);
  560. }
  561. catch( Exception e ) {
  562. editor.remove(key);
  563. }
  564. }
  565. protected void onCreate_Preferences() {
  566. sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
  567. SharedPreferences.Editor editor = sharedPrefs.edit();
  568. PreferenceManager.setDefaultValues( getApplication(), R.xml.preference, true );
  569. // Android: boolean-preferences with their default set to 'false'
  570. // don't get initialized. DO IT OURSELVES
  571. // SOL: http://stackoverflow.com/questions/2874276/initialize-preference-from-xml-in-the-main-activity
  572. if (!sharedPrefs.contains("pref_pinbl"))
  573. editor.putBoolean("pref_pinbl", false);
  574. if (!sharedPrefs.contains("pref_tmpcntns"))
  575. editor.putBoolean("pref_tmpcntns", false);
  576. if (!sharedPrefs.contains("pref_grndr_cnt"))
  577. editor.putInt("pref_grndr_cnt", 0);
  578. if (!sharedPrefs.contains("pref_tmron"))
  579. editor.putInt("pref_tmron", 0);
  580. if (!sharedPrefs.contains("pref_tmroff"))
  581. editor.putInt("pref_tmroff", 0);
  582. if (!sharedPrefs.contains("pref_o0"))
  583. editor.putString("pref_o0", "112");
  584. if (!sharedPrefs.contains("pref_o1"))
  585. editor.putString( "pref_o1", "98" );
  586. if (!sharedPrefs.contains("pref_o2"))
  587. editor.putString( "pref_o2", "118" );
  588. prefTestFloat( sharedPrefs, editor, "pref_tmpsp" );
  589. prefTestFloat( sharedPrefs, editor, "pref_tmpstm" );
  590. prefTestFloat( sharedPrefs, editor, "pref_tmppap" );
  591. prefTestFloat( sharedPrefs, editor, "pref_pd1p" );
  592. prefTestFloat( sharedPrefs, editor, "pref_pd1i" );
  593. prefTestFloat( sharedPrefs, editor, "pref_pd1d" );
  594. prefTestFloat( sharedPrefs, editor, "pref_pd1imn" );
  595. prefTestFloat( sharedPrefs, editor, "pref_pd1imx" );
  596. editor.commit();
  597. }
  598. @Override
  599. protected void onCreate(Bundle savedInstanceState) {
  600. onCreate_Preferences();
  601. super.onCreate(savedInstanceState);
  602. // Why is this here ?
  603. StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
  604. .permitAll().build();
  605. StrictMode.setThreadPolicy(policy);
  606. // deprecated : requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
  607. setContentView(R.layout.activity_main);
  608. logging_enabled = sharedPrefs.getBoolean("pref_ui_logging", false);
  609. setpoint = (TextView) findViewById(R.id.SetPoint);
  610. btemp = (TextView) findViewById(R.id.BTemp);
  611. indicator = (ImageView) findViewById(R.id.Indicator);
  612. logging = (TextView) findViewById(R.id.logging);
  613. background = (ImageView) findViewById(R.id.background);
  614. tempcontrol = (LinearLayout) findViewById(R.id.tempcontrol);
  615. video = findViewById(R.id.video);
  616. progress_bar = (ProgressBar) findViewById( R.id.progress );
  617. teller = 0;
  618. minbutton = (Button) findViewById(R.id.MinButton);
  619. minbutton.setOnClickListener(this);
  620. plusbutton = (Button) findViewById(R.id.PlusButton);
  621. plusbutton.setOnClickListener(this);
  622. meter1 = (Gauge) findViewById(R.id.power);
  623. meter2 = (Gauge) findViewById(R.id.shottimer);
  624. meter1.setTranslationX(20f);
  625. meter1.setTranslationY(-40f);
  626. meter2.setTranslationX(-165f + 20f);
  627. meter2.setTranslationY(-45f + -40f);
  628. tempcontrol.setTranslationY(-40f);
  629. // Against material design guidelines, ugly
  630. //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  631. // getActionBar().setDisplayShowHomeEnabled(true);
  632. // }
  633. //getActionBar().setLogo(R.mipmap.ic_launcher);
  634. //getActionBar().setDisplayUseLogoEnabled(true);
  635. //meter1.setValue(-50);
  636. //meter1.setValue(-50);
  637. if (!sharedPrefs.getBoolean("pref_ui_background", true))
  638. background.setVisibility(View.INVISIBLE);
  639. //background.setImageDrawable( null );
  640. if (sharedPrefs.getBoolean("pref_ui_screenwake", false))
  641. getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  642. // Enable Bluetooth when it is not enabled!
  643. BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  644. if ( mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled() ) {
  645. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  646. startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
  647. }
  648. // http://stackoverflow.com/questions/32708374/bluetooth-le-scanfilters-dont-work-on-android-m
  649. // http://developer.radiusnetworks.com/2015/09/29/is-your-beacon-app-ready-for-android-6.html
  650. final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
  651. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  652. // Android M Permission check

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

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