Info @ meCoffee лет назад: 6
Сommit
4891bf4909
60 измененных файлов с 17721 добавлено и 0 удалено
  1. 61 0
      .gitignore
  2. 64 0
      AndroidManifest.xml
  3. 339 0
      LICENSE.txt
  4. 2 0
      README.md
  5. 3891 0
      assets/56273d393cab0
  6. 1659 0
      assets/meCoffee-V10.hex
  7. 1472 0
      assets/meCoffee-V4.hex
  8. 1627 0
      assets/meCoffee-V9.hex
  9. 66 0
      build.gradle
  10. 2 0
      libs/SliderPreference/.gitattributes
  11. 3 0
      libs/SliderPreference/.gitignore
  12. 16 0
      libs/SliderPreference/AndroidManifest.xml
  13. 7 0
      libs/SliderPreference/LICENSE.txt
  14. 127 0
      libs/SliderPreference/README.md
  15. 15 0
      libs/SliderPreference/build.gradle
  16. 3 0
      libs/SliderPreference/example/.gitignore
  17. 25 0
      libs/SliderPreference/example/AndroidManifest.xml
  18. 17 0
      libs/SliderPreference/example/res/values/strings.xml
  19. 10 0
      libs/SliderPreference/example/res/xml/preferences.xml
  20. 29 0
      libs/SliderPreference/example/src/net/jayschwa/android/preference/SliderPreferenceExample/ExampleActivity.java
  21. 74 0
      libs/SliderPreference/res/layout/slider_preference_dialog.xml
  22. 21 0
      libs/SliderPreference/res/values/attrs.xml
  23. BIN
      libs/SliderPreference/screenshot.png
  24. 221 0
      libs/SliderPreference/src/net/jayschwa/android/preference/SliderPreference.java
  25. BIN
      libs/achartengine-1.2.0.jar
  26. BIN
      libs/android-support-v4.jar
  27. BIN
      res/drawable-hdpi/coffee.jpg
  28. BIN
      res/drawable-hdpi/ic_menu_share.png
  29. BIN
      res/drawable-hdpi/icon3.png
  30. BIN
      res/drawable-hdpi/silvia_off.png
  31. BIN
      res/drawable-hdpi/silvia_on.png
  32. BIN
      res/drawable-ldpi/icon3.png
  33. BIN
      res/drawable-mdpi/icon3.png
  34. BIN
      res/drawable-xhdpi/icon3.png
  35. BIN
      res/drawable-xhdpi/plastic.jpg
  36. 248 0
      res/layout/activity_main.xml
  37. 81 0
      res/menu/activity_main.xml
  38. 11 0
      res/values-v11/styles.xml
  39. 12 0
      res/values-v14/styles.xml
  40. 13 0
      res/values-v22/styles.xml
  41. 136 0
      res/values/array.xml
  42. 50 0
      res/values/attrs.xml
  43. 16 0
      res/values/colors.xml
  44. 6 0
      res/values/ids.xml
  45. 27 0
      res/values/strings.xml
  46. 20 0
      res/values/styles.xml
  47. 893 0
      res/xml/preference.xml
  48. 796 0
      res/xml/preference_legacy.xml
  49. 3 0
      settings.gradle
  50. 553 0
      src/nl/digitalthings/mebarista/BLEHandler.java
  51. 560 0
      src/nl/digitalthings/mebarista/BTHandler.java
  52. 1506 0
      src/nl/digitalthings/mebarista/BaristaService.java
  53. 26 0
      src/nl/digitalthings/mebarista/EditTextPreferenceWithSummary.java
  54. 794 0
      src/nl/digitalthings/mebarista/Gauge.java
  55. 30 0
      src/nl/digitalthings/mebarista/ListPreferenceWithSummary.java
  56. 67 0
      src/nl/digitalthings/mebarista/Logx.java
  57. 1726 0
      src/nl/digitalthings/mebarista/MainActivity.java
  58. 110 0
      src/nl/digitalthings/mebarista/STK500.java
  59. 134 0
      src/nl/digitalthings/mebarista/SettingsActivity.java
  60. 152 0
      src/nl/digitalthings/mebarista/TimePreference.java

+ 61 - 0
.gitignore

@@ -0,0 +1,61 @@
+# http://stackoverflow.com/questions/16736856/what-should-be-in-my-gitignore-for-an-android-studio-project 
+
+#built application files
+*.apk
+*.ap_
+
+# files for the dex VM
+*.dex
+
+# Java class files
+*.class
+
+# generated files
+bin/
+gen/
+
+# Local configuration file (sdk path, etc)
+local.properties
+
+# Windows thumbnail db
+Thumbs.db
+
+# OSX files
+.DS_Store
+
+# Eclipse project files
+.classpath
+.project
+
+# Android Studio
+*.iml
+.idea
+#.idea/workspace.xml - remove # and delete .idea if it better suit your needs.
+.gradle
+build/
+
+out/
+/*/out
+/*/*/build
+/*/*/production
+*.iws
+*.ipr
+*~
+*.swp
+
+.gradle
+/local.properties
+/.idea/workspace.xml
+/.idea/libraries
+.DS_Store
+/build
+
+.settings/
+proguard_logs/
+my-release-key.keystore
+proguard*
+gradle/
+gradlew
+gradlew.bat
+project.properties
+

+ 64 - 0
AndroidManifest.xml

@@ -0,0 +1,64 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="nl.digitalthings.mebarista"
+    android:versionCode="35"
+    android:versionName="v7.beta35" >
+
+    <uses-sdk
+        android:minSdkVersion="11"
+        android:targetSdkVersion="23" />
+
+
+    <uses-permission android:name="android.permission.BLUETOOTH"/>
+    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
+
+    <uses-permission android:name="android.permission.INTERNET" />
+
+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
+    <!-- uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" / -->
+
+    <uses-permission android:name="android.permission.CAPTURE_VIDEO_OUTPUT" />
+    <uses-permission android:name="android.permission.RECORD_AUDIO" />
+    <uses-permission android:name="android.permission.RECORD_VIDEO" android:required="false" />
+    <uses-permission android:name="android.permission.CAMERA" />
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+
+    <uses-feature android:name="android.hardware.camera2" android:required="false" />
+
+    <uses-feature android:name="android.hardware.camera" android:required="false" />
+    <uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
+
+    <uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
+
+    <application
+        android:allowBackup="true"
+        android:icon="@drawable/icon3"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name="nl.digitalthings.mebarista.MainActivity"
+            android:configChanges="orientation|screenSize"
+            android:hardwareAccelerated="true"
+            android:label="@string/app_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+
+        <activity
+            android:name="nl.digitalthings.mebarista.SettingsActivity"
+            android:configChanges="orientation|screenSize"
+            android:hardwareAccelerated="true"
+            android:label="@string/app_name" >
+        </activity>
+
+        <service android:name=".BaristaService"
+             />
+
+    </application>
+
+
+
+</manifest>

+ 339 - 0
LICENSE.txt

@@ -0,0 +1,339 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                            NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.

+ 2 - 0
README.md

@@ -0,0 +1,2 @@
+First public meBarista for Android repo : https://mecoffee.nl/mebarista/
+

Разница между файлами не показана из-за своего большого размера
+ 3891 - 0
assets/56273d393cab0


Разница между файлами не показана из-за своего большого размера
+ 1659 - 0
assets/meCoffee-V10.hex


Разница между файлами не показана из-за своего большого размера
+ 1472 - 0
assets/meCoffee-V4.hex


Разница между файлами не показана из-за своего большого размера
+ 1627 - 0
assets/meCoffee-V9.hex


+ 66 - 0
build.gradle

@@ -0,0 +1,66 @@
+buildscript {
+    repositories {
+        jcenter()
+        mavenCentral()
+    }
+    dependencies {
+        classpath 'com.android.tools.build:gradle:1.5.0'
+    }
+}
+apply plugin: 'com.android.application'
+
+repositories {
+    mavenCentral()
+}
+
+dependencies {
+    compile fileTree(include: ['*.jar'], dir: 'libs')
+    // compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
+    //compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
+    //compile 'org.apache.httpcomponents:httpmime:4.3.6'
+    compile project(':SliderPreference')
+}
+
+android {
+    compileSdkVersion 23
+    buildToolsVersion '23.0.2'
+    sourceSets {
+        main {
+            manifest.srcFile 'AndroidManifest.xml'
+            java.srcDirs = ['src']
+            resources.srcDirs = ['src']
+            aidl.srcDirs = ['src']
+            renderscript.srcDirs = ['src']
+            res.srcDirs = ['res']
+            assets.srcDirs = ['assets']
+        }
+
+        // Move the tests to tests/java, tests/res, etc...
+        instrumentTest.setRoot('tests')
+
+        // Move the build types to build-types/<type>
+        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
+        // This moves them out of them default location under src/<type>/... which would
+        // conflict with src/ being used by the main source set.
+        // Adding new build types or product flavors should be accompanied
+        // by a similar customization.
+        debug.setRoot('build-types/debug')
+        release.setRoot('build-types/release')
+
+        packagingOptions {
+            exclude 'META-INF/NOTICE'
+            exclude 'META-INF/LICENSE'
+        }
+
+    }
+    // http://stackoverflow.com/questions/32153318/httpclient-wont-import-in-android-studio
+    useLibrary 'org.apache.http.legacy'
+    buildTypes {
+        release {
+            zipAlignEnabled true
+        }
+    }
+}
+dependencies {
+    // compile 'com.google.android.gms:play-services-appindexing:8.1.0'
+}

+ 2 - 0
libs/SliderPreference/.gitattributes

@@ -0,0 +1,2 @@
+# Auto detect text files and perform LF normalization
+* text=auto

+ 3 - 0
libs/SliderPreference/.gitignore

@@ -0,0 +1,3 @@
+/.settings
+/bin
+/gen

+ 16 - 0
libs/SliderPreference/AndroidManifest.xml

@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+Copyright 2012 Jay Weisskopf
+
+Licensed under the MIT License (see LICENSE.txt)
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="net.jayschwa.android.preference"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="1"
+        android:targetSdkVersion="21" />
+
+</manifest>

+ 7 - 0
libs/SliderPreference/LICENSE.txt

@@ -0,0 +1,7 @@
+Copyright 2012 Jay Weisskopf
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 127 - 0
libs/SliderPreference/README.md

@@ -0,0 +1,127 @@
+Android Slider Preference Library
+=================================
+
+![A dialog-based preference that provides slider widget functionality. Useful for settings where the range of values are not discrete and fall along a continuum. This preference will store a float between 0.0 and 1.0 in the SharedPreferences.](https://raw.github.com/jayschwa/AndroidSliderPreference/master/screenshot.png)
+
+## Overview
+
+* Slider represents a `float` between `0.0` and `1.0`
+  * Access with `SliderPreference.getValue()` or [`SharedPreferences.getFloat()`][shar]
+* Supports multiple summaries (e.g. "Low", "Medium", "High") and selects one based on the slider's position
+  * Java: `SliderPreference.setSummary(CharSequence[] summaries)`
+  * XML: `android:summary="@array/string_array_of_summaries"`
+  * A single `String` still works too
+* Subclass of [`DialogPreference`][diag]
+  * Supports all [dialog-specific attributes][datr] such as `android:dialogMessage`
+  * Visually-consistent with Android's built-in preferences
+  * Less error-prone than displaying the slider directly on the settings screen
+* [MIT License](#license)
+
+[datr]: https://developer.android.com/reference/android/preference/DialogPreference.html#lattrs "DialogPreference attributes"
+[diag]: https://developer.android.com/reference/android/preference/DialogPreference.html "DialogPreference"
+[shar]: https://developer.android.com/reference/android/content/SharedPreferences.html#getFloat(java.lang.String,%20float) "getFloat()"
+
+## How To Use
+
+### Android Studio
+
+1. Paste or clone this library into the `/libs` folder, in the root directory of your project. Create a new folder: `/libs` if not already present.  (This step is not required - only for keeping cleaner project structure)
+
+2. Edit `settings.gradle` by adding the library. You have also define a project directory for the library. Your `settings.gradle` should look like below:
+
+    ```
+    include ':app', ':SliderPreference'
+    project(':SliderPreference').projectDir = new File('libs/SliderPreference')
+    ```
+
+3. In `app/build.gradle` add the SliderPreference library as a dependency:
+
+    ```
+    dependencies {
+        compile fileTree(dir: 'libs', include: ['*.jar'])
+        compile 'com.android.support:appcompat-v7:21.0.3'
+        compile project(":SliderPreference")
+    }
+    ```
+
+4. Sync project, clean and build. You can use the SliderPreference as part of your project now.
+
+### Eclipse
+
+Before you can add a `SliderPreference` to your application, you must first add a library reference:
+
+1. Clone or download a copy of the library
+2. Import the library into Eclipse: File menu -> Import -> Existing Project into Workspace
+3. Open your application's project properties and [add a library reference][ref] to "SliderPreference"
+
+[ref]: https://developer.android.com/tools/projects/projects-eclipse.html#ReferencingLibraryProject
+
+### Add a slider to your application
+
+``` XML
+<!-- preferences.xml -->
+<net.jayschwa.android.preference.SliderPreference
+    android:key="my_slider"
+    android:title="@string/slider_title"
+    android:summary="@array/slider_summaries"
+    android:defaultValue="@string/slider_default"
+    android:dialogMessage="@string/slider_message" />
+```
+``` XML
+<!-- strings.xml -->
+<string name="slider_title">Temperature</string>
+<string-array name="slider_summaries">
+    <!-- You can define as many summaries as you'd like -->
+    <!-- The active summary will reflect the preference's current value -->
+    <item>Freezing</item> <!-- 0.00 to 0.25 -->
+    <item>Chilly</item>   <!-- 0.25 to 0.50 -->
+    <item>Warm</item>     <!-- 0.50 to 0.75 -->
+    <item>Boiling</item>  <!-- 0.75 to 1.00 -->
+</string-array>
+<item name="slider_default" format="float" type="string">0.5</item>
+<string name="slider_message">Optional message displayed in the dialog above the slider</string>
+```
+
+It is possible to define the default value directly in the attribute. The summary can also be a regular string, instead of a string array:
+
+``` XML
+<net.jayschwa.android.preference.SliderPreference
+    android:summary="This summary is static and boring"
+    android:defaultValue="0.5" />
+```
+
+## Background
+
+Sliders are recommended by Android's official [design documentation][ptrn] for specific types of settings:
+
+> Use this pattern for a setting where the range of values are not discrete and fall along a continuum.
+>
+> ![Slider design pattern example](https://developer.android.com/design/media/settings_slider.png)
+
+Despite this recommendation, the Android SDK does not actually provide a [`Preference`][pref] with slider functionality. Various custom implementations can be found around the web, but many have issues such as:
+
+* The slider is displayed directly on the settings screen
+  * Higher chance of accidental clicks
+  * No way to confirm or cancel potential changes
+* Discrete values are displayed to the user
+  * Not ideal for this design pattern
+
+This library aims to be as consistent as possible with the design pattern and Android's built-in [`Preference`][pref] implementations.
+
+[ptrn]: https://developer.android.com/design/patterns/settings.html#patterns "Settings Design Patterns"
+[pref]: https://developer.android.com/reference/android/preference/Preference.html "Preference"
+
+## License
+
+This library is licensed under the [MIT License][mit]. A copy of the license is provided in [LICENSE.txt][copy]:
+
+> Copyright 2012 Jay Weisskopf
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+[copy]: https://raw.github.com/jayschwa/AndroidSliderPreference/master/LICENSE.txt
+[mit]: http://opensource.org/licenses/MIT "Open Source Initiative - The MIT License"

+ 15 - 0
libs/SliderPreference/build.gradle

@@ -0,0 +1,15 @@
+apply plugin: 'com.android.library'
+
+android {
+
+ compileSdkVersion 23
+    buildToolsVersion '23.0.2'
+
+    sourceSets {
+        main {
+            manifest.srcFile 'AndroidManifest.xml'
+            java.srcDirs = ['src']
+            res.srcDirs = ['res']
+        }
+    }
+}

+ 3 - 0
libs/SliderPreference/example/.gitignore

@@ -0,0 +1,3 @@
+/.settings
+/bin
+/gen

+ 25 - 0
libs/SliderPreference/example/AndroidManifest.xml

@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="net.jayschwa.android.preference.SliderPreferenceExample"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="1"
+        android:targetSdkVersion="17" />
+
+    <application
+        android:allowBackup="false"
+        android:label="@string/app_name" >
+        <activity
+            android:name=".ExampleActivity"
+            android:label="@string/app_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>

+ 17 - 0
libs/SliderPreference/example/res/values/strings.xml

@@ -0,0 +1,17 @@
+<resources>
+
+    <string name="app_name">Slider Preference Example</string>
+    <string name="slider_title">Basic Slider</string>
+    <string name="slider_message">Optional message is defined in android:dialogMessage.</string>
+
+    <item name="slider_default" format="float" type="string">0.5</item>
+
+    <string-array name="slider_summaries">
+        <item>Low</item>
+        <item>Medium-Low</item>
+        <item>Medium</item>
+        <item>Medium-High</item>
+        <item>High</item>
+    </string-array>
+
+</resources>

+ 10 - 0
libs/SliderPreference/example/res/xml/preferences.xml

@@ -0,0 +1,10 @@
+<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
+
+    <net.jayschwa.android.preference.SliderPreference
+        android:defaultValue="@string/slider_default"
+        android:dialogMessage="@string/slider_message"
+        android:key="basic_slider"
+        android:summary="@array/slider_summaries"
+        android:title="@string/slider_title" />
+
+</PreferenceScreen>

+ 29 - 0
libs/SliderPreference/example/src/net/jayschwa/android/preference/SliderPreferenceExample/ExampleActivity.java

@@ -0,0 +1,29 @@
+package net.jayschwa.android.preference.SliderPreferenceExample;
+
+import android.content.SharedPreferences;
+import android.os.Bundle;
+import android.preference.PreferenceActivity;
+
+// Deprecated PreferenceActivity methods are used for API Level 10 (and lower) compatibility
+// https://developer.android.com/guide/topics/ui/settings.html#Overview
+@SuppressWarnings("deprecation")
+public class ExampleActivity extends PreferenceActivity implements
+		SharedPreferences.OnSharedPreferenceChangeListener {
+
+	protected void onCreate(Bundle icicle) {
+		super.onCreate(icicle);
+		addPreferencesFromResource(R.xml.preferences);
+		getPreferenceManager().getSharedPreferences()
+				.registerOnSharedPreferenceChangeListener(this);
+	}
+
+	protected void onDestroy() {
+		getPreferenceManager().getSharedPreferences()
+				.unregisterOnSharedPreferenceChangeListener(this);
+		super.onDestroy();
+	}
+
+	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
+			String key) {
+	}
+}

+ 74 - 0
libs/SliderPreference/res/layout/slider_preference_dialog.xml

@@ -0,0 +1,74 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+Copyright 2012 Jay Weisskopf
+
+Licensed under the MIT License (see LICENSE.txt)
+-->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/slider_preference_layout"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical"
+    android:paddingBottom="8dip"
+    android:paddingLeft="16dip"
+    android:paddingRight="16dip"
+    android:paddingTop="8dip" >
+
+    <RelativeLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:orientation="horizontal"
+        android:padding="16dip">
+
+        <TextView
+            android:id="@+android:id/message"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:gravity="left"/>
+
+        <TextView
+            android:id="@+id/value"
+            android:layout_width="100dip"
+            android:layout_height="wrap_content"
+            android:layout_alignParentRight="true"
+            android:textStyle="bold"
+            android:text=""
+            android:layout_gravity="right"
+            android:gravity="right" />
+
+    </RelativeLayout>
+
+    <SeekBar
+        android:id="@+id/slider_preference_seekbar"
+        android:layout_width="fill_parent"
+        android:layout_height="wrap_content"
+        android:paddingBottom="12dip"
+        android:paddingTop="12dip" />
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:orientation="horizontal"
+        android:layout_marginTop="-18dip"
+        android:paddingLeft="16dip"
+        android:paddingRight="16dip" >
+
+        <TextView
+            android:id="@+id/min"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:textSize="10dip"
+            android:text=""
+            android:gravity="left"/>
+
+        <TextView
+            android:id="@+id/max"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:textSize="10dip"
+            android:text=""
+            android:gravity="right" />
+
+    </LinearLayout>
+
+</LinearLayout>

+ 21 - 0
libs/SliderPreference/res/values/attrs.xml

@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+Copyright 2012 Jay Weisskopf
+
+Licensed under the MIT License (see LICENSE.txt)
+-->
+<resources>
+
+    <declare-styleable name="SliderPreference">
+
+        <attr name="android:summary" />
+        <attr name="android:max" />
+        <attr name="minn" format="float" />
+        <attr name="resolution" format="float" />
+        <attr name="scales" format="float" />
+        <attr name="decimals" format="float" />
+        <attr name="format" format="string" />
+
+    </declare-styleable>
+
+</resources>

BIN
libs/SliderPreference/screenshot.png


+ 221 - 0
libs/SliderPreference/src/net/jayschwa/android/preference/SliderPreference.java

@@ -0,0 +1,221 @@
+/*
+ * Copyright 2012 Jay Weisskopf
+ *
+ * Licensed under the MIT License (see LICENSE.txt)
+ */
+
+package net.jayschwa.android.preference;
+
+import android.content.Context;
+import android.content.res.TypedArray;
+import android.preference.DialogPreference;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.View;
+import android.widget.SeekBar;
+import android.widget.TextView;
+
+import java.math.BigDecimal;
+
+/**
+ * @author Jay Weisskopf
+ */
+public class SliderPreference extends DialogPreference {
+
+    private static final String TAG = "SliderPreference";
+
+	protected float mValue, mValueOriginal, mMin, mMax, mResolution, mScale;
+    protected String mFormat;
+
+	public SliderPreference(Context context, AttributeSet attrs) {
+		super(context, attrs);
+		setup(context, attrs);
+	}
+
+	public SliderPreference(Context context, AttributeSet attrs, int defStyle) {
+		super(context, attrs, defStyle);
+		setup(context, attrs);
+	}
+
+	private void setup(Context context, AttributeSet attrs) {
+
+        setPersistent(true);
+        // shouldPersist();
+
+        //if( getPersistedFloat( -42f ) == -42f ) {
+
+        //    persistFloat( 0f );
+
+        //}
+
+		setDialogLayoutResource(R.layout.slider_preference_dialog);
+
+		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SliderPreference);
+		try {
+
+            mValueOriginal = mValue = 0;
+            mMin = 0;
+            mMax = 100;
+            mResolution = 0.1f;
+            mScale = 1;
+            mFormat = "%.2f";
+
+			//setSummary(a.getTextArray(R.styleable.SliderPreference_android_summary));
+            // a.get
+			mFormat = a.getString(R.styleable.SliderPreference_format);
+			mMin = a.getFloat(R.styleable.SliderPreference_minn, 0);
+			mMax = a.getFloat(R.styleable.SliderPreference_android_max, 100);
+			mResolution = a.getFloat(R.styleable.SliderPreference_resolution, 1);
+			mScale = a.getFloat(R.styleable.SliderPreference_scales, 1);
+
+		} catch (Exception e) {
+
+			Log.e("SliderPreference", "Error in attributes");
+		}
+		a.recycle();
+
+    }
+
+    // TODO implement :
+    // valueStorageToDialog
+    // valueDialogToStorage
+    // valueFormat ( currency symbol, precision etc )
+    protected String valueFormat( float value ) {
+
+        if( mFormat != null )
+            return String.format(mFormat, value);
+        else
+            return "" + value;
+
+    }
+
+	@Override
+	protected Object onGetDefaultValue(TypedArray a, int index) {
+
+			return a.getFloat(index, 0);
+
+    }
+
+	@Override
+	protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
+
+        try {
+
+            mValueOriginal = mValue = restoreValue ? getPersistedFloat( 0 ) / mScale : (float) defaultValue / mScale;
+
+			persistFloat( mValue * mScale );
+
+        }
+        catch( Exception e ) {
+
+            Log.e( TAG, "Types do not match:" + this.getKey() );
+
+        }
+
+    }
+
+	@Override
+	public CharSequence getSummary() {
+
+        try {
+            return String.format( super.getSummary().toString(), valueFormat( mValue /* mScale */ ) );
+        }
+        catch( Exception e ) {
+            Log.e( TAG, "getSummary error, format: '" + this.getKey() + "'" );
+        }
+
+        return "";
+
+	}
+
+	protected float getValueFromSeekbar( int progress ) {
+
+        return mMin + progress * mResolution;
+
+	}
+
+	@Override
+	protected View onCreateDialogView() {
+		// mSeekBarValue = (int) (mValue * SEEKBAR_RESOLUTION);
+		final View view = super.onCreateDialogView();
+		SeekBar seekbar = (SeekBar) view.findViewById(R.id.slider_preference_seekbar);
+
+        seekbar.setMax( (int) ( ( mMax - mMin ) / mResolution ) );
+
+		mValue = Math.min( mValue, mMax);
+		mValue = Math.max( mValue, mMin );
+
+		seekbar.setProgress( (int) ( ( mValue - mMin ) / mResolution ) );
+
+		TextView min, max;
+		min = (TextView) view.findViewById( R.id.min );
+		max = (TextView) view.findViewById( R.id.max );
+
+		min.setText( valueFormat( mMin ) );
+		max.setText( valueFormat( mMax ) );
+
+        TextView value = (TextView) view.findViewById( R.id.value );
+        value.setText( valueFormat( mValue ) );
+
+		seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
+
+			@Override
+			public void onStopTrackingTouch(SeekBar seekBar) {
+			}
+
+			@Override
+			public void onStartTrackingTouch(SeekBar seekBar) {
+			}
+
+			@Override
+			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
+
+				if (fromUser) {
+                    mValue = getValueFromSeekbar( progress );
+
+					TextView value = (TextView) view.findViewById( R.id.value );
+					value.setText( valueFormat( mValue ) );
+				}
+
+			}
+		});
+		return view;
+	}
+
+	@Override
+	protected void onDialogClosed(boolean positiveResult) {
+
+		if ( positiveResult && callChangeListener( mValue * mScale ) ) {
+
+            if( shouldPersist() ) {
+
+                try {
+
+                    persistFloat( mValue * mScale );
+
+                }
+                catch( ClassCastException e ) {
+
+                    getEditor().remove(getKey());
+                    getEditor().putFloat(getKey(), mValue * mScale);
+                    getEditor().commit();
+
+                    //persistFloat(mValue * mScale);
+
+                }
+
+            }
+
+            if ( mValueOriginal != mValue ) {
+                notifyChanged();
+
+                mValueOriginal = mValue;
+            }
+
+        }
+
+        super.onDialogClosed(positiveResult);
+
+    }
+
+}

