├── .gitignore
├── .idea
├── compiler.xml
├── copyright
│ └── profiles_settings.xml
├── encodings.xml
├── gradle.xml
├── misc.xml
├── modules.xml
├── runConfigurations.xml
└── vcs.xml
├── LICENSE
├── README.md
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── img
├── sample0.png
└── sample1.png
├── sample
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── _8rine
│ │ └── upnpdiscovery_sample
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── _8rine
│ │ │ └── upnpdiscovery_sample
│ │ │ └── MainActivity.java
│ └── res
│ │ ├── layout
│ │ ├── activity_main.xml
│ │ └── recyclerview_row_item.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ ├── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ │ └── xml
│ │ └── backup_descriptor.xml
│ └── test
│ └── java
│ └── com
│ └── _8rine
│ └── upnpdiscovery_sample
│ └── ExampleUnitTest.java
├── settings.gradle
└── upnpdiscovery
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
├── androidTest
└── java
│ └── com
│ └── _8rine
│ └── upnpdiscovery
│ └── ExampleInstrumentedTest.java
├── main
├── AndroidManifest.xml
├── java
│ └── com
│ │ └── _8rine
│ │ └── upnpdiscovery
│ │ ├── UPnPDevice.java
│ │ └── UPnPDiscovery.java
└── res
│ └── values
│ └── strings.xml
└── test
└── java
└── com
└── _8rine
└── upnpdiscovery
└── ExampleUnitTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | *.iml
3 | .gradle
4 | /local.properties
5 | /.idea/workspace.xml
6 | /.idea/libraries
7 | .DS_Store
8 | /build
9 | /captures
10 | .externalNativeBuild
11 | # Built application files
12 | *.apk
13 | *.ap_
14 |
15 | # Files for the ART/Dalvik VM
16 | *.dex
17 |
18 | # Java class files
19 | *.class
20 |
21 | # Generated files
22 | bin/
23 | gen/
24 | out/
25 |
26 | # Gradle files
27 | .gradle/
28 | build/
29 |
30 | # Local configuration file (sdk path, etc)
31 | local.properties
32 |
33 | # Proguard folder generated by Eclipse
34 | proguard/
35 |
36 | # Log Files
37 | *.log
38 |
39 | # Android Studio Navigation editor temp files
40 | .navigation/
41 |
42 | # Android Studio captures folder
43 | captures/
44 |
45 | # Intellij
46 | *.iml
47 | .idea/workspace.xml
48 |
49 | # Keystore files
50 | *.jks
51 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
19 |
20 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 | Android API 19 Platform
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 custanator
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Android-uPnP-Discovery
2 | Discover UPnP devices via SSDP (Simple Service Discovery Protocol) on the current WiFi network
3 |
4 | ## How:
5 |
6 | 1. Send M-SEARCH request via Multicast UDP
7 | 2. Receive Unicast UDP response from compatible devices
8 | 3. Get and parse XML description file from device
9 |
10 | # Demo
11 |
12 |
13 |
14 |
15 | # Installation
16 | ## Gradle
17 | ```text
18 | implementation 'com.github.custanator:upnpdiscovery:1.0.1'
19 | ```
20 |
21 | # Usage
22 | ## Basically usage
23 | Search all devices (M-SEARCH ST: ssdp:all)
24 |
25 | ```java
26 | UPnPDiscovery.discoveryDevices(activity, new UPnPDiscovery.OnDiscoveryListener() {
27 | @Override
28 | public void OnStart() {
29 | Log.d("UPnPDiscovery", "Starting discovery");
30 | }
31 |
32 | @Override
33 | public void OnFoundNewDevice(UPnPDevice device) {
34 | Log.d("UPnPDiscovery", "Found new device: " + device.toString());
35 | // String friendlyName = device.getFriendlyName();
36 | // ... see UPnPDevice description below
37 | }
38 |
39 | @Override
40 | public void OnFinish(HashSet devices) {
41 | Log.d("UPnPDiscovery", "Finish discovery");
42 | }
43 |
44 | @Override
45 | public void OnError(Exception e) {
46 | Log.d("UPnPDiscovery", "Error: " + e.getLocalizedMessage());
47 | }
48 | });
49 | ```
50 |
51 | ## Extended usage
52 | For custom query use:
53 |
54 | ```java
55 | String customQuery = "M-SEARCH * HTTP/1.1" + "\r\n" +
56 | "HOST: 239.255.255.250:1900" + "\r\n" +
57 | "MAN: \"ssdp:discover\"" + "\r\n" +
58 | "MX: 1"+ "\r\n" +
59 | //"ST: urn:schemas-upnp-org:service:AVTransport:1" + "\r\n" + // Use for Sonos
60 | //"ST: urn:schemas-upnp-org:device:InternetGatewayDevice:1" + "\r\n" + // Use for Routers
61 | "ST: ssdp:all" + "\r\n" + // Use this for all UPnP Devices (DEFAULT)
62 | "\r\n";
63 | int customPort = 1900;
64 | String customAddress = "239.255.255.250";
65 |
66 | UPnPDiscovery.discoveryDevices(activity, new UPnPDiscovery.OnDiscoveryListener() {
67 | @Override
68 | public void OnStart() {
69 | Log.d("UPnPDiscovery", "Starting discovery");
70 | }
71 |
72 | @Override
73 | public void OnFoundNewDevice(UPnPDevice device) {
74 | Log.d("UPnPDiscovery", "Found new device: " + device.toString());
75 | // String friendlyName = device.getFriendlyName();
76 | // ... see UPnPDevice description below
77 | }
78 |
79 | @Override
80 | public void OnFinish(HashSet devices) {
81 | Log.d("UPnPDiscovery", "Finish discovery");
82 | }
83 |
84 | @Override
85 | public void OnError(Exception e) {
86 | Log.d("UPnPDiscovery", "Error: " + e.getLocalizedMessage());
87 | }
88 | }, customQuery, customAddress, customPort);
89 | ```
90 |
91 | ## Methods
92 | UPNPDevice object has methods:
93 |
94 | ```java
95 | public String getHostAddress();
96 | public String getHeader();
97 | public String getST();
98 | public String getUSN();
99 | public String getServer();
100 | public String getLocation();
101 | public String getDescriptionXML();
102 | public String getDeviceType();
103 | public String getFriendlyName();
104 | public String getPresentationURL();
105 | public String getSerialNumber();
106 | public String getModelName();
107 | public String getModelNumber();
108 | public String getModelURL();
109 | public String getManufacturer();
110 | public String getManufacturerURL();
111 | public String getUDN();
112 | public String getURLBase();
113 |
114 | // Return all params
115 | public String toString();
116 | ```
117 |
118 | # Links
119 | 1. https://en.wikipedia.org/wiki/Universal_Plug_and_Play
120 | 2. https://en.wikipedia.org/wiki/Simple_Service_Discovery_Protocol
121 | 3. https://tools.ietf.org/html/draft-cai-ssdp-v1-03#section-2.2.1
122 | 4. http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf
123 | 5. https://github.com/berndverst/android-ssdp
124 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | maven {
7 | url 'https://maven.google.com/'
8 | name 'Google'
9 | }
10 | google()
11 | }
12 | dependencies {
13 | classpath 'com.android.tools.build:gradle:3.5.0'
14 | classpath 'com.novoda:bintray-release:0.9.1'
15 |
16 | // NOTE: Do not place your application dependencies here; they belong
17 | // in the individual module build.gradle files
18 | }
19 | }
20 |
21 | allprojects {
22 | repositories {
23 | jcenter()
24 | maven {
25 | url 'https://maven.google.com/'
26 | name 'Google'
27 | }
28 | }
29 | }
30 |
31 | task clean(type: Delete) {
32 | delete rootProject.buildDir
33 | }
34 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | android.enableJetifier=true
13 | android.useAndroidX=true
14 | org.gradle.jvmargs=-Xmx1536m
15 |
16 | # When configured, Gradle will run in incubating parallel mode.
17 | # This option should only be used with decoupled projects. More details, visit
18 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
19 | # org.gradle.parallel=true
20 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/custanator/android-upnp-discovery/7602ef7858491804d9c203c6d57ca63c78f55320/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Sep 02 15:13:49 CEST 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
7 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/img/sample0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/custanator/android-upnp-discovery/7602ef7858491804d9c203c6d57ca63c78f55320/img/sample0.png
--------------------------------------------------------------------------------
/img/sample1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/custanator/android-upnp-discovery/7602ef7858491804d9c203c6d57ca63c78f55320/img/sample1.png
--------------------------------------------------------------------------------
/sample/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/sample/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 29
5 | defaultConfig {
6 | applicationId "com.octarine.ssdp_test"
7 | minSdkVersion 15
8 | targetSdkVersion 29
9 | versionCode 1
10 | versionName "1.0"
11 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | }
20 |
21 | dependencies {
22 | implementation fileTree(dir: 'libs', include: ['*.jar'])
23 | androidTestImplementation('androidx.test.espresso:espresso-core:3.1.0', {
24 | exclude group: 'com.android.support', module: 'support-annotations'
25 | })
26 | implementation 'androidx.appcompat:appcompat:1.0.2'
27 | implementation project(':upnpdiscovery')
28 | testImplementation 'junit:junit:4.12'
29 | implementation 'androidx.recyclerview:recyclerview:1.0.0'
30 | }
31 |
--------------------------------------------------------------------------------
/sample/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/rustam/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/sample/src/androidTest/java/com/_8rine/upnpdiscovery_sample/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com._8rine.upnpdiscovery_sample;
2 |
3 | import android.content.Context;
4 | import androidx.test.platform.app.InstrumentationRegistry;
5 | import androidx.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.octarine.ssdp_test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/_8rine/upnpdiscovery_sample/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com._8rine.upnpdiscovery_sample;
2 |
3 | import androidx.annotation.NonNull;
4 | import android.content.Context;
5 | import androidx.appcompat.app.AppCompatActivity;
6 | import android.os.Bundle;
7 | import androidx.recyclerview.widget.LinearLayoutManager;
8 | import androidx.recyclerview.widget.RecyclerView;
9 | import android.util.Log;
10 | import android.view.LayoutInflater;
11 | import android.view.View;
12 | import android.view.ViewGroup;
13 | import android.widget.TextView;
14 | import android.widget.Toast;
15 |
16 | import com._8rine.upnpdiscovery.UPnPDevice;
17 | import com._8rine.upnpdiscovery.UPnPDiscovery;
18 |
19 | import java.util.ArrayList;
20 | import java.util.HashSet;
21 |
22 |
23 | public class MainActivity extends AppCompatActivity {
24 |
25 | private RecyclerView.Adapter mAdapter;
26 | private Context mContext;
27 |
28 | private final ArrayList myDataSet = new ArrayList<>();
29 |
30 | @Override
31 | protected void onCreate(Bundle savedInstanceState) {
32 | super.onCreate(savedInstanceState);
33 | setContentView(R.layout.activity_main);
34 |
35 | mContext = this;
36 | RecyclerView mRecyclerView = findViewById(R.id.recyclerView);
37 |
38 | // use this setting to improve performance if you know that changes
39 | // in content do not change the layout size of the RecyclerView
40 | mRecyclerView.setHasFixedSize(true);
41 |
42 | // use a linear layout manager
43 | RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
44 | mRecyclerView.setLayoutManager(mLayoutManager);
45 |
46 | // specify an adapter (see also next example)
47 | mAdapter = new MyAdapter(myDataSet);
48 | mRecyclerView.setAdapter(mAdapter);
49 |
50 |
51 | UPnPDiscovery.discoveryDevices(this, new UPnPDiscovery.OnDiscoveryListener() {
52 | @Override
53 | public void OnStart() {
54 | Toast.makeText(mContext, "Start discovery", Toast.LENGTH_SHORT).show();
55 | }
56 |
57 | @Override
58 | public void OnFoundNewDevice(UPnPDevice device) {
59 | Toast.makeText(mContext, "Found new device", Toast.LENGTH_SHORT).show();
60 | Log.d("App", device.getLocation());
61 | myDataSet.add(device.toString());
62 | mAdapter.notifyDataSetChanged();
63 | }
64 |
65 | @Override
66 | public void OnFinish(HashSet devices) {
67 | // To do something
68 | Toast.makeText(mContext, "Discovery finished", Toast.LENGTH_SHORT).show();
69 | }
70 |
71 | @Override
72 | public void OnError(Exception e) {
73 | Toast.makeText(mContext, "Error: " + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
74 | }
75 | });
76 |
77 | }
78 |
79 | public class MyAdapter extends RecyclerView.Adapter {
80 | private final ArrayList mDataset;
81 |
82 | class ViewHolder extends RecyclerView.ViewHolder {
83 | final TextView mTextView;
84 | ViewHolder(View view) {
85 | super(view);
86 | mTextView = view.findViewById(R.id.textView);
87 | }
88 | }
89 |
90 | MyAdapter(ArrayList myDataset) {
91 | mDataset = myDataset;
92 | }
93 |
94 | @NonNull
95 | @Override
96 | public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
97 | int viewType) {
98 | View v = LayoutInflater.from(parent.getContext())
99 | .inflate(R.layout.recyclerview_row_item, parent, false);
100 | return new ViewHolder(v);
101 | }
102 |
103 | @Override
104 | public void onBindViewHolder(ViewHolder holder, int position) {
105 | holder.mTextView.setText(mDataset.get(position));
106 | }
107 |
108 | @Override
109 | public int getItemCount() {
110 | return mDataset.size();
111 | }
112 | }
113 |
114 |
115 |
116 |
117 | }
118 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
14 |
18 |
19 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/recyclerview_row_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
11 |
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/custanator/android-upnp-discovery/7602ef7858491804d9c203c6d57ca63c78f55320/sample/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/custanator/android-upnp-discovery/7602ef7858491804d9c203c6d57ca63c78f55320/sample/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/custanator/android-upnp-discovery/7602ef7858491804d9c203c6d57ca63c78f55320/sample/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/custanator/android-upnp-discovery/7602ef7858491804d9c203c6d57ca63c78f55320/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/custanator/android-upnp-discovery/7602ef7858491804d9c203c6d57ca63c78f55320/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | UPnPDiscovery Sample
3 |
4 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/sample/src/main/res/xml/backup_descriptor.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/sample/src/test/java/com/_8rine/upnpdiscovery_sample/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com._8rine.upnpdiscovery_sample;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':sample', ':upnpdiscovery'
2 |
--------------------------------------------------------------------------------
/upnpdiscovery/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/upnpdiscovery/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.novoda.bintray-release'
3 |
4 | android {
5 | compileSdkVersion 29
6 |
7 | defaultConfig {
8 | minSdkVersion 15
9 | targetSdkVersion 29
10 | versionCode 2
11 | versionName "1.0.1"
12 |
13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
14 |
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | lintOptions {
23 | abortOnError false
24 | }
25 | }
26 |
27 | dependencies {
28 | implementation fileTree(dir: 'libs', include: ['*.jar'])
29 | androidTestImplementation('androidx.test.espresso:espresso-core:3.1.0', {
30 | exclude group: 'com.android.support', module: 'support-annotations'
31 | })
32 | implementation 'androidx.appcompat:appcompat:1.0.2'
33 | implementation 'com.android.volley:volley:1.1.1'
34 | implementation 'com.stanfy:gson-xml-java:0.1.7'
35 | testImplementation 'junit:junit:4.12'
36 | }
37 |
38 | publish {
39 | userOrg = 'custanator'
40 | groupId = 'com.github.custanator'
41 | artifactId = 'upnpdiscovery'
42 | publishVersion = '1.0.1'
43 | desc = 'Discovery UPnP devices via SSDP protocol'
44 | licences = ['MIT']
45 | uploadName = 'Android-uPnP-Discovery'
46 | website = 'https://github.com/custanator/android-upnp-discovery.git'
47 | }
48 |
49 |
--------------------------------------------------------------------------------
/upnpdiscovery/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/rustam/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/upnpdiscovery/src/androidTest/java/com/_8rine/upnpdiscovery/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com._8rine.upnpdiscovery;
2 |
3 | import android.content.Context;
4 | import androidx.test.platform.app.InstrumentationRegistry;
5 | import androidx.test.ext.junit.runners.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.octarine.upnpdiscovery.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/upnpdiscovery/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/upnpdiscovery/src/main/java/com/_8rine/upnpdiscovery/UPnPDevice.java:
--------------------------------------------------------------------------------
1 | package com._8rine.upnpdiscovery;
2 |
3 | import androidx.annotation.NonNull;
4 |
5 | import com.stanfy.gsonxml.GsonXml;
6 | import com.stanfy.gsonxml.GsonXmlBuilder;
7 | import com.stanfy.gsonxml.XmlParserCreator;
8 | import org.xmlpull.v1.XmlPullParser;
9 | import org.xmlpull.v1.XmlPullParserFactory;
10 |
11 | public class UPnPDevice {
12 |
13 | private static final String LINE_END = "\r\n";
14 |
15 | // From SSDP Packet
16 | private final String mHostAddress;
17 | // SSDP Packet Header
18 | private final String mHeader;
19 | private final String mLocation;
20 | private final String mServer;
21 | private final String mUSN;
22 | private final String mST;
23 |
24 | // XML content
25 | private String mXML;
26 |
27 | // From description XML
28 | private String mDeviceType;
29 | private String mFriendlyName;
30 | private String mPresentationURL;
31 | private String mSerialNumber;
32 | private String mModelName;
33 | private String mModelNumber;
34 | private String mModelURL;
35 | private String mManufacturer;
36 | private String mManufacturerURL;
37 | private String mUDN;
38 | private String mURLBase;
39 |
40 | UPnPDevice(String hostAddress, String header) {
41 | this.mHeader = header;
42 | this.mHostAddress = hostAddress;
43 | String LOCATION_TEXT = "LOCATION: ";
44 | this.mLocation = parseHeader(header, LOCATION_TEXT);
45 | String SERVER_TEXT = "SERVER: ";
46 | this.mServer = parseHeader(header, SERVER_TEXT);
47 | String USN_TEXT = "USN: ";
48 | this.mUSN = parseHeader(header, USN_TEXT);
49 | String ST_TEXT = "ST: ";
50 | this.mST = parseHeader(header, ST_TEXT);
51 | }
52 |
53 | public void update(String xml) {
54 | this.mXML = xml;
55 | xmlParse(xml);
56 | }
57 |
58 | @NonNull
59 | public String toString() {
60 | return "FriendlyName: " + mFriendlyName + LINE_END +
61 | "ModelName: " + mModelName + LINE_END +
62 | "HostAddress: " + mHostAddress + LINE_END +
63 | "Location: " + mLocation + LINE_END +
64 | "Server: " + mServer + LINE_END +
65 | "USN: " + mUSN + LINE_END +
66 | "ST: " + mST + LINE_END +
67 | "DeviceType: " + mDeviceType + LINE_END +
68 | "PresentationURL: " + mPresentationURL + LINE_END +
69 | "SerialNumber: " + mSerialNumber + LINE_END +
70 | "ModelURL: " + mModelURL + LINE_END +
71 | "ModelNumber: " + mModelNumber + LINE_END +
72 | "Manufacturer: " + mManufacturer + LINE_END +
73 | "ManufacturerURL: " + mManufacturerURL + LINE_END +
74 | "UDN: " + mUDN + LINE_END +
75 | "URLBase: " + mURLBase;
76 | }
77 |
78 | private String parseHeader(String mSearchAnswer, String whatSearch){
79 | String result = "";
80 | int searchLinePos = mSearchAnswer.indexOf(whatSearch);
81 | if(searchLinePos != -1){
82 | searchLinePos += whatSearch.length();
83 | int locColon = mSearchAnswer.indexOf(LINE_END, searchLinePos);
84 | result = mSearchAnswer.substring(searchLinePos, locColon);
85 | }
86 | return result;
87 | }
88 |
89 | private void xmlParse(String xml) {
90 | XmlParserCreator parserCreator = new XmlParserCreator() {
91 | @Override
92 | public XmlPullParser createParser() {
93 | try {
94 | return XmlPullParserFactory.newInstance().newPullParser();
95 | } catch (Exception e) {
96 | throw new RuntimeException(e);
97 | }
98 | }
99 | };
100 |
101 | GsonXml gsonXml = new GsonXmlBuilder()
102 | .setXmlParserCreator(parserCreator)
103 | .create();
104 |
105 |
106 | DescriptionModel model = gsonXml.fromXml(xml, DescriptionModel.class);
107 |
108 | this.mFriendlyName = model.device.friendlyName;
109 | this.mDeviceType = model.device.deviceType;
110 | this.mPresentationURL = model.device.presentationURL;
111 | this.mSerialNumber = model.device.serialNumber;
112 | this.mModelName = model.device.modelName;
113 | this.mModelNumber = model.device.modelNumber;
114 | this.mModelURL = model.device.modelURL;
115 | this.mManufacturer = model.device.manufacturer;
116 | this.mManufacturerURL = model.device.manufacturerURL;
117 | this.mUDN = model.device.UDN;
118 | this.mURLBase = model.URLBase;
119 | }
120 |
121 | private static class Device {
122 | private String deviceType;
123 | private String friendlyName;
124 | private String presentationURL;
125 | private String serialNumber;
126 | private String modelName;
127 | private String modelNumber;
128 | private String modelURL;
129 | private String manufacturer;
130 | private String manufacturerURL;
131 | private String UDN;
132 |
133 | }
134 |
135 | private static class DescriptionModel {
136 | private Device device;
137 | private String URLBase;
138 |
139 | }
140 |
141 | public String getHostAddress() {
142 | return mHostAddress;
143 | }
144 |
145 | public String getHeader() {
146 | return mHeader;
147 | }
148 |
149 | public String getST() {
150 | return mST;
151 | }
152 |
153 | public String getUSN() {
154 | return mUSN;
155 | }
156 |
157 | public String getServer() {
158 | return mServer;
159 | }
160 |
161 | public String getLocation() {
162 | return mLocation;
163 | }
164 |
165 | public String getDescriptionXML() {
166 | return mXML;
167 | }
168 |
169 | public String getDeviceType() {
170 | return mDeviceType;
171 | }
172 |
173 | public String getFriendlyName() {
174 | return mFriendlyName;
175 | }
176 |
177 | public String getPresentationURL() {
178 | return mPresentationURL;
179 | }
180 |
181 | public String getSerialNumber() {
182 | return mSerialNumber;
183 | }
184 |
185 | public String getModelName() {
186 | return mModelName;
187 | }
188 |
189 | public String getModelNumber() {
190 | return mModelNumber;
191 | }
192 |
193 | public String getModelURL() {
194 | return mModelURL;
195 | }
196 |
197 | public String getManufacturer() {
198 | return mManufacturer;
199 | }
200 |
201 | public String getManufacturerURL() {
202 | return mManufacturerURL;
203 | }
204 |
205 | public String getUDN() {
206 | return mUDN;
207 | }
208 |
209 | public String getURLBase() {
210 | return mURLBase;
211 | }
212 | }
213 |
--------------------------------------------------------------------------------
/upnpdiscovery/src/main/java/com/_8rine/upnpdiscovery/UPnPDiscovery.java:
--------------------------------------------------------------------------------
1 | package com._8rine.upnpdiscovery;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.net.wifi.WifiManager;
6 | import android.os.AsyncTask;
7 | import android.util.Log;
8 |
9 | import com.android.volley.Request;
10 | import com.android.volley.Response;
11 | import com.android.volley.VolleyError;
12 | import com.android.volley.toolbox.StringRequest;
13 | import com.android.volley.toolbox.Volley;
14 |
15 | import java.io.IOException;
16 | import java.net.DatagramPacket;
17 | import java.net.DatagramSocket;
18 | import java.net.InetAddress;
19 | import java.util.HashSet;
20 |
21 | public class UPnPDiscovery extends AsyncTask {
22 |
23 | private static final String TAG = UPnPDiscovery.class.getSimpleName();
24 |
25 | private static final int DISCOVER_TIMEOUT = 1500;
26 | private static final String LINE_END = "\r\n";
27 | private static final String DEFAULT_QUERY = "M-SEARCH * HTTP/1.1" + LINE_END +
28 | "HOST: 239.255.255.250:1900" + LINE_END +
29 | "MAN: \"ssdp:discover\"" + LINE_END +
30 | "MX: 1"+ LINE_END +
31 | //"ST: urn:schemas-upnp-org:service:AVTransport:1" + LINE_END + // Use for Sonos
32 | //"ST: urn:schemas-upnp-org:device:InternetGatewayDevice:1" + LINE_END + // Use for Routes
33 | "ST: ssdp:all" + LINE_END + // Use this for all UPnP Devices
34 | LINE_END;
35 | private static final String DEFAULT_ADDRESS = "239.255.255.250";
36 |
37 | private final HashSet devices = new HashSet<>();
38 | private final Context mContext;
39 | private final Activity mActivity;
40 | private int mThreadsCount;
41 | private final String mCustomQuery;
42 | private final String mInternetAddress;
43 | private final int mPort;
44 |
45 | public interface OnDiscoveryListener {
46 | void OnStart();
47 | void OnFoundNewDevice(UPnPDevice device);
48 | void OnFinish(HashSet devices);
49 | void OnError(Exception e);
50 | }
51 |
52 | private final OnDiscoveryListener mListener;
53 |
54 | private UPnPDiscovery(Activity activity, OnDiscoveryListener listener) {
55 | mContext = activity.getApplicationContext();
56 | mActivity = activity;
57 | mListener = listener;
58 | mThreadsCount = 0;
59 | mCustomQuery = DEFAULT_QUERY;
60 | mInternetAddress = DEFAULT_ADDRESS;
61 | mPort = 1900;
62 | }
63 |
64 | private UPnPDiscovery(Activity activity, OnDiscoveryListener listener, String customQuery, String address, int port) {
65 | mContext = activity.getApplicationContext();
66 | mActivity = activity;
67 | mListener = listener;
68 | mThreadsCount = 0;
69 | mCustomQuery = customQuery;
70 | mInternetAddress = address;
71 | mPort = port;
72 | }
73 |
74 | @Override
75 | protected Void doInBackground(Activity... activities) {
76 | mActivity.runOnUiThread(new Runnable() {
77 | public void run() {
78 | mListener.OnStart();
79 | }
80 | });
81 | WifiManager wifi = (WifiManager) mContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
82 | if(wifi != null) {
83 | WifiManager.MulticastLock lock = wifi.createMulticastLock("The Lock");
84 | lock.acquire();
85 | DatagramSocket socket = null;
86 | try {
87 | InetAddress group = InetAddress.getByName(mInternetAddress);
88 | int port = mPort;
89 | String query = mCustomQuery;
90 |
91 | socket = new DatagramSocket(null);
92 | socket.setReuseAddress(true);
93 | socket.setBroadcast(true);
94 | socket.bind(new InetSocketAddress(port));
95 |
96 | DatagramPacket datagramPacketRequest = new DatagramPacket(query.getBytes(), query.length(), group, port);
97 | socket.send(datagramPacketRequest);
98 |
99 | long time = System.currentTimeMillis();
100 | long curTime = System.currentTimeMillis();
101 |
102 | while (curTime - time < 1000) {
103 | DatagramPacket datagramPacket = new DatagramPacket(new byte[1024], 1024);
104 | socket.receive(datagramPacket);
105 | String response = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
106 | if (response.substring(0, 12).toUpperCase().equals("HTTP/1.1 200")) {
107 | UPnPDevice device = new UPnPDevice(datagramPacket.getAddress().getHostAddress(), response);
108 | mThreadsCount++;
109 | getData(device.getLocation(), device);
110 | }
111 | curTime = System.currentTimeMillis();
112 | }
113 |
114 | } catch (final IOException e) {
115 | e.printStackTrace();
116 | mActivity.runOnUiThread(new Runnable() {
117 | public void run() {
118 | mListener.OnError(e);
119 | }
120 | });
121 | } finally {
122 | if (socket != null) {
123 | socket.close();
124 | }
125 | }
126 | lock.release();
127 | }
128 | return null;
129 | }
130 |
131 | private void getData(final String url, final UPnPDevice device) {
132 | StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
133 | new Response.Listener() {
134 | @Override
135 | public void onResponse(String response) {
136 | device.update(response);
137 | mListener.OnFoundNewDevice(device);
138 | devices.add(device);
139 | mThreadsCount--;
140 | if (mThreadsCount == 0) {
141 | mActivity.runOnUiThread(new Runnable() {
142 | public void run() {
143 | mListener.OnFinish(devices);
144 | }
145 | });
146 | }
147 | }
148 | }, new Response.ErrorListener() {
149 | @Override
150 | public void onErrorResponse(VolleyError error) {
151 | mThreadsCount--;
152 | Log.d(TAG, "URL: " + url + " get content error!");
153 | }
154 | });
155 | stringRequest.setTag(TAG + "SSDP description request");
156 | Volley.newRequestQueue(mContext).add(stringRequest);
157 | }
158 |
159 | public static void discoveryDevices(Activity activity, OnDiscoveryListener listener) {
160 | UPnPDiscovery discover = new UPnPDiscovery(activity, listener);
161 | discover.execute();
162 | try {
163 | Thread.sleep(DISCOVER_TIMEOUT);
164 | } catch (InterruptedException ignored) {
165 | }
166 | }
167 |
168 | public static boolean discoveryDevices(Activity activity, OnDiscoveryListener listener, String customQuery, String address, int port) {
169 | UPnPDiscovery discover = new UPnPDiscovery(activity, listener, customQuery, address, port);
170 | discover.execute();
171 | try {
172 | Thread.sleep(DISCOVER_TIMEOUT);
173 | return true;
174 | } catch (InterruptedException e) {
175 | return false;
176 | }
177 | }
178 |
179 | }
180 |
--------------------------------------------------------------------------------
/upnpdiscovery/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | UPnPDiscovery
3 |
4 |
--------------------------------------------------------------------------------
/upnpdiscovery/src/test/java/com/_8rine/upnpdiscovery/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com._8rine.upnpdiscovery;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------