MainActivity.java 59 KB

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

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

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