BIN
libs/achartengine-1.2.0.jar


BIN
libs/android-support-v4.jar


BIN
res/drawable-hdpi/coffee.jpg


BIN
res/drawable-hdpi/ic_menu_share.png


BIN
res/drawable-hdpi/icon3.png


BIN
res/drawable-hdpi/silvia_off.png


BIN
res/drawable-hdpi/silvia_on.png


BIN
res/drawable-ldpi/icon3.png


BIN
res/drawable-mdpi/icon3.png


BIN
res/drawable-xhdpi/icon3.png


BIN
res/drawable-xhdpi/plastic.jpg


+ 248 - 0
res/layout/activity_main.xml

@@ -0,0 +1,248 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Root: only reason to use relative is background -->
+<RelativeLayout
+	android:id="@+id/root2"
+	android:layout_width="fill_parent"
+	android:layout_height="fill_parent"
+    android:background="#000000"
+	xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:atswidget="http://schemas.android.com/apk/res-auto"
+     >
+
+    <!-- Picture background -->
+    <ImageView
+        android:id="@+id/background"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:src="@drawable/coffee"
+        android:background="#00000000"
+        android:scaleType="centerCrop" />
+
+    <!-- Camera background -->
+    <SurfaceView
+        android:id="@+id/video"
+        android:layout_width="fill_parent"
+        android:layout_height="fill_parent"
+        android:visibility="invisible" />
+
+    <!-- Main content: for now: graph -->
+    <RelativeLayout
+        android:id="@+id/achart"
+        android:layout_width="match_parent"
+        android:layout_height="fill_parent"
+        android:visibility="visible"
+        android:layout_alignParentTop="true"
+        android:layout_alignParentBottom="true"
+        />
+
+    <!-- Installation manual
+    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
+        android:id="@+id/installation_manual"
+        android:visibility="invisible"
+        android:layout_width="fill_parent"
+        android:layout_height="fill_parent"
+        />
+    -->
+
+    <TextView
+        android:id="@+id/logging"
+        android:layout_width="match_parent"
+        android:layout_height="fill_parent"
+        android:visibility="visible"
+        android:textColor="#FFFFFF"
+        android:layout_alignParentTop="true"
+        android:layout_alignParentBottom="true"
+        />
+
+    <!-- Overlay over background ( the actual controls ) -->
+    <RelativeLayout 
+        android:id="@+id/root"
+    	android:layout_width="fill_parent"
+		android:layout_height="fill_parent"
+		android:padding="16dp"
+	    >
+
+        <!-- Top bar -->
+        <RelativeLayout
+            android:id="@+id/topbar"
+    		android:layout_width="fill_parent"
+			android:layout_height="wrap_content" 
+			android:layout_alignParentTop="true" >
+                    
+	        <!--  Indicator / ON/OFF -->
+	        <ImageView
+				android:id="@+id/Indicator"
+		        android:layout_width="64dp"
+		        android:layout_height="64dp"
+		        android:layout_alignParentTop="true"
+			    android:layout_alignParentRight="true"	        
+		        android:src="@drawable/silvia_off"
+		        android:scaleType="centerInside" />
+
+            <ProgressBar
+                android:id="@+id/progress"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_alignParentTop="true"
+                android:layout_alignParentRight="true"
+                android:visibility="gone" >
+            </ProgressBar>
+	        		
+        </RelativeLayout>
+
+		<!--  Bottom bar -->
+		<RelativeLayout
+            android:id="@+id/bottombar"
+    		android:layout_width="wrap_content"
+			android:layout_height="wrap_content"
+            android:layout_alignParentBottom="true"
+            android:layout_alignParentLeft="true" >
+
+            <RelativeLayout
+                android:id="@+id/gauges"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_alignParentBottom="true"
+                android:layout_alignParentLeft="true" >
+
+            <nl.digitalthings.mebarista.Gauge
+                android:id="@+id/power"
+                android:layout_width="200dp"
+                android:layout_height="200dp"
+                android:layout_alignParentBottom="true"
+                android:layout_alignParentLeft="true"
+                android:layout_marginRight="20dp"
+                atswidget:totalNotches="50"
+                atswidget:incrementPerLargeNotch="20"
+                atswidget:incrementPerSmallNotch="4"
+                atswidget:scaleCenterValue="0"
+                atswidget:scaleColor="0x9f004d0f"
+                atswidget:scaleMinValue="0"
+                atswidget:scaleMaxValue="100"
+                atswidget:rangeOkColor="0x9f00ff00"
+                atswidget:rangeOkMinValue="0"
+                atswidget:rangeOkMaxValue="10"
+                atswidget:rangeWarningColor="0x9fff8800"
+                atswidget:rangeWarningMinValue="10"
+                atswidget:rangeWarningMaxValue="25"
+                atswidget:rangeErrorColor="0x9fff0000"
+                atswidget:rangeErrorMinValue="25"
+                atswidget:rangeErrorMaxValue="100"
+                atswidget:unitTitle="Boiler %"
+            atswidget:lowerTitle=""
+            atswidget:upperTitle=""
+            atswidget:showGauge="false"
+            atswidget:showHand="true"
+            atswidget:showRange="true"
+            />
+
+                <nl.digitalthings.mebarista.Gauge
+                    android:id="@+id/shottimer"
+                    android:layout_width="200dp"
+                    android:layout_height="200dp"
+                    android:layout_alignParentBottom="true"
+                    android:layout_toRightOf="@id/power"
+
+                    android:visibility="gone"
+                    atswidget:totalNotches="45"
+                    atswidget:incrementPerLargeNotch="5"
+                    atswidget:incrementPerSmallNotch="1"
+                    atswidget:scaleCenterValue="0"
+                    atswidget:scaleColor="0x9f004d0f"
+                    atswidget:scaleMinValue="0"
+                    atswidget:scaleMaxValue="45"
+                    atswidget:angleMinValue="0"
+                    atswidget:angleMaxValue="270"
+                    atswidget:rangeOkColor="0x9fff8800"
+                    atswidget:rangeOkMinValue="0"
+                    atswidget:rangeOkMaxValue="20"
+                    atswidget:rangeWarningColor="0x9f00ff00"
+                    atswidget:rangeWarningMinValue="20"
+                    atswidget:rangeWarningMaxValue="25"
+                    atswidget:rangeErrorColor="0x9fff0000"
+                    atswidget:rangeErrorMinValue="25"
+                    atswidget:rangeErrorMaxValue="45"
+                    atswidget:unitTitle="Shot time"
+                    atswidget:lowerTitle=""
+                    atswidget:upperTitle=""
+                    atswidget:showGauge="false"
+                    atswidget:showHand="true"
+                    atswidget:showRange="true"
+                    />
+
+            </RelativeLayout>
+
+            <!-- Temperature control -->
+		    <LinearLayout
+		        android:id="@+id/tempcontrol"
+		        android:orientation="vertical"
+				android:layout_width="wrap_content"
+				android:layout_height="wrap_content"
+				android:layout_alignParentBottom="true"
+				android:layout_alignParentRight="true" >
+				
+		        <TextView
+					android:id="@+id/BTemp"
+					android:layout_width="fill_parent"
+					android:layout_height="wrap_content"
+					android:text="---,-- °"
+					android:textSize="24sp"
+					android:textStyle="bold"
+					android:textColor="#FFFFFF"					 
+					android:gravity="center" 
+				    />
+		    
+		    	<RelativeLayout
+		        	android:id="@+id/tempcontrolctrls"
+					android:layout_width="wrap_content"
+					android:layout_height="wrap_content" >
+				
+			   		<Button
+						android:id="@+id/MinButton"
+						android:layout_width="52dp"
+						android:layout_height="52dp"
+						android:text="-"
+						android:textSize="28sp"
+						android:textStyle="bold"
+						android:textColor="#FFFFFF"
+						android:background="#B0993300"
+						 />
+					
+			        <TextView 
+						android:id="@+id/SetPoint"
+						android:layout_width="70dp"
+						android:layout_height="wrap_content"
+						android:text="---,-- °"
+						android:textSize="14sp"
+						android:textColor="#FFFFFF"
+						android:editable="false"
+						android:gravity="center" 
+			            android:layout_gravity="center"
+						android:layout_toRightOf="@id/MinButton"
+						android:layout_centerVertical="true"
+						android:layout_marginLeft="0dp"
+						/>
+			        
+			        <Button
+						android:id="@+id/PlusButton"
+						android:layout_width="52dp"
+						android:layout_height="52dp"
+						android:text="+"
+						android:textSize="28sp"
+						android:textStyle="bold"
+						android:textColor="#FFFFFF"
+						android:background="#B0993300"
+						android:layout_toRightOf="@id/SetPoint"
+						 />
+			        
+				</RelativeLayout>        		
+
+            </LinearLayout>
+
+		</RelativeLayout>
+
+
+
+    </RelativeLayout>
+		    
+</RelativeLayout>

+ 81 - 0
res/menu/activity_main.xml

@@ -0,0 +1,81 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android" >
+
+    <item
+        android:id="@+id/menu_scan"
+        android:orderInCategory="1"
+        android:showAsAction="always"
+        android:title="Scan"/>
+
+    <item
+        android:id="@+id/menu_item_share"
+        android:showAsAction="always"
+        android:title="Share"
+        android:icon="@drawable/ic_menu_share" />
+
+    <item
+        android:id="@+id/menu_item_video"
+        android:showAsAction="always"
+        android:title="Video"
+        android:icon="@android:drawable/ic_menu_camera" />
+
+    <item
+        android:id="@+id/menu_demo"
+        android:orderInCategory="3"
+        android:showAsAction="never"
+        android:title="Demo meCoffee vs Factory"/>
+
+    <!-- item
+        android:id="@+id/menu_im"
+        android:orderInCategory="4"
+        android:showAsAction="never"
+        android:title="Installation Manual"/ -->
+
+    <item
+        android:id="@+id/menu_settings"
+        android:orderInCategory="3"
+        android:showAsAction="never"
+        android:title="@string/menu_settings"/>
+
+    <item
+        android:id="@+id/menu_fw_reset"
+        android:orderInCategory="3"
+        android:showAsAction="never"
+        android:visible="false"
+        android:title="FW Reset"/>
+
+    <item
+        android:id="@+id/menu_fw_flash"
+        android:orderInCategory="3"
+        android:showAsAction="never"
+        android:visible="false"
+        android:title="FW Flash"/>
+
+    <item
+        android:id="@+id/menu_fw_stop"
+        android:orderInCategory="3"
+        android:showAsAction="never"
+        android:visible="false"
+        android:title="FW Stopt"/>
+
+    <item
+        android:id="@+id/menu_fw_start"
+        android:orderInCategory="3"
+        android:showAsAction="never"
+        android:visible="false"
+        android:title="FW Start"/>
+
+    <item
+        android:id="@+id/menu_fw_close"
+        android:orderInCategory="3"
+        android:showAsAction="never"
+        android:visible="false"
+        android:title="FW Close"/>
+
+    <item
+        android:id="@+id/menu_fw_open"
+        android:orderInCategory="3"
+        android:showAsAction="never"
+        android:visible="false"
+        android:title="FW Open"/>
+
+</menu>

+ 11 - 0
res/values-v11/styles.xml

@@ -0,0 +1,11 @@
+<resources>
+
+    <!--
+        Base application theme for API 11+. This theme completely replaces
+        AppBaseTheme from res/values/styles.xml on API 11+ devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
+        <!-- API 11 theme customizations can go here. -->
+    </style>
+
+</resources>

+ 12 - 0
res/values-v14/styles.xml

@@ -0,0 +1,12 @@
+<resources>
+
+    <!--
+        Base application theme for API 14+. This theme completely replaces
+        AppBaseTheme from BOTH res/values/styles.xml and
+        res/values-v11/styles.xml on API 14+ devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
+        <!-- API 14 theme customizations can go here. -->
+    </style>
+
+</resources>

+ 13 - 0
res/values-v22/styles.xml

@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+    <style name="AppBaseTheme" parent="@android:style/Theme.Material.Light.DarkActionBar">
+        <!-- Main theme colors -->
+        <!--   your app branding color for the app bar -->
+        <item name="android:colorPrimary">@color/primary</item>
+        <!--   darker variant for the status bar and contextual app bars -->
+        <item name="android:colorPrimaryDark">@color/primary_dark</item>
+        <!--   theme UI controls like checkboxes and text fields -->
+        <item name="android:colorAccent">@color/accent</item>
+    </style>
+</resources>

+ 136 - 0
res/values/array.xml

@@ -0,0 +1,136 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string-array name="Language">
+        <item>English (US)</item>
+        <item>English (UK)</item>
+        <item>French (France)</item>
+        <item>Spanish (Spain)</item>
+        <item>Italian</item>
+    </string-array>
+
+    <string-array name="LanguageAlias">
+        <item>"en-US"</item>
+        <item>"en-GB"</item>
+        <item>"fr-FR"</item>
+        <item>"es-ES"</item>
+        <item>"it-IT"</item>
+    </string-array>
+
+    <string-array name="graph_history">
+        <item>10 Minutes</item>
+        <item>20 Minutes</item>
+        <item>30 Minutes</item>
+    </string-array>
+
+    <string-array name="graph_history_alias">
+        <item>10</item>
+        <item>20</item>
+        <item>30</item>
+    </string-array>
+
+    <string-array name="pid_winddown">
+        <item>0</item>
+        <item>500</item>
+        <item>1000</item>
+        <item>1500</item>
+        <item>2000</item>
+        <item>2500</item>
+        <item>3000</item>
+        <item>3500</item>
+        <item>4000</item>
+        <item>4500</item>
+        <item>5000</item>
+        <item>5500</item>
+        <item>6000</item>
+        <item>6500</item>
+        <item>7000</item>
+        <item>7500</item>
+        <item>8000</item>
+        <item>12000</item>
+        <item>24000</item>
+        <item>48000</item>
+
+    </string-array>
+
+    <string-array name="pid_winddown_alias">
+        <item>0</item>
+        <item>500</item>
+        <item>1000</item>
+        <item>1500</item>
+        <item>2000</item>
+        <item>2500</item>
+        <item>3000</item>
+        <item>3500</item>
+        <item>4000</item>
+        <item>4500</item>
+        <item>5000</item>
+        <item>5500</item>
+        <item>6000</item>
+        <item>6500</item>
+        <item>7000</item>
+        <item>7500</item>
+        <item>8000</item>
+        <item>12000</item>
+        <item>24000</item>
+        <item>48000</item>
+    </string-array>
+
+    <string-array name="pid_interval">
+        <item>100</item>
+        <item>500</item>
+        <item>1000</item>
+        <item>2000</item>
+        <item>3000</item>
+        <item>4000</item>
+        <item>5000</item>
+    </string-array>
+
+    <string-array name="pid_interval_alias">
+        <item>100</item>
+        <item>500</item>
+        <item>1000</item>
+        <item>2000</item>
+        <item>3000</item>
+        <item>4000</item>
+        <item>5000</item>
+    </string-array>
+
+    <string-array name="fw_timing">
+        <item>0 ms</item>
+        <item>250 ms [ default ]</item>
+        <item>500 ms</item>
+        <item>750 ms</item>
+        <item>1000 ms</item>
+        <item>1250 ms</item>
+        <item>1500 ms</item>
+    </string-array>
+
+    <string-array name="fw_timing_alias">
+        <item>0</item>
+        <item>250</item>
+        <item>500</item>
+        <item>750</item>
+        <item>1000</item>
+        <item>1250</item>
+        <item>1500</item>
+    </string-array>
+
+    <string-array name="hw_out">
+        <item>Boiler</item>
+        <item>Pump</item>
+        <item>Valve</item>
+        <item>Indicator</item>
+        <item>Grinder</item>
+        <item>None</item>
+    </string-array>
+
+    <string-array name="hw_out_alias">
+        <item>98</item>
+        <item>112</item>
+        <item>118</item>
+        <item>105</item>
+        <item>103</item>
+        <item>110</item>
+    </string-array>
+
+</resources>

+ 50 - 0
res/values/attrs.xml

@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+
+    <!-- note: to re-use an existing Android attribute not already used by the superclass, name should have prefix "android:" and do not define a format -->
+    <declare-styleable name="PreferencesNumberPicker">
+        <attr name="android:max" />
+        <attr name="min" format="integer" />
+        <attr name="scale" format="integer" />
+    </declare-styleable>
+
+
+
+        <declare-styleable name="Dial">
+            <attr name="totalNotches" format="integer"/>
+
+            <attr name="incrementPerLargeNotch" format="integer"/>
+            <attr name="incrementPerSmallNotch" format="integer"/>
+
+            <attr name="scaleColor" format="integer"/>
+            <attr name="scaleCenterValue" format="integer"/>
+            <attr name="scaleMinValue" format="integer"/>
+            <attr name="angleMinValue" format="integer"/>
+            <attr name="scaleMaxValue" format="integer"/>
+            <attr name="angleMaxValue" format="integer"/>
+
+            <attr name="rangeOkColor" format="integer"/>
+            <attr name="rangeOkMinValue" format="integer"/>
+            <attr name="rangeOkMaxValue" format="integer"/>
+
+            <attr name="rangeWarningColor" format="integer"/>
+            <attr name="rangeWarningMinValue" format="integer"/>
+            <attr name="rangeWarningMaxValue" format="integer"/>
+
+            <attr name="rangeErrorColor" format="integer"/>
+            <attr name="rangeErrorMinValue" format="integer"/>
+            <attr name="rangeErrorMaxValue" format="integer"/>
+
+            <attr name="upperTitle" format="string"/>
+            <attr name="lowerTitle" format="string"/>
+            <attr name="unitTitle" format="string"/>
+
+            <attr name="showRange" format="boolean"/>
+            <attr name="showHand" format="boolean"/>
+            <attr name="showGauge" format="boolean"/>
+
+        </declare-styleable>
+
+
+</resources>

