44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/app/src/main/java/com/sysolve/androidthings/contrib/driver/ws2812b/ColorToBitPatternConverter.java:
--------------------------------------------------------------------------------
1 | package com.sysolve.androidthings.contrib.driver.ws2812b;
2 |
3 |
4 | import android.support.annotation.ColorInt;
5 | import android.support.annotation.NonNull;
6 | import android.support.annotation.Size;
7 | import android.support.annotation.VisibleForTesting;
8 |
9 | class ColorToBitPatternConverter {
10 | private static final int MAX_NUMBER_OF_SUPPORTED_LEDS = 512;
11 | private static final int FIRST_TWELVE_BIT_BIT_MASK = 0x00FFF000;
12 | private static final int SECOND_TWELVE_BIT_BIT_MASK = 0x00000FFF;
13 |
14 | private final TwelveBitIntToBitPatternMapper mTwelveBitIntToBitPatternMapper;
15 | private ColorChannelSequence.Sequencer colorChannelSequencer;
16 |
17 | ColorToBitPatternConverter(@ColorChannelSequence.Sequence int colorChannelSequence) {
18 | this(colorChannelSequence, new TwelveBitIntToBitPatternMapper());
19 | }
20 |
21 | @VisibleForTesting
22 | ColorToBitPatternConverter(@ColorChannelSequence.Sequence int colorChannelSequence, @NonNull TwelveBitIntToBitPatternMapper twelveBitIntToBitPatternMapper) {
23 | colorChannelSequencer = ColorChannelSequence.createSequencer(colorChannelSequence);
24 | mTwelveBitIntToBitPatternMapper = twelveBitIntToBitPatternMapper;
25 | }
26 |
27 | /**
28 | * Converts the passed color array to a correlating byte array of bit patterns. These resulting
29 | * bit patterns are readable by a WS2812B LED strip if they are sent by a SPI device with the
30 | * right frequency.
31 | *
32 | * @param colors An array of color integers {@link ColorInt}
33 | * @return Returns a byte array of correlating bit patterns
34 | */
35 | byte[] convertToBitPattern(@ColorInt @NonNull @Size(max = MAX_NUMBER_OF_SUPPORTED_LEDS) int[] colors) {
36 | if (colors.length > MAX_NUMBER_OF_SUPPORTED_LEDS) {
37 | throw new IllegalArgumentException("Only " + MAX_NUMBER_OF_SUPPORTED_LEDS + " LEDs are supported. A Greater Number (" + colors.length + ") will result in SPI errors!");
38 | }
39 |
40 | byte[] bitPatterns = new byte[colors.length * 8];
41 |
42 | int i = 0;
43 | for (int color : colors) {
44 | color = colorChannelSequencer.rearrangeColorChannels(color);
45 | int firstValue = (color & FIRST_TWELVE_BIT_BIT_MASK) >> 12;
46 | int secondValue = color & SECOND_TWELVE_BIT_BIT_MASK;
47 |
48 | System.arraycopy(mTwelveBitIntToBitPatternMapper.getBitPattern(firstValue), 0, bitPatterns, i, 4);
49 | i += 4;
50 | System.arraycopy(mTwelveBitIntToBitPatternMapper.getBitPattern(secondValue), 0, bitPatterns, i, 4);
51 | i += 4;
52 | }
53 | return bitPatterns;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/app/src/main/java/com/sysolve/androidthings/contrib/driver/ws2812b/ColorChannelSequence.java:
--------------------------------------------------------------------------------
1 | package com.sysolve.androidthings.contrib.driver.ws2812b;
2 |
3 |
4 | import android.support.annotation.ColorInt;
5 | import android.support.annotation.IntDef;
6 | import android.support.annotation.NonNull;
7 |
8 | import java.lang.annotation.Retention;
9 | import java.util.Arrays;
10 |
11 | import static java.lang.annotation.RetentionPolicy.SOURCE;
12 |
13 | @SuppressWarnings("WeakerAccess")
14 | public class ColorChannelSequence {
15 | public static final int RGB = 1;
16 | public static final int RBG = 2;
17 | public static final int GRB = 3;
18 | public static final int GBR = 4;
19 | public static final int BRG = 5;
20 | public static final int BGR = 6;
21 | @Sequence
22 | private static final int[] ALL_SEQUENCES = {RGB, RBG, GRB, GBR, BRG, BGR};
23 |
24 | @Retention(SOURCE)
25 | @IntDef({RGB, RBG, GRB, GBR, BRG, BGR})
26 | @SuppressWarnings("WeakerAccess")
27 | public @interface Sequence {}
28 |
29 | interface Sequencer
30 | {
31 | int rearrangeColorChannels(@ColorInt int color);
32 | }
33 |
34 | @NonNull
35 | static Sequencer createSequencer(@Sequence int colorChannelSequence)
36 | {
37 | switch (colorChannelSequence) {
38 | case BGR:
39 | return new Sequencer() {
40 | @Override
41 | public int rearrangeColorChannels(int color) {
42 | return ((color & 0xff0000) >> 16) | (color & 0xff00) | ((color & 0xff) << 16);
43 | }
44 | };
45 | case BRG:
46 | return new Sequencer() {
47 | @Override
48 | public int rearrangeColorChannels(int color) {
49 | return ((color & 0xff0000) >> 8) | ((color & 0xff00) >> 8) | ((color & 0xff) << 16);
50 | }
51 | };
52 | case GBR:
53 | return new Sequencer() {
54 | @Override
55 | public int rearrangeColorChannels(int color) {
56 | return ((color & 0xff0000) >> 16) | ((color & 0xff00) << 8) | ((color & 0xff) << 8);
57 | }
58 | };
59 | case GRB:
60 | return new Sequencer() {
61 | @Override
62 | public int rearrangeColorChannels(int color) {
63 | return ((color & 0xff0000) >> 8) | ((color & 0xff00) << 8) | (color & 0xff);
64 | }
65 | };
66 | case RBG:
67 | return new Sequencer() {
68 | @Override
69 | public int rearrangeColorChannels(int color) {
70 | return (color & 0xff0000) | ((color & 0xff00) >> 8) | ((color & 0xff) << 8);
71 | }
72 | };
73 | case RGB:
74 | return new Sequencer() {
75 | @Override
76 | public int rearrangeColorChannels(int color) {
77 | return color;
78 | }
79 | };
80 | default:
81 | throw new IllegalArgumentException("Invalid color channel sequence: " + colorChannelSequence + ". Supported color channel sequences are: " + Arrays.toString(ColorChannelSequence.ALL_SEQUENCES));
82 | }
83 | }
84 |
85 | }
86 |
--------------------------------------------------------------------------------
/app/src/main/java/com/sysolve/androidthings/contrib/driver/ws2812b/Ws2812b.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Google Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.sysolve.androidthings.contrib.driver.ws2812b;
18 |
19 | import android.support.annotation.ColorInt;
20 | import android.support.annotation.NonNull;
21 | import android.support.annotation.VisibleForTesting;
22 |
23 | import com.google.android.things.pio.PeripheralManager;
24 | import com.google.android.things.pio.SpiDevice;
25 |
26 | import java.io.IOException;
27 |
28 | /**
29 | * Device driver for WS2812B LEDs using SPI.
30 | *
31 | * For more information on SPI, see:
32 | * https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
33 | * For information on the WS2812B protocol, see:
34 | * https://wp.josh.com/2014/05/13/ws2812-neopixels-are-not-so-finicky-once-you-get-to-know-them/
35 | * https://cpldcpu.com/2014/01/14/light_ws2812-library-v2-0-part-i-understanding-the-ws2812/
36 | */
37 |
38 | @SuppressWarnings({"unused", "WeakerAccess"})
39 | public class Ws2812b implements AutoCloseable {
40 | private static final String TAG = "Ws2812b";
41 |
42 | @NonNull
43 | private final ColorToBitPatternConverter mColorToBitPatternConverter;
44 | private SpiDevice mDevice = null;
45 |
46 | /**
47 | * Create a new WS2812B driver.
48 | *
49 | * @param spiBusPort Name of the SPI bus
50 | */
51 | public Ws2812b(String spiBusPort) throws IOException {
52 | this(spiBusPort, new ColorToBitPatternConverter(ColorChannelSequence.GRB));
53 | }
54 |
55 | /**
56 | * Create a new WS2812B driver.
57 | *
58 | * @param spiBusPort Name of the SPI bus
59 | * @param colorChannelSequence The {@link ColorChannelSequence.Sequence} indicates the red/green/blue byte order for the LED strip.
60 | * @throws IOException if the initialization of the SpiDevice fails
61 | *
62 | */
63 | public Ws2812b(String spiBusPort, @ColorChannelSequence.Sequence int colorChannelSequence) throws IOException {
64 | this (spiBusPort, new ColorToBitPatternConverter(colorChannelSequence));
65 | }
66 |
67 | private Ws2812b(String spiBusPort, @NonNull ColorToBitPatternConverter colorToBitPatternConverter) throws IOException {
68 | mColorToBitPatternConverter = colorToBitPatternConverter;
69 | mDevice = PeripheralManager.getInstance().openSpiDevice(spiBusPort);
70 | try {
71 | initSpiDevice(mDevice);
72 | } catch (IOException|RuntimeException e) {
73 | try {
74 | close();
75 | } catch (IOException|RuntimeException ignored) {
76 | }
77 | throw e;
78 | }
79 | }
80 |
81 | @VisibleForTesting
82 | /*package*/ Ws2812b(SpiDevice device, @NonNull ColorToBitPatternConverter colorToBitPatternConverter) throws IOException {
83 | mColorToBitPatternConverter = colorToBitPatternConverter;
84 | mDevice = device;
85 | initSpiDevice(mDevice);
86 | }
87 |
88 | private void initSpiDevice(SpiDevice device) throws IOException {
89 |
90 | double durationOfOneBitInNs = 417.0;
91 | double durationOfOneBitInS = durationOfOneBitInNs * Math.pow(10, -9);
92 | int frequencyInHz = (int) Math.round(1.0 / durationOfOneBitInS);
93 |
94 | device.setFrequency(frequencyInHz);
95 | device.setBitsPerWord(8);
96 | device.setDelay(0);
97 | }
98 |
99 | /**
100 | * Transforms the passed color array and writes it to the SPI connected WS2812b LED strip.
101 | * @param colors An array of 24 bit RGB color integers {@link ColorInt}
102 | * @throws IOException if writing to the SPI device fails
103 | */
104 | public void write(@NonNull @ColorInt int[] colors) throws IOException {
105 | if (mDevice == null) {
106 | throw new IllegalStateException("SPI device not opened");
107 | }
108 |
109 | byte[] convertedColors = mColorToBitPatternConverter.convertToBitPattern(colors);
110 | mDevice.write(convertedColors, convertedColors.length);
111 | }
112 |
113 | /**
114 | * Releases the SPI interface and related resources.
115 | * @throws IOException if the SpiDevice is already closed
116 | */
117 | @Override
118 | public void close() throws IOException {
119 | if (mDevice != null) {
120 | try {
121 | mDevice.close();
122 | } finally {
123 | mDevice = null;
124 | }
125 | }
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/java/com/sysolve/androidthings/contrib/driver/ws2812b/TwelveBitIntToBitPatternMapper.java:
--------------------------------------------------------------------------------
1 | package com.sysolve.androidthings.contrib.driver.ws2812b;
2 |
3 |
4 | import android.support.annotation.IntRange;
5 | import android.support.annotation.NonNull;
6 | import android.support.annotation.Size;
7 | import android.support.annotation.VisibleForTesting;
8 | import android.util.SparseArray;
9 |
10 | import java.util.ArrayList;
11 | import java.util.Arrays;
12 | import java.util.Iterator;
13 | import java.util.List;
14 |
15 | /**
16 | * Creates a storage which maps any possible 12 bit sized integer to bit patterns. If a sequence of
17 | * these bit patterns is sent to a WS2812b LED strip using SPI, the outcoming high and low voltage
18 | * pulses are recognized as the original 12 bit integers.
19 | * Converting algorithm:
20 | * - 1 src bit is converted to a 3 bit long bit pattern
21 | * - The 9th bit in a sequence of bit pattern is a pause bit and must be removed. The pause bit is
22 | * automatically transmitted between every byte
23 | * - This results in the fact that 3 source bits are converted to 1 destination byte
24 | *
25 | * => 3 src bits = 8 bit (1 dst byte)
26 | * => 12 src bits = 32 bit (4 dst bytes)
27 | */
28 | class TwelveBitIntToBitPatternMapper {
29 | private static final int BIGGEST_12_BIT_NUMBER = 0B1111_1111_1111;
30 | private static final List BIT_PATTERN_FOR_ZERO_BIT = Arrays.asList(true, false, false);
31 | private static final List BIT_PATTERN_FOR_ONE_BIT = Arrays.asList(true, true, false);
32 | private static final int ONE_BYTE_BIT_MASKS[] = new int[]{ 0B10000000,
33 | 0B01000000,
34 | 0B00100000,
35 | 0B00010000,
36 | 0B00001000,
37 | 0B00000100,
38 | 0B00000010,
39 | 0B00000001};
40 | @NonNull
41 | private final SparseArray mSparseArray;
42 |
43 | TwelveBitIntToBitPatternMapper() {
44 | this(new SparseArray(BIGGEST_12_BIT_NUMBER));
45 | }
46 |
47 | @VisibleForTesting
48 | TwelveBitIntToBitPatternMapper(@NonNull final SparseArray sparseArray) {
49 | mSparseArray = sparseArray;
50 | fillBitPatternStorage();
51 | }
52 |
53 | /**
54 | * Returns for each possible 12 bit integer a corresponding sequence of bit pattern as byte array.
55 | * Throws an {@link IllegalArgumentException} if the integer is using more than 12 bit.
56 | *
57 | * @param twelveBitValue Any 12 bit integer (from 0 to 4095)
58 | * @return The corresponding bit pattern as 4 byte sized array
59 | */
60 | @NonNull
61 | @Size(value = 4)
62 | byte[] getBitPattern(@IntRange(from = 0, to = BIGGEST_12_BIT_NUMBER) int twelveBitValue) {
63 | byte[] bitPatternByteArray = mSparseArray.get(twelveBitValue);
64 | if (bitPatternByteArray == null)
65 | {
66 | throw new IllegalArgumentException("Only values from 0 to " + BIGGEST_12_BIT_NUMBER + " are allowed. The passed input value was: " + twelveBitValue);
67 | }
68 | return bitPatternByteArray;
69 | }
70 |
71 | private void fillBitPatternStorage() {
72 | for (int i = 0; i <= BIGGEST_12_BIT_NUMBER; i++) {
73 | mSparseArray.append(i, calculateBitPatternByteArray(i));
74 | }
75 | }
76 |
77 | @Size(value = 4)
78 | private byte[] calculateBitPatternByteArray(@IntRange(from = 0, to = BIGGEST_12_BIT_NUMBER) int twelveBitNumber) {
79 | List bitPatterns = new ArrayList<>();
80 | int highest12BitBitMask = 1 << 11;
81 | for (int i = 0; i < 12; i++) {
82 | if ((twelveBitNumber & highest12BitBitMask) == highest12BitBitMask){
83 | bitPatterns.addAll(BIT_PATTERN_FOR_ONE_BIT);
84 | }
85 | else{
86 | bitPatterns.addAll(BIT_PATTERN_FOR_ZERO_BIT);
87 | }
88 | twelveBitNumber = twelveBitNumber << 1;
89 | }
90 | bitPatterns = removePauseBits(bitPatterns);
91 | return convertBitPatternsToByteArray(bitPatterns);
92 | }
93 |
94 | private List removePauseBits(List bitPatterns) {
95 | Iterator iterator = bitPatterns.iterator();
96 | int i = 0;
97 | while (iterator.hasNext()) {
98 | iterator.next();
99 | if (i == 8)
100 | {
101 | iterator.remove();
102 | i = 0;
103 | continue;
104 | }
105 | i++;
106 | }
107 | return bitPatterns;
108 | }
109 |
110 | @Size(value = 4)
111 | private byte[] convertBitPatternsToByteArray(List bitPatterns) {
112 |
113 | if (bitPatterns.size() != 32)
114 | {
115 | throw new IllegalArgumentException("Undefined bit pattern size: Expected size is 32. Passed size: " + bitPatterns.size());
116 | }
117 | byte[] bitPatternsAsByteArray = new byte[4];
118 | bitPatternsAsByteArray [0] = convertBitPatternsToByte(bitPatterns.subList(0, 8));
119 | bitPatternsAsByteArray [1] = convertBitPatternsToByte(bitPatterns.subList(8, 16));
120 | bitPatternsAsByteArray [2] = convertBitPatternsToByte(bitPatterns.subList(16, 24));
121 | bitPatternsAsByteArray [3] = convertBitPatternsToByte(bitPatterns.subList(24, 32));
122 | return bitPatternsAsByteArray;
123 | }
124 |
125 | private byte convertBitPatternsToByte(List bitPatterns) {
126 | int bitPatternByte = 0;
127 | for (int i = 0; i < 8; i++) {
128 | if (bitPatterns.get(i))
129 | {
130 | bitPatternByte |= ONE_BYTE_BIT_MASKS[i];
131 | }
132 | }
133 | return (byte) bitPatternByte;
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/app/src/main/java/com/sysolve/androidthings/utils/HttpServer.java:
--------------------------------------------------------------------------------
1 | package com.sysolve.androidthings.utils;
2 |
3 | import android.graphics.Color;
4 | import android.os.Environment;
5 | import android.util.Log;
6 |
7 | import com.sysolve.androidthings.cameracar.MainActivity;
8 |
9 | import java.io.File;
10 | import java.util.Map;
11 |
12 | import fi.iki.elonen.NanoHTTPD;
13 | import fi.iki.elonen.SimpleWebServer;
14 |
15 | /**
16 | * Created by 13311 on 2018-01-27.
17 | */
18 |
19 | public class HttpServer extends SimpleWebServer {
20 |
21 | public static String wwwRoot = Environment.getExternalStorageDirectory() + "/cameracar-www/";
22 |
23 | MainActivity main;
24 |
25 | public HttpServer(MainActivity main) {
26 | super(null, 8080, new File(wwwRoot), false, "*");
27 |
28 | try {
29 | this.main = main;
30 | start(NanoHTTPD.SOCKET_READ_TIMEOUT, true);
31 | Log.i("HTTPD", "\nRunning! Point your browsers to http://localhost:8080/ \n");
32 | } catch (Exception e) {
33 | Log.e("HTTPD", e.getMessage(), e);
34 | }
35 | }
36 |
37 | @Override
38 | protected NanoHTTPD.Response addCORSHeaders(Map queryHeaders, NanoHTTPD.Response
39 | resp, String cors) {
40 | //resp = super.addCORSHeaders(queryHeaders, resp, cors);
41 |
42 | resp.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
43 | resp.addHeader("Pragma", "no-cache");
44 | resp.addHeader("Expires", "0");
45 |
46 | return resp;
47 | }
48 |
49 | @Override
50 | public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
51 | //Log.i("HTTPD", session.getUri());
52 | if (session.getUri().startsWith("/action/")) {
53 | String msg = "";
54 | Map parms = session.getParms();
55 | String cmd = parms.get("cmd");
56 | if (cmd == null) {
57 | msg = "";
58 |
59 | msg += "
";
60 | msg += "
";
61 | msg += "
";
62 | msg += "
";
63 | msg += "";
64 | msg += "
";
65 | msg += "
";
66 |
67 | msg += "
";
68 | msg += "
";
69 | msg += "";
70 |
71 | msg += "
";
72 | msg += "
";
73 | msg += "
";
74 | msg += "
";
75 |
76 | msg += "
";
77 | msg += "
";
78 |
79 | msg += "";
80 |
81 | msg += "";
82 | msg += "";
85 | msg += "\n";
86 | } else {
87 | Log.i("HTTP", "cmd="+cmd);
88 | cmd = cmd.trim().toLowerCase();
89 | if ("s".equals(cmd)) {
90 | //停止
91 | main.emStop();
92 | } else if ("f".equals(cmd)) {
93 | //前进
94 | main.goForward();
95 | } else if ("b".equals(cmd)) {
96 | //后退
97 | main.goBack();
98 | } else if ("l".equals(cmd)) {
99 | //左转
100 | main.turnLeft();
101 | } else if ("r".equals(cmd)) {
102 | //右转
103 | main.turnRight();
104 | } else if ("a".equals(cmd)) {
105 | //加速
106 | main.speedAdd();
107 | } else if ("d".equals(cmd)) {
108 | //减速
109 | main.speedDecrease();
110 | } else if ("lt".equals(cmd)) {
111 | //向左偏移
112 | main.leftT();
113 | } else if ("rt".equals(cmd)) {
114 | //向右偏移
115 | main.rightT();
116 | } else if ("nt".equals(cmd)) {
117 | //无偏移
118 | main.noT();
119 | } else if ("cred".equals(cmd)) {
120 | //显示红色
121 | main.color(Color.RED);
122 | } else if ("cyellow".equals(cmd)) {
123 | //显示黄色
124 | main.color(Color.YELLOW);
125 | } else if ("cgreen".equals(cmd)) {
126 | //显示绿色
127 | main.color(Color.GREEN);
128 | } else if ("cblue".equals(cmd)) {
129 | //显示蓝色
130 | main.color(Color.BLUE);
131 | } else if ("cmore".equals(cmd)) {
132 | //显示炫彩
133 | main.moreColor();
134 | } else if ("cno".equals(cmd)) {
135 | //不显示颜色
136 | main.color(Color.BLACK);
137 | } else if ("son".equals(cmd)) {
138 | //启用超声波
139 | main.superSound(true);
140 | } else if ("soff".equals(cmd)) {
141 | //停用超声波
142 | main.superSound(false);
143 | } else if ("tp".equals(cmd)) {
144 | //拍照
145 | main.takePicture();
146 | } else if ("tpv".equals(cmd)) {
147 | //拍照
148 | //main.takePicture();
149 | msg = "{\"tpv\": "+ main.picVersion +"}";
150 | }
151 | }
152 |
153 | return newFixedLengthResponse(msg);
154 | } else {
155 | return super.serve(session);
156 | }
157 | }
158 | }
159 |
--------------------------------------------------------------------------------
/app/src/main/java/com/sysolve/androidthings/utils/BoardSpec.java:
--------------------------------------------------------------------------------
1 | /*
2 | * @author Ray, ray@sysolve.com
3 | * Copyright 2018, Sysolve IoT Open Source
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package com.sysolve.androidthings.utils;
19 |
20 | import android.os.Build;
21 |
22 | /**
23 | * Define pins for different Board Type
24 | */
25 | public class BoardSpec {
26 | private static final String DEVICE_RPI3 = "rpi3";
27 | private static final String DEVICE_IMX6UL_PICO = "imx6ul_pico";
28 | private static final String DEVICE_IMX7D_PICO = "imx7d_pico";
29 |
30 | public static final int PIN_13 = 0;
31 | public static final int PIN_15 = 1;
32 | public static final int PIN_16 = 2;
33 | public static final int PIN_18 = 3;
34 | public static final int PIN_22 = 4;
35 | public static final int PIN_29 = 5;
36 | public static final int PIN_31 = 6; //for google simplepio/blink application
37 | public static final int PIN_32 = 7;
38 | public static final int PIN_35 = 8;
39 | public static final int PIN_36 = 9;
40 | public static final int PIN_37 = 10;
41 | public static final int PIN_38 = 11;
42 | public static final int PIN_40 = 12; //for google simplepio/button application
43 |
44 | public static BoardSpec getInstance() {
45 | return instance;
46 | }
47 |
48 | public static BoardSpec instance = getBoardSpec(Build.DEVICE);
49 |
50 | public static BoardSpec getBoardSpec(String device) {
51 | switch (device) {
52 | case DEVICE_RPI3:
53 | return createBoardSpecRPI3();
54 | case DEVICE_IMX6UL_PICO:
55 | return createBoardSpecIMX6UL_PICO();
56 | case DEVICE_IMX7D_PICO:
57 | return createBoardSpecIMX7D_PICO();
58 | default:
59 | throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE);
60 | }
61 | }
62 |
63 | private String[] gpios;
64 | private String[] pwms;
65 | private String i2c = null;
66 | private String spi = null;
67 | private String uart = null;
68 |
69 | public String getGpioPin(int i) {
70 | if (gpios==null || i>=gpios.length || gpios[i]==null) {
71 | throw new IllegalArgumentException("GPIO pin not Supported, Device: " + Build.DEVICE);
72 | } else {
73 | return gpios[i];
74 | }
75 | }
76 |
77 | public String getPwm(int i) {
78 | if (pwms==null || i>=pwms.length || pwms[i]==null) {
79 | throw new IllegalArgumentException("PWM_" +i+ " not Supported, Device: " + Build.DEVICE);
80 | } else {
81 | return pwms[i];
82 | }
83 | }
84 |
85 | public static String getGoogleSampleButtonGpioPin() {
86 | return BoardSpec.getInstance().getGpioPin(PIN_40);
87 | }
88 |
89 | public static String getGoogleSampleLedGpioPin() {
90 | return BoardSpec.getInstance().getGpioPin(PIN_31);
91 | }
92 |
93 | public static String getPWMPort() {
94 | return BoardSpec.getInstance().getPwm(0);
95 | }
96 |
97 | public static String getGoogleSampleSpeakerPwmPin() {
98 | return BoardSpec.getInstance().getPwm(1);
99 | }
100 |
101 | public static String getI2cBus() {
102 | String s = BoardSpec.getInstance().i2c;
103 | if (s!=null)
104 | return s;
105 | else
106 | throw new IllegalArgumentException("I2C Bus not Supported, Device: " + Build.DEVICE);
107 | }
108 |
109 | public static String getUartName() {
110 | String s = BoardSpec.getInstance().uart;
111 | if (s!=null)
112 | return s;
113 | else
114 | throw new IllegalArgumentException("UART not Supported, Device: " + Build.DEVICE);
115 | }
116 |
117 | public static String getSpiBus() {
118 | String s = BoardSpec.getInstance().spi;
119 | if (s!=null)
120 | return s;
121 | else
122 | throw new IllegalArgumentException("SPI Bus not Supported, Device: " + Build.DEVICE);
123 | }
124 |
125 |
126 | private static BoardSpec createBoardSpecRPI3() {
127 | BoardSpec spec = new BoardSpec();
128 | spec.i2c = "I2C1";
129 | spec.spi = "SPI0.0";
130 | spec.uart = "UART0";
131 | spec.pwms = new String[] {
132 | "PWM0",
133 | "PWM1"
134 | };
135 | spec.gpios = new String[] {
136 | "BCM27", // PIN_13,
137 | "BCM22", // PIN_15,
138 | "BCM23", // PIN_16,
139 | "BCM24", // PIN_18,
140 | "BCM25", // PIN_22,
141 | "BCM5", // PIN_29,
142 | "BCM6", // PIN_31,
143 | "BCM12", // PIN_32,
144 | "BCM19", // PIN_35,
145 | "BCM16", // PIN_36,
146 | "BCM26", // PIN_37,
147 | "BCM20", // PIN_38,
148 | "BCM21", // PIN_40
149 | };
150 |
151 | return spec;
152 | }
153 |
154 | private static BoardSpec createBoardSpecIMX6UL_PICO() {
155 | BoardSpec spec = new BoardSpec();
156 | spec.i2c = "I2C2";
157 | spec.spi = "SPI3.0";
158 | spec.uart = "UART3";
159 | spec.pwms = new String[] {
160 | "PWM7",
161 | "PWM8"
162 | };
163 | spec.gpios = new String[] {
164 | "GPIO4_IO23", // PIN_13,
165 | null, // PIN_15, //not support
166 | "GPIO2_IO00", // PIN_16,
167 | "GPIO2_IO01", // PIN_18,
168 | null, // PIN_22, //not support
169 | "GPIO4_IO21", // PIN_29,
170 | "GPIO4_IO22", // PIN_31,
171 | null, // PIN_32, //not support
172 | "GPIO4_IO19", // PIN_35,
173 | "GPIO5_IO02", // PIN_36,
174 | "GPIO1_IO18", // PIN_37,
175 | "GPIO2_IO02", // PIN_38,
176 | "GPIO2_IO03" // PIN_40
177 | };
178 | return spec;
179 | }
180 |
181 | private static BoardSpec createBoardSpecIMX7D_PICO() {
182 | BoardSpec spec = new BoardSpec();
183 | spec.i2c = "I2C1";
184 | spec.spi = "SPI3.1";
185 | spec.uart = "UART6";
186 | spec.pwms = new String[] {
187 | "PWM1",
188 | "PWM2"
189 | };
190 | spec.gpios = new String[] {
191 | "GPIO2_IO03", // PIN_13,
192 | "GPIO1_IO10", // PIN_15,
193 | "GPIO6_IO13", // PIN_16,
194 | "GPIO6_IO12", // PIN_18,
195 | "GPIO5_IO00", // PIN_22,
196 | "GPIO2_IO01", // PIN_29,
197 | "GPIO2_IO02", // PIN_31,
198 | null, // PIN_32, //not support
199 | "GPIO2_IO00", // PIN_35,
200 | "GPIO2_IO07", // PIN_36,
201 | "GPIO2_IO05", // PIN_37,
202 | "GPIO6_IO15", // PIN_38,
203 | "GPIO6_IO14", // PIN_40
204 | };
205 | return spec;
206 | }
207 |
208 | }
209 |
--------------------------------------------------------------------------------
/app/src/main/java/com/sysolve/androidthings/cameracar/DoorbellCamera.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016, The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.sysolve.androidthings.cameracar;
17 |
18 | import android.content.Context;
19 | import android.graphics.ImageFormat;
20 | import android.hardware.camera2.CameraAccessException;
21 | import android.hardware.camera2.CameraCaptureSession;
22 | import android.hardware.camera2.CameraCharacteristics;
23 | import android.hardware.camera2.CameraDevice;
24 | import android.hardware.camera2.CameraManager;
25 | import android.hardware.camera2.CaptureRequest;
26 | import android.hardware.camera2.CaptureResult;
27 | import android.hardware.camera2.TotalCaptureResult;
28 | import android.hardware.camera2.params.StreamConfigurationMap;
29 | import android.media.ImageReader;
30 | import android.os.Handler;
31 | import android.util.Log;
32 | import android.util.Size;
33 |
34 | import java.util.Collections;
35 |
36 | import static android.content.Context.CAMERA_SERVICE;
37 |
38 | /**
39 | * Helper class to deal with methods to deal with images from the camera.
40 | */
41 | public class DoorbellCamera {
42 | private static final String TAG = DoorbellCamera.class.getSimpleName();
43 |
44 | private static final int IMAGE_WIDTH = 1280;
45 | private static final int IMAGE_HEIGHT = 720;
46 | private static final int MAX_IMAGES = 1;
47 |
48 | private CameraDevice mCameraDevice;
49 |
50 | private CameraCaptureSession mCaptureSession;
51 |
52 | /**
53 | * An {@link ImageReader} that handles still image capture.
54 | */
55 | private ImageReader mImageReader;
56 |
57 | // Lazy-loaded singleton, so only one instance of the camera is created.
58 | private DoorbellCamera() {
59 | }
60 |
61 | private static class InstanceHolder {
62 | private static DoorbellCamera mCamera = new DoorbellCamera();
63 | }
64 |
65 | public static DoorbellCamera getInstance() {
66 | return InstanceHolder.mCamera;
67 | }
68 |
69 | /**
70 | * Initialize the camera device
71 | */
72 | public void initializeCamera(Context context,
73 | Handler backgroundHandler,
74 | ImageReader.OnImageAvailableListener imageAvailableListener) {
75 | // Discover the camera instance
76 | CameraManager manager = (CameraManager) context.getSystemService(CAMERA_SERVICE);
77 | String[] camIds = {};
78 | try {
79 | camIds = manager.getCameraIdList();
80 | } catch (CameraAccessException e) {
81 | Log.d(TAG, "Cam access exception getting IDs", e);
82 | }
83 | if (camIds.length < 1) {
84 | Log.d(TAG, "No cameras found");
85 | return;
86 | }
87 | String id = camIds[0];
88 | Log.d(TAG, "Using camera id " + id);
89 |
90 | // Initialize the image processor
91 | mImageReader = ImageReader.newInstance(IMAGE_WIDTH, IMAGE_HEIGHT,
92 | ImageFormat.JPEG, MAX_IMAGES);
93 | mImageReader.setOnImageAvailableListener(
94 | imageAvailableListener, backgroundHandler);
95 |
96 | // Open the camera resource
97 | try {
98 | manager.openCamera(id, mStateCallback, backgroundHandler);
99 | } catch (CameraAccessException cae) {
100 | Log.d(TAG, "Camera access exception", cae);
101 | }
102 | }
103 |
104 | /**
105 | * Callback handling device state changes
106 | */
107 | private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
108 | @Override
109 | public void onOpened(CameraDevice cameraDevice) {
110 | Log.d(TAG, "Opened camera.");
111 | mCameraDevice = cameraDevice;
112 | }
113 |
114 | @Override
115 | public void onDisconnected(CameraDevice cameraDevice) {
116 | Log.d(TAG, "Camera disconnected, closing.");
117 | cameraDevice.close();
118 | }
119 |
120 | @Override
121 | public void onError(CameraDevice cameraDevice, int i) {
122 | Log.d(TAG, "Camera device error, closing.");
123 | cameraDevice.close();
124 | }
125 |
126 | @Override
127 | public void onClosed(CameraDevice cameraDevice) {
128 | Log.d(TAG, "Closed camera, releasing");
129 | mCameraDevice = null;
130 | }
131 | };
132 |
133 | /**
134 | * Begin a still image capture
135 | */
136 | public void takePicture() {
137 | if (mCameraDevice == null) {
138 | Log.w(TAG, "Cannot capture image. Camera not initialized.");
139 | return;
140 | }
141 |
142 | // Here, we create a CameraCaptureSession for capturing still images.
143 | try {
144 | mCameraDevice.createCaptureSession(
145 | Collections.singletonList(mImageReader.getSurface()),
146 | mSessionCallback,
147 | null);
148 | } catch (CameraAccessException cae) {
149 | Log.d(TAG, "access exception while preparing pic", cae);
150 | }
151 | }
152 |
153 | /**
154 | * Callback handling session state changes
155 | */
156 | private CameraCaptureSession.StateCallback mSessionCallback =
157 | new CameraCaptureSession.StateCallback() {
158 | @Override
159 | public void onConfigured(CameraCaptureSession cameraCaptureSession) {
160 | // The camera is already closed
161 | if (mCameraDevice == null) {
162 | return;
163 | }
164 |
165 | // When the session is ready, we start capture.
166 | mCaptureSession = cameraCaptureSession;
167 | triggerImageCapture();
168 | }
169 |
170 | @Override
171 | public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) {
172 | Log.w(TAG, "Failed to configure camera");
173 | }
174 | };
175 |
176 | /**
177 | * Execute a new capture request within the active session
178 | */
179 | private void triggerImageCapture() {
180 | try {
181 | final CaptureRequest.Builder captureBuilder =
182 | mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
183 | captureBuilder.addTarget(mImageReader.getSurface());
184 | captureBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
185 | Log.d(TAG, "Session initialized.");
186 | mCaptureSession.capture(captureBuilder.build(), mCaptureCallback, null);
187 | } catch (CameraAccessException cae) {
188 | Log.d(TAG, "camera capture exception");
189 | }
190 | }
191 |
192 | /**
193 | * Callback handling capture session events
194 | */
195 | private final CameraCaptureSession.CaptureCallback mCaptureCallback =
196 | new CameraCaptureSession.CaptureCallback() {
197 |
198 | @Override
199 | public void onCaptureProgressed(CameraCaptureSession session,
200 | CaptureRequest request,
201 | CaptureResult partialResult) {
202 | Log.d(TAG, "Partial result");
203 | }
204 |
205 | @Override
206 | public void onCaptureCompleted(CameraCaptureSession session,
207 | CaptureRequest request,
208 | TotalCaptureResult result) {
209 | if (session != null) {
210 | session.close();
211 | mCaptureSession = null;
212 | Log.d(TAG, "CaptureSession closed");
213 | }
214 | }
215 | };
216 |
217 |
218 | /**
219 | * Close the camera resources
220 | */
221 | public void shutDown() {
222 | if (mCameraDevice != null) {
223 | mCameraDevice.close();
224 | }
225 | }
226 |
227 | /**
228 | * Helpful debugging method: Dump all supported camera formats to log. You don't need to run
229 | * this for normal operation, but it's very helpful when porting this code to different
230 | * hardware.
231 | */
232 | public static void dumpFormatInfo(Context context) {
233 | CameraManager manager = (CameraManager) context.getSystemService(CAMERA_SERVICE);
234 | String[] camIds = {};
235 | try {
236 | camIds = manager.getCameraIdList();
237 | } catch (CameraAccessException e) {
238 | Log.d(TAG, "Cam access exception getting IDs");
239 | }
240 | if (camIds.length < 1) {
241 | Log.d(TAG, "No cameras found");
242 | } else {
243 | String id = camIds[0];
244 | Log.d(TAG, "Using camera id " + id);
245 | try {
246 | CameraCharacteristics characteristics = manager.getCameraCharacteristics(id);
247 | StreamConfigurationMap configs = characteristics.get(
248 | CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
249 | for (int format : configs.getOutputFormats()) {
250 | Log.d(TAG, "Getting sizes for format: " + format);
251 | for (Size s : configs.getOutputSizes(format)) {
252 | Log.d(TAG, "\t" + s.toString());
253 | }
254 | }
255 | int[] effects = characteristics.get(CameraCharacteristics.CONTROL_AVAILABLE_EFFECTS);
256 | for (int effect : effects) {
257 | Log.d(TAG, "Effect available: " + effect);
258 | }
259 | } catch (CameraAccessException e) {
260 | Log.d(TAG, "Cam access exception getting characteristics.");
261 | }
262 | }
263 | }
264 | }
265 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/app/src/main/java/com/sysolve/androidthings/cameracar/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.sysolve.androidthings.cameracar;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.content.pm.PackageManager;
6 | import android.graphics.Bitmap;
7 | import android.graphics.BitmapFactory;
8 | import android.graphics.Color;
9 | import android.media.Image;
10 | import android.media.ImageReader;
11 | import android.os.Bundle;
12 | import android.os.Handler;
13 | import android.os.HandlerThread;
14 | import android.util.Base64;
15 | import android.util.Log;
16 | import android.view.KeyEvent;
17 | import android.view.View;
18 | import android.widget.ImageView;
19 |
20 | import com.google.android.things.pio.Gpio;
21 | import com.google.android.things.pio.GpioCallback;
22 | import com.google.android.things.pio.PeripheralManager;
23 | import com.google.android.things.pio.Pwm;
24 | import com.google.android.things.pio.UartDevice;
25 | import com.google.android.things.pio.UartDeviceCallback;
26 | import com.sysolve.androidthings.contrib.driver.ws2812b.Ws2812b;
27 | import com.sysolve.androidthings.utils.BoardSpec;
28 | import com.sysolve.androidthings.utils.HttpServer;
29 | import com.sysolve.androidthings.utils.Unzip;
30 |
31 | import java.io.BufferedOutputStream;
32 | import java.io.File;
33 | import java.io.FileOutputStream;
34 | import java.io.IOException;
35 | import java.nio.ByteBuffer;
36 |
37 | import static android.content.ContentValues.TAG;
38 |
39 | public class MainActivity extends Activity {
40 | private static final String TAG = MainActivity.class.getSimpleName();
41 |
42 | Gpio mButtonGpio = null;
43 |
44 | private Pwm pwmLeft;
45 | private Pwm pwmRight;
46 |
47 | Gpio left0;
48 | Gpio left1;
49 | Gpio right0;
50 | Gpio right1;
51 | Gpio stop;
52 |
53 | private static double PWM_FREQUENCY_HZ = 100000;
54 |
55 | private static final int SPEED_NORMAL = 100;
56 | private static final int SPEED_TURNING_INSIDE = 70;
57 | private static final int SPEED_TURNING_OUTSIDE = 250;
58 |
59 | int buttonPressedTimes = 0;
60 |
61 | private HandlerThread mInputThread;
62 | private Handler mInputHandler;
63 |
64 | Gpio echoDeviceEn;
65 |
66 | private Runnable mTransferUartRunnable = new Runnable() {
67 | @Override
68 | public void run() {
69 | transferUartData();
70 | }
71 | };
72 |
73 |
74 | Ws2812b mWs2812b;
75 |
76 | private int mFrame = 0;
77 | private Handler mHandler;
78 | private HandlerThread mPioThread;
79 |
80 | private static final int FRAME_DELAY_MS = 30; // 24fps
81 |
82 | int[] mLedColors = new int[] {
83 | Color.BLUE, Color.BLUE, Color.BLUE,
84 | Color.BLUE, Color.BLUE, Color.BLUE,
85 | Color.BLUE, Color.BLUE, Color.BLUE,
86 | Color.BLUE, //Color.RED, Color.RED,
87 | //Color.RED, Color.RED, Color.RED,
88 | //Color.RED, Color.RED, Color.RED,
89 | //Color.RED, Color.RED, Color.RED,
90 | //Color.RED, Color.GREEN, Color.BLUE,
91 | //Color.RED, Color.GREEN, Color.BLUE,
92 | //Color.RED, Color.GREEN, Color.BLUE
93 | };
94 |
95 | boolean showMoreColor = false;
96 |
97 | private Runnable mAnimateRunnable = new Runnable() {
98 | final float[] hsv = {1f, 1f, 1f};
99 |
100 | @Override
101 | public void run() {
102 | if (showMoreColor) {
103 | try {
104 | for (int i = 0; i < mLedColors.length; i++) { // Assigns gradient colors.
105 | int n = (i + mFrame) % (mLedColors.length * 3);
106 | hsv[0] = n * 360.f / (mLedColors.length * 3);
107 | mLedColors[i] = Color.HSVToColor(0, hsv);
108 | }
109 | mWs2812b.write(mLedColors);
110 | mFrame = (mFrame + 1) % (mLedColors.length * 3);
111 | } catch (IOException e) {
112 | Log.e(TAG, "Error while writing to LED strip", e);
113 | }
114 | mHandler.postDelayed(mAnimateRunnable, FRAME_DELAY_MS);
115 | } else {
116 | try {
117 | for (int i = 0; i < mLedColors.length; i++) { // Assigns gradient colors.
118 | mLedColors[i] = color;
119 | }
120 | mWs2812b.write(mLedColors);
121 | } catch (Exception e) {
122 | e.printStackTrace();
123 | }
124 |
125 | mHandler.postDelayed(mAnimateRunnable, 500);
126 | }
127 | }
128 | };
129 |
130 | @Override
131 | protected void onCreate(Bundle savedInstanceState) {
132 | super.onCreate(savedInstanceState);
133 |
134 |
135 | try {
136 | mWs2812b = new Ws2812b(BoardSpec.getSpiBus());
137 | } catch (IOException e) {
138 | // couldn't configure the device...
139 | }
140 |
141 | try {
142 | mWs2812b.write(mLedColors);
143 | } catch (IOException e) {
144 | // error setting LEDs
145 | }
146 |
147 | initCamera();
148 |
149 | /*
150 | try {
151 | Thread.sleep(500);
152 | } catch (InterruptedException e) {
153 | e.printStackTrace();
154 | }
155 | int c = mLedColors[0];
156 | for (int i=0;i10) {
563 | speed = speed - 5;
564 | try {
565 | pwmLeft.setPwmDutyCycle(speed + lrdSpeed);
566 | pwmRight.setPwmDutyCycle(speed - lrdSpeed);
567 | } catch (IOException e) {
568 | e.printStackTrace();
569 | }
570 | }
571 | }
572 |
573 | public void speedAdd() {
574 | if (speed<100) {
575 | speed = speed + 5;
576 | try {
577 | pwmLeft.setPwmDutyCycle(speed + lrdSpeed);
578 | pwmRight.setPwmDutyCycle(speed - lrdSpeed);
579 | } catch (IOException e) {
580 | e.printStackTrace();
581 | }
582 | }
583 | }
584 |
585 | private UartDevice echoDevice;
586 |
587 | private void openUart(PeripheralManager service, String name, int baudRate) throws IOException {
588 | echoDevice = service.openUartDevice(name);
589 | // Configure the UART
590 | echoDevice.setBaudrate(baudRate);
591 | echoDevice.setDataSize(8);
592 | echoDevice.setParity(UartDevice.PARITY_NONE);
593 | echoDevice.setStopBits(1);
594 |
595 | Log.i(TAG, "Open UART device");
596 |
597 | echoDevice.registerUartDeviceCallback(mInputHandler, mCallback);
598 | }
599 |
600 | /**
601 | * Close the UART device connection, if it exists
602 | */
603 | private void closeUart() throws IOException {
604 | if (echoDevice != null) {
605 | echoDevice.unregisterUartDeviceCallback(mCallback);
606 | try {
607 | echoDevice.close();
608 | } finally {
609 | echoDevice = null;
610 | }
611 | }
612 | }
613 |
614 | /**
615 | * Callback invoked when UART receives new incoming data.
616 | */
617 | private UartDeviceCallback mCallback = new UartDeviceCallback() {
618 | @Override
619 | public boolean onUartDeviceDataAvailable(UartDevice uart) {
620 | // Queue up a data transfer
621 | transferUartData();
622 | //Continue listening for more interrupts
623 | return true;
624 | }
625 |
626 | @Override
627 | public void onUartDeviceError(UartDevice uart, int error) {
628 | Log.w(TAG, uart + ": Error event " + error);
629 | }
630 | };
631 |
632 | public static int CHUNK_SIZE = 128;
633 |
634 | public boolean echo_prefix;
635 | public int echoHigh;
636 | public int echoLow;
637 | public int echoCRC;
638 |
639 | //private static byte[] prefix = "IoT".getBytes();
640 | /**
641 | * Loop over the contents of the UART RX buffer, transferring each
642 | * one back to the TX buffer to create a loopback service.
643 | *
644 | * Potentially long-running operation. Call from a worker thread.
645 | */
646 | private void transferUartData() {
647 | if (echoDevice != null) {
648 | // Loop until there is no more data in the RX buffer.
649 | try {
650 | byte[] buffer = new byte[CHUNK_SIZE];
651 | int read;
652 |
653 | while ((read = echoDevice.read(buffer, buffer.length)) > 0) {
654 | //mLoopbackDevice.write(prefix, prefix.length);
655 | //mLoopbackDevice.write(buffer, read);
656 | for (int i=0;i0 && distance<100)
662 | emStop();
663 | Log.i(TAG, "distance="+distance+"mm");
664 | } else {
665 | Log.i(TAG, "distance CRC Error");
666 | }
667 | i+=4;
668 | } else {
669 | break;
670 | }
671 | } else {
672 | i++;
673 | }
674 | }
675 | }
676 | } catch (IOException e) {
677 | Log.w(TAG, "Unable to transfer data over UART", e);
678 | }
679 | }
680 | }
681 |
682 | @Override
683 | protected void onDestroy() {
684 | super.onDestroy();
685 |
686 | // Close the LED strip when finished:
687 | try {
688 | mWs2812b.close();
689 | } catch (IOException e) {
690 | // error closing LED strip
691 | }
692 |
693 | try {
694 | left0.close();
695 | left1.close();
696 | right0.close();
697 | right1.close();
698 | echoDeviceEn.close();
699 | stop.close();
700 | } catch (IOException e) {
701 | e.printStackTrace();
702 | }
703 |
704 | try {
705 | pwmLeft.close();
706 | } catch (IOException e) {
707 | Log.e(TAG, e.getMessage(), e);
708 | }
709 | try {
710 | pwmRight.close();
711 | } catch (Exception e) {
712 | Log.e(TAG, e.getMessage(), e);
713 | }
714 |
715 | if (mButtonGpio!=null) try {
716 | mButtonGpio.close();
717 | } catch (IOException e) {
718 | Log.e(TAG, e.getMessage(), e);
719 | }
720 |
721 | // Terminate the worker thread
722 | if (mInputThread != null) {
723 | mInputThread.quitSafely();
724 | }
725 |
726 | // Attempt to close the UART device
727 | try {
728 | closeUart();
729 | } catch (IOException e) {
730 | Log.e(TAG, "Error closing UART device:", e);
731 | }
732 |
733 | mCamera.shutDown();
734 |
735 | mCameraThread.quitSafely();
736 | }
737 |
738 | int color;
739 |
740 | public void color(int color) {
741 | showMoreColor = false;
742 | this.color = color;
743 | }
744 |
745 | public void moreColor() {
746 | showMoreColor = true;
747 | }
748 |
749 | public void superSound(boolean on) {
750 | try {
751 | if (on) {
752 | echoDeviceEn.setValue(false);
753 | } else {
754 | echoDeviceEn.setValue(true);
755 | }
756 | } catch (Exception e) {
757 | e.printStackTrace();
758 | }
759 | }
760 |
761 | Handler handler = new Handler();
762 |
763 | public void takePicture() {
764 |
765 | handler.post(new Runnable() {
766 | @Override
767 | public void run() {
768 | try {
769 | Log.i(TAG, "PhotoCamera take Picture");
770 | mCamera.takePicture();
771 | } catch (Exception e) {
772 | e.printStackTrace();
773 | }
774 | }
775 | });
776 | }
777 | }
778 |
--------------------------------------------------------------------------------