+ 16 - 0
res/values/colors.xml

@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="utf-8"?>
+    <resources>
+        <color name="primary">#795548</color>
+        <color name="primary_dark">#3E2723</color>
+        <color name="accent">#EF6C00</color>
+        <color name="black">#000</color>
+
+    <color name="white">#ffffff</color>
+    <color name="light_gray">#A8A8A8</color>
+    <color name="dark_gray">#606060</color>
+    <color name="blue">#80C8FE</color>
+    <color name="dark_blue">#0066B3</color>
+    <color name="light_blue">#BFE3FE</color>
+
+    </resources>
+

+ 6 - 0
res/values/ids.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+    <item name="graph" type="id" />
+
+</resources>

+ 27 - 0
res/values/strings.xml

@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+    <string name="app_name">meBarista</string>
+    <string name="hello_world">Hello world!</string>
+    <string name="menu_settings">Settings</string>
+    <string name="terminalMessage">#&gt;HelloUser</string>
+    <string name="TerminalInitMessage">Type what to send</string>
+    <string name="SendButtonText">Send</string>
+    <string name="about">About</string>
+    <string name="messageUnknownButton">Unknown button was pressed</string>
+    <string name="seachingDev">Searching for bluetooth devices</string>
+    <string name="UnsupportedBluetooth">This device doesn\'t support bluetooth, exiting!</string>
+    <string name="notSwithcedOnBluetooth">Without bluetooth this program is useless</string>
+    <string name="defaultSpinnerMessage">Seaching paired bluetooth devices</string>
+    <string name="noPairedDevices">No paired devices, searching new devices</string>
+    <string name="findedPairedDevices">Paired devices finded</string>
+    <string name="noCurrentDevice">You are not connected to device </string>
+    <string name="searchFailed">Failed to start search devices, exiting</string>
+    <string name="findedDevices">Finded devices, look at list</string>
+    <string name="SocketRead">Data readed from socket</string>
+    <string name="ButtonOk">OK</string>
+    <string name="ButtonRe">Re</string>
+    <string name="OnDestroy">Destroyed</string>
+    <string name="OnStop">Stopped</string>
+
+</resources>

+ 20 - 0
res/values/styles.xml

@@ -0,0 +1,20 @@
+<resources>
+
+    <!--
+        Base application theme, dependent on API level. This theme is replaced
+        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.Light">
+        <!--
+            Theme customizations available in newer API levels can go in
+            res/values-vXX/styles.xml, while customizations related to
+            backward-compatibility can go here.
+        -->
+    </style>
+
+    <!-- Application theme. -->
+    <style name="AppTheme" parent="AppBaseTheme">
+        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
+    </style>
+
+</resources>

+ 893 - 0
res/xml/preference.xml

@@ -0,0 +1,893 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
+                    xmlns:auto="http://schemas.android.com/apk/res-auto">
+
+    <PreferenceScreen
+        android:title="Temperature"
+        android:key="pref_temperature">
+
+        <!-- SwitchPreference
+            android:key="pref_tmpnbl"
+            android:title="Enable meCoffee boiler control"
+            android:summary="Make meCoffee control the boiler"
+            android:enabled="false"
+            android:defaultValue="false" / -->
+
+        <SwitchPreference
+            android:key="pref_tmpcntns"
+            android:title="Continuous mode"
+            android:summary="Instead of using an interval, dim the boiler"
+            android:defaultValue="false" />
+
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_tmpsp"
+            android:key="pref_tmpsp"
+            android:defaultValue="101"
+            android:dialogMessage="Brew temperature ( Celsius )"
+            android:max="150"
+            android:enabled="true"
+            android:title="Brew temperature"
+            android:summary="%d degrees"
+            auto:scale="100"
+            / -->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_tmpsp"
+            android:title="Brew temperature ( Celsius )"
+            android:dialogMessage=""
+            android:summary="%s, default: 101 °"
+            android:defaultValue="10100"
+            android:max="125"
+            auto:minn="50"
+            auto:resolution="0.5"
+            auto:format="%.2f °"
+            auto:scales="100"
+            />
+
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_tmpstm"
+            android:key="pref_tmpstm"
+            android:defaultValue="125"
+            android:dialogMessage="Steam temperature ( Celsius )"
+            android:max="150"
+            android:enabled="true"
+            android:title="Steam temperature"
+            android:summary="%d degrees"
+            auto:scale="100"
+            / -->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_tmpstm"
+            android:title="Steam temperature ( Celsius )"
+            android:dialogMessage=""
+            android:summary="%s, default: 125 °"
+            android:defaultValue="12500"
+            android:max="140"
+            auto:minn="110"
+            auto:resolution="0.5"
+            auto:format="%.2f °"
+            auto:scales="100"
+            />
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_tmppap"
+            android:key="pref_tmppap"
+            android:defaultValue="10"
+            android:dialogMessage="Please select the percentage to increase the boiler power while brewing"
+            android:max="100"
+            android:title="Pro Active Percentage"
+            android:summary="%d %%"
+            /-->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_tmppap"
+            android:title="Pro Active Percentage"
+            android:dialogMessage="Please select the percentage to increase the boiler power while brewing"
+            android:summary="%s, default: 33 %%"
+            android:defaultValue="33"
+            android:max="100"
+            auto:minn="0"
+            auto:resolution="1"
+            auto:format="%.0f %%"
+            auto:scales="1"
+            />
+
+        <PreferenceScreen
+            android:title="PID"
+            android:key="pref_temperature_pid">
+
+            <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+                android:id="@+id/pref_pd1p"
+                android:key="pref_pd1p"
+                android:defaultValue="10"
+                android:dialogMessage="Please select the Proportional component"
+                android:summary="%d, default: 25"
+                android:max="100"
+                android:title="Proportional component ( P )"
+                / -->
+
+            <net.jayschwa.android.preference.SliderPreference
+                android:key="pref_pd1p"
+                android:title="Proportional component ( P )"
+                android:dialogMessage="Please select the Proportional component"
+                android:summary="%s, default: 20"
+                android:defaultValue="20"
+                android:max="100"
+                auto:minn="0"
+                auto:resolution="1"
+                auto:format="%.0f"
+                auto:scales="1" />
+
+            <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+                android:id="@+id/pref_pd1i"
+                android:key="pref_pd1i"
+                android:defaultValue="10"
+                android:dialogMessage="Please select the Integral component"
+                android:max="100"
+                android:title="Integral component ( I )"
+                android:summary="%d, default: 3"
+                / -->
+
+            <net.jayschwa.android.preference.SliderPreference
+                android:key="pref_pd1i"
+                android:title="Integral component ( I )"
+                android:dialogMessage="Please select the Integral component"
+                android:summary="%s, default: 0.3"
+                android:defaultValue="0.3"
+                android:max="1"
+                auto:minn="0"
+                auto:resolution="0.01"
+                auto:format="%.2f"
+                auto:scales="100" />
+
+            <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+                android:id="@+id/pref_pd1d"
+                android:key="pref_pd1d"
+                android:defaultValue="10"
+                android:dialogMessage="Please select the Derivative component"
+                android:max="255"
+                android:title="Derivative component ( D )"
+                android:summary="%d, default:128 "
+                / -->
+
+            <net.jayschwa.android.preference.SliderPreference
+                android:key="pref_pd1d"
+                android:title="Derivative component ( D )"
+                android:dialogMessage="Please select the Derivative component"
+                android:summary="%s, default: 128"
+                android:defaultValue="128"
+                android:max="256"
+                auto:minn="0"
+                auto:resolution="1"
+                auto:format="%.0f"
+                auto:scales="1" />
+
+            <!-- ListPreference
+                android:key="pref_pd1imn"
+                android:title="Integral ( I ) wind-down minimum"
+                android:summary="%s, default: 1000"
+                android:entries="@array/pid_winddown"
+                android:entryValues="@array/pid_winddown_alias"/ -->
+
+            <net.jayschwa.android.preference.SliderPreference
+                android:key="pref_pd1imm"
+                android:title="Integral ( I ) wind-down minimum"
+                android:dialogMessage="The minimum maintenance power, limiting this helps overshoots and oscillation."
+                android:summary="%s, default: 5"
+                android:defaultValue="0"
+                android:max="100"
+                auto:minn="0"
+                auto:format="%.0f %%"
+                auto:resolution="1"
+                auto:scales="655.36"
+                />
+
+
+            <!-- ListPreference
+                android:key="pref_pd1imx"
+                android:title="Integral ( I ) wind-down limit"
+                android:summary="%s, default: 3000"
+                android:entries="@array/pid_winddown"
+                android:entryValues="@array/pid_winddown_alias"/ -->
+
+            <net.jayschwa.android.preference.SliderPreference
+                android:key="pref_pd1imx"
+                android:title="Integral ( I ) wind-down limit"
+                android:dialogMessage="The maximum maintenance power, limiting this helps overshoots and oscillation."
+                android:summary="%s, default: 20"
+                android:defaultValue="20"
+                android:max="100"
+                auto:minn="0"
+                auto:format="%.0f %%"
+                auto:resolution="1"
+                auto:scales="655.36"
+                />
+
+            <!-- ListPreference
+                android:key="pref_pd1sz"
+                android:title="Polling interval"
+                android:summary="%s ms, default: 1000 ms"
+                android:entries="@array/pid_interval"
+                android:entryValues="@array/pid_interval"/ -->
+
+            <net.jayschwa.android.preference.SliderPreference
+                android:key="pref_pd1sz"
+                android:title="Polling interval"
+                android:dialogMessage="Default for continous mode: 1000 ms, \ndefault for interval mode: 5000 ms."
+                android:summary="%s, default: 1000 ms"
+                android:defaultValue="1000"
+                android:max="10000"
+                auto:minn="1000"
+                auto:format="%.0f ms"
+                auto:resolution="500"
+                />
+
+            <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+                android:id="@+id/pref_pd1id"
+                android:key="pref_pd1id"
+                android:defaultValue="10"
+                android:dialogMessage="Speed at which the error component reacts ( 10 = default, lower is faster, bigger is slow  )"
+                android:max="50"
+                min="1"
+                android:title="I-Speed parameter down"
+                android:summary="%d, default:10 "
+                / -->
+
+
+            <!-- net.jayschwa.android.preference.SliderPreference
+                android:key="pref_pd1id"
+                android:title="Integral speed below setpoint"
+                android:dialogMessage="Lower is faster, higher is slower. Default: 10."
+                android:summary="%s, default: 10"
+                android:defaultValue="10"
+                android:max="50"
+                auto:minn="0"
+                auto:format="%.0f"
+                auto:resolution="1"
+                / -->
+
+            <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+                android:id="@+id/pref_pd1iu"
+                android:key="pref_pd1iu"
+                android:defaultValue="10"
+                android:dialogMessage="Speed at which the error component reacts ( 10 = default, lower is faster, bigger is slow  )"
+                android:max="50"
+                min="1"
+                android:title="Please select the I-Speed parameter down"
+                android:summary="%d, default:10 "
+                / -->
+
+            <!-- net.jayschwa.android.preference.SliderPreference
+                android:key="pref_pd1iu"
+                android:title="Integral speed above setpoint"
+                android:dialogMessage="Lower is faster, higher is slower. Default: 10."
+                android:summary="%s, default: 10"
+                android:defaultValue="10"
+                android:max="50"
+                auto:minn="0"
+                auto:format="%.0f"
+                auto:resolution="1"
+                / -->
+
+            <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/temperature/pid"
+                />
+            </Preference>
+
+        </PreferenceScreen>
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/temperature/"
+                />
+
+        </Preference>
+
+    </PreferenceScreen>
+
+    <PreferenceScreen
+        android:title="Pressure"
+        android:key="pref_pp">
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_pp_start"
+            android:key="pref_pp1"
+            android:defaultValue="100"
+            android:dialogMessage="Please select pump pressure to start with"
+            android:max="100"
+            android:title="At start of pull"
+            android:summary="%d %%"
+            android:enabled="true"
+            / -->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_pp1"
+            android:title="At start of pull"
+            android:dialogMessage="Please select pump pressure to start with"
+            android:summary="%s, default: 100 %%"
+            android:defaultValue="100"
+            android:max="100"
+            auto:minn="0"
+            auto:resolution="1"
+            auto:format="%.0f %%"
+            auto:scales="1"
+            />
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_pp_end"
+            android:key="pref_pp2"
+            android:defaultValue="70"
+            android:dialogMessage="Please select pump pressure to end with"
+            android:max="100"
+            android:title="At end of pull"
+            android:summary="%d %%"
+            android:enabled="true"
+
+            / -->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_pp2"
+            android:title="At end of pull"
+            android:dialogMessage="Please select pump pressure to end with"
+            android:summary="%s, default: 100 %%"
+            android:defaultValue="100"
+            android:max="100"
+            auto:minn="0"
+            auto:resolution="1"
+            auto:format="%.0f %%"
+            auto:scales="1"
+            />
+
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_pp_period"
+            android:key="pref_ppt"
+            android:defaultValue="25"
+            android:dialogMessage="Please select the period to taper from the start pressure to the end pressure"
+            android:max="60"
+            android:title="Period"
+            android:enabled="true"
+            android:summary="%d seconds"
+            / -->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_ppt"
+            android:title="Period"
+            android:dialogMessage="Please select the period to taper from the start pressure to the end pressure"
+            android:summary="%s, default: 25 s"
+            android:defaultValue="25"
+            android:max="60"
+            auto:minn="0"
+            auto:resolution="1"
+            auto:format="%.0f s"
+            auto:scales="1"
+            />
+
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/pressure"
+                />
+
+        </Preference>
+
+    </PreferenceScreen>
+
+    <PreferenceScreen
+        android:title="Preinfusion"
+        android:key="pref_pi">
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_pi_shtmx"
+            android:key="pref_shtmx"
+            android:defaultValue="0"
+            android:dialogMessage="Please select total shot time ( 0 for infinity )"
+            android:max="40"
+            android:title="Max shot time"
+            android:summary="%d seconds"
+            / -->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_shtmx"
+            android:title="Max shot time"
+            android:dialogMessage="Please select maximum shot time"
+            android:summary="%s, default: 60 s"
+            android:defaultValue="60"
+            android:max="60"
+            auto:minn="0"
+            auto:resolution="1"
+            auto:format="%.0f s"
+            auto:scales="1"
+            />
+
+        <SwitchPreference
+            android:key="pref_pinbl"
+            android:title="Enable"
+            android:summary="Fill the puck first and pull the shot a couple of seconds later"
+            android:defaultValue="true" />
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_pi_pump"
+            android:dependency="pref_pinbl"
+            android:key="pref_pistrt"
+            android:defaultValue="3"
+            android:dialogMessage="Please select pump time in seconds"
+            android:max="10"
+            android:title="Pump time"
+            android:summary="%d seconds"
+            / -->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_pistrt"
+            android:dependency="pref_pinbl"
+            android:title="Pump time"
+            android:dialogMessage="Please select pump time in seconds"
+            android:summary="%s, default: 3 s"
+            android:defaultValue="3"
+            android:max="10"
+            auto:minn="0"
+            auto:resolution="0.1"
+            auto:format="%.1f s"
+            auto:scales="1000"
+            />
+
+
+        <SwitchPreference
+            android:key="pref_pivlv"
+            android:dependency="pref_pinbl"
+            android:title="Close valve while paused"
+            android:summary=""
+            android:defaultValue="false" />
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_pi_pause"
+            android:dependency="pref_pinbl"
+            android:key="pref_piprd"
+            android:defaultValue="3"
+            android:dialogMessage="Please select pause time in seconds"
+            android:max="10"
+            android:title="Pause time"
+            android:summary="%d seconds"
+            / -->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_piprd"
+            android:dependency="pref_pinbl"
+            android:title="Pause time"
+            android:dialogMessage="Please select pause time in seconds"
+            android:summary="%s, default: 3 s"
+            android:defaultValue="3"
+            android:max="10"
+            auto:minn="0"
+            auto:resolution="0.1"
+            auto:format="%.1f s"
+            auto:scales="1000"
+            />
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/preinfusion/"
+                />
+
+        </Preference>
+
+    </PreferenceScreen>
+
+    <PreferenceScreen
+        xmlns:android="http://schemas.android.com/apk/res/android"
+        android:title="Timers"
+        android:key="pref_timer">
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_tmrosd"
+            android:title="Auto shutoff time"
+            android:dialogMessage="Inactivity timer. 0 means no disactivity timer"
+            android:summary="%s minutes, default: 60 minutes"
+            android:defaultValue="60"
+            android:max="120"
+            auto:minn="0"
+            auto:resolution="1"
+            auto:format="%.0f minutes"
+            auto:scales="1"
+            />
+
+        <SwitchPreference
+            android:key="pref_tmrwnbl"
+            android:title="Enable"
+            android:summary="Automatically turn machine on at a certain time"
+            android:defaultValue="false" />
+
+        <nl.digitalthings.mebarista.TimePreference
+            android:id="@+id/pref_tmron"
+            android:dependency="pref_tmrwnbl"
+            android:key="pref_tmron"
+            android:dialogMessage="Please select the wakeup time"
+            android:title="Wakeup time"
+            />
+
+        <SwitchPreference
+            android:key="pref_tmrsnbl"
+            android:title="Enable"
+            android:summary="Automatically turn machine off at a certain time"
+            android:enabled="true"
+            android:defaultValue="false" />
+
+        <nl.digitalthings.mebarista.TimePreference
+            android:id="@+id/pref_tmroff"
+            android:dependency="pref_tmrsnbl"
+            android:key="pref_tmroff"
+            android:defaultValue="3"
+            android:dialogMessage="Please select the shutdown time"
+            android:title="Shutdown time"
+            android:summary=" seconds"
+            android:enabled="true"
+            />
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/timer/"
+                />
+
+        </Preference>
+
+    </PreferenceScreen>
+
+    <PreferenceScreen
+        android:title="Bluetooth"
+        android:key="pref_bt">
+
+        <nl.digitalthings.mebarista.EditTextPreferenceWithSummary
+            android:id="@+id/pref_bt_devicename"
+            android:key="pref_btname"
+            android:defaultValue="meCoffee"
+            android:title="Device name"
+            android:summary="Connected device has name '%s'"
+            />
+
+        <nl.digitalthings.mebarista.EditTextPreferenceWithSummary
+            android:id="@+id/pref_bt_devicename_prefix"
+            android:key="pref_bt_devicename_prefix"
+            android:defaultValue="meCoffee"
+            android:title="Device name prefix"
+            android:summary="Devices wich names start with '%s' will be automatically connected"
+            />
+
+        <SwitchPreference
+            android:key="pref_bt_bt2_enabled"
+            android:title="Enable BT2 / Classic"
+            android:summary="Scans for BT2 / Classic devices"
+            android:defaultValue="true" />
+
+        <SwitchPreference
+            android:key="pref_bt_ble_enabled"
+            android:title="Enable BLE / Bluetooth Low Energy"
+            android:summary="Scans for BLE / Bluetooth Low Energy devices"
+            android:defaultValue="false" />
+
+        <SwitchPreference
+            android:key="pref_bt_disable"
+            android:title="Disable on close"
+            android:summary="Disable Bluetooth adapter if App is closed"
+            android:defaultValue="false" />
+
+
+        <SwitchPreference
+            android:key="pref_bt_keepdiscovering"
+            android:title="Keep discovering"
+            android:summary="Keep discovering devices when not connected"
+            android:enabled="true"
+            android:defaultValue="false" />
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_bt_scanlimit_minutes"
+            android:dependency="pref_bt_scanlimit"
+            android:key="pref_pt_scanlimit_minutes"
+            android:defaultValue="3"
+            android:dialogMessage="Please select scan time in minutues"
+            android:max="10"
+            android:title="Bluetooth scan time"
+            android:enabled="false"
+            android:summary=" minutes"
+            / -->
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/bluetooth/"
+                />
+
+        </Preference>
+
+    </PreferenceScreen>
+
+    <PreferenceScreen
+        android:title="User interface"
+        android:key="pref_ui">
+
+        <SwitchPreference
+            android:key="pref_ui_graph_enable"
+            android:title="Enable graph"
+            android:summary="Show the temperature graph on the background"
+            android:defaultValue="true" />
+
+        <ListPreference
+            android:key="pref_ui_graph_history"
+            android:title="Graph history"
+            android:dependency="pref_ui_graph_enable"
+            android:entries="@array/graph_history"
+            android:entryValues="@array/graph_history_alias"/>
+
+        <SwitchPreference
+            android:id="@+id/pref_ui_second_sensor"
+            android:key="pref_ui_second_sensor"
+            android:title="Show second sensor"
+            android:summary=""
+            android:defaultValue="false" />
+
+        <CheckBoxPreference
+            android:key="pref_ui_tempcontrol_enable"
+            android:title="Enable temperature control"
+            android:defaultValue="false" />
+
+        <SwitchPreference
+            android:id="@+id/pref_ui_background"
+            android:key="pref_ui_background"
+            android:title="Show background"
+            android:summary=""
+            android:defaultValue="true" />
+
+        <SwitchPreference
+            android:id="@+id/pref_ui_logging"
+            android:key="pref_ui_logging"
+            android:title="Show logging"
+            android:summary=""
+            android:defaultValue="false" />
+
+        <SwitchPreference
+            android:id="@+id/pref_ui_screenwake"
+            android:key="pref_ui_screenwake"
+            android:title="Prevent screen sleep"
+            android:summary=""
+            android:defaultValue="false" />
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/userinterface/"
+                />
+
+        </Preference>
+
+    </PreferenceScreen>
+
+    <!-- PreferenceScreen
+        android:title="Statistics"
+        android:key="pref_statistics">
+
+        <nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_grndr_cnt"
+            android:key="pref_grndr_cnt"
+            android:defaultValue="0"
+            android:dialogMessage="The times the grinder has grinded!"
+            android:enabled="false"
+            android:selectable="false"
+            android:shouldDisableView="false"
+            android:title="Grinder counter"
+            android:summary=" times"
+            android:max="65000"
+            />
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/statistics"
+                />
+
+        </Preference>
+
+    </PreferenceScreen !-->
+
+    <PreferenceScreen
+        android:title="Hardware"
+        android:key="pref_hardware">
+
+        <ListPreference
+            android:id="@+id/pref_hw_out0"
+            android:key="pref_o0"
+            android:title="Output 1"
+            android:summary="%s, default: Pump"
+            android:defaultValue="112"
+            android:entries="@array/hw_out"
+            android:entryValues="@array/hw_out_alias"/>
+
+        <ListPreference
+            android:id="@+id/pref_support_hw_out1"
+            android:key="pref_o1"
+            android:title="Output 2"
+            android:summary="%s, default: Boiler"
+            android:defaultValue="98"
+            android:entries="@array/hw_out"
+            android:entryValues="@array/hw_out_alias"/>
+
+        <ListPreference
+            android:id="@+id/pref_hw_out2"
+            android:key="pref_o2"
+            android:title="Output 3"
+            android:summary="%s, default: Valve"
+            android:defaultValue="118"
+            android:entries="@array/hw_out"
+            android:entryValues="@array/hw_out_alias"/>
+
+        <SwitchPreference
+            android:key="pref_tmrpwr"
+            android:title="Installed as timer"
+            android:summary="Prevent warmup after power outage or cold boot"
+            android:enabled="true"
+            android:defaultValue="false" />
+
+        <SwitchPreference
+            android:key="pref_pwrflp"
+            android:title="Power button flips back"
+            android:summary="Enable Silvia V5 power button or similar"
+            android:enabled="true"
+            android:defaultValue="false" />
+
+        <!-- SwitchPreference
+            android:key="pref_s1ad"
+            android:title="Sensor 1 divide"
+            android:summary="Do the sensor dance"
+            android:enabled="true"
+            android:defaultValue="false" / -->
+
+        <PreferenceScreen
+            android:title="Firmware"
+            android:key="pref_firmware">
+
+            <nl.digitalthings.mebarista.EditTextPreferenceWithSummary
+                android:id="@+id/pref_uname"
+                android:key="pref_uname"
+                android:defaultValue=""
+                android:title="Device firmware"
+                android:summary="Running version: %s"
+                />
+
+            <!-- nl.digitalthings.mebarista.EditTextPreferenceWithSummary
+                android:id="@+id/pref_fw_pin"
+                android:key="pref_fw_pin"
+                android:defaultValue=""
+                android:title="Pin code required for flashing"
+                android:summary="'%s'"
+                / -->
+
+            <SwitchPreference
+                android:id="@+id/pref_support_fw_enable"
+                android:key="pref_support_fw_enable"
+                android:title="Enable"
+                android:summary="Enable Flash Firmware button, make sure to read and understand the help section first."
+                android:defaultValue="false" />
+
+            <Preference android:title="Flash firmware V4 ( legacy )"
+                android:summary="When selected, meBarista will reflash your espresso machine. Read help section first."
+                android:dependency="pref_support_fw_enable"
+                android:enabled="false">
+
+                <intent android:targetPackage="nl.digitalthings.mebarista"
+                    android:targetClass="nl.digitalthings.mebarista.MainActivity"
+                    android:data="flashfirmware_V4"
+                    android:dependency="pref_support_fw_enable"
+                    />
+            </Preference>
+
+            <Preference android:title="Flash firmware V9 ( newest )"
+                android:summary="When selected, meBarista will reflash your espresso machine. Read help section first."
+                android:dependency="pref_support_fw_enable"
+                android:enabled="false">
+
+                <intent android:targetPackage="nl.digitalthings.mebarista"
+                    android:targetClass="nl.digitalthings.mebarista.MainActivity"
+                    android:data="flashfirmware_V9"
+                    android:dependency="pref_support_fw_enable"
+                    />
+            </Preference>
+
+            <Preference android:title="Flash firmware V10 ( newest )"
+                android:summary="When selected, meBarista will reflash your espresso machine. Read help section first."
+                android:dependency="pref_support_fw_enable"
+                android:enabled="false">
+
+                <intent android:targetPackage="nl.digitalthings.mebarista"
+                    android:targetClass="nl.digitalthings.mebarista.MainActivity"
+                    android:data="flashfirmware_V10"
+                    android:dependency="pref_support_fw_enable"
+                    />
+            </Preference>
+
+            <ListPreference
+                android:key="pref_fw_timing"
+                android:title="Flash timing"
+                android:dependency="pref_support_fw_enable"
+                android:defaultValue="250"
+                android:entries="@array/fw_timing"
+                android:entryValues="@array/fw_timing_alias"/>
+
+            <Preference android:title="Help" >
+
+                <intent
+                    android:action="android.intent.action.VIEW"
+                    android:data="https://www.mecoffee.nl/mebarista/help/hardware/firmware/"
+                    />
+
+            </Preference>
+
+        </PreferenceScreen>
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/hardware/"
+                />
+
+        </Preference>
+
+    </PreferenceScreen>
+
+    <PreferenceScreen
+        android:title="Support"
+        android:key="pref_support">
+
+
+        <nl.digitalthings.mebarista.EditTextPreferenceWithSummary
+            android:id="@+id/pref_support_email"
+            android:key="pref_support_email"
+            android:defaultValue="support@yourdealer.com"
+            android:title="Helpdesk email address"
+            android:summary="Support tickets are sent to '%s' by default"
+            />
+
+        <Preference android:title="Support ticket" >
+
+            <intent android:targetPackage="nl.digitalthings.mebarista"
+                android:targetClass="nl.digitalthings.mebarista.MainActivity"
+                android:data="supportticket" />
+
+        </Preference>
+
+        <Preference android:title="Credits and Licenses" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="http://www.mecoffee.nl/mebarista/credits/"
+                />
+
+        </Preference>
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="http://www.mecoffee.nl/mebarista/help/support/"
+                />
+
+        </Preference>
+
+    </PreferenceScreen>
+
+</PreferenceScreen>

+ 796 - 0
res/xml/preference_legacy.xml

@@ -0,0 +1,796 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
+                    xmlns:auto="http://schemas.android.com/apk/res-auto">
+
+    <PreferenceScreen
+        android:title="Temperature"
+        android:key="pref_temperature">
+
+        <!-- SwitchPreference
+            android:key="pref_tmpnbl"
+            android:title="Enable meCoffee boiler control"
+            android:summary="Make meCoffee control the boiler"
+            android:enabled="false"
+            android:defaultValue="false" / -->
+
+        <SwitchPreference
+            android:key="pref_tmpcntns"
+            android:title="Continuous mode"
+            android:summary="Instead of using an interval, dim the boiler"
+            android:defaultValue="false" />
+
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_tmpsp"
+            android:key="pref_tmpsp"
+            android:defaultValue="101"
+            android:dialogMessage="Brew temperature ( Celsius )"
+            android:max="150"
+            android:enabled="true"
+            android:title="Brew temperature"
+            android:summary="%d degrees"
+            auto:scale="100"
+            / -->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_tmpsp"
+            android:title="Brew temperature ( Celsius )"
+            android:dialogMessage=""
+            android:summary="%s, default: 101 °"
+            android:defaultValue="10100"
+            android:max="125"
+            auto:minn="50"
+            auto:resolution="0.5"
+            auto:format="%.2f °"
+            auto:scales="100"
+            />
+
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_tmpstm"
+            android:key="pref_tmpstm"
+            android:defaultValue="125"
+            android:dialogMessage="Steam temperature ( Celsius )"
+            android:max="150"
+            android:enabled="true"
+            android:title="Steam temperature"
+            android:summary="%d degrees"
+            auto:scale="100"
+            / -->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_tmpstm"
+            android:title="Steam temperature ( Celsius )"
+            android:dialogMessage=""
+            android:summary="%s, default: 125 °"
+            android:defaultValue="12500"
+            android:max="140"
+            auto:minn="110"
+            auto:resolution="0.5"
+            auto:format="%.2f °"
+            auto:scales="100"
+            />
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_tmppap"
+            android:key="pref_tmppap"
+            android:defaultValue="10"
+            android:dialogMessage="Please select the percentage to increase the boiler power while brewing"
+            android:max="100"
+            android:title="Pro Active Percentage"
+            android:summary="%d %%"
+            /-->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_tmppap"
+            android:title="Pro Active Percentage"
+            android:dialogMessage="Please select the percentage to increase the boiler power while brewing"
+            android:summary="%s, default: 33 %%"
+            android:defaultValue="33"
+            android:max="100"
+            auto:minn="0"
+            auto:resolution="1"
+            auto:format="%.0f %%"
+            auto:scales="1"
+            />
+
+        <PreferenceScreen
+            android:title="PID"
+            android:key="pref_temperature_pid">
+
+            <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+                android:id="@+id/pref_pd1p"
+                android:key="pref_pd1p"
+                android:defaultValue="10"
+                android:dialogMessage="Please select the Proportional component"
+                android:summary="%d, default: 25"
+                android:max="100"
+                android:title="Proportional component ( P )"
+                / -->
+
+            <net.jayschwa.android.preference.SliderPreference
+                android:key="pref_pd1p"
+                android:title="Proportional component ( P )"
+                android:dialogMessage="Please select the Proportional component"
+                android:summary="%s, default: 25"
+                android:defaultValue="25"
+                android:max="100"
+                auto:minn="0"
+                auto:resolution="1"
+                auto:format="%.0f"
+                auto:scales="1" />
+
+            <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+                android:id="@+id/pref_pd1i"
+                android:key="pref_pd1i"
+                android:defaultValue="10"
+                android:dialogMessage="Please select the Integral component"
+                android:max="100"
+                android:title="Integral component ( I )"
+                android:summary="%d, default: 3"
+                / -->
+
+            <net.jayschwa.android.preference.SliderPreference
+                android:key="pref_pd1i"
+                android:title="Integral component ( I )"
+                android:dialogMessage="Please select the Integral component"
+                android:summary="%s, default: 3"
+                android:defaultValue="3"
+                android:max="10"
+                auto:minn="0"
+                auto:resolution="1"
+                auto:format="%.0f"
+                auto:scales="1" />
+
+            <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+                android:id="@+id/pref_pd1d"
+                android:key="pref_pd1d"
+                android:defaultValue="10"
+                android:dialogMessage="Please select the Derivative component"
+                android:max="255"
+                android:title="Derivative component ( D )"
+                android:summary="%d, default:128 "
+                / -->
+
+            <net.jayschwa.android.preference.SliderPreference
+                android:key="pref_pd1d"
+                android:title="Derivative component ( D )"
+                android:dialogMessage="Please select the Derivative component"
+                android:summary="%s, default: 128"
+                android:defaultValue="128"
+                android:max="256"
+                auto:minn="0"
+                auto:resolution="1"
+                auto:format="%.0f"
+                auto:scales="1" />
+
+            <!-- ListPreference
+                android:key="pref_pd1imn"
+                android:title="Integral ( I ) wind-down minimum"
+                android:summary="%s, default: 1000"
+                android:entries="@array/pid_winddown"
+                android:entryValues="@array/pid_winddown_alias"/ -->
+
+
+
+            <!-- ListPreference
+                android:key="pref_pd1imx"
+                android:title="Integral ( I ) wind-down limit"
+                android:summary="%s, default: 3000"
+                android:entries="@array/pid_winddown"
+                android:entryValues="@array/pid_winddown_alias"/ -->
+
+            <net.jayschwa.android.preference.SliderPreference
+                android:key="pref_pd1imx"
+                android:title="Integral ( I ) wind-down limit"
+                android:dialogMessage="The maximum maintenance power, limiting this helps overshoots and oscillation."
+                android:summary="%s, default: 3750"
+                android:defaultValue="3750"
+                android:max="6000"
+                auto:minn="0"
+                auto:format="%.0f"
+                auto:resolution="250"
+                auto:scales="1"
+                />
+
+            <!-- ListPreference
+                android:key="pref_pd1sz"
+                android:title="Polling interval"
+                android:summary="%s ms, default: 1000 ms"
+                android:entries="@array/pid_interval"
+                android:entryValues="@array/pid_interval"/ -->
+
+            <net.jayschwa.android.preference.SliderPreference
+                android:key="pref_pd1sz"
+                android:title="Polling interval"
+                android:dialogMessage="Default for continous mode: 1000 ms, default for interval mode: 5000 ms."
+                android:summary="%s, default: 1000 ms"
+                android:defaultValue="1000"
+                android:max="10000"
+                auto:minn="1000"
+                auto:format="%.0f ms"
+                auto:resolution="500"
+                />
+
+            <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+                android:id="@+id/pref_pd1id"
+                android:key="pref_pd1id"
+                android:defaultValue="10"
+                android:dialogMessage="Speed at which the error component reacts ( 10 = default, lower is faster, bigger is slow  )"
+                android:max="50"
+                min="1"
+                android:title="I-Speed parameter down"
+                android:summary="%d, default:10 "
+                / -->
+
+
+
+
+            <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+                android:id="@+id/pref_pd1iu"
+                android:key="pref_pd1iu"
+                android:defaultValue="10"
+                android:dialogMessage="Speed at which the error component reacts ( 10 = default, lower is faster, bigger is slow  )"
+                android:max="50"
+                min="1"
+                android:title="Please select the I-Speed parameter down"
+                android:summary="%d, default:10 "
+                / -->
+
+
+
+            <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/temperature/pid"
+                />
+            </Preference>
+
+        </PreferenceScreen>
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/temperature/"
+                />
+
+        </Preference>
+
+    </PreferenceScreen>
+
+    <PreferenceScreen
+        android:title="Pressure"
+        android:key="pref_pp">
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_pp_start"
+            android:key="pref_pp1"
+            android:defaultValue="100"
+            android:dialogMessage="Please select pump pressure to start with"
+            android:max="100"
+            android:title="At start of pull"
+            android:summary="%d %%"
+            android:enabled="true"
+            / -->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_pp1"
+            android:title="At start of pull"
+            android:dialogMessage="Please select pump pressure to start with"
+            android:summary="%s, default: 100 %%"
+            android:defaultValue="100"
+            android:max="100"
+            auto:minn="0"
+            auto:resolution="1"
+            auto:format="%.0f %%"
+            auto:scales="1"
+            />
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_pp_end"
+            android:key="pref_pp2"
+            android:defaultValue="70"
+            android:dialogMessage="Please select pump pressure to end with"
+            android:max="100"
+            android:title="At end of pull"
+            android:summary="%d %%"
+            android:enabled="true"
+
+            / -->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_pp2"
+            android:title="At end of pull"
+            android:dialogMessage="Please select pump pressure to end with"
+            android:summary="%s, default: 100 %%"
+            android:defaultValue="100"
+            android:max="100"
+            auto:minn="0"
+            auto:resolution="1"
+            auto:format="%.0f %%"
+            auto:scales="1"
+            />
+
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_pp_period"
+            android:key="pref_ppt"
+            android:defaultValue="25"
+            android:dialogMessage="Please select the period to taper from the start pressure to the end pressure"
+            android:max="60"
+            android:title="Period"
+            android:enabled="true"
+            android:summary="%d seconds"
+            / -->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_ppt"
+            android:title="Period"
+            android:dialogMessage="Please select the period to taper from the start pressure to the end pressure"
+            android:summary="%s, default: 25 s"
+            android:defaultValue="25"
+            android:max="60"
+            auto:minn="0"
+            auto:resolution="1"
+            auto:format="%.0f s"
+            auto:scales="1"
+            />
+
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/pressure"
+                />
+
+        </Preference>
+
+    </PreferenceScreen>
+
+    <PreferenceScreen
+        android:title="Preinfusion"
+        android:key="pref_pi">
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_pi_shtmx"
+            android:key="pref_shtmx"
+            android:defaultValue="0"
+            android:dialogMessage="Please select total shot time ( 0 for infinity )"
+            android:max="40"
+            android:title="Max shot time"
+            android:summary="%d seconds"
+            / -->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_shtmx"
+            android:title="Max shot time"
+            android:dialogMessage="Please select maximum shot time"
+            android:summary="%s, default: 60 s"
+            android:defaultValue="60"
+            android:max="60"
+            auto:minn="0"
+            auto:resolution="1"
+            auto:format="%.0f s"
+            auto:scales="1"
+            />
+
+        <SwitchPreference
+            android:key="pref_pinbl"
+            android:title="Enable"
+            android:summary="Fill the puck first and pull the shot a couple of seconds later"
+            android:defaultValue="true" />
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_pi_pump"
+            android:dependency="pref_pinbl"
+            android:key="pref_pistrt"
+            android:defaultValue="3"
+            android:dialogMessage="Please select pump time in seconds"
+            android:max="10"
+            android:title="Pump time"
+            android:summary="%d seconds"
+            / -->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_pistrt"
+            android:dependency="pref_pinbl"
+            android:title="Pump time"
+            android:dialogMessage="Please select pump time in seconds"
+            android:summary="%s, default: 3 s"
+            android:defaultValue="3"
+            android:max="10"
+            auto:minn="0"
+            auto:resolution="1"
+            auto:format="%.0f s"
+            auto:scales="1"
+            />
+
+
+        <SwitchPreference
+            android:key="pref_pivlv"
+            android:dependency="pref_pinbl"
+            android:title="Close valve while paused"
+            android:summary=""
+            android:defaultValue="false" />
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_pi_pause"
+            android:dependency="pref_pinbl"
+            android:key="pref_piprd"
+            android:defaultValue="3"
+            android:dialogMessage="Please select pause time in seconds"
+            android:max="10"
+            android:title="Pause time"
+            android:summary="%d seconds"
+            / -->
+
+        <net.jayschwa.android.preference.SliderPreference
+            android:key="pref_piprd"
+            android:dependency="pref_pinbl"
+            android:title="Pause time"
+            android:dialogMessage="Please select pause time in seconds"
+            android:summary="%s, default: 3 s"
+            android:defaultValue="3"
+            android:max="10"
+            auto:minn="0"
+            auto:resolution="1"
+            auto:format="%.0f s"
+            auto:scales="1"
+            />
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/preinfusion/"
+                />
+
+        </Preference>
+
+    </PreferenceScreen>
+
+    <PreferenceScreen
+        xmlns:android="http://schemas.android.com/apk/res/android"
+        android:title="Timers"
+        android:key="pref_timer">
+
+        <SwitchPreference
+            android:key="pref_tmrwnbl"
+            android:title="Enable"
+            android:summary="Automatically turn machine on at a certain time"
+            android:defaultValue="false" />
+
+        <nl.digitalthings.mebarista.TimePreference
+            android:id="@+id/pref_tmron"
+            android:dependency="pref_tmrwnbl"
+            android:key="pref_tmron"
+            android:dialogMessage="Please select the wakeup time"
+            android:title="Wakeup time"
+            />
+
+        <SwitchPreference
+            android:key="pref_tmrsnbl"
+            android:title="Enable"
+            android:summary="Automatically turn machine off at a certain time"
+            android:enabled="true"
+            android:defaultValue="false" />
+
+        <nl.digitalthings.mebarista.TimePreference
+            android:id="@+id/pref_tmroff"
+            android:dependency="pref_tmrsnbl"
+            android:key="pref_tmroff"
+            android:defaultValue="3"
+            android:dialogMessage="Please select the shutdown time"
+            android:title="Shutdown time"
+            android:summary=" seconds"
+            android:enabled="true"
+            />
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/timer/"
+                />
+
+        </Preference>
+
+    </PreferenceScreen>
+
+    <PreferenceScreen
+        android:title="Bluetooth"
+        android:key="pref_bt">
+
+        <nl.digitalthings.mebarista.EditTextPreferenceWithSummary
+            android:id="@+id/pref_bt_devicename"
+            android:key="pref_btname"
+            android:defaultValue="meCoffee"
+            android:title="Device name"
+            android:summary="Connected device has name '%s'"
+            />
+
+        <nl.digitalthings.mebarista.EditTextPreferenceWithSummary
+            android:id="@+id/pref_bt_devicename_prefix"
+            android:key="pref_bt_devicename_prefix"
+            android:defaultValue="meCoffee"
+            android:title="Device name prefix"
+            android:summary="Devices wich names start with '%s' will be automatically connected"
+            />
+
+        <SwitchPreference
+            android:key="pref_bt_bt2_enabled"
+            android:title="Enable BT2 / Classic"
+            android:summary="Scans for BT2 / Classic devices"
+            android:defaultValue="true" />
+
+        <SwitchPreference
+            android:key="pref_bt_ble_enabled"
+            android:title="Enable BLE / Bluetooth Low Energy"
+            android:summary="Scans for BLE / Bluetooth Low Energy devices"
+            android:defaultValue="false" />
+
+        <SwitchPreference
+            android:key="pref_bt_disable"
+            android:title="Disable on close"
+            android:summary="Disable Bluetooth adapter if App is closed"
+            android:defaultValue="false" />
+
+
+        <SwitchPreference
+            android:key="pref_bt_keepdiscovering"
+            android:title="Keep discovering"
+            android:summary="Keep discovering devices when not connected"
+            android:enabled="true"
+            android:defaultValue="false" />
+
+        <!-- nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_bt_scanlimit_minutes"
+            android:dependency="pref_bt_scanlimit"
+            android:key="pref_pt_scanlimit_minutes"
+            android:defaultValue="3"
+            android:dialogMessage="Please select scan time in minutues"
+            android:max="10"
+            android:title="Bluetooth scan time"
+            android:enabled="false"
+            android:summary=" minutes"
+            / -->
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/bluetooth/"
+                />
+
+        </Preference>
+
+    </PreferenceScreen>
+
+    <PreferenceScreen
+        android:title="User interface"
+        android:key="pref_ui">
+
+        <SwitchPreference
+            android:key="pref_ui_graph_enable"
+            android:title="Enable graph"
+            android:summary="Show the temperature graph on the background"
+            android:defaultValue="true" />
+
+        <ListPreference
+            android:key="pref_ui_graph_history"
+            android:title="Graph history"
+            android:dependency="pref_ui_graph_enable"
+            android:entries="@array/graph_history"
+            android:entryValues="@array/graph_history_alias"/>
+
+        <SwitchPreference
+            android:id="@+id/pref_ui_second_sensor"
+            android:key="pref_ui_second_sensor"
+            android:title="Show second sensor"
+            android:summary=""
+            android:defaultValue="false" />
+
+        <CheckBoxPreference
+            android:key="pref_ui_tempcontrol_enable"
+            android:title="Enable temperature control"
+            android:defaultValue="false" />
+
+        <SwitchPreference
+            android:id="@+id/pref_ui_background"
+            android:key="pref_ui_background"
+            android:title="Show background"
+            android:summary=""
+            android:defaultValue="true" />
+
+        <SwitchPreference
+            android:id="@+id/pref_ui_logging"
+            android:key="pref_ui_logging"
+            android:title="Show logging"
+            android:summary=""
+            android:defaultValue="false" />
+
+        <SwitchPreference
+            android:id="@+id/pref_ui_screenwake"
+            android:key="pref_ui_screenwake"
+            android:title="Prevent screen sleep"
+            android:summary=""
+            android:defaultValue="false" />
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/userinterface/"
+                />
+
+        </Preference>
+
+    </PreferenceScreen>
+
+    <!-- PreferenceScreen
+        android:title="Statistics"
+        android:key="pref_statistics">
+
+        <nl.digitalthings.mebarista.PreferencesNumberPicker
+            android:id="@+id/pref_grndr_cnt"
+            android:key="pref_grndr_cnt"
+            android:defaultValue="0"
+            android:dialogMessage="The times the grinder has grinded!"
+            android:enabled="false"
+            android:selectable="false"
+            android:shouldDisableView="false"
+            android:title="Grinder counter"
+            android:summary=" times"
+            android:max="65000"
+            />
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/statistics"
+                />
+
+        </Preference>
+
+    </PreferenceScreen !-->
+
+    <PreferenceScreen
+        android:title="Hardware"
+        android:key="pref_hardware">
+
+        <SwitchPreference
+            android:key="pref_tmrpwr"
+            android:title="Installed as timer"
+            android:summary="Prevent warmup after power outage"
+            android:enabled="true"
+            android:defaultValue="false" />
+
+        <PreferenceScreen
+            android:title="Firmware"
+            android:key="pref_firmware">
+
+            <nl.digitalthings.mebarista.EditTextPreferenceWithSummary
+                android:id="@+id/pref_uname"
+                android:key="pref_uname"
+                android:defaultValue=""
+                android:title="Device firmware"
+                android:summary="Running version: %s"
+                />
+
+            <!-- nl.digitalthings.mebarista.EditTextPreferenceWithSummary
+                android:id="@+id/pref_fw_pin"
+                android:key="pref_fw_pin"
+                android:defaultValue=""
+                android:title="Pin code required for flashing"
+                android:summary="'%s'"
+                / -->
+
+            <SwitchPreference
+                android:id="@+id/pref_support_fw_enable"
+                android:key="pref_support_fw_enable"
+                android:title="Enable"
+                android:summary="Enable Flash Firmware button, only use this if you know what you are doing."
+                android:defaultValue="false" />
+
+            <Preference android:title="Flash firmware V4 ( legacy )"
+                android:summary="Once clicked, the App will reflash your coffee-machine. Use with extreme care."
+                android:dependency="pref_support_fw_enable"
+                android:enabled="false">
+
+                <intent android:targetPackage="nl.digitalthings.mebarista"
+                    android:targetClass="nl.digitalthings.mebarista.MainActivity"
+                    android:data="flashfirmware_V4"
+                    android:dependency="pref_support_fw_enable"
+                    />
+            </Preference>
+
+            <Preference android:title="Flash firmware V9 ( newest )"
+                android:summary="Once clicked, the App will reflash your coffee-machine. Use with extreme care."
+                android:dependency="pref_support_fw_enable"
+                android:enabled="true">
+
+            <intent android:targetPackage="nl.digitalthings.mebarista"
+                    android:targetClass="nl.digitalthings.mebarista.MainActivity"
+                    android:data="flashfirmware_V9"
+                    android:dependency="pref_support_fw_enable"
+                    />
+
+            </Preference>
+
+            <ListPreference
+                android:key="pref_fw_timing"
+                android:title="Flash timing"
+                android:dependency="pref_support_fw_enable"
+                android:defaultValue="250"
+                android:entries="@array/fw_timing"
+                android:entryValues="@array/fw_timing_alias"/>
+
+            <Preference android:title="Help" >
+
+                <intent
+                    android:action="android.intent.action.VIEW"
+                    android:data="https://www.mecoffee.nl/mebarista/help/hardware/firmware/"
+                    />
+
+            </Preference>
+
+        </PreferenceScreen>
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="https://www.mecoffee.nl/mebarista/help/hardware/"
+                />
+
+        </Preference>
+
+    </PreferenceScreen>
+
+    <PreferenceScreen
+        android:title="Support"
+        android:key="pref_support">
+
+
+        <nl.digitalthings.mebarista.EditTextPreferenceWithSummary
+            android:id="@+id/pref_support_email"
+            android:key="pref_support_email"
+            android:defaultValue="support@yourdealer.com"
+            android:title="Helpdesk email address"
+            android:summary="Support tickets are sent to '%s' by default"
+            />
+
+        <Preference android:title="Support ticket" >
+
+            <intent android:targetPackage="nl.digitalthings.mebarista"
+                android:targetClass="nl.digitalthings.mebarista.MainActivity"
+                android:data="supportticket" />
+
+        </Preference>
+
+        <Preference android:title="Credits and Licenses" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="http://www.mecoffee.nl/mebarista/credits/"
+                />
+
+        </Preference>
+
+        <Preference android:title="Help" >
+
+            <intent
+                android:action="android.intent.action.VIEW"
+                android:data="http://www.mecoffee.nl/mebarista/help/support/"
+                />
+
+        </Preference>
+
+    </PreferenceScreen>
+
+</PreferenceScreen>

+ 3 - 0
settings.gradle

@@ -0,0 +1,3 @@
+include ':SliderPreference'
+project(':SliderPreference').projectDir = new File('libs/SliderPreference')
+

+ 553 - 0
src/nl/digitalthings/mebarista/BLEHandler.java

@@ -0,0 +1,553 @@
+package nl.digitalthings.mebarista;
+
+import android.annotation.TargetApi;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothGatt;
+import android.bluetooth.BluetoothGattCallback;
+import android.bluetooth.BluetoothGattCharacteristic;
+import android.bluetooth.BluetoothGattService;
+import android.bluetooth.BluetoothManager;
+import android.bluetooth.BluetoothProfile;
+import android.bluetooth.le.BluetoothLeScanner;
+import android.bluetooth.le.ScanCallback;
+import android.bluetooth.le.ScanFilter;
+import android.bluetooth.le.ScanResult;
+import android.bluetooth.le.ScanSettings;
+import android.content.Context;
+import android.os.Build;
+import android.os.Handler;
+import android.os.Message;
+import android.os.ParcelUuid;
+import android.util.Log;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.Semaphore;
+
+// http://stackoverflow.com/questions/825732/how-can-i-implement-an-outputstream-that-i-can-rewind
+// https://github.com/robokoding/STK500
+// https://github.com/ksksue/PhysicaloidLibrary
+
+@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
+public class BLEHandler {
+
+    private static final String TAG = "BLE";
+
+    public class ble_os extends OutputStream {
+
+        byte[] queue = new byte[20];
+        int queued = 0;
+
+        @Override
+        public void write( int b ) throws IOException {
+
+            queue[ queued++ ] = (byte)b;
+
+            if( queued >= queue.length )
+                flush( );
+
+        }
+
+        @Override
+        public void flush( ) throws IOException {
+
+            // If queue is empty, abort
+            if( queued == 0 )
+                return;
+
+            // Prepare message by copying data in
+            Message m = new Message();
+            m.obj = Arrays.copyOfRange( queue, 0,  queued );
+
+            // Clear queue once copied
+            queued = 0;
+            for( int i = 0; i < queue.length; i++ )
+                queue[ i ] = 0;
+
+            // Test or wait for the output channel to be free
+            try {
+                output_wait.acquire();
+            } catch (InterruptedException e) {
+                throw new IOException( e.getMessage( ) );
+            }
+
+            // Hand the actual sending over to the BLE owning thread
+            write_handler.sendMessage( m );
+
+        }
+
+    }
+
+    public class ble_is extends InputStream {
+
+        @Override
+        public int read () throws IOException {
+
+            // Test or wait for data being available
+            try {
+                ble_available.acquire( );
+            } catch (InterruptedException e) {
+                throw new IOException( e.getMessage() );
+            }
+
+            // Fetch first byte from queue and remove it
+            int res = input_sb.charAt( 0 );
+            input_sb.delete( 0, 1 );
+
+            return res;
+
+        }
+
+        @Override
+        public int available( ) {
+
+            return input_sb.length( );
+
+        }
+
+    }
+
+    // service
+    BaristaService service;
+
+    // BLE
+    BluetoothGattService mBluetoothGattService;
+    BluetoothGatt mBluetoothGatt;
+    BluetoothGattCharacteristic characteristic;
+    BluetoothDevice bledevice;
+
+    StringBuffer input_sb;
+    BluetoothManager btmanager;
+    public ble_os os;
+    public ble_is is;
+    Logx logx;
+    byte[] fw;
+    private final Semaphore ble_available = new Semaphore( 40960, false ), output_wait = new Semaphore( 1, false );
+    boolean connecting = false;
+
+    boolean start_firmware = false;
+
+    Handler write_handler = new Handler() {
+
+        @Override
+        public void handleMessage( Message msg ) {
+
+            if( characteristic == null )
+                return;
+
+            characteristic.setValue( ( byte[] ) msg.obj );
+
+            if( !mBluetoothGatt.writeCharacteristic( characteristic ) )
+                Log.e( TAG, "write failed" );
+
+        }
+
+    };
+
+    public Handler flush_handler = new Handler() {
+
+        @Override
+        public void handleMessage( Message msg ) {
+            try {
+                os.flush();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+
+    };
+
+    // final BluetoothManager mBluetoothManager;
+
+    public BLEHandler( BaristaService serv, BluetoothManager ble_manager) {
+        // mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
+
+
+
+        service = serv;
+        btmanager = ble_manager;
+        input_sb = new StringBuffer();
+         is = new ble_is();
+        os = new ble_os();
+
+        ble_available.drainPermits( );
+    }
+
+
+
+    // https://developer.android.com/guide/topics/connectivity/bluetooth-le.html
+    // http://stackoverflow.com/questions/24780714/hm-10-bluetooth-module-ble-4-0-keep-losing-connection
+    // http://stackoverflow.com/questions/28018722/android-could-not-connect-to-bluetooth-device-on-lollipop
+
+    final BluetoothGattCallback bgc = new BluetoothGattCallback() {
+        @Override
+        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
+
+            if (newState == BluetoothProfile.STATE_CONNECTED) {
+
+//                 BLE_stop();
+
+                Log.i(TAG, "STATE_CONNECTED");
+
+                // mBluetoothGatt.discoverServices();
+
+                mBluetoothAdapter.stopLeScan( mLeScanCallback );
+
+                bledevice = gatt.getDevice();
+                gatt.discoverServices();
+
+            }
+
+            if( newState == BluetoothProfile.STATE_DISCONNECTED ) {
+
+                Log.i(TAG, "STATE_DISCONNECTED");
+
+        //        gatt.close();
+
+                if( bledevice == null ) {
+                    Log.i( TAG, "STATE_DISCONNECTED: was already disconnected, skipping" );
+
+                    return;
+                }
+
+                if( characteristic != null ) {
+                gatt.setCharacteristicNotification( characteristic, false );
+                    characteristic = null; }
+
+ //gatt.close();
+
+               mBluetoothGatt.close();
+
+                mBluetoothGatt = null;
+
+                bledevice = null;
+
+                // gatt.setCharacteristicNotification( characteristic, false ); // Prevents double notifications if reconnected
+
+                // connecting = false;
+                // bledevice = null;
+
+                service.connected( null, null );
+
+                // TODO: moet dit wel?
+
+                //BluetoothAdapter mBluetoothAdapter = btmanager.getAdapter(); // BluetoothAdapter.getDefaultAdapter();
+
+                if( !mBluetoothAdapter.isDiscovering() ) {
+
+                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
+                    // mBluetoothAdapter.startLeScan(new UUID[]{UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb")}, mLeScanCallback); // TODO, when to stop
+                    setup();
+                }
+
+            }
+
+            Log.i( TAG, "connectionstatechange");
+
+        }
+
+        @Override
+        // Characteristic notification
+        public void onCharacteristicChanged(BluetoothGatt gatt,
+                                            BluetoothGattCharacteristic characteristic) {
+
+
+            String out, v = characteristic.getStringValue( 0 );
+/*
+            out = "";
+            for(int i =0; i< v.length(); i++ )
+                out += Integer.toHexString( (int)v.charAt( i ) );
+            System.out.println("char:" + out);
+            System.out.println(v); */
+
+
+            String char_string = characteristic.getStringValue(0);
+            input_sb.append(char_string);
+            ble_available.release(char_string.length());
+
+        }
+
+        @Override
+        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic char2, int status) {
+            if (status != BluetoothGatt.GATT_SUCCESS)
+                Log.e( TAG, "write failed");
+
+            output_wait.release();
+        }
+
+        @Override
+        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
+            if (status == BluetoothGatt.GATT_SUCCESS) {
+                List<BluetoothGattService> gattServices = gatt.getServices();
+
+                for (BluetoothGattService gattService : gattServices) {
+
+                    if ( gattService.getUuid().toString().startsWith( "0000ffe0" ) ) {
+                        // if ("0000ffe0-0000-1000-8000-00805f9b34fb".equals(gattService.getUuid().toString())) {
+
+                        //mBluetoothGattService = gattService;
+                        Log.i( TAG, "Service found");
+
+                        if( characteristic != null ) {
+                            Log.i( TAG, "Chararacterics already set" );
+
+                            gatt.setCharacteristicNotification(characteristic, false);
+
+                            characteristic = null;
+                        }
+
+//                        if( characteristic != null )
+  //                          gatt.setCharacteristicNotification(characteristic, false);
+
+                        characteristic = gattService.getCharacteristic(UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb"));
+
+                        if( characteristic == null ) {
+                            Log.e( TAG, "Characteristic null : not found" );
+                            continue;
+                        }
+
+                        //if( characteristic.getWriteType() == BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE ) {
+                        //    return ;
+                        //}
+
+                        gatt.setCharacteristicNotification(characteristic, true);
+                        characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
+                        if (!gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH))
+                            Log.e( TAG, "no req conn prio");
+
+                        // now we have working input- & output-stream's
+                        // let's run the firmware update if required
+
+                        Log.i( TAG, "Connected?" );
+
+                        //
+                        // tijdelijk uit totdat FW flashing werkt. service.connected( is, os );
+
+                        service.connected(is, os);
+
+                    } else
+                        Log.i( TAG, "more service: " + gattService.getUuid().toString());
+                }
+            } else {
+                Log.i(TAG, "onServicesDiscovered received: " + status);
+            }
+        }
+    };
+
+    final BluetoothAdapter.LeScanCallback mLeScanCallback =
+            new BluetoothAdapter.LeScanCallback() {
+        @Override
+        public void onLeScan(final BluetoothDevice device, int rssi,
+        byte[] scanRecord) {
+
+            if( connecting ) {
+                Log.i( TAG, "meLEScanCallback : backed out connecting" );
+
+                return;
+            }
+
+            if( device.getName() == null ) {
+                Log.i( TAG, "meLEScanCallback : backed out device name null" );
+
+                return;
+            }
+
+            if( !device.getName().startsWith("meCoffee") ) {
+                Log.i( TAG, "meLEScanCallback : backed out device name not meCoffee* but " + device.getName( ) );
+
+                return;
+            }
+
+            if( device == bledevice ) {
+                Log.i(TAG, "mLeScanCallBack: backed out, already connected to this device");
+
+                return ;
+            }
+
+            BluetoothAdapter mBluetoothAdapter = btmanager.getAdapter(); // repeated everywhere because unsure if this is the right call in the right context
+            mBluetoothAdapter.cancelDiscovery();
+
+            Method connectGattMethod = null;
+
+
+            try {
+                Log.i( TAG, "connectGatt -> "  + device.getName() );
+
+                // connecting = true;
+
+                bledevice = device;
+
+                connectGattMethod = device.getClass().getMethod("connectGatt", Context.class, boolean.class, BluetoothGattCallback.class, int.class);
+
+
+            } catch (NoSuchMethodException e) {
+                e.printStackTrace();
+            }
+
+            try {
+
+                // https://stackoverflow.com/questions/22214254/android-ble-connect-slowly : about second boolean, was true, changed to false
+
+                mBluetoothGatt = (BluetoothGatt) connectGattMethod.invoke(device, service.getApplicationContext(), false, bgc, /* TRANSPORT_LE */ 2);
+                //    mBluetoothGatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);
+            } catch (IllegalAccessException e) {
+                e.printStackTrace();
+            } catch (IllegalArgumentException e) {
+                e.printStackTrace();
+            } catch (InvocationTargetException e) {
+                e.printStackTrace();
+            }
+
+        }
+    };
+
+    class MyScanCallback extends ScanCallback {
+//Fields and constructor omitted
+
+        @Override
+        public void onScanResult(int callbackType, ScanResult result) {
+
+            //Will execute on the main thread!
+            //Do the work below on a worker thread instead!
+
+            //if (showldConnect(result)) {
+            //    BluetoothDevice device = result.getDevice();
+            //    scaner.stopScan(this);
+            //    device.connectGatt(context, false, gattCallback);
+           // }
+
+            BluetoothDevice device = result.getDevice();
+
+            Log.i( TAG, "myScanCallback::onScanResult: " + device.getName() );
+
+            if( device != null ) {
+
+                // https://stackoverflow.com/questions/33274009/how-to-prevent-bluetoothgattcallback-from-being-executed-multiple-times-at-a-tim
+
+                bluetoothLeScanner.stopScan( this );
+                //bluetoothLeScanner.
+
+//                if( mBluetoothGatt == null /* || mBluetoothGatt.getDevice() != device */ )
+                    mBluetoothGatt = device.connectGatt( service.getApplicationContext(), false, bgc );
+//                else
+//                    mBluetoothGatt.connect();
+            }
+
+        }
+
+    }
+
+    BluetoothAdapter mBluetoothAdapter;
+    BluetoothLeScanner bluetoothLeScanner;
+
+    //@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
+    public void setup( ) {
+
+        Log.i( TAG, "BLE Started");
+
+        // BLE
+        if( mBluetoothAdapter == null )
+            mBluetoothAdapter = btmanager.getAdapter(); // BluetoothAdapter.getDefaultAdapter();
+
+        if( false ) {
+        /* BluetoothAdapter */
+
+
+            // mBluetoothAdapter.startDiscovery();
+            mBluetoothAdapter.startLeScan(new UUID[]{UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb")}, mLeScanCallback); // TODO, when to stop ?
+        }
+
+        // Static device picking
+        //byte[] address = new byte[] { (byte)0x00, (byte)0x17, (byte)0xEA, (byte)0x93, (byte)0x9F, (byte)0x75}; // V7
+        //byte[] address = new byte[] { (byte)0x00, (byte)0x17, (byte)0xEA, (byte)0x93, (byte)0xA3, (byte)0x8B};
+        //BluetoothDevice device = mBluetoothAdapter.getRemoteDevice( address );
+
+        // https://intersog.com/blog/tech-tips/how-to-work-properly-with-bt-le-on-android/
+
+        ScanSettings scanSettings = new ScanSettings.Builder()
+                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
+                .build();
+
+        //If name or address of peripheral is known
+        ScanFilter scanFilter = new ScanFilter.Builder()
+                .setServiceUuid( new ParcelUuid( UUID.fromString( "0000ffe0-0000-1000-8000-00805f9b34fb") ) )
+                .build();
+
+        // BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
+
+        /* BluetoothLeScanner */
+        if( bluetoothLeScanner == null )
+            bluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
+
+        bluetoothLeScanner.startScan( Collections.singletonList(scanFilter), scanSettings, new MyScanCallback()  );
+
+        Log.i(TAG, "startScan()");
+
+        // API ?? how did this work?
+        // mBluetoothGatt = device.connectGatt(service, true, bgc, BluetoothDevice.TRANSPORT_LE );
+
+        /*
+
+
+        Method connectGattMethod = null;
+
+        try {
+            //connectGattMethod = device.getClass().getMethod("connectGatt", Context.class, boolean.class, BluetoothGattCallback.class, int.class);
+        } catch (NoSuchMethodException e) {
+            e.printStackTrace();
+        }
+
+        try {
+            //mBluetoothGatt = (BluetoothGatt) connectGattMethod.invoke(device, service.getApplicationContext(), true, bgc,  TRANSPORT_LE  2);
+         //    mBluetoothGatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);
+        } catch (IllegalAccessException e) {
+            e.printStackTrace();
+        } catch (IllegalArgumentException e) {
+            e.printStackTrace();
+        } catch (InvocationTargetException e) {
+            e.printStackTrace();
+        }
+
+    }
+ */
+
+    }
+
+    public void discover( ) {
+        System.out.println( "BLE discover" );
+
+        setup( ); // TOD: is dit wel nodig?
+    }
+
+    public void close() {
+
+        Log.i(TAG, "Close");
+
+        BluetoothAdapter mBluetoothAdapter = btmanager.getAdapter(); // repeated everywhere because unsure if this is the right call in the right context
+
+        mBluetoothAdapter.cancelDiscovery();
+
+        if( mBluetoothGatt != null) {
+            if( characteristic != null )
+                mBluetoothGatt.setCharacteristicNotification(characteristic, false);
+
+            mBluetoothGatt.disconnect();
+
+            // mBluetoothGatt.close();
+        }
+
+        service.connected(null, null);
+
+        mBluetoothAdapter.startDiscovery();
+
+    }
+
+}

+ 560 - 0
src/nl/digitalthings/mebarista/BTHandler.java

@@ -0,0 +1,560 @@
+package nl.digitalthings.mebarista;
+
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothSocket;
+import android.bluetooth.BluetoothAdapter;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.SharedPreferences;
+import android.os.Build;
+import android.preference.PreferenceManager;
+import android.util.Log;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.UUID;
+
+public class BTHandler {
+
+    private static final String TAG = "BT2";
+
+    // bluetooth
+    static String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
+    BluetoothAdapter mBluetoothAdapter;
+    BluetoothSocket socket = null;
+    private InputStream inStream;
+    private OutputStream outStream;
+
+    // service
+    BaristaService service;
+
+    // Discovery related state
+    boolean no_connected = false;
+    boolean discovery_allow = true;
+    boolean discovery_running = false;
+    boolean discovery_timer_running = false;
+    Timer discovery_timer = new Timer();
+
+    // Util
+    SharedPreferences sharedPref;
+
+    public BTHandler(BaristaService serv) {
+        Log.i( TAG, "Constructor" );
+
+        // mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
+        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
+
+        service = serv;
+        inStream = null;
+        outStream = null;
+        socket = null;
+
+        // not allowed here:
+        // sharedPref =  PreferenceManager.getDefaultSharedPreferences(service);
+
+        IntentFilter f1, f2, f3, f4, f5, f6; // Not sure if necessary
+
+        // TODO: move over to connect or something
+        service.ma.registerReceiver( mReceiver, f1 = new IntentFilter( BluetoothDevice.ACTION_FOUND ) ); // Don't forget to unregister during onDestroy
+        service.ma.registerReceiver( mReceiver, f2 = new IntentFilter( BluetoothDevice.ACTION_PAIRING_REQUEST ) ); // Don't forget to unregister during onDestroy
+        service.ma.registerReceiver( mReceiver, f3 = new IntentFilter( BluetoothDevice.ACTION_BOND_STATE_CHANGED ) ); // Don't forget to unregister during onDestroy
+        service.ma.registerReceiver( mReceiver, f4 = new IntentFilter( BluetoothDevice.ACTION_ACL_CONNECTED ) ); // Don't forget to unregister during onDestroy
+        service.ma.registerReceiver( mReceiver, f5 = new IntentFilter( BluetoothDevice.ACTION_ACL_DISCONNECTED)); // Don't forget to unregister during onDestroy
+        service.ma.registerReceiver( mReceiver, f6 = new IntentFilter( BluetoothAdapter.ACTION_DISCOVERY_FINISHED)); // Don't forget to unregister during onDestroy
+        service.ma.registerReceiver( mReceiver, f6 = new IntentFilter( BluetoothAdapter.ACTION_DISCOVERY_STARTED)); // Don't forget to unregister during onDestroy
+    }
+
+    // Called from BaristaService upon onDestroy
+    public void close_object() {
+
+        // TODO: or should it be done six times?
+        // crasht soms : Receiver not registered service.ma.unregisterReceiver(mReceiver);
+
+        discovery_timer.cancel();
+
+    }
+
+    // Connect wrappers
+    private BluetoothSocket connect_secure(BluetoothDevice device) {
+        BluetoothSocket socket = null;
+
+        try {
+
+                socket = device.createRfcommSocketToServiceRecord( UUID.fromString(SPP_UUID) );
+
+        } catch (IOException e) {
+
+                try { socket.close(); } catch (IOException e1) { }
+
+                // Creating the socket failed: continue to iterate over bonded devices
+                Log.e( TAG, "Secure SOCKET CREATION failed");
+
+        }
+
+        return socket;
+    }
+
+    private BluetoothSocket connect_insecure(BluetoothDevice device) {
+        BluetoothSocket socket = null;
+
+        try {
+
+            socket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString(SPP_UUID));
+
+        } catch (IOException e) {
+
+                try { socket.close(); } catch (IOException e1) { }
+
+                // Creating the socket failed: continue to iterate over bonded devices
+                Log.e( TAG, "Insecure SOCKET CREATION failed");
+
+        }
+
+        return socket;
+    }
+
+    private BluetoothSocket connect_introspection(BluetoothDevice device) {
+        BluetoothSocket socket = null;
+
+        try {
+
+                Class<?> clazz = device.getClass();
+                Class<?>[] paramTypes = new Class<?>[] {Integer.TYPE};
+
+                Method m = clazz.getMethod("createRfcommSocket", paramTypes);
+                Object[] params = new Object[] {Integer.valueOf(1)};
+
+                socket = (BluetoothSocket) m.invoke(device, params);
+
+        } catch (InvocationTargetException e) {
+
+            try { socket.close(); } catch (IOException e1) { }
+
+            // Creating the socket failed: continue to iterate over bonded devices
+            Log.e( TAG, "Introspection SOCKET CREATION failed");
+        }
+
+        catch (NoSuchMethodException e) {
+
+            try { socket.close(); } catch (IOException e1) { }
+
+            // Creating the socket failed: continue to iterate over bonded devices
+            Log.e( TAG, "Introspection SOCKET CREATION failed");
+        }
+        catch (IllegalAccessException e) {
+
+            try { socket.close(); } catch (IOException e1) { }
+
+            // Creating the socket failed: continue to iterate over bonded devices
+            Log.e( TAG, "Introspection SOCKET CREATION failed");
+        }
+
+        return socket;
+    }
+
+    public boolean scan_connect() {
+
+        if( mBluetoothAdapter == null )
+            return false;
+
+        // SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(service);
+
+        // SharedPreferences preference = service.getSharedPreferences( "preference", 0);
+
+        // Iterate over bonded devices to find clients
+        // while(!stop) {
+
+            for(BluetoothDevice device : mBluetoothAdapter.getBondedDevices() ) {
+            	String deviceName = device.getName();
+            	
+            	if( deviceName == null ) {
+            		// getting friendly bluetooth name may fail
+            		continue;
+            	}
+            	
+                if( !service.is_meCoffee( deviceName ) )
+                    continue;
+
+                Log.i( TAG, "CONNECTING to " + deviceName);
+
+                socket = null;
+
+                // As per the Android documentation:
+                // http://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#connect()
+                mBluetoothAdapter.cancelDiscovery();
+
+                // Use the introspection variant ( for older devices ? )
+                socket = connect_introspection( device );
+
+                // Failed? Continue the loop
+                if( socket == null )
+                    continue;
+
+                // Connect to socket
+                if( !socket.isConnected() ) {
+                    try {
+
+                        socket.connect();
+
+                    } catch (IOException e) {
+
+                        System.out.println( e.getMessage() );
+
+                        try { socket.close();  } catch(Exception ei) {  }
+
+                        // Connecting the socket failed: continue to iterate over bonded devices
+                        Log.e( TAG, "SOCKET CONNECT failed" );
+                        continue;
+                    }
+                }
+
+            // Create input and outputstreams
+            try {
+
+                inStream = socket.getInputStream();
+                outStream = socket.getOutputStream();
+
+            } catch (IOException e1) {
+
+                // Getting the streams failed: continue to iterate over bonded devices
+                try { socket.close();  } catch(Exception ei) {}
+
+                Log.e( TAG, "STREAMs failed" );
+                continue;
+            }
+
+            // Check for nulls
+            if( inStream == null || outStream == null) {
+                try { socket.close();  } catch(Exception ei) {}
+
+                continue;
+            }
+
+            // succeeded: break out of this function by returning...
+            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(service);
+
+            SharedPreferences.Editor editor = settings.edit();
+            editor.putString("pref_bt_devicename", device.getName());
+            editor.commit();
+
+                if( !no_connected )
+                    service.connected( inStream, outStream );
+
+            return true;
+
+        } // bonded_devices
+
+        // Nothing connected
+        return false;
+
+        //    try { Thread.sleep(5000); } catch (InterruptedException e) {  }
+
+        // } // while true
+
+    }  // scan_connect
+
+    // --- AUTO pairing ---
+
+    // http://stackoverflow.com/questions/9608140/how-to-unpair-or-delete-paired-bluetooth-device-programmatically-on-android
+    private void unpairDevice(BluetoothDevice device) {
+        try {
+            Method method = device.getClass().getMethod("removeBond", (Class[]) null);
+            method.invoke(device, (Object[]) null);
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    // http://stackoverflow.com/questions/17168263/how-to-pair-bluetooth-device-programmatically-android
+    // http://developer.android.com/guide/topics/connectivity/bluetooth.html
+    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+        public void onReceive(Context context, Intent intent) {
+            String action = intent.getAction();
+            // TODO: get his out of here, should only happen once
+            sharedPref =  PreferenceManager.getDefaultSharedPreferences(service);
+
+            switch( action ) {
+
+                case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
+
+                    // TODO:
+                    Log.i( TAG, "Discovery started" );
+                    discovery_running = true; // is this even useful ?
+
+                    service.spinner( true );
+                    break;
+
+                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
+                    Log.i( TAG, "Discovery finished" );
+                    discovery_running = false;
+
+                    service.spinner( false );
+
+                    if( inStream != null || !discovery_allow || discovery_running )
+                        return;
+
+                    if( !sharedPref.getBoolean( "pref_bt_keepdiscovering", false ) )
+                        return;
+
+                    if( !mBluetoothAdapter.isDiscovering() && !discovery_timer_running )
+
+                        Log.i(TAG, "Restarting timer for new discovery in " + 60 + " seconds");
+
+                        discovery_timer_running = true;
+
+                        discovery_timer.schedule(new TimerTask() {
+                            @Override
+                            public void run() {
+
+                                if( ! ( mBluetoothAdapter.isDiscovering() || discovery_running ) ) {
+                                    if( inStream == null ) {
+                                        Log.i("BT2", "Restarting discovery from timer" );
+
+                                        mBluetoothAdapter.startDiscovery();
+                                    }
+                                }
+                                else
+                                    Log.i("BT2", "Discovery from timer: discovery was already running?" );
+
+                                discovery_timer_running = false;
+
+                            }
+                        }, 60*1000 );
+
+                    break;
+
+                case BluetoothDevice.ACTION_ACL_CONNECTED:
+                    Log.i( TAG, "ACL Connected" );
+
+                    // TODO: set flag
+                    break;
+
+                case BluetoothDevice.ACTION_ACL_DISCONNECTED:
+
+                    Log.i(TAG, "ACL Disconnected");
+
+                    // TODO: if we were not connected: do nothing ( because spurious messages on app startup )
+
+                    if( inStream != null )
+                    try {
+                        inStream.close();
+                    } catch (IOException e) {
+                        e.printStackTrace();
+                    }
+
+                    if( outStream != null )
+                        try {
+                            outStream.close();
+                        } catch (IOException e) {
+                            e.printStackTrace();
+                        }
+
+                    if( socket != null )
+                        try {
+                            socket.close();
+                        } catch (IOException e) {
+                            e.printStackTrace();
+                        }
+
+                    inStream = null;
+                    outStream = null;
+                    service.connected( inStream, outStream );
+
+                    if( !sharedPref.getBoolean( "pref_bt_keepdiscovering", false ) || !discovery_allow || discovery_running )
+                        return;
+
+                    if( !mBluetoothAdapter.isDiscovering() ) {
+
+                        Log.i("BT2", "Restarting discovery from disconnect" );
+                        mBluetoothAdapter.startDiscovery();
+
+                    }
+                    else
+                        Log.i("BT2", "Discovery from disconnect: was already running?" );
+
+                    break;
+
+                case BluetoothDevice.ACTION_FOUND:
+                    {
+                        discovery_running = true; // apparently we are discovering
+
+                        BluetoothDevice device_discovered = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+                        Log.i( TAG, "discovered " + device_discovered.getName());
+
+                        // Do not take action if we are currently connected
+                        if( inStream != null )
+                            return;
+
+                        // Only service BT2
+                        if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&  device_discovered.getType() != BluetoothDevice.DEVICE_TYPE_CLASSIC )
+                            return;
+
+                        // Only service devices which name is right
+                        if( !service.is_meCoffee( device_discovered.getName() ) )
+                            return;
+
+                        Log.i( TAG, "Checking device" );
+                        // If we are currently connected to another device, do nothing
+                        // TODO
+
+                        // If already bonded to this device, do nothing
+                        if( device_discovered.getBondState() == BluetoothDevice.BOND_BONDED ) {
+                            Log.i( TAG, "Already bonded" );
+
+                            scan_connect();
+
+                            return;
+                        }
+
+                        // We are trying to pair to a new device, stop discovering
+                        // http://stackoverflow.com/questions/16326750/cant-cancel-bluetooth-discovery-process
+                        // mBluetoothAdapter.cancelDiscovery(); according to SO link, unreliable
+
+                        // Break existing bonds
+                        for(BluetoothDevice device_bonded : mBluetoothAdapter.getBondedDevices() ) {
+
+                            if( service.is_meCoffee( device_bonded.getName() ) ) {
+
+                                Log.i( TAG, "Unbonded " + device_bonded.getName() );
+                                unpairDevice( device_bonded );
+
+                            }
+
+                        }
+
+                        mBluetoothAdapter.cancelDiscovery();
+
+                        Log.i( TAG, "Pairing" );
+                        // Programmatically pair with the device
+
+                        if( !device_discovered.setPin( "4321".getBytes() ) )
+                            Log.i( TAG, "setPin failed" );
+
+                        try {
+                            if (!device_discovered.setPairingConfirmation(false))
+                                Log.i(TAG, "setPairingConfirmation failed");
+                        }
+                        catch( Exception e ) {
+                            Log.i(TAG, "setPairingConfirmation exception");
+                        }
+
+                        if ( !device_discovered.createBond() ) {
+
+                            Log.i( TAG, "createBond failed: restarting discovery" );
+
+                            mBluetoothAdapter.startDiscovery();
+                        }
+
+                    }
+                    break;
+
+                case BluetoothDevice.ACTION_PAIRING_REQUEST:
+                    Log.i( TAG, "ACTION_PAIRING_REQUEST" );
+                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+
+                    // device.setPairingConfirmation(false);
+                    device.setPin( "4321".getBytes() );
+                    break;
+
+                case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
+                    if( intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1) == BluetoothDevice.BOND_BONDED )
+                        scan_connect();
+                    break;
+
+                default:
+                    Log.e( TAG, "unknown action: " + action );
+                    break;
+            }
+
+        }
+    };
+
+
+
+    public void discover() {
+
+        discovery_allow = true;
+
+        if( mBluetoothAdapter == null )
+            return;
+
+        if( scan_connect() ) {
+            Log.i( TAG, "Connected already paired device" );
+            return ;
+        }
+
+        Log.i(TAG, "No connected device was able to connect or found, discovering");
+        mBluetoothAdapter.startDiscovery();
+
+    }
+
+    public void discover_stop() {
+/*
+        try {
+            service.ma.unregisterReceiver(mReceiver);
+        }
+        catch( Exception e ) {
+            // TODO: do better on mReceiver
+        }
+*/
+        discovery_allow = false;
+
+        mBluetoothAdapter.cancelDiscovery();
+
+        discovery_timer.cancel();
+
+        discovery_timer = new Timer();
+    }
+
+    void close() {
+        Log.i( TAG, "Closing" );
+        if( inStream != null )
+        try {
+            inStream.close();
+            inStream = null;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        if( outStream != null )
+        try {
+            outStream.close();
+            outStream = null;
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        if( socket != null )
+            try { socket.close(); socket = null; } catch (IOException e1) { }
+
+        // TODO: waarom service niet informeren?
+
+    }
+
+    public void write(byte[] bytes) {
+
+        if(outStream != null) {
+
+            try {
+                outStream.write(bytes);
+                outStream.flush();
+            } catch (IOException e) {
+
+                e.printStackTrace();
+
+            }
+        }
+        else
+            Log.i( TAG, "outStream null, not writing" );
+
+    }
+
+}

Разница между файлами не показана из-за своего большого размера
+ 1506 - 0
src/nl/digitalthings/mebarista/BaristaService.java


+ 26 - 0
src/nl/digitalthings/mebarista/EditTextPreferenceWithSummary.java

@@ -0,0 +1,26 @@
+package nl.digitalthings.mebarista;
+
+import android.content.Context;
+import android.preference.EditTextPreference;
+import android.util.AttributeSet;
+
+public class EditTextPreferenceWithSummary extends EditTextPreference {
+
+
+    public EditTextPreferenceWithSummary(Context context, AttributeSet attrs, int defStyle) {
+        super(context, attrs, defStyle);
+    }
+
+    public EditTextPreferenceWithSummary(Context context, AttributeSet attrs) {
+        super(context, attrs);
+    }
+
+    public EditTextPreferenceWithSummary(Context context) {
+        super(context);
+    }
+
+    @Override
+    public String getSummary() {
+        return  String.format( super.getSummary().toString(), super.getPersistedString( "" ) ); // super.getSummary().toString() + super.getPersistedString( "" );
+    }
+}

+ 794 - 0
src/nl/digitalthings/mebarista/Gauge.java

@@ -0,0 +1,794 @@
+// Copyright (c) 2010, Freddy Martens (http://atstechlab.wordpress.com), 
+// MindTheRobot (http://mindtherobot.com/blog/)  and contributors
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without modification, 
+// are permitted provided that the following conditions are met:
+//
+//	* Redistributions of source code must retain the above copyright notice, 
+//	  this list of conditions and the following disclaimer.
+//	* Redistributions in binary form must reproduce the above copyright notice, 
+//	  this list of conditions and the following disclaimer in the documentation 
+//	  and/or other materials provided with the distribution.
+//	* Neither the name of Ondrej Zara nor the names of its contributors may be used 
+//	  to endorse or promote products derived from this software without specific 
+//	  prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
+// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
+// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
+// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
+// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
+// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
+// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+package nl.digitalthings.mebarista;
+
+import nl.digitalthings.mebarista.R;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.BitmapShader;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.LinearGradient;
+import android.graphics.Matrix;
+import android.graphics.Paint;
+import android.graphics.Path;
+import android.graphics.RadialGradient;
+import android.graphics.RectF;
+import android.graphics.Shader;
+import android.graphics.Typeface;
+import android.os.Bundle;
+import android.os.Parcelable;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.View;
+import android.content.res.TypedArray;
+
+public final class Gauge extends View {
+
+	private static final String TAG = Gauge.class.getSimpleName();
+	
+	// drawing tools
+	private RectF rimRect;
+	private Paint rimPaint;
+	private Paint rimCirclePaint;
+	
+	private RectF faceRect;
+	private Bitmap faceTexture;
+	private Paint facePaint;
+	private Paint rimShadowPaint;
+	
+	private Paint scalePaint;
+	private RectF scaleRect;
+
+	private RectF valueRect;
+	private RectF rangeRect;
+
+	private Paint rangeOkPaint;
+	private Paint rangeWarningPaint;
+	private Paint rangeErrorPaint;
+	private Paint rangeAllPaint;
+	
+	private Paint valueOkPaint;
+	private Paint valueWarningPaint;
+	private Paint valueErrorPaint;
+	private Paint valueAllPaint;
+		
+	private Paint unitPaint;	
+	private Path  unitPath;
+	private RectF unitRect;
+
+	private Paint lowerTitlePaint;	
+	private Paint upperTitlePaint;	
+	private Path  lowerTitlePath;
+	private Path  upperTitlePath;
+	private RectF titleRect;
+
+	private Paint handPaint;
+	private Path handPath;
+
+	private Paint handScrewPaint;
+	
+	private Paint backgroundPaint; 
+	// end drawing tools
+	
+	private Bitmap background; // holds the cached static part
+	
+	// scale configuration
+	// Values passed as property. Defaults are set here.
+	private boolean showHand                 = true;
+	private boolean showGauge                = false;
+	private boolean showRange                = false;
+	
+	private int totalNotches                 = 120; // Total number of notches on the scale. 
+	private int incrementPerLargeNotch       = 10;
+	private int incrementPerSmallNotch       = 2;
+
+	private int scaleColor                   = 0x9f004d0f;
+	private int scaleCenterValue             = 0; // the one in the top center (12 o'clock), this corresponds with -90 degrees
+	private int scaleMinValue                = -90;
+	private int scaleMaxValue                = 120;
+
+    private int angleMinValue                = -120;
+    private int angleMaxValue                = 120;
+
+    private float degreeMinValue             = 0;
+	private float degreeMaxValue             = 0;
+
+	private int rangeOkColor                 = 0x9f00ff00;
+	private int rangeOkMinValue              = scaleMinValue;
+	private int rangeOkMaxValue              = 45;
+	private float degreeOkMinValue           = 0;
+	private float degreeOkMaxValue           = 0;
+
+	private int rangeWarningColor            = 0x9fff8800;
+	private int rangeWarningMinValue         = rangeOkMaxValue;
+	private int rangeWarningMaxValue         = 80;
+	private float degreeWarningMinValue      = 0;
+	private float degreeWarningMaxValue      = 0;
+
+	private int rangeErrorColor              = 0x9fff0000;
+	private int rangeErrorMinValue           = rangeWarningMaxValue;
+	private int rangeErrorMaxValue           = 120;
+	private float degreeErrorMinValue        = 0;
+	private float degreeErrorMaxValue        = 0;
+	
+	private String lowerTitle                = "www.ats-global.com";
+	private String upperTitle                = "Visit http://atstechlab.wordpress.com";
+	private String unitTitle                 = "\u2103";
+
+	// Fixed values.
+	private static float scalePosition = 0.10f;  // The distance from the rim to the scale
+	private static float valuePosition = 0.285f; // The distance from the rim to the ranges
+	private static float rangePosition = 0.122f; // The distance from the rim to the ranges
+	private static float titlePosition = 0.145f; // The Distance from the rim to the titles
+	private static float unitPosition  = 0.300f; // The distance from the rim to the unit
+	private static float rimSize       = 0.02f;
+
+	private  float degreesPerNotch      = 360.0f/totalNotches;
+	private static final int centerDegrees   =  -90; // the one in the top center (12 o'clock), this corresponds with -90 degrees
+
+	// hand dynamics 
+	private boolean dialInitialized         = false;
+	private float currentValue              = scaleCenterValue;
+	private float targetValue               = scaleCenterValue;
+	private float dialVelocity              = 0.0f;
+	private float dialAcceleration          = 0.0f;
+	private long lastDialMoveTime           = -1L;
+	
+	
+	public Gauge(Context context) {
+		super(context);
+		init(context, null);
+	}
+
+	public Gauge(Context context, AttributeSet attrs) {
+		super(context, attrs);
+		init(context, attrs);
+	}
+
+	public Gauge(Context context, AttributeSet attrs, int defStyle) {
+		super(context, attrs, defStyle);
+		init(context, attrs);
+	}
+	
+	@Override
+	protected void onAttachedToWindow() {
+		super.onAttachedToWindow();
+	}
+
+	@Override
+	protected void onDetachedFromWindow() {
+		super.onDetachedFromWindow();
+	}
+	
+	@Override
+	protected void onRestoreInstanceState(Parcelable state) {
+		Bundle bundle = (Bundle) state;
+		Parcelable superState = bundle.getParcelable("superState");
+		super.onRestoreInstanceState(superState);
+		
+		dialInitialized  = bundle.getBoolean("dialInitialized");
+		currentValue     = bundle.getFloat("currentValue");
+		targetValue       = bundle.getFloat("targetValue");
+		dialVelocity     = bundle.getFloat("dialVelocity");
+		dialAcceleration = bundle.getFloat("dialAcceleration");
+		lastDialMoveTime = bundle.getLong("lastDialMoveTime");
+	}
+
+	@Override
+	protected Parcelable onSaveInstanceState() {
+		Parcelable superState = super.onSaveInstanceState();
+		
+		Bundle state = new Bundle();
+		state.putParcelable("superState", superState);
+		state.putBoolean("dialInitialized", dialInitialized);
+		state.putFloat("currentValue", currentValue);
+		state.putFloat("targetValue", targetValue);
+		state.putFloat("dialVelocity", dialVelocity);
+		state.putFloat("dialAcceleration", dialAcceleration);
+		state.putLong("lastDialMoveTime", lastDialMoveTime);
+		return state;
+	}
+
+	private void init(Context context, AttributeSet attrs) {
+		// Get the properties from the resource file.
+		// setLayerType(View.LAYER_TYPE_SOFTWARE, null);
+
+		if (context != null && attrs != null){
+			TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Dial);
+			showRange              = a.getBoolean(R.styleable.Dial_showRange,          showRange);
+			showGauge              = a.getBoolean(R.styleable.Dial_showGauge,          showGauge);
+			//showHand               = a.getBoolean(R.styleable.Dial_showHand,           showHand);
+
+			totalNotches           = a.getInt(R.styleable.Dial_totalNotches,           totalNotches);
+			incrementPerLargeNotch = a.getInt(R.styleable.Dial_incrementPerLargeNotch, incrementPerLargeNotch);
+			incrementPerSmallNotch = a.getInt(R.styleable.Dial_incrementPerSmallNotch, incrementPerSmallNotch);
+			scaleCenterValue       = a.getInt(R.styleable.Dial_scaleCenterValue,       scaleCenterValue);
+			scaleColor             = a.getInt(R.styleable.Dial_scaleColor,             scaleColor);
+			scaleMinValue          = a.getInt(R.styleable.Dial_scaleMinValue,          scaleMinValue);
+			scaleMaxValue          = a.getInt(R.styleable.Dial_scaleMaxValue,          scaleMaxValue);
+            angleMinValue          = a.getInt(R.styleable.Dial_angleMinValue,          angleMinValue);
+            angleMaxValue          = a.getInt(R.styleable.Dial_angleMaxValue,          angleMaxValue);
+
+            rangeOkColor           = a.getInt(R.styleable.Dial_rangeOkColor,           rangeOkColor);
+			rangeOkMinValue        = a.getInt(R.styleable.Dial_rangeOkMinValue,        rangeOkMinValue);
+			rangeOkMaxValue        = a.getInt(R.styleable.Dial_rangeOkMaxValue,        rangeOkMaxValue);
+			rangeWarningColor      = a.getInt(R.styleable.Dial_rangeWarningColor,      rangeWarningColor);
+			rangeWarningMinValue   = a.getInt(R.styleable.Dial_rangeWarningMinValue,   rangeWarningMinValue);
+			rangeWarningMaxValue   = a.getInt(R.styleable.Dial_rangeWarningMaxValue,   rangeWarningMaxValue);
+			rangeErrorColor        = a.getInt(R.styleable.Dial_rangeErrorColor,        rangeErrorColor);
+			rangeErrorMinValue     = a.getInt(R.styleable.Dial_rangeErrorMinValue,     rangeErrorMinValue);
+			rangeErrorMaxValue     = a.getInt(R.styleable.Dial_rangeErrorMaxValue,     rangeErrorMaxValue);
+			String unitTitle       = a.getString(R.styleable.Dial_unitTitle);
+			String lowerTitle      = a.getString(R.styleable.Dial_lowerTitle);
+			String upperTitle      = a.getString(R.styleable.Dial_upperTitle);
+			if (unitTitle != null) this.unitTitle = unitTitle;
+			if (lowerTitle != null) this.lowerTitle = lowerTitle;
+			if (upperTitle != null) this.upperTitle = upperTitle;
+		}
+		degreeMinValue        = valueToAngle(scaleMinValue)        + centerDegrees;
+		degreeMaxValue        = valueToAngle(scaleMaxValue)        + centerDegrees;
+		degreeOkMinValue      = valueToAngle(rangeOkMinValue)      + centerDegrees;
+		degreeOkMaxValue      = valueToAngle(rangeOkMaxValue)      + centerDegrees;
+		degreeWarningMinValue = valueToAngle(rangeWarningMinValue) + centerDegrees;
+		degreeWarningMaxValue = valueToAngle(rangeWarningMaxValue) + centerDegrees;
+		degreeErrorMinValue   = valueToAngle(rangeErrorMinValue)   + centerDegrees;
+		degreeErrorMaxValue   = valueToAngle(rangeErrorMaxValue)   + centerDegrees;
+
+        degreesPerNotch      = ( angleMaxValue - angleMinValue )*1.0f / totalNotches;
+
+        // initDrawingTools();
+	}
+
+	private void initDrawingTools() {
+		// All drawing has been scaled to actual pixels because of :
+		// https://groups.google.com/forum/#!msg/android-developers/eTxV4KPy1G4/tAe2zUPCjMcJ
+
+		int w = getWidth(), h = getHeight();
+		rimRect = new RectF(0.0f, 0.0f, getWidth() /* 1.0f */, getHeight() /* 1.0f */);
+
+		scalePosition = 0.10f * getWidth();  // The distance from the rim to the scale
+		valuePosition = 0.285f * getWidth(); // The distance from the rim to the ranges
+		rangePosition = 0.122f * getWidth(); // The distance from the rim to the ranges
+		titlePosition = 0.145f * getWidth(); // The Distance from the rim to the titles
+		unitPosition  = 0.300f * getWidth(); // The distance from the rim to the unit
+		rimSize       = 0.02f * getWidth();
+
+
+		faceRect = new RectF();
+		faceRect.set(rimRect.left  + rimSize, rimRect.top    + rimSize, 
+			         rimRect.right - rimSize, rimRect.bottom - rimSize);		
+
+		scaleRect = new RectF();
+		scaleRect.set(faceRect.left + scalePosition, faceRect.top + scalePosition,
+					  faceRect.right - scalePosition, faceRect.bottom - scalePosition);
+
+		rangeRect = new RectF();
+		rangeRect.set(faceRect.left  + rangePosition, faceRect.top    + rangePosition,
+				      faceRect.right - rangePosition, faceRect.bottom - rangePosition);
+		
+		valueRect = new RectF();
+		valueRect.set(faceRect.left  + valuePosition, faceRect.top    + valuePosition,
+				      faceRect.right - valuePosition, faceRect.bottom - valuePosition);
+
+		titleRect = new RectF();
+		titleRect.set(faceRect.left  + titlePosition, faceRect.top    + titlePosition,
+					  faceRect.right - titlePosition, faceRect.bottom - titlePosition);
+
+		unitRect = new RectF();
+		unitRect.set(faceRect.left  + unitPosition, faceRect.top    + unitPosition,
+					 faceRect.right - unitPosition, faceRect.bottom - unitPosition);
+		
+		faceTexture = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.plastic);
+		BitmapShader paperShader = new BitmapShader(faceTexture, 
+												    Shader.TileMode.MIRROR, 
+												    Shader.TileMode.MIRROR);
+		Matrix paperMatrix = new Matrix();
+		paperMatrix.setScale(1.0f / faceTexture.getWidth(),
+				1.0f / faceTexture.getHeight());
+
+		paperShader.setLocalMatrix(paperMatrix);
+
+		rimShadowPaint = new Paint();
+		rimShadowPaint.setShader(new RadialGradient(0.5f * getWidth(), 0.5f * getHeight(), faceRect.width() / 2.0f,
+				new int[]{0x00000000, 0x00000500, 0x50000500},
+				new float[]{0.96f, 0.96f, 0.99f},
+				Shader.TileMode.MIRROR));
+		rimShadowPaint.setStyle(Paint.Style.FILL);
+
+		// the linear gradient is a bit skewed for realism
+		rimPaint = new Paint();
+		rimPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
+		rimPaint.setShader(new LinearGradient(0.40f * getWidth(), 0.0f, 0.60f * getWidth(), 1.0f * getHeight(),
+										   Color.rgb(0xf0, 0xf5, 0xf0),
+										   Color.rgb(0x30, 0x31, 0x30),
+										   Shader.TileMode.CLAMP));		
+
+		rimCirclePaint = new Paint();
+		//rimCirclePaint.setAntiAlias(true);
+		rimCirclePaint.setStyle(Paint.Style.STROKE);
+		rimCirclePaint.setColor(Color.argb(0x4f, 0x33, 0x36, 0x33));
+		rimCirclePaint.setStrokeWidth(0.005f * getWidth() );
+		
+		facePaint = new Paint();
+		facePaint.setFilterBitmap(true);
+		facePaint.setStyle(Paint.Style.FILL);
+		facePaint.setShader(paperShader);
+
+		scalePaint = new Paint();
+		scalePaint.setStyle(Paint.Style.STROKE);
+		scalePaint.setColor(scaleColor);
+		scalePaint.setStrokeWidth(0.005f * getWidth() );
+		scalePaint.setAntiAlias(true);
+		//
+		// scalePaint.setTextSize(0.045f);
+
+        // http://stackoverflow.com/questions/13974129/android-4-2-1-wrong-character-kerning-spacing
+        scalePaint.setTextSize( 0.045f * getWidth() );
+        scalePaint.setLinearText(true);
+
+        scalePaint.setTypeface(Typeface.SANS_SERIF);
+		scalePaint.setTextScaleX(0.8f);
+		scalePaint.setTextAlign(Paint.Align.CENTER);
+		
+		rangeOkPaint = new Paint();
+		rangeOkPaint.setStyle(Paint.Style.STROKE);
+		rangeOkPaint.setColor(rangeOkColor);
+		rangeOkPaint.setStrokeWidth(0.012f * getWidth() );
+		rangeOkPaint.setAntiAlias(true);
+
+		rangeWarningPaint = new Paint();
+		rangeWarningPaint.setStyle(Paint.Style.STROKE);
+		rangeWarningPaint.setColor(rangeWarningColor);
+		rangeWarningPaint.setStrokeWidth(0.012f * getWidth() );
+		rangeWarningPaint.setAntiAlias(true);
+
+		rangeErrorPaint = new Paint();
+		rangeErrorPaint.setStyle(Paint.Style.STROKE);
+		rangeErrorPaint.setColor(rangeErrorColor);
+		rangeErrorPaint.setStrokeWidth(0.012f * getWidth() );
+		rangeErrorPaint.setAntiAlias(true);
+
+		rangeAllPaint = new Paint();
+		rangeAllPaint.setStyle(Paint.Style.STROKE);
+		rangeAllPaint.setColor(0xcff8f8f8);
+		rangeAllPaint.setStrokeWidth(0.012f * getWidth() );
+		rangeAllPaint.setAntiAlias(true);
+		rangeAllPaint.setShadowLayer(0.005f, -0.002f, -0.002f, 0x7f000000);
+
+		valueOkPaint = new Paint();
+		valueOkPaint.setStyle(Paint.Style.STROKE);
+		valueOkPaint.setColor(rangeOkColor);
+		valueOkPaint.setStrokeWidth(0.20f * getWidth() );
+		valueOkPaint.setAntiAlias(true);
+
+		valueWarningPaint = new Paint();
+		valueWarningPaint.setStyle(Paint.Style.STROKE);
+		valueWarningPaint.setColor(rangeWarningColor);
+		valueWarningPaint.setStrokeWidth(0.20f * getWidth() );
+		valueWarningPaint.setAntiAlias(true);
+
+		valueErrorPaint = new Paint();
+		valueErrorPaint.setStyle(Paint.Style.STROKE);
+		valueErrorPaint.setColor(rangeErrorColor);
+		valueErrorPaint.setStrokeWidth(0.20f * getWidth() );
+		valueErrorPaint.setAntiAlias(true);
+
+		valueAllPaint = new Paint();
+		valueAllPaint.setStyle(Paint.Style.STROKE);
+		valueAllPaint.setColor(0xcff8f8f8);
+		valueAllPaint.setStrokeWidth(0.20f * getWidth() );
+		valueAllPaint.setAntiAlias(true);
+		valueAllPaint.setShadowLayer(0.005f, -0.002f, -0.002f, 0x7f000000);
+
+		unitPaint = new Paint();
+		unitPaint.setColor(0xaf0c0c0c);
+		unitPaint.setAntiAlias(true);
+		unitPaint.setTypeface(Typeface.DEFAULT_BOLD);
+		unitPaint.setTextAlign(Paint.Align.CENTER);
+		unitPaint.setTextSize(0.05f * getWidth() );
+		unitPaint.setTextScaleX(0.8f);
+
+		upperTitlePaint = new Paint();
+		upperTitlePaint.setColor(0xaf0c0c0c);
+		upperTitlePaint.setAntiAlias(true);
+		upperTitlePaint.setTypeface(Typeface.DEFAULT_BOLD);
+		upperTitlePaint.setTextAlign(Paint.Align.CENTER);
+		upperTitlePaint.setTextSize(0.09f * getWidth() );
+		upperTitlePaint.setTextScaleX(0.8f);
+
+		lowerTitlePaint = new Paint();
+		lowerTitlePaint.setColor(0xaf0c0c0c);
+		lowerTitlePaint.setAntiAlias(true);
+		lowerTitlePaint.setTypeface(Typeface.DEFAULT_BOLD);
+		lowerTitlePaint.setTextAlign(Paint.Align.CENTER);
+		lowerTitlePaint.setTextSize(0.04f * getWidth() );
+		lowerTitlePaint.setTextScaleX(0.8f);
+
+
+		handPaint = new Paint();
+		handPaint.setAntiAlias(true);
+
+		handPaint.setColor(0xff392f2c);
+		//handPaint.setShadowLayer(0.01f, -0.005f, -0.005f, 0x7f000000);
+		handPaint.setStyle(Paint.Style.FILL);
+        handPaint.setStrokeWidth(0.1f);
+        //handPaint.setColor(android.graphics.Color.RED);
+        //handPaint.setStyle(Paint.Style.STROKE);
+
+		handScrewPaint = new Paint();
+
+		handScrewPaint.setAntiAlias(true);
+		//handScrewPaint.setColor(0xff493f3c);
+		handScrewPaint.setColor(0xffff3f3c);
+		handScrewPaint.setStyle(Paint.Style.FILL);
+		
+		backgroundPaint = new Paint();
+		backgroundPaint.setFilterBitmap(true);
+
+		unitPath = new Path();
+		unitPath.addArc(unitRect, 180.0f, 180.0f);
+
+		upperTitlePath = new Path();
+		upperTitlePath.addArc(titleRect, 180.0f, 180.0f);
+
+		lowerTitlePath = new Path();
+		lowerTitlePath.addArc(titleRect, -180.0f, -180.0f);
+
+		// The hand is drawn with the tip facing up. That means when the image is not rotated, the tip 
+		// faces north. When the the image is rotated -90 degrees, the tip is facing west and so on.
+		handPath = new Path();
+		// handPath.setFillType(Path.FillType.EVEN_ODD);//   X      Y
+
+		handPath.moveTo(0.5f * w, (0.5f + 0.2f) * h);                                 // 0.500, 0.700
+
+		handPath.lineTo( ( 0.5f - 0.010f ) * w, ( 0.5f + 0.2f - 0.007f ) * h);               // 0.490, 0.630
+
+		handPath.lineTo( ( 0.5f - 0.002f ) * w, ( 0.5f - 0.40f ) * h);                       // 0.498, 0.100
+
+		handPath.lineTo( ( 0.5f + 0.002f ) * w, ( 0.5f - 0.40f ) * h);                       // 0.502, 0.100
+
+		handPath.lineTo((0.5f + 0.010f) * w, (0.5f + 0.2f - 0.007f) * h);               // 0.510, 0.630
+
+		//handPath.lineTo(0.5f * w, 0.5f + 0.2f * h);                                 // 0.500, 0.700
+
+		handPath.addCircle(0.5f * w, 0.5f * h, 0.025f * w, Path.Direction.CW);
+
+		handPath.close();
+
+    }
+
+    @Override
+	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+		//Log.d(TAG, "Width spec: " + MeasureSpec.toString(widthMeasureSpec));
+		//Log.d(TAG, "Height spec: " + MeasureSpec.toString(heightMeasureSpec));
+		
+		int widthMode = MeasureSpec.getMode(widthMeasureSpec);
+		int widthSize = MeasureSpec.getSize(widthMeasureSpec);
+		
+		int heightMode = MeasureSpec.getMode(heightMeasureSpec);
+		int heightSize = MeasureSpec.getSize(heightMeasureSpec);
+		
+		int chosenWidth = chooseDimension(widthMode, widthSize);
+		int chosenHeight = chooseDimension(heightMode, heightSize);
+		
+		int chosenDimension = Math.min(chosenWidth, chosenHeight);
+		
+		setMeasuredDimension(chosenDimension, chosenDimension);
+	}
+	
+	private int chooseDimension(int mode, int size) {
+		if (mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY) {
+			return size;
+		} else { // (mode == MeasureSpec.UNSPECIFIED)
+			return getPreferredSize();
+		} 
+	}
+	
+	// in case there is no size specified
+	private int getPreferredSize() {
+		return 250;
+	}
+
+	private void drawRim(Canvas canvas) {
+		// first, draw the metallic body
+		canvas.drawOval(rimRect, rimPaint);
+		// now the outer rim circle
+		canvas.drawOval(rimRect, rimCirclePaint);
+	}
+	
+	private void drawFace(Canvas canvas) {		
+		canvas.drawOval(faceRect, facePaint);
+		// draw the inner rim circle
+
+		// was: canvas.drawOval(faceRect, rimCirclePaint);
+		canvas.drawOval(faceRect, rimCirclePaint);
+
+		// draw the rim shadow inside the face
+		canvas.drawOval(faceRect, rimShadowPaint); // boosdoener
+	}
+
+
+	private void drawBackground(Canvas canvas) {
+		if (background == null) {
+			Log.w(TAG, "Background not created");
+		} else {
+			canvas.drawBitmap(background, 0, 0, backgroundPaint);
+		}
+	}
+
+    private void fa( Canvas canvas, String text, Paint p, float x, float y ) {
+        Path mTextOutlinePath = new Path();
+
+        // adjust the x,y text origin to your personal needs
+        p.getTextPath(text, 0, text.length(), x /* getPaddingLeft() */, y /* getBaseline() */, mTextOutlinePath);
+		canvas.drawPath(mTextOutlinePath, p);
+        // canvas.drawPath(mTextOutlinePath, mStrokePaint);
+
+    }
+	private void drawScale(Canvas canvas) {
+		// Draw the circle
+		canvas.drawOval(scaleRect, scalePaint);
+
+		for (int i = 0; i <= totalNotches; ++i) {
+
+			canvas.save(Canvas.MATRIX_SAVE_FLAG);
+			canvas.rotate(degreeOkMinValue + 90 + degreesPerNotch * i, 0.5f * getWidth(), 0.5f * getHeight());
+
+			float y1 = scaleRect.top;
+			float y2 = y1 - 0.015f * getHeight();
+			float y3 = y1 - 0.025f * getHeight();
+			
+			int value = notchToValue(i);
+
+			if (i % (incrementPerLargeNotch/incrementPerSmallNotch) == 0) {
+				/* if (value >= scaleMinValue && value <= scaleMaxValue) { */
+					// draw a nick
+					canvas.drawLine(0.5f * getWidth(), y1, 0.5f * getWidth(), y3, scalePaint);
+
+					String valueString = Integer.toString(value);
+
+                    canvas.drawText(valueString, 0.5f * getWidth(), y3 - 0.015f * getWidth(), scalePaint);
+
+				/* } */
+			}
+			else{
+				/* if (value >= scaleMinValue && value <= scaleMaxValue) { */
+					// draw a nick
+					canvas.drawLine(0.5f * getWidth(), y1, 0.5f * getWidth(), y2, scalePaint);
+				/* } */
+			}
+
+			canvas.restore();
+		}
+
+	}
+	
+	private void drawScaleRanges(Canvas canvas) {
+
+		canvas.drawArc(rangeRect, degreeMinValue,        degreeMaxValue -        degreeMinValue, false, rangeAllPaint);
+		canvas.drawArc(rangeRect, degreeOkMinValue, degreeOkMaxValue - degreeOkMinValue, false, rangeOkPaint);
+		canvas.drawArc(rangeRect, degreeWarningMinValue, degreeWarningMaxValue - degreeWarningMinValue, false, rangeWarningPaint);
+		canvas.drawArc(rangeRect, degreeErrorMinValue, degreeErrorMaxValue - degreeErrorMinValue, false, rangeErrorPaint);
+
+	}
+
+	private void drawTitle(Canvas canvas) {
+		// Use a vertical offset when printing the upper title. The upper and lower title
+		// use the same rectangular but the spacing  between the title and the ranges
+		// is not equal for the upper and lower title and therefore, the upper title is 
+		// moved downwards.
+		canvas.drawTextOnPath(upperTitle, upperTitlePath, 0.0f, 0.02f * getHeight(), upperTitlePaint);
+		canvas.drawTextOnPath(lowerTitle, lowerTitlePath, 0.0f, 0.0f,  lowerTitlePaint);				
+		canvas.drawTextOnPath(unitTitle,  unitPath,       0.0f, 0.0f,  unitPaint);				
+	}
+
+	int centerx, centery;
+
+	private void drawHand(Canvas canvas) {
+		if (true || dialInitialized) {
+
+			float angle = valueToAngle(currentValue );
+         	canvas.save(Canvas.MATRIX_SAVE_FLAG);
+			canvas.rotate(angle, centerx, centery);
+			canvas.drawPath(handPath, handPaint);
+			canvas.restore();
+			
+			canvas.drawCircle(0.5f * getWidth() , 0.5f * getHeight() , 0.01f * getWidth(), handScrewPaint);
+		}
+	}
+	
+	private void drawGauge(Canvas canvas) {
+		if (dialInitialized) {
+			// When currentValue is not rotated, the tip of the hand points
+			// to n -90 degrees.
+			float angle = valueToAngle(currentValue) - 90;
+	
+			if(targetValue <= rangeOkMaxValue){
+				canvas.drawArc(valueRect, degreeMinValue, angle - degreeMinValue, false, valueOkPaint);
+			}
+			if((targetValue > rangeOkMaxValue) && (targetValue <= rangeWarningMaxValue)){
+				canvas.drawArc(valueRect, degreeMinValue, degreeOkMaxValue - degreeMinValue, false, valueOkPaint);
+				canvas.drawArc(valueRect, degreeWarningMinValue, angle - degreeWarningMinValue, false, valueWarningPaint);
+			}
+			if((targetValue > rangeWarningMaxValue) && (targetValue <= rangeErrorMaxValue)){
+				canvas.drawArc(valueRect, degreeMinValue, degreeOkMaxValue - degreeMinValue, false, valueOkPaint);
+				canvas.drawArc(valueRect, degreeWarningMinValue, degreeWarningMaxValue - degreeWarningMinValue, false, valueWarningPaint);
+				canvas.drawArc(valueRect, degreeErrorMinValue, angle - degreeErrorMinValue, false, valueErrorPaint);
+			}
+		}
+	}
+
+	private void drawBezel(Canvas canvas) {
+		// Draw the bevel in which the value is draw.
+		canvas.save(Canvas.MATRIX_SAVE_FLAG);
+		canvas.drawArc(valueRect, degreeMinValue, degreeMaxValue - degreeMinValue, false, valueAllPaint);
+		canvas.restore();		
+	}
+
+	/* Translate a notch to a value for the scale.
+	 * The notches are evenly spread across the scale, half of the notches on the left hand side
+	 * and the other half on the right hand side.
+	 * The raw value calculation uses a constant so that each notch represents a value n + 2.
+	 */
+	private int notchToValue(int notch) {
+		//int rawValue = ((notch < totalNotches / 2) ? notch : (notch - totalNotches)) * incrementPerSmallNotch;
+		//int shiftedValue = rawValue + scaleCenterValue;
+		//return shiftedValue;
+        
+        return notch * ( scaleMaxValue - scaleMinValue ) / totalNotches;
+	}
+	
+	private float valueToAngle(float value) {
+		// scaleCenterValue represents an angle of -90 degrees.
+
+
+		//return (value - scaleCenterValue) / 2.0f * degreesPerNotch;
+
+
+        // jaja
+
+        float frac = ( value - scaleMinValue ) / ( scaleMaxValue - scaleMinValue );
+
+        return angleMinValue + frac * ( angleMaxValue - angleMinValue );
+
+        //return degreeOkMinValue - ( value / scaleMaxValue ) * ( degreeOkMinValue + 90 );
+	}
+
+    private float valueToAngle2(float value) {
+		// scaleCenterValue represents an angle of -90 degrees.
+        // return (value - scaleCenterValue) / 2.0f * degreesPerNotch;
+        return valueToAngle(value);
+
+        //return degreeOkMinValue - ( value / scaleMaxValue ) * 2 * ( degreeOkMinValue + 90 );
+    }
+
+	// Canvas backgroundCanvas ;
+
+	@Override
+	protected void onDraw(Canvas canvas) {
+
+        drawBackground(canvas);
+
+		// Draw the needle using the updated value
+		if (showHand){
+		drawHand( canvas );
+
+		}
+
+		// Calculate a new current value.
+		calculateCurrentValue();
+
+	}
+
+
+
+	@Override
+	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
+		// Log.d(TAG, "Size changed to " + w + "x" + h);
+
+		initDrawingTools();
+		regenerateBackground();
+
+		centerx = w / 2;
+		centery = h / 2;
+	}
+	
+	private void regenerateBackground() {
+		// free the old bitmap
+		if (background != null) {
+			background.recycle();
+		}
+		
+		background = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
+		Canvas backgroundCanvas = new Canvas(background);
+
+		drawRim(backgroundCanvas);
+		drawFace(backgroundCanvas);
+
+		drawScale(backgroundCanvas);
+		if (showRange){
+			drawScaleRanges(backgroundCanvas);
+		}
+		if (showGauge) {
+			drawBezel(backgroundCanvas);
+		}
+
+		drawTitle(backgroundCanvas);		
+	}
+
+	// Move the hand slowly to the new position.
+	private void calculateCurrentValue() {
+		if (!(Math.abs(currentValue - targetValue) > 0.01f)) {
+			return;
+		}
+		
+		if (lastDialMoveTime != -1L) {
+			long currentTime = System.currentTimeMillis();
+			float delta = (currentTime - lastDialMoveTime) / 1000.0f;
+
+			float direction = Math.signum(dialVelocity);
+			if (Math.abs(dialVelocity) < 90.0f) {
+				dialAcceleration = 5.0f * (targetValue - currentValue);
+			} else {
+				dialAcceleration = 0.0f;
+			}
+			currentValue += dialVelocity * delta;
+			dialVelocity += dialAcceleration * delta;
+			if ((targetValue - currentValue) * direction < 0.01f * direction) {
+				currentValue = targetValue;
+				dialVelocity = 0.0f;
+				dialAcceleration = 0.0f;
+				lastDialMoveTime = -1L;
+			} else {
+				lastDialMoveTime = System.currentTimeMillis();				
+			}
+			invalidate();
+		} else {
+			lastDialMoveTime = System.currentTimeMillis();
+			calculateCurrentValue();
+		}
+	}
+	
+	public void setValue(float value) {
+		if      (value < scaleMinValue) value = scaleMinValue;
+		else if (value > scaleMaxValue) value = scaleMaxValue;
+
+		targetValue = value;
+		dialInitialized = true;
+		
+		invalidate(); // forces onDraw() to be called.
+	}
+
+	public float getValue() {
+		return targetValue;
+	}
+
+}

+ 30 - 0
src/nl/digitalthings/mebarista/ListPreferenceWithSummary.java

@@ -0,0 +1,30 @@
+package nl.digitalthings.mebarista;
+
+import android.content.Context;
+import android.preference.EditTextPreference;
+import android.preference.ListPreference;
+import android.util.AttributeSet;
+
+public class ListPreferenceWithSummary extends ListPreference {
+
+
+    public ListPreferenceWithSummary(Context context, AttributeSet attrs, int defStyle) {
+        super(context, attrs, defStyle);
+    }
+
+    public ListPreferenceWithSummary(Context context, AttributeSet attrs) {
+        super(context, attrs);
+    }
+
+    public ListPreferenceWithSummary(Context context) {
+        super(context);
+    }
+
+    @Override
+    public String getSummary() {
+        return  String.format( super.getSummary().toString(), super.getValue(  ) );
+
+        // super.get
+        // super.getSummary().toString() + super.getPersistedString( "" );
+    }
+}

+ 67 - 0
src/nl/digitalthings/mebarista/Logx.java

@@ -0,0 +1,67 @@
+package nl.digitalthings.mebarista;
+
+import android.content.Context;
+import android.widget.Toast;
+
+public class Logx  {
+
+    Context ctxt;
+    MainActivity main;
+    public static final String TAG = "BT-for-STK";
+
+    public Logx(MainActivity main, Context ctxt){
+        this.ctxt = ctxt;
+        this.main = main;
+    }
+
+    /** prints a msg on the UI screen **/
+    public void makeToast(String msg){
+        final String out = msg;
+        main.runOnUiThread(new Runnable() {
+
+            @Override
+            public void run() {
+                Toast.makeText(ctxt, out, Toast.LENGTH_SHORT).show();
+
+            }
+        });
+    }
+
+    public void printToConsole(String msg){
+        final String out = msg;
+        main.runOnUiThread(new Runnable() {
+
+            @Override
+            public void run() {
+
+                // System.out.println(out);
+                // main.printToConsole(out);
+                main.log(out);
+
+            }
+        });
+    }
+
+    public void logcat(String msg, String level) {
+        if (level.equals("v")) {
+            android.util.Log.v(TAG, msg);
+            main.log(msg);
+        }
+        else if (level.equals("d")){
+            android.util.Log.d(TAG, msg);
+            main.log(msg);
+        }
+        else if (level.equals("i")) {
+            android.util.Log.i(TAG, msg);
+            main.log(msg);
+        }
+        else if (level.equals("w")) {
+            android.util.Log.w(TAG, msg);
+            main.log(msg);
+        }
+        else if (level.equals("e")) {
+            android.util.Log.e(TAG, msg);
+            main.log(msg);
+        }
+    }
+}

Разница между файлами не показана из-за своего большого размера
+ 1726 - 0
src/nl/digitalthings/mebarista/MainActivity.java


+ 110 - 0
src/nl/digitalthings/mebarista/STK500.java

@@ -0,0 +1,110 @@
+package nl.digitalthings.mebarista;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Arrays;
+
+public class STK500 {
+    private OutputStream outStream = null;
+    private InputStream inputStream = null;
+    Logx log;
+
+    public STK500( InputStream i, OutputStream o, Logx l ) {
+
+        outStream = o;
+        inputStream = i;
+        log = l;
+
+    }
+
+    private byte[] sync ( String operation, int n, byte[] data ) throws IOException {
+
+        outStream.write(data);
+
+        return sync( operation, n );
+
+    }
+
+    private byte[] sync ( String operation, byte[] data ) throws IOException {
+
+        outStream.write(data);
+
+        return sync( operation, 0 );
+
+    }
+
+    private byte[] sync ( String operation, int n ) throws IOException {
+
+        outStream.flush();
+
+        int insync = inputStream.read();
+        byte[] res = null;
+
+        if( n > 0 ) {
+            res = new byte[n];
+
+            inputStream.read( res, 0, n );
+        }
+
+        int ok = inputStream.read();
+        boolean syn = insync == 0x14 && ok == 0x10;
+
+        if( !syn ) {
+            log.logcat("not in sync: " + operation, "v");
+            throw new IOException("not in sync: " + operation);
+        }
+
+        while( inputStream.available() > 0 )
+            inputStream.read();
+
+        return res;
+
+    }
+
+    // Inspired by https://github.com/robokoding/STK500
+    public void main ( byte[] program ) throws IOException {
+
+        // Consume anything in input stream
+        while (inputStream.available() > 0)
+            inputStream.read();
+
+        sync("initial sync", new byte[] { 0x30, 0x20, 0x30, 0x20, 0x30, 0x20, 0x30, 0x20, 0x30, 0x20 } );
+
+        int minor = sync( "minor version", 1, new byte[] { 0x41, (byte) 0x82, 0x20 } )[0];
+        int major = sync( "major version", 1, new byte[] { 0x41, (byte) 0x81, 0x20 } )[0];
+        log.logcat( "version: " + major + "." + minor, "v" );
+
+        sync( "enter programming mode", new byte[] { 0x50, 0x20 } );
+
+        byte[] signature = sync( "device signature", 3, new byte[] { 0x75, 0x20 } );
+        log.logcat( "signature: " + String.format( "%02X", signature[0] ) + String.format( "%02X", signature[1] ) + String.format( "%02X", signature[2] ), "v" );
+
+        log.logcat( "flashing: please wait ...", "v" );
+        int programIndex = 0;
+        int pages_per_ten_percent = program.length / 128 / 10;
+        int pages_programmed = 0;
+
+        while ( programIndex < program.length ) {
+            int size = Math.min( program.length - programIndex, 128 );
+
+            sync( "load page address " + programIndex, new byte[]{0x55, (byte) ((programIndex / 2) % 256), (byte) ((programIndex / 2) / 256), 0x20});
+
+            outStream.write( new byte[] { 0x64, 0x00, (byte)size, 0x46 } );
+            outStream.write( Arrays.copyOfRange( program, programIndex, programIndex + size ) );
+            sync( "write page at " + programIndex, new byte[]{0x20} );
+
+            programIndex += size;
+            pages_programmed++;
+
+            if( pages_programmed % pages_per_ten_percent == 0 )
+                log.logcat("" + (int)( pages_programmed / pages_per_ten_percent * 10 ) + "%", "v" );
+        }
+
+        sync( "leave programming mode", new byte[] { 0x51, 0x20 } );
+
+        log.logcat("Programmed " + programIndex + " of " + program.length + " bytes", "v");
+
+    }
+
+}

+ 134 - 0
src/nl/digitalthings/mebarista/SettingsActivity.java

@@ -0,0 +1,134 @@
+package nl.digitalthings.mebarista;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.content.SharedPreferences;
+import android.content.pm.PackageManager;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.preference.PreferenceActivity;
+import android.preference.PreferenceManager;
+import android.util.Log;
+
+import java.util.Map;
+
+/**
+ * Created by jan on 11/20/13.
+ */
+
+
+public class SettingsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
+
+    private static final String TAG = "Settings";
+
+    BaristaService mBoundService;
+
+    private ServiceConnection mConnection = new ServiceConnection() {
+
+        public void onServiceConnected(ComponentName className, IBinder service) {
+            mBoundService = ((BaristaService.LocalBinder)service).getService();
+
+            if( !mBoundService.legacy )
+                addPreferencesFromResource(R.xml.preference);
+            else
+                addPreferencesFromResource(R.xml.preference_legacy);
+        }
+
+        public void onServiceDisconnected(ComponentName className) {
+            mBoundService = null;
+        }
+
+    };
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
+
+        bindService(new Intent(SettingsActivity.this,
+                BaristaService.class), mConnection, Context.BIND_AUTO_CREATE);
+
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
+            if( findPreference("pref_bt_ble_enabled") != null ) // .setEnabled(false);
+                System.out.println( "jopiedopie" );
+        }
+
+       // this.getApplicationContext().getSharedPreferences( "zyx " ).
+    }
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+
+        unbindService(mConnection);
+    }
+
+    @Override
+    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
+        // handle the preference change here
+        //showNotification(key, "changed" );
+
+        // TODO: why is this here? should move to baristaservice
+
+        System.out.println("Changed: " + key);
+
+        String val = "";
+        Map<String,?> keys = sharedPreferences.getAll();
+
+        for( Map.Entry<String,?> entry : keys.entrySet( ) ) {
+
+            if( entry.getKey().equals( key ) ) {
+                String entry_type = entry.getValue().getClass().getName();
+
+                System.out.println( "type of " + key + " is " + entry_type );
+
+                // Do something
+                if( entry_type.equals("java.lang.Integer") || entry_type.equals("java.lang.Long") )
+                    val = entry.getValue().toString();
+
+                if( entry_type.equals( "java.lang.Float" ) ) {
+                    Float value = (Float)entry.getValue();
+
+                    val = "" + value.intValue();
+                }
+
+                if( entry_type.equals("java.lang.Boolean") )
+                    val = (Boolean)entry.getValue() ? "1" : "0";
+
+                if( entry_type.equals( "java.lang.String" ) )
+                    val = entry.getValue( ).toString( );
+
+                break;
+            }
+
+        }
+
+        // publish the change to device
+        String keystr = key.replace("pref_", "");
+
+        if( ! ( keystr.startsWith( "bt_") || keystr.startsWith( "ui_" ) || keystr.startsWith( "support" ) ) ) {
+            System.out.println("cmd set " + keystr + " " + val);
+            // mBoundService.write(("cmd set " + keystr + " " + val + "\n")); // TODO: remove nl
+
+            Intent i = new Intent(this, BaristaService.class);
+            i.putExtra("action", "send" );
+            i.putExtra("payload", "cmd set " + keystr + " " + val + "\n" );
+            startService(i);
+        }
+
+        if( key.equals( "pref_bt_bt2_enabled" ) || key.equals( "pref_bt_ble_enabled" ) ) {
+
+            //  mBoundService.scan( );
+            Log.i( TAG, "BT setting changed? Start scan");
+
+            Intent i = new Intent(this, BaristaService.class);
+            i.putExtra("action", "scan" );
+            startService(i);
+
+        }
+    }
+
+}

+ 152 - 0
src/nl/digitalthings/mebarista/TimePreference.java

@@ -0,0 +1,152 @@
+package nl.digitalthings.mebarista;
+
+import android.content.Context;
+import android.preference.DialogPreference;
+import android.util.AttributeSet;
+import android.view.View;
+import android.widget.TimePicker;
+import android.content.res.TypedArray;
+import android.text.format.DateFormat;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+
+public class TimePreference extends DialogPreference {
+
+    private Calendar calendar;
+    private TimePicker picker = null;
+
+    public TimePreference(Context ctxt) {
+        this(ctxt, null);
+    }
+
+    public TimePreference(Context ctxt, AttributeSet attrs) {
+        this(ctxt, attrs, 0);
+    }
+
+    public TimePreference(Context ctxt, AttributeSet attrs, int defStyle) {
+        super(ctxt, attrs, defStyle);
+
+        setPositiveButtonText( "Set" );
+        setNegativeButtonText("Cancel");
+        calendar = Calendar.getInstance(); // new GregorianCalendar();
+    }
+
+    @Override
+    protected View onCreateDialogView() {
+
+        picker = new TimePicker(getContext());
+        return (picker);
+    }
+
+    @Override
+    protected void onBindDialogView(View v) {
+        super.onBindDialogView(v);
+        picker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY));
+        picker.setCurrentMinute(calendar.get(Calendar.MINUTE));
+    }
+
+    @Override
+    protected void onDialogClosed(boolean positiveResult) {
+        super.onDialogClosed(positiveResult);
+
+        if (positiveResult) {
+            System.out.println( "Selected HOUR " + picker.getCurrentHour() );
+            calendar.set(Calendar.HOUR_OF_DAY, picker.getCurrentHour());
+            calendar.set(Calendar.MINUTE, picker.getCurrentMinute());
+
+
+            setSummary(getSummary());
+            if (callChangeListener(calendar.getTimeInMillis())) {
+                System.out.println( "dialog closed: ");
+
+                Calendar fromMidnight; // = Calendar.getInstance();
+
+                //fromMidnight.setTimeInMillis(calendar.getTimeInMillis());
+
+                fromMidnight = (Calendar)calendar.clone();
+
+                // calendar.setTimeZone( fromMidnight.getTimeZone() );
+
+                fromMidnight.set(Calendar.HOUR_OF_DAY, 0);
+                fromMidnight.set(Calendar.MINUTE, 0);
+                fromMidnight.set(Calendar.SECOND, 0);
+                fromMidnight.set(Calendar.MILLISECOND, 0);
+
+                calendar.set( Calendar.SECOND, 0);
+                calendar.set( Calendar.MILLISECOND, 0);
+
+                calendar.set( Calendar.DST_OFFSET, 0); // dat hoeft misschien niet
+
+                // persistLong((calendar.getTimeInMillis() - fromMidnight.getTimeInMillis()) / 1000);
+
+                // persist in seconds!
+                int val_seconds = calendar.get( Calendar.HOUR_OF_DAY ) * 60 * 60 + calendar.get( Calendar.MINUTE ) * 60;
+                persistInt(val_seconds);
+                //persist
+                notifyChanged();
+            }
+        }
+    }
+
+    @Override
+    protected Object onGetDefaultValue(TypedArray a, int index) {
+        return (a.getString(index));
+    }
+
+    @Override
+    protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
+
+        if (restoreValue) {
+            if (false && defaultValue == null) {
+                calendar.setTimeInMillis( getPersistedInt( 0/* System.currentTimeMillis() */ ) * 1000 );
+            } else {
+                //Long stored_seconds = Long.parseLong(getPersistedString((String) defaultValue));
+
+                int stored_seconds = getPersistedInt(0);
+                 int hours = stored_seconds / 3600;
+
+                calendar.set(Calendar.HOUR_OF_DAY, hours );
+                calendar.set(Calendar.MINUTE, ( stored_seconds - hours*3600 ) / 60 );
+                calendar.set(Calendar.SECOND, 0);
+                calendar.set(Calendar.MILLISECOND, 0);
+
+                //calendar.setTimeInMillis( calendar.getTimeInMillis() + stored_millis );
+            }
+        } else {
+            if ( false && defaultValue == null) {
+                calendar.setTimeInMillis( System.currentTimeMillis() );
+            } else {
+                //Long stored_seconds = Long.parseLong(getPersistedString((String) defaultValue));
+
+                // Long stored_seconds = Long.parseLong(getPersistedString((String) defaultValue));
+
+                // int stored_seconds = Integer.parseInt( getPersistedString( "0" ) );
+
+                int stored_seconds = getPersistedInt(0);
+
+                int hours = stored_seconds / 3600;
+
+                calendar.set(Calendar.HOUR_OF_DAY, hours );
+                calendar.set(Calendar.MINUTE, ( stored_seconds - hours*3600 ) / 60 );
+                calendar.set(Calendar.SECOND, 0);
+                calendar.set(Calendar.MILLISECOND, 0);
+
+
+                // calendar.setTimeInMillis( Long.parseLong((String) defaultValue) * 1000 );
+            }
+        }
+        setSummary(getSummary());
+    }
+
+    @Override
+    public CharSequence getSummary() {
+        if (calendar == null) {
+            return null;
+        }
+        return DateFormat.getTimeFormat(getContext()).format(new Date(calendar.getTimeInMillis()));
+    }
+}
+
+