From a0c589d61f929ecb586fa00865a5edaa1dc98ccb Mon Sep 17 00:00:00 2001 From: Patches Date: Sun, 12 May 2019 14:04:19 -0500 Subject: [PATCH] issue116, issue127-130, and issue 133 - Add Android P support, sample app, add RoboElectric; Update documentation; Bug and crash fixes --- .github/ISSUE_TEMPLATE/bug-report.md | 9 +- .gitignore | 7 +- .idea/dictionaries/patches.xml | 12 + .travis.yml | 15 +- CHANGE.md | 4 +- README.md | 78 ++- build.gradle | 7 +- changes/4.x.md | 1 + changes/whatsnew/2.x.md | 13 + changes/whatsnew/3.x.md | 21 + config/detekt-config.yml | 4 +- documentation/adding_and_removing_networks.md | 66 +- ...necting_and_disconnecting_from_networks.md | 4 +- documentation/current_network.md | 27 +- documentation/enabling_and_disabling_wifi.md | 32 +- documentation/frequency.md | 36 +- documentation/ip.md | 16 +- documentation/nearby_access_points.md | 29 +- documentation/permissions_example.md | 302 --------- documentation/rssi.md | 12 +- documentation/saved_networks.md | 34 +- .../using_legacy_classes_and_logic.md | 41 ++ gradle/cpd.gradle | 4 +- gradle/custom-tasks.gradle | 26 - gradle/jacoco.gradle | 4 +- gradle/static-analysis.gradle | 41 +- gradle/versions.gradle | 18 +- .../-get-current-network-callbacks/index.html | 9 + .../no-current-network.html | 19 + .../index.html | 9 + .../no-current-network-info.html | 19 + .../index.html | 9 + .../no-access-points-found.html | 19 + .../-wise-fy-receiver/-init-.html | 14 + .../-wise-fy-receiver/index.html | 37 ++ .../-wise-fy-receiver/on-receive.html | 14 + .../com.isupatches.wisefy.reciever/index.html | 24 + .../-wise-fy/-brains/-init-.html | 14 +- .../-wise-fy/-brains/get-smarts.html | 1 + .../-wise-fy/-brains/index.html | 14 +- .../-wise-fy/-brains/logging.html | 2 +- .../-wise-fy/add-w-e-p-network.html | 11 +- .../-wise-fy/add-w-p-a2-network.html | 3 +- .../com.isupatches.wisefy/-wise-fy/dump.html | 1 + .../-wise-fy/get-nearby-access-points.html | 8 +- .../com.isupatches.wisefy/-wise-fy/index.html | 4 +- ...is-device-connected-to-mobile-network.html | 4 +- ...e-connected-to-mobile-or-wifi-network.html | 1 - .../is-device-connected-to-wifi-network.html | 3 +- .../-wise-fy/is-device-roaming.html | 3 +- javadoc/wisefy/index-outline.html | 582 +++++++++--------- settings.gradle | 2 +- wisefy/build.gradle | 20 +- .../wisefy/BaseAndroidJUnit4TestClass.kt | 82 --- .../wisefy/WiseFyConnectionTests.kt | 190 ------ .../main/java/com/isupatches/wisefy/WiseFy.kt | 288 ++++++--- .../com/isupatches/wisefy/WiseFyPrechecks.kt | 4 +- .../callbacks/GetCurrentNetworkCallbacks.kt | 13 +- .../GetCurrentNetworkInfoCallbacks.kt | 13 +- .../GetNearbyAccessPointsCallbacks.kt | 11 + .../AbstractWiseFyConnection.kt} | 108 +--- .../wisefy/connection/WiseFyConnection.kt | 52 ++ .../connection/WiseFyConnectionLegacy.kt | 193 ++++++ .../connection/WiseFyConnectionSDK23.kt | 266 ++++++++ .../connection/WiseFyConnectionStatus.kt | 31 + .../AbstractWiseFySearch.kt} | 461 ++++++++------ .../isupatches/wisefy/search/WiseFySearch.kt | 51 ++ .../wisefy/search/WiseFySearchLegacy.kt | 46 ++ .../wisefy/search/WiseFySearchSDK23.kt | 47 ++ .../com/isupatches/wisefy/utils/SleepUtil.kt | 1 + .../wisefy/utils/WifiConfigurationUtil.kt | 74 ++- .../isupatches/wisefy}/AddOpenNetworkTests.kt | 22 +- .../isupatches/wisefy}/AddWEPNetworkTests.kt | 24 +- .../isupatches/wisefy}/AddWPA2NetworkTests.kt | 23 +- .../wisefy}/ConnectToNetworkTests.kt | 17 +- .../isupatches/wisefy}/DisableWifiTests.kt | 15 +- .../DisconnectFromCurrentNetworkTests.kt | 15 +- .../com/isupatches/wisefy}/EnableWifiTests.kt | 15 +- .../wisefy}/GetCurrentNetworkInfoTest.kt | 36 +- .../wisefy}/GetCurrentNetworkTests.kt | 40 +- .../isupatches/wisefy}/GetFrequencyTests.kt | 68 +- .../java/com/isupatches/wisefy/GetIPTests.kt} | 35 +- .../wisefy}/GetNearbyAccessPointsTests.kt | 83 ++- .../com/isupatches/wisefy}/GetRSSITests.kt | 20 +- .../wisefy}/GetSavedNetworkTests.kt | 18 +- .../wisefy}/GetSavedNetworksTests.kt | 18 +- .../IsDeviceConnectedToMobileNetworkTests.kt | 19 +- ...viceConnectedToMobileOrWifiNetworkTests.kt | 15 +- .../wisefy}/IsDeviceConnectedToSSIDTests.kt | 16 +- .../IsDeviceConnectedToWifiNetworkTests.kt | 19 +- .../wisefy}/IsDeviceRoamingTests.kt | 25 +- .../isupatches/wisefy}/IsNetwork5gHzTests.kt | 58 +- .../isupatches/wisefy}/IsNetworkEAPTests.kt | 16 +- .../isupatches/wisefy}/IsNetworkPSKTest.kt | 16 +- .../isupatches/wisefy}/IsNetworkSavedTests.kt | 15 +- .../wisefy}/IsNetworkSecureTests.kt | 16 +- .../isupatches/wisefy}/IsNetworkWPA2Test.kt | 16 +- .../isupatches/wisefy}/IsNetworkWPATests.kt | 16 +- .../isupatches/wisefy}/IsNetworkWepTests.kt | 16 +- .../isupatches/wisefy}/IsWifiEnabledTests.kt | 15 +- .../isupatches/wisefy}/RemoveNetworkTests.kt | 18 +- .../wisefy}/SearchForAccessPointTests.kt | 19 +- .../wisefy}/SearchForAccessPointsTests.kt | 18 +- .../isupatches/wisefy}/SearchForSSIDTests.kt | 19 +- .../isupatches/wisefy}/SearchForSSIDsTests.kt | 18 +- .../isupatches/wisefy/WiseFyPrechecksTests.kt | 28 +- .../com/isupatches/wisefy}/WiseFyTests.kt | 17 +- .../connection/WiseFyConnectionLegacyTests.kt | 313 ++++++++++ .../connection/WisefyConnectionSDK23Tests.kt | 421 +++++++++++++ .../wisefy/internal}/GeneratorUtil.kt | 4 +- .../internal/NetworkCapabilitiesUtil.kt | 42 ++ .../wisefy/internal}/NullCallbackUtil.kt | 16 +- .../wisefy/internal/ReflectionHelpers.java | 99 +++ .../wisefy/internal}/VerificationUtil.kt | 26 +- .../wisefy/internal/base/BaseUnitTest.kt | 88 +++ .../wisefy/internal/mock}/MockNetworkUtil.kt | 48 +- .../mock}/MockWiseFyConnectionUtil.kt | 41 +- .../internal/mock}/MockWiseFyPrechecksUtil.kt | 5 +- .../internal/mock}/MockWiseFySearchUtil.kt | 37 +- .../wisefy/main/PublicApiVisibilityTests.kt | 24 + .../search/AbstractWiseFySearchTests.kt | 204 ++++++ .../wisefy/search/WiseFySearchLegacyTests.kt} | 322 +++++----- .../wisefy/search/WiseFySearchSdk23Tests.kt | 484 +++++++++++++++ wisefysample/.gitignore | 1 + wisefysample/build.gradle | 61 ++ wisefysample/proguard-rules.pro | 0 wisefysample/src/main/AndroidManifest.xml | 33 + .../wisefysample/MainApplication.kt | 63 ++ .../internal/base/BaseActivity.kt | 14 + .../internal/base/BaseFragment.kt | 63 ++ .../wisefysample/internal/base/BaseMvp.kt | 17 + .../internal/base/BasePresenter.kt | 52 ++ .../internal/base/ViewNotAttachedException.kt | 5 + .../internal/di/PermissionsModule.kt | 12 + .../internal/di/PreferencesModule.kt | 39 ++ .../internal/di/ScreenBindingsModule.kt | 16 + .../internal/models/NetworkType.kt | 19 + .../internal/models/SearchType.kt | 19 + .../wisefysample/internal/nav/MainRouter.kt | 24 + .../internal/preferences/AddNetworkStore.kt | 74 +++ .../preferences/RemoveNetworkStore.kt | 37 ++ .../internal/preferences/SearchStore.kt | 108 ++++ .../preferences/SharedPreferenceKeys.kt | 3 + .../internal/util/EditTextExtensions.kt | 5 + .../wisefysample/internal/util/HtmlUtil.kt | 13 + .../internal/util/KeyboardUtil.kt | 15 + .../internal/util/PermissionsUtil.kt | 18 + .../wisefysample/internal/util/ToastUtil.kt | 8 + .../wisefysample/ui/add/AddNetworkFragment.kt | 210 +++++++ .../wisefysample/ui/add/AddNetworkModel.kt | 66 ++ .../wisefysample/ui/add/AddNetworkMvp.kt | 35 ++ .../ui/add/AddNetworkPresenter.kt | 46 ++ .../wisefysample/ui/main/MainActivity.kt | 83 +++ .../wisefysample/ui/main/MainFragment.kt | 15 + .../wisefysample/ui/misc/MiscFragment.kt | 335 ++++++++++ .../wisefysample/ui/misc/MiscModel.kt | 166 +++++ .../wisefysample/ui/misc/MiscMvp.kt | 75 +++ .../wisefysample/ui/misc/MiscPresenter.kt | 134 ++++ .../ui/remove/RemoveNetworkFragment.kt | 126 ++++ .../ui/remove/RemoveNetworkModel.kt | 35 ++ .../ui/remove/RemoveNetworkMvp.kt | 31 + .../ui/remove/RemoveNetworkPresenter.kt | 39 ++ .../wisefysample/ui/search/SearchFragment.kt | 367 +++++++++++ .../wisefysample/ui/search/SearchModel.kt | 124 ++++ .../wisefysample/ui/search/SearchMvp.kt | 63 ++ .../wisefysample/ui/search/SearchPresenter.kt | 101 +++ .../src/main/res/drawable/button_pressed.xml | 5 + .../src/main/res/drawable/button_selector.xml | 5 + .../main/res/drawable/button_unpressed.xml | 5 + .../src/main/res/drawable/ic_add_circle.xml | 9 + .../src/main/res/drawable/ic_apps.xml | 9 + .../src/main/res/drawable/ic_home.xml | 9 + .../res/drawable/ic_launcher_background.xml | 9 + .../res/drawable/ic_launcher_foreground.xml | 13 + .../main/res/drawable/ic_remove_circle.xml | 9 + .../src/main/res/drawable/ic_search.xml | 9 + .../src/main/res/layout/activity_main.xml | 49 ++ .../res/layout/dialog_permission_error.xml | 32 + .../layout/dialog_permission_rationale.xml | 32 + .../src/main/res/layout/fragment_add.xml | 118 ++++ .../src/main/res/layout/fragment_main.xml | 28 + .../src/main/res/layout/fragment_misc.xml | 126 ++++ .../src/main/res/layout/fragment_remove.xml | 45 ++ .../src/main/res/layout/fragment_search.xml | 234 +++++++ wisefysample/src/main/res/menu/menu_main.xml | 40 ++ .../res/mipmap-anydpi-v26/ic_launcher.xml | 5 + .../mipmap-anydpi-v26/ic_launcher_round.xml | 5 + .../src/main/res/mipmap-hdpi/ic_launcher.png | Bin 0 -> 6154 bytes .../src/main/res/mipmap-mdpi/ic_launcher.png | Bin 0 -> 5002 bytes .../src/main/res/mipmap-xhdpi/ic_launcher.png | Bin 0 -> 7264 bytes .../main/res/mipmap-xxhdpi/ic_launcher.png | Bin 0 -> 9399 bytes .../main/res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 11818 bytes wisefysample/src/main/res/values/colors.xml | 8 + wisefysample/src/main/res/values/dimens.xml | 15 + .../src/main/res/values/preferences.xml | 6 + wisefysample/src/main/res/values/strings.xml | 50 ++ wisefysample/src/main/res/values/styles.xml | 15 + 197 files changed, 8294 insertions(+), 2044 deletions(-) create mode 100644 .idea/dictionaries/patches.xml create mode 100644 changes/4.x.md create mode 100644 changes/whatsnew/2.x.md create mode 100644 changes/whatsnew/3.x.md delete mode 100644 documentation/permissions_example.md create mode 100644 documentation/using_legacy_classes_and_logic.md delete mode 100644 gradle/custom-tasks.gradle create mode 100644 javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-current-network-callbacks/no-current-network.html create mode 100644 javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-current-network-info-callbacks/no-current-network-info.html create mode 100644 javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-nearby-access-points-callbacks/no-access-points-found.html create mode 100644 javadoc/wisefy/com.isupatches.wisefy.reciever/-wise-fy-receiver/-init-.html create mode 100644 javadoc/wisefy/com.isupatches.wisefy.reciever/-wise-fy-receiver/index.html create mode 100644 javadoc/wisefy/com.isupatches.wisefy.reciever/-wise-fy-receiver/on-receive.html create mode 100644 javadoc/wisefy/com.isupatches.wisefy.reciever/index.html delete mode 100644 wisefy/src/androidTest/java/com/isupatches/wisefy/BaseAndroidJUnit4TestClass.kt delete mode 100644 wisefy/src/androidTest/java/com/isupatches/wisefy/WiseFyConnectionTests.kt rename wisefy/src/main/java/com/isupatches/wisefy/{WiseFyConnection.kt => connection/AbstractWiseFyConnection.kt} (50%) create mode 100644 wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnection.kt create mode 100644 wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnectionLegacy.kt create mode 100644 wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnectionSDK23.kt create mode 100644 wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnectionStatus.kt rename wisefy/src/main/java/com/isupatches/wisefy/{WiseFySearch.kt => search/AbstractWiseFySearch.kt} (67%) create mode 100644 wisefy/src/main/java/com/isupatches/wisefy/search/WiseFySearch.kt create mode 100644 wisefy/src/main/java/com/isupatches/wisefy/search/WiseFySearchLegacy.kt create mode 100644 wisefy/src/main/java/com/isupatches/wisefy/search/WiseFySearchSDK23.kt rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/AddOpenNetworkTests.kt (86%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/AddWEPNetworkTests.kt (86%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/AddWPA2NetworkTests.kt (86%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/ConnectToNetworkTests.kt (92%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/DisableWifiTests.kt (88%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/DisconnectFromCurrentNetworkTests.kt (90%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/EnableWifiTests.kt (88%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/GetCurrentNetworkInfoTest.kt (65%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/GetCurrentNetworkTests.kt (64%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/GetFrequencyTests.kt (82%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main/GetIIPTests.kt => test/java/com/isupatches/wisefy/GetIPTests.kt} (67%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/GetNearbyAccessPointsTests.kt (56%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/GetRSSITests.kt (94%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/GetSavedNetworkTests.kt (88%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/GetSavedNetworksTests.kt (94%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/IsDeviceConnectedToMobileNetworkTests.kt (59%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/IsDeviceConnectedToMobileOrWifiNetworkTests.kt (75%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/IsDeviceConnectedToSSIDTests.kt (69%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/IsDeviceConnectedToWifiNetworkTests.kt (59%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/IsDeviceRoamingTests.kt (56%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/IsNetwork5gHzTests.kt (69%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/IsNetworkEAPTests.kt (69%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/IsNetworkPSKTest.kt (69%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/IsNetworkSavedTests.kt (68%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/IsNetworkSecureTests.kt (81%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/IsNetworkWPA2Test.kt (70%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/IsNetworkWPATests.kt (69%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/IsNetworkWepTests.kt (69%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/IsWifiEnabledTests.kt (65%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/RemoveNetworkTests.kt (92%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/SearchForAccessPointTests.kt (94%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/SearchForAccessPointsTests.kt (94%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/SearchForSSIDTests.kt (88%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/main => test/java/com/isupatches/wisefy}/SearchForSSIDsTests.kt (88%) rename wisefy/src/{androidTest => test}/java/com/isupatches/wisefy/WiseFyPrechecksTests.kt (87%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy/test => test/java/com/isupatches/wisefy}/WiseFyTests.kt (78%) create mode 100644 wisefy/src/test/java/com/isupatches/wisefy/connection/WiseFyConnectionLegacyTests.kt create mode 100644 wisefy/src/test/java/com/isupatches/wisefy/connection/WisefyConnectionSDK23Tests.kt rename wisefy/src/{androidTest/java/com/isupatches/wisefy => test/java/com/isupatches/wisefy/internal}/GeneratorUtil.kt (97%) create mode 100644 wisefy/src/test/java/com/isupatches/wisefy/internal/NetworkCapabilitiesUtil.kt rename wisefy/src/{androidTest/java/com/isupatches/wisefy => test/java/com/isupatches/wisefy/internal}/NullCallbackUtil.kt (96%) create mode 100644 wisefy/src/test/java/com/isupatches/wisefy/internal/ReflectionHelpers.java rename wisefy/src/{androidTest/java/com/isupatches/wisefy => test/java/com/isupatches/wisefy/internal}/VerificationUtil.kt (93%) create mode 100644 wisefy/src/test/java/com/isupatches/wisefy/internal/base/BaseUnitTest.kt rename wisefy/src/{androidTest/java/com/isupatches/wisefy => test/java/com/isupatches/wisefy/internal/mock}/MockNetworkUtil.kt (93%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy => test/java/com/isupatches/wisefy/internal/mock}/MockWiseFyConnectionUtil.kt (60%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy => test/java/com/isupatches/wisefy/internal/mock}/MockWiseFyPrechecksUtil.kt (98%) rename wisefy/src/{androidTest/java/com/isupatches/wisefy => test/java/com/isupatches/wisefy/internal/mock}/MockWiseFySearchUtil.kt (84%) create mode 100644 wisefy/src/test/java/com/isupatches/wisefy/search/AbstractWiseFySearchTests.kt rename wisefy/src/{androidTest/java/com/isupatches/wisefy/WiseFySearchTests.kt => test/java/com/isupatches/wisefy/search/WiseFySearchLegacyTests.kt} (67%) create mode 100644 wisefy/src/test/java/com/isupatches/wisefy/search/WiseFySearchSdk23Tests.kt create mode 100644 wisefysample/.gitignore create mode 100644 wisefysample/build.gradle create mode 100644 wisefysample/proguard-rules.pro create mode 100644 wisefysample/src/main/AndroidManifest.xml create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/MainApplication.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/BaseActivity.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/BaseFragment.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/BaseMvp.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/BasePresenter.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/ViewNotAttachedException.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/di/PermissionsModule.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/di/PreferencesModule.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/di/ScreenBindingsModule.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/models/NetworkType.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/models/SearchType.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/nav/MainRouter.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/AddNetworkStore.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/RemoveNetworkStore.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/SearchStore.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/SharedPreferenceKeys.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/EditTextExtensions.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/HtmlUtil.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/KeyboardUtil.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/PermissionsUtil.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/ToastUtil.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/add/AddNetworkFragment.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/add/AddNetworkModel.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/add/AddNetworkMvp.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/add/AddNetworkPresenter.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/main/MainActivity.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/main/MainFragment.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/misc/MiscFragment.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/misc/MiscModel.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/misc/MiscMvp.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/misc/MiscPresenter.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkFragment.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkModel.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkMvp.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkPresenter.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/search/SearchFragment.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/search/SearchModel.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/search/SearchMvp.kt create mode 100644 wisefysample/src/main/java/com/isupatches/wisefysample/ui/search/SearchPresenter.kt create mode 100644 wisefysample/src/main/res/drawable/button_pressed.xml create mode 100644 wisefysample/src/main/res/drawable/button_selector.xml create mode 100644 wisefysample/src/main/res/drawable/button_unpressed.xml create mode 100644 wisefysample/src/main/res/drawable/ic_add_circle.xml create mode 100644 wisefysample/src/main/res/drawable/ic_apps.xml create mode 100644 wisefysample/src/main/res/drawable/ic_home.xml create mode 100644 wisefysample/src/main/res/drawable/ic_launcher_background.xml create mode 100644 wisefysample/src/main/res/drawable/ic_launcher_foreground.xml create mode 100644 wisefysample/src/main/res/drawable/ic_remove_circle.xml create mode 100644 wisefysample/src/main/res/drawable/ic_search.xml create mode 100644 wisefysample/src/main/res/layout/activity_main.xml create mode 100644 wisefysample/src/main/res/layout/dialog_permission_error.xml create mode 100644 wisefysample/src/main/res/layout/dialog_permission_rationale.xml create mode 100644 wisefysample/src/main/res/layout/fragment_add.xml create mode 100644 wisefysample/src/main/res/layout/fragment_main.xml create mode 100644 wisefysample/src/main/res/layout/fragment_misc.xml create mode 100644 wisefysample/src/main/res/layout/fragment_remove.xml create mode 100644 wisefysample/src/main/res/layout/fragment_search.xml create mode 100644 wisefysample/src/main/res/menu/menu_main.xml create mode 100644 wisefysample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml create mode 100644 wisefysample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml create mode 100644 wisefysample/src/main/res/mipmap-hdpi/ic_launcher.png create mode 100644 wisefysample/src/main/res/mipmap-mdpi/ic_launcher.png create mode 100644 wisefysample/src/main/res/mipmap-xhdpi/ic_launcher.png create mode 100644 wisefysample/src/main/res/mipmap-xxhdpi/ic_launcher.png create mode 100644 wisefysample/src/main/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 wisefysample/src/main/res/values/colors.xml create mode 100644 wisefysample/src/main/res/values/dimens.xml create mode 100644 wisefysample/src/main/res/values/preferences.xml create mode 100644 wisefysample/src/main/res/values/strings.xml create mode 100644 wisefysample/src/main/res/values/styles.xml diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md index e5af5082..d7695c64 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.md +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -6,6 +6,8 @@ about: Create a report to help us improve Thank you for creating an issue to improve this library! Please check Please check [the current issues](https://github.com/isuPatches/WiseFy/issues) to make sure that the improvement isn't already being worked on. +It will be _EXTREMELY_ helpful if you also take a look at the [sample app](/wisefysample) to see how it behalves and if you can reproduce there. + **Description** A clear and concise description of the bug. @@ -27,10 +29,13 @@ A description of what you expected to happen. **Actual behavior** A description of what actually happened -**Android Information** +**Additional Information** - Device (i.e. Nexus 5x): - OS Version (i.e. Android 8.1): -- Rooted: + - Rooted: + - Using legacy connection logic?: + - Using legacy search logic?: + - Reproducible with sample app?: **Logs** Please include logs from WiseFy if at all possible. They can be found with `logging(true)` set on the WiseFy instance and by filtering on 'WiseFy' diff --git a/.gitignore b/.gitignore index 8c2981d9..9e2f1274 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,9 @@ *.iml .gradle /local.properties -/.idea /build -.DS_Store \ No newline at end of file +.DS_Store + +/.idea/*.xml +/.idea/caches/* +/.idea/libraries/* \ No newline at end of file diff --git a/.idea/dictionaries/patches.xml b/.idea/dictionaries/patches.xml new file mode 100644 index 00000000..533095c3 --- /dev/null +++ b/.idea/dictionaries/patches.xml @@ -0,0 +1,12 @@ + + + + inet + isupatches + prechecks + runnables + ssid + wisefy + + + \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index d9565959..a64819e2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,9 +8,6 @@ env: global: - TARGET_SDK=28 - BUILD_TOOLS_VERSION=28.0.3 - matrix: - - EMULATOR_SDK=android-19 ABI=armeabi-v7a - - EMULATOR_SDK=android-22 ABI=armeabi-v7a android: components: @@ -18,20 +15,12 @@ android: - platform-tools - tools - android-${TARGET_SDK} - - android-19 - - android-22 - build-tools-${BUILD_TOOLS_VERSION} + - extra-google-m2repository - extra-android-m2repository -before_script: - - android-update-sdk --components=sys-img-$ABI-$EMULATOR_SDK --accept-licenses='android-sdk-license-[0-9a-f]{8}' - - echo no | android create avd --force -n test -t $EMULATOR_SDK --abi $ABI - - emulator -avd test -no-audio -no-window & - - ./gradlew clean assembleDebug assembleDebugAndroidTest - - android-wait-for-emulator - - adb shell input keyevent 82 & - script: + - ./gradlew clean assembleDebug assembleDebugAndroidTest - travis_wait 60 ./gradlew makeGoodChoices after_success: diff --git a/CHANGE.md b/CHANGE.md index d180b35a..dec0bce3 100644 --- a/CHANGE.md +++ b/CHANGE.md @@ -6,4 +6,6 @@ WiseFy upon each new major release will start a brand new change log. [2.x Changes](/changes/2.x.md) -[3.x Changes](/changes/3.x.md) \ No newline at end of file +[3.x Changes](/changes/3.x.md) + +[3.x Changes](/changes/4.x.md) \ No newline at end of file diff --git a/README.md b/README.md index 9a27de72..867c7462 100644 --- a/README.md +++ b/README.md @@ -3,48 +3,44 @@ Wifi configuration and util library built for Android. >
*Developed by Patches 04/24/2016 - present*
->
Logo/icon created by mansya (2018)
->
Supports Android SDK levels 16-27

+>
Logo/icon created by mansya (2018)
+>
Supports Android SDK levels 16-28

[![Build Status](https://travis-ci.org/isuPatches/WiseFy.svg?branch=master)](https://travis-ci.org/isuPatches/WiseFy) [ ![Download](https://api.bintray.com/packages/isupatches/Maven/wisefy/images/download.svg) ](https://bintray.com/isupatches/Maven/wisefy/_latestVersion) [![codecov](https://codecov.io/gh/isuPatches/WiseFy/branch/3.x/graph/badge.svg)](https://codecov.io/gh/isuPatches/WiseFy) [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-WiseFy-brightgreen.svg?style=flat)](https://android-arsenal.com/details/1/6011) [![Android Weekly](https://img.shields.io/badge/Android%20Weekly-%23230-blue.svg)](http://androidweekly.net/issues/issue-230) -## What's New in 3.x - -- Rewritten in Kotlin - - Static analysis tools added -- Ability to get the IP of a device -- Additional details in callbacks for adding a network: - - The new id of the network - - The WifiConfiguration of the network that was added -- isNetworkInConfigurationList renamed isNetworkSaved -- brains renamed Brains -- Nullability issues will be more visible -- Definitions for NetworkTypes and WiseFyCodes -- Immutability throughout the library -- Improved architecture -- Updated dependencies -- Updated to Gradle 4.x and AGP 3.x -- Target now is set to API 27 -- Less duplicate code -- Improved testing -- Updated documentation with new Kotlin examples -- Other improvements and adjustments! - -## What's New in 2.0.x - -- Asynchronous API - - Certain methods have callbacks and are run on a WiseFy specific background thread -- Ability to search by regex for: - - Nearby access points - - Saved Configurations - - SSIDs -- Ability to query for RSSI -- Ability to query for if the device is roaming -- Additional methods to query for network security -- Full fledged documentation directory -- Tested against Android O +## What's New in 4.x + +- Android P Support + - New isDeviceRoaming logic +- New logic for SDK 23 and above + - WiseFySearch rewritten to remove deprecated APIs from Android OS + - WiseFyConnection rewritten to remove deprecated APIs from Android OS + - Ability to use legacy search logic + - Ability to use legacy connection logic +- Update to Android X +- Improved annotations for required permissions +- Update to gradle 5.x +- Static analysis tools updated +- WEP is now deprecated due to security and other issues with this network type and will be phased out +- Introduction of [RoboElectric](https://github.com/robolectric/robolectric) for better unit testing + - This may be controversial, but please check this [issue](https://github.com/isuPatches/WiseFy/issues/133) for rationale +- Removal of Checkstyle and FindBugs since project is no longer Java +- Removal of GCM support due to GCM being sunset +- New [sample app](/wisefysample) included as part of the repo + - This replaces the previous permissions example +- Crash fixes for: + - Async api with null current network + - Async api with null current network info + - Async api with null nearby access points +- Fix for searching when empty list returned from OS +- More tests +- Removal of some generic variable names from documentation for clarity + +Previous updates: +- [What's New in 3.x](/changes/whatsnew/3.x.md) +- [What's New in 2.x](/changes/whatsnew/2.x.md) ## Adding to your project @@ -125,6 +121,8 @@ _With Java_ WiseFy wisefy = new WiseFy.Brains(getActivity()).logging(true).getSmarts(); ``` +By default, legacy logic is disabled on devices with SDK 23 or higher. If you want to use or test against the legacy search or connection logic, please see: [Using Legacy Classes And Logic](/documentation/using_legacy_classes_and_logic.md). + ## Cleanup Since the Async API of WiseFy is run on a background thread, it is necessary to make sure it is exited and cleanup up properly. @@ -134,7 +132,7 @@ To stop the WiseFy thread and nullify it along with it's handler please call: _With Kotlin_ ```kotlin -wisefy.dump(); +wisefy.dump() ``` _With Java_ @@ -160,14 +158,14 @@ For the sake of transparency and because you're probably curious as to what perm If access points or SSIDs are not being returned on >= 6.x devices but there are visible networks, it's most likely because you haven't asked in your application for the `Manifest.permission.ACCESS_COARSE_LOCATION` permission which is what allows us to see the access points nearby. This permission request will not be added to the WiseFy library to reduce package bloat and so users can determine their own UI/UX. -Please check [the permssions example](/documentation/permissions_example.md) for a sample of how to request permissions for WiseFy. +Please check [the sample app](/wisefysample) for an example of how to request permissions for WiseFy. ## Usage Please check [the documentation markdown directory](/documentation) for usage examples and details about both the synchronous and asynchronous API. ## License ## -Copyright 2018 Patches Klinefelter +Copyright 2019 Patches Klinefelter Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at diff --git a/build.gradle b/build.gradle index f911ad5d..333ddb82 100644 --- a/build.gradle +++ b/build.gradle @@ -2,11 +2,11 @@ buildscript { project.ext { agp_version = '3.4.0' bintray_version = '1.8.4' - cpd_version = '1.3' + cpd_version = '2.0-SNAPSHOT' dokka_version = '0.9.18' dexcount_version = '0.8.5' jacoco_version = '0.8.3' - kotlin_version = "1.3.30" + kotlin_version = "1.3.31" maven_version = '2.1' } @@ -14,6 +14,7 @@ buildscript { jcenter() google() maven { url "https://plugins.gradle.org/m2/" } + maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } } dependencies { @@ -140,7 +141,7 @@ task makeGoodChoices { outputs.upToDateWhen { false } - dependsOn 'staticAnalysisSanityCheck', 'jacocoAllCombinedTests' + dependsOn 'staticAnalysisSanityCheck', ':wisefy:jacocoDebugUnitTest' doLast { println "\n#############################################" + "\n# All checks passed! You are doing so good! #" + diff --git a/changes/4.x.md b/changes/4.x.md new file mode 100644 index 00000000..cf967710 --- /dev/null +++ b/changes/4.x.md @@ -0,0 +1 @@ +## v4.0.0 - 05/x/2019 \ No newline at end of file diff --git a/changes/whatsnew/2.x.md b/changes/whatsnew/2.x.md new file mode 100644 index 00000000..61c75b67 --- /dev/null +++ b/changes/whatsnew/2.x.md @@ -0,0 +1,13 @@ +## What's New in 2.0.x + +- Asynchronous API + - Certain methods have callbacks and are run on a WiseFy specific background thread +- Ability to search by regex for: + - Nearby access points + - Saved Configurations + - SSIDs +- Ability to query for RSSI +- Ability to query for if the device is roaming +- Additional methods to query for network security +- Full fledged documentation directory +- Tested against Android O diff --git a/changes/whatsnew/3.x.md b/changes/whatsnew/3.x.md new file mode 100644 index 00000000..a5ad4109 --- /dev/null +++ b/changes/whatsnew/3.x.md @@ -0,0 +1,21 @@ +## What's New in 3.x + +- Rewritten in Kotlin + - Static analysis tools added +- Ability to get the IP of a device +- Additional details in callbacks for adding a network: + - The new id of the network + - The WifiConfiguration of the network that was added +- isNetworkInConfigurationList renamed isNetworkSaved +- brains renamed Brains +- Nullability issues will be more visible +- Definitions for NetworkTypes and WiseFyCodes +- Immutability throughout the library +- Improved architecture +- Updated dependencies +- Updated to Gradle 4.x and AGP 3.x +- Target now is set to API 27 +- Less duplicate code +- Improved testing +- Updated documentation with new Kotlin examples +- Other improvements and adjustments! diff --git a/config/detekt-config.yml b/config/detekt-config.yml index b1ffb2f4..4fcb6738 100644 --- a/config/detekt-config.yml +++ b/config/detekt-config.yml @@ -61,7 +61,7 @@ complexity: ignoreDefaultParameters: false LongMethod: active: true - threshold: 20 + threshold: 50 LargeClass: active: true threshold: 150 @@ -83,7 +83,7 @@ complexity: threshold: 5 NestedBlockDepth: active: true - threshold: 5 + threshold: 6 TooManyFunctions: active: true thresholdInFiles: 50 diff --git a/documentation/adding_and_removing_networks.md b/documentation/adding_and_removing_networks.md index 0454d896..cbe5cca4 100644 --- a/documentation/adding_and_removing_networks.md +++ b/documentation/adding_and_removing_networks.md @@ -64,11 +64,11 @@ _With Kotlin_ ```kotlin wisefy.addOpenNetwork("Open Network", object: AddNetworkCallbacks { - override fun failureAddingNetwork(wifiManagerReturn: Int) { + override fun networkAdded(newNetworkId: Int, networkConfig: WifiConfiguration) { } - - override fun networkAdded(newNetworkId: Int, networkConfig: WifiConfiguration) { + + override fun failureAddingNetwork(wifiManagerReturn: Int) { } @@ -83,17 +83,17 @@ _With Java_ ```java wisefy.addOpenNetwork("Open Network", new AddNetworkCallbacks() { @Override - public void failureAddingNetwork(int i) { - + public void networkAdded(int newNetworkId, WifiConfiguration wifiConfiguration) { + } - + @Override - public void networkAdded(int i, WifiConfiguration wifiConfiguration) { + public void failureAddingNetwork(int wifiManagerReturn) { } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); @@ -105,12 +105,12 @@ _With Kotlin_ ```Kotlin wisefy.addWEPNetwork("WEP Network", "123456", object: AddNetworkCallbacks { - override fun failureAddingNetwork(wifiManagerReturn: Int) { - - } - override fun networkAdded(newNetworkId: Int, networkConfig: WifiConfiguration) { - + + } + + override fun failureAddingNetwork(wifiManagerReturn: Int) { + } override fun wisefyFailure(wisefyFailureCode: Int) { @@ -124,17 +124,17 @@ _With Java_ ```java wisefy.addWEPNetwork("WEP Network", "123456", new AddNetworkCallbacks() { @Override - public void failureAddingNetwork(int i) { + public void networkAdded(int newNetworkId, WifiConfiguration wifiConfiguration) { } - + @Override - public void networkAdded(int i, WifiConfiguration wifiConfiguration) { + public void failureAddingNetwork(int wifiManagerReturn) { } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); @@ -146,11 +146,11 @@ _With Kotlin_ ```kotlin wisefy.addWPA2Network("WPA2 Network", "12345678", object: AddNetworkCallbacks { - override fun failureAddingNetwork(wifiManagerReturn: Int) { + override fun networkAdded(newNetworkId: Int, networkConfig: WifiConfiguration) { } - - override fun networkAdded(newNetworkId: Int, networkConfig: WifiConfiguration) { + + override fun failureAddingNetwork(wifiManagerReturn: Int) { } @@ -165,17 +165,17 @@ _With Java_ ```java wisefy.addWPA2Network("WPA2 Network", "12345678", new AddNetworkCallbacks() { @Override - public void failureAddingNetwork(int i) { + public void networkAdded(int newNetworkId, WifiConfiguration wifiConfiguration) { } - + @Override - public void networkAdded(int i, WifiConfiguration wifiConfiguration) { + public void failureAddingNetwork(int wifiManagerReturn) { } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); @@ -187,15 +187,15 @@ _With Kotlin_ ```kotlin wisefy.removeNetwork("SSID to remove", object: RemoveNetworkCallbacks { - override fun failureRemovingNetwork() { + override fun networkRemoved() { } - - override fun networkNotFoundToRemove() { + + override fun failureRemovingNetwork() { } - override fun networkRemoved() { + override fun networkNotFoundToRemove() { } @@ -210,22 +210,22 @@ _With Java_ ```java wisefy.removeNetwork("SSID to remove", new RemoveNetworkCallbacks() { @Override - public void failureRemovingNetwork() { + public void networkRemoved() { } - + @Override - public void networkNotFoundToRemove() { + public void failureRemovingNetwork() { } @Override - public void networkRemoved() { + public void networkNotFoundToRemove() { } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); diff --git a/documentation/connecting_and_disconnecting_from_networks.md b/documentation/connecting_and_disconnecting_from_networks.md index c02bce83..96afc747 100644 --- a/documentation/connecting_and_disconnecting_from_networks.md +++ b/documentation/connecting_and_disconnecting_from_networks.md @@ -74,7 +74,7 @@ wisefy.connectToNetwork("SSID to connect to", 3000, new ConnectToNetworkCallback } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); @@ -115,7 +115,7 @@ wisefy.disconnectFromCurrentNetwork(new DisconnectFromCurrentNetworkCallbacks() } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); diff --git a/documentation/current_network.md b/documentation/current_network.md index e23296a7..fbce7d3b 100644 --- a/documentation/current_network.md +++ b/documentation/current_network.md @@ -40,6 +40,10 @@ wisefy.getCurrentNetwork(object: GetCurrentNetworkCallbacks { } + override fun noCurrentNetwork() { + + } + override fun wisefyFailure(wisefyFailureCode: Int) { } @@ -53,10 +57,15 @@ wisefy.getCurrentNetwork(new GetCurrentNetworkCallbacks() { @Override public void retrievedCurrentNetwork(WifiInfo wifiInfo) { + } + + @Override + public void noCurrentNetwork() { + } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); @@ -68,12 +77,17 @@ _With Kotlin_ ```kotlin wisefy.getCurrentNetworkInfo(object: GetCurrentNetworkInfoCallbacks { + override fun retrievedCurrentNetworkInfo(currentNetworkDetails: NetworkInfo) { - + + } + + override fun noCurrentNetworkInfo() { + } override fun wisefyFailure(wisefyFailureCode: Int) { - + } }) ``` @@ -85,10 +99,15 @@ wisefy.getCurrentNetworkInfo(new GetCurrentNetworkInfoCallbacks() { @Override public void retrievedCurrentNetworkInfo(NetworkInfo networkInfo) { + } + + @Override + public void noCurrentNetworkInfo() { + } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); diff --git a/documentation/enabling_and_disabling_wifi.md b/documentation/enabling_and_disabling_wifi.md index 3867d37b..8bfa771a 100644 --- a/documentation/enabling_and_disabling_wifi.md +++ b/documentation/enabling_and_disabling_wifi.md @@ -36,11 +36,11 @@ _With Kotlin_ ```kotlin wisefy.disableWifi(object : DisableWifiCallbacks { - override fun failureDisablingWifi() { + override fun wifiDisabled() { } - - override fun wifiDisabled() { + + override fun failureDisablingWifi() { } @@ -55,17 +55,17 @@ _With Java_ ```java wisefy.disableWifi(new DisableWifiCallbacks() { @Override - public void failureDisablingWifi() { - + public void wifiDisabled() { + } - + @Override - public void wifiDisabled() { + public void failureDisablingWifi() { } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); @@ -77,11 +77,11 @@ _With Kotlin_ ```kotlin wisefy.enableWifi(object: EnableWifiCallbacks { - override fun failureEnablingWifi() { + override fun wifiEnabled() { } - - override fun wifiEnabled() { + + override fun failureEnablingWifi() { } @@ -95,17 +95,17 @@ _With Java_ ```java wisefy.enableWifi(new EnableWifiCallbacks() { @Override - public void failureEnablingWifi() { - + public void wifiEnabled() { + } - + @Override - public void wifiEnabled() { + public void failureEnablingWifi() { } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); diff --git a/documentation/frequency.md b/documentation/frequency.md index b2d59d65..2209d4b4 100644 --- a/documentation/frequency.md +++ b/documentation/frequency.md @@ -69,12 +69,12 @@ _With Kotlin_ ```kotlin wisefy.getFrequency(object: GetFrequencyCallbacks { - override fun failureGettingFrequency() { - - } - override fun retrievedFrequency(frequency: Int) { + } + + override fun failureGettingFrequency() { + } override fun wisefyFailure(wisefyFailureCode: Int) { @@ -88,17 +88,17 @@ _With Java_ ```java wisefy.getFrequency(new GetFrequencyCallbacks() { @Override - public void failureGettingFrequency() { + public void retrievedFrequency(int frequency) { } - + @Override - public void retrievedFrequency(int i) { - + public void failureGettingFrequency() { + } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); @@ -111,12 +111,12 @@ _With Kotlin_ ```kotlin wisefy.getFrequency(wifiInfo, object: GetFrequencyCallbacks { - override fun failureGettingFrequency() { - - } - override fun retrievedFrequency(frequency: Int) { + } + + override fun failureGettingFrequency() { + } override fun wisefyFailure(wisefyFailureCode: Int) { @@ -130,17 +130,17 @@ _With Java_ ```java wisefy.getFrequency(wifiInfo, new GetFrequencyCallbacks() { @Override - public void failureGettingFrequency() { + public void retrievedFrequency(int frequency) { } - + @Override - public void retrievedFrequency(int i) { - + public void failureGettingFrequency() { + } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); diff --git a/documentation/ip.md b/documentation/ip.md index 1f10dd45..94bd9f4d 100644 --- a/documentation/ip.md +++ b/documentation/ip.md @@ -22,14 +22,14 @@ _With Kotlin_ ```kotlin wisefy.getIP(object: GetIPCallbacks { - override fun failureRetrievingIP() { - - } - override fun retrievedIP(ip: String) { } + + override fun failureRetrievingIP() { + } + override fun wisefyFailure(wisefyFailureCode: Int) { } @@ -41,17 +41,17 @@ _With Java_ ```java wisefy.getIP(new GetIPCallbacks() { @Override - public void failureRetrievingIP() { + public void retrievedIP(String ip) { } @Override - public void retrievedIP(String s) { + public void failureRetrievingIP() { } - + @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); diff --git a/documentation/nearby_access_points.md b/documentation/nearby_access_points.md index ad21e12d..80c3d1a0 100644 --- a/documentation/nearby_access_points.md +++ b/documentation/nearby_access_points.md @@ -86,6 +86,10 @@ wisefy.getNearbyAccessPoints(true, object: GetNearbyAccessPointsCallbacks { } + override fun noAccessPointsFound() { + + } + override fun wisefyFailure(wisefyFailureCode: Int) { } @@ -99,6 +103,11 @@ wisefy.getNearbyAccessPoints(true, new GetNearbyAccessPointsCallbacks() { @Override public void retrievedNearbyAccessPoints(List accessPoints) { + } + + @Override + public void noAccessPointsFound() { + } @Override @@ -134,7 +143,7 @@ _With Java_ ```java wisefy.searchForAccessPoint("regex for SSID", 3000, true, new SearchForAccessPointCallbacks() { @Override - public void accessPointFound(ScanResult scanResult) { + public void accessPointFound(ScanResult accessPoint) { } @@ -144,7 +153,7 @@ wisefy.searchForAccessPoint("regex for SSID", 3000, true, new SearchForAccessPoi } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); @@ -186,7 +195,7 @@ wisefy.searchForAccessPoints("regex for SSID", true, new SearchForAccessPointsCa } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); @@ -217,7 +226,7 @@ _With Java_ ```java wisefy.searchForSSID("regex for SSID", 3000, new SearchForSSIDCallbacks() { @Override - public void ssidFound(String s) { + public void ssidFound(String ssid) { } @@ -227,7 +236,7 @@ wisefy.searchForSSID("regex for SSID", 3000, new SearchForSSIDCallbacks() { } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); @@ -239,11 +248,11 @@ _With Kotlin_ ```kotlin wisefy.searchForSSIDs("regex for SSID", object: SearchForSSIDsCallbacks { - override fun noSSIDsFound() { + override fun retrievedSSIDs(ssids: List) { } - - override fun retrievedSSIDs(ssids: List) { + + override fun noSSIDsFound() { } @@ -258,7 +267,7 @@ _With Java_ ```java wisefy.searchForSSIDs("regex for SSID", new SearchForSSIDsCallbacks() { @Override - public void retrievedSSIDs(List list) { + public void retrievedSSIDs(List ssids) { } @@ -268,7 +277,7 @@ wisefy.searchForSSIDs("regex for SSID", new SearchForSSIDsCallbacks() { } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); diff --git a/documentation/permissions_example.md b/documentation/permissions_example.md deleted file mode 100644 index 3ab6c73e..00000000 --- a/documentation/permissions_example.md +++ /dev/null @@ -1,302 +0,0 @@ -The `ACCESS_COARSE_LOCATION` location permission is necessary to query for nearby access points. - -First we define the permissions in the manifest: - -```xml - - - - - - -``` - -Then on the activity using WiseFy then we can start asking for permissions and handling the permission callbacks. - -_With Kotlin_ - -```kotlin -package com.isupatches.wisefysample.ui.main - -import android.Manifest.permission.ACCESS_COARSE_LOCATION -import android.content.pm.PackageManager -import android.net.wifi.ScanResult -import android.os.Bundle -import android.util.Log -import androidx.core.content.ContextCompat -import androidx.appcompat.app.AppCompatActivity - -import com.isupatches.wisefy.WiseFy -import com.isupatches.wisefy.callbacks.GetNearbyAccessPointsCallbacks -import com.isupatches.wisefysample.R -import com.isupatches.wisefysample.util.PermissionUtil - -class MainActivity : AppCompatActivity() { - - companion object { - private val TAG = MainActivity::class.java.simpleName - } - - private lateinit var wisefy: WiseFy - - private val permissionUtil = PermissionUtil.getInstance() - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - - wisefy = WiseFy.Brains(this).logging(true).getSmarts() - - if (checkForPermissions()) { - getNearbyAccessPoints() - } - } - - override fun onDestroy() { - super.onDestroy() - wisefy.dump() - } - - private fun checkForPermissions(): Boolean { - return isPermissionGranted(ACCESS_COARSE_LOCATION, WISEFY_PERMISSION_REQUEST_CODE) - } - - private fun isPermissionGranted(permission: String, requestCode: Int): Boolean { - return if (permissionUtil.permissionNotGranted(this, permission)) { - if (permissionUtil.shouldShowPermissionRationale(this, permission)) { - // Display dialog or rationale for requesting permission here - } else { - permissionUtil.requestPermissions(this, arrayOf(permission), requestCode) - } - false - } else { - true - } - } - - override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { - when (requestCode) { - WISEFY_PERMISSION_REQUEST_CODE -> { - if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - Log.d(TAG, "WiseFy permissions granted") - // Continue WiseFy logic here - } else { - Log.e(TAG, "Access course location permission denied") - // Display permission error here - } - } else -> { - // Display permission error here - Log.wtf(TAG, "Weird permission requested, not handled") - } - } - } - - @Throws(SecurityException::class) - private fun getNearbyAccessPoints() { - wisefy.getNearbyAccessPoints(true, object : GetNearbyAccessPointsCallbacks { - override fun wisefyFailure(wisefyFailureCode: Int) { - // failure logic goes here - } - - override fun retrievedNearbyAccessPoints(accessPoints: List) { - // You should see this populate with results after approving the - // the ACCESS_COARSE_LOCATION permission - Log.d(TAG, "List: $nearbyAccessPoints") - } - }) - } -} -``` - -_With Java_ - -```java -package wisefy_sample.isupatches.com.wisefysample.ui; - -import android.content.pm.PackageManager; -import android.net.wifi.ScanResult; -import android.os.Bundle; -import android.util.Log; -import androidx.annotation.NonNull; -import androidx.appcompat.app.AppCompatActivity; - -import com.isupatches.wisefy.WiseFy; -import com.isupatches.wisefy.callbacks.GetNearbyAccessPointsCallbacks; - -import java.util.List; - -import wisefy_sample.isupatches.com.wisefysample.R; -import wisefy_sample.isupatches.com.wisefysample.constants.Permissions; -import wisefy_sample.isupatches.com.wisefysample.util.PermissionUtil; -import static android.Manifest.permission.ACCESS_COARSE_LOCATION; - - -public class MainActivity extends AppCompatActivity { - - private static final String TAG = MainActivity.class.getSimpleName(); - - private WiseFy wisefy; - - private PermissionUtil permissionUtil = PermissionUtil.getInstance(); - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - wisefy = new WiseFy.Brains(this).logging(true).getSmarts(); - - if (checkForPermissions()) { - getNearbyAccessPoints(); - } - } - - @Override - protected void onDestroy() { - super.onDestroy(); - wisefy.dump(); - } - - private boolean checkForPermissions() { - return isPermissionGranted(ACCESS_COARSE_LOCATION, R.string.access_course_location_permission_rationale, Permissions.ACCESS_COARSE_LOCATION_RESULT_CODE); - } - - public boolean isPermissionGranted(String permission, int rationaleResId, int requestCode) { - if (permissionUtil.permissionNotGranted(this, permission)) { - if (permissionUtil.shouldShowPermissionRationale(this, permission)) { - // Display dialog or rationale for requesting permission here - } else { - permissionUtil.requestPermissions(this, new String[]{permission}, requestCode); - } - return false; - } else { - return true; - } - } - - @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { - switch (requestCode) { - case Permissions.WISEFY_PERMISSION_REQUEST_CODE: - if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - Log.d(TAG, "Wisefy permissions granted"); - // Continue WiseFy logic here - } else { - Log.e(TAG, "Access course location permission denied"); - // Display permission error here - } - break; - default: - Log.wtf(TAG, "Weird permission requested, not handled"); - // Display permission error here - break; - } - } - - private void getNearbyAccessPoints() throws SecurityException { - wisefy.getNearbyAccessPoints(true, new GetNearbyAccessPointsCallbacks() { - @Override - public void retrievedNearbyAccessPoints(List accessPoints) { - // You should see this populate with results after approving the - // the ACCESS_COARSE_LOCATION permission - Log.d(TAG, "List: " + list.toString()); - } - - @Override - public void wisefyFailure(int wisefyFailureCode) { - - } - }); - } -} -``` - -In this example, PermissionUtil is just an abstracted, shared piece of logic: - -_With Kotlin_ - -```kotlin -package com.isupatches.wisefysample.util - -import android.app.Activity -import android.content.pm.PackageManager -import androidx.appcompat.app.AppCompatActivity -import androidx.core.content.ContextCompat - -class PermissionUtil private constructor() { - - companion object { - private val INSTANCE: PermissionUtil = PermissionUtil() - - fun getInstance(): PermissionUtil = INSTANCE - } - - fun permissionNotGranted(activity: Activity, permission: String): Boolean { - return ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED - } - - fun shouldShowPermissionRationale(activity: Activity, permission: String): Boolean = - ActivityCompat.shouldShowRequestPermissionRationale(activity, permission) - - - fun requestPermissions(activity: Activity, permissions: Array, requestCode: Int) { - ActivityCompat.requestPermissions(activity, permissions, requestCode) - } -} -``` - -_With Java_ - -```java -package wisefy_sample.isupatches.com.wisefysample.util; - -import android.app.Activity; -import android.content.pm.PackageManager; -import androidx.appcompat.app.AppCompatActivity; -import androidx.core.content.ContextCompat; - -public class PermissionUtil { - - private static final PermissionUtil PERMISSION_UTIL = new PermissionUtil(); - - private PermissionUtil() { - - } - - public static PermissionUtil getInstance() { - return PERMISSION_UTIL; - } - - public boolean permissionNotGranted(Activity activity, String permission) { - return ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED; - } - - public boolean shouldShowPermissionRationale(Activity activity, String permission) { - return ActivityCompat.shouldShowRequestPermissionRationale(activity, permission); - } - - public void requestPermissions(Activity activity, String[] permissions, int requestCode) { - ActivityCompat.requestPermissions(activity, permissions, requestCode); - } -} -``` - -And there is a class for storing constants for permission checks: - -_With Kotlin_ - -``` -package wisefy_sample.isupatches.com.wisefysample.constants; - -internal const val WISEFY_PERMISSION_REQUEST_CODE = 1 -``` - -_With Java_ - -```java -package wisefy_sample.isupatches.com.wisefysample.constants; - -public class Permissions { - public static final int WISEFY_PERMISSION_REQUEST_CODE = 1; -} -``` \ No newline at end of file diff --git a/documentation/rssi.md b/documentation/rssi.md index ab9e9828..1ae595c4 100644 --- a/documentation/rssi.md +++ b/documentation/rssi.md @@ -51,12 +51,12 @@ _With Kotlin_ ```kotlin wisefy.getRSSI("regex for SSID", true, 3000, object: GetRSSICallbacks{ - override fun networkNotFoundToRetrieveRSSI() { - - } - override fun retrievedRSSI(rssi: Int) { + } + + override fun networkNotFoundToRetrieveRSSI() { + } override fun wisefyFailure(wisefyFailureCode: Int) { @@ -70,7 +70,7 @@ _With Java_ ```java wisefy.getRSSI("regex for SSID", true, 3000, new GetRSSICallbacks() { @Override - public void retrievedRSSI(int i) { + public void retrievedRSSI(int rssi) { } @@ -80,7 +80,7 @@ wisefy.getRSSI("regex for SSID", true, 3000, new GetRSSICallbacks() { } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); diff --git a/documentation/saved_networks.md b/documentation/saved_networks.md index 1737a606..541380de 100644 --- a/documentation/saved_networks.md +++ b/documentation/saved_networks.md @@ -83,17 +83,17 @@ _With Java_ ```java wisefy.getSavedNetwork("regex for SSID", new GetSavedNetworkCallbacks() { @Override - public void savedNetworkNotFound() { - + public void retrievedSavedNetwork(WifiConfiguration savedNetwork) { + } - + @Override - public void retrievedSavedNetwork(WifiConfiguration wifiConfiguration) { + public void savedNetworkNotFound() { } @Override - public void wisefyFailure(int i) { + public void wisefyFailure(int wisefyFailureCode) { } }); @@ -105,14 +105,14 @@ _With Kotlin_ ```kotlin wisefy.getSavedNetworks(object: GetSavedNetworksCallbacks { - override fun noSavedNetworksFound() { + override fun retrievedSavedNetworks(savedNetworks: List) { } - override fun retrievedSavedNetworks(savedNetworks: List) { + override fun noSavedNetworksFound() { } - + override fun wisefyFailure(wisefyFailureCode: Int) { } @@ -124,12 +124,12 @@ _With Java_ ```java wisefy.getSavedNetworks(new GetSavedNetworksCallbacks() { @Override - public void noSavedNetworksFound() { - + public void retrievedSavedNetworks(List savedNetworks) { + } - + @Override - public void retrievedSavedNetworks(List savedNetworks) { + public void noSavedNetworksFound() { } @@ -146,11 +146,11 @@ _With Kotlin_ ```kotlin wisefy.getSavedNetworks("regex for SSID", object: GetSavedNetworksCallbacks { - override fun noSavedNetworksFound() { + override fun retrievedSavedNetworks(savedNetworks: List) { } - override fun retrievedSavedNetworks(savedNetworks: List) { + override fun noSavedNetworksFound() { } @@ -165,15 +165,15 @@ _With Java_ ```java wisefy.getSavedNetworks("regex for SSID", new GetSavedNetworksCallbacks() { @Override - public void noSavedNetworksFound() { + public void retrievedSavedNetworks(List savedNetworks) { } @Override - public void retrievedSavedNetworks(List savedNetworks) { + public void noSavedNetworksFound() { } - + @Override public void wisefyFailure(int wisefyFailureCode) { diff --git a/documentation/using_legacy_classes_and_logic.md b/documentation/using_legacy_classes_and_logic.md new file mode 100644 index 00000000..aa2adf98 --- /dev/null +++ b/documentation/using_legacy_classes_and_logic.md @@ -0,0 +1,41 @@ +To grab an instance with legacy connection enabled: + +_With Kotlin_ + +```kotlin +wiseFy = WiseFy.Brains(activity!!, useLegacyConnection = true, useLegacySearch = false).getSmarts() +``` + +_With Java_ + +```java +WiseFy wisefy = new WiseFy.Brains(getActivity(), true, false).getSmarts(); +``` + +To grab an instance with legacy search enabled: + +_With Kotlin_ + +```kotlin +wiseFy = WiseFy.Brains(activity!!, useLegacyConnection = false, useLegacySearch = true).getSmarts() +``` + +_With Java_ + +```java +WiseFy wisefy = new WiseFy.Brains(getActivity(), false, true).getSmarts(); +``` + +To grab an instance with both legacy search and legacy connection enabled: + +_With Kotlin_ + +```kotlin +wiseFy = WiseFy.Brains(activity!!, useLegacyConnection = true, useLegacySearch = true).getSmarts() +``` + +_With Java_ + +```java +WiseFy wisefy = new WiseFy.Brains(getActivity(), true, true).getSmarts(); +``` \ No newline at end of file diff --git a/gradle/cpd.gradle b/gradle/cpd.gradle index ca60d758..70c94a35 100644 --- a/gradle/cpd.gradle +++ b/gradle/cpd.gradle @@ -1,8 +1,8 @@ apply plugin: 'cpd' cpd { - language = 'java' - toolVersion = '6.8.0' + language = 'kotlin' + toolVersion = '6.13.0' } cpdCheck { diff --git a/gradle/custom-tasks.gradle b/gradle/custom-tasks.gradle deleted file mode 100644 index a97f0669..00000000 --- a/gradle/custom-tasks.gradle +++ /dev/null @@ -1,26 +0,0 @@ -task makeGoodChoices { - group = "verification" - - outputs.upToDateWhen { false } - - dependsOn 'pmd', 'lintDebug', 'cpdCheck', 'checkstyle', 'jacocoDebugTestReport' - doLast { - println "\n#############################################" + - "\n# All checks passed! You are doing so good! #" + - "\n# You may now push the awesome to origin :) #" + - "\n#############################################" - } -} - -task staticAnalysisSanityCheck { - group = "verification" - - outputs.upToDateWhen { false } - - dependsOn 'pmd', 'lintDebug', 'cpdCheck', 'checkstyle' - doLast { - println "\n##################################################" + - "\n# Static analysis passed! You are doing so good! #" + - "\n##################################################" - } -} diff --git a/gradle/jacoco.gradle b/gradle/jacoco.gradle index e05f6f65..3c754027 100644 --- a/gradle/jacoco.gradle +++ b/gradle/jacoco.gradle @@ -39,7 +39,7 @@ project.afterEvaluate { ])) reports { - xml.enabled = false + xml.enabled = true // Enabled for CodeCov html.enabled = true } } @@ -112,7 +112,7 @@ project.afterEvaluate { ])) reports { - xml.enabled = true // Enabled for CodeCov + xml.enabled = false html.enabled = true } } diff --git a/gradle/static-analysis.gradle b/gradle/static-analysis.gradle index 05679452..e13c87db 100644 --- a/gradle/static-analysis.gradle +++ b/gradle/static-analysis.gradle @@ -3,7 +3,7 @@ task staticAnalysisSanityCheck { outputs.upToDateWhen { false } - dependsOn 'checkAll', 'lintAll' + dependsOn 'ktlintAll', 'detektAll', 'cpdAll', 'pmdAll', 'lintAll' doLast { println "\n##################################################" + "\n# Static analysis passed! You are doing so good! #" + @@ -11,15 +11,46 @@ task staticAnalysisSanityCheck { } } -task checkAll() { +task ktlintAll { group = 'verification' - outputs.upToDateWhen { false } + dependsOn ':wisefy:ktlintCheck' + doLast { + println "\n##################################################" + + "\n# KTLinted all the things! Go you! #" + + "\n##################################################" + } +} + +task detektAll { + group = 'verification' + + dependsOn ':wisefy:detekt' + doLast { + println "\n##################################################" + + "\n# No issues Detekt'ed :badjoke: #" + + "\n##################################################" + } +} + +task cpdAll { + group = 'verification' + + dependsOn ':wisefy:cpdCheck' + doLast { + println "\n##################################################" + + "\n# Code so DRY, it must have an umbrella! #" + + "\n##################################################" + } +} + +task pmdAll { + group = 'verification' - dependsOn ':wisefy:check' + dependsOn ':wisefy:pmd' doLast { println "\n##################################################" + - "\n# Checked all the things! Go you! #" + + "\n# PMD'ed all the things! Oooohh yea!! #" + "\n##################################################" } } diff --git a/gradle/versions.gradle b/gradle/versions.gradle index 5cc1fc15..b2e44042 100644 --- a/gradle/versions.gradle +++ b/gradle/versions.gradle @@ -1,11 +1,25 @@ ext { + androidx_appcompat_version = "1.1.0-alpha04" + androidx_constraintlayout_version = "2.0.0-alpha5" androidx_support_annotations_version = '1.0.0' - androidx_espresso_core_version = '3.1.0' - androidx_test_runner_version = "1.1.0" + androidx_core_ktx_version = '1.0.1' + androidx_core_test_version = '1.1.0' + + google_android_material_version = "1.1.0-alpha06" + + dagger_version = "2.22.1" detekt_version = "1.0.0-RC14" ktlint_version = "0.31.0" + rxandroid_version = '2.1.1' + rxjava_version = '2.2.7' + + // Test deps junit_version = '4.12' mockito_version = '2.27.0' + robo_electric_version = '4.2.1' + + androidx_espresso_core_version = '3.1.0' + androidx_test_runner_version = "1.1.0" } \ No newline at end of file diff --git a/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-current-network-callbacks/index.html b/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-current-network-callbacks/index.html index ceac2150..052f2d87 100644 --- a/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-current-network-callbacks/index.html +++ b/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-current-network-callbacks/index.html @@ -23,6 +23,15 @@

Functions

+

noCurrentNetwork

+ + +abstract fun noCurrentNetwork(): Unit +

Called when the Android OS returns no current network.

+ + + +

retrievedCurrentNetwork

diff --git a/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-current-network-callbacks/no-current-network.html b/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-current-network-callbacks/no-current-network.html new file mode 100644 index 00000000..3e8db520 --- /dev/null +++ b/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-current-network-callbacks/no-current-network.html @@ -0,0 +1,19 @@ + + + +GetCurrentNetworkCallbacks.noCurrentNetwork - wisefy + + + +wisefy / com.isupatches.wisefy.callbacks / GetCurrentNetworkCallbacks / noCurrentNetwork
+
+

noCurrentNetwork

+ +abstract fun noCurrentNetwork(): Unit +

Called when the Android OS returns no current network.

+

Author
+Patches

+

Since
+4.0

+ + diff --git a/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-current-network-info-callbacks/index.html b/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-current-network-info-callbacks/index.html index 511bb114..681065c8 100644 --- a/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-current-network-info-callbacks/index.html +++ b/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-current-network-info-callbacks/index.html @@ -23,6 +23,15 @@

Functions

+

noCurrentNetworkInfo

+ + +abstract fun noCurrentNetworkInfo(): Unit +

Called when the Android OS returns no current network info.

+ + + +

retrievedCurrentNetworkInfo

diff --git a/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-current-network-info-callbacks/no-current-network-info.html b/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-current-network-info-callbacks/no-current-network-info.html new file mode 100644 index 00000000..fc08dc8a --- /dev/null +++ b/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-current-network-info-callbacks/no-current-network-info.html @@ -0,0 +1,19 @@ + + + +GetCurrentNetworkInfoCallbacks.noCurrentNetworkInfo - wisefy + + + +wisefy / com.isupatches.wisefy.callbacks / GetCurrentNetworkInfoCallbacks / noCurrentNetworkInfo
+
+

noCurrentNetworkInfo

+ +abstract fun noCurrentNetworkInfo(): Unit +

Called when the Android OS returns no current network info.

+

Author
+Patches

+

Since
+4.0

+ + diff --git a/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-nearby-access-points-callbacks/index.html b/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-nearby-access-points-callbacks/index.html index 6f6040a5..e1f8cd41 100644 --- a/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-nearby-access-points-callbacks/index.html +++ b/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-nearby-access-points-callbacks/index.html @@ -23,6 +23,15 @@

Functions

+

noAccessPointsFound

+ + +abstract fun noAccessPointsFound(): Unit +

Called when the Android OS returns no access points.

+ + + +

retrievedNearbyAccessPoints

diff --git a/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-nearby-access-points-callbacks/no-access-points-found.html b/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-nearby-access-points-callbacks/no-access-points-found.html new file mode 100644 index 00000000..fd442055 --- /dev/null +++ b/javadoc/wisefy/com.isupatches.wisefy.callbacks/-get-nearby-access-points-callbacks/no-access-points-found.html @@ -0,0 +1,19 @@ + + + +GetNearbyAccessPointsCallbacks.noAccessPointsFound - wisefy + + + +wisefy / com.isupatches.wisefy.callbacks / GetNearbyAccessPointsCallbacks / noAccessPointsFound
+
+

noAccessPointsFound

+ +abstract fun noAccessPointsFound(): Unit +

Called when the Android OS returns no access points.

+

Author
+Patches

+

Since
+4.0

+ + diff --git a/javadoc/wisefy/com.isupatches.wisefy.reciever/-wise-fy-receiver/-init-.html b/javadoc/wisefy/com.isupatches.wisefy.reciever/-wise-fy-receiver/-init-.html new file mode 100644 index 00000000..b4fc78e4 --- /dev/null +++ b/javadoc/wisefy/com.isupatches.wisefy.reciever/-wise-fy-receiver/-init-.html @@ -0,0 +1,14 @@ + + + +WiseFyReceiver.<init> - wisefy + + + +wisefy / com.isupatches.wisefy.reciever / WiseFyReceiver / <init>
+
+

<init>

+ +WiseFyReceiver() + + diff --git a/javadoc/wisefy/com.isupatches.wisefy.reciever/-wise-fy-receiver/index.html b/javadoc/wisefy/com.isupatches.wisefy.reciever/-wise-fy-receiver/index.html new file mode 100644 index 00000000..95c8a785 --- /dev/null +++ b/javadoc/wisefy/com.isupatches.wisefy.reciever/-wise-fy-receiver/index.html @@ -0,0 +1,37 @@ + + + +WiseFyReceiver - wisefy + + + +wisefy / com.isupatches.wisefy.reciever / WiseFyReceiver
+
+

WiseFyReceiver

+class WiseFyReceiver : BroadcastReceiver +

Constructors

+ + + + + + + +
+

<init>

+
+WiseFyReceiver()
+

Functions

+ + + + + + + +
+

onReceive

+
+fun onReceive(context: Context?, intent: Intent?): Unit
+ + diff --git a/javadoc/wisefy/com.isupatches.wisefy.reciever/-wise-fy-receiver/on-receive.html b/javadoc/wisefy/com.isupatches.wisefy.reciever/-wise-fy-receiver/on-receive.html new file mode 100644 index 00000000..2de22f0b --- /dev/null +++ b/javadoc/wisefy/com.isupatches.wisefy.reciever/-wise-fy-receiver/on-receive.html @@ -0,0 +1,14 @@ + + + +WiseFyReceiver.onReceive - wisefy + + + +wisefy / com.isupatches.wisefy.reciever / WiseFyReceiver / onReceive
+
+

onReceive

+ +fun onReceive(context: Context?, intent: Intent?): Unit + + diff --git a/javadoc/wisefy/com.isupatches.wisefy.reciever/index.html b/javadoc/wisefy/com.isupatches.wisefy.reciever/index.html new file mode 100644 index 00000000..2a37983a --- /dev/null +++ b/javadoc/wisefy/com.isupatches.wisefy.reciever/index.html @@ -0,0 +1,24 @@ + + + +com.isupatches.wisefy.reciever - wisefy + + + +wisefy / com.isupatches.wisefy.reciever
+
+

Package com.isupatches.wisefy.reciever

+

Types

+ + + + + + + +
+

WiseFyReceiver

+
+class WiseFyReceiver : BroadcastReceiver
+ + diff --git a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/-brains/-init-.html b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/-brains/-init-.html index 375322c2..aee7285f 100644 --- a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/-brains/-init-.html +++ b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/-brains/-init-.html @@ -8,9 +8,19 @@ wisefy / com.isupatches.wisefy / WiseFy / Brains / <init>

<init>

- -Brains(context: Context) + +Brains(context: Context, useLegacyConnection: Boolean = false, useLegacySearch: Boolean = false)

The Builder class for WiseFy.

+

Updates

+
  • +

    05/12/2019

    +
    • Branched wisefyConnection based off of if device is pre or post SDK23
    • +
    • Branched wisefySearch based off of if device is pre or post SDK23
    • +
    • Added useLegacyConnection
    • +
    • Added useLegacySearch
    • +
    +
  • +

Author
Patches

Since
diff --git a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/-brains/get-smarts.html b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/-brains/get-smarts.html index 1653a1e9..0c5f8cbe 100644 --- a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/-brains/get-smarts.html +++ b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/-brains/get-smarts.html @@ -13,6 +13,7 @@

getSmarts

Uses a private constructor and returns a WiseFy instance.

See Also

WiseFyLogger.configureWiseFyLoggerImplementation

+

WiseFyConnection.init

Author
Patches

diff --git a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/-brains/index.html b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/-brains/index.html index e6cb1ee0..0564ccf6 100644 --- a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/-brains/index.html +++ b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/-brains/index.html @@ -10,6 +10,16 @@

Brains

class Brains

The Builder class for WiseFy.

+

Updates

+
  • +

    05/12/2019

    +
    • Branched wisefyConnection based off of if device is pre or post SDK23
    • +
    • Branched wisefySearch based off of if device is pre or post SDK23
    • +
    • Added useLegacyConnection
    • +
    • Added useLegacySearch
    • +
    +
  • +

Author
Patches

Since
@@ -22,7 +32,7 @@

Constructors

<init>

-Brains(context: Context) +Brains(context: Context, useLegacyConnection: Boolean = false, useLegacySearch: Boolean = false)

The Builder class for WiseFy.

@@ -45,7 +55,7 @@

Functions

logging

-fun logging(loggingEnabled: Boolean): Brains +fun logging(loggingEnabled: Boolean): WiseFy.Brains

Used to enable/or disable logging for a WiseFy instance.

diff --git a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/-brains/logging.html b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/-brains/logging.html index ea6a9ea1..87bebc69 100644 --- a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/-brains/logging.html +++ b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/-brains/logging.html @@ -9,7 +9,7 @@

logging

-fun logging(loggingEnabled: Boolean): Brains +fun logging(loggingEnabled: Boolean): WiseFy.Brains

Used to enable/or disable logging for a WiseFy instance.

Parameters

diff --git a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/add-w-e-p-network.html b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/add-w-e-p-network.html index 5a43be82..6c187aa4 100644 --- a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/add-w-e-p-network.html +++ b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/add-w-e-p-network.html @@ -9,7 +9,9 @@

addWEPNetwork

-@Sync @CallingThread fun addWEPNetwork(ssid: String?, password: String?): Int +@Sync @CallingThread fun addWEPNetwork(ssid: String?, password: String?): Int
+Deprecated: Due to security and performance limitations, WEP networks are discouraged
+

To add a WEP network to the user's configured network list.

Parameters

@@ -28,7 +30,9 @@

Parameters

Since
3.0

-@Async @WiseFyThread fun addWEPNetwork(ssid: String?, password: String?, callbacks: AddNetworkCallbacks?): Unit +@Async @WiseFyThread fun addWEPNetwork(ssid: String?, password: String?, callbacks: AddNetworkCallbacks?): Unit
+Deprecated: Due to security and performance limitations, WEP networks are discouraged
+

To add a WEP network to the user's configured network list.

Parameters

@@ -38,12 +42,11 @@

Parameters

callbacks - The listener to return results to

See Also
-

addNetworkConfiguration

+

addNetworkWithPasswordAsync

AddNetworkCallbacks

generateWEPNetworkConfiguration

runOnWiseFyThread

WiseFyLock

-

WiseFyPrechecks.addNetworkPrechecks

Author
Patches

diff --git a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/add-w-p-a2-network.html b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/add-w-p-a2-network.html index e4fa4af6..d83f5a02 100644 --- a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/add-w-p-a2-network.html +++ b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/add-w-p-a2-network.html @@ -38,12 +38,11 @@

Parameters

callbacks - The listener to return results to

See Also
-

addNetworkConfiguration

+

addNetworkWithPasswordAsync

AddNetworkCallbacks

generateWPA2NetworkConfiguration

runOnWiseFyThread

WiseFyLock

-

WiseFyPrechecks.addNetworkPrechecks

Author
Patches

diff --git a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/dump.html b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/dump.html index 3a24708e..fda023a8 100644 --- a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/dump.html +++ b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/dump.html @@ -12,6 +12,7 @@

dump

fun dump(): Unit

Used to cleanup the thread started by WiseFy.

See Also
+

WiseFyConnection.destroy

WiseFyHandlerThread

WiseFyLock

diff --git a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/get-nearby-access-points.html b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/get-nearby-access-points.html index ab810e11..51e0b195 100644 --- a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/get-nearby-access-points.html +++ b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/get-nearby-access-points.html @@ -23,10 +23,8 @@

Exceptions

List of ScanResults|null - List of nearby access points

See Also

ScanResult

-

WifiManager.getScanResults

-

WifiManager.startScan

+

WiseFySearch.getNearbyAccessPoints

WiseFyPrechecks.getNearbyAccessPointsChecks

-

WiseFySearch.removeEntriesWithLowerSignalStrength

Author
Patches

@@ -44,11 +42,9 @@

Parameters

See Also

GetNearbyAccessPointsCallbacks

runOnWiseFyThread

-

WifiManager.getScanResults

-

WifiManager.startScan

+

WiseFySearch.getNearbyAccessPoints

WiseFyLock

WiseFyPrechecks.getNearbyAccessPointsChecks

-

WiseFySearch.removeEntriesWithLowerSignalStrength

Author
Patches

diff --git a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/index.html b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/index.html index f57ab59a..636d2d66 100644 --- a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/index.html +++ b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/index.html @@ -47,8 +47,8 @@

Functions

addWEPNetwork

-fun addWEPNetwork(ssid: String?, password: String?): Int
-fun addWEPNetwork(ssid: String?, password: String?, callbacks: AddNetworkCallbacks?): Unit +fun addWEPNetwork(ssid: String?, password: String?): Int
+fun addWEPNetwork(ssid: String?, password: String?, callbacks: AddNetworkCallbacks?): Unit

To add a WEP network to the user's configured network list.

diff --git a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/is-device-connected-to-mobile-network.html b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/is-device-connected-to-mobile-network.html index d07262df..8ef1537a 100644 --- a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/is-device-connected-to-mobile-network.html +++ b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/is-device-connected-to-mobile-network.html @@ -14,9 +14,7 @@

isDeviceConnectedToMobileNetwork

Return
bool - If the device is currently connected to a mobile network

See Also
-

ConnectivityManager.getActiveNetworkInfo

-

MOBILE

-

WiseFyConnection.isNetworkConnectedAndMatchesType

+

WiseFyConnection.isDeviceConnectedToMobileNetwork

WiseFyPrechecks.isDeviceConnectedToMobileNetworkChecks

Author
diff --git a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/is-device-connected-to-mobile-or-wifi-network.html b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/is-device-connected-to-mobile-or-wifi-network.html index a6a9f06d..2ad8fca0 100644 --- a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/is-device-connected-to-mobile-or-wifi-network.html +++ b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/is-device-connected-to-mobile-or-wifi-network.html @@ -14,7 +14,6 @@

isDeviceConnectedToMobileOrWifiNetwork

Return
bool - If the device is currently connected to a mobile or wifi network

See Also
-

ConnectivityManager.getActiveNetworkInfo

WiseFyConnection.isNetworkConnected

WiseFyPrechecks.isDeviceConnectedToMobileOrWifiNetworkChecks

diff --git a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/is-device-connected-to-wifi-network.html b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/is-device-connected-to-wifi-network.html index 8e094daa..ec3a609c 100644 --- a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/is-device-connected-to-wifi-network.html +++ b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/is-device-connected-to-wifi-network.html @@ -15,8 +15,7 @@

isDeviceConnectedToWifiNetwork

bool - If the device is currently connected to a wifi network

See Also

ConnectivityManager.getActiveNetworkInfo

-

WIFI

-

WiseFyConnection.isNetworkConnectedAndMatchesType

+

WiseFyConnection.isDeviceConnectedToWifiNetwork

WiseFyPrechecks.isDeviceConnectedToWifiNetworkChecks

Author
diff --git a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/is-device-roaming.html b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/is-device-roaming.html index 7b31a4b7..4ab9bc25 100644 --- a/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/is-device-roaming.html +++ b/javadoc/wisefy/com.isupatches.wisefy/-wise-fy/is-device-roaming.html @@ -14,8 +14,7 @@

isDeviceRoaming

Return
boolean - If the current network is roaming

See Also
-

ConnectivityManager.getActiveNetworkInfo

-

NetworkInfo.isRoaming

+

WiseFyConnection.isDeviceRoaming

WiseFyPrechecks.isDeviceRoamingChecks

Author
diff --git a/javadoc/wisefy/index-outline.html b/javadoc/wisefy/index-outline.html index 06a43201..72a44890 100644 --- a/javadoc/wisefy/index-outline.html +++ b/javadoc/wisefy/index-outline.html @@ -5,7 +5,7 @@ -wisefy
+wisefy

    @@ -14,7 +14,7 @@ -alltypes
    +alltypes
    -package com.isupatches.wisefy
    +package com.isupatches.wisefy
    -package com.isupatches.wisefy.callbacks
    +package com.isupatches.wisefy.callbacks
    -package com.isupatches.wisefy.constants
    +package com.isupatches.wisefy.constants
    -package com.isupatches.wisefy.threads
    +package com.isupatches.wisefy.threads
      @@ -890,7 +896,7 @@ -class WiseFyHandlerThread : HandlerThread
      +class WiseFyHandlerThread : HandlerThread
      diff --git a/settings.gradle b/settings.gradle index 7eba3cbb..4a68c9f5 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1 +1 @@ -include ':wisefy' +include ':wisefy', ':wisefysample' diff --git a/wisefy/build.gradle b/wisefy/build.gradle index 011717c3..e8787e3a 100644 --- a/wisefy/build.gradle +++ b/wisefy/build.gradle @@ -59,7 +59,18 @@ android { } testOptions { - unitTests.returnDefaultValues = true + unitTests { + returnDefaultValues = true + /* + * includeAndroidResources and all block were added for RoboElectric + */ + includeAndroidResources = true + all { + jacoco { + includeNoLocationClasses = true + } + } + } } sourceSets { @@ -80,11 +91,8 @@ dependencies { // Kotlin implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" - androidTestImplementation "androidx.test.espresso:espresso-core:$androidx_espresso_core_version" - androidTestImplementation "androidx.test:runner:$androidx_test_runner_version" - androidTestImplementation "org.mockito:mockito-core:$mockito_version" - androidTestImplementation "org.mockito:mockito-android:$mockito_version" - + testImplementation "org.robolectric:robolectric:$robo_electric_version" + testImplementation "androidx.test:core:$androidx_core_test_version" testImplementation "org.mockito:mockito-core:$mockito_version" testImplementation "junit:junit:$junit_version" } diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/BaseAndroidJUnit4TestClass.kt b/wisefy/src/androidTest/java/com/isupatches/wisefy/BaseAndroidJUnit4TestClass.kt deleted file mode 100644 index 2e9a93ff..00000000 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/BaseAndroidJUnit4TestClass.kt +++ /dev/null @@ -1,82 +0,0 @@ -package com.isupatches.wisefy - -import android.net.ConnectivityManager -import android.net.wifi.WifiManager -import android.os.Build -import androidx.test.platform.app.InstrumentationRegistry -import org.junit.After -import org.mockito.Mockito -import org.mockito.Mockito.mock - -/** - * A common test class to extend. - * - * @author Patches - */ -internal open class BaseAndroidJUnit4TestClass { - - protected val wisefy: WiseFy - protected val mockWiseFySearch: WiseFySearch - - protected val mockConnectivityManager: ConnectivityManager - protected val mockWifiManager: WifiManager - - protected val mockNetworkUtil: MockNetworkUtil - protected val mockWiseFyConnectionUtil: MockWiseFyConnectionUtil - protected val mockWiseFyPrechecksUtil: MockWiseFyPrechecksUtil - protected val mockWiseFySearchUtil: MockWiseFySearchUtil - - protected val nullCallbackUtil: NullCallbackUtil - - protected val verificationUtil: VerificationUtil - - /** - * Constructor. - */ - init { - val mockWiseFyConnection = mock(WiseFyConnection::class.java) - val mockWiseFyPrechecks = mock(WiseFyPrechecks::class.java) - mockWiseFySearch = mock(WiseFySearch::class.java) - - mockWifiManager = mock(WifiManager::class.java) - mockConnectivityManager = mock(ConnectivityManager::class.java) - - wisefy = WiseFy.Brains(InstrumentationRegistry.getInstrumentation().targetContext) - .customConnectivityManager(mockConnectivityManager) - .customWifiManager(mockWifiManager) - .customWiseFyConnection(mockWiseFyConnection) - .customWiseFyPrechecks(mockWiseFyPrechecks) - .customWiseFySearch(mockWiseFySearch) - .logging(true) - .getSmarts() - - mockNetworkUtil = MockNetworkUtil(mockConnectivityManager, mockWifiManager) - - mockWiseFyConnectionUtil = MockWiseFyConnectionUtil(mockWiseFyConnection) - mockWiseFyPrechecksUtil = MockWiseFyPrechecksUtil(mockWiseFyPrechecks) - mockWiseFySearchUtil = MockWiseFySearchUtil(mockWiseFySearch) - - nullCallbackUtil = NullCallbackUtil(wisefy) - - verificationUtil = VerificationUtil(mockConnectivityManager, mockWifiManager) - } - - @After fun tearDown() { - wisefy.dump() - } - - /* - * HELPERS - */ - - /** - * Checks to see if the device has Lollipop or higher. - * - * @return boolean - True if device is at least Lollipop - * - * @see Build.VERSION_CODES - */ - protected fun preLollipop(): Boolean = Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP - - protected fun any(type: Class): T = Mockito.any(type) -} diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/WiseFyConnectionTests.kt b/wisefy/src/androidTest/java/com/isupatches/wisefy/WiseFyConnectionTests.kt deleted file mode 100644 index 7d79dae0..00000000 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/WiseFyConnectionTests.kt +++ /dev/null @@ -1,190 +0,0 @@ -package com.isupatches.wisefy - -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue - -import org.junit.Before -import org.junit.Test - -/** - * Used to test the WiseFyConnection class and functionality determining various connection states. - * - * @author Patches - */ -internal class WiseFyConnectionTests : BaseAndroidJUnit4TestClass() { - - private lateinit var wisefyConnection: WiseFyConnection - - @Before fun setUp() { - wisefyConnection = WiseFyConnectionImpl.create(mockConnectivityManager, mockWifiManager) - } - - /* - * isCurrentNetworkConnectedToSSID tests - */ - - @Test fun isCurrentNetworkConnectedToSSID_failure_nullSSIDParam() { - assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(null)) - } - - @Test fun isCurrentNetworkConnectedToSSID_failure_nullConnectionInfo() { - mockNetworkUtil.currentNetwork_null() - assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) - } - - @Test fun isCurrentNetworkConnectedToSSID_failure_nullSSID() { - mockNetworkUtil.currentNetwork(null) - mockNetworkUtil.currentNetworkConnectionStatus(true, true, null) - assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) - } - - @Test fun isCurrentNetworkConnectedToSSID_failure_differentSSID() { - mockNetworkUtil.currentNetwork(TEST_SSID2) - mockNetworkUtil.currentNetworkConnectionStatus(true, true, null) - assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) - } - - @Test fun isCurrentNetworkConnectedToSSID_failure_notAvailable() { - mockNetworkUtil.currentNetwork(TEST_SSID) - mockNetworkUtil.currentNetworkConnectionStatus(false, true, null) - assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) - } - - @Test fun isCurrentNetworkConnectedToSSID_failure_notAvailableOrConnected() { - mockNetworkUtil.currentNetwork(TEST_SSID) - mockNetworkUtil.currentNetworkConnectionStatus(false, false, null) - assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) - } - - @Test fun isCurrentNetworkConnectedToSSID_failure_notConnected() { - mockNetworkUtil.currentNetwork(TEST_SSID) - mockNetworkUtil.currentNetworkConnectionStatus(true, false, null) - assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) - } - - @Test fun isCurrentNetworkConnectedToSSID_success() { - mockNetworkUtil.currentNetwork(TEST_SSID) - mockNetworkUtil.currentNetworkConnectionStatus(true, true, null) - assertTrue(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) - } - - /* - * isNetworkConnected tests - */ - - @Test fun isNetworkConnected_failure_nullNetworkInfoParam() { - assertFalse(wisefyConnection.isNetworkConnected(null)) - } - - @Test fun isNetworkConnected_failure_notAvailable() { - val networkInfo = mockNetworkUtil.currentNetworkConnectionStatus(false, true, null) - assertFalse(wisefyConnection.isNetworkConnected(networkInfo)) - } - - @Test fun isNetworkConnected_failure_notAvailableOrConnected() { - val networkInfo = mockNetworkUtil.currentNetworkConnectionStatus(false, false, null) - assertFalse(wisefyConnection.isNetworkConnected(networkInfo)) - } - - @Test fun isNetworkConnected_failure_notConnected() { - val networkInfo = mockNetworkUtil.currentNetworkConnectionStatus(true, false, null) - assertFalse(wisefyConnection.isNetworkConnected(networkInfo)) - } - - @Test fun isNetworkConnected_success() { - val networkInfo = mockNetworkUtil.currentNetworkConnectionStatus(true, true, null) - assertTrue(wisefyConnection.isNetworkConnected(networkInfo)) - } - - /* - * isNetworkConnectedAndMatchesType tests - */ - - @Test fun isNetworkConnectedAndMatchesType_failure_nullNetworkInfo() { - assertFalse(wisefyConnection.isNetworkConnectedAndMatchesType(null, TEST_TYPE1)) - } - - @Test fun isNetworkConnectedAndMatchesType_failure_notAvailable() { - mockNetworkUtil.currentNetwork(TEST_SSID) - val networkInfo = mockNetworkUtil.currentNetworkConnectionStatus(false, true, TEST_TYPE1) - assertFalse(wisefyConnection.isNetworkConnectedAndMatchesType(networkInfo, TEST_TYPE1)) - } - - @Test fun isNetworkConnectedAndMatchesType_failure_notAvailableOrConnected() { - mockNetworkUtil.currentNetwork(TEST_SSID) - val networkInfo = mockNetworkUtil.currentNetworkConnectionStatus(false, false, TEST_TYPE1) - assertFalse(wisefyConnection.isNetworkConnectedAndMatchesType(networkInfo, TEST_TYPE1)) - } - - @Test fun isNetworkConnectedAndMatchesType_failure_notConnected() { - mockNetworkUtil.currentNetwork(TEST_SSID) - val networkInfo = mockNetworkUtil.currentNetworkConnectionStatus(true, false, TEST_TYPE1) - assertFalse(wisefyConnection.isNetworkConnectedAndMatchesType(networkInfo, TEST_TYPE1)) - } - - @Test fun isNetworkConnectedAndMatchesType_failure_nullTypeName() { - mockNetworkUtil.currentNetwork(TEST_SSID) - val networkInfo = mockNetworkUtil.currentNetworkConnectionStatus(true, true, null) - assertFalse(wisefyConnection.isNetworkConnectedAndMatchesType(networkInfo, TEST_TYPE1)) - } - - @Test fun isNetworkConnectedAndMatchesType_failure_differentTypeName() { - mockNetworkUtil.currentNetwork(TEST_SSID) - val networkInfo = mockNetworkUtil.currentNetworkConnectionStatus(true, true, TEST_TYPE2) - assertFalse(wisefyConnection.isNetworkConnectedAndMatchesType(networkInfo, TEST_TYPE1)) - } - - @Test fun isNetworkConnectedAndMatchesType_success() { - mockNetworkUtil.currentNetwork(TEST_SSID) - val networkInfo = mockNetworkUtil.currentNetworkConnectionStatus(true, true, TEST_TYPE1) - assertTrue(wisefyConnection.isNetworkConnectedAndMatchesType(networkInfo, TEST_TYPE1)) - } - - /* - * waitToConnectToSSID tests - */ - - @Test fun waitToConnectToSSID_failure_nullSSIDParam() { - assertFalse(wisefyConnection.waitToConnectToSSID(null, TEST_TIMEOUT)) - } - - @Test fun waitToConnectToSSID_failure_nullConnectionInfo() { - mockNetworkUtil.currentNetwork_null() - assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) - } - - @Test fun waitToConnectToSSID_failure_nullSSID() { - mockNetworkUtil.currentNetwork(null) - assertFalse(wisefyConnection.waitToConnectToSSID(null, TEST_TIMEOUT)) - } - - @Test fun waitToConnectToSSID_failure_differentSSID() { - mockNetworkUtil.currentNetworkConnectionStatus(true, true, TEST_TYPE1) - mockNetworkUtil.currentNetwork(TEST_SSID2) - assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) - } - - @Test fun waitToConnectToSSID_failure_notAvailable() { - mockNetworkUtil.currentNetworkConnectionStatus(false, true, TEST_TYPE1) - mockNetworkUtil.currentNetwork(TEST_SSID) - assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) - } - - @Test fun waitToConnectToSSID_failure_notAvailableOrConnected() { - mockNetworkUtil.currentNetworkConnectionStatus(false, false, TEST_TYPE1) - mockNetworkUtil.currentNetwork(TEST_SSID) - assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) - } - - @Test fun waitToConnectToSSID_failure_notConnected() { - mockNetworkUtil.currentNetworkConnectionStatus(true, false, TEST_TYPE1) - mockNetworkUtil.currentNetwork(TEST_SSID) - assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) - } - - @Test fun waitToConnectToSSID_success() { - mockNetworkUtil.currentNetworkConnectionStatus(true, true, TEST_TYPE1) - mockNetworkUtil.currentNetwork(TEST_SSID) - assertTrue(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) - } -} diff --git a/wisefy/src/main/java/com/isupatches/wisefy/WiseFy.kt b/wisefy/src/main/java/com/isupatches/wisefy/WiseFy.kt index 8d3a6c30..6e58a7af 100644 --- a/wisefy/src/main/java/com/isupatches/wisefy/WiseFy.kt +++ b/wisefy/src/main/java/com/isupatches/wisefy/WiseFy.kt @@ -1,5 +1,5 @@ /* - * Copyright 2018 Patches Klinefelter + * Copyright 2019 Patches Klinefelter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,10 @@ import android.net.wifi.WifiInfo import android.net.wifi.WifiManager import android.os.Build import android.os.Handler +import android.os.Looper import androidx.annotation.RequiresApi import androidx.annotation.RequiresPermission +import androidx.annotation.VisibleForTesting import com.isupatches.wisefy.annotations.Async import com.isupatches.wisefy.annotations.CallingThread @@ -56,16 +58,20 @@ import com.isupatches.wisefy.callbacks.SearchForAccessPointCallbacks import com.isupatches.wisefy.callbacks.SearchForAccessPointsCallbacks import com.isupatches.wisefy.callbacks.SearchForSSIDCallbacks import com.isupatches.wisefy.callbacks.SearchForSSIDsCallbacks +import com.isupatches.wisefy.connection.WiseFyConnection +import com.isupatches.wisefy.connection.WiseFyConnectionLegacy +import com.isupatches.wisefy.connection.WiseFyConnectionSDK23 import com.isupatches.wisefy.constants.Capability import com.isupatches.wisefy.constants.EAP import com.isupatches.wisefy.constants.MISSING_PARAMETER -import com.isupatches.wisefy.constants.MOBILE import com.isupatches.wisefy.constants.PSK import com.isupatches.wisefy.constants.WEP -import com.isupatches.wisefy.constants.WIFI import com.isupatches.wisefy.constants.WPA import com.isupatches.wisefy.constants.WPA2 import com.isupatches.wisefy.logging.WiseFyLogger +import com.isupatches.wisefy.search.WiseFySearch +import com.isupatches.wisefy.search.WiseFySearchLegacy +import com.isupatches.wisefy.search.WiseFySearchSDK23 import com.isupatches.wisefy.threads.WiseFyHandlerThread import com.isupatches.wisefy.utils.generateOpenNetworkConfiguration import com.isupatches.wisefy.utils.generateWEPNetworkConfiguration @@ -85,7 +91,7 @@ import java.net.UnknownHostException * @since 3.0 */ @PublicAPI -@Suppress("LargeClass, SyntheticAccessor") +@Suppress("LargeClass", "SyntheticAccessor") class WiseFy private constructor( private val connectivityManager: ConnectivityManager, private val wifiManager: WifiManager, @@ -132,10 +138,21 @@ class WiseFy private constructor( /** * The Builder class for WiseFy. * + * Updates + * - 05/12/2019 + * * Branched wisefyConnection based off of if device is pre or post SDK23 + * * Branched wisefySearch based off of if device is pre or post SDK23 + * * Added useLegacyConnection + * * Added useLegacySearch + * * @author Patches * @since 3.0 */ - class Brains(context: Context) { + class Brains @JvmOverloads constructor( + context: Context, + useLegacyConnection: Boolean = false, + useLegacySearch: Boolean = false + ) { private var loggingEnabled: Boolean = false private var connectivityManager: ConnectivityManager @@ -147,8 +164,23 @@ class WiseFy private constructor( init { connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager - wisefyConnection = WiseFyConnectionImpl.create(connectivityManager, wifiManager) - wisefySearch = WiseFySearchImpl.create(wifiManager) + + // We'll use SDK 23 logic for WiseFyConnection if client is on at least an SDK 23 device + // and "useLegacyConnection" option is not enabled + + wisefyConnection = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || useLegacyConnection) { + WiseFyConnectionLegacy.create(connectivityManager, wifiManager) + } else { + WiseFyConnectionSDK23.create(connectivityManager, wifiManager) + } + // We'll use SDK 23 logic for WiseFySearch if client is on at least an SDK 23 device + // and "useLegacySearch" option is not enabled + wisefySearch = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || useLegacySearch) { + WiseFySearchLegacy.create(wifiManager) + } else { + WiseFySearchSDK23.create(wifiManager) + } + wisefyPrechecks = WiseFyPrechecksImpl.create(wisefySearch) } @@ -160,7 +192,9 @@ class WiseFy private constructor( * @author Patches * @since 3.0 */ - fun logging(loggingEnabled: Boolean): Brains = apply { this.loggingEnabled = loggingEnabled } + fun logging(loggingEnabled: Boolean): Brains = apply { + this.loggingEnabled = loggingEnabled + } /** * Used internally to set ConnectivityManager in tests. @@ -236,12 +270,17 @@ class WiseFy private constructor( * Uses a private constructor and returns a WiseFy instance. * * @see [WiseFyLogger.configureWiseFyLoggerImplementation] + * @see [WiseFyConnection.init] + * + * Updates + * - 05/12/2019: Added new call to [WiseFyConnection.init] * * @author Patches * @since 3.0 */ fun getSmarts(): WiseFy { WiseFyLogger.configureWiseFyLoggerImplementation(loggingEnabled) + wisefyConnection.init() return WiseFy( connectivityManager = connectivityManager, wifiManager = wifiManager, @@ -333,6 +372,8 @@ class WiseFy private constructor( @Sync @CallingThread @RequiresPermission(ACCESS_WIFI_STATE) + @Deprecated("Due to security and performance limitations, WEP networks are discouraged") + @Suppress("deprecation") override fun addWEPNetwork(ssid: String?, password: String?): Int { val precheck = wisefyPrechecks.addNetworkPrechecks(ssid, password) return if (precheck.failed()) { @@ -347,12 +388,14 @@ class WiseFy private constructor( * @param password The password for the WEP network being added * @param callbacks The listener to return results to * - * @see [addNetworkConfiguration] + * @see [addNetworkWithPasswordAsync] * @see [AddNetworkCallbacks] * @see [generateWEPNetworkConfiguration] * @see [runOnWiseFyThread] * @see [WiseFyLock] - * @see [WiseFyPrechecks.addNetworkPrechecks] + * + * Updates + * - 05/12/2019: Abstracted logic for adding network into addNetworkWithPasswordAsync * * @author Patches * @since 3.0 @@ -360,22 +403,17 @@ class WiseFy private constructor( @Async @WiseFyThread @RequiresPermission(ACCESS_WIFI_STATE) + @Deprecated("Due to security and performance limitations, WEP networks are discouraged") + @Suppress("deprecation") override fun addWEPNetwork(ssid: String?, password: String?, callbacks: AddNetworkCallbacks?) { runOnWiseFyThread(Runnable { synchronized(wisefyLock) { - val precheck = wisefyPrechecks.addNetworkPrechecks(ssid, password) - if (precheck.failed()) { - callbacks?.wisefyFailure(precheck.code) - return@Runnable - } - - val wepNetworkConfiguration = generateWEPNetworkConfiguration(ssid!!, password!!) - val result = addNetworkConfiguration(wepNetworkConfiguration) - if (result != WIFI_MANAGER_FAILURE) { - callbacks?.networkAdded(result, wepNetworkConfiguration) - } else { - callbacks?.failureAddingNetwork(result) - } + addNetworkWithPasswordAsync( + ssid = ssid, + password = password, + wifiConfigurationProvider = { generateWEPNetworkConfiguration(ssid!!, password!!) }, + callbacks = callbacks + ) } }) } @@ -412,12 +450,14 @@ class WiseFy private constructor( * @param password The password for the WPA2 network being added * @param callbacks The listener to return results to * - * @see [addNetworkConfiguration] + * @see [addNetworkWithPasswordAsync] * @see [AddNetworkCallbacks] * @see [generateWPA2NetworkConfiguration] * @see [runOnWiseFyThread] * @see [WiseFyLock] - * @see [WiseFyPrechecks.addNetworkPrechecks] + * + * Updates + * - 05/12/2019: Abstracted logic for adding network into addNetworkWithPasswordAsync * * @author Patches * @since 3.0 @@ -428,19 +468,12 @@ class WiseFy private constructor( override fun addWPA2Network(ssid: String?, password: String?, callbacks: AddNetworkCallbacks?) { runOnWiseFyThread(Runnable { synchronized(wisefyLock) { - val precheck = wisefyPrechecks.addNetworkPrechecks(ssid, password) - if (precheck.failed()) { - callbacks?.wisefyFailure(precheck.code) - return@Runnable - } - - val wpa2NetworkConfiguration = generateWPA2NetworkConfiguration(ssid!!, password!!) - val result = addNetworkConfiguration(wpa2NetworkConfiguration) - if (result != WIFI_MANAGER_FAILURE) { - callbacks?.networkAdded(result, wpa2NetworkConfiguration) - } else { - callbacks?.failureAddingNetwork(result) - } + addNetworkWithPasswordAsync( + ssid = ssid, + password = password, + wifiConfigurationProvider = { generateWPA2NetworkConfiguration(ssid!!, password!!) }, + callbacks = callbacks + ) } }) } @@ -680,9 +713,13 @@ class WiseFy private constructor( /** * Used to cleanup the thread started by WiseFy. * + * @see [WiseFyConnection.destroy] * @see WiseFyHandlerThread * @see WiseFyLock * + * Updates + * - 05/12/2019: Added new call to [WiseFyConnection.destroy] + * * @author Patches * @since 3.0 */ @@ -711,6 +748,7 @@ class WiseFy private constructor( wisefyHandlerThread = null } wisefyHandler = null + wisefyConnection.destroy() WiseFyLogger.debug(TAG, "Cleaned up WiseFy Thread") } @@ -782,7 +820,7 @@ class WiseFy private constructor( */ @Sync @CallingThread - @RequiresPermission(allOf = arrayOf(ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE)) + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) @Throws(SecurityException::class) override fun getCurrentNetwork(): WifiInfo? { return if (wisefyPrechecks.getCurrentNetworkChecks().passed()) { @@ -804,12 +842,15 @@ class WiseFy private constructor( * @see [WiseFyLock] * @see [WiseFyPrechecks.getCurrentNetworkChecks] * + * Updates + * - 05/12/2019: Added noCurrentNetwork callback + * * @author Patches * @since 3.0 */ @Async @WiseFyThread - @RequiresPermission(allOf = arrayOf(ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE)) + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) override fun getCurrentNetwork(callbacks: GetCurrentNetworkCallbacks?) { runOnWiseFyThread(Runnable { synchronized(wisefyLock) { @@ -819,7 +860,12 @@ class WiseFy private constructor( return@Runnable } - callbacks?.retrievedCurrentNetwork(wifiManager.connectionInfo) + val currentNetwork: WifiInfo? = wifiManager.connectionInfo + if (currentNetwork != null) { + callbacks?.retrievedCurrentNetwork(currentNetwork) + } else { + callbacks?.noCurrentNetwork() + } } }) } @@ -857,6 +903,9 @@ class WiseFy private constructor( * @see [WiseFyLock] * @see [WiseFyPrechecks.getCurrentNetworkInfoChecks] * + * Updates + * - 05/12/2019: Added noCurrentNetworkInfo callback + * * @author Patches * @since 3.0 */ @@ -872,7 +921,12 @@ class WiseFy private constructor( return@Runnable } - callbacks?.retrievedCurrentNetworkInfo(connectivityManager.activeNetworkInfo) + val currentNetworkInfo: NetworkInfo? = connectivityManager.activeNetworkInfo + if (currentNetworkInfo != null) { + callbacks?.retrievedCurrentNetworkInfo(currentNetworkInfo) + } else { + callbacks?.noCurrentNetworkInfo() + } } }) } @@ -893,7 +947,7 @@ class WiseFy private constructor( @Sync @CallingThread @RequiresApi(Build.VERSION_CODES.LOLLIPOP) - @RequiresPermission(allOf = arrayOf(ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE)) + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) @Throws(SecurityException::class) override fun getFrequency(): Int? { val currentNetwork = getCurrentNetwork() @@ -919,7 +973,7 @@ class WiseFy private constructor( @Async @WiseFyThread @RequiresApi(Build.VERSION_CODES.LOLLIPOP) - @RequiresPermission(allOf = arrayOf(ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE)) + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) @Throws(SecurityException::class) override fun getFrequency(callbacks: GetFrequencyCallbacks?) { runOnWiseFyThread(Runnable { @@ -1028,7 +1082,7 @@ class WiseFy private constructor( */ @Async @WiseFyThread - @RequiresPermission(ACCESS_WIFI_STATE) + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) override fun getIP(callbacks: GetIPCallbacks?) { runOnWiseFyThread(Runnable { synchronized(wisefyLock) { @@ -1062,29 +1116,25 @@ class WiseFy private constructor( * @throws SecurityException Without necessary permissions granted * * @see [ScanResult] - * @see [WifiManager.getScanResults] - * @see [WifiManager.startScan] + * @see [WiseFySearch.getNearbyAccessPoints] * @see [WiseFyPrechecks.getNearbyAccessPointsChecks] - * @see [WiseFySearch.removeEntriesWithLowerSignalStrength] + * + * Updates + * - 05/12/2019: Added call to new getNearbyAccessPoints * * @author Patches * @since 3.0 */ @Sync @CallingThread - @RequiresPermission(allOf = arrayOf(ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE)) + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) @Throws(SecurityException::class) override fun getNearbyAccessPoints(filterDuplicates: Boolean): List? { if (wisefyPrechecks.getNearbyAccessPointsChecks().failed()) { return null } - wifiManager.startScan() - return if (filterDuplicates) { - wisefySearch.removeEntriesWithLowerSignalStrength(wifiManager.scanResults) - } else { - wifiManager.scanResults - } + return wisefySearch.getNearbyAccessPoints(filterDuplicates) } /** @@ -1097,18 +1147,21 @@ class WiseFy private constructor( * * @see [GetNearbyAccessPointsCallbacks] * @see [runOnWiseFyThread] - * @see [WifiManager.getScanResults] - * @see [WifiManager.startScan] + * @see [WiseFySearch.getNearbyAccessPoints] * @see [WiseFyLock] * @see [WiseFyPrechecks.getNearbyAccessPointsChecks] - * @see [WiseFySearch.removeEntriesWithLowerSignalStrength] + * + * Updates + * - 05/12/2019 + * * Added call to new getNearbyAccessPoints + * * Added noAccessPointsFound callback * * @author Patches * @since 3.0 */ @Async @WiseFyThread - @RequiresPermission(allOf = arrayOf(ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE)) + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) override fun getNearbyAccessPoints(filterDuplicates: Boolean, callbacks: GetNearbyAccessPointsCallbacks?) { runOnWiseFyThread(Runnable { synchronized(wisefyLock) { @@ -1118,13 +1171,11 @@ class WiseFy private constructor( return@Runnable } - wifiManager.startScan() - if (filterDuplicates) { - callbacks?.retrievedNearbyAccessPoints( - wisefySearch.removeEntriesWithLowerSignalStrength(wifiManager.scanResults) - ) + val nearbyAccessPoints = wisefySearch.getNearbyAccessPoints(filterDuplicates) + if (nearbyAccessPoints != null) { + callbacks?.retrievedNearbyAccessPoints(nearbyAccessPoints) } else { - callbacks?.retrievedNearbyAccessPoints(wifiManager.scanResults) + callbacks?.noAccessPointsFound() } } }) @@ -1318,7 +1369,7 @@ class WiseFy private constructor( } val savedNetworks = wifiManager.configuredNetworks - if (savedNetworks != null && !savedNetworks.isEmpty()) { + if (savedNetworks != null && savedNetworks.isNotEmpty()) { callbacks?.retrievedSavedNetworks(savedNetworks) } else { callbacks?.noSavedNetworksFound() @@ -1379,7 +1430,7 @@ class WiseFy private constructor( } val savedNetworks = wisefySearch.findSavedNetworksMatchingRegex(regexForSSID!!) - if (savedNetworks != null && !savedNetworks.isEmpty()) { + if (savedNetworks != null && savedNetworks.isNotEmpty()) { callbacks?.retrievedSavedNetworks(savedNetworks) } else { callbacks?.noSavedNetworksFound() @@ -1405,11 +1456,12 @@ class WiseFy private constructor( * * @return bool - If the device is currently connected to a mobile network * - * @see [ConnectivityManager.getActiveNetworkInfo] - * @see [MOBILE] - * @see [WiseFyConnection.isNetworkConnectedAndMatchesType] + * @see [WiseFyConnection.isDeviceConnectedToMobileNetwork] * @see [WiseFyPrechecks.isDeviceConnectedToMobileNetworkChecks] * + * Updates + * - 05/12/2019: Started using isDeviceConnectedToMobileNetwork + * * @author Patches * @since 3.0 */ @@ -1418,14 +1470,13 @@ class WiseFy private constructor( @RequiresPermission(ACCESS_NETWORK_STATE) override fun isDeviceConnectedToMobileNetwork(): Boolean = wisefyPrechecks.isDeviceConnectedToMobileNetworkChecks().passed() && - wisefyConnection.isNetworkConnectedAndMatchesType(connectivityManager.activeNetworkInfo, MOBILE) + wisefyConnection.isDeviceConnectedToMobileNetwork() /** * To check if the device is connected to a mobile or wifi network. * * @return bool - If the device is currently connected to a mobile or wifi network * - * @see [ConnectivityManager.getActiveNetworkInfo] * @see [WiseFyConnection.isNetworkConnected] * @see [WiseFyPrechecks.isDeviceConnectedToMobileOrWifiNetworkChecks] * @@ -1437,7 +1488,7 @@ class WiseFy private constructor( @RequiresPermission(ACCESS_NETWORK_STATE) override fun isDeviceConnectedToMobileOrWifiNetwork(): Boolean = wisefyPrechecks.isDeviceConnectedToMobileOrWifiNetworkChecks().passed() && - wisefyConnection.isNetworkConnected(connectivityManager.activeNetworkInfo) + wisefyConnection.isNetworkConnected() /** * To check if the device is connected to a given SSID. @@ -1454,7 +1505,7 @@ class WiseFy private constructor( */ @Sync @CallingThread - @RequiresPermission(allOf = arrayOf(ACCESS_NETWORK_STATE, ACCESS_WIFI_STATE)) + @RequiresPermission(allOf = [ACCESS_NETWORK_STATE, ACCESS_WIFI_STATE]) override fun isDeviceConnectedToSSID(ssid: String?): Boolean = wisefyPrechecks.isDeviceConnectedToSSIDChecks(ssid).passed() && wisefyConnection.isCurrentNetworkConnectedToSSID(ssid) @@ -1465,10 +1516,12 @@ class WiseFy private constructor( * @return bool - If the device is currently connected to a wifi network * * @see [ConnectivityManager.getActiveNetworkInfo] - * @see [WIFI] - * @see [WiseFyConnection.isNetworkConnectedAndMatchesType] + * @see [WiseFyConnection.isDeviceConnectedToWifiNetwork] * @see [WiseFyPrechecks.isDeviceConnectedToWifiNetworkChecks] * + * Updates + * - 05/12/2019: Started using isDeviceConnectedToWifiNetwork + * * @author Patches * @since 3.0 */ @@ -1477,17 +1530,19 @@ class WiseFy private constructor( @RequiresPermission(ACCESS_NETWORK_STATE) override fun isDeviceConnectedToWifiNetwork(): Boolean = wisefyPrechecks.isDeviceConnectedToWifiNetworkChecks().passed() && - wisefyConnection.isNetworkConnectedAndMatchesType(connectivityManager.activeNetworkInfo, WIFI) + wisefyConnection.isDeviceConnectedToWifiNetwork() /** * To query if the device is roaming. * * @return boolean - If the current network is roaming * - * @see [ConnectivityManager.getActiveNetworkInfo] - * @see [NetworkInfo.isRoaming] + * @see [WiseFyConnection.isDeviceRoaming] * @see [WiseFyPrechecks.isDeviceRoamingChecks] * + * Updates + * - 05/12/2019: Started using isDeviceRoaming + * * @author Patches * @since 3.0 */ @@ -1498,9 +1553,7 @@ class WiseFy private constructor( if (wisefyPrechecks.isDeviceRoamingChecks().failed()) { return false } - - val networkInfo = connectivityManager.activeNetworkInfo - return networkInfo != null && networkInfo.isRoaming + return wisefyConnection.isDeviceRoaming() } /** @@ -1534,7 +1587,7 @@ class WiseFy private constructor( @Sync @CallingThread @RequiresApi(Build.VERSION_CODES.LOLLIPOP) - @RequiresPermission(allOf = arrayOf(ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE)) + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) @Throws(SecurityException::class) override fun isNetwork5gHz(): Boolean { val frequency = getFrequency() @@ -1818,7 +1871,7 @@ class WiseFy private constructor( */ @Sync @CallingThread - @RequiresPermission(ACCESS_WIFI_STATE) + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) override fun searchForAccessPoint( regexForSSID: String?, timeoutInMillis: Int, @@ -1852,7 +1905,7 @@ class WiseFy private constructor( */ @Async @WiseFyThread - @RequiresPermission(ACCESS_WIFI_STATE) + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) override fun searchForAccessPoint( regexForSSID: String?, timeoutInMillis: Int, @@ -1897,7 +1950,7 @@ class WiseFy private constructor( */ @Sync @CallingThread - @RequiresPermission(ACCESS_WIFI_STATE) + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) override fun searchForAccessPoints(regexForSSID: String?, filterDuplicates: Boolean): List? { return if (wisefyPrechecks.searchForAccessPointsChecks(regexForSSID).passed()) { wisefySearch.findAccessPointsMatchingRegex(regexForSSID!!, filterDuplicates) @@ -1926,7 +1979,7 @@ class WiseFy private constructor( */ @Async @WiseFyThread - @RequiresPermission(ACCESS_WIFI_STATE) + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) override fun searchForAccessPoints( regexForSSID: String?, filterDuplicates: Boolean, @@ -1968,7 +2021,7 @@ class WiseFy private constructor( @Sync @CallingThread @WaitsForTimeout - @RequiresPermission(ACCESS_WIFI_STATE) + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) override fun searchForSSID(regexForSSID: String?, timeoutInMillis: Int): String? { if (wisefyPrechecks.searchForSSIDChecks(regexForSSID).failed()) { return null @@ -1998,7 +2051,7 @@ class WiseFy private constructor( @Async @WiseFyThread @WaitsForTimeout - @RequiresPermission(ACCESS_WIFI_STATE) + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) override fun searchForSSID(regexForSSID: String?, timeoutInMillis: Int, callbacks: SearchForSSIDCallbacks?) { runOnWiseFyThread(Runnable { synchronized(wisefyLock) { @@ -2033,7 +2086,7 @@ class WiseFy private constructor( */ @Sync @CallingThread - @RequiresPermission(ACCESS_WIFI_STATE) + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) override fun searchForSSIDs(regexForSSID: String?): List? { return if (wisefyPrechecks.searchForSSIDsChecks(regexForSSID).passed()) { wisefySearch.findSSIDsMatchingRegex(regexForSSID!!) @@ -2057,7 +2110,7 @@ class WiseFy private constructor( */ @Async @WiseFyThread - @RequiresPermission(ACCESS_WIFI_STATE) + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) override fun searchForSSIDs(regexForSSID: String?, callbacks: SearchForSSIDsCallbacks?) { runOnWiseFyThread(Runnable { synchronized(wisefyLock) { @@ -2068,7 +2121,7 @@ class WiseFy private constructor( } val ssids = wisefySearch.findSSIDsMatchingRegex(regexForSSID!!) - if (ssids != null && ssids.isNotEmpty()) { + if (ssids != null) { callbacks?.retrievedSSIDs(ssids) } else { callbacks?.noSSIDsFound() @@ -2081,6 +2134,46 @@ class WiseFy private constructor( * HELPERS */ + /** + * Used internally to add a network with password from async API. + * + * *NOTES* NOT to be used with sync APIs. + * + * @param ssid The ssid of the network to add + * @param password The password for the network to add + * @param wifiConfigurationProvider The configuration of the network to add (as a provider) + * @param callbacks The callbacks for adding the network + * + * @see [addNetworkConfiguration] + * @see [WiseFyPrechecks.addNetworkPrechecks] + * @see [WIFI_MANAGER_FAILURE] + * @see [WifiConfiguration] + * + * @author Patches + * @since 4.0 + */ + private fun addNetworkWithPasswordAsync( + ssid: String?, + password: String?, + wifiConfigurationProvider: () -> WifiConfiguration, + callbacks: AddNetworkCallbacks? + ) { + val precheck = wisefyPrechecks.addNetworkPrechecks(ssid, password) + if (precheck.failed()) { + callbacks?.wisefyFailure(precheck.code) + return + } + + val wifiConfiguration = wifiConfigurationProvider() + + val result = addNetworkConfiguration(wifiConfiguration) + if (result != WIFI_MANAGER_FAILURE) { + callbacks?.networkAdded(result, wifiConfiguration) + } else { + callbacks?.failureAddingNetwork(result) + } + } + /** * Used internally to add and save a new wifi configuration. * @@ -2182,17 +2275,24 @@ class WiseFy private constructor( /** * Used internally to setup a WiseFyThread to run background operations. * + * @param useMainLooper Only to be set to true for testing. It's a hacky param to allow RoboElectric + * to complete runnables posted to the [WiseFyHandlerThread] :( I feel bad about this. + * * @see [runOnWiseFyThread] * @see [WiseFyHandlerThread] * + * Updates + * - 05/12/2019: Marks as visible for testing and added useMainLooper param + * * @author Patches * @since 3.0 */ - private fun setupWiseFyThread() { + @VisibleForTesting + internal fun setupWiseFyThread(useMainLooper: Boolean = false) { wisefyHandlerThread = WiseFyHandlerThread(WiseFyHandlerThread.TAG) wisefyHandlerThread?.let { it.start() - val looper = it.looper + val looper = if (useMainLooper) Looper.getMainLooper() else it.looper wisefyHandler = Handler(looper) } } diff --git a/wisefy/src/main/java/com/isupatches/wisefy/WiseFyPrechecks.kt b/wisefy/src/main/java/com/isupatches/wisefy/WiseFyPrechecks.kt index 15208908..75b23f20 100644 --- a/wisefy/src/main/java/com/isupatches/wisefy/WiseFyPrechecks.kt +++ b/wisefy/src/main/java/com/isupatches/wisefy/WiseFyPrechecks.kt @@ -22,6 +22,7 @@ import com.isupatches.wisefy.constants.DEFAULT_PRECHECK_RETURN_CODE import com.isupatches.wisefy.constants.MISSING_PARAMETER import com.isupatches.wisefy.constants.NETWORK_ALREADY_CONFIGURED import com.isupatches.wisefy.constants.WiseFyCode +import com.isupatches.wisefy.search.WiseFySearch /** * A helper class with methods to determine if the necessary requirements are met to preform operations. @@ -463,8 +464,7 @@ internal class WiseFyPrechecksImpl private constructor( */ private fun checkAddNetworkPrerequisites(ssid: String?): PrecheckResult = when { - ssid == null -> PrecheckResult(code = MISSING_PARAMETER) - ssid.isEmpty() -> PrecheckResult(code = MISSING_PARAMETER) + ssid.isNullOrEmpty() -> PrecheckResult(code = MISSING_PARAMETER) wisefySearch.isNetworkASavedConfiguration(ssid) -> { PrecheckResult(code = NETWORK_ALREADY_CONFIGURED) } diff --git a/wisefy/src/main/java/com/isupatches/wisefy/callbacks/GetCurrentNetworkCallbacks.kt b/wisefy/src/main/java/com/isupatches/wisefy/callbacks/GetCurrentNetworkCallbacks.kt index 179485ad..e52dbe96 100644 --- a/wisefy/src/main/java/com/isupatches/wisefy/callbacks/GetCurrentNetworkCallbacks.kt +++ b/wisefy/src/main/java/com/isupatches/wisefy/callbacks/GetCurrentNetworkCallbacks.kt @@ -1,5 +1,5 @@ /* - * Copyright 2018 Patches Klinefelter + * Copyright 2019 Patches Klinefelter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,11 +23,22 @@ import android.net.wifi.WifiInfo * @see [BaseCallback] * @see [com.isupatches.wisefy.WiseFy.getCurrentNetwork] * + * Updates + * - 05/12/2019: Added noCurrentNetwork callback + * * @author Patches * @since 3.0 */ interface GetCurrentNetworkCallbacks : BaseCallback { + /** + * Called when the Android OS returns no current network. + * + * @author Patches + * @since 4.0 + */ + fun noCurrentNetwork() + /** * Called when WiseFy has successfully retrieved the device's current network. * diff --git a/wisefy/src/main/java/com/isupatches/wisefy/callbacks/GetCurrentNetworkInfoCallbacks.kt b/wisefy/src/main/java/com/isupatches/wisefy/callbacks/GetCurrentNetworkInfoCallbacks.kt index c62b0b41..f672bd7f 100644 --- a/wisefy/src/main/java/com/isupatches/wisefy/callbacks/GetCurrentNetworkInfoCallbacks.kt +++ b/wisefy/src/main/java/com/isupatches/wisefy/callbacks/GetCurrentNetworkInfoCallbacks.kt @@ -1,5 +1,5 @@ /* - * Copyright 2018 Patches Klinefelter + * Copyright 2019 Patches Klinefelter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,11 +23,22 @@ import android.net.NetworkInfo * @see [BaseCallback] * @see [com.isupatches.wisefy.WiseFy.getCurrentNetworkInfo] * + * Updates + * - 05/12/2019: Added noCurrentNetworkInfo callback + * * @author Patches * @since 3.0 */ interface GetCurrentNetworkInfoCallbacks : BaseCallback { + /** + * Called when the Android OS returns no current network info. + * + * @author Patches + * @since 4.0 + */ + fun noCurrentNetworkInfo() + /** * Called when WiseFy has successfully retrieved the device's current network info. * diff --git a/wisefy/src/main/java/com/isupatches/wisefy/callbacks/GetNearbyAccessPointsCallbacks.kt b/wisefy/src/main/java/com/isupatches/wisefy/callbacks/GetNearbyAccessPointsCallbacks.kt index cddac61f..2d5fee76 100644 --- a/wisefy/src/main/java/com/isupatches/wisefy/callbacks/GetNearbyAccessPointsCallbacks.kt +++ b/wisefy/src/main/java/com/isupatches/wisefy/callbacks/GetNearbyAccessPointsCallbacks.kt @@ -23,6 +23,9 @@ import android.net.wifi.ScanResult * @see [BaseCallback] * @see [com.isupatches.wisefy.WiseFy.getNearbyAccessPoints] * + * Updates + * - 05/12/2019: Added noCurrentNetwork callback + * * @author Patches * @since 3.0 */ @@ -37,4 +40,12 @@ interface GetNearbyAccessPointsCallbacks : BaseCallback { * @since 3.0 */ fun retrievedNearbyAccessPoints(nearbyAccessPoints: List<@JvmSuppressWildcards ScanResult>) + + /** + * Called when the Android OS returns no access points. + * + * @author Patches + * @since 4.0 + */ + fun noAccessPointsFound() } diff --git a/wisefy/src/main/java/com/isupatches/wisefy/WiseFyConnection.kt b/wisefy/src/main/java/com/isupatches/wisefy/connection/AbstractWiseFyConnection.kt similarity index 50% rename from wisefy/src/main/java/com/isupatches/wisefy/WiseFyConnection.kt rename to wisefy/src/main/java/com/isupatches/wisefy/connection/AbstractWiseFyConnection.kt index 60e17f45..a96346b6 100644 --- a/wisefy/src/main/java/com/isupatches/wisefy/WiseFyConnection.kt +++ b/wisefy/src/main/java/com/isupatches/wisefy/connection/AbstractWiseFyConnection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2018 Patches Klinefelter + * Copyright 2019 Patches Klinefelter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,42 +13,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.isupatches.wisefy +package com.isupatches.wisefy.connection import android.Manifest.permission.ACCESS_NETWORK_STATE import android.Manifest.permission.ACCESS_WIFI_STATE -import android.net.ConnectivityManager -import android.net.NetworkInfo import android.net.wifi.WifiManager import androidx.annotation.RequiresPermission import com.isupatches.wisefy.annotations.WaitsForTimeout -import com.isupatches.wisefy.constants.NetworkType import com.isupatches.wisefy.constants.QUOTE import com.isupatches.wisefy.logging.WiseFyLogger import com.isupatches.wisefy.utils.rest /** - * A class used internally to query and determine different parts of the connection state for a - * device. + * A class used internally to house shared connectivity logic between all SDK versions of Android. * - * @see [ConnectivityManager] * @see [WifiManager] * @see [WiseFyConnection] * * @author Patches - * @since 3.0 + * @since 4.0 */ -internal class WiseFyConnectionImpl private constructor( - private val connectivityManager: ConnectivityManager, +internal abstract class AbstractWiseFyConnection( private val wifiManager: WifiManager ) : WiseFyConnection { internal companion object { - private val TAG = WiseFyConnection::class.java.simpleName - - fun create(connectivityManager: ConnectivityManager, wifiManager: WifiManager): WiseFyConnection = - WiseFyConnectionImpl(connectivityManager, wifiManager) + private val TAG = AbstractWiseFyConnection::class.java.simpleName } /** @@ -63,10 +54,13 @@ internal class WiseFyConnectionImpl private constructor( * @see [isNetworkConnected] * @see [WifiManager.getConnectionInfo] * + * Updates + * - 05/12/2019: Moved here from previous WiseFyConnectionImpl class + * * @author Patches * @since 3.0 */ - @RequiresPermission(allOf = arrayOf(ACCESS_NETWORK_STATE, ACCESS_WIFI_STATE)) + @RequiresPermission(allOf = [ACCESS_NETWORK_STATE, ACCESS_WIFI_STATE]) override fun isCurrentNetworkConnectedToSSID(ssid: String?): Boolean { if (ssid.isNullOrEmpty()) { return false @@ -77,9 +71,7 @@ internal class WiseFyConnectionImpl private constructor( if (!it.ssid.isNullOrEmpty()) { val currentSSID = it.ssid.replace(QUOTE, "") WiseFyLogger.debug(TAG, "Current SSID: %s, Desired SSID: %s", currentSSID, ssid) - if (currentSSID.equals(ssid, ignoreCase = true) && - isNetworkConnected(connectivityManager.activeNetworkInfo) - ) { + if (currentSSID.equals(ssid, ignoreCase = true) && isNetworkConnected()) { WiseFyLogger.debug(TAG, "Network is connected") return true } @@ -88,41 +80,6 @@ internal class WiseFyConnectionImpl private constructor( return false } - /** - * Used internally to check if a network is connected. - * - * @param networkInfo The network to check - * - * @return boolean - True if the network is both available and connected - * - * @see [NetworkInfo] - * - * @author Patches - * @since 3.0 - */ - override fun isNetworkConnected(networkInfo: NetworkInfo?): Boolean { - WiseFyLogger.debug(TAG, "networkInfo: %s", networkInfo ?: "") - return networkInfo != null && networkInfo.isConnected && networkInfo.isAvailable - } - - /** - * Used internally to check if a given network matches a given type and is connected. - * - * @param networkInfo The network to check - * @param type The type of network (i.error. Mobile or Wifi) - * - * @return boolean - True if the network is both connected and matches the given type of network - * - * @see [doesNetworkMatchType] - * @see [isNetworkConnected] - * @see [NetworkInfo] - * - * @author Patches - * @since 3.0 - */ - override fun isNetworkConnectedAndMatchesType(networkInfo: NetworkInfo?, @NetworkType type: String): Boolean = - isNetworkConnected(networkInfo) && doesNetworkMatchType(networkInfo, type) - /** * Used internally to check if the device connects to a given SSID within a specified time. * @@ -133,11 +90,14 @@ internal class WiseFyConnectionImpl private constructor( * * @see [isCurrentNetworkConnectedToSSID] * + * Updates + * - 05/12/2019: Moved here from previous WiseFyConnectionImpl class + * * @author Patches * @since 3.0 */ @WaitsForTimeout - @RequiresPermission(allOf = arrayOf(ACCESS_NETWORK_STATE, ACCESS_WIFI_STATE)) + @RequiresPermission(allOf = [ACCESS_NETWORK_STATE, ACCESS_WIFI_STATE]) override fun waitToConnectToSSID(ssid: String?, timeoutInMillis: Int): Boolean { WiseFyLogger.debug(TAG, "Waiting %d milliseconds to connect to network with ssid %s", timeoutInMillis, ssid ?: "") var currentTime: Long @@ -152,42 +112,4 @@ internal class WiseFyConnectionImpl private constructor( } while (currentTime < endTime) return false } - - /** - * Used internally to check to see if a given network matches a specified type (i.error. Mobile or Wifi) - * - * *NOTE* Case insensitive - * - * @param networkInfo The network to check - * @param type The type of network - * - * @return boolean - True if the network matches the given type - * - * @see [NetworkInfo] - * @see [NetworkType] - * - * @author Patches - * @since 3.0 - */ - private fun doesNetworkMatchType(networkInfo: NetworkInfo?, @NetworkType type: String): Boolean = - type.equals(networkInfo?.typeName, ignoreCase = true) -} - -/** - * An interface with methods that relate to checking device connectivity. - * - * @see [WiseFyConnectionImpl] - * - * @author Patches - * @since 3.0 - */ -internal interface WiseFyConnection { - - fun isCurrentNetworkConnectedToSSID(ssid: String?): Boolean - - fun isNetworkConnected(networkInfo: NetworkInfo?): Boolean - - fun isNetworkConnectedAndMatchesType(networkInfo: NetworkInfo?, @NetworkType type: String): Boolean - - fun waitToConnectToSSID(ssid: String?, timeoutInMillis: Int): Boolean } diff --git a/wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnection.kt b/wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnection.kt new file mode 100644 index 00000000..85bb701c --- /dev/null +++ b/wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnection.kt @@ -0,0 +1,52 @@ +/* + * Copyright 2019 Patches Klinefelter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.isupatches.wisefy.connection + +/** + * An interface with methods that relate to checking device connectivity. + * + * @see [WiseFyConnectionLegacy] + * @see [WiseFyConnectionSDK23] + * + * Updates + * - 05/12/2019 + * * Made more generic for pre and post SDK 23 classes + * * Added init and destroy signatures + * * Split isNetworkConnectedAndMatchesType into isDeviceConnectedToWifiNetwork + * and isDeviceConnectedToMobileNetwork + * * Added isDeviceRoaming + * + * @author Patches + * @since 3.0 + */ +internal interface WiseFyConnection { + + fun init() + + fun destroy() + + fun isCurrentNetworkConnectedToSSID(ssid: String?): Boolean + + fun isDeviceConnectedToWifiNetwork(): Boolean + + fun isDeviceConnectedToMobileNetwork(): Boolean + + fun isDeviceRoaming(): Boolean + + fun isNetworkConnected(): Boolean + + fun waitToConnectToSSID(ssid: String?, timeoutInMillis: Int): Boolean +} diff --git a/wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnectionLegacy.kt b/wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnectionLegacy.kt new file mode 100644 index 00000000..46cac95e --- /dev/null +++ b/wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnectionLegacy.kt @@ -0,0 +1,193 @@ +/* + * Copyright 2019 Patches Klinefelter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.isupatches.wisefy.connection + +import android.net.ConnectivityManager +import android.net.NetworkInfo +import android.net.wifi.WifiManager + +import com.isupatches.wisefy.constants.MOBILE +import com.isupatches.wisefy.constants.NetworkType +import com.isupatches.wisefy.constants.WIFI +import com.isupatches.wisefy.logging.WiseFyLogger + +/** + * A class used internally to query and determine different parts of the connection state for a + * device when WiseFy is set to use the legacy connectivity class or is on a pre-SDK23 device. + * + * @see [ConnectivityManager] + * @see [WifiManager] + * @see [AbstractWiseFyConnection] + * + * @author Patches + * @since 3.0 + */ +@Suppress("deprecation") +internal class WiseFyConnectionLegacy private constructor( + private val connectivityManager: ConnectivityManager, + wifiManager: WifiManager +) : AbstractWiseFyConnection(wifiManager) { + + internal companion object { + private val TAG = WiseFyConnectionLegacy::class.java.simpleName + + fun create(connectivityManager: ConnectivityManager, wifiManager: WifiManager): WiseFyConnection = + WiseFyConnectionLegacy(connectivityManager, wifiManager) + } + + /** + * Used internally for any initialization of [WiseFyConnectionLegacy] class. + * + * @author Patches + * @since 4.0 + */ + override fun init() { + // No-op + } + + /** + * Used internally for any tear down of [WiseFyConnectionLegacy] class. + * + * @author Patches + * @since 4.0 + */ + override fun destroy() { + // No-op + } + + /** + * Used internally to check if a network is connected to a mobile network (i.e. non-Wifi) + * + * @return boolean - True if the device is using a mobile network, false otherwise + * + * @see [ConnectivityManager.getActiveNetworkInfo] + * @see [isNetworkConnectedAndMatchesType] + * @see [MOBILE] + * + * @author Patches + * @since 4.0 + */ + override fun isDeviceConnectedToMobileNetwork(): Boolean = + isNetworkConnectedAndMatchesType(connectivityManager.activeNetworkInfo, MOBILE) + + /** + * Used internally to check if a network is connected to a wifi network (i.e. not using + * mobile data) + * + * @return boolean - True if the device is using a wifi network, false otherwise + * + * @see [ConnectivityManager.getActiveNetworkInfo] + * @see [isNetworkConnectedAndMatchesType] + * @see [WIFI] + * + * @author Patches + * @since 4.0 + */ + override fun isDeviceConnectedToWifiNetwork(): Boolean = + isNetworkConnectedAndMatchesType(connectivityManager.activeNetworkInfo, WIFI) + + /** + * Used internally to check if a network is in a roaming state. + * + * @return boolean - True if the device is roaming, false otherwise + * + * @see [ConnectivityManager.getActiveNetworkInfo] + * @see [NetworkInfo.isRoaming] + * + * @author Patches + * @since 4.0 + */ + override fun isDeviceRoaming(): Boolean { + val networkInfo = connectivityManager.activeNetworkInfo + return networkInfo != null && networkInfo.isRoaming + } + + /** + * Used internally to check if a network is connected. + * + * @return boolean - True if the network is both available and connected + * + * @see [NetworkInfo] + * @see [isConnectedAndAvailable] + * + * Updates + * - 05/12/2019: Switched to using [isConnectedAndAvailable] + * + * @author Patches + * @since 3.0 + */ + override fun isNetworkConnected(): Boolean { + val networkInfo = connectivityManager.activeNetworkInfo + WiseFyLogger.debug(TAG, "networkInfo: %s", networkInfo ?: "") + return networkInfo?.isConnectedAndAvailable() ?: false + } + + /** + * Used internally to check to see if a given network matches a specified type (i.error. Mobile or Wifi) + * + * *NOTE* Case insensitive + * + * @param networkInfo The network to check + * @param type The type of network + * + * @return boolean - True if the network matches the given type + * + * @see [NetworkInfo] + * @see [NetworkType] + * + * Updates + * - 05/12/2019: Made networkInfo expectation non-null + * + * @author Patches + * @since 3.0 + */ + private fun doesNetworkMatchType(networkInfo: NetworkInfo, @NetworkType type: String): Boolean = + type.equals(networkInfo.typeName, ignoreCase = true) + + /** + * Used internally to check if a given network matches a given type and is connected. + * + * @param networkInfo The network to check + * @param type The type of network (i.error. Mobile or Wifi) + * + * @return boolean - True if the network is both connected and matches the given type of network + * + * @see [doesNetworkMatchType] + * @see [isConnectedAndAvailable] + * @see [NetworkInfo] + * + * Updates + * - 05/12/2019: Switched to using [isConnectedAndAvailable] over [isNetworkConnected] + * + * @author Patches + * @since 3.0 + */ + private fun isNetworkConnectedAndMatchesType(networkInfo: NetworkInfo?, @NetworkType type: String): Boolean = + networkInfo?.let { doesNetworkMatchType(it, type) && it.isConnectedAndAvailable() } ?: false + + /** + * Used within legacy class to determine if a given network is in a connected state. + * + * @return boolean - Whether the given NetworkInfo is both connected and available. + * + * @see [NetworkInfo.isConnected] + * @see [NetworkInfo.isAvailable] + * + * @author Patches + * @since 4.0 + */ + private fun NetworkInfo.isConnectedAndAvailable() = isConnected && isAvailable +} diff --git a/wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnectionSDK23.kt b/wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnectionSDK23.kt new file mode 100644 index 00000000..439a7b7e --- /dev/null +++ b/wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnectionSDK23.kt @@ -0,0 +1,266 @@ +/* + * Copyright 2019 Patches Klinefelter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.isupatches.wisefy.connection + +import android.net.ConnectivityManager +import android.net.LinkProperties +import android.net.Network +import android.net.NetworkCapabilities +import android.net.NetworkInfo +import android.net.NetworkRequest +import android.net.wifi.WifiManager +import android.os.Build +import androidx.annotation.RequiresApi +import androidx.annotation.VisibleForTesting + +import com.isupatches.wisefy.logging.WiseFyLogger + +/** + * A class used internally to query and determine different parts of the connection state for a + * device when WiseFy is on a device with at least SDK23 and is not configured to use the legacy + * connection class. + * + * @see [ConnectivityManager] + * @see [WifiManager] + * @see [AbstractWiseFyConnection] + * + * @author Patches + * @since 4.0 + */ +@RequiresApi(Build.VERSION_CODES.M) +internal class WiseFyConnectionSDK23 private constructor( + private val connectivityManager: ConnectivityManager, + wifiManager: WifiManager +) : AbstractWiseFyConnection(wifiManager) { + + internal companion object { + // Internal to avoid SyntheticAccessor error within networkChangeCallback + internal val TAG = WiseFyConnectionSDK23::class.java.simpleName + + fun create(connectivityManager: ConnectivityManager, wifiManager: WifiManager): WiseFyConnection = + WiseFyConnectionSDK23(connectivityManager, wifiManager) + } + + // Internal to avoid SyntheticAccessor error within networkChangeCallback + internal var connectionStatus: WiseFyConnectionStatus? = null + + @VisibleForTesting internal val networkChangeCallbacks by lazy { + object : ConnectivityManager.NetworkCallback() { + override fun onAvailable(network: Network?) { + super.onAvailable(network) + WiseFyLogger.debug(TAG, "onAvailable, $network") + this@WiseFyConnectionSDK23.connectionStatus = WiseFyConnectionStatus.AVAILABLE + } + + override fun onCapabilitiesChanged(network: Network?, networkCapabilities: NetworkCapabilities?) { + super.onCapabilitiesChanged(network, networkCapabilities) + WiseFyLogger.debug(TAG, "onCapabilitiesChanged, network: $network, networkCapabilities: $networkCapabilities") + } + + override fun onLinkPropertiesChanged(network: Network?, linkProperties: LinkProperties?) { + super.onLinkPropertiesChanged(network, linkProperties) + WiseFyLogger.debug(TAG, "onLinkPropertiesChanged, network: $network, linkProperties: $linkProperties") + } + + override fun onLosing(network: Network?, maxMsToLive: Int) { + super.onLosing(network, maxMsToLive) + WiseFyLogger.debug(TAG, "onLosing, network: $network, maxMsToLive: $maxMsToLive") + this@WiseFyConnectionSDK23.connectionStatus = WiseFyConnectionStatus.LOSING + } + + override fun onLost(network: Network?) { + super.onLost(network) + WiseFyLogger.debug(TAG, "onLost, network: $network") + this@WiseFyConnectionSDK23.connectionStatus = WiseFyConnectionStatus.LOST + } + + override fun onUnavailable() { + super.onUnavailable() + WiseFyLogger.debug(TAG, "onUnavailable") + this@WiseFyConnectionSDK23.connectionStatus = WiseFyConnectionStatus.UNAVAILABLE + } + } + } + + /** + * Used internally for any initialization of [WiseFyConnectionLegacy] class. + * + * @see [startListeningForNetworkChanges] + * + * @author Patches + * @since 4.0 + */ + override fun init() { + startListeningForNetworkChanges(connectivityManager) + } + + /** + * Used internally for any tear down of [WiseFyConnectionLegacy] class. + * + * @see [stopListeningForNetworkChanges] + * + * @author Patches + * @since 4.0 + */ + override fun destroy() { + stopListeningForNetworkChanges(connectivityManager) + } + + /** + * Used internally to check if a network is connected to a mobile network (i.e. non-Wifi) + * + * @return boolean - True if the device is using a mobile network, false otherwise + * + * @see [doesNetworkHaveTransportTypeAndInternetCapability] + * @see [isNetworkConnected] + * @see [NetworkCapabilities.TRANSPORT_CELLULAR] + * + * @author Patches + * @since 4.0 + */ + override fun isDeviceConnectedToMobileNetwork(): Boolean = + doesNetworkHaveTransportTypeAndInternetCapability( + transportType = NetworkCapabilities.TRANSPORT_CELLULAR + ) && isNetworkConnected() + + /** + * Used internally to check if a network is connected to a wifi network (i.e. not using + * mobile data) + * + * @return boolean - True if the device is using a wifi network, false otherwise + * + * @see [doesNetworkHaveTransportTypeAndInternetCapability] + * @see [isNetworkConnected] + * @see [NetworkCapabilities.TRANSPORT_WIFI] + * + * @author Patches + * @since 4.0 + */ + override fun isDeviceConnectedToWifiNetwork(): Boolean = + doesNetworkHaveTransportTypeAndInternetCapability( + transportType = NetworkCapabilities.TRANSPORT_WIFI + ) && isNetworkConnected() + + /** + * Used internally to check if a network is in a roaming state. + * + * *NOTE* Determines roaming differently on P and above devices. + * + * @return boolean - True if the device is roaming, false otherwise + * + * @see [doesNetworkHaveCapability] + * @see [ConnectivityManager.getActiveNetworkInfo] + * @see [NetworkInfo.isRoaming] + * + * @author Patches + * @since 4.0 + */ + override fun isDeviceRoaming(): Boolean = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + // NET_CAPABILITY_NOT_ROAMING only available for P and above devices :'( + !doesNetworkHaveCapability(capability = NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING) + } else { + val networkInfo = connectivityManager.activeNetworkInfo + @Suppress("DEPRECATION") + networkInfo != null && networkInfo.isRoaming + } + + /** + * Used internally to check if a network is connected. + * + * @return boolean - True if the network is available + * + * @see [connectionStatus] + * @see [networkChangeCallbacks] + * @see [WiseFyConnectionStatus] + * + * @author Patches + * @since 4.0 + */ + override fun isNetworkConnected(): Boolean = connectionStatus == WiseFyConnectionStatus.AVAILABLE + + /** + * Used internally to check if the active network has a certain transport type as well as + * internet capability. + * + * @see [getActiveNetworkCapabilities] + * @see [NetworkCapabilities.hasTransport] + * @see [NetworkCapabilities.hasCapability] + * @see [NetworkCapabilities.NET_CAPABILITY_INTERNET] + * + * @author Patches + * @since 4.0 + */ + private fun doesNetworkHaveTransportTypeAndInternetCapability(transportType: Int): Boolean = + getActiveNetworkCapabilities()?.let { + it.hasTransport(transportType) && + it.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + } ?: false + + /** + * Used internally to check if the active network has a certain capability (i.e. to check if the + * device has [NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING] capability listed) + * + * @see [getActiveNetworkCapabilities] + * @see [NetworkCapabilities.hasCapability] + * + * @author Patches + * @since 4.0 + */ + private fun doesNetworkHaveCapability(capability: Int): Boolean = + getActiveNetworkCapabilities()?.hasCapability(capability) ?: false + + /** + * Used internally to return the capabilities of the active network. + * + * @see [NetworkCapabilities] + * @see [ConnectivityManager.getNetworkCapabilities] + * @see [ConnectivityManager.getActiveNetwork] + * + * @author Patches + * @since 4.0 + */ + private fun getActiveNetworkCapabilities(): NetworkCapabilities? = + connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) + + /** + * Used internally to start listening for network changes + * + * @see [ConnectivityManager.registerNetworkCallback] + * @see [NetworkRequest.Builder] + * @see [networkChangeCallbacks] + * + * @author Patches + * @since 4.0 + */ + private fun startListeningForNetworkChanges(connectivityManager: ConnectivityManager) { + val request = NetworkRequest.Builder().build() + connectivityManager.registerNetworkCallback(request, networkChangeCallbacks) + } + + /** + * Used internally to stop listening for network changes + * + * @see [ConnectivityManager.unregisterNetworkCallback] + * @see [networkChangeCallbacks] + * + * @author Patches + * @since 4.0 + */ + private fun stopListeningForNetworkChanges(connectivityManager: ConnectivityManager) { + connectivityManager.unregisterNetworkCallback(networkChangeCallbacks) + } +} diff --git a/wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnectionStatus.kt b/wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnectionStatus.kt new file mode 100644 index 00000000..7de264ed --- /dev/null +++ b/wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnectionStatus.kt @@ -0,0 +1,31 @@ +/* + * Copyright 2019 Patches Klinefelter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.isupatches.wisefy.connection + +/** + * Constant to indicate network connection status for SDK23 and above. + * + * @see [WiseFyConnectionSDK23] + * + * @author Patches + * @since 4.0 + */ +internal enum class WiseFyConnectionStatus { + AVAILABLE, + LOSING, + LOST, + UNAVAILABLE +} diff --git a/wisefy/src/main/java/com/isupatches/wisefy/WiseFySearch.kt b/wisefy/src/main/java/com/isupatches/wisefy/search/AbstractWiseFySearch.kt similarity index 67% rename from wisefy/src/main/java/com/isupatches/wisefy/WiseFySearch.kt rename to wisefy/src/main/java/com/isupatches/wisefy/search/AbstractWiseFySearch.kt index 0c3de275..c790c9be 100644 --- a/wisefy/src/main/java/com/isupatches/wisefy/WiseFySearch.kt +++ b/wisefy/src/main/java/com/isupatches/wisefy/search/AbstractWiseFySearch.kt @@ -1,5 +1,5 @@ /* - * Copyright 2018 Patches Klinefelter + * Copyright 2019 Patches Klinefelter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.isupatches.wisefy +package com.isupatches.wisefy.search import android.Manifest.permission.ACCESS_WIFI_STATE import android.net.wifi.ScanResult @@ -21,35 +21,123 @@ import android.net.wifi.WifiConfiguration import android.net.wifi.WifiManager import androidx.annotation.RequiresPermission -import com.isupatches.wisefy.annotations.WaitsForTimeout import com.isupatches.wisefy.constants.QUOTE import com.isupatches.wisefy.logging.WiseFyLogger import com.isupatches.wisefy.utils.rest -import java.util.ArrayList import java.util.Locale /** - * A class used internally for the purposes of shared query logic. This handles saved networks and - * nearby access points. There is also filtering by regex functionality and some RSSI logic that - * are tied into these queries. + * A class used internally to house shared search logic between all SDK versions of Android. * * @see [WifiManager] * @see [WiseFySearch] * * @author Patches - * @since 3.0 + * @since 4.0 */ -internal class WiseFySearchImpl private constructor( +@Suppress("LargeClass") +internal abstract class AbstractWiseFySearch( private val wifiManager: WifiManager ) : WiseFySearch { - internal companion object { - private val TAG = WiseFySearch::class.java.simpleName + companion object { + private val TAG = AbstractWiseFySearch::class.java.simpleName + } + + /** + * An abstracted provider for various SDK level support the provides a way to retrieve a list + * of nearby access points + */ + abstract val scanResultsProvider: () -> List? + + /** + * Used internally to return the first configuration of s saved networks matching a given regex. + * + * @param regexForSSID The regex for the SSID to find in the configured network list + * + * @return WiFiConfiguration|null - The first saved configuration matching the given regex or null if none found + * + * @see [savedNetworkMatchesRegex] + * @see [WifiConfiguration] + * @see [WifiManager.getConfiguredNetworks] + * + * Updates + * - 05/12/2019: Moved here from previous WiseFySearchImpl class + * + * @author Patches + * @since 3.0 + */ + @RequiresPermission(ACCESS_WIFI_STATE) + override fun findSavedNetworkByRegex(regexForSSID: String): WifiConfiguration? { + val savedNetworks = wifiManager.configuredNetworks + if (savedNetworks == null || savedNetworks.isEmpty()) { + return null + } + + for (savedNetwork in savedNetworks) { + if (savedNetworkMatchesRegex(savedNetwork, regexForSSID)) { + return savedNetwork + } + } + return null + } + + /** + * Used internally to return a list of saved networks matching a given regex. + * + * @param regexForSSID The regex for the SSIDs to find in the configured network list + * + * @return List of WifiConfigurations|null - Saved network configurations matching the given regex or null if ' + * none found + * + * @see [savedNetworkMatchesRegex] + * @see [WifiConfiguration] + * @see [WifiManager.getConfiguredNetworks] + * + * Updates + * - 05/12/2019: Moved here from previous WiseFySearchImpl class + * + * @author Patches + * @since 3.0 + */ + @RequiresPermission(ACCESS_WIFI_STATE) + override fun findSavedNetworksMatchingRegex(regexForSSID: String): List? { + val savedNetworks = wifiManager.configuredNetworks + val matchingSavedNetworks = ArrayList() - fun create(wifiManager: WifiManager): WiseFySearch = WiseFySearchImpl(wifiManager) + if (savedNetworks == null || savedNetworks.isEmpty()) { + return null + } + + for (savedNetwork in savedNetworks) { + if (savedNetworkMatchesRegex(savedNetwork, regexForSSID)) { + matchingSavedNetworks.add(savedNetwork) + } + } + + return if (matchingSavedNetworks.isNotEmpty()) matchingSavedNetworks else null } + /** + * Used internally to determine if a network exists as a saved network configuration. + * + * @param ssid The ssid to check for in the configured network list + * + * @return boolean - True if the ssid was found in the configuration list + * + * @see [findSavedNetworkByRegex] + * + * Updates + * - 05/12/2019: Moved here from previous WiseFySearchImpl class + * + * @author Patches + * @since 3.0 + */ + @RequiresPermission(ACCESS_WIFI_STATE) + override fun isNetworkASavedConfiguration(ssid: String?): Boolean = + !ssid.isNullOrEmpty() && findSavedNetworkByRegex(ssid) != null + /** * Used internally to wait for a given time and return the first ScanResult whose SSID matches a given regex. * @@ -67,15 +155,23 @@ internal class WiseFySearchImpl private constructor( * @see [hasHighestSignalStrength] * @see [rest] * @see [ScanResult] - * @see [WifiManager.startScan] - * @see [WifiManager.getScanResults] + * @see [scanResultsProvider] + * + * Updates + * - 05/12/2019 + * * Moved here from previous WiseFySearchImpl class + * * Fixed bad behavior with empty access point list + * * Started using scanResultsProvider for various SDK level support * * @author Patches * @since 3.0 */ - @WaitsForTimeout @RequiresPermission(ACCESS_WIFI_STATE) - override fun findAccessPointByRegex(regexForSSID: String, timeoutInMillis: Int, takeHighest: Boolean): ScanResult? { + override fun findAccessPointByRegex( + regexForSSID: String, + timeoutInMillis: Int, + takeHighest: Boolean + ): ScanResult? { var scanPass = 1 var currentTime: Long val endTime = System.currentTimeMillis() + timeoutInMillis @@ -83,43 +179,39 @@ internal class WiseFySearchImpl private constructor( do { currentTime = System.currentTimeMillis() - WiseFyLogger.debug(TAG, "Scanning SSIDs, pass %d", scanPass) - wifiManager.startScan() - val accessPoints = wifiManager.scanResults - if (accessPoints == null || accessPoints.isEmpty()) { - continue - } + val accessPointsTemp = scanResultsProvider() - var found = false - for (accessPoint in accessPoints) { - if (takeHighest) { - if (accessPointMatchesRegex(accessPoint, regexForSSID) && hasHighestSignalStrength( - accessPoints, - accessPoint - ) - ) { - accessPointToReturn = accessPoint - // Need to continue through rest of the list since - // we don't know which one will have the highest - break - } - } else { - if (accessPointMatchesRegex(accessPoint, regexForSSID)) { - accessPointToReturn = accessPoint - found = true - break + WiseFyLogger.debug(TAG, "Scanning SSIDs, pass %d", scanPass) + if (accessPointsTemp != null && accessPointsTemp.isNotEmpty()) { + var found = false + for (accessPoint in accessPointsTemp) { + if (takeHighest) { + if (accessPointMatchesRegex(accessPoint, regexForSSID) && + hasHighestSignalStrength(accessPointsTemp, accessPoint) + ) { + accessPointToReturn = accessPoint + // Need to continue through rest of the list since + // we don't know which one will have the highest + break + } + } else { + if (accessPointMatchesRegex(accessPoint, regexForSSID)) { + accessPointToReturn = accessPoint + found = true + break + } } } - } - if (found) { - break + if (found) { + break + } + } else { + WiseFyLogger.warn(TAG, "Empty access point list") } - - rest() - WiseFyLogger.debug(TAG, "Current time: %d, end time: %d (findAccessPointByRegex)", currentTime, endTime) scanPass++ + rest() } while (currentTime < endTime) return accessPointToReturn } @@ -135,26 +227,33 @@ internal class WiseFySearchImpl private constructor( * @see [accessPointMatchesRegex] * @see [hasHighestSignalStrength] * @see [ScanResult] - * @see [WifiManager.startScan] - * @see [WifiManager.getScanResults] + * @see [scanResultsProvider] + * + * Updates + * - 05/12/2019 + * * Moved here from previous WiseFySearchImpl class + * * Started using scanResultsProvider for various SDK level support * * @author Patches * @since 3.0 */ @RequiresPermission(ACCESS_WIFI_STATE) - override fun findAccessPointsMatchingRegex(regexForSSID: String, takeHighest: Boolean): List? { - wifiManager.startScan() + override fun findAccessPointsMatchingRegex( + regexForSSID: String, + takeHighest: Boolean + ): List? { val matchingAccessPoints = ArrayList() - val accessPoints = wifiManager.scanResults - if (accessPoints == null || accessPoints.isEmpty()) { + val accessPointsTemp = scanResultsProvider() + + if (accessPointsTemp == null || accessPointsTemp.isEmpty()) { return null } - for (accessPoint in accessPoints) { + for (accessPoint in accessPointsTemp) { if (accessPointMatchesRegex(accessPoint, regexForSSID)) { if (takeHighest) { - if (hasHighestSignalStrength(accessPoints, accessPoint)) { + if (hasHighestSignalStrength(accessPointsTemp, accessPoint)) { matchingAccessPoints.add(accessPoint) } } else { @@ -163,69 +262,7 @@ internal class WiseFySearchImpl private constructor( } } - return if (!matchingAccessPoints.isEmpty()) matchingAccessPoints else null - } - - /** - * Used internally to return the first configuration of s saved networks matching a given regex. - * - * @param regexForSSID The regex for the SSID to find in the configured network list - * - * @return WiFiConfiguration|null - The first saved configuration matching the given regex or null if none found - * - * @see [savedNetworkMatchesRegex] - * @see [WifiConfiguration] - * @see [WifiManager.getConfiguredNetworks] - * - * @author Patches - * @since 3.0 - */ - @RequiresPermission(ACCESS_WIFI_STATE) - override fun findSavedNetworkByRegex(regexForSSID: String): WifiConfiguration? { - val savedNetworks = wifiManager.configuredNetworks - if (savedNetworks == null || savedNetworks.isEmpty()) { - return null - } - - for (savedNetwork in savedNetworks) { - if (savedNetworkMatchesRegex(savedNetwork, regexForSSID)) { - return savedNetwork - } - } - return null - } - - /** - * Used internally to return a list of saved networks matching a given regex. - * - * @param regexForSSID The regex for the SSIDs to find in the configured network list - * - * @return List of WifiConfigurations|null - Saved network configurations matching the given regex or null if ' - * none found - * - * @see [savedNetworkMatchesRegex] - * @see [WifiConfiguration] - * @see [WifiManager.getConfiguredNetworks] - * - * @author Patches - * @since 3.0 - */ - @RequiresPermission(ACCESS_WIFI_STATE) - override fun findSavedNetworksMatchingRegex(regexForSSID: String): List? { - val savedNetworks = wifiManager.configuredNetworks - val matchingSavedNetworks = ArrayList() - - if (savedNetworks == null || savedNetworks.isEmpty()) { - return null - } - - for (savedNetwork in savedNetworks) { - if (savedNetworkMatchesRegex(savedNetwork, regexForSSID)) { - matchingSavedNetworks.add(savedNetwork) - } - } - - return if (!matchingSavedNetworks.isEmpty()) matchingSavedNetworks else null + return if (matchingAccessPoints.isNotEmpty()) matchingAccessPoints else null } /** @@ -237,89 +274,62 @@ internal class WiseFySearchImpl private constructor( * given regex or null if none found * * @see [accessPointMatchesRegex] - * @see [WifiManager.getScanResults] - * @see [WifiManager.startScan] + * @see [scanResultsProvider] + * + * Updates + * - 05/12/2019 + * * Moved here from previous WiseFySearchImpl class + * * Started using scanResultsProvider for various SDK level support * * @author Patches * @since 3.0 */ @RequiresPermission(ACCESS_WIFI_STATE) - override fun findSSIDsMatchingRegex(regexForSSID: String): List? { - wifiManager.startScan() + override fun findSSIDsMatchingRegex( + regexForSSID: String + ): List? { val matchingSSIDs = ArrayList() - val accessPoints = wifiManager.scanResults - if (accessPoints != null && accessPoints.isNotEmpty()) { - for (accessPoint in accessPoints) { + val accessPointsTemp = scanResultsProvider() + if (accessPointsTemp != null && accessPointsTemp.isNotEmpty()) { + for (accessPoint in accessPointsTemp) { if (accessPointMatchesRegex(accessPoint, regexForSSID) && !matchingSSIDs.contains(accessPoint.SSID)) { matchingSSIDs.add(accessPoint.SSID) } } } - return if (!matchingSSIDs.isEmpty()) matchingSSIDs else null + return if (matchingSSIDs.isNotEmpty()) matchingSSIDs else null } /** - * Used internally to determine if a network exists as a saved network configuration. + * Used internally to return a list of nearby access points. * - * @param ssid The ssid to check for in the configured network list - * - * @return boolean - True if the ssid was found in the configuration list - * - * @see [findSavedNetworkByRegex] + * @param filterDuplicates If you want to exclude SSIDs with that same name that have a weaker signal strength * - * @author Patches - * @since 3.0 - */ - @RequiresPermission(ACCESS_WIFI_STATE) - override fun isNetworkASavedConfiguration(ssid: String?): Boolean = - !ssid.isNullOrEmpty() && findSavedNetworkByRegex(ssid) != null - - /** - * Used internally to build a list of ScanResults (removes duplicates by taking access point with higher RSSI). - * - * *NOTE* Case insensitive - * - * @param accessPoints The list of access points to remove entries with lower signal strength from - * - * @return List of ScanResults - The filtered list of networks + * @return List of ScanResult|null - A list of nearby access points or null if there are none * + * @see [scanResultsProvider] * @see [ScanResult] - * @see [WifiManager.compareSignalLevel] + * @see [removeEntriesWithLowerSignalStrength] * * @author Patches - * @since 3.0 + * @since 4.0 */ - override fun removeEntriesWithLowerSignalStrength(accessPoints: List): List { - val accessPointsToReturn = ArrayList() + @RequiresPermission(ACCESS_WIFI_STATE) + override fun getNearbyAccessPoints( + filterDuplicates: Boolean + ): List? { + val accessPointsTemp = scanResultsProvider() - for (accessPoint in accessPoints) { - var found = false - for (i in accessPointsToReturn.indices) { - val scanResult = accessPointsToReturn[i] - WiseFyLogger.debug(TAG, "SSID 1: %s, SSID 2: %s", accessPoint.SSID, scanResult.SSID) - if (accessPoint.SSID.equals(scanResult.SSID, ignoreCase = true)) { - found = true - WiseFyLogger.debug(TAG, "RSSI level of access point 1: %d", scanResult.level) - WiseFyLogger.debug(TAG, "RSSI level of access point 2: %d", accessPoint.level) - WiseFyLogger.debug( - TAG, - "comparison result: %d (removeEntriesWithLowerSignalStrength)", - WifiManager.compareSignalLevel(accessPoint.level, scanResult.level) - ) - if (WifiManager.compareSignalLevel(accessPoint.level, scanResult.level) > 0) { - WiseFyLogger.debug(TAG, "New result has a higher or same signal strength, swapping") - accessPointsToReturn[i] = accessPoint - } - } - } + if (accessPointsTemp == null || accessPointsTemp.isEmpty()) { + return null + } - if (!found) { - WiseFyLogger.debug(TAG, "Found new wifi network") - accessPointsToReturn.add(accessPoint) - } + return if (filterDuplicates) { + removeEntriesWithLowerSignalStrength(accessPointsTemp) + } else { + accessPointsTemp } - return accessPointsToReturn } /* @@ -336,6 +346,9 @@ internal class WiseFySearchImpl private constructor( * * @see [ScanResult] * + * Updates + * - 05/12/2019: Moved here from previous WiseFySearchImpl class + * * @author Patches * @since 3.0 */ @@ -361,6 +374,9 @@ internal class WiseFySearchImpl private constructor( * @see [ScanResult] * @see [WifiManager.compareSignalLevel] * + * Updates + * - 05/12/2019: Moved here from previous WiseFySearchImpl class + * * @author Patches * @since 3.0 */ @@ -383,6 +399,58 @@ internal class WiseFySearchImpl private constructor( return true } + /** + * Used internally to build a list of ScanResults (removes duplicates by taking access point with higher RSSI). + * + * *NOTE* Case insensitive + * + * @param accessPoints The list of access points to remove entries with lower signal strength from + * + * @return List of ScanResults - The filtered list of networks + * + * @see [ScanResult] + * @see [WifiManager.compareSignalLevel] + * + * Updates + * - 05/12/2019 + * * Moved here from previous WiseFySearchImpl class + * * Made private + * + * @author Patches + * @since 3.0 + */ + private fun removeEntriesWithLowerSignalStrength(accessPoints: List): List { + val accessPointsToReturn = ArrayList() + + for (accessPoint in accessPoints) { + var found = false + for (i in accessPointsToReturn.indices) { + val scanResult = accessPointsToReturn[i] + WiseFyLogger.debug(TAG, "SSID 1: %s, SSID 2: %s", accessPoint.SSID, scanResult.SSID) + if (accessPoint.SSID.equals(scanResult.SSID, ignoreCase = true)) { + found = true + WiseFyLogger.debug(TAG, "RSSI level of access point 1: %d", scanResult.level) + WiseFyLogger.debug(TAG, "RSSI level of access point 2: %d", accessPoint.level) + WiseFyLogger.debug( + TAG, + "comparison result: %d (removeEntriesWithLowerSignalStrength)", + WifiManager.compareSignalLevel(accessPoint.level, scanResult.level) + ) + if (WifiManager.compareSignalLevel(accessPoint.level, scanResult.level) > 0) { + WiseFyLogger.debug(TAG, "New result has a higher or same signal strength, swapping") + accessPointsToReturn[i] = accessPoint + } + } + } + + if (!found) { + WiseFyLogger.debug(TAG, "Found new wifi network") + accessPointsToReturn.add(accessPoint) + } + } + return accessPointsToReturn + } + /** * Used internally to check if a saved network has an SSID that matches a given regex. * @@ -393,39 +461,22 @@ internal class WiseFySearchImpl private constructor( * * @see [WifiConfiguration] * + * Updates + * - 05/12/2019 + * * Moved here from previous WiseFySearchImpl class + * * Started to use ?.let for nullness check + * * @author Patches * @since 3.0 */ private fun savedNetworkMatchesRegex(savedNetwork: WifiConfiguration?, regexForSSID: String): Boolean { - if (savedNetwork?.SSID != null) { - val ssidInList = savedNetwork.SSID.replace(QUOTE, "") - return ssidInList.matches(regexForSSID.toRegex()) - } - return false + return savedNetwork?.let { + return if (it.SSID != null) { + val ssidInList = it.SSID.replace(QUOTE, "") + ssidInList.matches(regexForSSID.toRegex()) + } else { + false + } + } ?: false } } - -/** - * An interface that helps with searching. - * - * @see [WiseFySearchImpl] - * - * @author Patches - * @since 3.0 - */ -internal interface WiseFySearch { - - fun findAccessPointByRegex(regexForSSID: String, timeoutInMillis: Int, takeHighest: Boolean): ScanResult? - - fun findAccessPointsMatchingRegex(regexForSSID: String, takeHighest: Boolean): List? - - fun findSavedNetworkByRegex(regexForSSID: String): WifiConfiguration? - - fun findSavedNetworksMatchingRegex(regexForSSID: String): List? - - fun findSSIDsMatchingRegex(regexForSSID: String): List? - - fun isNetworkASavedConfiguration(ssid: String?): Boolean - - fun removeEntriesWithLowerSignalStrength(accessPoints: List): List -} diff --git a/wisefy/src/main/java/com/isupatches/wisefy/search/WiseFySearch.kt b/wisefy/src/main/java/com/isupatches/wisefy/search/WiseFySearch.kt new file mode 100644 index 00000000..d29bd5b5 --- /dev/null +++ b/wisefy/src/main/java/com/isupatches/wisefy/search/WiseFySearch.kt @@ -0,0 +1,51 @@ +/* + * Copyright 2019 Patches Klinefelter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.isupatches.wisefy.search + +import android.net.wifi.ScanResult +import android.net.wifi.WifiConfiguration + +/** + * An interface that helps with searching. + * + * @see [WiseFySearchLegacy] + * @see [WiseFySearchSDK23] + * + * Updates + * - 05/12/2019 + * * Made more generic for pre and post SDK 23 classes + * * Added getNearbyAccessPoints + * * Removed removeEntriesWithLowerSignalStrength + * + * @author Patches + * @since 3.0 + */ +internal interface WiseFySearch { + + fun findAccessPointByRegex(regexForSSID: String, timeoutInMillis: Int, takeHighest: Boolean): ScanResult? + + fun findAccessPointsMatchingRegex(regexForSSID: String, takeHighest: Boolean): List? + + fun findSavedNetworkByRegex(regexForSSID: String): WifiConfiguration? + + fun findSavedNetworksMatchingRegex(regexForSSID: String): List? + + fun findSSIDsMatchingRegex(regexForSSID: String): List? + + fun getNearbyAccessPoints(filterDuplicates: Boolean): List? + + fun isNetworkASavedConfiguration(ssid: String?): Boolean +} diff --git a/wisefy/src/main/java/com/isupatches/wisefy/search/WiseFySearchLegacy.kt b/wisefy/src/main/java/com/isupatches/wisefy/search/WiseFySearchLegacy.kt new file mode 100644 index 00000000..6d63894e --- /dev/null +++ b/wisefy/src/main/java/com/isupatches/wisefy/search/WiseFySearchLegacy.kt @@ -0,0 +1,46 @@ +/* + * Copyright 2019 Patches Klinefelter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.isupatches.wisefy.search + +import android.net.wifi.WifiManager + +/** + * A class used internally for the purposes of shared query logic. This handles saved networks and + * nearby access points. There is also filtering by regex functionality and some RSSI logic that + * are tied into these queries. + * + * @see [WifiManager] + * @see [AbstractWiseFySearch] + * + * @author Patches + * @since 3.0 + */ +@Suppress("deprecation") +internal class WiseFySearchLegacy private constructor( + wifiManager: WifiManager +) : AbstractWiseFySearch(wifiManager) { + + internal companion object { + fun create(wifiManager: WifiManager): WiseFySearch = WiseFySearchLegacy(wifiManager) + } + + // For SDK 23 and below, devices are still allowed to trigger a scan for nearby access points, + // so we'll continue to do that to preserve previous behavior. + override val scanResultsProvider by lazy { { + wifiManager.startScan() + wifiManager.scanResults + } } +} diff --git a/wisefy/src/main/java/com/isupatches/wisefy/search/WiseFySearchSDK23.kt b/wisefy/src/main/java/com/isupatches/wisefy/search/WiseFySearchSDK23.kt new file mode 100644 index 00000000..9e8e9e88 --- /dev/null +++ b/wisefy/src/main/java/com/isupatches/wisefy/search/WiseFySearchSDK23.kt @@ -0,0 +1,47 @@ +/* + * Copyright 2019 Patches Klinefelter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.isupatches.wisefy.search + +import android.net.wifi.WifiManager +import android.os.Build +import androidx.annotation.RequiresApi + +/** + * A class used internally to query and determine different parts of the connection state for a + * device when WiseFy is on a device with at least SDK23 and is not configured to use the legacy + * connection class. + * + * @see [AbstractWiseFySearch] + * @see [WifiManager] + * + * @author Patches + * @since 4.0 + */ +@RequiresApi(Build.VERSION_CODES.M) +internal class WiseFySearchSDK23 private constructor( + private val wifiManager: WifiManager +) : AbstractWiseFySearch(wifiManager) { + + internal companion object { + fun create(wifiManager: WifiManager): WiseFySearch = WiseFySearchSDK23(wifiManager) + } + + // For SDK 23 and above, devices will be limited on ability to trigger scans and it's been + // indicated by Android Google docs that eventually apps will no longer be able to trigger a + // scan to prevent abusive apps, therefore for WiseFy we're going to just use the last + // set of scan results...the downside is this may take some time to be updated. + override val scanResultsProvider by lazy { { wifiManager.scanResults } } +} diff --git a/wisefy/src/main/java/com/isupatches/wisefy/utils/SleepUtil.kt b/wisefy/src/main/java/com/isupatches/wisefy/utils/SleepUtil.kt index 53f0bdeb..3a2d92b1 100644 --- a/wisefy/src/main/java/com/isupatches/wisefy/utils/SleepUtil.kt +++ b/wisefy/src/main/java/com/isupatches/wisefy/utils/SleepUtil.kt @@ -38,6 +38,7 @@ internal fun rest() { * @author Patches * @since 3.0 */ +@Suppress("SwallowedException") private fun sleep(timeToSleepInMillis: Long) { try { Thread.sleep(timeToSleepInMillis) diff --git a/wisefy/src/main/java/com/isupatches/wisefy/utils/WifiConfigurationUtil.kt b/wisefy/src/main/java/com/isupatches/wisefy/utils/WifiConfigurationUtil.kt index 6f34c734..7339d3dd 100644 --- a/wisefy/src/main/java/com/isupatches/wisefy/utils/WifiConfigurationUtil.kt +++ b/wisefy/src/main/java/com/isupatches/wisefy/utils/WifiConfigurationUtil.kt @@ -1,5 +1,5 @@ /* - * Copyright 2018 Patches Klinefelter + * Copyright 2019 Patches Klinefelter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,6 +29,9 @@ import com.isupatches.wisefy.constants.QUOTE * @see [com.isupatches.wisefy.WiseFy.addOpenNetwork] * @see [WifiConfiguration] * + * Updates + * - 05/12/2019: General cleanup and removing deprecated values + * * @author Patches * @since 3.0 */ @@ -36,15 +39,19 @@ internal fun generateOpenNetworkConfiguration(ssid: String): WifiConfiguration { val wifiConfiguration = WifiConfiguration() wifiConfiguration.SSID = convertSSIDForConfig(ssid) wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE) - wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN) - wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA) + + // Allowed auth algorithms wifiConfiguration.allowedAuthAlgorithms.clear() - wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP) - wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP) - wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40) - wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104) + + // Allowed protocols + wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN) + + // Allowed Group Ciphers wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP) wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP) + + // Allowed Pairwise Ciphers + wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP) return wifiConfiguration } @@ -59,22 +66,52 @@ internal fun generateOpenNetworkConfiguration(ssid: String): WifiConfiguration { * @see [com.isupatches.wisefy.WiseFy.addWEPNetwork] * @see [WifiConfiguration] * + * Updates + * - 05/12/2019: General cleanup and removing deprecated values + * * @author Patches * @since 3.0 */ +@Deprecated("Due to security and performance limitations, WEP networks are discouraged") +@Suppress("deprecation") internal fun generateWEPNetworkConfiguration(ssid: String, password: String): WifiConfiguration { val wifiConfiguration = WifiConfiguration() wifiConfiguration.SSID = convertSSIDForConfig(ssid) wifiConfiguration.wepKeys[0] = QUOTE + password + QUOTE wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE) - wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN) - wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA) + + // Deprecated due to security issues with WPA networks, should use WPA2 instead + wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA) // WPA network protocol + + /* + * Allowed Auth Algorithms + */ + wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN) + // Deprecated due to shared key authentication requiring static WEP keys wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED) - wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP) - wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP) + + /* + * Allowed Protocols + */ + wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN) + + /* + * Allowed Group Ciphers + */ + + // Deprecated because of WEP wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40) wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104) + + /* + * Allowed Pairwise Ciphers + */ + + wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP) + // Deprecated WPA algorithm, RSN and WPA2 should be used instead + wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP) + return wifiConfiguration } @@ -89,6 +126,9 @@ internal fun generateWEPNetworkConfiguration(ssid: String, password: String): Wi * @see [com.isupatches.wisefy.WiseFy.addWPA2Network] * @see [WifiConfiguration] * + * Updates + * - 05/12/2019: General cleanup and removing deprecated values + * * @author Patches * @since 3.0 */ @@ -96,17 +136,17 @@ internal fun generateWPA2NetworkConfiguration(ssid: String, password: String): W val wifiConfiguration = WifiConfiguration() wifiConfiguration.SSID = convertSSIDForConfig(ssid) wifiConfiguration.preSharedKey = QUOTE + password + QUOTE - wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN) wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK) wifiConfiguration.status = WifiConfiguration.Status.ENABLED - wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP) - wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP) - wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP) - wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP) + + // Allowed protocols wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN) - wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA) + // Allowed Group Ciphers + wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP) wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP) + + // Allowed Pairwise Ciphers wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP) return wifiConfiguration } diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/AddOpenNetworkTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/AddOpenNetworkTests.kt similarity index 86% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/AddOpenNetworkTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/AddOpenNetworkTests.kt index bab3655b..989d031c 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/AddOpenNetworkTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/AddOpenNetworkTests.kt @@ -1,26 +1,32 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import android.net.wifi.WifiConfiguration -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.OPEN_NETWORK_SSID -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.WiseFy.Companion.WIFI_MANAGER_FAILURE import com.isupatches.wisefy.callbacks.AddNetworkCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest + import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Test -import org.mockito.ArgumentMatchers.anyInt +import org.junit.runner.RunWith + import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Tests the ability to add open networks. * * @author Patches */ -internal class AddOpenNetworkTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class AddOpenNetworkTests : BaseUnitTest() { @Test fun sync_failure_prechecks() { mockWiseFyPrechecksUtil.addNetwork_failure() @@ -77,7 +83,7 @@ internal class AddOpenNetworkTests : BaseAndroidJUnit4TestClass() { mockNetworkUtil.addNetwork_success() val mockCallbacks = mock(AddNetworkCallbacks::class.java) wisefy.addOpenNetwork(OPEN_NETWORK_SSID, mockCallbacks) - verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).networkAdded(anyInt(), any(WifiConfiguration::class.java)) + verifyNetworkAdded(mockCallbacks) verificationUtil.triedToAddNetwork() } diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/AddWEPNetworkTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/AddWEPNetworkTests.kt similarity index 86% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/AddWEPNetworkTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/AddWEPNetworkTests.kt index 275a2a8e..69dcad27 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/AddWEPNetworkTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/AddWEPNetworkTests.kt @@ -1,27 +1,33 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import android.net.wifi.WifiConfiguration -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT -import com.isupatches.wisefy.WEP_NETWORK_PASSWORD -import com.isupatches.wisefy.WEP_NETWORK_SSID import com.isupatches.wisefy.WiseFy.Companion.WIFI_MANAGER_FAILURE import com.isupatches.wisefy.callbacks.AddNetworkCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest + import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Test -import org.mockito.ArgumentMatchers.anyInt +import org.junit.runner.RunWith + import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Tests the ability to add WEP networks. * * @author Patches */ -internal class AddWEPNetworkTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +@Suppress("deprecation") +internal class AddWEPNetworkTests : BaseUnitTest() { @Test fun sync_failure_prechecks() { mockWiseFyPrechecksUtil.addNetwork_failure() @@ -78,7 +84,7 @@ internal class AddWEPNetworkTests : BaseAndroidJUnit4TestClass() { mockNetworkUtil.addNetwork_success() val mockCallbacks = mock(AddNetworkCallbacks::class.java) wisefy.addWEPNetwork(WEP_NETWORK_SSID, WEP_NETWORK_PASSWORD, mockCallbacks) - verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).networkAdded(anyInt(), any(WifiConfiguration::class.java)) + verifyNetworkAdded(mockCallbacks) verificationUtil.triedToAddNetwork() } diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/AddWPA2NetworkTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/AddWPA2NetworkTests.kt similarity index 86% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/AddWPA2NetworkTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/AddWPA2NetworkTests.kt index cc72c70f..caea489b 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/AddWPA2NetworkTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/AddWPA2NetworkTests.kt @@ -1,27 +1,32 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import android.net.wifi.WifiConfiguration -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT -import com.isupatches.wisefy.WPA2_NETWORK_PASSWORD -import com.isupatches.wisefy.WPA2_NETWORK_SSID import com.isupatches.wisefy.WiseFy.Companion.WIFI_MANAGER_FAILURE import com.isupatches.wisefy.callbacks.AddNetworkCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest + import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Test -import org.mockito.ArgumentMatchers.anyInt +import org.junit.runner.RunWith + import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Tests the ability to add WPA2 networks. * * @author Patches */ -internal class AddWPA2NetworkTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class AddWPA2NetworkTests : BaseUnitTest() { @Test fun sync_failure_prechecks() { mockWiseFyPrechecksUtil.addNetwork_failure() @@ -78,7 +83,7 @@ internal class AddWPA2NetworkTests : BaseAndroidJUnit4TestClass() { mockNetworkUtil.addNetwork_success() val mockCallbacks = mock(AddNetworkCallbacks::class.java) wisefy.addWPA2Network(WPA2_NETWORK_SSID, WPA2_NETWORK_PASSWORD, mockCallbacks) - verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).networkAdded(anyInt(), any(WifiConfiguration::class.java)) + verifyNetworkAdded(mockCallbacks) verificationUtil.triedToAddNetwork() } diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/ConnectToNetworkTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/ConnectToNetworkTests.kt similarity index 92% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/ConnectToNetworkTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/ConnectToNetworkTests.kt index 75012ffb..c98b4219 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/ConnectToNetworkTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/ConnectToNetworkTests.kt @@ -1,25 +1,30 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.TEST_SSID -import com.isupatches.wisefy.TEST_TIMEOUT -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.callbacks.ConnectToNetworkCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Tests the ability to connect to a network. * * @author Patches */ -internal class ConnectToNetworkTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class ConnectToNetworkTests : BaseUnitTest() { @Test fun sync_failure_prechecks() { mockWiseFyPrechecksUtil.connectToNetwork_failure() diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/DisableWifiTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/DisableWifiTests.kt similarity index 88% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/DisableWifiTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/DisableWifiTests.kt index ea3826fb..096d9aa7 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/DisableWifiTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/DisableWifiTests.kt @@ -1,23 +1,30 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.callbacks.DisableWifiCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Tests the ability to disable a device's wifi. * * @author Patches */ -internal class DisableWifiTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class DisableWifiTests : BaseUnitTest() { @Test fun sync_failure_prechecks() { mockWiseFyPrechecksUtil.disableWifi_failure() diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/DisconnectFromCurrentNetworkTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/DisconnectFromCurrentNetworkTests.kt similarity index 90% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/DisconnectFromCurrentNetworkTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/DisconnectFromCurrentNetworkTests.kt index e914a08a..7dc2b172 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/DisconnectFromCurrentNetworkTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/DisconnectFromCurrentNetworkTests.kt @@ -1,23 +1,30 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.callbacks.DisconnectFromCurrentNetworkCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Tests the ability to disconnect a device from it's current network. * * @author Patches */ -internal class DisconnectFromCurrentNetworkTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class DisconnectFromCurrentNetworkTests : BaseUnitTest() { @Test fun sync_failure_prechecks() { mockWiseFyPrechecksUtil.disconnectFromCurrentNetwork_failure() diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/EnableWifiTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/EnableWifiTests.kt similarity index 88% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/EnableWifiTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/EnableWifiTests.kt index 1d4ddfde..b152d657 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/EnableWifiTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/EnableWifiTests.kt @@ -1,23 +1,30 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.callbacks.EnableWifiCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Tests the ability to enable a device's wifi. * * @author Patches */ -internal class EnableWifiTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class EnableWifiTests : BaseUnitTest() { @Test fun sync_failure_prechecks() { mockWiseFyPrechecksUtil.enableWifi_failure() diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetCurrentNetworkInfoTest.kt b/wisefy/src/test/java/com/isupatches/wisefy/GetCurrentNetworkInfoTest.kt similarity index 65% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetCurrentNetworkInfoTest.kt rename to wisefy/src/test/java/com/isupatches/wisefy/GetCurrentNetworkInfoTest.kt index cbca51e4..c7f07d9c 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetCurrentNetworkInfoTest.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/GetCurrentNetworkInfoTest.kt @@ -1,27 +1,33 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy import android.net.NetworkInfo +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.callbacks.GetCurrentNetworkInfoCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.fail import org.junit.Test +import org.junit.runner.RunWith import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Tests the ability to retrieve a device's current network information. * * @author Patches */ -internal class GetCurrentNetworkInfoTest : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class GetCurrentNetworkInfoTest : BaseUnitTest() { @Test fun sync_failure_prechecks() { mockWiseFyPrechecksUtil.getCurrentNetworkInfo_failure() @@ -29,6 +35,12 @@ internal class GetCurrentNetworkInfoTest : BaseAndroidJUnit4TestClass() { verificationUtil.didNotTryToGetCurrentNetworkInfo() } + @Test fun sync_failure_nullCurrentNetwork() { + mockWiseFyPrechecksUtil.getCurrentNetworkInfo_success() + assertEquals(null, wisefy.getCurrentNetworkInfo()) + verificationUtil.triedToGetCurrentNetworkInfo() + } + @Test fun sync_success() { mockWiseFyPrechecksUtil.getCurrentNetworkInfo_success() mockNetworkUtil.activeNetwork() @@ -55,6 +67,20 @@ internal class GetCurrentNetworkInfoTest : BaseAndroidJUnit4TestClass() { verificationUtil.didNotTryToGetCurrentNetworkInfo() } + @Test fun async_failure_nullCurrentNetwork() { + mockWiseFyPrechecksUtil.getCurrentNetworkInfo_success() + val mockCallbacks = mock(GetCurrentNetworkInfoCallbacks::class.java) + wisefy.getCurrentNetworkInfo(mockCallbacks) + verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).noCurrentNetworkInfo() + verificationUtil.triedToGetCurrentNetworkInfo() + } + + @Test fun async_failure_nullCurrentNetwork_nullCallbacks() { + mockWiseFyPrechecksUtil.getCurrentNetworkInfo_success() + nullCallbackUtil.callGetCurrentNetworkInfo() + verificationUtil.triedToGetCurrentNetworkInfo() + } + @Test fun async_success() { mockWiseFyPrechecksUtil.getCurrentNetworkInfo_success() mockNetworkUtil.activeNetwork() @@ -68,6 +94,6 @@ internal class GetCurrentNetworkInfoTest : BaseAndroidJUnit4TestClass() { mockWiseFyPrechecksUtil.getCurrentNetworkInfo_success() mockNetworkUtil.activeNetwork() nullCallbackUtil.callGetCurrentNetworkInfo() - verificationUtil.didNotTryToGetCurrentNetworkInfo() + verificationUtil.triedToGetCurrentNetworkInfo() } } diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetCurrentNetworkTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/GetCurrentNetworkTests.kt similarity index 64% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetCurrentNetworkTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/GetCurrentNetworkTests.kt index ecc07bea..f9e2670e 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetCurrentNetworkTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/GetCurrentNetworkTests.kt @@ -1,23 +1,31 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.TEST_SSID -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.callbacks.GetCurrentNetworkCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest + import org.junit.Assert.assertEquals import org.junit.Assert.fail import org.junit.Test +import org.junit.runner.RunWith + import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Tests the ability to retrieve a device's current network. * * @author Patches */ -internal class GetCurrentNetworkTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class GetCurrentNetworkTests : BaseUnitTest() { @Test fun sync_failure_prechecks() { mockWiseFyPrechecksUtil.getCurrentNetwork_failure() @@ -25,6 +33,12 @@ internal class GetCurrentNetworkTests : BaseAndroidJUnit4TestClass() { verificationUtil.didNotTryToGetCurrentNetwork() } + @Test fun sync_failure_nullCurrentNetwork() { + mockWiseFyPrechecksUtil.getCurrentNetwork_success() + assertEquals(null, wisefy.getCurrentNetwork()) + verificationUtil.triedToGetCurrentNetwork() + } + @Test fun sync_success() { mockWiseFyPrechecksUtil.getCurrentNetwork_success() mockNetworkUtil.currentNetwork(TEST_SSID) @@ -51,6 +65,20 @@ internal class GetCurrentNetworkTests : BaseAndroidJUnit4TestClass() { verificationUtil.didNotTryToGetCurrentNetwork() } + @Test fun async_failure_nullCurrentNetwork() { + mockWiseFyPrechecksUtil.getCurrentNetwork_success() + val mockCallbacks = mock(GetCurrentNetworkCallbacks::class.java) + wisefy.getCurrentNetwork(mockCallbacks) + verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).noCurrentNetwork() + verificationUtil.triedToGetCurrentNetwork() + } + + @Test fun async_failure_nullCurrentNetwork_nullCallbacks() { + mockWiseFyPrechecksUtil.getCurrentNetwork_success() + nullCallbackUtil.callGetCurrentNetwork() + verificationUtil.triedToGetCurrentNetwork() + } + @Test fun async_success() { mockWiseFyPrechecksUtil.getCurrentNetwork_success() val currentNetwork = mockNetworkUtil.currentNetwork(TEST_SSID) @@ -64,6 +92,6 @@ internal class GetCurrentNetworkTests : BaseAndroidJUnit4TestClass() { mockWiseFyPrechecksUtil.getCurrentNetwork_success() mockNetworkUtil.currentNetwork(TEST_SSID) nullCallbackUtil.callGetCurrentNetwork() - verificationUtil.didNotTryToGetCurrentNetwork() + verificationUtil.triedToGetCurrentNetwork() } } diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetFrequencyTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/GetFrequencyTests.kt similarity index 82% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetFrequencyTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/GetFrequencyTests.kt index adfd7ed8..8f17c7ea 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetFrequencyTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/GetFrequencyTests.kt @@ -1,32 +1,35 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy import android.net.wifi.WifiInfo -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.TEST_NETWORK_FREQUENCY_24GHZ -import com.isupatches.wisefy.VERIFICATION_FAILURE_TIMEOUT -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT +import android.os.Build + import com.isupatches.wisefy.callbacks.GetFrequencyCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest + import org.junit.Assert.assertEquals import org.junit.Assert.fail import org.junit.Test +import org.junit.runner.RunWith + import org.mockito.Mockito.after import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Tests the ability to retrieve a network's frequency. * * @author Patches */ -internal class GetFrequencyTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.LOLLIPOP]) +internal class GetFrequencyTests : BaseUnitTest() { @Test fun sync_getFrequency_currentNetwork_failure() { - if (preLollipop()) { - return - } - mockWiseFyPrechecksUtil.getCurrentNetwork_success() mockNetworkUtil.currentNetwork_null() assertEquals(null, wisefy.getFrequency()) @@ -34,10 +37,6 @@ internal class GetFrequencyTests : BaseAndroidJUnit4TestClass() { } @Test fun sync_getFrequency_currentNetwork_success() { - if (preLollipop()) { - return - } - mockWiseFyPrechecksUtil.getCurrentNetwork_success() val wifiInfo = mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_24GHZ) val frequency = wisefy.getFrequency() @@ -51,10 +50,6 @@ internal class GetFrequencyTests : BaseAndroidJUnit4TestClass() { } @Test fun async_getFrequency_currentNetwork_failure() { - if (preLollipop()) { - return - } - mockWiseFyPrechecksUtil.getCurrentNetwork_success() mockNetworkUtil.currentNetwork_null() val mockCallbacks = mock(GetFrequencyCallbacks::class.java) @@ -64,10 +59,6 @@ internal class GetFrequencyTests : BaseAndroidJUnit4TestClass() { } @Test fun async_getFrequency_currentNetwork_failure_nullCallback() { - if (preLollipop()) { - return - } - mockWiseFyPrechecksUtil.getCurrentNetwork_success() mockNetworkUtil.currentNetwork_null() nullCallbackUtil.callGetFrequency() @@ -75,10 +66,6 @@ internal class GetFrequencyTests : BaseAndroidJUnit4TestClass() { } @Test fun async_getFrequency_currentNetwork_success() { - if (preLollipop()) { - return - } - mockWiseFyPrechecksUtil.getCurrentNetwork_success() val mockWifiInfo = mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_24GHZ) val mockCallbacks = mock(GetFrequencyCallbacks::class.java) @@ -89,29 +76,18 @@ internal class GetFrequencyTests : BaseAndroidJUnit4TestClass() { } @Test fun async_getFrequency_currentNetwork_success_nullCallback() { - if (preLollipop()) { - return - } - mockWiseFyPrechecksUtil.getCurrentNetwork_success() + mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_24GHZ) nullCallbackUtil.callGetFrequency() verificationUtil.triedToGetCurrentNetwork() } @Test fun sync_getFrequency_networkProvided_failure() { - if (preLollipop()) { - return - } - mockNetworkUtil.currentNetwork_null() assertEquals(null, wisefy.getFrequency(null as? WifiInfo?)) } @Test fun sync_getFrequency_networkProvided_success() { - if (preLollipop()) { - return - } - val mockWifiInfo = mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_24GHZ) val frequency = wisefy.getFrequency(mockWifiInfo) if (frequency != null) { @@ -122,10 +98,6 @@ internal class GetFrequencyTests : BaseAndroidJUnit4TestClass() { } @Test fun async_getFrequency_networkProvided_failure() { - if (preLollipop()) { - return - } - mockNetworkUtil.currentNetwork_null() val mockCallbacks = mock(GetFrequencyCallbacks::class.java) wisefy.getFrequency(null, mockCallbacks) @@ -133,19 +105,11 @@ internal class GetFrequencyTests : BaseAndroidJUnit4TestClass() { } @Test fun async_getFrequency_networkProvided_failure_nullCallback() { - if (preLollipop()) { - return - } - mockNetworkUtil.currentNetwork_null() nullCallbackUtil.callGetFrequency_networkProvided(null) } @Test fun async_getFrequency_networkProvided_success() { - if (preLollipop()) { - return - } - val mockWifiInfo = mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_24GHZ) val mockCallbacks = mock(GetFrequencyCallbacks::class.java) wisefy.getFrequency(mockWifiInfo, mockCallbacks) @@ -154,10 +118,6 @@ internal class GetFrequencyTests : BaseAndroidJUnit4TestClass() { } @Test fun async_getFrequency_networkProvided_success_nullCallback() { - if (preLollipop()) { - return - } - val mockWifiInfo = mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_24GHZ) nullCallbackUtil.callGetFrequency_networkProvided(mockWifiInfo) verify(mockWifiInfo, after(VERIFICATION_FAILURE_TIMEOUT).times(0)).frequency diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetIIPTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/GetIPTests.kt similarity index 67% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetIIPTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/GetIPTests.kt index 8f62b72b..dbdd214d 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetIIPTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/GetIPTests.kt @@ -1,22 +1,30 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.TEST_IP_ADDRESS_STRING -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.callbacks.GetIPCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest + import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Tests the ability to get the IP of a device. * * @author Patches */ -internal class GetIIPTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class GetIPTests : BaseUnitTest() { @Test fun sync_getIP_failure_missingPrerequisites() { mockWiseFyPrechecksUtil.getIP_failure() @@ -42,6 +50,11 @@ internal class GetIIPTests : BaseAndroidJUnit4TestClass() { verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).wisefyFailure(MISSING_PARAMETER) } + @Test fun async_getIP_failure_missingPrerequisites_nullCallbacks() { + mockWiseFyPrechecksUtil.getIP_failure() + nullCallbackUtil.callGetIP() + } + @Test fun async_getIP_failure() { mockWiseFyPrechecksUtil.getIP_success() mockNetworkUtil.ip_failure() @@ -50,6 +63,12 @@ internal class GetIIPTests : BaseAndroidJUnit4TestClass() { verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).failureRetrievingIP() } + @Test fun async_getIP_failure_nullCallbacks() { + mockWiseFyPrechecksUtil.getIP_success() + mockNetworkUtil.ip_failure() + nullCallbackUtil.callGetIP() + } + @Test fun async_getIP_success() { mockWiseFyPrechecksUtil.getIP_success() mockNetworkUtil.ip_success() @@ -57,4 +76,10 @@ internal class GetIIPTests : BaseAndroidJUnit4TestClass() { wisefy.getIP(mockCallbacks) verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).retrievedIP(TEST_IP_ADDRESS_STRING) } + + @Test fun async_getIP_success_nullCallbacks() { + mockWiseFyPrechecksUtil.getIP_success() + mockNetworkUtil.ip_success() + nullCallbackUtil.callGetIP() + } } diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetNearbyAccessPointsTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/GetNearbyAccessPointsTests.kt similarity index 56% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetNearbyAccessPointsTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/GetNearbyAccessPointsTests.kt index 2b5dfd33..dbeb9e28 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetNearbyAccessPointsTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/GetNearbyAccessPointsTests.kt @@ -1,48 +1,67 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.callbacks.GetNearbyAccessPointsCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest + import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Tests the ability to retrieve a list of nearby access points for a device. * * @author Patches */ -internal class GetNearbyAccessPointsTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class GetNearbyAccessPointsTests : BaseUnitTest() { @Test fun sync_failure_prechecks_filterDuplicates_false() { mockWiseFyPrechecksUtil.getNearbyAccessPoints_failure() assertEquals(null, wisefy.getNearbyAccessPoints(false)) - verificationUtil.didNotTryToGetNearbyAccessPoints() } @Test fun sync_failure_prechecks_filterDuplicates_true() { mockWiseFyPrechecksUtil.getNearbyAccessPoints_failure() assertEquals(null, wisefy.getNearbyAccessPoints(true)) - verificationUtil.didNotTryToGetNearbyAccessPoints() + } + + @Test fun sync_failure_filterDuplicates_false() { + mockWiseFyPrechecksUtil.getNearbyAccessPoints_success() + mockWiseFySearchUtil.nearbyAccessPoints_null(false) + val nearbyAccessPoints = wisefy.getNearbyAccessPoints(false) + assertEquals(null, nearbyAccessPoints) + } + + @Test fun sync_failure_filterDuplicates_true() { + mockWiseFyPrechecksUtil.getNearbyAccessPoints_success() + mockWiseFySearchUtil.nearbyAccessPoints_null(true) + val nearbyAccessPoints = wisefy.getNearbyAccessPoints(true) + assertEquals(null, nearbyAccessPoints) } @Test fun sync_success_filterDuplicates_false() { mockWiseFyPrechecksUtil.getNearbyAccessPoints_success() - val accessPoints = mockNetworkUtil.nearbyAccessPoints() + val accessPoints = mockWiseFySearchUtil.nearbyAccessPoints_success(false) val nearbyAccessPoints = wisefy.getNearbyAccessPoints(false) assertEquals(accessPoints, nearbyAccessPoints) - verificationUtil.triedToGetNearbyAccessPoints() } @Test fun sync_success_filterDuplicates_true() { mockWiseFyPrechecksUtil.getNearbyAccessPoints_success() - val accessPoints = mockWiseFySearchUtil.removeEntriesWithLowerSignalStrength() + val accessPoints = mockWiseFySearchUtil.nearbyAccessPoints_success(true) val nearbyAccessPoints = wisefy.getNearbyAccessPoints(true) assertEquals(accessPoints, nearbyAccessPoints) - verificationUtil.triedToGetNearbyAccessPoints() } @Test fun async_failure_prechecks_filterDuplicates_false() { @@ -50,13 +69,11 @@ internal class GetNearbyAccessPointsTests : BaseAndroidJUnit4TestClass() { val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java) wisefy.getNearbyAccessPoints(false, mockCallbacks) verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).wisefyFailure(MISSING_PARAMETER) - verificationUtil.didNotTryToGetNearbyAccessPoints() } @Test fun async_failure_prechecks_filterDuplicates_false_nullCallback() { mockWiseFyPrechecksUtil.getNearbyAccessPoints_failure() nullCallbackUtil.callGetNearbyAccessPoints(false) - verificationUtil.didNotTryToGetNearbyAccessPoints() } @Test fun async_failure_prechecks_filterDuplicates_true() { @@ -64,44 +81,66 @@ internal class GetNearbyAccessPointsTests : BaseAndroidJUnit4TestClass() { val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java) wisefy.getNearbyAccessPoints(true, mockCallbacks) verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).wisefyFailure(MISSING_PARAMETER) - verificationUtil.didNotTryToGetNearbyAccessPoints() } @Test fun async_failure_prechecks_filterDuplicates_true_nullCallback() { mockWiseFyPrechecksUtil.getNearbyAccessPoints_failure() nullCallbackUtil.callGetNearbyAccessPoints(true) - verificationUtil.didNotTryToGetNearbyAccessPoints() + } + + @Test fun async_failure_filterDuplicates_false() { + mockWiseFyPrechecksUtil.getNearbyAccessPoints_success() + mockWiseFySearchUtil.nearbyAccessPoints_null(false) + val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java) + wisefy.getNearbyAccessPoints(false, mockCallbacks) + verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).noAccessPointsFound() + } + + @Test fun async_failure_filterDuplicates_false_nullCallback() { + mockWiseFyPrechecksUtil.getNearbyAccessPoints_success() + mockWiseFySearchUtil.nearbyAccessPoints_success(true) + nullCallbackUtil.callGetNearbyAccessPoints(false) + } + + @Test fun async_failure_filterDuplicates_true() { + mockWiseFyPrechecksUtil.getNearbyAccessPoints_success() + mockWiseFySearchUtil.nearbyAccessPoints_null(true) + val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java) + wisefy.getNearbyAccessPoints(true, mockCallbacks) + verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).noAccessPointsFound() + } + + @Test fun async_failure_filterDuplicates_true_nullCallback() { + mockWiseFyPrechecksUtil.getNearbyAccessPoints_success() + mockWiseFySearchUtil.nearbyAccessPoints_null(true) + nullCallbackUtil.callGetNearbyAccessPoints(true) } @Test fun async_success_filterDuplicates_false() { mockWiseFyPrechecksUtil.getNearbyAccessPoints_success() - val accessPoints = mockNetworkUtil.nearbyAccessPoints() + val accessPoints = mockWiseFySearchUtil.nearbyAccessPoints_success(false) val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java) wisefy.getNearbyAccessPoints(false, mockCallbacks) verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).retrievedNearbyAccessPoints(accessPoints) - verificationUtil.triedToGetNearbyAccessPoints() } @Test fun async_success_filterDuplicates_false_nullCallback() { mockWiseFyPrechecksUtil.getNearbyAccessPoints_success() - mockNetworkUtil.nearbyAccessPoints() + mockWiseFySearchUtil.nearbyAccessPoints_success(true) nullCallbackUtil.callGetNearbyAccessPoints(false) - verificationUtil.didNotTryToGetNearbyAccessPoints() } @Test fun async_success_filterDuplicates_true() { mockWiseFyPrechecksUtil.getNearbyAccessPoints_success() - val accessPoints = mockWiseFySearchUtil.removeEntriesWithLowerSignalStrength() + val accessPoints = mockWiseFySearchUtil.nearbyAccessPoints_success(true) val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java) wisefy.getNearbyAccessPoints(true, mockCallbacks) verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).retrievedNearbyAccessPoints(accessPoints) - verificationUtil.triedToGetNearbyAccessPoints() } @Test fun async_success_filterDuplicates_true_nullCallback() { mockWiseFyPrechecksUtil.getNearbyAccessPoints_success() - mockWiseFySearchUtil.removeEntriesWithLowerSignalStrength() + mockWiseFySearchUtil.nearbyAccessPoints_success(true) nullCallbackUtil.callGetNearbyAccessPoints(true) - verificationUtil.didNotTryToGetNearbyAccessPoints() } } diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetRSSITests.kt b/wisefy/src/test/java/com/isupatches/wisefy/GetRSSITests.kt similarity index 94% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetRSSITests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/GetRSSITests.kt index 2d1f80b6..06038a63 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetRSSITests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/GetRSSITests.kt @@ -1,25 +1,31 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.TEST_RSSI_LEVEL -import com.isupatches.wisefy.TEST_SSID -import com.isupatches.wisefy.TEST_TIMEOUT -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.callbacks.GetRSSICallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest + import org.junit.Assert.assertEquals import org.junit.Assert.fail import org.junit.Test +import org.junit.runner.RunWith + import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Tests the ability to retrieve the RSSI for a nearby access point. * * @author Patches */ -internal class GetRSSITests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class GetRSSITests : BaseUnitTest() { @Test fun sync_failure_prechecks_takeHighest_false() { mockWiseFyPrechecksUtil.getRSSI_failure() diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetSavedNetworkTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/GetSavedNetworkTests.kt similarity index 88% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetSavedNetworkTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/GetSavedNetworkTests.kt index 80179852..73331d43 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetSavedNetworkTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/GetSavedNetworkTests.kt @@ -1,22 +1,30 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.TEST_SSID -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.callbacks.GetSavedNetworkCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest + import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Tests the ability to retrieve a saved on a device. * * @author Patches */ -internal class GetSavedNetworkTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class GetSavedNetworkTests : BaseUnitTest() { @Test fun sync_failure_prechecks() { mockWiseFyPrechecksUtil.getSavedNetwork_failure() diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetSavedNetworksTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/GetSavedNetworksTests.kt similarity index 94% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetSavedNetworksTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/GetSavedNetworksTests.kt index 9bc37ad8..3ac6a31c 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/GetSavedNetworksTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/GetSavedNetworksTests.kt @@ -1,22 +1,30 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.TEST_SSID -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.callbacks.GetSavedNetworksCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest + import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Tests the ability to retrieve a list of saved networks on a device. * * @author Patches */ -internal class GetSavedNetworksTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class GetSavedNetworksTests : BaseUnitTest() { @Test fun sync_failure_prechecks() { mockWiseFyPrechecksUtil.getSavedNetworks_failure() diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsDeviceConnectedToMobileNetworkTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/IsDeviceConnectedToMobileNetworkTests.kt similarity index 59% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsDeviceConnectedToMobileNetworkTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/IsDeviceConnectedToMobileNetworkTests.kt index 843630a6..6eae86bc 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsDeviceConnectedToMobileNetworkTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/IsDeviceConnectedToMobileNetworkTests.kt @@ -1,16 +1,25 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build + +import com.isupatches.wisefy.internal.base.BaseUnitTest -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Tests the ability to determine if a device is connected to a mobile network. * * @author Patches */ -internal class IsDeviceConnectedToMobileNetworkTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class IsDeviceConnectedToMobileNetworkTests : BaseUnitTest() { @Test fun failure_prechecks() { mockWiseFyPrechecksUtil.isDeviceConnectedToMobileNetwork_failure() @@ -19,14 +28,14 @@ internal class IsDeviceConnectedToMobileNetworkTests : BaseAndroidJUnit4TestClas @Test fun failure() { mockWiseFyPrechecksUtil.isDeviceConnectedToMobileNetwork_success() - mockWiseFyConnectionUtil.isNetworkConnectedAndMatchesType(false) + mockWiseFyConnectionUtil.isDeviceConnectedToMobileNetwork(false) assertFalse(wisefy.isDeviceConnectedToMobileNetwork()) } @Test fun success() { mockWiseFyPrechecksUtil.isDeviceConnectedToMobileNetwork_success() mockNetworkUtil.activeNetwork() - mockWiseFyConnectionUtil.isNetworkConnectedAndMatchesType(true) + mockWiseFyConnectionUtil.isDeviceConnectedToMobileNetwork(true) assertTrue(wisefy.isDeviceConnectedToMobileNetwork()) } } diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsDeviceConnectedToMobileOrWifiNetworkTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/IsDeviceConnectedToMobileOrWifiNetworkTests.kt similarity index 75% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsDeviceConnectedToMobileOrWifiNetworkTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/IsDeviceConnectedToMobileOrWifiNetworkTests.kt index cf604ea9..49658b9f 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsDeviceConnectedToMobileOrWifiNetworkTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/IsDeviceConnectedToMobileOrWifiNetworkTests.kt @@ -1,16 +1,25 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build + +import com.isupatches.wisefy.internal.base.BaseUnitTest -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Tests the ability to determine if a device is connected to a mobile or wifi network. * * @author Patches */ -internal class IsDeviceConnectedToMobileOrWifiNetworkTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class IsDeviceConnectedToMobileOrWifiNetworkTests : BaseUnitTest() { @Test fun failure_missingPrerequisite() { mockWiseFyPrechecksUtil.isDeviceConnectedToMobileOrWifiNetwork_failure() diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsDeviceConnectedToSSIDTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/IsDeviceConnectedToSSIDTests.kt similarity index 69% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsDeviceConnectedToSSIDTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/IsDeviceConnectedToSSIDTests.kt index 065fc25c..2a7c1bb4 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsDeviceConnectedToSSIDTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/IsDeviceConnectedToSSIDTests.kt @@ -1,17 +1,25 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build + +import com.isupatches.wisefy.internal.base.BaseUnitTest -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.TEST_SSID import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Tests the ability to determine if a device is connected to an SSID. * * @author Patches */ -internal class IsDeviceConnectedToSSIDTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class IsDeviceConnectedToSSIDTests : BaseUnitTest() { @Test fun failure_prechecks() { mockWiseFyPrechecksUtil.isDeviceConnectedToSSIDChecks_failure() diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsDeviceConnectedToWifiNetworkTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/IsDeviceConnectedToWifiNetworkTests.kt similarity index 59% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsDeviceConnectedToWifiNetworkTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/IsDeviceConnectedToWifiNetworkTests.kt index 64059827..7c1d136c 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsDeviceConnectedToWifiNetworkTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/IsDeviceConnectedToWifiNetworkTests.kt @@ -1,16 +1,25 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build + +import com.isupatches.wisefy.internal.base.BaseUnitTest -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Tests the ability to determine if a device is connected to a wifi network. * * @author Patches */ -internal class IsDeviceConnectedToWifiNetworkTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class IsDeviceConnectedToWifiNetworkTests : BaseUnitTest() { @Test fun failure_missingPrerequisite() { mockWiseFyPrechecksUtil.isDeviceConnectedToWifiNetwork_failure() @@ -19,14 +28,14 @@ internal class IsDeviceConnectedToWifiNetworkTests : BaseAndroidJUnit4TestClass( @Test fun failure() { mockWiseFyPrechecksUtil.isDeviceConnectedToWifiNetwork_success() - mockWiseFyConnectionUtil.isNetworkConnectedAndMatchesType(false) + mockWiseFyConnectionUtil.isDeviceConnectedToWifiNetwork(false) assertFalse(wisefy.isDeviceConnectedToWifiNetwork()) } @Test fun success() { mockWiseFyPrechecksUtil.isDeviceConnectedToWifiNetwork_success() mockNetworkUtil.activeNetwork() - mockWiseFyConnectionUtil.isNetworkConnectedAndMatchesType(true) + mockWiseFyConnectionUtil.isDeviceConnectedToWifiNetwork(true) assertTrue(wisefy.isDeviceConnectedToWifiNetwork()) } } diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsDeviceRoamingTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/IsDeviceRoamingTests.kt similarity index 56% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsDeviceRoamingTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/IsDeviceRoamingTests.kt index 645f0fdf..243a0530 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsDeviceRoamingTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/IsDeviceRoamingTests.kt @@ -1,37 +1,40 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build + +import com.isupatches.wisefy.internal.base.BaseUnitTest -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Tests the ability to determine if a device is roaming. * * @author Patches */ -internal class IsDeviceRoamingTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class IsDeviceRoamingTests : BaseUnitTest() { @Test fun failure_missingPrerequisite() { mockWiseFyPrechecksUtil.isDeviceRoaming_failure() assertFalse(wisefy.isDeviceRoaming()) } - @Test fun failure_nullActiveNetworkInfo() { - mockWiseFyPrechecksUtil.isDeviceRoaming_success() - mockNetworkUtil.currentNetwork_null() - assertFalse(wisefy.isDeviceRoaming()) - } - @Test fun failure() { mockWiseFyPrechecksUtil.isDeviceRoaming_success() - mockNetworkUtil.isDeviceRoaming(false) + mockWiseFyConnectionUtil.isDeviceRoaming(false) assertFalse(wisefy.isDeviceRoaming()) } @Test fun success() { mockWiseFyPrechecksUtil.isDeviceRoaming_success() - mockNetworkUtil.isDeviceRoaming(true) + mockWiseFyConnectionUtil.isDeviceRoaming(true) assertTrue(wisefy.isDeviceRoaming()) } } diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetwork5gHzTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/IsNetwork5gHzTests.kt similarity index 69% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetwork5gHzTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/IsNetwork5gHzTests.kt index 3da7cb32..d9202b8a 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetwork5gHzTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/IsNetwork5gHzTests.kt @@ -1,91 +1,73 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.TEST_NETWORK_FREQUENCY_5GHZ -import com.isupatches.wisefy.TEST_NETWORK_FREQUENCY_ABOVE_5GHZ -import com.isupatches.wisefy.TEST_NETWORK_FREQUENCY_BELOW_5GHZ +import android.os.Build + +import com.isupatches.wisefy.internal.base.BaseUnitTest import org.junit.Assert.assertEquals +import org.junit.Assume.assumeTrue +import org.junit.Before import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Tests the ability to determine if a network is 5 gHz. * * @author Patches */ -internal class IsNetwork5gHzTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class IsNetwork5gHzTests : BaseUnitTest() { + + @Before fun setup() { + assumeTrue( + "Can only run on API Level 21 or newer", + Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP + ) + } @Test fun currentNetwork_failure_above5ghz() { - if (preLollipop()) { - return - } - mockWiseFyPrechecksUtil.getCurrentNetwork_success() mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_ABOVE_5GHZ) assertEquals(false, wisefy.isNetwork5gHz()) } @Test fun currentNetwork_failure_below5ghz() { - if (preLollipop()) { - return - } - mockWiseFyPrechecksUtil.getCurrentNetwork_success() mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_BELOW_5GHZ) assertEquals(false, wisefy.isNetwork5gHz()) } @Test fun currentNetwork_failure_null() { - if (preLollipop()) { - return - } - mockWiseFyPrechecksUtil.getCurrentNetwork_success() mockNetworkUtil.currentNetwork_null() assertEquals(false, wisefy.isNetwork5gHz()) } @Test fun currentNetwork_success() { - if (preLollipop()) { - return - } - mockWiseFyPrechecksUtil.getCurrentNetwork_success() mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_5GHZ) assertEquals(true, wisefy.isNetwork5gHz()) } @Test fun provideWifiInfo_failure_above5ghz() { - if (preLollipop()) { - return - } - val network = mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_ABOVE_5GHZ) assertEquals(false, wisefy.isNetwork5gHz(network)) } @Test fun provideWifiInfo_failure_below5ghz() { - if (preLollipop()) { - return - } - val network = mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_BELOW_5GHZ) assertEquals(false, wisefy.isNetwork5gHz(network)) } @Test fun provideWifiInfo_failure_null() { - if (preLollipop()) { - return - } - assertEquals(false, wisefy.isNetwork5gHz(null)) } @Test fun provideWifiInfo_success() { - if (preLollipop()) { - return - } - val mockWifiInfo = mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_5GHZ) assertEquals(true, wisefy.isNetwork5gHz(mockWifiInfo)) } diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkEAPTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/IsNetworkEAPTests.kt similarity index 69% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkEAPTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/IsNetworkEAPTests.kt index fa4c43fd..aaf06c1f 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkEAPTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/IsNetworkEAPTests.kt @@ -1,18 +1,26 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass import com.isupatches.wisefy.constants.EAP -import com.isupatches.wisefy.createMockAccessPointWithCapabilities +import com.isupatches.wisefy.internal.base.BaseUnitTest +import com.isupatches.wisefy.internal.createMockAccessPointWithCapabilities import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Tests the ability to determine if a network has EAP security. * * @author Patches */ -internal class IsNetworkEAPTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class IsNetworkEAPTests : BaseUnitTest() { @Test fun failure_differentCapability() { val scanResult = createMockAccessPointWithCapabilities("Other") diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkPSKTest.kt b/wisefy/src/test/java/com/isupatches/wisefy/IsNetworkPSKTest.kt similarity index 69% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkPSKTest.kt rename to wisefy/src/test/java/com/isupatches/wisefy/IsNetworkPSKTest.kt index dec75c53..a36d28b2 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkPSKTest.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/IsNetworkPSKTest.kt @@ -1,18 +1,26 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass import com.isupatches.wisefy.constants.PSK -import com.isupatches.wisefy.createMockAccessPointWithCapabilities +import com.isupatches.wisefy.internal.base.BaseUnitTest +import com.isupatches.wisefy.internal.createMockAccessPointWithCapabilities import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Tests the ability to determine if a network has PSK security. * * @author Patches */ -internal class IsNetworkPSKTest : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class IsNetworkPSKTest : BaseUnitTest() { @Test fun failure_differentCapability() { val scanResult = createMockAccessPointWithCapabilities("Other") diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkSavedTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/IsNetworkSavedTests.kt similarity index 68% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkSavedTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/IsNetworkSavedTests.kt index 2591c59c..e2aa5def 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkSavedTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/IsNetworkSavedTests.kt @@ -1,17 +1,24 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.TEST_SSID +import android.os.Build + +import com.isupatches.wisefy.internal.base.BaseUnitTest import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Tests the ability to determine if a network is in a device's list of saved networks. * * @author Patches */ -internal class IsNetworkSavedTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class IsNetworkSavedTests : BaseUnitTest() { @Test fun failure_missingPrerequisite() { mockWiseFyPrechecksUtil.isNetworkSaved_failure() diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkSecureTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/IsNetworkSecureTests.kt similarity index 81% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkSecureTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/IsNetworkSecureTests.kt index 22e31298..24393dc3 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkSecureTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/IsNetworkSecureTests.kt @@ -1,22 +1,30 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass import com.isupatches.wisefy.constants.EAP import com.isupatches.wisefy.constants.PSK import com.isupatches.wisefy.constants.WEP import com.isupatches.wisefy.constants.WPA import com.isupatches.wisefy.constants.WPA2 -import com.isupatches.wisefy.createMockAccessPointWithCapabilities +import com.isupatches.wisefy.internal.base.BaseUnitTest +import com.isupatches.wisefy.internal.createMockAccessPointWithCapabilities import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Tests the ability to determine if a network is secure. * * @author Patches */ -internal class IsNetworkSecureTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class IsNetworkSecureTests : BaseUnitTest() { @Test fun failure_emptyCapabilities() { val scanResult = createMockAccessPointWithCapabilities("") diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkWPA2Test.kt b/wisefy/src/test/java/com/isupatches/wisefy/IsNetworkWPA2Test.kt similarity index 70% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkWPA2Test.kt rename to wisefy/src/test/java/com/isupatches/wisefy/IsNetworkWPA2Test.kt index e6681c6c..4a1ad500 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkWPA2Test.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/IsNetworkWPA2Test.kt @@ -1,18 +1,26 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass import com.isupatches.wisefy.constants.WPA2 -import com.isupatches.wisefy.createMockAccessPointWithCapabilities +import com.isupatches.wisefy.internal.base.BaseUnitTest +import com.isupatches.wisefy.internal.createMockAccessPointWithCapabilities import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Tests the ability to determine if a network has WPA2 security. * * @author Patches */ -internal class IsNetworkWPA2Test : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class IsNetworkWPA2Test : BaseUnitTest() { @Test fun failure_differentCapability() { val scanResult = createMockAccessPointWithCapabilities("Other") diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkWPATests.kt b/wisefy/src/test/java/com/isupatches/wisefy/IsNetworkWPATests.kt similarity index 69% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkWPATests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/IsNetworkWPATests.kt index 8a517eaa..c1298435 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkWPATests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/IsNetworkWPATests.kt @@ -1,18 +1,26 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass import com.isupatches.wisefy.constants.WPA -import com.isupatches.wisefy.createMockAccessPointWithCapabilities +import com.isupatches.wisefy.internal.base.BaseUnitTest +import com.isupatches.wisefy.internal.createMockAccessPointWithCapabilities import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Tests the ability to determine if a network has WPA security. * * @author Patches */ -internal class IsNetworkWPATests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class IsNetworkWPATests : BaseUnitTest() { @Test fun failure_differentCapability() { val scanResult = createMockAccessPointWithCapabilities("Other") diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkWepTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/IsNetworkWepTests.kt similarity index 69% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkWepTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/IsNetworkWepTests.kt index 0e5c6c06..2c6118a4 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsNetworkWepTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/IsNetworkWepTests.kt @@ -1,18 +1,26 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass import com.isupatches.wisefy.constants.WEP -import com.isupatches.wisefy.createMockAccessPointWithCapabilities +import com.isupatches.wisefy.internal.base.BaseUnitTest +import com.isupatches.wisefy.internal.createMockAccessPointWithCapabilities import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Tests the ability to determine if a network has WEP security. * * @author Patches */ -internal class IsNetworkWepTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class IsNetworkWepTests : BaseUnitTest() { @Test fun failure_differentCapability() { val scanResult = createMockAccessPointWithCapabilities("Other") diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsWifiEnabledTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/IsWifiEnabledTests.kt similarity index 65% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsWifiEnabledTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/IsWifiEnabledTests.kt index 0b917fe8..a7773872 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/IsWifiEnabledTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/IsWifiEnabledTests.kt @@ -1,15 +1,24 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build + +import com.isupatches.wisefy.internal.base.BaseUnitTest -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Tests the ability to determine if wifi is enabled on a device. * * @author Patches */ -internal class IsWifiEnabledTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class IsWifiEnabledTests : BaseUnitTest() { @Test fun failure_prechecks() { mockWiseFyPrechecksUtil.isWifiEnabled_failure() diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/RemoveNetworkTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/RemoveNetworkTests.kt similarity index 92% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/RemoveNetworkTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/RemoveNetworkTests.kt index 2ef21727..ff5fa344 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/RemoveNetworkTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/RemoveNetworkTests.kt @@ -1,22 +1,30 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.TEST_SSID -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.callbacks.RemoveNetworkCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest + import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Tests the ability to remove a network from a device's list of saved networks. * * @author Patches */ -internal class RemoveNetworkTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class RemoveNetworkTests : BaseUnitTest() { @Test fun sync_failure_prechecks() { mockWiseFyPrechecksUtil.removeNetwork_failure() diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/SearchForAccessPointTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/SearchForAccessPointTests.kt similarity index 94% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/SearchForAccessPointTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/SearchForAccessPointTests.kt index 7cc45d90..52014d61 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/SearchForAccessPointTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/SearchForAccessPointTests.kt @@ -1,23 +1,30 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.TEST_SSID -import com.isupatches.wisefy.TEST_TIMEOUT -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.callbacks.SearchForAccessPointCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest + import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Used to test the functionality to search for a set of nearby access points. * * @author Patches */ -internal class SearchForAccessPointTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class SearchForAccessPointTests : BaseUnitTest() { @Test fun sync_failure_prechecks_filterDuplicates_false() { mockWiseFyPrechecksUtil.searchForAccessPoint_failure() diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/SearchForAccessPointsTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/SearchForAccessPointsTests.kt similarity index 94% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/SearchForAccessPointsTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/SearchForAccessPointsTests.kt index 713369f5..430170b7 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/SearchForAccessPointsTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/SearchForAccessPointsTests.kt @@ -1,22 +1,30 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.TEST_SSID -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.callbacks.SearchForAccessPointsCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest + import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Used to test the functionality to search for a nearby access point. * * @author Patches */ -internal class SearchForAccessPointsTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class SearchForAccessPointsTests : BaseUnitTest() { @Test fun sync_failure_prechecks_filterDuplicates_false() { mockWiseFyPrechecksUtil.searchForAccessPoints_failure() diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/SearchForSSIDTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/SearchForSSIDTests.kt similarity index 88% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/SearchForSSIDTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/SearchForSSIDTests.kt index 3b72f425..dc17cb47 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/SearchForSSIDTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/SearchForSSIDTests.kt @@ -1,23 +1,30 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.TEST_SSID -import com.isupatches.wisefy.TEST_TIMEOUT -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.callbacks.SearchForSSIDCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest + import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Used to test the functionality to search for SSIDs nearby. * * @author Patches */ -internal class SearchForSSIDTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class SearchForSSIDTests : BaseUnitTest() { @Test fun sync_failure_missingPrerequisite() { mockWiseFyPrechecksUtil.searchForSSID_failure() diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/SearchForSSIDsTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/SearchForSSIDsTests.kt similarity index 88% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/main/SearchForSSIDsTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/SearchForSSIDsTests.kt index 7a4d5d44..a381b8d9 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/main/SearchForSSIDsTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/SearchForSSIDsTests.kt @@ -1,22 +1,30 @@ -package com.isupatches.wisefy.main +package com.isupatches.wisefy + +import android.os.Build -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.TEST_SSID -import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT import com.isupatches.wisefy.callbacks.SearchForSSIDsCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER +import com.isupatches.wisefy.internal.base.BaseUnitTest + import org.junit.Assert.assertEquals import org.junit.Test +import org.junit.runner.RunWith + import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + /** * Used to test the functionality to search for SSIDs nearby. * * @author Patches */ -internal class SearchForSSIDsTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class SearchForSSIDsTests : BaseUnitTest() { @Test fun sync_failure_precheck() { mockWiseFyPrechecksUtil.searchForSSIDs_failure() diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/WiseFyPrechecksTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/WiseFyPrechecksTests.kt similarity index 87% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/WiseFyPrechecksTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/WiseFyPrechecksTests.kt index 4da62b2c..7aecd023 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/WiseFyPrechecksTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/WiseFyPrechecksTests.kt @@ -1,12 +1,18 @@ package com.isupatches.wisefy +import android.os.Build + import com.isupatches.wisefy.constants.DEFAULT_PRECHECK_RETURN_CODE import com.isupatches.wisefy.constants.MISSING_PARAMETER import com.isupatches.wisefy.constants.NETWORK_ALREADY_CONFIGURED +import com.isupatches.wisefy.internal.base.BaseUnitTest import org.junit.Assert.assertEquals - import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Used to test the WiseFyPrechecks class and functionality pertaining to being able to continue @@ -14,7 +20,9 @@ import org.junit.Test * * @author Patches */ -internal class WiseFyPrechecksTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class WiseFyPrechecksTests : BaseUnitTest() { private val wisefyPrechecks: WiseFyPrechecks = WiseFyPrechecksImpl.create(mockWiseFySearch) @@ -22,6 +30,10 @@ internal class WiseFyPrechecksTests : BaseAndroidJUnit4TestClass() { assertEquals(MISSING_PARAMETER, wisefyPrechecks.addNetworkPrechecks(null).code) } + @Test fun addNetworkPrechecks_failure_emptySSID() { + assertEquals(MISSING_PARAMETER, wisefyPrechecks.addNetworkPrechecks("").code) + } + @Test fun addNetworkPrechecks_failure_networkAlreadySaved() { mockWiseFySearchUtil.isNetworkASavedConfiguration(true) assertEquals(NETWORK_ALREADY_CONFIGURED, wisefyPrechecks.addNetworkPrechecks(TEST_SSID).code) @@ -36,10 +48,18 @@ internal class WiseFyPrechecksTests : BaseAndroidJUnit4TestClass() { assertEquals(MISSING_PARAMETER, wisefyPrechecks.addNetworkPrechecks(null, WEP_NETWORK_PASSWORD).code) } + @Test fun addNetworkPrechecks_withPassword_failure_emptySSIDParam() { + assertEquals(MISSING_PARAMETER, wisefyPrechecks.addNetworkPrechecks("", WEP_NETWORK_PASSWORD).code) + } + @Test fun addNetworkPrechecks_withPassword_failure_nullPasswordParam() { assertEquals(MISSING_PARAMETER, wisefyPrechecks.addNetworkPrechecks(WEP_NETWORK_SSID, null).code) } + @Test fun addNetworkPrechecks_withPassword_failure_emptyPasswordParam() { + assertEquals(MISSING_PARAMETER, wisefyPrechecks.addNetworkPrechecks(WEP_NETWORK_SSID, "").code) + } + @Test fun addNetworkPrechecks_withPassword_failure_networkAlreadySaved() { mockWiseFySearchUtil.isNetworkASavedConfiguration(true) assertEquals(NETWORK_ALREADY_CONFIGURED, wisefyPrechecks.addNetworkPrechecks(WEP_NETWORK_SSID, WEP_NETWORK_PASSWORD).code) @@ -73,6 +93,10 @@ internal class WiseFyPrechecksTests : BaseAndroidJUnit4TestClass() { assertEquals(DEFAULT_PRECHECK_RETURN_CODE, wisefyPrechecks.getCurrentNetworkChecks().code) } + @Test fun getCurrentNetworkInfoChecks() { + assertEquals(DEFAULT_PRECHECK_RETURN_CODE, wisefyPrechecks.getCurrentNetworkInfoChecks().code) + } + @Test fun getIPChecks() { assertEquals(DEFAULT_PRECHECK_RETURN_CODE, wisefyPrechecks.getIPChecks().code) } diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/test/WiseFyTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/WiseFyTests.kt similarity index 78% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/test/WiseFyTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/WiseFyTests.kt index 05023cec..cbfed2b1 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/test/WiseFyTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/WiseFyTests.kt @@ -1,23 +1,26 @@ -package com.isupatches.wisefy.test +package com.isupatches.wisefy +import android.os.Build import androidx.test.platform.app.InstrumentationRegistry -import com.isupatches.wisefy.BaseAndroidJUnit4TestClass -import com.isupatches.wisefy.TEST_NUMBER_OF_BARS -import com.isupatches.wisefy.TEST_RSSI_LEVEL_HIGH -import com.isupatches.wisefy.TEST_RSSI_LEVEL_LOW -import com.isupatches.wisefy.WiseFy +import com.isupatches.wisefy.internal.base.BaseUnitTest import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Tests that pertain to the builder for WiseFy or general use. * * @author Patches */ -internal class WiseFyTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class WiseFyTests : BaseUnitTest() { companion object { private const val EXPECTED_NUMBER_OF_BARS = 4 diff --git a/wisefy/src/test/java/com/isupatches/wisefy/connection/WiseFyConnectionLegacyTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/connection/WiseFyConnectionLegacyTests.kt new file mode 100644 index 00000000..ceda633d --- /dev/null +++ b/wisefy/src/test/java/com/isupatches/wisefy/connection/WiseFyConnectionLegacyTests.kt @@ -0,0 +1,313 @@ +package com.isupatches.wisefy.connection + +import android.os.Build + +import com.isupatches.wisefy.TEST_SSID +import com.isupatches.wisefy.TEST_SSID2 +import com.isupatches.wisefy.TEST_TIMEOUT +import com.isupatches.wisefy.TEST_TYPE1 +import com.isupatches.wisefy.constants.MOBILE +import com.isupatches.wisefy.constants.WIFI +import com.isupatches.wisefy.internal.base.BaseUnitTest +import org.junit.After + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * Used to test the WiseFyConnectionLegacy class and functionality determining various connection states. + * + * @author Patches + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.JELLY_BEAN]) +internal class WiseFyConnectionLegacyTests : BaseUnitTest() { + + private val wisefyConnection = WiseFyConnectionLegacy.create( + mockConnectivityManager, + mockWifiManager + ) + + @Before fun setUp() { + super.tearDown() + wisefyConnection.init() + } + + @After override fun tearDown() { + super.tearDown() + wisefyConnection.destroy() + } + + /* + * isCurrentNetworkConnectedToSSID tests + */ + + @Test fun isCurrentNetworkConnectedToSSID_failure_nullSSIDParam() { + assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(null)) + } + + @Test fun isCurrentNetworkConnectedToSSID_failure_emptySSIDParam() { + assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID("")) + } + + @Test fun isCurrentNetworkConnectedToSSID_failure_nullConnectionInfo() { + mockNetworkUtil.currentNetwork_null() + assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) + } + + @Test fun isCurrentNetworkConnectedToSSID_failure_nullSSID() { + mockNetworkUtil.currentNetwork(null) + mockNetworkUtil.currentNetworkConnectionStatus(true, true, null) + assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) + } + + @Test fun isCurrentNetworkConnectedToSSID_failure_emptySSID() { + mockNetworkUtil.currentNetwork("") + mockNetworkUtil.currentNetworkConnectionStatus(true, true, null) + assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) + } + + @Test fun isCurrentNetworkConnectedToSSID_failure_differentSSID() { + mockNetworkUtil.currentNetwork(TEST_SSID2) + mockNetworkUtil.currentNetworkConnectionStatus(true, true, null) + assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) + } + + @Test fun isCurrentNetworkConnectedToSSID_failure_notAvailable() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(false, true, null) + assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) + } + + @Test fun isCurrentNetworkConnectedToSSID_failure_notAvailableOrConnected() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(false, false, null) + assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) + } + + @Test fun isCurrentNetworkConnectedToSSID_failure_notConnected() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(true, false, null) + assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) + } + + @Test fun isCurrentNetworkConnectedToSSID_success() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(true, true, null) + assertTrue(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) + } + + /* + * isNetworkConnected tests + */ + + @Test fun isNetworkConnected_failure_nullNetworkInfoParam() { + assertFalse(wisefyConnection.isNetworkConnected()) + } + + @Test fun isNetworkConnected_failure_notAvailable() { + mockNetworkUtil.currentNetworkConnectionStatus(false, true, null) + assertFalse(wisefyConnection.isNetworkConnected()) + } + + @Test fun isNetworkConnected_failure_notAvailableOrConnected() { + mockNetworkUtil.currentNetworkConnectionStatus(false, false, null) + assertFalse(wisefyConnection.isNetworkConnected()) + } + + @Test fun isNetworkConnected_failure_notConnected() { + mockNetworkUtil.currentNetworkConnectionStatus(true, false, null) + assertFalse(wisefyConnection.isNetworkConnected()) + } + + @Test fun isNetworkConnected_success() { + mockNetworkUtil.currentNetworkConnectionStatus(true, true, null) + assertTrue(wisefyConnection.isNetworkConnected()) + } + + /* + * isDeviceConnectedToMobileNetwork tests + */ + + @Test fun isDeviceConnectedToMobileNetwork_failure_nullNetworkInfo() { + assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + @Test fun isDeviceConnectedToMobileNetwork_failure_notAvailableOrConnected() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(false, false, MOBILE) + assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + @Test fun isDeviceConnectedToMobileNetwork_failure_notAvailable() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(false, true, MOBILE) + assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + @Test fun isDeviceConnectedToMobileNetwork_failure_notConnected() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(true, false, MOBILE) + assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + @Test fun isDeviceConnectedToMobileNetwork_failure_nullTypeName() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(true, true, null) + assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + @Test fun isDeviceConnectedToMobileNetwork_failure_differentTypeName() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(true, true, WIFI) + assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + @Test fun isDeviceConnectedToMobileNetwork_failure_differentTypeName_differentCase() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(true, true, "wifi") + assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + @Test fun isDeviceConnectedToMobileNetwork_success() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(true, true, MOBILE) + assertTrue(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + @Test fun isDeviceConnectedToMobileNetwork_success_differentCase() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(true, true, "mobile") + assertTrue(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + /* + * isDeviceConnectedToWifiNetwork tests + */ + + @Test fun isDeviceConnectedToWifiNetwork_failure_nullNetworkInfo() { + assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + @Test fun isDeviceConnectedToWifiNetwork_failure_notAvailableOrConnected() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(false, false, WIFI) + assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + @Test fun isDeviceConnectedToWifiNetwork_failure_notAvailable() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(false, true, WIFI) + assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + @Test fun isDeviceConnectedToWifiNetwork_failure_notConnected() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(true, false, WIFI) + assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + @Test fun isDeviceConnectedToWifiNetwork_failure_nullTypeName() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(true, true, null) + assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + @Test fun isDeviceConnectedToWifiNetwork_failure_differentTypeName() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(true, true, MOBILE) + assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + @Test fun isDeviceConnectedToWifiNetwork_failure_differentTypeName_differentCase() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(true, true, "mobile") + assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + @Test fun isDeviceConnectedToWifiNetwork_success() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(true, true, WIFI) + assertTrue(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + @Test fun isDeviceConnectedToWifiNetwork_success_differentCase() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.currentNetworkConnectionStatus(true, true, "wifi") + assertTrue(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + /* + * isDeviceRoaming tests + */ + + @Test fun isDeviceRoaming_failure_nullNetworkInfo() { + assertFalse(wisefyConnection.isDeviceRoaming()) + } + + @Test fun isDeviceRoaming_failure() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.isDeviceRoaming(false) + assertFalse(wisefyConnection.isDeviceRoaming()) + } + + @Test fun isDeviceRoaming_success() { + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.isDeviceRoaming(true) + assertTrue(wisefyConnection.isDeviceRoaming()) + } + + /* + * waitToConnectToSSID tests + */ + + @Test fun waitToConnectToSSID_failure_nullSSIDParam() { + assertFalse(wisefyConnection.waitToConnectToSSID(null, TEST_TIMEOUT)) + } + + @Test fun waitToConnectToSSID_failure_nullConnectionInfo() { + mockNetworkUtil.currentNetwork_null() + assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) + } + + @Test fun waitToConnectToSSID_failure_nullSSID() { + mockNetworkUtil.currentNetwork(null) + assertFalse(wisefyConnection.waitToConnectToSSID(null, TEST_TIMEOUT)) + } + + @Test fun waitToConnectToSSID_failure_differentSSID() { + mockNetworkUtil.currentNetworkConnectionStatus(true, true, TEST_TYPE1) + mockNetworkUtil.currentNetwork(TEST_SSID2) + assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) + } + + @Test fun waitToConnectToSSID_failure_notAvailable() { + mockNetworkUtil.currentNetworkConnectionStatus(false, true, TEST_TYPE1) + mockNetworkUtil.currentNetwork(TEST_SSID) + assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) + } + + @Test fun waitToConnectToSSID_failure_notAvailableOrConnected() { + mockNetworkUtil.currentNetworkConnectionStatus(false, false, TEST_TYPE1) + mockNetworkUtil.currentNetwork(TEST_SSID) + assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) + } + + @Test fun waitToConnectToSSID_failure_notConnected() { + mockNetworkUtil.currentNetworkConnectionStatus(true, false, TEST_TYPE1) + mockNetworkUtil.currentNetwork(TEST_SSID) + assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) + } + + @Test fun waitToConnectToSSID_success() { + mockNetworkUtil.currentNetworkConnectionStatus(true, true, TEST_TYPE1) + mockNetworkUtil.currentNetwork(TEST_SSID) + assertTrue(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) + } +} diff --git a/wisefy/src/test/java/com/isupatches/wisefy/connection/WisefyConnectionSDK23Tests.kt b/wisefy/src/test/java/com/isupatches/wisefy/connection/WisefyConnectionSDK23Tests.kt new file mode 100644 index 00000000..90c35aa8 --- /dev/null +++ b/wisefy/src/test/java/com/isupatches/wisefy/connection/WisefyConnectionSDK23Tests.kt @@ -0,0 +1,421 @@ +package com.isupatches.wisefy.connection + +import android.net.Network +import android.os.Build + +import com.isupatches.wisefy.TEST_SSID +import com.isupatches.wisefy.TEST_SSID2 +import com.isupatches.wisefy.TEST_TIMEOUT +import com.isupatches.wisefy.internal.base.BaseUnitTest +import com.isupatches.wisefy.internal.getNetworkCapabilities + +import org.junit.After +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith + +import org.mockito.Mockito.`when` +import org.mockito.Mockito.mock + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class WisefyConnectionSDK23Tests : BaseUnitTest() { + + private val wisefyConnection = WiseFyConnectionSDK23.create( + mockConnectivityManager, + mockWifiManager + ) + + @Before fun setUp() { + super.tearDown() + wisefyConnection.init() + } + + @After override fun tearDown() { + super.tearDown() + wisefyConnection.destroy() + } + + /* + * isCurrentNetworkConnectedToSSID tests + */ + + @Test fun isCurrentNetworkConnectedToSSID_failure_nullSSIDParam() { + withAvailableNetwork() + assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(null)) + } + + @Test fun isCurrentNetworkConnectedToSSID_failure_nullConnectionInfo() { + withAvailableNetwork() + mockNetworkUtil.currentNetwork_null() + assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) + } + + @Test fun isCurrentNetworkConnectedToSSID_failure_nullSSID() { + withAvailableNetwork() + mockNetworkUtil.currentNetwork(null) + assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) + } + + @Test fun isCurrentNetworkConnectedToSSID_failure_differentSSID() { + withAvailableNetwork() + mockNetworkUtil.currentNetwork(TEST_SSID2) + assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) + } + + @Test fun isCurrentNetworkConnectedToSSID_failure_unavailable() { + mockNetworkUtil.currentNetwork(TEST_SSID) + withUnavailableNetwork() + assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) + } + + @Test fun isCurrentNetworkConnectedToSSID_failure_lost() { + mockNetworkUtil.currentNetwork(TEST_SSID) + withLostNetwork() + assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) + } + + @Test fun isCurrentNetworkConnectedToSSID_failure_losing() { + mockNetworkUtil.currentNetwork(TEST_SSID) + withLosingNetwork() + assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) + } + + @Test fun isCurrentNetworkConnectedToSSID_success() { + mockNetworkUtil.currentNetwork(TEST_SSID) + withAvailableNetwork() + assertTrue(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) + } + + /* + * isNetworkConnected tests + */ + + @Test fun isNetworkConnected_failure_unavailable() { + withUnavailableNetwork() + assertFalse(wisefyConnection.isNetworkConnected()) + } + + @Test fun isNetworkConnected_failure_lost() { + withLostNetwork() + assertFalse(wisefyConnection.isNetworkConnected()) + } + + @Test fun isNetworkConnected_failure_losing() { + withLosingNetwork() + assertFalse(wisefyConnection.isNetworkConnected()) + } + + @Test fun isNetworkConnected_success() { + withAvailableNetwork() + assertTrue(wisefyConnection.isNetworkConnected()) + } + + /* + * isDeviceConnectedToMobileNetwork tests + */ + + @Test fun isDeviceConnectedToMobileNetwork_failure_noActiveNetwork() { + assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + @Test fun isDeviceConnectedToMobileNetwork_failure_noCapabilities() { + withAvailableNetwork() + assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + @Test fun isDeviceConnectedToMobileNetwork_failure_differentTransport() { + withAvailableNetwork() + val networkCapabilities = getNetworkCapabilities( + android.net.NetworkCapabilities.TRANSPORT_WIFI, + arrayOf(android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET) + ) + setUpNetworkCapabilities(networkCapabilities) + assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + @Test fun isDeviceConnectedToMobileNetwork_failure_noInternetCapability() { + withAvailableNetwork() + val networkCapabilities = getNetworkCapabilities( + android.net.NetworkCapabilities.TRANSPORT_CELLULAR + ) + setUpNetworkCapabilities(networkCapabilities) + assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + @Test fun isDeviceConnectedToMobileNetwork_failure_unavailable() { + withUnavailableNetwork() + val networkCapabilities = getNetworkCapabilities( + android.net.NetworkCapabilities.TRANSPORT_CELLULAR, + arrayOf(android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET) + ) + setUpNetworkCapabilities(networkCapabilities) + assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + @Test fun isDeviceConnectedToMobileNetwork_failure_lost() { + withLostNetwork() + val networkCapabilities = getNetworkCapabilities( + android.net.NetworkCapabilities.TRANSPORT_CELLULAR, + arrayOf(android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET) + ) + setUpNetworkCapabilities(networkCapabilities) + assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + @Test fun isDeviceConnectedToMobileNetwork_failure_losing() { + withLosingNetwork() + val networkCapabilities = getNetworkCapabilities( + android.net.NetworkCapabilities.TRANSPORT_CELLULAR, + arrayOf(android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET) + ) + setUpNetworkCapabilities(networkCapabilities) + assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + @Test fun isDeviceConnectedToMobileNetwork_success() { + withAvailableNetwork() + val networkCapabilities = getNetworkCapabilities( + android.net.NetworkCapabilities.TRANSPORT_CELLULAR, + arrayOf(android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET) + ) + setUpNetworkCapabilities(networkCapabilities) + assertTrue(wisefyConnection.isDeviceConnectedToMobileNetwork()) + } + + /* + * isDeviceConnectedToWifiNetwork tests + */ + + @Test fun isDeviceConnectedToWifiNetwork_failure_noActiveNetwork() { + assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + @Test fun isDeviceConnectedToWifiNetwork_failure_noCapabilities() { + withAvailableNetwork() + assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + @Test fun isDeviceConnectedToWifiNetwork_failure_differentTransport() { + withAvailableNetwork() + val networkCapabilities = getNetworkCapabilities( + android.net.NetworkCapabilities.TRANSPORT_CELLULAR, + arrayOf(android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET) + ) + setUpNetworkCapabilities(networkCapabilities) + assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + @Test fun isDeviceConnectedToWifiNetwork_failure_noInternetCapability() { + withAvailableNetwork() + val networkCapabilities = getNetworkCapabilities( + android.net.NetworkCapabilities.TRANSPORT_WIFI + ) + setUpNetworkCapabilities(networkCapabilities) + assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + @Test fun isDeviceConnectedToWifiNetwork_failure_unavailable() { + withUnavailableNetwork() + val networkCapabilities = getNetworkCapabilities( + android.net.NetworkCapabilities.TRANSPORT_WIFI, + arrayOf(android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET) + ) + setUpNetworkCapabilities(networkCapabilities) + assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + @Test fun isDeviceConnectedToWifiNetwork_failure_lost() { + withLostNetwork() + val networkCapabilities = getNetworkCapabilities( + android.net.NetworkCapabilities.TRANSPORT_WIFI, + arrayOf(android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET) + ) + setUpNetworkCapabilities(networkCapabilities) + assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + @Test fun isDeviceConnectedToWifiNetwork_failure_losing() { + withLosingNetwork() + val networkCapabilities = getNetworkCapabilities( + android.net.NetworkCapabilities.TRANSPORT_WIFI, + arrayOf(android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET) + ) + setUpNetworkCapabilities(networkCapabilities) + assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + @Test fun isDeviceConnectedToWifiNetwork_success() { + withAvailableNetwork() + val networkCapabilities = getNetworkCapabilities( + android.net.NetworkCapabilities.TRANSPORT_WIFI, + arrayOf(android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET) + ) + setUpNetworkCapabilities(networkCapabilities) + assertTrue(wisefyConnection.isDeviceConnectedToWifiNetwork()) + } + + /* + * isDeviceRoaming tests + */ + + @Test fun isDeviceRoaming_failure_nullNetworkInfo() { + assumeTrue( + "Can only run on API's before Level 28", + Build.VERSION.SDK_INT < Build.VERSION_CODES.P + ) + assertFalse(wisefyConnection.isDeviceRoaming()) + } + + @Test fun isDeviceRoaming_failure() { + assumeTrue( + "Can only run on API's before Level 28", + Build.VERSION.SDK_INT < Build.VERSION_CODES.P + ) + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.isDeviceRoaming(false) + assertFalse(wisefyConnection.isDeviceRoaming()) + } + + @Test fun isDeviceRoaming_success() { + assumeTrue( + "Can only run on API's before Level 28", + Build.VERSION.SDK_INT < Build.VERSION_CODES.P + ) + mockNetworkUtil.currentNetwork(TEST_SSID) + mockNetworkUtil.isDeviceRoaming(true) + assertTrue(wisefyConnection.isDeviceRoaming()) + } + + @Config(sdk = [Build.VERSION_CODES.P]) + @Test fun isDeviceRoaming_sdk28_failure_nullNetwork() { + assumeTrue( + "Can only run on API Level 28 or newer", + Build.VERSION.SDK_INT >= Build.VERSION_CODES.P + ) + mockNetworkUtil.isDeviceRoaming(false) + assertTrue(wisefyConnection.isDeviceRoaming()) + } + + @Config(sdk = [Build.VERSION_CODES.P]) + @Test fun isDeviceRoaming_sdk28_failure_missingNotRoamingCapability() { + assumeTrue( + "Can only run on API Level 28 or newer", + Build.VERSION.SDK_INT >= Build.VERSION_CODES.P + ) + val networkCapabilities = android.net.NetworkCapabilities(null) + setUpNetworkCapabilities(networkCapabilities) + mockNetworkUtil.isDeviceRoaming(false) + assertTrue(wisefyConnection.isDeviceRoaming()) + } + + @Config(sdk = [Build.VERSION_CODES.P]) + @Test fun isDeviceRoaming_sdk28_success() { + assumeTrue( + "Can only run on API Level 28 or newer", + Build.VERSION.SDK_INT >= Build.VERSION_CODES.P + ) + val networkCapabilities = getNetworkCapabilities(arrayOf(android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING)) + setUpNetworkCapabilities(networkCapabilities) + mockNetworkUtil.isDeviceRoaming(true) + assertFalse(wisefyConnection.isDeviceRoaming()) + } + + /* + * waitToConnectToSSID tests + */ + + @Test fun waitToConnectToSSID_failure_nullSSIDParam() { + withAvailableNetwork() + assertFalse(wisefyConnection.waitToConnectToSSID(null, TEST_TIMEOUT)) + } + + @Test fun waitToConnectToSSID_failure_nullConnectionInfo() { + withAvailableNetwork() + mockNetworkUtil.currentNetwork_null() + assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) + } + + @Test fun waitToConnectToSSID_failure_nullSSID() { + withAvailableNetwork() + mockNetworkUtil.currentNetwork(null) + assertFalse(wisefyConnection.waitToConnectToSSID(null, TEST_TIMEOUT)) + } + + @Test fun waitToConnectToSSID_failure_differentSSID() { + withAvailableNetwork() + mockNetworkUtil.currentNetwork(TEST_SSID2) + assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) + } + + @Test fun waitToConnectToSSID_failure_unavailable() { + withUnavailableNetwork() + mockNetworkUtil.currentNetwork(TEST_SSID) + assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) + } + + @Test fun waitToConnectToSSID_failure_losing() { + withLosingNetwork() + mockNetworkUtil.currentNetwork(TEST_SSID) + assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) + } + + @Test fun waitToConnectToSSID_failure_lost() { + withLostNetwork() + mockNetworkUtil.currentNetwork(TEST_SSID) + assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) + } + + @Test fun waitToConnectToSSID_success() { + withAvailableNetwork() + mockNetworkUtil.currentNetwork(TEST_SSID) + assertTrue(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) + } + + /* + * + */ + + private fun setUpNetworkCapabilities(networkCapabilities: android.net.NetworkCapabilities) { + val network = mock(Network::class.java) + `when`(mockConnectivityManager.activeNetwork).thenReturn(network) + `when`(mockConnectivityManager.getNetworkCapabilities(network)).thenReturn(networkCapabilities) + (wisefyConnection as WiseFyConnectionSDK23).networkChangeCallbacks.onCapabilitiesChanged( + network, + networkCapabilities + ) + } + + /* + * Connection status helpers + */ + + private fun withAvailableNetwork() { + (wisefyConnection as WiseFyConnectionSDK23).networkChangeCallbacks.onAvailable( + mock(Network::class.java) + ) + } + + private fun withLosingNetwork() { + (wisefyConnection as WiseFyConnectionSDK23).networkChangeCallbacks.onLosing( + mock(Network::class.java), + 1 + ) + } + + private fun withLostNetwork() { + (wisefyConnection as WiseFyConnectionSDK23).networkChangeCallbacks.onLost( + mock(Network::class.java) + ) + } + + private fun withUnavailableNetwork() { + (wisefyConnection as WiseFyConnectionSDK23).networkChangeCallbacks.onUnavailable() + } +} diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/GeneratorUtil.kt b/wisefy/src/test/java/com/isupatches/wisefy/internal/GeneratorUtil.kt similarity index 97% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/GeneratorUtil.kt rename to wisefy/src/test/java/com/isupatches/wisefy/internal/GeneratorUtil.kt index 9e7aec7e..8e98e153 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/GeneratorUtil.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/internal/GeneratorUtil.kt @@ -1,9 +1,9 @@ -package com.isupatches.wisefy +package com.isupatches.wisefy.internal import android.net.wifi.ScanResult import android.net.wifi.WifiConfiguration + import org.mockito.Mockito.mock -import java.util.ArrayList /** * Creates a mock of a nearby access point for tests with specified security capabilities. diff --git a/wisefy/src/test/java/com/isupatches/wisefy/internal/NetworkCapabilitiesUtil.kt b/wisefy/src/test/java/com/isupatches/wisefy/internal/NetworkCapabilitiesUtil.kt new file mode 100644 index 00000000..ac3b7c40 --- /dev/null +++ b/wisefy/src/test/java/com/isupatches/wisefy/internal/NetworkCapabilitiesUtil.kt @@ -0,0 +1,42 @@ +package com.isupatches.wisefy.internal + +import android.net.NetworkCapabilities + +internal fun getNetworkCapabilities(transportType: Int): NetworkCapabilities { + val networkCapabilities = NetworkCapabilities(null) + ReflectionHelpers.callInstanceMethod( + networkCapabilities, + "addTransportType", + ReflectionHelpers.ClassParameter.from(Int::class.java, transportType) + ) + return networkCapabilities +} + +internal fun getNetworkCapabilities(capabilities: Array): NetworkCapabilities { + val networkCapabilities = NetworkCapabilities(null) + for (capability in capabilities) { + ReflectionHelpers.callInstanceMethod( + networkCapabilities, + "addCapability", + ReflectionHelpers.ClassParameter.from(Int::class.java, capability) + ) + } + return networkCapabilities +} + +internal fun getNetworkCapabilities(transportType: Int, capabilities: Array): NetworkCapabilities { + val networkCapabilities = NetworkCapabilities(null) + ReflectionHelpers.callInstanceMethod( + networkCapabilities, + "addTransportType", + ReflectionHelpers.ClassParameter.from(Int::class.java, transportType) + ) + for (capability in capabilities) { + ReflectionHelpers.callInstanceMethod( + networkCapabilities, + "addCapability", + ReflectionHelpers.ClassParameter.from(Int::class.java, capability) + ) + } + return networkCapabilities +} diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/NullCallbackUtil.kt b/wisefy/src/test/java/com/isupatches/wisefy/internal/NullCallbackUtil.kt similarity index 96% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/NullCallbackUtil.kt rename to wisefy/src/test/java/com/isupatches/wisefy/internal/NullCallbackUtil.kt index 24278eb1..5cee47dc 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/NullCallbackUtil.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/internal/NullCallbackUtil.kt @@ -1,8 +1,13 @@ -package com.isupatches.wisefy +package com.isupatches.wisefy.internal import android.net.wifi.WifiInfo + +import com.isupatches.wisefy.TEST_SSID +import com.isupatches.wisefy.TEST_TIMEOUT +import com.isupatches.wisefy.WiseFy import com.isupatches.wisefy.callbacks.GetFrequencyCallbacks import com.isupatches.wisefy.callbacks.GetSavedNetworksCallbacks + import org.junit.Assert.fail /** @@ -32,6 +37,7 @@ internal class NullCallbackUtil internal constructor(private val wisefy: WiseFy) * @param ssid The ssid to use when adding * @param password The password to use when adding */ + @Suppress("DEPRECATION") fun callAddWEPNetwork(ssid: String?, password: String?) { try { wisefy.addWEPNetwork(ssid, password, null) @@ -157,6 +163,14 @@ internal class NullCallbackUtil internal constructor(private val wisefy: WiseFy) } } + fun callGetIP() { + try { + wisefy.getIP(null) + } catch (npe: NullPointerException) { + fail() + } + } + /** * To try to get nearby access points with null callbacks. * diff --git a/wisefy/src/test/java/com/isupatches/wisefy/internal/ReflectionHelpers.java b/wisefy/src/test/java/com/isupatches/wisefy/internal/ReflectionHelpers.java new file mode 100644 index 00000000..42014c7d --- /dev/null +++ b/wisefy/src/test/java/com/isupatches/wisefy/internal/ReflectionHelpers.java @@ -0,0 +1,99 @@ +package com.isupatches.wisefy.internal; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** Collection of helper methods for calling methods and accessing fields reflectively. */ +@SuppressWarnings(value = {"unchecked", "TypeParameterUnusedInFormals", "NewApi"}) +public class ReflectionHelpers { + + /** + * Reflectively call an instance method on an object. + * + * @param instance Target object. + * @param methodName The method name to call. + * @param classParameters Array of parameter types and values. + * @param The return type. + * @return The return value of the method. + */ + public static R callInstanceMethod(final Object instance, final String methodName, ClassParameter... classParameters) { + try { + final Class[] classes = ClassParameter.getClasses(classParameters); + final Object[] values = ClassParameter.getValues(classParameters); + + return traverseClassHierarchy(instance.getClass(), NoSuchMethodException.class, traversalClass -> { + Method declaredMethod = traversalClass.getDeclaredMethod(methodName, classes); + declaredMethod.setAccessible(true); + return (R) declaredMethod.invoke(instance, values); + }); + } catch (InvocationTargetException e) { + if (e.getTargetException() instanceof RuntimeException) { + throw (RuntimeException) e.getTargetException(); + } + if (e.getTargetException() instanceof Error) { + throw (Error) e.getTargetException(); + } + throw new RuntimeException(e.getTargetException()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private static R traverseClassHierarchy(Class targetClass, Class exceptionClass, InsideTraversal insideTraversal) throws Exception { + Class hierarchyTraversalClass = targetClass; + while (true) { + try { + return insideTraversal.run(hierarchyTraversalClass); + } catch (Exception e) { + if (!exceptionClass.isInstance(e)) { + throw e; + } + hierarchyTraversalClass = hierarchyTraversalClass.getSuperclass(); + if (hierarchyTraversalClass == null) { + throw new RuntimeException(e); + } + } + } + } + + private interface InsideTraversal { + R run(Class traversalClass) throws Exception; + } + + /** + * Typed parameter used with reflective method calls. + * + * @param The value of the method parameter. + */ + public static class ClassParameter { + final Class clazz; + final V val; + + ClassParameter(Class clazz, V val) { + this.clazz = clazz; + this.val = val; + } + + public static ClassParameter from(Class clazz, V val) { + return new ClassParameter<>(clazz, val); + } + + static Class[] getClasses(ClassParameter... classParameters) { + Class[] classes = new Class[classParameters.length]; + for (int i = 0; i < classParameters.length; i++) { + Class paramClass = classParameters[i].clazz; + classes[i] = paramClass; + } + return classes; + } + + static Object[] getValues(ClassParameter... classParameters) { + Object[] values = new Object[classParameters.length]; + for (int i = 0; i < classParameters.length; i++) { + Object paramValue = classParameters[i].val; + values[i] = paramValue; + } + return values; + } + } +} \ No newline at end of file diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/VerificationUtil.kt b/wisefy/src/test/java/com/isupatches/wisefy/internal/VerificationUtil.kt similarity index 93% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/VerificationUtil.kt rename to wisefy/src/test/java/com/isupatches/wisefy/internal/VerificationUtil.kt index 47694735..24322fa7 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/VerificationUtil.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/internal/VerificationUtil.kt @@ -1,12 +1,17 @@ -package com.isupatches.wisefy +package com.isupatches.wisefy.internal import android.net.ConnectivityManager import android.net.wifi.WifiConfiguration import android.net.wifi.WifiManager + +import com.isupatches.wisefy.VERIFICATION_FAILURE_TIMEOUT +import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT + import org.mockito.ArgumentMatchers.any import org.mockito.ArgumentMatchers.anyBoolean import org.mockito.ArgumentMatchers.anyInt import org.mockito.Mockito.after +import org.mockito.Mockito.atLeastOnce import org.mockito.Mockito.timeout import org.mockito.Mockito.verify @@ -86,15 +91,6 @@ internal class VerificationUtil internal constructor( verify(mockConnectivityManager, after(VERIFICATION_FAILURE_TIMEOUT).times(0)).activeNetworkInfo } - /** - * To verify no attempt to get nearby access points was made. - * - * @see WifiManager.getScanResults - */ - fun didNotTryToGetNearbyAccessPoints() { - verify(mockWifiManager, after(VERIFICATION_FAILURE_TIMEOUT).times(0)).scanResults - } - /** * To verify no attempt to get saved networks was made. * @@ -104,6 +100,11 @@ internal class VerificationUtil internal constructor( verify(mockWifiManager, after(VERIFICATION_FAILURE_TIMEOUT).times(0)).configuredNetworks } + @Suppress("DEPRECATION") + fun didNotTryToScanForAccessPoints() { + verify(mockWifiManager, after(VERIFICATION_FAILURE_TIMEOUT).times(0)).startScan() + } + /** * To verify no attempt to remove a network was made. * @@ -203,4 +204,9 @@ internal class VerificationUtil internal constructor( fun triedToRemoveNetwork() { verify(mockWifiManager, timeout(VERIFICATION_SUCCESS_TIMEOUT)).removeNetwork(anyInt()) } + + @Suppress("DEPRECATION") + fun triedToScanForAccessPoints() { + verify(mockWifiManager, atLeastOnce()).startScan() + } } diff --git a/wisefy/src/test/java/com/isupatches/wisefy/internal/base/BaseUnitTest.kt b/wisefy/src/test/java/com/isupatches/wisefy/internal/base/BaseUnitTest.kt new file mode 100644 index 00000000..8f41801b --- /dev/null +++ b/wisefy/src/test/java/com/isupatches/wisefy/internal/base/BaseUnitTest.kt @@ -0,0 +1,88 @@ +package com.isupatches.wisefy.internal.base + +import android.net.ConnectivityManager +import android.net.wifi.WifiConfiguration +import android.net.wifi.WifiManager +import androidx.test.core.app.ApplicationProvider + +import com.isupatches.wisefy.VERIFICATION_SUCCESS_TIMEOUT +import com.isupatches.wisefy.WiseFy +import com.isupatches.wisefy.WiseFyPrechecks +import com.isupatches.wisefy.callbacks.AddNetworkCallbacks +import com.isupatches.wisefy.connection.WiseFyConnection +import com.isupatches.wisefy.internal.NullCallbackUtil +import com.isupatches.wisefy.internal.VerificationUtil +import com.isupatches.wisefy.internal.mock.MockNetworkUtil +import com.isupatches.wisefy.internal.mock.MockWiseFyConnectionUtil +import com.isupatches.wisefy.internal.mock.MockWiseFyPrechecksUtil +import com.isupatches.wisefy.internal.mock.MockWiseFySearchUtil +import com.isupatches.wisefy.search.WiseFySearch + +import org.junit.After + +import org.mockito.ArgumentMatchers.anyInt +import org.mockito.Mockito +import org.mockito.Mockito.mock +import org.mockito.Mockito.timeout +import org.mockito.Mockito.verify + +internal abstract class BaseUnitTest { + + protected val wisefy: WiseFy + protected val mockWiseFySearch: WiseFySearch + + protected val mockConnectivityManager: ConnectivityManager + protected val mockWifiManager: WifiManager + + protected val mockNetworkUtil: MockNetworkUtil + protected val mockWiseFyConnectionUtil: MockWiseFyConnectionUtil + protected val mockWiseFyPrechecksUtil: MockWiseFyPrechecksUtil + protected val mockWiseFySearchUtil: MockWiseFySearchUtil + + protected val nullCallbackUtil: NullCallbackUtil + + protected val verificationUtil: VerificationUtil + + /** + * Constructor. + */ + init { + val mockWiseFyConnection = mock(WiseFyConnection::class.java) + val mockWiseFyPrechecks = mock(WiseFyPrechecks::class.java) + mockWiseFySearch = mock(WiseFySearch::class.java) + + mockWifiManager = mock(WifiManager::class.java) + mockConnectivityManager = mock(ConnectivityManager::class.java) + + wisefy = WiseFy.Brains(ApplicationProvider.getApplicationContext()) + .customConnectivityManager(mockConnectivityManager) + .customWifiManager(mockWifiManager) + .customWiseFyConnection(mockWiseFyConnection) + .customWiseFyPrechecks(mockWiseFyPrechecks) + .customWiseFySearch(mockWiseFySearch) + .logging(true) + .getSmarts() + + wisefy.setupWiseFyThread(true) + + mockNetworkUtil = MockNetworkUtil(mockConnectivityManager, mockWifiManager) + + mockWiseFyConnectionUtil = MockWiseFyConnectionUtil(mockWiseFyConnection) + mockWiseFyPrechecksUtil = MockWiseFyPrechecksUtil(mockWiseFyPrechecks) + mockWiseFySearchUtil = MockWiseFySearchUtil(mockWiseFySearch) + + nullCallbackUtil = NullCallbackUtil(wisefy) + + verificationUtil = VerificationUtil(mockConnectivityManager, mockWifiManager) + } + + @After open fun tearDown() { + wisefy.dump() + } + + protected fun any(type: Class): T = Mockito.any(type) + + protected fun verifyNetworkAdded(mockCallbacks: AddNetworkCallbacks) { + verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).networkAdded(anyInt(), any(WifiConfiguration::class.java)) + } +} \ No newline at end of file diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/MockNetworkUtil.kt b/wisefy/src/test/java/com/isupatches/wisefy/internal/mock/MockNetworkUtil.kt similarity index 93% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/MockNetworkUtil.kt rename to wisefy/src/test/java/com/isupatches/wisefy/internal/mock/MockNetworkUtil.kt index a5cd0fb5..62acbf3c 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/MockNetworkUtil.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/internal/mock/MockNetworkUtil.kt @@ -1,4 +1,4 @@ -package com.isupatches.wisefy +package com.isupatches.wisefy.internal.mock import android.net.ConnectivityManager import android.net.NetworkInfo @@ -6,12 +6,23 @@ import android.net.wifi.ScanResult import android.net.wifi.WifiConfiguration import android.net.wifi.WifiInfo import android.net.wifi.WifiManager + +import com.isupatches.wisefy.TEST_IP_ADDRESS_INT +import com.isupatches.wisefy.TEST_RSSI_LEVEL +import com.isupatches.wisefy.TEST_RSSI_LEVEL_HIGH +import com.isupatches.wisefy.TEST_RSSI_LEVEL_LOW +import com.isupatches.wisefy.TEST_SSID +import com.isupatches.wisefy.TEST_SSID2 +import com.isupatches.wisefy.TEST_SSID3 import com.isupatches.wisefy.WiseFy.Companion.WIFI_MANAGER_FAILURE +import com.isupatches.wisefy.internal.createMockAccessPointWithSSID +import com.isupatches.wisefy.internal.createMockAccessPointWithSSIDAndRSSI +import com.isupatches.wisefy.internal.createSavedNetwork + import org.mockito.ArgumentMatchers.any import org.mockito.ArgumentMatchers.anyInt import org.mockito.Mockito.`when` import org.mockito.Mockito.mock -import java.util.ArrayList /** * A class that mocks lower level returns from ConnectivityManager and WifiManager. @@ -54,7 +65,8 @@ internal class MockNetworkUtil internal constructor( return mockCurrentNetwork } - internal fun currentNetworkConnectionStatus(isAvailable: Boolean, isConnected: Boolean, type: String?): NetworkInfo { + @Suppress("DEPRECATION") + internal fun currentNetworkConnectionStatus(isAvailable: Boolean, isConnected: Boolean, type: String?) { val networkInfo = mock(NetworkInfo::class.java) `when`(networkInfo.isAvailable).thenReturn(isAvailable) `when`(networkInfo.isConnected).thenReturn(isConnected) @@ -62,7 +74,6 @@ internal class MockNetworkUtil internal constructor( `when`(networkInfo.typeName).thenReturn(type) } `when`(mockConnectivityManager.activeNetworkInfo).thenReturn(networkInfo) - return networkInfo } internal fun currentNetwork_null() { @@ -101,6 +112,7 @@ internal class MockNetworkUtil internal constructor( internal fun getExpectedSSIDs(): List? = expectedSSIDs + @Suppress("DEPRECATION") internal fun isDeviceRoaming(roaming: Boolean) { val networkInfo = mock(NetworkInfo::class.java) `when`(networkInfo.isRoaming).thenReturn(roaming) @@ -111,12 +123,6 @@ internal class MockNetworkUtil internal constructor( `when`(mockWifiManager.isWifiEnabled).thenReturn(wifiEnabled) } - internal fun nearbyAccessPoints(): List { - val accessPoints = createMockAccessPointList(TEST_SSID, TEST_RSSI_LEVEL_HIGH, TEST_SSID2, TEST_RSSI_LEVEL_LOW) - `when`(mockWifiManager.scanResults).thenReturn(accessPoints) - return accessPoints - } - internal fun networkWithFrequency(frequency: Int): WifiInfo { val mockWifiInfo = mock(WifiInfo::class.java) `when`(mockWifiInfo.frequency).thenReturn(frequency) @@ -173,7 +179,7 @@ internal class MockNetworkUtil internal constructor( `when`(mockWifiManager.scanResults).thenReturn(accessPoints) } - internal fun nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(takeHighest: Boolean): List { + internal fun nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(takeHighest: Boolean) { val accessPoint1 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL_HIGH) val accessPoint2 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL_LOW) @@ -189,11 +195,9 @@ internal class MockNetworkUtil internal constructor( addToExpectedSSIDs(accessPoint1) `when`(mockWifiManager.scanResults).thenReturn(accessPoints) - - return accessPoints } - internal fun nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(takeHighest: Boolean): List { + internal fun nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(takeHighest: Boolean) { val accessPoint1 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL_LOW) val accessPoint2 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL_HIGH) @@ -209,11 +213,9 @@ internal class MockNetworkUtil internal constructor( addToExpectedSSIDs(accessPoint1) `when`(mockWifiManager.scanResults).thenReturn(accessPoints) - - return accessPoints } - internal fun nearbyAccessPoints_multipleSSIDs_sameRSSI(addSecondNetwork: Boolean): List { + internal fun nearbyAccessPoints_multipleSSIDs_sameRSSI(addSecondNetwork: Boolean) { val accessPoint1 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL) val accessPoint2 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID2, TEST_RSSI_LEVEL) @@ -234,11 +236,9 @@ internal class MockNetworkUtil internal constructor( } `when`(mockWifiManager.scanResults).thenReturn(accessPoints) - - return accessPoints } - internal fun nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(addSecondNetwork: Boolean): List { + internal fun nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(addSecondNetwork: Boolean) { val accessPoint1 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL) val accessPoint2 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL) @@ -254,8 +254,6 @@ internal class MockNetworkUtil internal constructor( addToExpectedSSIDs(accessPoint1) `when`(mockWifiManager.scanResults).thenReturn(accessPoints) - - return accessPoints } internal fun nearbyAccessPoints_multipleNonMatchingSSIDs() { @@ -279,7 +277,7 @@ internal class MockNetworkUtil internal constructor( } internal fun nearbyAccessPoints_nullAccessPoint() { - val accessPoints = emptyList() + val accessPoints = arrayListOf(null) `when`(mockWifiManager.scanResults).thenReturn(accessPoints) } @@ -300,6 +298,10 @@ internal class MockNetworkUtil internal constructor( `when`(mockWifiManager.configuredNetworks).thenReturn(ArrayList()) } + internal fun savedNetworks_listWithNull() { + `when`(mockWifiManager.configuredNetworks).thenReturn(arrayListOf(null)) + } + internal fun savedNetworks_matchingSSID() { val savedNetwork = createSavedNetwork(TEST_SSID) diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/MockWiseFyConnectionUtil.kt b/wisefy/src/test/java/com/isupatches/wisefy/internal/mock/MockWiseFyConnectionUtil.kt similarity index 60% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/MockWiseFyConnectionUtil.kt rename to wisefy/src/test/java/com/isupatches/wisefy/internal/mock/MockWiseFyConnectionUtil.kt index 092d1b50..66bb2c60 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/MockWiseFyConnectionUtil.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/internal/mock/MockWiseFyConnectionUtil.kt @@ -1,7 +1,7 @@ -package com.isupatches.wisefy +package com.isupatches.wisefy.internal.mock + +import com.isupatches.wisefy.connection.WiseFyConnection -import android.net.NetworkInfo -import org.mockito.ArgumentMatchers.any import org.mockito.ArgumentMatchers.anyInt import org.mockito.ArgumentMatchers.anyString import org.mockito.Mockito.`when` @@ -29,25 +29,40 @@ internal class MockWiseFyConnectionUtil internal constructor( } /** - * Mocks if the device is connected to a network. + * To mock if the device is connected to a mobile network. * - * @param connected Whether the device is connected or not + * @param connected If the device is connected to a mobile network * - * @see WiseFyConnection.isNetworkConnected + * @see WiseFyConnection.isDeviceConnectedToMobileNetwork */ - fun isNetworkConnected(connected: Boolean) { - `when`(mockWiseFyConnection.isNetworkConnected(any(NetworkInfo::class.java))).thenReturn(connected) + fun isDeviceConnectedToMobileNetwork(connected: Boolean) { + `when`(mockWiseFyConnection.isDeviceConnectedToMobileNetwork()).thenReturn(connected) } /** - * To mock if the device is connected to a mobile network. + * To mock if the device is connected to a Wifi network. * - * @param connectedAndMatchesType If the device is connected to a mobile network + * @param connected If the device is connected to a Wifi network * - * @see WiseFyConnection.isNetworkConnectedAndMatchesType + * @see WiseFyConnection.isDeviceConnectedToWifiNetwork */ - fun isNetworkConnectedAndMatchesType(connectedAndMatchesType: Boolean) { - `when`(mockWiseFyConnection.isNetworkConnectedAndMatchesType(any(NetworkInfo::class.java), anyString())).thenReturn(connectedAndMatchesType) + fun isDeviceConnectedToWifiNetwork(connected: Boolean) { + `when`(mockWiseFyConnection.isDeviceConnectedToWifiNetwork()).thenReturn(connected) + } + + fun isDeviceRoaming(roaming: Boolean) { + `when`(mockWiseFyConnection.isDeviceRoaming()).thenReturn(roaming) + } + + /** + * Mocks if the device is connected to a network. + * + * @param connected Whether the device is connected or not + * + * @see WiseFyConnection.isNetworkConnected + */ + fun isNetworkConnected(connected: Boolean) { + `when`(mockWiseFyConnection.isNetworkConnected()).thenReturn(connected) } /** diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/MockWiseFyPrechecksUtil.kt b/wisefy/src/test/java/com/isupatches/wisefy/internal/mock/MockWiseFyPrechecksUtil.kt similarity index 98% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/MockWiseFyPrechecksUtil.kt rename to wisefy/src/test/java/com/isupatches/wisefy/internal/mock/MockWiseFyPrechecksUtil.kt index 1bfb3300..7141e16c 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/MockWiseFyPrechecksUtil.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/internal/mock/MockWiseFyPrechecksUtil.kt @@ -1,5 +1,8 @@ -package com.isupatches.wisefy +package com.isupatches.wisefy.internal.mock +import com.isupatches.wisefy.DEFAULT_PRECHECK_RESULT +import com.isupatches.wisefy.PrecheckResult +import com.isupatches.wisefy.WiseFyPrechecks import com.isupatches.wisefy.constants.MISSING_PARAMETER import org.mockito.ArgumentMatchers.anyString diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/MockWiseFySearchUtil.kt b/wisefy/src/test/java/com/isupatches/wisefy/internal/mock/MockWiseFySearchUtil.kt similarity index 84% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/MockWiseFySearchUtil.kt rename to wisefy/src/test/java/com/isupatches/wisefy/internal/mock/MockWiseFySearchUtil.kt index 8723cb69..7b9f4094 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/MockWiseFySearchUtil.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/internal/mock/MockWiseFySearchUtil.kt @@ -1,13 +1,22 @@ -package com.isupatches.wisefy +package com.isupatches.wisefy.internal.mock import android.net.wifi.ScanResult import android.net.wifi.WifiConfiguration -import org.mockito.ArgumentMatchers + +import com.isupatches.wisefy.TEST_RSSI_LEVEL +import com.isupatches.wisefy.TEST_RSSI_LEVEL_HIGH +import com.isupatches.wisefy.TEST_RSSI_LEVEL_LOW +import com.isupatches.wisefy.TEST_SSID +import com.isupatches.wisefy.TEST_SSID2 +import com.isupatches.wisefy.internal.createMockAccessPointList +import com.isupatches.wisefy.internal.createMockAccessPointWithSSIDAndRSSI +import com.isupatches.wisefy.internal.createSavedNetwork +import com.isupatches.wisefy.search.WiseFySearch + import org.mockito.ArgumentMatchers.anyBoolean import org.mockito.ArgumentMatchers.anyInt import org.mockito.ArgumentMatchers.anyString import org.mockito.Mockito.`when` -import java.util.ArrayList /** * A class to mock returns from the WiseFySearch class. @@ -18,6 +27,16 @@ import java.util.ArrayList */ internal class MockWiseFySearchUtil internal constructor(private val mockWiseFySearch: WiseFySearch) { + fun nearbyAccessPoints_null(filterDuplicates: Boolean) { + `when`(mockWiseFySearch.getNearbyAccessPoints(filterDuplicates)).thenReturn(null) + } + + fun nearbyAccessPoints_success(filterDuplicates: Boolean): List { + val accessPoints = createMockAccessPointList(TEST_SSID, TEST_RSSI_LEVEL_HIGH, TEST_SSID2, TEST_RSSI_LEVEL_LOW) + `when`(mockWiseFySearch.getNearbyAccessPoints(filterDuplicates)).thenReturn(accessPoints) + return accessPoints + } + /** * Mocks no nearby access point. * @@ -135,16 +154,4 @@ internal class MockWiseFySearchUtil internal constructor(private val mockWiseFyS fun isNetworkASavedConfiguration(saved: Boolean) { `when`(mockWiseFySearch.isNetworkASavedConfiguration(anyString())).thenReturn(saved) } - - /** - * Mocks a basic return of two networks from WiseFySearch#removeEntriesWithLowerSignalStrength. - * - * @see WiseFySearch.removeEntriesWithLowerSignalStrength - * @return List of ScanResults - The mocked networks that will be returned - */ - fun removeEntriesWithLowerSignalStrength(): List { - val accessPoints = createMockAccessPointList(TEST_SSID, TEST_RSSI_LEVEL_HIGH, TEST_SSID2, TEST_RSSI_LEVEL_LOW) - `when`(mockWiseFySearch.removeEntriesWithLowerSignalStrength(ArgumentMatchers.anyList())).thenReturn(accessPoints) - return accessPoints - } } diff --git a/wisefy/src/test/java/com/isupatches/wisefy/main/PublicApiVisibilityTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/main/PublicApiVisibilityTests.kt index 69a444ac..43407de6 100644 --- a/wisefy/src/test/java/com/isupatches/wisefy/main/PublicApiVisibilityTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/main/PublicApiVisibilityTests.kt @@ -1,5 +1,6 @@ package com.isupatches.wisefy.main +import android.net.NetworkInfo import android.net.wifi.ScanResult import android.net.wifi.WifiConfiguration import android.net.wifi.WifiInfo @@ -23,6 +24,7 @@ import com.isupatches.wisefy.callbacks.DisableWifiCallbacks import com.isupatches.wisefy.callbacks.DisconnectFromCurrentNetworkCallbacks import com.isupatches.wisefy.callbacks.EnableWifiCallbacks import com.isupatches.wisefy.callbacks.GetCurrentNetworkCallbacks +import com.isupatches.wisefy.callbacks.GetCurrentNetworkInfoCallbacks import com.isupatches.wisefy.callbacks.GetFrequencyCallbacks import com.isupatches.wisefy.callbacks.GetIPCallbacks import com.isupatches.wisefy.callbacks.GetNearbyAccessPointsCallbacks @@ -189,12 +191,31 @@ class PublicApiVisibilityTests { override fun wisefyFailure(wisefyFailureCode: Int) { } + override fun noCurrentNetwork() { + } + override fun retrievedCurrentNetwork(currentNetwork: WifiInfo) { } }) verify(wisefy).getCurrentNetwork(any(GetCurrentNetworkCallbacks::class.java)) } + @Test fun getCurrentNetworkInfo_apis() { + wisefy.getCurrentNetworkInfo() + verify(wisefy).getCurrentNetworkInfo() + wisefy.getCurrentNetworkInfo(object : GetCurrentNetworkInfoCallbacks { + override fun noCurrentNetworkInfo() { + } + + override fun retrievedCurrentNetworkInfo(currentNetworkDetails: NetworkInfo) { + } + + override fun wisefyFailure(wisefyFailureCode: Int) { + } + }) + verify(wisefy).getCurrentNetworkInfo(any(GetCurrentNetworkInfoCallbacks::class.java)) + } + @Test fun getFrequency_apis() { wisefy.getFrequency() verify(wisefy).getFrequency() @@ -248,6 +269,9 @@ class PublicApiVisibilityTests { override fun retrievedNearbyAccessPoints(nearbyAccessPoints: List) { } + override fun noAccessPointsFound() { + } + override fun wisefyFailure(wisefyFailureCode: Int) { } }) diff --git a/wisefy/src/test/java/com/isupatches/wisefy/search/AbstractWiseFySearchTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/search/AbstractWiseFySearchTests.kt new file mode 100644 index 00000000..4a167946 --- /dev/null +++ b/wisefy/src/test/java/com/isupatches/wisefy/search/AbstractWiseFySearchTests.kt @@ -0,0 +1,204 @@ +package com.isupatches.wisefy.search + +import android.os.Build + +import com.isupatches.wisefy.TEST_REGEX +import com.isupatches.wisefy.TEST_SSID +import com.isupatches.wisefy.internal.base.BaseUnitTest + +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@Suppress("LargeClass", "TooManyFunctions") +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.JELLY_BEAN, Build.VERSION_CODES.P]) +internal class AbstractWiseFySearchTests : BaseUnitTest() { + + private val wisefySearch: WiseFySearch = WiseFySearchSDK23.create(mockWifiManager) + + /* + * findSavedNetworkByRegex tests + */ + + @Test fun findSavedNetworkByRegex_failure_nullSavedNetworkList() { + mockNetworkUtil.savedNetworks_nullList() + assertEquals(null, wisefySearch.findSavedNetworkByRegex(TEST_SSID)) + } + + @Test fun findSavedNetworkByRegex_failure_emptySavedNetworkList() { + mockNetworkUtil.savedNetworks_emptyList() + assertEquals(null, wisefySearch.findSavedNetworkByRegex(TEST_SSID)) + } + + @Test fun findSavedNetworkByRegex_failure_nullSavedNetworkInList() { + mockNetworkUtil.savedNetworks_listWithNull() + assertEquals(null, wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) + } + + @Test fun findSavedNetworkByRegex_failure_nullWifiConfiguration() { + mockNetworkUtil.savedNetworks_nullSavedNetwork() + assertEquals(null, wisefySearch.findSavedNetworkByRegex(TEST_SSID)) + } + + @Test fun findSavedNetworkByRegex_failure_nullSSID() { + mockNetworkUtil.savedNetworks_nullSSID() + assertEquals(null, wisefySearch.findSavedNetworkByRegex(TEST_SSID)) + } + + @Test fun findSavedNetworkByRegex_failure_nonMatchingSSID() { + mockNetworkUtil.savedNetworks_nonMatchingSSID() + assertEquals(null, wisefySearch.findSavedNetworkByRegex(TEST_SSID)) + } + + @Test fun findSavedNetworkByRegex_failure_multipleNonMatchingSSIDs() { + mockNetworkUtil.savedNetworks_multipleNonMatchingSSIDs() + assertEquals(null, wisefySearch.findSavedNetworkByRegex(TEST_SSID)) + } + + @Test fun findSavedNetworkByRegex_success() { + mockNetworkUtil.savedNetworks_matchingSSID() + assertEquals(mockNetworkUtil.getExpectedSavedNetwork(), wisefySearch.findSavedNetworkByRegex(TEST_SSID)) + } + + @Test fun findSavedNetworkByRegex_success_multipleMatchingSSIDs() { + mockNetworkUtil.savedNetworks_multipleMatchingSSIDs() + assertEquals(mockNetworkUtil.getExpectedSavedNetwork(), wisefySearch.findSavedNetworkByRegex(TEST_SSID)) + } + + @Test fun findSavedNetworkByRegex_success_multipleSSIDs_nonRegex() { + mockNetworkUtil.savedNetworks_multipleSSIDs(false) + assertEquals(mockNetworkUtil.getExpectedSavedNetwork(), wisefySearch.findSavedNetworkByRegex(TEST_SSID)) + } + + @Test fun findSavedNetworkByRegex_success_multipleSSIDs_regex() { + mockNetworkUtil.savedNetworks_multipleSSIDs(true) + assertEquals(mockNetworkUtil.getExpectedSavedNetwork(), wisefySearch.findSavedNetworkByRegex(TEST_REGEX)) + } + + /* + * findSavedNetworksMatchingRegex tests + */ + + @Test fun findSavedNetworksMatchingRegex_failure_nullSavedNetworkList() { + mockNetworkUtil.savedNetworks_nullList() + assertEquals(null, wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) + } + + @Test fun findSavedNetworksMatchingRegex_failure_emptySavedNetworkList() { + mockNetworkUtil.savedNetworks_emptyList() + assertEquals(null, wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) + } + + @Test fun findSavedNetworksMatchingRegex_failure_nullSavedNetworkInList() { + mockNetworkUtil.savedNetworks_listWithNull() + assertEquals(null, wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) + } + + @Test fun findSavedNetworksMatchingRegex_failure_nullWifiConfiguration() { + mockNetworkUtil.savedNetworks_nullSavedNetwork() + assertEquals(null, wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) + } + + @Test fun findSavedNetworksMatchingRegex_failure_nullSSID() { + mockNetworkUtil.savedNetworks_nullSSID() + assertEquals(null, wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) + } + + @Test fun findSavedNetworksMatchingRegex_failure_nonMatchingSSID() { + mockNetworkUtil.savedNetworks_nonMatchingSSID() + assertEquals(null, wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) + } + + @Test fun findSavedNetworksMatchingRegex_failure_multipleNonMatchingSSIDs() { + mockNetworkUtil.savedNetworks_multipleNonMatchingSSIDs() + assertEquals(null, wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) + } + + @Test fun findSavedNetworksMatchingRegex_success() { + mockNetworkUtil.savedNetworks_matchingSSID() + assertEquals(mockNetworkUtil.getExpectedSavedNetworks(), wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) + } + + @Test fun findSavedNetworksMatchingRegex_success_multipleMatchingSSIDs() { + mockNetworkUtil.savedNetworks_multipleMatchingSSIDs() + assertEquals(mockNetworkUtil.getExpectedSavedNetworks(), wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) + } + + @Test fun findSavedNetworksMatchingRegex_success_multipleSSIDs_nonRegex() { + mockNetworkUtil.savedNetworks_multipleSSIDs(false) + assertEquals(mockNetworkUtil.getExpectedSavedNetworks(), wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) + } + + @Test fun findSavedNetworksMatchingRegex_success_multipleSSIDs_regex() { + mockNetworkUtil.savedNetworks_multipleSSIDs(true) + assertEquals(mockNetworkUtil.getExpectedSavedNetworks(), wisefySearch.findSavedNetworksMatchingRegex(TEST_REGEX)) + } + + /* + * isNetworkASavedConfiguration tests + */ + + @Test fun isNetworkASavedConfiguration_failure_nullSSIDParam() { + mockNetworkUtil.savedNetworks_nullList() + assertEquals(false, wisefySearch.isNetworkASavedConfiguration(null)) + } + + @Test fun isNetworkASavedConfiguration_failure_emptySSIDParam() { + mockNetworkUtil.savedNetworks_nullList() + assertEquals(false, wisefySearch.isNetworkASavedConfiguration("")) + } + + @Test fun isNetworkASavedConfiguration_failure_nullSavedNetworkList() { + mockNetworkUtil.savedNetworks_nullList() + assertEquals(false, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) + } + + @Test fun isNetworkASavedConfiguration_failure_emptySavedNetworkList() { + mockNetworkUtil.savedNetworks_emptyList() + assertEquals(false, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) + } + + @Test fun isNetworkASavedConfiguration_failure_nullWifiConfiguration() { + mockNetworkUtil.savedNetworks_nullSavedNetwork() + assertEquals(false, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) + } + + @Test fun isNetworkASavedConfiguration_failure_nullSSID() { + mockNetworkUtil.savedNetworks_nullSSID() + assertEquals(false, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) + } + + @Test fun isNetworkASavedConfiguration_failure_nonMatchingSSID() { + mockNetworkUtil.savedNetworks_nonMatchingSSID() + assertEquals(false, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) + } + + @Test fun isNetworkASavedConfiguration_failure_multipleNonMatchingSSIDs() { + mockNetworkUtil.savedNetworks_multipleNonMatchingSSIDs() + assertEquals(false, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) + } + + @Test fun isNetworkASavedConfiguration_success() { + mockNetworkUtil.savedNetworks_matchingSSID() + assertEquals(true, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) + } + + @Test fun isNetworkASavedConfiguration_success_multipleMatchingSSIDs() { + mockNetworkUtil.savedNetworks_multipleMatchingSSIDs() + assertEquals(true, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) + } + + @Test fun isNetworkASavedConfiguration_success_multipleSSIDs_nonRegex() { + mockNetworkUtil.savedNetworks_multipleSSIDs(false) + assertEquals(true, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) + } + + @Test fun isNetworkASavedConfiguration_success_multipleSSIDs_regex() { + mockNetworkUtil.savedNetworks_multipleSSIDs(true) + assertEquals(true, wisefySearch.isNetworkASavedConfiguration(TEST_REGEX)) + } +} \ No newline at end of file diff --git a/wisefy/src/androidTest/java/com/isupatches/wisefy/WiseFySearchTests.kt b/wisefy/src/test/java/com/isupatches/wisefy/search/WiseFySearchLegacyTests.kt similarity index 67% rename from wisefy/src/androidTest/java/com/isupatches/wisefy/WiseFySearchTests.kt rename to wisefy/src/test/java/com/isupatches/wisefy/search/WiseFySearchLegacyTests.kt index 4dc177f5..c8cb32a0 100644 --- a/wisefy/src/androidTest/java/com/isupatches/wisefy/WiseFySearchTests.kt +++ b/wisefy/src/test/java/com/isupatches/wisefy/search/WiseFySearchLegacyTests.kt @@ -1,8 +1,19 @@ -package com.isupatches.wisefy +package com.isupatches.wisefy.search -import org.junit.Assert.assertEquals +import android.os.Build + +import com.isupatches.wisefy.TEST_REGEX +import com.isupatches.wisefy.TEST_SSID +import com.isupatches.wisefy.TEST_TIMEOUT +import com.isupatches.wisefy.internal.base.BaseUnitTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config /** * Used to test the WiseFySearch class and search capabilities. @@ -12,9 +23,11 @@ import org.junit.Test * @author Patches */ @Suppress("LargeClass", "TooManyFunctions") -internal class WiseFySearchTests : BaseAndroidJUnit4TestClass() { +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.JELLY_BEAN]) +internal class WiseFySearchLegacyTests : BaseUnitTest() { - private val wisefySearch: WiseFySearch = WiseFySearchImpl.create(mockWifiManager) + private val wisefySearch: WiseFySearch = WiseFySearchLegacy.create(mockWifiManager) /* * findAccessPointByRegex tests @@ -23,357 +36,297 @@ internal class WiseFySearchTests : BaseAndroidJUnit4TestClass() { @Test fun findAccessPointByRegex_failure_nullAccessPoints_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_nullList() assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_failure_nullAccessPoints_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_nullList() assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_failure_emptyAccessPointList_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_emptyList() assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_failure_emptyAccessPointList_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_emptyList() assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_failure_nullAccessPoint_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_nullAccessPoint() assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_failure_nullAccessPoint_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_nullAccessPoint() assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_failure_nullSSID_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_nullSSID() assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_failure_nullSSID_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_nullSSID() assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_failure_nonMatchingSSID_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_nonMatchingSSID() assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_failure_nonMatchingSSID_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_nonMatchingSSID() assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_failure_multipleNonMatchingSSIDs_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_multipleNonMatchingSSIDs() assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_failure_multipleNonMatchingSSIDs_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_multipleNonMatchingSSIDs() assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_success_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_matchingSSID() assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_success_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_matchingSSID() assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_success_multipleSSIDs_sameRSSI_nonRegex_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(false) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_success_multipleSSIDs_sameRSSI_nonRegex_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(false) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_success_multipleSSIDs_sameRSSI_regex_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(true) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_REGEX, TEST_TIMEOUT, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_success_multipleSSIDs_sameRSSI_regex_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(true) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_REGEX, TEST_TIMEOUT, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_success_multipleMatchingSSIDs_accessPoint1HasHigherRSSI_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(false) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_success_multipleMatchesSSIDs_accessPoint1HasHigherRSSI_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(true) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_success_multipleMatchingSSIDs_accessPoint2HasHigherRSSI_takeHighest_false() { val takeHighest = false mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(takeHighest) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, takeHighest)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_success_multipleMatchesSSIDs_accessPoint2HasHigherRSSI_takeHighest_true() { val takeHighest = true mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(takeHighest) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, takeHighest)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_success_multipleMatchingSSIDs_sameRSSI_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(false) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointByRegex_success_multipleMatchesSSIDs_sameRSSI_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(false) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.triedToScanForAccessPoints() } /* - * findAccessPointsMatchingRegex tests - */ + * findAccessPointsMatchingRegex tests + */ @Test fun findAccessPointsMatchingRegex_failure_nullAccessPoints_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_nullList() assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_failure_nullAccessPoints_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_nullList() assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_failure_emptyAccessPointList_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_emptyList() assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_failure_emptyAccessPointList_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_emptyList() assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_failure_nullAccessPoint_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_nullAccessPoint() assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_failure_nullAccessPoint_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_nullAccessPoint() assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_failure_nullSSID_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_nullSSID() assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_failure_nullSSID_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_nullSSID() assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_failure_nonMatchingSSID_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_nonMatchingSSID() assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_failure_nonMatchingSSID_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_nonMatchingSSID() assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_failure_multipleNonMatchingSSIDs_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_multipleNonMatchingSSIDs() assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_failure_multipleNonMatchingSSIDs_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_multipleNonMatchingSSIDs() assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_success_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_matchingSSID() assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_success_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_matchingSSID() assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_success_multipleSSIDs_nonRegex_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(false) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_success_multipleSSIDs_nonRegex_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(false) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_success_multipleSSIDs_regex_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(true) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_REGEX, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_success_multipleSSIDs_regex_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(true) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_REGEX, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_success_multipleMatchingSSIDs_accessPoint1HasHigherRSSI_takeHighest_false() { val takeHighest = false mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(takeHighest) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, takeHighest)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_success_multipleMatchingSSIDs_accessPoint1HasHigherRSSI_takeHighest_true() { val takeHighest = true mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(takeHighest) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, takeHighest)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_success_multipleMatchingSSIDs_accessPoint2HasHigherRSSI_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(false) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_success_multipleMatchingSSIDs_accessPoint2HasHigherRSSI_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(true) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_success_multipleMatchingSSIDs_sameRSSI_takeHighest_false() { mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(true) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findAccessPointsMatchingRegex_success_multipleMatchingSSIDs_sameRSSI_takeHighest_true() { mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(true) assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) - } - - /* - * findSavedNetworkByRegex tests - */ - - @Test fun findSavedNetworkByRegex_failure_nullSavedNetworkList() { - mockNetworkUtil.savedNetworks_nullList() - assertEquals(null, wisefySearch.findSavedNetworkByRegex(TEST_SSID)) - } - - @Test fun findSavedNetworkByRegex_failure_emptySavedNetworkList() { - mockNetworkUtil.savedNetworks_emptyList() - assertEquals(null, wisefySearch.findSavedNetworkByRegex(TEST_SSID)) - } - - @Test fun findSavedNetworkByRegex_failure_nullWifiConfiguration() { - mockNetworkUtil.savedNetworks_nullSavedNetwork() - assertEquals(null, wisefySearch.findSavedNetworkByRegex(TEST_SSID)) - } - - @Test fun findSavedNetworkByRegex_failure_nullSSID() { - mockNetworkUtil.savedNetworks_nullSSID() - assertEquals(null, wisefySearch.findSavedNetworkByRegex(TEST_SSID)) - } - - @Test fun findSavedNetworkByRegex_failure_nonMatchingSSID() { - mockNetworkUtil.savedNetworks_nonMatchingSSID() - assertEquals(null, wisefySearch.findSavedNetworkByRegex(TEST_SSID)) - } - - @Test fun findSavedNetworkByRegex_failure_multipleNonMatchingSSIDs() { - mockNetworkUtil.savedNetworks_multipleNonMatchingSSIDs() - assertEquals(null, wisefySearch.findSavedNetworkByRegex(TEST_SSID)) - } - - @Test fun findSavedNetworkByRegex_success() { - mockNetworkUtil.savedNetworks_matchingSSID() - assertEquals(mockNetworkUtil.getExpectedSavedNetwork(), wisefySearch.findSavedNetworkByRegex(TEST_SSID)) - } - - @Test fun findSavedNetworkByRegex_success_multipleMatchingSSIDs() { - mockNetworkUtil.savedNetworks_multipleMatchingSSIDs() - assertEquals(mockNetworkUtil.getExpectedSavedNetwork(), wisefySearch.findSavedNetworkByRegex(TEST_SSID)) - } - - @Test fun findSavedNetworkByRegex_success_multipleSSIDs_nonRegex() { - mockNetworkUtil.savedNetworks_multipleSSIDs(false) - assertEquals(mockNetworkUtil.getExpectedSavedNetwork(), wisefySearch.findSavedNetworkByRegex(TEST_SSID)) - } - - @Test fun findSavedNetworkByRegex_success_multipleSSIDs_regex() { - mockNetworkUtil.savedNetworks_multipleSSIDs(true) - assertEquals(mockNetworkUtil.getExpectedSavedNetwork(), wisefySearch.findSavedNetworkByRegex(TEST_REGEX)) - } - - /* - * findSavedNetworksMatchingRegex tests - */ - - @Test fun findSavedNetworksMatchingRegex_failure_nullSavedNetworkList() { - mockNetworkUtil.savedNetworks_nullList() - assertEquals(null, wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) - } - - @Test fun findSavedNetworksMatchingRegex_failure_emptySavedNetworkList() { - mockNetworkUtil.savedNetworks_emptyList() - assertEquals(null, wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) - } - - @Test fun findSavedNetworksMatchingRegex_failure_nullWifiConfiguration() { - mockNetworkUtil.savedNetworks_nullSavedNetwork() - assertEquals(null, wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) - } - - @Test fun findSavedNetworksMatchingRegex_failure_nullSSID() { - mockNetworkUtil.savedNetworks_nullSSID() - assertEquals(null, wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) - } - - @Test fun findSavedNetworksMatchingRegex_failure_nonMatchingSSID() { - mockNetworkUtil.savedNetworks_nonMatchingSSID() - assertEquals(null, wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) - } - - @Test fun findSavedNetworksMatchingRegex_failure_multipleNonMatchingSSIDs() { - mockNetworkUtil.savedNetworks_multipleNonMatchingSSIDs() - assertEquals(null, wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) - } - - @Test fun findSavedNetworksMatchingRegex_success() { - mockNetworkUtil.savedNetworks_matchingSSID() - assertEquals(mockNetworkUtil.getExpectedSavedNetworks(), wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) - } - - @Test fun findSavedNetworksMatchingRegex_success_multipleMatchingSSIDs() { - mockNetworkUtil.savedNetworks_multipleMatchingSSIDs() - assertEquals(mockNetworkUtil.getExpectedSavedNetworks(), wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) - } - - @Test fun findSavedNetworksMatchingRegex_success_multipleSSIDs_nonRegex() { - mockNetworkUtil.savedNetworks_multipleSSIDs(false) - assertEquals(mockNetworkUtil.getExpectedSavedNetworks(), wisefySearch.findSavedNetworksMatchingRegex(TEST_SSID)) - } - - @Test fun findSavedNetworksMatchingRegex_success_multipleSSIDs_regex() { - mockNetworkUtil.savedNetworks_multipleSSIDs(true) - assertEquals(mockNetworkUtil.getExpectedSavedNetworks(), wisefySearch.findSavedNetworksMatchingRegex(TEST_REGEX)) + verificationUtil.triedToScanForAccessPoints() } /* @@ -383,143 +336,172 @@ internal class WiseFySearchTests : BaseAndroidJUnit4TestClass() { @Test fun findSSIDsMatchingRegex_failure_nullAccessPoints() { mockNetworkUtil.nearbyAccessPoints_nullList() assertEquals(null, wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findSSIDsMatchingRegex_failure_emptySavedNetworkList() { mockNetworkUtil.nearbyAccessPoints_emptyList() assertEquals(null, wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findSSIDsMatchingRegex_failure_nullAccessPoint() { mockNetworkUtil.nearbyAccessPoints_nullAccessPoint() assertEquals(null, wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findSSIDsMatchingRegex_failure_nullSSID() { mockNetworkUtil.nearbyAccessPoints_nullSSID() assertEquals(null, wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findSSIDsMatchingRegex_failure_nonMatchingSSID() { mockNetworkUtil.nearbyAccessPoints_nonMatchingSSID() assertEquals(null, wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findSSIDsMatchingRegex_failure_multipleNonMatchingSSIDs() { mockNetworkUtil.nearbyAccessPoints_multipleNonMatchingSSIDs() assertEquals(null, wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findSSIDsMatchingRegex_success() { mockNetworkUtil.nearbyAccessPoints_matchingSSID() assertEquals(mockNetworkUtil.getExpectedSSIDs(), wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findSSIDsMatchingRegex_success_multipleMatchingSSIDs_sameRSSI() { mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(true) assertEquals(mockNetworkUtil.getExpectedSSIDs(), wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findSSIDsMatchingRegex_success_multipleMatchingSSIDs_accessPoint1HasHigherRSSI() { mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(true) assertEquals(mockNetworkUtil.getExpectedSSIDs(), wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findSSIDsMatchingRegex_success_multipleMatchingSSIDs_accessPoint2HasHigherRSSI() { mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(true) assertEquals(mockNetworkUtil.getExpectedSSIDs(), wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findSSIDsMatchingRegex_success_multipleSSIDs_nonRegex() { mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(false) assertEquals(mockNetworkUtil.getExpectedSSIDs(), wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.triedToScanForAccessPoints() } @Test fun findSSIDsMatchingRegex_success_multipleSSIDs_regex() { mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(true) assertEquals(mockNetworkUtil.getExpectedSSIDs(), wisefySearch.findSSIDsMatchingRegex(TEST_REGEX)) + verificationUtil.triedToScanForAccessPoints() } /* - * isNetworkASavedConfiguration tests + * getNearbyAccessPoints tests */ - @Test fun isNetworkASavedConfiguration_failure_nullSSIDParam() { - mockNetworkUtil.savedNetworks_nullList() - assertEquals(false, wisefySearch.isNetworkASavedConfiguration(null)) - } - - @Test fun isNetworkASavedConfiguration_failure_nullSavedNetworkList() { - mockNetworkUtil.savedNetworks_nullList() - assertEquals(false, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) - } - - @Test fun isNetworkASavedConfiguration_failure_emptySavedNetworkList() { - mockNetworkUtil.savedNetworks_emptyList() - assertEquals(false, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) - } - - @Test fun isNetworkASavedConfiguration_failure_nullWifiConfiguration() { - mockNetworkUtil.savedNetworks_nullSavedNetwork() - assertEquals(false, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) + @Test fun getNearbyAccessPoints_nullAccessPointList_filterDuplicates_true() { + mockNetworkUtil.nearbyAccessPoints_nullList() + val accessPoints = wisefySearch.getNearbyAccessPoints(true) + assertNull(accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.triedToScanForAccessPoints() } - @Test fun isNetworkASavedConfiguration_failure_nullSSID() { - mockNetworkUtil.savedNetworks_nullSSID() - assertEquals(false, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) + @Test fun getNearbyAccessPoints_emptyAccessPointList_filterDuplicates_true() { + mockNetworkUtil.nearbyAccessPoints_emptyList() + val accessPoints = wisefySearch.getNearbyAccessPoints(true) + assertNull(accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.triedToScanForAccessPoints() } - @Test fun isNetworkASavedConfiguration_failure_nonMatchingSSID() { - mockNetworkUtil.savedNetworks_nonMatchingSSID() - assertEquals(false, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) + @Test fun getNearbyAccessPoints_differentSSIDs_filterDuplicates_true() { + mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(true) + val accessPoints = wisefySearch.getNearbyAccessPoints(true) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.triedToScanForAccessPoints() } - @Test fun isNetworkASavedConfiguration_failure_multipleNonMatchingSSIDs() { - mockNetworkUtil.savedNetworks_multipleNonMatchingSSIDs() - assertEquals(false, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) + @Test fun getNearbyAccessPoints_sameSignalLevels_filterDuplicates_true() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(false) + val accessPoints = wisefySearch.getNearbyAccessPoints(true) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.triedToScanForAccessPoints() } - @Test fun isNetworkASavedConfiguration_success() { - mockNetworkUtil.savedNetworks_matchingSSID() - assertEquals(true, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) + @Test fun getNearbyAccessPoints_accessPoint1Higher_filterDuplicates_true() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(true) + val accessPoints = wisefySearch.getNearbyAccessPoints(true) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.triedToScanForAccessPoints() } - @Test fun isNetworkASavedConfiguration_success_multipleMatchingSSIDs() { - mockNetworkUtil.savedNetworks_multipleMatchingSSIDs() - assertEquals(true, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) + @Test fun getNearbyAccessPoints_accessPoint2Higher_filterDuplicates_true() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(true) + val accessPoints = wisefySearch.getNearbyAccessPoints(true) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.triedToScanForAccessPoints() } - @Test fun isNetworkASavedConfiguration_success_multipleSSIDs_nonRegex() { - mockNetworkUtil.savedNetworks_multipleSSIDs(false) - assertEquals(true, wisefySearch.isNetworkASavedConfiguration(TEST_SSID)) + @Test fun getNearbyAccessPoints_nullAccessPointList_filterDuplicates_false() { + mockNetworkUtil.nearbyAccessPoints_nullList() + val accessPoints = wisefySearch.getNearbyAccessPoints(false) + assertNull(accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.triedToScanForAccessPoints() } - @Test fun isNetworkASavedConfiguration_success_multipleSSIDs_regex() { - mockNetworkUtil.savedNetworks_multipleSSIDs(true) - assertEquals(true, wisefySearch.isNetworkASavedConfiguration(TEST_REGEX)) + @Test fun getNearbyAccessPoints_emptyAccessPointList_filterDuplicates_false() { + mockNetworkUtil.nearbyAccessPoints_emptyList() + val accessPoints = wisefySearch.getNearbyAccessPoints(false) + assertNull(accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.triedToScanForAccessPoints() } - /* - * removeEntriesWithLowerSignalStrength tests - */ - - @Test fun removeEntriesWithLowerSignalStrength_differentSSIDs() { - val accessPoints = mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(true) - assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.removeEntriesWithLowerSignalStrength(accessPoints)) + @Test fun getNearbyAccessPoints_differentSSIDs_filterDuplicates_false() { + mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(true) + val accessPoints = wisefySearch.getNearbyAccessPoints(false) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.triedToScanForAccessPoints() } - @Test fun removeEntriesWithLowerSignalStrength_sameSignalLevels() { - val accessPoints = mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(false) - assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.removeEntriesWithLowerSignalStrength(accessPoints)) + @Test fun getNearbyAccessPoints_sameSignalLevels_filterDuplicates_false() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(true) + val accessPoints = wisefySearch.getNearbyAccessPoints(false) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.triedToScanForAccessPoints() } - @Test fun removeEntriesWithLowerSignalStrength_accessPoint1Higher() { - val accessPoints = mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(true) - assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.removeEntriesWithLowerSignalStrength(accessPoints)) + @Test fun getNearbyAccessPoints_accessPoint1Higher_filterDuplicates_false() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(false) + val accessPoints = wisefySearch.getNearbyAccessPoints(false) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.triedToScanForAccessPoints() } - @Test fun removeEntriesWithLowerSignalStrength_accessPoint2Higher() { - val accessPoints = mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(true) - assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.removeEntriesWithLowerSignalStrength(accessPoints)) + @Test fun getNearbyAccessPoints_accessPoint2Higher_filterDuplicates_false() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(false) + val accessPoints = wisefySearch.getNearbyAccessPoints(false) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.triedToScanForAccessPoints() } } diff --git a/wisefy/src/test/java/com/isupatches/wisefy/search/WiseFySearchSdk23Tests.kt b/wisefy/src/test/java/com/isupatches/wisefy/search/WiseFySearchSdk23Tests.kt new file mode 100644 index 00000000..4b065040 --- /dev/null +++ b/wisefy/src/test/java/com/isupatches/wisefy/search/WiseFySearchSdk23Tests.kt @@ -0,0 +1,484 @@ +package com.isupatches.wisefy.search + +import android.os.Build + +import com.isupatches.wisefy.TEST_REGEX +import com.isupatches.wisefy.TEST_SSID +import com.isupatches.wisefy.TEST_TIMEOUT +import com.isupatches.wisefy.internal.base.BaseUnitTest + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith + +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@Suppress("LargeClass", "TooManyFunctions") +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.M]) +internal class WiseFySearchSdk23Tests : BaseUnitTest() { + + private val wisefySearch: WiseFySearch = WiseFySearchSDK23.create(mockWifiManager) + + /* + * findAccessPointByRegex tests + */ + + @Test fun findAccessPointByRegex_failure_nullAccessPoints_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_nullList() + assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_failure_nullAccessPoints_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_nullList() + assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_failure_emptyAccessPointList_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_emptyList() + assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_failure_emptyAccessPointList_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_emptyList() + assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_failure_nullAccessPoint_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_nullAccessPoint() + assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_failure_nullAccessPoint_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_nullAccessPoint() + assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_failure_nullSSID_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_nullSSID() + assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_failure_nullSSID_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_nullSSID() + assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_failure_nonMatchingSSID_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_nonMatchingSSID() + assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_failure_nonMatchingSSID_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_nonMatchingSSID() + assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_failure_multipleNonMatchingSSIDs_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_multipleNonMatchingSSIDs() + assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_failure_multipleNonMatchingSSIDs_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_multipleNonMatchingSSIDs() + assertEquals(null, wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_success_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_matchingSSID() + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_success_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_matchingSSID() + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_success_multipleSSIDs_sameRSSI_nonRegex_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(false) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_success_multipleSSIDs_sameRSSI_nonRegex_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(false) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_success_multipleSSIDs_sameRSSI_regex_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(true) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_REGEX, TEST_TIMEOUT, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_success_multipleSSIDs_sameRSSI_regex_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(true) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_REGEX, TEST_TIMEOUT, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_success_multipleMatchingSSIDs_accessPoint1HasHigherRSSI_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(false) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_success_multipleMatchesSSIDs_accessPoint1HasHigherRSSI_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(true) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_success_multipleMatchingSSIDs_accessPoint2HasHigherRSSI_takeHighest_false() { + val takeHighest = false + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(takeHighest) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, takeHighest)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_success_multipleMatchesSSIDs_accessPoint2HasHigherRSSI_takeHighest_true() { + val takeHighest = true + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(takeHighest) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, takeHighest)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_success_multipleMatchingSSIDs_sameRSSI_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(false) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointByRegex_success_multipleMatchesSSIDs_sameRSSI_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(false) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoint(), wisefySearch.findAccessPointByRegex(TEST_SSID, TEST_TIMEOUT, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + /* + * findAccessPointsMatchingRegex tests + */ + + @Test fun findAccessPointsMatchingRegex_failure_nullAccessPoints_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_nullList() + assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_failure_nullAccessPoints_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_nullList() + assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_failure_emptyAccessPointList_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_emptyList() + assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_failure_emptyAccessPointList_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_emptyList() + assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_failure_nullAccessPoint_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_nullAccessPoint() + assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_failure_nullAccessPoint_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_nullAccessPoint() + assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_failure_nullSSID_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_nullSSID() + assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_failure_nullSSID_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_nullSSID() + assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_failure_nonMatchingSSID_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_nonMatchingSSID() + assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_failure_nonMatchingSSID_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_nonMatchingSSID() + assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_failure_multipleNonMatchingSSIDs_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_multipleNonMatchingSSIDs() + assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_failure_multipleNonMatchingSSIDs_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_multipleNonMatchingSSIDs() + assertEquals(null, wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_success_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_matchingSSID() + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_success_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_matchingSSID() + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_success_multipleSSIDs_nonRegex_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(false) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_success_multipleSSIDs_nonRegex_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(false) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_success_multipleSSIDs_regex_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(true) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_REGEX, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_success_multipleSSIDs_regex_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(true) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_REGEX, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_success_multipleMatchingSSIDs_accessPoint1HasHigherRSSI_takeHighest_false() { + val takeHighest = false + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(takeHighest) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, takeHighest)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_success_multipleMatchingSSIDs_accessPoint1HasHigherRSSI_takeHighest_true() { + val takeHighest = true + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(takeHighest) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, takeHighest)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_success_multipleMatchingSSIDs_accessPoint2HasHigherRSSI_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(false) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_success_multipleMatchingSSIDs_accessPoint2HasHigherRSSI_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(true) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_success_multipleMatchingSSIDs_sameRSSI_takeHighest_false() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(true) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, false)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findAccessPointsMatchingRegex_success_multipleMatchingSSIDs_sameRSSI_takeHighest_true() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(true) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), wisefySearch.findAccessPointsMatchingRegex(TEST_SSID, true)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + /* + * findSSIDsMatchingRegex tests + */ + + @Test fun findSSIDsMatchingRegex_failure_nullAccessPoints() { + mockNetworkUtil.nearbyAccessPoints_nullList() + assertEquals(null, wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findSSIDsMatchingRegex_failure_emptySavedNetworkList() { + mockNetworkUtil.nearbyAccessPoints_emptyList() + assertEquals(null, wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findSSIDsMatchingRegex_failure_nullAccessPoint() { + mockNetworkUtil.nearbyAccessPoints_nullAccessPoint() + assertEquals(null, wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findSSIDsMatchingRegex_failure_nullSSID() { + mockNetworkUtil.nearbyAccessPoints_nullSSID() + assertEquals(null, wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findSSIDsMatchingRegex_failure_nonMatchingSSID() { + mockNetworkUtil.nearbyAccessPoints_nonMatchingSSID() + assertEquals(null, wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findSSIDsMatchingRegex_failure_multipleNonMatchingSSIDs() { + mockNetworkUtil.nearbyAccessPoints_multipleNonMatchingSSIDs() + assertEquals(null, wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findSSIDsMatchingRegex_success() { + mockNetworkUtil.nearbyAccessPoints_matchingSSID() + assertEquals(mockNetworkUtil.getExpectedSSIDs(), wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findSSIDsMatchingRegex_success_multipleMatchingSSIDs_sameRSSI() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(true) + assertEquals(mockNetworkUtil.getExpectedSSIDs(), wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findSSIDsMatchingRegex_success_multipleMatchingSSIDs_accessPoint1HasHigherRSSI() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(true) + assertEquals(mockNetworkUtil.getExpectedSSIDs(), wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findSSIDsMatchingRegex_success_multipleMatchingSSIDs_accessPoint2HasHigherRSSI() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(true) + assertEquals(mockNetworkUtil.getExpectedSSIDs(), wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findSSIDsMatchingRegex_success_multipleSSIDs_nonRegex() { + mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(false) + assertEquals(mockNetworkUtil.getExpectedSSIDs(), wisefySearch.findSSIDsMatchingRegex(TEST_SSID)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun findSSIDsMatchingRegex_success_multipleSSIDs_regex() { + mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(true) + assertEquals(mockNetworkUtil.getExpectedSSIDs(), wisefySearch.findSSIDsMatchingRegex(TEST_REGEX)) + verificationUtil.didNotTryToScanForAccessPoints() + } + + /* + * getNearbyAccessPoints tests + */ + + @Test fun getNearbyAccessPoints_differentSSIDs_filterDuplicates_true() { + mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(true) + val accessPoints = wisefySearch.getNearbyAccessPoints(true) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun getNearbyAccessPoints_sameSignalLevels_filterDuplicates_true() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(false) + val accessPoints = wisefySearch.getNearbyAccessPoints(true) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun getNearbyAccessPoints_accessPoint1Higher_filterDuplicates_true() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(true) + val accessPoints = wisefySearch.getNearbyAccessPoints(true) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun getNearbyAccessPoints_accessPoint2Higher_filterDuplicates_true() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(true) + val accessPoints = wisefySearch.getNearbyAccessPoints(true) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun getNearbyAccessPoints_nullAccessPointList_filterDuplicates_false() { + mockNetworkUtil.nearbyAccessPoints_nullList() + val accessPoints = wisefySearch.getNearbyAccessPoints(false) + assertNull(accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun getNearbyAccessPoints_emptyAccessPointList_filterDuplicates_false() { + mockNetworkUtil.nearbyAccessPoints_emptyList() + val accessPoints = wisefySearch.getNearbyAccessPoints(false) + assertNull(accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun getNearbyAccessPoints_differentSSIDs_filterDuplicates_false() { + mockNetworkUtil.nearbyAccessPoints_multipleSSIDs_sameRSSI(true) + val accessPoints = wisefySearch.getNearbyAccessPoints(false) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun getNearbyAccessPoints_sameSignalLevels_filterDuplicates_false() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(true) + val accessPoints = wisefySearch.getNearbyAccessPoints(false) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun getNearbyAccessPoints_accessPoint1Higher_filterDuplicates_false() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(false) + val accessPoints = wisefySearch.getNearbyAccessPoints(false) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.didNotTryToScanForAccessPoints() + } + + @Test fun getNearbyAccessPoints_accessPoint2Higher_filterDuplicates_false() { + mockNetworkUtil.nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(false) + val accessPoints = wisefySearch.getNearbyAccessPoints(false) + assertEquals(mockNetworkUtil.getExpectedNearbyAccessPoints(), accessPoints) + verificationUtil.triedToGetNearbyAccessPoints() + verificationUtil.didNotTryToScanForAccessPoints() + } +} diff --git a/wisefysample/.gitignore b/wisefysample/.gitignore new file mode 100644 index 00000000..796b96d1 --- /dev/null +++ b/wisefysample/.gitignore @@ -0,0 +1 @@ +/build diff --git a/wisefysample/build.gradle b/wisefysample/build.gradle new file mode 100644 index 00000000..f63b8e60 --- /dev/null +++ b/wisefysample/build.gradle @@ -0,0 +1,61 @@ +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-android-extensions' +apply plugin: "kotlin-kapt" + +android { + + compileSdkVersion rootProject.ext.MAX_SDK_VERSION + buildToolsVersion rootProject.ext.BUILD_TOOLS_VERSION + + defaultConfig { + applicationId "com.isupatches.wisefysample" + minSdkVersion rootProject.ext.MIN_SDK_VERSION + targetSdkVersion rootProject.ext.MAX_SDK_VERSION + versionCode rootProject.ext.VERSION_CODE + versionName rootProject.ext.VERSION_NAME + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + implementation project(':wisefy') + + implementation fileTree(dir: 'libs', include: ['*.jar']) + + implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + + // Android X + implementation "androidx.appcompat:appcompat:$androidx_appcompat_version" + implementation "androidx.constraintlayout:constraintlayout:$androidx_constraintlayout_version" + implementation "androidx.core:core-ktx:$androidx_core_ktx_version" + + // Google Material + implementation "com.google.android.material:material:$google_android_material_version" + + // Dependency Injection + implementation "com.google.dagger:dagger:$dagger_version" + kapt "com.google.dagger:dagger-compiler:$dagger_version" + implementation "com.google.dagger:dagger-android-support:$dagger_version" + kapt "com.google.dagger:dagger-android-processor:$dagger_version" + + // Rx + implementation "io.reactivex.rxjava2:rxandroid:$rxandroid_version" + implementation "io.reactivex.rxjava2:rxjava:$rxjava_version" + + // Unit test dependencies + testImplementation "junit:junit:$junit_version" + + // Instrumentation test dependencies + androidTestImplementation "androidx.test.espresso:espresso-core:$androidx_espresso_core_version" + androidTestImplementation "androidx.test.espresso:espresso-intents:$androidx_espresso_core_version" + androidTestImplementation "androidx.test:runner:$androidx_test_runner_version" + androidTestImplementation "androidx.test:rules:$androidx_test_runner_version" +} diff --git a/wisefysample/proguard-rules.pro b/wisefysample/proguard-rules.pro new file mode 100644 index 00000000..e69de29b diff --git a/wisefysample/src/main/AndroidManifest.xml b/wisefysample/src/main/AndroidManifest.xml new file mode 100644 index 00000000..824c1ab2 --- /dev/null +++ b/wisefysample/src/main/AndroidManifest.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/MainApplication.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/MainApplication.kt new file mode 100644 index 00000000..bae2a977 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/MainApplication.kt @@ -0,0 +1,63 @@ +package com.isupatches.wisefysample + +import android.annotation.SuppressLint +import android.app.Activity +import android.app.Application +import android.content.Context +import androidx.fragment.app.Fragment + +import com.isupatches.wisefysample.internal.di.PermissionsModule +import com.isupatches.wisefysample.internal.di.PreferencesModule +import com.isupatches.wisefysample.internal.di.ScreenBindingsModule + +import dagger.BindsInstance +import dagger.Component +import dagger.android.DispatchingAndroidInjector +import dagger.android.HasActivityInjector +import dagger.android.support.AndroidSupportInjectionModule +import dagger.android.support.HasSupportFragmentInjector + +import javax.inject.Inject +import javax.inject.Singleton + +@SuppressLint("Registered") +internal open class MainApplication : Application(), HasActivityInjector, HasSupportFragmentInjector { + + override fun onCreate() { + super.onCreate() + initializeDependencyInjection() + } + + private fun initializeDependencyInjection() { + mainApplicationComponent = DaggerMainApplication_MainApplicationComponent.builder() + .application(this) + .build() + mainApplicationComponent.inject(this) + } + + @Inject lateinit var activityInjector: DispatchingAndroidInjector + override fun activityInjector() = activityInjector + + @Inject lateinit var supportFragmentInject: DispatchingAndroidInjector + override fun supportFragmentInjector() = supportFragmentInject + + private lateinit var mainApplicationComponent: MainApplicationComponent + + @Singleton + @Component(modules = [ + AndroidSupportInjectionModule::class, + ScreenBindingsModule::class, + PermissionsModule::class, + PreferencesModule::class + ]) + interface MainApplicationComponent { + + fun inject(mainApplication: MainApplication) + + @Component.Builder interface Builder { + fun build(): MainApplicationComponent + + @BindsInstance fun application(application: Context): Builder + } + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/BaseActivity.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/BaseActivity.kt new file mode 100644 index 00000000..3d54cca2 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/BaseActivity.kt @@ -0,0 +1,14 @@ +package com.isupatches.wisefysample.internal.base + +import android.os.Bundle +import androidx.appcompat.app.AppCompatActivity + +import dagger.android.AndroidInjection + +internal abstract class BaseActivity : AppCompatActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + AndroidInjection.inject(this) + super.onCreate(savedInstanceState) + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/BaseFragment.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/BaseFragment.kt new file mode 100644 index 00000000..47fddc47 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/BaseFragment.kt @@ -0,0 +1,63 @@ +package com.isupatches.wisefysample.internal.base + +import android.content.Context +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.annotation.LayoutRes +import androidx.fragment.app.Fragment + +import com.isupatches.wisefy.WiseFy +import com.isupatches.wisefy.constants.WiseFyCode +import com.isupatches.wisefysample.internal.util.PermissionUtil +import com.isupatches.wisefysample.internal.util.displayShortToast + +import dagger.android.support.AndroidSupportInjection + +import javax.inject.Inject + +internal abstract class BaseFragment : Fragment() { + + @get:LayoutRes abstract val layoutRes: Int + + protected lateinit var wiseFy: WiseFy + @Inject lateinit var permissionUtil: PermissionUtil + + override fun onAttach(context: Context) { + AndroidSupportInjection.inject(this) + super.onAttach(context) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + wiseFy = WiseFy.Brains(activity!!).logging(true).getSmarts() + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(layoutRes, container, false) + } + + override fun onDestroy() { + super.onDestroy() + wiseFy.dump() + } + + protected fun displayWiseFyFailureWithCode(@WiseFyCode wiseFyFailureCode: Int) { + displayShortToast("WiseFy Failure. Code: $wiseFyFailureCode") + } + + protected fun isPermissionGranted(permission: String, requestCode: Int): Boolean { + return if (permissionUtil.permissionNotGranted(activity!!, permission)) { + if (shouldShowRequestPermissionRationale(permission)) { + // Display dialog or rationale for requesting permission here + requestPermissions(arrayOf(permission), requestCode) + } else { + requestPermissions(arrayOf(permission), requestCode) + } + false + } else { + true + } + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/BaseMvp.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/BaseMvp.kt new file mode 100644 index 00000000..c3da0fd1 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/BaseMvp.kt @@ -0,0 +1,17 @@ +package com.isupatches.wisefysample.internal.base + +import com.isupatches.wisefy.constants.WiseFyCode + +internal interface BaseMvp { + + interface View { + fun displayWiseFyFailure(@WiseFyCode wiseFyFailureCode: Int) + } + + interface Presenter { + fun attachView(view: V) + fun detachView() + + fun displayWiseFyFailure(@WiseFyCode wiseFyFailureCode: Int) + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/BasePresenter.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/BasePresenter.kt new file mode 100644 index 00000000..b6bf1109 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/BasePresenter.kt @@ -0,0 +1,52 @@ +package com.isupatches.wisefysample.internal.base + +import android.util.Log + +import com.isupatches.wisefy.constants.WiseFyCode + +import io.reactivex.android.schedulers.AndroidSchedulers + +internal abstract class BasePresenter : BaseMvp.Presenter { + + companion object { + private val TAG = BasePresenter::class.java.simpleName + } + + private var view: V? = null + + private val mainThread = AndroidSchedulers.mainThread() + + private val isViewAttached: Boolean + get() = view != null + + override fun attachView(view: V) { + this.view = view + } + + override fun detachView() { + view = null + } + + protected fun getView(): V = view ?: throw ViewNotAttachedException() + + protected fun doSafelyWithView(viewCommand: (view: V) -> Unit) { + if (isViewAttached) { + mainThread.scheduleDirect { + if (isViewAttached) { + viewCommand(view!!) + } else { + Log.w(TAG, "ViewCommand was scheduled., but view is now detached!") + } + } + } + } + + override fun displayWiseFyFailure(@WiseFyCode wiseFyFailureCode: Int) { + doSafelyWithView { view -> view.displayWiseFyFailure(wiseFyFailureCode) } + } + + @Suppress("unused") + protected interface ViewCommand { + fun command(view: V?) + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/ViewNotAttachedException.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/ViewNotAttachedException.kt new file mode 100644 index 00000000..bc75cea4 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/base/ViewNotAttachedException.kt @@ -0,0 +1,5 @@ +package com.isupatches.wisefysample.internal.base + +import java.lang.RuntimeException + +internal class ViewNotAttachedException : RuntimeException("New view attached. Did you forget to call attachView()?") diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/di/PermissionsModule.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/di/PermissionsModule.kt new file mode 100644 index 00000000..eb40647b --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/di/PermissionsModule.kt @@ -0,0 +1,12 @@ +package com.isupatches.wisefysample.internal.di + +import com.isupatches.wisefysample.internal.util.PermissionUtil +import com.isupatches.wisefysample.internal.util.PermissionsUtilImpl + +import dagger.Binds +import dagger.Module + +@Suppress("unused") +@Module internal interface PermissionsModule { + @Binds fun bindPermissionUtil(impl: PermissionsUtilImpl): PermissionUtil +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/di/PreferencesModule.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/di/PreferencesModule.kt new file mode 100644 index 00000000..894d4da3 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/di/PreferencesModule.kt @@ -0,0 +1,39 @@ +package com.isupatches.wisefysample.internal.di + +import android.content.Context +import androidx.annotation.StringRes + +import com.isupatches.wisefysample.R +import com.isupatches.wisefysample.internal.preferences.AddNetworkStore +import com.isupatches.wisefysample.internal.preferences.RemoveNetworkStore +import com.isupatches.wisefysample.internal.preferences.SearchStore +import com.isupatches.wisefysample.internal.preferences.SharedPreferencesAddNetworkStore +import com.isupatches.wisefysample.internal.preferences.SharedPreferencesRemoveNetworkStore +import com.isupatches.wisefysample.internal.preferences.SharedPreferencesSearchStore + +import dagger.Module +import dagger.Provides + +import javax.inject.Singleton + +@Suppress("unused") +@Module internal object PreferencesModule { + + @JvmStatic @Singleton @Provides + fun provideAddNetworkStore(context: Context): AddNetworkStore = SharedPreferencesAddNetworkStore( + sharedPreferences = getSharedPreferences(context, R.string.preferences_add_network_data) + ) + + @JvmStatic @Singleton @Provides + fun provideRemoveNetworkStore(context: Context): RemoveNetworkStore = SharedPreferencesRemoveNetworkStore( + sharedPreferences = getSharedPreferences(context, R.string.preferences_remove_network_data) + ) + + @JvmStatic @Singleton @Provides + fun provideSearchStore(context: Context): SearchStore = SharedPreferencesSearchStore( + sharedPreferences = getSharedPreferences(context, R.string.preferences_search_data) + ) + + private fun getSharedPreferences(context: Context, @StringRes prefKey: Int) = + context.getSharedPreferences(context.getString(prefKey), Context.MODE_PRIVATE) +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/di/ScreenBindingsModule.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/di/ScreenBindingsModule.kt new file mode 100644 index 00000000..7957505a --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/di/ScreenBindingsModule.kt @@ -0,0 +1,16 @@ +package com.isupatches.wisefysample.internal.di + +import com.isupatches.wisefysample.ui.main.MainActivity + +import dagger.Module +import dagger.android.ContributesAndroidInjector + +@Suppress("unused") +@Module +internal interface ScreenBindingsModule { + + @ContributesAndroidInjector(modules = [ + MainActivity.FragmentBindings::class + ]) + fun mainActivity(): MainActivity +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/models/NetworkType.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/models/NetworkType.kt new file mode 100644 index 00000000..a21f87a6 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/models/NetworkType.kt @@ -0,0 +1,19 @@ +package com.isupatches.wisefysample.internal.models + +internal enum class NetworkType(val intVal: Int) { + OPEN(0), + WEP(1), + WPA2(2); + + companion object { + + fun of(intVal: Int): NetworkType { + return when (intVal) { + OPEN.intVal -> OPEN + WEP.intVal -> WEP + WPA2.intVal -> WPA2 + else -> throw IllegalArgumentException("Invalid NetworkType, intVal: $intVal") + } + } + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/models/SearchType.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/models/SearchType.kt new file mode 100644 index 00000000..d580f97b --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/models/SearchType.kt @@ -0,0 +1,19 @@ +package com.isupatches.wisefysample.internal.models + +internal enum class SearchType(val intVal: Int) { + ACCESS_POINT(0), + SSID(1), + SAVED_NETWORK(2); + + companion object { + + fun of(intVal: Int): SearchType { + return when (intVal) { + ACCESS_POINT.intVal -> ACCESS_POINT + SSID.intVal -> SSID + SAVED_NETWORK.intVal -> SAVED_NETWORK + else -> throw IllegalArgumentException("Invalid SearchType, intVal: $intVal") + } + } + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/nav/MainRouter.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/nav/MainRouter.kt new file mode 100644 index 00000000..63d87fb3 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/nav/MainRouter.kt @@ -0,0 +1,24 @@ +package com.isupatches.wisefysample.internal.nav + +import androidx.fragment.app.Fragment +import androidx.fragment.app.FragmentActivity +import com.google.android.material.bottomnavigation.BottomNavigationView + +import com.isupatches.wisefysample.R + +internal fun BottomNavigationView.selectItem(actionId: Int) { + menu.findItem(actionId)?.isChecked = true +} + +internal fun openFragment(activity: FragmentActivity?, fragment: Fragment, tag: String) { + activity?.let { + val supportFragmentManager = it.supportFragmentManager + (0 until supportFragmentManager.backStackEntryCount).forEach { _ -> + supportFragmentManager.popBackStack() + } + with(supportFragmentManager.beginTransaction()) { + replace(R.id.fragmentContainer, fragment, tag) + commit() + } + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/AddNetworkStore.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/AddNetworkStore.kt new file mode 100644 index 00000000..cc66b2c6 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/AddNetworkStore.kt @@ -0,0 +1,74 @@ +package com.isupatches.wisefysample.internal.preferences + +import android.content.SharedPreferences +import androidx.core.content.edit + +import com.isupatches.wisefysample.internal.models.NetworkType + +private const val PREF_NETWORK_TYPE = "network type" +private const val PREF_LAST_USED_NETWORK_NAME = "last used network name" +private const val PREF_LAST_USED_NETWORK_PASSWORD = "last used network password" + +internal interface AddNetworkStore { + fun clear() + + fun getNetworkType(): NetworkType + fun getLastUsedNetworkName(): String + fun getLastUsedNetworkPassword(): String + + fun setNetworkType(networkType: NetworkType) + fun setLastUsedNetworkName(lastUsedNetworkName: String) + fun setLastUsedNetworkPassword(lastUsedNetworkPassword: String) +} + +internal class SharedPreferencesAddNetworkStore( + private val sharedPreferences: SharedPreferences +) : AddNetworkStore { + + override fun clear() { + sharedPreferences.edit { clear() } + } + + /* + * Network type + */ + + override fun getNetworkType() = NetworkType.of( + sharedPreferences.getInt(PREF_NETWORK_TYPE, NetworkType.WPA2.intVal) + ) + + override fun setNetworkType(networkType: NetworkType) { + sharedPreferences.edit { + putInt(PREF_NETWORK_TYPE, networkType.intVal) + } + } + + /* + * Last used network name + */ + + override fun getLastUsedNetworkName() = sharedPreferences.getString( + PREF_LAST_USED_NETWORK_NAME, + "" + ) ?: "" + override fun setLastUsedNetworkName(lastUsedNetworkName: String) { + sharedPreferences.edit { + putString(PREF_LAST_USED_NETWORK_NAME, lastUsedNetworkName) + } + } + + /* + * Last used network password + */ + + override fun getLastUsedNetworkPassword() = sharedPreferences.getString( + PREF_LAST_USED_NETWORK_PASSWORD, + "" + ) ?: "" + + override fun setLastUsedNetworkPassword(lastUsedNetworkPassword: String) { + sharedPreferences.edit { + putString(PREF_LAST_USED_NETWORK_PASSWORD, lastUsedNetworkPassword) + } + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/RemoveNetworkStore.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/RemoveNetworkStore.kt new file mode 100644 index 00000000..95ef2df6 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/RemoveNetworkStore.kt @@ -0,0 +1,37 @@ +package com.isupatches.wisefysample.internal.preferences + +import android.content.SharedPreferences + +import androidx.core.content.edit + +internal interface RemoveNetworkStore { + fun clear() + + fun getLastUsedRegex(): String + + fun setLastUsedRegex(lastUsedRegex: String) +} + +internal class SharedPreferencesRemoveNetworkStore( + private val sharedPreferences: SharedPreferences +) : RemoveNetworkStore { + + override fun clear() { + sharedPreferences.edit { clear() } + } + + /* + * Last used Regex + */ + + override fun getLastUsedRegex() = sharedPreferences.getString( + PREF_LAST_USED_REGEX, + "" + ) ?: "" + + override fun setLastUsedRegex(lastUsedRegex: String) { + sharedPreferences.edit { + putString(PREF_LAST_USED_REGEX, lastUsedRegex) + } + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/SearchStore.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/SearchStore.kt new file mode 100644 index 00000000..8970842e --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/SearchStore.kt @@ -0,0 +1,108 @@ +package com.isupatches.wisefysample.internal.preferences + +import android.content.SharedPreferences + +import androidx.core.content.edit + +import com.isupatches.wisefysample.internal.models.SearchType + +private const val PREF_SEARCH_TYPE = "search type" +private const val PREF_RETURN_FULL_LIST = "return full list" +private const val PREF_FILTER_DUPLICATES = "filter duplicates" +private const val PREF_TIMEOUT = "timeout" + +internal interface SearchStore { + fun clear() + + fun getLastUsedRegex(): String + fun getSearchType(): SearchType + fun shouldReturnFullList(): Boolean + fun shouldFilterDuplicates(): Boolean + fun getTimeout(): Int + + fun setLastUsedRegex(lastUsedRegex: String) + fun setSearchType(searchType: SearchType) + fun setReturnFullList(returnFullList: Boolean) + fun setFilterDuplicates(filterDuplicates: Boolean) + fun setTimeout(timeout: Int) +} + +internal class SharedPreferencesSearchStore( + private val sharedPreferences: SharedPreferences +) : SearchStore { + + override fun clear() { + sharedPreferences.edit { clear() } + } + + /* + * Last used Regex + */ + + override fun getLastUsedRegex() = sharedPreferences.getString( + PREF_LAST_USED_REGEX, + "" + ) ?: "" + + override fun setLastUsedRegex(lastUsedRegex: String) { + sharedPreferences.edit { + putString(PREF_LAST_USED_REGEX, lastUsedRegex) + } + } + + /* + * Search type + */ + + override fun getSearchType(): SearchType = SearchType.of( + sharedPreferences.getInt(PREF_SEARCH_TYPE, SearchType.ACCESS_POINT.intVal) + ) + + override fun setSearchType(searchType: SearchType) { + sharedPreferences.edit { + putInt(PREF_SEARCH_TYPE, searchType.intVal) + } + } + + /* + * Return full list + */ + + override fun shouldReturnFullList() = sharedPreferences.getBoolean( + PREF_RETURN_FULL_LIST, + true + ) + + override fun setReturnFullList(returnFullList: Boolean) { + sharedPreferences.edit { + putBoolean(PREF_RETURN_FULL_LIST, returnFullList) + } + } + + /* + * Filter duplicates + */ + + override fun shouldFilterDuplicates() = sharedPreferences.getBoolean( + PREF_FILTER_DUPLICATES, + true + ) + + override fun setFilterDuplicates(filterDuplicates: Boolean) { + sharedPreferences.edit { + putBoolean(PREF_FILTER_DUPLICATES, filterDuplicates) + } + } + + /* + * Timeout + */ + + override fun getTimeout() = sharedPreferences.getInt(PREF_TIMEOUT, 1) + + override fun setTimeout(timeout: Int) { + sharedPreferences.edit { + putInt(PREF_TIMEOUT, timeout) + } + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/SharedPreferenceKeys.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/SharedPreferenceKeys.kt new file mode 100644 index 00000000..65cc979c --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/SharedPreferenceKeys.kt @@ -0,0 +1,3 @@ +package com.isupatches.wisefysample.internal.preferences + +internal const val PREF_LAST_USED_REGEX = "last used regex" diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/EditTextExtensions.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/EditTextExtensions.kt new file mode 100644 index 00000000..60b1aa5b --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/EditTextExtensions.kt @@ -0,0 +1,5 @@ +package com.isupatches.wisefysample.internal.util + +import android.widget.EditText + +internal fun EditText.getTrimmedInput(): String = text.toString().trim() diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/HtmlUtil.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/HtmlUtil.kt new file mode 100644 index 00000000..375dd6aa --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/HtmlUtil.kt @@ -0,0 +1,13 @@ +package com.isupatches.wisefysample.internal.util + +import android.os.Build +import android.text.Html +import android.text.Spanned + +@Suppress("DEPRECATION") +internal fun String.asHtmlSpanned(): Spanned = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + Html.fromHtml(this, Html.FROM_HTML_MODE_COMPACT) + } else { + Html.fromHtml(this) + } diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/KeyboardUtil.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/KeyboardUtil.kt new file mode 100644 index 00000000..aa96c77b --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/KeyboardUtil.kt @@ -0,0 +1,15 @@ +package com.isupatches.wisefysample.internal.util + +import android.app.Activity +import android.view.View +import android.view.inputmethod.InputMethodManager + +import com.isupatches.wisefysample.internal.base.BaseFragment + +internal fun BaseFragment.hideKeyboardFrom(view: View) { + activity?.let { + (it.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager).also { inputManger -> + inputManger.hideSoftInputFromWindow(view.windowToken, 0) + } + } +} \ No newline at end of file diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/PermissionsUtil.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/PermissionsUtil.kt new file mode 100644 index 00000000..6ab58d30 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/PermissionsUtil.kt @@ -0,0 +1,18 @@ +package com.isupatches.wisefysample.internal.util + +import android.content.Context +import android.content.pm.PackageManager +import androidx.core.content.ContextCompat + +import javax.inject.Inject + +internal interface PermissionUtil { + fun permissionNotGranted(context: Context, permission: String): Boolean +} + +internal class PermissionsUtilImpl @Inject constructor(): PermissionUtil { + + override fun permissionNotGranted(context: Context, permission: String): Boolean { + return ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED + } +} \ No newline at end of file diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/ToastUtil.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/ToastUtil.kt new file mode 100644 index 00000000..257bdfe9 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/internal/util/ToastUtil.kt @@ -0,0 +1,8 @@ +package com.isupatches.wisefysample.internal.util + +import android.widget.Toast +import com.isupatches.wisefysample.internal.base.BaseFragment + +internal fun BaseFragment.displayShortToast(message: String) { + Toast.makeText(activity, message, Toast.LENGTH_SHORT).show() +} \ No newline at end of file diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/add/AddNetworkFragment.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/add/AddNetworkFragment.kt new file mode 100644 index 00000000..ad0ac1d4 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/add/AddNetworkFragment.kt @@ -0,0 +1,210 @@ +package com.isupatches.wisefysample.ui.add + +import android.Manifest.permission.ACCESS_WIFI_STATE +import android.content.pm.PackageManager +import android.net.wifi.WifiConfiguration +import android.os.Bundle +import android.util.Log +import android.view.View + +import com.isupatches.wisefy.constants.WiseFyCode +import com.isupatches.wisefysample.R +import com.isupatches.wisefysample.internal.base.BaseFragment +import com.isupatches.wisefysample.internal.models.NetworkType +import com.isupatches.wisefysample.internal.preferences.AddNetworkStore +import com.isupatches.wisefysample.internal.util.displayShortToast +import com.isupatches.wisefysample.internal.util.getTrimmedInput +import com.isupatches.wisefysample.internal.util.hideKeyboardFrom + +import kotlinx.android.synthetic.main.fragment_add.addNetworkBtn +import kotlinx.android.synthetic.main.fragment_add.addNetworkTypeRdg +import kotlinx.android.synthetic.main.fragment_add.networkNameEdt +import kotlinx.android.synthetic.main.fragment_add.networkPasswordTil +import kotlinx.android.synthetic.main.fragment_add.networkPasswordEdt + +import javax.inject.Inject + +internal class AddNetworkFragment : BaseFragment(), AddNetworkMvp.View { + + override val layoutRes = R.layout.fragment_add + + private val presenter by lazy { AddNetworkPresenter(wiseFy) } + + @Inject lateinit var addNetworkStore: AddNetworkStore + + companion object { + val TAG: String = AddNetworkFragment::class.java.simpleName + + fun newInstance() = AddNetworkFragment() + + private const val WISEFY_ADD_OPEN_NETWORK_REQUEST_CODE = 1 + private const val WISEFY_ADD_WEP_NETWORK_REQUEST_CODE = 2 + private const val WISEFY_ADD_WPA2_NETWORK_REQUEST_CODE = 3 + } + + override fun onStart() { + super.onStart() + presenter.attachView(this) + } + + override fun onStop() { + presenter.detachView() + super.onStop() + addNetworkStore.setLastUsedNetworkName(networkNameEdt.getTrimmedInput()) + addNetworkStore.setLastUsedNetworkPassword(networkPasswordEdt.getTrimmedInput()) + hideKeyboardFrom(addNetworkBtn) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + if (savedInstanceState == null) { + restoreUI() + } + + addNetworkBtn.setOnClickListener { + when (addNetworkTypeRdg.checkedRadioButtonId) { + R.id.openNetworkRdb -> addOpenNetwork() + R.id.wepNetworkRdb -> addWEPNetwork() + R.id.wpa2NetworkRdb -> addWPA2Network() + } + } + addNetworkTypeRdg.setOnCheckedChangeListener { _, checkedId -> + when (checkedId) { + R.id.openNetworkRdb -> addNetworkStore.setNetworkType(NetworkType.OPEN) + R.id.wepNetworkRdb -> addNetworkStore.setNetworkType(NetworkType.WEP) + R.id.wpa2NetworkRdb -> addNetworkStore.setNetworkType(NetworkType.WPA2) + } + updateUI() + } + } + + /* + * View helpers + */ + + private fun adjustNetworkPasswordVisibility(visibility: Int) { + networkPasswordTil.visibility = visibility + networkPasswordEdt.visibility = visibility + } + + private fun restoreUI() { + // Restore edit text values + networkNameEdt.setText(addNetworkStore.getLastUsedNetworkName()) + networkPasswordEdt.setText(addNetworkStore.getLastUsedNetworkPassword()) + + // Restore checked state + val checkedId = when(addNetworkStore.getNetworkType()) { + NetworkType.OPEN -> R.id.openNetworkRdb + NetworkType.WEP -> R.id.wepNetworkRdb + NetworkType.WPA2 -> R.id.wpa2NetworkRdb + } + addNetworkTypeRdg.check(checkedId) + + // Show/hide password edit + when(addNetworkStore.getNetworkType()) { + NetworkType.OPEN -> adjustNetworkPasswordVisibility(View.INVISIBLE) + else -> adjustNetworkPasswordVisibility(View.VISIBLE) + } + } + + private fun updateUI() { + when(addNetworkTypeRdg.checkedRadioButtonId) { + R.id.openNetworkRdb -> adjustNetworkPasswordVisibility(View.INVISIBLE) + else -> adjustNetworkPasswordVisibility(View.VISIBLE) + } + } + + /* + * Presenter callback overrides + */ + + override fun displayFailureAddingNetwork(wifiManagerReturn: Int) { + displayShortToast("Failure adding network. WifiManager return: $wifiManagerReturn") + } + + override fun displayNetworkAdded(newNetworkId: Int, networkConfig: WifiConfiguration) { + displayShortToast("Network added. Id: $newNetworkId, Config: $networkConfig") + } + + override fun displayWiseFyFailure(@WiseFyCode wiseFyFailureCode: Int) { + displayWiseFyFailureWithCode(wiseFyFailureCode) + } + + /* + * WiseFy helpers + */ + + private fun addOpenNetwork() { + if (checkAddOpenNetworkPermissions()) { + presenter.addOpenNetwork(networkNameEdt.getTrimmedInput()) + } + } + + private fun addWEPNetwork() { + if (checkAddWEPNetworkPermissions()) { + presenter.addWEPNetwork( + ssid = networkNameEdt.getTrimmedInput(), + password = networkPasswordEdt.getTrimmedInput() + ) + } + } + + private fun addWPA2Network() { + if (checkAddWPA2NetworkPermissions()) { + presenter.addWPA2Network( + ssid = networkNameEdt.getTrimmedInput(), + password = networkPasswordEdt.getTrimmedInput() + ) + } + } + + /* + * Permission helpers + */ + + private fun checkAddOpenNetworkPermissions(): Boolean { + return isPermissionGranted(ACCESS_WIFI_STATE, WISEFY_ADD_OPEN_NETWORK_REQUEST_CODE) + } + + private fun checkAddWEPNetworkPermissions(): Boolean { + return isPermissionGranted(ACCESS_WIFI_STATE, WISEFY_ADD_WEP_NETWORK_REQUEST_CODE) + } + + private fun checkAddWPA2NetworkPermissions(): Boolean { + return isPermissionGranted(ACCESS_WIFI_STATE, WISEFY_ADD_WPA2_NETWORK_REQUEST_CODE) + } + + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { + when (requestCode) { + WISEFY_ADD_OPEN_NETWORK_REQUEST_CODE -> { + if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + addOpenNetwork() + } else { + Log.w(TAG, "Permissions for adding an open network are denied") + // Display permission error here + } + } + WISEFY_ADD_WEP_NETWORK_REQUEST_CODE -> { + if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + addWEPNetwork() + } else { + Log.w(TAG, "Permissions for adding a WEP network are denied") + // Display permission error here + } + } + WISEFY_ADD_WPA2_NETWORK_REQUEST_CODE -> { + if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + addWPA2Network() + } else { + Log.w(TAG, "Permissions for adding a WPA2 network are denied") + // Display permission error here + } + } + else -> { + // Display permission error here + Log.wtf(TAG, "Weird permission requested, not handled") + } + } + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/add/AddNetworkModel.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/add/AddNetworkModel.kt new file mode 100644 index 00000000..1d402f39 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/add/AddNetworkModel.kt @@ -0,0 +1,66 @@ +package com.isupatches.wisefysample.ui.add + +import android.Manifest.permission.ACCESS_WIFI_STATE +import android.net.wifi.WifiConfiguration +import androidx.annotation.RequiresPermission + +import com.isupatches.wisefy.WiseFy +import com.isupatches.wisefy.callbacks.AddNetworkCallbacks + +internal class AddNetworkModel( + private val presenter: AddNetworkMvp.Presenter, + private val wiseFy: WiseFy +): AddNetworkMvp.Model { + + @RequiresPermission(ACCESS_WIFI_STATE) + override fun addOpenNetwork(ssid: String) { + wiseFy.addOpenNetwork(ssid, object : AddNetworkCallbacks { + override fun networkAdded(newNetworkId: Int, networkConfig: WifiConfiguration) { + presenter.displayNetworkAdded(newNetworkId, networkConfig) + } + + override fun failureAddingNetwork(wifiManagerReturn: Int) { + presenter.displayFailureAddingNetwork(wifiManagerReturn) + } + + override fun wisefyFailure(wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } + + @RequiresPermission(ACCESS_WIFI_STATE) + @Suppress("DEPRECATION") + override fun addWEPNetwork(ssid: String, password: String) { + wiseFy.addWEPNetwork(ssid, password, object : AddNetworkCallbacks { + override fun networkAdded(newNetworkId: Int, networkConfig: WifiConfiguration) { + presenter.displayNetworkAdded(newNetworkId, networkConfig) + } + + override fun failureAddingNetwork(wifiManagerReturn: Int) { + presenter.displayFailureAddingNetwork(wifiManagerReturn) + } + + override fun wisefyFailure(wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } + + @RequiresPermission(ACCESS_WIFI_STATE) + override fun addWPA2Network(ssid: String, password: String) { + wiseFy.addWPA2Network(ssid, password, object : AddNetworkCallbacks { + override fun networkAdded(newNetworkId: Int, networkConfig: WifiConfiguration) { + presenter.displayNetworkAdded(newNetworkId, networkConfig) + } + + override fun failureAddingNetwork(wifiManagerReturn: Int) { + presenter.displayFailureAddingNetwork(wifiManagerReturn) + } + + override fun wisefyFailure(wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/add/AddNetworkMvp.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/add/AddNetworkMvp.kt new file mode 100644 index 00000000..1a334a55 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/add/AddNetworkMvp.kt @@ -0,0 +1,35 @@ +package com.isupatches.wisefysample.ui.add + +import android.net.wifi.WifiConfiguration + +import com.isupatches.wisefysample.internal.base.BaseMvp + +internal interface AddNetworkMvp { + + interface View : BaseMvp.View { + fun displayFailureAddingNetwork(wifiManagerReturn: Int) + fun displayNetworkAdded(newNetworkId: Int, networkConfig: WifiConfiguration) + } + + interface Presenter : BaseMvp.Presenter { + + /* + * Model call-throughs + */ + fun addOpenNetwork(ssid: String) + fun addWEPNetwork(ssid: String, password: String) + fun addWPA2Network(ssid: String, password: String) + + /* + * View callbacks + */ + fun displayFailureAddingNetwork(wifiManagerReturn: Int) + fun displayNetworkAdded(newNetworkId: Int, networkConfig: WifiConfiguration) + } + + interface Model { + fun addOpenNetwork(ssid: String) + fun addWEPNetwork(ssid: String, password: String) + fun addWPA2Network(ssid: String, password: String) + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/add/AddNetworkPresenter.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/add/AddNetworkPresenter.kt new file mode 100644 index 00000000..311573af --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/add/AddNetworkPresenter.kt @@ -0,0 +1,46 @@ +package com.isupatches.wisefysample.ui.add + +import android.Manifest.permission.ACCESS_WIFI_STATE +import android.net.wifi.WifiConfiguration +import androidx.annotation.RequiresPermission + +import com.isupatches.wisefy.WiseFy +import com.isupatches.wisefysample.internal.base.BasePresenter + +internal class AddNetworkPresenter( + wiseFy: WiseFy +) : BasePresenter(), AddNetworkMvp.Presenter { + + private val model = AddNetworkModel(this, wiseFy) + + /* + * Model call-throughs + */ + + @RequiresPermission(ACCESS_WIFI_STATE) + override fun addOpenNetwork(ssid: String) { + model.addOpenNetwork(ssid) + } + + @RequiresPermission(ACCESS_WIFI_STATE) + override fun addWEPNetwork(ssid: String, password: String) { + model.addWEPNetwork(ssid, password) + } + + @RequiresPermission(ACCESS_WIFI_STATE) + override fun addWPA2Network(ssid: String, password: String) { + model.addWPA2Network(ssid, password) + } + + /* + * View callbacks + */ + + override fun displayFailureAddingNetwork(wifiManagerReturn: Int) { + doSafelyWithView { view -> view.displayFailureAddingNetwork(wifiManagerReturn) } + } + + override fun displayNetworkAdded(newNetworkId: Int, networkConfig: WifiConfiguration) { + doSafelyWithView { view -> view.displayNetworkAdded(newNetworkId, networkConfig) } + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/main/MainActivity.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/main/MainActivity.kt new file mode 100644 index 00000000..58d0e701 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/main/MainActivity.kt @@ -0,0 +1,83 @@ +package com.isupatches.wisefysample.ui.main + +import android.os.Bundle +import android.view.MenuItem +import androidx.appcompat.app.AppCompatActivity +import androidx.fragment.app.Fragment + +import com.google.android.material.bottomnavigation.BottomNavigationView + +import com.isupatches.wisefysample.R +import com.isupatches.wisefysample.internal.nav.openFragment +import com.isupatches.wisefysample.internal.nav.selectItem +import com.isupatches.wisefysample.ui.add.AddNetworkFragment +import com.isupatches.wisefysample.ui.misc.MiscFragment +import com.isupatches.wisefysample.ui.remove.RemoveNetworkFragment +import com.isupatches.wisefysample.ui.search.SearchFragment + +import dagger.Module +import dagger.android.AndroidInjection +import dagger.android.AndroidInjector +import dagger.android.ContributesAndroidInjector +import dagger.android.DispatchingAndroidInjector +import dagger.android.support.HasSupportFragmentInjector + +import kotlinx.android.synthetic.main.activity_main.bottomNavigationView + +import javax.inject.Inject + +internal class MainActivity : AppCompatActivity(), + BottomNavigationView.OnNavigationItemSelectedListener, + HasSupportFragmentInjector { + + @Inject lateinit var fragmentInjector: DispatchingAndroidInjector + override fun supportFragmentInjector(): AndroidInjector = fragmentInjector + + override fun onCreate(savedInstanceState: Bundle?) { + AndroidInjection.inject(this) + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + + bottomNavigationView.setOnNavigationItemSelectedListener(this) + if (savedInstanceState == null) { + bottomNavigationView.selectItem(R.id.menu_home) + openFragment(this, MainFragment.newInstance(), MainFragment.TAG) + } + } + + override fun onNavigationItemSelected(item: MenuItem): Boolean { + when (item.itemId) { + R.id.menu_add -> { + openFragment(this, AddNetworkFragment.newInstance(), AddNetworkFragment.TAG) + return true + } + R.id.menu_remove -> { + openFragment(this, RemoveNetworkFragment.newInstance(), RemoveNetworkFragment.TAG) + return true + } + R.id.menu_home -> { + openFragment(this, MainFragment.newInstance(), MainFragment.TAG) + return true + } + R.id.menu_search -> { + openFragment(this, SearchFragment.newInstance(), SearchFragment.TAG) + return true + } + R.id.menu_misc -> { + openFragment(this, MiscFragment.newInstance(), MiscFragment.TAG) + return true + } + } + bottomNavigationView.selectItem(item.itemId) + return super.onOptionsItemSelected(item) + } + + @Suppress("unused") + @Module internal interface FragmentBindings { + @ContributesAndroidInjector fun addNetworkFragment(): AddNetworkFragment + @ContributesAndroidInjector fun removeNetworkFragment(): RemoveNetworkFragment + @ContributesAndroidInjector fun mainFragment(): MainFragment + @ContributesAndroidInjector fun miscFragment(): MiscFragment + @ContributesAndroidInjector fun searchFragment(): SearchFragment + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/main/MainFragment.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/main/MainFragment.kt new file mode 100644 index 00000000..6a0bbc45 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/main/MainFragment.kt @@ -0,0 +1,15 @@ +package com.isupatches.wisefysample.ui.main + +import com.isupatches.wisefysample.R +import com.isupatches.wisefysample.internal.base.BaseFragment + +internal class MainFragment : BaseFragment() { + + override val layoutRes = R.layout.fragment_main + + companion object { + val TAG: String = MainFragment::class.java.simpleName + + fun newInstance() = MainFragment() + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/misc/MiscFragment.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/misc/MiscFragment.kt new file mode 100644 index 00000000..a31c9d4a --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/misc/MiscFragment.kt @@ -0,0 +1,335 @@ +package com.isupatches.wisefysample.ui.misc + +import android.Manifest.permission.ACCESS_COARSE_LOCATION +import android.Manifest.permission.ACCESS_NETWORK_STATE +import android.Manifest.permission.ACCESS_WIFI_STATE +import android.Manifest.permission.CHANGE_WIFI_STATE +import android.content.pm.PackageManager +import android.net.NetworkInfo +import android.net.wifi.ScanResult +import android.net.wifi.WifiConfiguration +import android.net.wifi.WifiInfo +import android.os.Build +import android.os.Bundle +import android.util.Log +import android.view.View + +import com.isupatches.wisefy.constants.WiseFyCode +import com.isupatches.wisefysample.R +import com.isupatches.wisefysample.internal.base.BaseFragment +import com.isupatches.wisefysample.internal.util.displayShortToast + +import kotlinx.android.synthetic.main.fragment_misc.enableWifiBtn +import kotlinx.android.synthetic.main.fragment_misc.disableWifiBtn +import kotlinx.android.synthetic.main.fragment_misc.getCurrentNetworkBtn +import kotlinx.android.synthetic.main.fragment_misc.getCurrentNetworkDetailsBtn +import kotlinx.android.synthetic.main.fragment_misc.getFrequencyBtn +import kotlinx.android.synthetic.main.fragment_misc.getIPBtn +import kotlinx.android.synthetic.main.fragment_misc.getNearbyAccessPointsBtn +import kotlinx.android.synthetic.main.fragment_misc.getSavedNetworksBtn + +internal class MiscFragment : BaseFragment(), MiscMvp.View { + + override val layoutRes = R.layout.fragment_misc + + private val presenter by lazy { MiscPresenter(wiseFy) } + + companion object { + val TAG: String = MiscFragment::class.java.simpleName + + fun newInstance() = MiscFragment() + + private const val WISEFY_DISABLE_WIFI_REQUEST_CODE = 1 + private const val WISEFY_ENABLE_WIFI_REQUEST_CODE = 2 + private const val WISEFY_GET_CURRENT_NETWORK_REQUEST_CODE = 3 + private const val WISEFY_GET_CURRENT_NETWORK_INFO_REQUEST_CODE = 4 + private const val WISEFY_GET_FREQUENCY_REQUEST_CODE = 5 + private const val WISEFY_GET_IP_REQUEST_CODE = 6 + private const val WISEFY_GET_NEARBY_ACCESS_POINTS_REQUEST_CODE = 7 + private const val WISEFY_GET_SAVED_NETWORKS_REQUEST_CODE = 8 + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + disableWifiBtn.setOnClickListener { + disableWifi() + } + enableWifiBtn.setOnClickListener { + enableWifi() + } + getCurrentNetworkBtn.setOnClickListener { + getCurrentNetwork() + } + getCurrentNetworkDetailsBtn.setOnClickListener { + getCurrentNetworkInfo() + } + getFrequencyBtn.setOnClickListener { + getFrequency() + } + getIPBtn.setOnClickListener { + getIP() + } + getNearbyAccessPointsBtn.setOnClickListener { + getNearbyAccessPoints() + } + getSavedNetworksBtn.setOnClickListener { + getSavedNetworks() + } + } + + override fun onStart() { + super.onStart() + presenter.attachView(this) + } + + override fun onStop() { + presenter.detachView() + super.onStop() + } + + /* + * Presenter overrides + */ + + override fun displayWifiDisabled() { + displayShortToast("Wifi disabled!") + } + + override fun displayFailureDisablingWifi() { + displayShortToast("Failure disabling wifi") + } + + override fun displayWifiEnabled() { + displayShortToast("Wifi enabled!") + } + + override fun displayFailureEnablingWifi() { + displayShortToast("Failure enabling wifi") + } + + override fun displayCurrentNetwork(currentNetwork: WifiInfo) { + displayShortToast("Current network: $currentNetwork") + } + + override fun displayNoCurrentNetwork() { + displayShortToast("No current network") + } + + override fun displayCurrentNetworkInfo(currentNetworkDetails: NetworkInfo) { + displayShortToast("Current network info: $currentNetworkDetails") + } + + override fun displayNoCurrentNetworkInfo() { + displayShortToast("No current network info") + } + + override fun displayFrequency(frequency: Int) { + displayShortToast("Frequency: $frequency") + } + + override fun displayFailureRetrievingFrequency() { + displayShortToast("Failure retrieving frequency") + } + + override fun displayIP(ip: String) { + displayShortToast("IP: $ip") + } + + override fun displayFailureRetrievingIP() { + displayShortToast("Failure retrieving IP") + } + + override fun displayNearbyAccessPoints(accessPoints: List) { + displayShortToast("Nearby access points: $accessPoints") + } + + override fun displayNoAccessPointsFound() { + displayShortToast("No access points found!") + } + + override fun displaySavedNetworks(savedNetworks: List) { + displayShortToast("Saved networks: $savedNetworks") + } + + override fun displayNoSavedNetworksFound() { + displayShortToast("No saved networks found!") + } + + override fun displayWiseFyFailure(@WiseFyCode wiseFyFailureCode: Int) { + displayWiseFyFailureWithCode(wiseFyFailureCode) + } + + /* + * WiseFy helpers + */ + + private fun disableWifi() { + if (checkDisableWifiPermissions()) { + presenter.disableWifi() + } + } + + private fun enableWifi() { + if (checkEnableWifiPermissions()) { + presenter.enableWifi() + } + } + + @Throws(SecurityException::class) + private fun getCurrentNetwork() { + if (checkGetCurrentNetworkPermissions()) { + presenter.getCurrentNetwork() + } + } + + private fun getCurrentNetworkInfo() { + if (checkGetCurrentNetworkInfoPermissions()) { + presenter.getCurrentNetworkInfo() + } + } + + @Throws(SecurityException::class) + private fun getFrequency() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + if (checkGetFrequencyPermissions()) { + presenter.getFrequency() + } + } else { + displayShortToast("getFrequency is a Lollipop and above feature") + } + } + + @Throws(SecurityException::class) + private fun getIP() { + if (checkGetIPPermissions()) { + presenter.getIP() + } + } + + @Throws(SecurityException::class) + private fun getNearbyAccessPoints() { + if (checkGetNearbyAccessPointsPermissions()) { + presenter.getNearbyAccessPoints() + } + } + + private fun getSavedNetworks() { + if (checkGetSavedNetworksPermissions()) { + presenter.getSavedNetworks() + } + } + + /* + * Permission helpers + */ + + private fun checkDisableWifiPermissions(): Boolean { + return isPermissionGranted(CHANGE_WIFI_STATE, WISEFY_DISABLE_WIFI_REQUEST_CODE) + } + + private fun checkEnableWifiPermissions(): Boolean { + return isPermissionGranted(CHANGE_WIFI_STATE, WISEFY_ENABLE_WIFI_REQUEST_CODE) + } + + private fun checkGetCurrentNetworkPermissions(): Boolean { + return isPermissionGranted(ACCESS_WIFI_STATE, WISEFY_GET_CURRENT_NETWORK_REQUEST_CODE) + && isPermissionGranted(ACCESS_COARSE_LOCATION, WISEFY_GET_CURRENT_NETWORK_REQUEST_CODE) + } + + private fun checkGetCurrentNetworkInfoPermissions(): Boolean { + return isPermissionGranted(ACCESS_NETWORK_STATE, WISEFY_GET_CURRENT_NETWORK_INFO_REQUEST_CODE) + } + + private fun checkGetFrequencyPermissions(): Boolean { + return isPermissionGranted(ACCESS_WIFI_STATE, WISEFY_GET_FREQUENCY_REQUEST_CODE) + && isPermissionGranted(ACCESS_COARSE_LOCATION, WISEFY_GET_FREQUENCY_REQUEST_CODE) + } + + private fun checkGetIPPermissions(): Boolean { + return isPermissionGranted(ACCESS_WIFI_STATE, WISEFY_GET_IP_REQUEST_CODE) + && isPermissionGranted(ACCESS_COARSE_LOCATION, WISEFY_GET_IP_REQUEST_CODE) + } + + private fun checkGetNearbyAccessPointsPermissions(): Boolean { + return isPermissionGranted(ACCESS_WIFI_STATE, WISEFY_GET_NEARBY_ACCESS_POINTS_REQUEST_CODE) + && isPermissionGranted(ACCESS_COARSE_LOCATION, WISEFY_GET_NEARBY_ACCESS_POINTS_REQUEST_CODE) + } + + private fun checkGetSavedNetworksPermissions(): Boolean { + return isPermissionGranted(ACCESS_WIFI_STATE, WISEFY_GET_SAVED_NETWORKS_REQUEST_CODE) + } + + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { + when (requestCode) { + WISEFY_DISABLE_WIFI_REQUEST_CODE -> { + if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + getIP() + } else { + Log.w(TAG, "Permissions for disabling wifi are denied") + // Display permission error here + } + } + WISEFY_ENABLE_WIFI_REQUEST_CODE -> { + if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + getIP() + } else { + Log.w(TAG, "Permissions for enabling wifi are denied") + // Display permission error here + } + } + WISEFY_GET_CURRENT_NETWORK_REQUEST_CODE -> { + if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + getCurrentNetwork() + } else { + Log.w(TAG, "Permissions for getting current network are denied") + // Display permission error here + } + } + WISEFY_GET_CURRENT_NETWORK_INFO_REQUEST_CODE -> { + if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + getCurrentNetworkInfo() + } else { + Log.w(TAG, "Permissions for getting current network info are denied") + // Display permission error here + } + } + WISEFY_GET_FREQUENCY_REQUEST_CODE -> { + if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + getFrequency() + } else { + Log.w(TAG, "Permissions for getting frequency are denied") + // Display permission error here + } + } + WISEFY_GET_IP_REQUEST_CODE -> { + if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + getIP() + } else { + Log.w(TAG, "Permissions for getting ip are denied") + // Display permission error here + } + } + WISEFY_GET_NEARBY_ACCESS_POINTS_REQUEST_CODE -> { + if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + getNearbyAccessPoints() + } else { + Log.w(TAG, "Permissions for getting nearby access points are denied") + // Display permission error here + } + } + WISEFY_GET_SAVED_NETWORKS_REQUEST_CODE -> { + if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + getIP() + } else { + Log.w(TAG, "Permissions for getting saved networks are denied") + // Display permission error here + } + } + else -> { + // Display permission error here + Log.wtf(TAG, "Weird permission requested, not handled") + } + } + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/misc/MiscModel.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/misc/MiscModel.kt new file mode 100644 index 00000000..4f894ebf --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/misc/MiscModel.kt @@ -0,0 +1,166 @@ +package com.isupatches.wisefysample.ui.misc + +import android.Manifest.permission.ACCESS_COARSE_LOCATION +import android.Manifest.permission.ACCESS_NETWORK_STATE +import android.Manifest.permission.ACCESS_WIFI_STATE +import android.Manifest.permission.CHANGE_WIFI_STATE +import android.net.NetworkInfo +import android.net.wifi.ScanResult +import android.net.wifi.WifiConfiguration +import android.net.wifi.WifiInfo +import android.os.Build +import androidx.annotation.RequiresApi +import androidx.annotation.RequiresPermission + +import com.isupatches.wisefy.WiseFy +import com.isupatches.wisefy.callbacks.DisableWifiCallbacks +import com.isupatches.wisefy.callbacks.EnableWifiCallbacks +import com.isupatches.wisefy.callbacks.GetCurrentNetworkCallbacks +import com.isupatches.wisefy.callbacks.GetCurrentNetworkInfoCallbacks +import com.isupatches.wisefy.callbacks.GetFrequencyCallbacks +import com.isupatches.wisefy.callbacks.GetIPCallbacks +import com.isupatches.wisefy.callbacks.GetNearbyAccessPointsCallbacks +import com.isupatches.wisefy.callbacks.GetSavedNetworksCallbacks + +internal class MiscModel( + private val presenter: MiscMvp.Presenter, + private val wiseFy: WiseFy +): MiscMvp.Model { + + @RequiresPermission(allOf = [CHANGE_WIFI_STATE]) + override fun disableWifi() { + wiseFy.disableWifi(object : DisableWifiCallbacks { + override fun wifiDisabled() { + presenter.displayWifiDisabled() + } + + override fun failureDisablingWifi() { + presenter.displayFailureDisablingWifi() + } + + override fun wisefyFailure(wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } + + @RequiresPermission(allOf = [CHANGE_WIFI_STATE]) + override fun enableWifi() { + wiseFy.enableWifi(object : EnableWifiCallbacks { + override fun wifiEnabled() { + presenter.displayWifiEnabled() + } + + override fun failureEnablingWifi() { + presenter.displayFailureEnablingWifi() + } + + override fun wisefyFailure(wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } + + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) + override fun getCurrentNetwork() { + wiseFy.getCurrentNetwork(object : GetCurrentNetworkCallbacks { + override fun retrievedCurrentNetwork(currentNetwork: WifiInfo) { + presenter.displayCurrentNetwork(currentNetwork) + } + + override fun noCurrentNetwork() { + presenter.displayNoCurrentNetwork() + } + + override fun wisefyFailure(wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } + + @RequiresPermission(allOf = [ACCESS_NETWORK_STATE]) + override fun getCurrentNetworkInfo() { + wiseFy.getCurrentNetworkInfo(object : GetCurrentNetworkInfoCallbacks { + override fun retrievedCurrentNetworkInfo(currentNetworkDetails: NetworkInfo) { + presenter.displayCurrentNetworkInfo(currentNetworkDetails) + } + + override fun noCurrentNetworkInfo() { + presenter.displayNoCurrentNetworkInfo() + } + + override fun wisefyFailure(wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } + + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) + @RequiresApi(Build.VERSION_CODES.LOLLIPOP) + override fun getFrequency() { + wiseFy.getFrequency(object : GetFrequencyCallbacks { + override fun retrievedFrequency(frequency: Int) { + presenter.displayFrequency(frequency) + } + + override fun failureGettingFrequency() { + presenter.displayFailureRetrievingFrequency() + } + + override fun wisefyFailure(wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } + + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) + override fun getIP() { + wiseFy.getIP(object : GetIPCallbacks { + override fun retrievedIP(ip: String) { + presenter.displayIP(ip) + } + + override fun failureRetrievingIP() { + presenter.displayFailureRetrievingIP() + } + + override fun wisefyFailure(wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } + + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) + override fun getNearbyAccessPoints() { + wiseFy.getNearbyAccessPoints(true, object : GetNearbyAccessPointsCallbacks { + override fun retrievedNearbyAccessPoints(nearbyAccessPoints: List) { + presenter.displayNearbyAccessPoints(nearbyAccessPoints) + } + + override fun noAccessPointsFound() { + presenter.displayNoAccessPointsFound() + } + + override fun wisefyFailure(wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } + + @RequiresPermission(allOf = [ACCESS_WIFI_STATE]) + override fun getSavedNetworks() { + wiseFy.getSavedNetworks(object : GetSavedNetworksCallbacks { + override fun noSavedNetworksFound() { + presenter.displayNoSavedNetworksFound() + } + + override fun retrievedSavedNetworks(savedNetworks: List) { + presenter.displaySavedNetworks(savedNetworks) + } + + override fun wisefyFailure(wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/misc/MiscMvp.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/misc/MiscMvp.kt new file mode 100644 index 00000000..42229059 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/misc/MiscMvp.kt @@ -0,0 +1,75 @@ +package com.isupatches.wisefysample.ui.misc + +import android.net.NetworkInfo +import android.net.wifi.ScanResult +import android.net.wifi.WifiConfiguration +import android.net.wifi.WifiInfo +import com.isupatches.wisefysample.internal.base.BaseMvp + +internal interface MiscMvp { + + interface View : BaseMvp.View { + fun displayWifiDisabled() + fun displayFailureDisablingWifi() + fun displayWifiEnabled() + fun displayFailureEnablingWifi() + fun displayCurrentNetwork(currentNetwork: WifiInfo) + fun displayNoCurrentNetwork() + fun displayCurrentNetworkInfo(currentNetworkDetails: NetworkInfo) + fun displayNoCurrentNetworkInfo() + fun displayFrequency(frequency: Int) + fun displayFailureRetrievingFrequency() + fun displayIP(ip: String) + fun displayFailureRetrievingIP() + fun displayNearbyAccessPoints(accessPoints: List) + fun displayNoAccessPointsFound() + fun displayNoSavedNetworksFound() + fun displaySavedNetworks(savedNetworks: List) + } + + interface Presenter : BaseMvp.Presenter { + + /* + * Model call-throughs + */ + fun disableWifi() + fun enableWifi() + fun getCurrentNetwork() + fun getCurrentNetworkInfo() + fun getFrequency() + fun getIP() + fun getNearbyAccessPoints() + fun getSavedNetworks() + + /* + * View callbacks + */ + fun displayWifiDisabled() + fun displayFailureDisablingWifi() + fun displayWifiEnabled() + fun displayFailureEnablingWifi() + fun displayCurrentNetwork(currentNetwork: WifiInfo) + fun displayNoCurrentNetwork() + fun displayCurrentNetworkInfo(currentNetworkDetails: NetworkInfo) + fun displayNoCurrentNetworkInfo() + fun displayFrequency(frequency: Int) + fun displayFailureRetrievingFrequency() + fun displayIP(ip: String) + fun displayFailureRetrievingIP() + fun displayNearbyAccessPoints(accessPoints: List) + fun displayNoAccessPointsFound() + fun displayNoSavedNetworksFound() + fun displaySavedNetworks(savedNetworks: List) + } + + interface Model { + fun disableWifi() + fun enableWifi() + fun getCurrentNetwork() + fun getCurrentNetworkInfo() + fun getFrequency() + fun getIP() + fun getNearbyAccessPoints() + fun getSavedNetworks() + } +} \ No newline at end of file diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/misc/MiscPresenter.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/misc/MiscPresenter.kt new file mode 100644 index 00000000..30859d6c --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/misc/MiscPresenter.kt @@ -0,0 +1,134 @@ +package com.isupatches.wisefysample.ui.misc + +import android.Manifest.permission.ACCESS_COARSE_LOCATION +import android.Manifest.permission.ACCESS_NETWORK_STATE +import android.Manifest.permission.ACCESS_WIFI_STATE +import android.Manifest.permission.CHANGE_WIFI_STATE +import android.net.NetworkInfo +import android.net.wifi.ScanResult +import android.net.wifi.WifiConfiguration +import android.net.wifi.WifiInfo +import android.os.Build +import androidx.annotation.RequiresApi +import androidx.annotation.RequiresPermission + +import com.isupatches.wisefy.WiseFy +import com.isupatches.wisefysample.internal.base.BasePresenter + +internal class MiscPresenter(wiseFy: WiseFy) : BasePresenter(), MiscMvp.Presenter { + + private val model = MiscModel(this, wiseFy) + + /* + * Model call-throughs + */ + + @RequiresPermission(allOf = [CHANGE_WIFI_STATE]) + override fun disableWifi() { + model.disableWifi() + } + + @RequiresPermission(allOf = [CHANGE_WIFI_STATE]) + override fun enableWifi() { + model.enableWifi() + } + + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) + override fun getCurrentNetwork() { + model.getCurrentNetwork() + } + + @RequiresPermission(allOf = [ACCESS_NETWORK_STATE]) + override fun getCurrentNetworkInfo() { + model.getCurrentNetworkInfo() + } + + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) + @RequiresApi(Build.VERSION_CODES.LOLLIPOP) + override fun getFrequency() { + model.getFrequency() + } + + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) + override fun getIP() { + model.getIP() + } + + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) + override fun getNearbyAccessPoints() { + model.getNearbyAccessPoints() + } + + @RequiresPermission(allOf = [ACCESS_WIFI_STATE]) + override fun getSavedNetworks() { + model.getSavedNetworks() + } + + /* + * View callbacks + */ + + override fun displayWifiDisabled() { + doSafelyWithView { view -> view.displayWifiDisabled() } + } + + override fun displayFailureDisablingWifi() { + doSafelyWithView { view -> view.displayFailureDisablingWifi() } + } + + override fun displayWifiEnabled() { + doSafelyWithView { view -> view.displayWifiEnabled() } + } + + override fun displayFailureEnablingWifi() { + doSafelyWithView { view -> view.displayFailureEnablingWifi() } + } + + override fun displayCurrentNetwork(currentNetwork: WifiInfo) { + doSafelyWithView { view -> view.displayCurrentNetwork(currentNetwork) } + } + + override fun displayNoCurrentNetwork() { + doSafelyWithView { view -> view.displayNoCurrentNetwork() } + } + + override fun displayCurrentNetworkInfo(currentNetworkDetails: NetworkInfo) { + doSafelyWithView { view -> view.displayCurrentNetworkInfo(currentNetworkDetails) } + } + + override fun displayNoCurrentNetworkInfo() { + doSafelyWithView { view -> view.displayNoCurrentNetworkInfo() } + } + + override fun displayFrequency(frequency: Int) { + doSafelyWithView { view -> view.displayFrequency(frequency) } + } + + override fun displayFailureRetrievingFrequency() { + doSafelyWithView { view -> view.displayFailureRetrievingFrequency() } + } + + override fun displayIP(ip: String) { + doSafelyWithView { view -> view.displayIP(ip) } + } + + override fun displayFailureRetrievingIP() { + doSafelyWithView { view -> view.displayFailureRetrievingIP() } + } + + override fun displayNearbyAccessPoints(accessPoints: List) { + doSafelyWithView { view -> view.displayNearbyAccessPoints(accessPoints) } + } + + override fun displayNoAccessPointsFound() { + doSafelyWithView { view -> view.displayNoAccessPointsFound() } + } + + override fun displayNoSavedNetworksFound() { + doSafelyWithView { view -> view.displayNoSavedNetworksFound() } + } + + override fun displaySavedNetworks(savedNetworks: List) { + doSafelyWithView { view -> view.displaySavedNetworks(savedNetworks) } + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkFragment.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkFragment.kt new file mode 100644 index 00000000..3d7f6577 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkFragment.kt @@ -0,0 +1,126 @@ +package com.isupatches.wisefysample.ui.remove + +import android.Manifest.permission.ACCESS_WIFI_STATE +import android.content.pm.PackageManager +import android.os.Bundle +import android.util.Log +import android.view.View + +import com.isupatches.wisefy.constants.WiseFyCode +import com.isupatches.wisefysample.R +import com.isupatches.wisefysample.internal.base.BaseFragment +import com.isupatches.wisefysample.internal.preferences.RemoveNetworkStore +import com.isupatches.wisefysample.internal.util.displayShortToast +import com.isupatches.wisefysample.internal.util.getTrimmedInput +import com.isupatches.wisefysample.internal.util.hideKeyboardFrom + +import kotlinx.android.synthetic.main.fragment_remove.removeNetworkBtn +import kotlinx.android.synthetic.main.fragment_remove.removeNetworkEdt + +import javax.inject.Inject + +internal class RemoveNetworkFragment : BaseFragment(), RemoveNetworkMvp.View { + + override val layoutRes = R.layout.fragment_remove + + private val presenter by lazy { RemoveNetworkPresenter(wiseFy) } + + @Inject lateinit var removeNetworkStore: RemoveNetworkStore + + companion object { + val TAG: String = RemoveNetworkFragment::class.java.simpleName + + fun newInstance() = RemoveNetworkFragment() + + private const val WISEFY_REMOVE_NETWORK_REQUEST_CODE = 1 + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + if (savedInstanceState == null) { + restoreUI() + } + + removeNetworkBtn.setOnClickListener { + hideKeyboardFrom(removeNetworkBtn) + removeNetwork() + } + } + + override fun onStart() { + super.onStart() + presenter.attachView(this) + } + + override fun onStop() { + presenter.detachView() + super.onStop() + removeNetworkStore.setLastUsedRegex(removeNetworkEdt.getTrimmedInput()) + hideKeyboardFrom(removeNetworkBtn) + } + + /* + * View helpers + */ + + private fun restoreUI() { + // Restore edit text value + removeNetworkEdt.setText(removeNetworkStore.getLastUsedRegex()) + } + + /* + * Presenter callback overrides + */ + + override fun displayNetworkRemoved() { + displayShortToast("Network removed") + } + + override fun displayNetworkNotFoundToRemove() { + displayShortToast("Network not found to remove") + } + + override fun displayFailureRemovingNetwork() { + displayShortToast("Failure removing network!") + } + + override fun displayWiseFyFailure(@WiseFyCode wiseFyFailureCode: Int) { + displayWiseFyFailureWithCode(wiseFyFailureCode) + } + + /* + * WiseFy helpers + */ + + private fun removeNetwork() { + if (checkRemoveNetworkPermissions()) { + presenter.removeNetwork(removeNetworkEdt.getTrimmedInput()) + } + } + + /* + * Permission helpers + */ + + private fun checkRemoveNetworkPermissions(): Boolean { + return isPermissionGranted(ACCESS_WIFI_STATE, WISEFY_REMOVE_NETWORK_REQUEST_CODE) + } + + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { + when (requestCode) { + WISEFY_REMOVE_NETWORK_REQUEST_CODE -> { + if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + removeNetwork() + } else { + Log.w(TAG, "Permissions for remove saved network are denied") + // Display permission error here + } + } + else -> { + // Display permission error here + Log.wtf(TAG, "Weird permission requested, not handled") + } + } + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkModel.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkModel.kt new file mode 100644 index 00000000..e929da34 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkModel.kt @@ -0,0 +1,35 @@ +package com.isupatches.wisefysample.ui.remove + +import android.Manifest.permission.ACCESS_WIFI_STATE +import androidx.annotation.RequiresPermission + +import com.isupatches.wisefy.WiseFy +import com.isupatches.wisefy.callbacks.RemoveNetworkCallbacks +import com.isupatches.wisefy.constants.WiseFyCode + +internal class RemoveNetworkModel( + private val presenter: RemoveNetworkMvp.Presenter, + private val wiseFy: WiseFy +): RemoveNetworkMvp.Model { + + @RequiresPermission(ACCESS_WIFI_STATE) + override fun removeNetwork(networkName: String) { + wiseFy.removeNetwork(networkName, object : RemoveNetworkCallbacks { + override fun networkRemoved() { + presenter.displayNetworkRemoved() + } + + override fun networkNotFoundToRemove() { + presenter.displayNetworkNotFoundToRemove() + } + + override fun failureRemovingNetwork() { + presenter.displayFailureRemovingNetwork() + } + + override fun wisefyFailure(@WiseFyCode wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } +} \ No newline at end of file diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkMvp.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkMvp.kt new file mode 100644 index 00000000..de71a923 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkMvp.kt @@ -0,0 +1,31 @@ +package com.isupatches.wisefysample.ui.remove + +import com.isupatches.wisefysample.internal.base.BaseMvp + +internal interface RemoveNetworkMvp { + + interface View : BaseMvp.View { + fun displayNetworkRemoved() + fun displayNetworkNotFoundToRemove() + fun displayFailureRemovingNetwork() + } + + interface Presenter : BaseMvp.Presenter { + + /* + * Model call-throughs + */ + fun removeNetwork(networkName: String) + + /* + * View callbacks + */ + fun displayNetworkRemoved() + fun displayNetworkNotFoundToRemove() + fun displayFailureRemovingNetwork() + } + + interface Model { + fun removeNetwork(networkName: String) + } +} \ No newline at end of file diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkPresenter.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkPresenter.kt new file mode 100644 index 00000000..cc4dfe55 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkPresenter.kt @@ -0,0 +1,39 @@ +package com.isupatches.wisefysample.ui.remove + +import android.Manifest.permission.ACCESS_WIFI_STATE +import androidx.annotation.RequiresPermission + +import com.isupatches.wisefy.WiseFy +import com.isupatches.wisefysample.internal.base.BasePresenter + +internal class RemoveNetworkPresenter( + wiseFy: WiseFy +) : BasePresenter(), RemoveNetworkMvp.Presenter { + + private val model = RemoveNetworkModel(this, wiseFy) + + /* + * Model call-throughs + */ + + @RequiresPermission(ACCESS_WIFI_STATE) + override fun removeNetwork(networkName: String) { + model.removeNetwork(networkName) + } + + /* + * View callbacks + */ + + override fun displayNetworkRemoved() { + doSafelyWithView { view -> view.displayNetworkRemoved() } + } + + override fun displayNetworkNotFoundToRemove() { + doSafelyWithView { view -> view.displayNetworkNotFoundToRemove() } + } + + override fun displayFailureRemovingNetwork() { + doSafelyWithView { view -> view.displayFailureRemovingNetwork() } + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/search/SearchFragment.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/search/SearchFragment.kt new file mode 100644 index 00000000..f3b348a0 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/search/SearchFragment.kt @@ -0,0 +1,367 @@ +package com.isupatches.wisefysample.ui.search + +import android.Manifest +import android.Manifest.permission.ACCESS_WIFI_STATE +import android.net.wifi.ScanResult +import android.net.wifi.WifiConfiguration +import android.os.Bundle +import android.view.View +import android.widget.SeekBar + +import com.isupatches.wisefysample.R +import com.isupatches.wisefysample.internal.models.SearchType +import com.isupatches.wisefysample.internal.preferences.SearchStore +import com.isupatches.wisefysample.internal.base.BaseFragment +import com.isupatches.wisefysample.internal.util.asHtmlSpanned +import com.isupatches.wisefysample.internal.util.displayShortToast +import com.isupatches.wisefysample.internal.util.getTrimmedInput +import com.isupatches.wisefysample.internal.util.hideKeyboardFrom + +import kotlinx.android.synthetic.main.fragment_search.filterDupesRdg +import kotlinx.android.synthetic.main.fragment_search.filterDupesTxt +import kotlinx.android.synthetic.main.fragment_search.returnFullListRdg +import kotlinx.android.synthetic.main.fragment_search.searchBtn +import kotlinx.android.synthetic.main.fragment_search.searchRegexEdt +import kotlinx.android.synthetic.main.fragment_search.searchTypeRdg +import kotlinx.android.synthetic.main.fragment_search.timeoutSeek +import kotlinx.android.synthetic.main.fragment_search.timeoutTxt + +import javax.inject.Inject + +internal class SearchFragment : BaseFragment(), SearchMvp.View { + + override val layoutRes = R.layout.fragment_search + + private val presenter by lazy { SearchPresenter(wiseFy) } + + @Inject lateinit var searchStore: SearchStore + + companion object { + val TAG: String = SearchFragment::class.java.simpleName + + fun newInstance() = SearchFragment() + + private const val TIMEOUT_MIN = 1 + private const val TIMEOUT_MAX = 60 + + private const val WISEFY_SEARCH_FOR_SAVED_NETWORK_REQUEST_CODE = 1 + private const val WISEFY_SEARCH_FOR_SAVED_NETWORKS_REQUEST_CODE = 2 + private const val WISEFY_SEARCH_FOR_ACCESS_POINT_REQUEST_CODE = 3 + private const val WISEFY_SEARCH_FOR_ACCESS_POINTS_REQUEST_CODE = 4 + private const val WISEFY_SEARCH_FOR_SSID_REQUEST_CODE = 5 + private const val WISEFY_SEARCH_FOR_SSIDS_REQUEST_CODE = 6 + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + if (savedInstanceState == null) { + restoreUI() + } + + searchTypeRdg.setOnCheckedChangeListener { _, checkedId -> + when (checkedId) { + R.id.accessPointRdb -> searchStore.setSearchType(SearchType.ACCESS_POINT) + R.id.ssidRdb -> searchStore.setSearchType(SearchType.SSID) + R.id.savedNetworkRdb -> searchStore.setSearchType(SearchType.SAVED_NETWORK) + } + updateUI() + } + filterDupesRdg.setOnCheckedChangeListener { _, checkedId -> + when (checkedId) { + R.id.yesFilterDupesRdb -> searchStore.setFilterDuplicates(true) + else -> searchStore.setFilterDuplicates(false) + } + } + returnFullListRdg.setOnCheckedChangeListener { _, checkedId -> + when (checkedId) { + R.id.yesFullListRdb -> searchStore.setReturnFullList(true) + else -> searchStore.setReturnFullList(false) + } + updateUI() + } + searchBtn.setOnClickListener { search() } + + with(timeoutSeek) { + max = TIMEOUT_MAX + setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { + override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { + val timeout = Math.max(TIMEOUT_MIN, progress) + searchStore.setTimeout(timeout) + timeoutTxt.text = getString(R.string.timeout_after_x_seconds_args_html, timeout).asHtmlSpanned() + } + + override fun onStartTrackingTouch(seekBar: SeekBar?) { + // No-op + } + + override fun onStopTrackingTouch(seekBar: SeekBar?) { + // No-op + } + }) + } + } + + override fun onStart() { + super.onStart() + presenter.attachView(this) + } + + override fun onStop() { + presenter.detachView() + super.onStop() + searchStore.setLastUsedRegex(searchRegexEdt.getTrimmedInput()) + hideKeyboardFrom(searchBtn) + } + + /* + * View helpers + */ + + private fun adjustFilterDupesVisibility(visibility: Int) { + filterDupesTxt.visibility = visibility + filterDupesRdg.visibility = visibility + } + + private fun adjustTimeoutVisibility(visibility: Int) { + timeoutSeek.visibility = visibility + timeoutTxt.visibility = visibility + } + + private fun getFilterDuplicates(): Boolean = + filterDupesRdg.checkedRadioButtonId == R.id.yesFilterDupesRdb + + private fun getSelectedTimeout(): Int = timeoutSeek.progress * 1000 + + private fun restoreUI() { + // Restore edit text value + searchRegexEdt.setText(searchStore.getLastUsedRegex()) + + // Restore checked state + val checkedId = when (searchStore.getSearchType()) { + SearchType.ACCESS_POINT -> { + showAccessPointUI() + R.id.accessPointRdb + } + SearchType.SSID -> { + showSSIDUI() + R.id.ssidRdb + } + SearchType.SAVED_NETWORK -> { + showSavedNetworkUI() + R.id.savedNetworkRdb + } + } + searchTypeRdg.check(checkedId) + + // Restore return full list + val fullListCheckedId = if (searchStore.shouldReturnFullList()) { + R.id.yesFullListRdb + } else { + R.id.noReturnFullListRdb + } + returnFullListRdg.check(fullListCheckedId) + + // Restore filter duplicates + val filterDupesCheckedId = if (searchStore.shouldFilterDuplicates()) { + R.id.yesFilterDupesRdb + } else { + R.id.noFilterDupesRdb + } + filterDupesRdg.check(filterDupesCheckedId) + + // Restore timeout + val timeout = searchStore.getTimeout() + timeoutSeek.progress = timeout + timeoutTxt.text = getString(R.string.timeout_after_x_seconds_args_html, timeout).asHtmlSpanned() + when(searchStore.getSearchType()) { + SearchType.SAVED_NETWORK -> adjustTimeoutVisibility(View.INVISIBLE) + else -> toggleSeekVisibility() + } + } + + private fun search() { + when (searchTypeRdg.checkedRadioButtonId) { + R.id.accessPointRdb -> { + when (returnFullListRdg.checkedRadioButtonId) { + R.id.yesFullListRdb -> searchForAccessPoints() + R.id.noReturnFullListRdb -> searchForAccessPoint() + } + } + R.id.ssidRdb -> { + when (returnFullListRdg.checkedRadioButtonId) { + R.id.yesFullListRdb -> searchForSSIDs() + R.id.noReturnFullListRdb -> searchForSSID() + } + } + R.id.savedNetworkRdb -> { + when (returnFullListRdg.checkedRadioButtonId) { + R.id.yesFullListRdb -> getSavedNetworks() + R.id.noReturnFullListRdb -> getSavedNetwork() + } + } + } + } + + private fun showAccessPointUI() { + adjustFilterDupesVisibility(View.VISIBLE) + toggleSeekVisibility() + } + + private fun showSavedNetworkUI() { + adjustFilterDupesVisibility(View.INVISIBLE) + adjustTimeoutVisibility(View.INVISIBLE) + } + + private fun showSSIDUI() { + adjustFilterDupesVisibility(View.INVISIBLE) + toggleSeekVisibility() + } + + private fun toggleSeekVisibility() { + when (returnFullListRdg.checkedRadioButtonId) { + R.id.yesFullListRdb -> adjustTimeoutVisibility(View.INVISIBLE) + R.id.noReturnFullListRdb -> adjustTimeoutVisibility(View.VISIBLE) + } + } + + private fun updateUI() { + when (searchTypeRdg.checkedRadioButtonId) { + R.id.accessPointRdb -> showAccessPointUI() + R.id.ssidRdb -> showSSIDUI() + R.id.savedNetworkRdb -> showSavedNetworkUI() + } + } + + /* + * WiseFy helpers + */ + + private fun getSavedNetwork() { + if (checkSearchForSavedNetworkPermissions()) { + presenter.getSavedNetwork(searchRegexEdt.getTrimmedInput()) + } + } + + private fun getSavedNetworks() { + if (checkSearchForSavedNetworksPermissions()) { + presenter.getSavedNetworks(searchRegexEdt.getTrimmedInput()) + } + } + + @Throws(SecurityException::class) + private fun searchForAccessPoint() { + if (checkSearchForAccessPointPermissions()) { + presenter.searchForAccessPoint(searchRegexEdt.getTrimmedInput(), getSelectedTimeout(), getFilterDuplicates()) + } + } + + @Throws(SecurityException::class) + private fun searchForAccessPoints() { + if (checkSearchForAccessPointsPermissions()) { + presenter.searchForAccessPoints(searchRegexEdt.getTrimmedInput(), getFilterDuplicates()) + } + } + + @Throws(SecurityException::class) + private fun searchForSSID() { + if (checkSearchForSSIDPermissions()) { + presenter.searchForSSID(searchRegexEdt.getTrimmedInput(), getSelectedTimeout()) + } + } + + @Throws(SecurityException::class) + private fun searchForSSIDs() { + if (checkSearchForSSIDsPermissions()) { + presenter.searchForSSIDs(searchRegexEdt.getTrimmedInput()) + } + } + + /* + * Presenter callback overrides + */ + + override fun displaySavedNetwork(savedNetwork: WifiConfiguration) { + displayShortToast("Saved network: $savedNetwork") + } + + override fun displaySavedNetworkNotFound() { + displayShortToast("Saved network not found") + } + + override fun displaySavedNetworks(savedNetworks: List) { + displayShortToast("Saved networks: $savedNetworks") + } + + override fun displayNoSavedNetworksFound() { + displayShortToast("No saved networks found") + } + + override fun displayAccessPoint(accessPoint: ScanResult) { + displayShortToast("Access point: $accessPoint") + } + + override fun displayAccessPointNotFound() { + displayShortToast("Access point not found") + } + + override fun displayAccessPoints(accessPoints: List) { + displayShortToast("Access points: $accessPoints") + } + + override fun displayNoAccessPointsFound() { + displayShortToast("No access points found") + } + + override fun displaySSID(ssid: String) { + displayShortToast("SSID: $ssid") + } + + override fun displaySSIDNotFound() { + displayShortToast("SSID not found") + } + + override fun displaySSIDs(ssids: List) { + displayShortToast("SSIDs: $ssids") + } + + override fun displayNoSSIDsFound() { + displayShortToast("No SSIDs found") + } + + override fun displayWiseFyFailure(wiseFyFailureCode: Int) { + displayWiseFyFailureWithCode(wiseFyFailureCode) + } + + /* + * Permission helpers + */ + + private fun checkSearchForSavedNetworkPermissions(): Boolean { + return isPermissionGranted(ACCESS_WIFI_STATE, WISEFY_SEARCH_FOR_SAVED_NETWORK_REQUEST_CODE) + } + + private fun checkSearchForSavedNetworksPermissions(): Boolean { + return isPermissionGranted(ACCESS_WIFI_STATE, WISEFY_SEARCH_FOR_SAVED_NETWORKS_REQUEST_CODE) + } + + private fun checkSearchForAccessPointPermissions(): Boolean { + return isPermissionGranted(ACCESS_WIFI_STATE, WISEFY_SEARCH_FOR_ACCESS_POINT_REQUEST_CODE) + && isPermissionGranted(Manifest.permission.ACCESS_COARSE_LOCATION, WISEFY_SEARCH_FOR_ACCESS_POINT_REQUEST_CODE) + } + + private fun checkSearchForAccessPointsPermissions(): Boolean { + return isPermissionGranted(ACCESS_WIFI_STATE, WISEFY_SEARCH_FOR_ACCESS_POINTS_REQUEST_CODE) + && isPermissionGranted(Manifest.permission.ACCESS_COARSE_LOCATION, WISEFY_SEARCH_FOR_ACCESS_POINTS_REQUEST_CODE) + } + + private fun checkSearchForSSIDPermissions(): Boolean { + return isPermissionGranted(ACCESS_WIFI_STATE, WISEFY_SEARCH_FOR_SSID_REQUEST_CODE) + && isPermissionGranted(Manifest.permission.ACCESS_COARSE_LOCATION, WISEFY_SEARCH_FOR_SSID_REQUEST_CODE) + } + + private fun checkSearchForSSIDsPermissions(): Boolean { + return isPermissionGranted(ACCESS_WIFI_STATE, WISEFY_SEARCH_FOR_SSIDS_REQUEST_CODE) + && isPermissionGranted(Manifest.permission.ACCESS_COARSE_LOCATION, WISEFY_SEARCH_FOR_SSIDS_REQUEST_CODE) + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/search/SearchModel.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/search/SearchModel.kt new file mode 100644 index 00000000..877d6dc3 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/search/SearchModel.kt @@ -0,0 +1,124 @@ +package com.isupatches.wisefysample.ui.search + +import android.Manifest.permission.ACCESS_COARSE_LOCATION +import android.Manifest.permission.ACCESS_WIFI_STATE +import android.net.wifi.ScanResult +import android.net.wifi.WifiConfiguration +import androidx.annotation.RequiresPermission + +import com.isupatches.wisefy.WiseFy +import com.isupatches.wisefy.callbacks.GetSavedNetworkCallbacks +import com.isupatches.wisefy.callbacks.GetSavedNetworksCallbacks +import com.isupatches.wisefy.callbacks.SearchForAccessPointCallbacks +import com.isupatches.wisefy.callbacks.SearchForAccessPointsCallbacks +import com.isupatches.wisefy.callbacks.SearchForSSIDCallbacks +import com.isupatches.wisefy.callbacks.SearchForSSIDsCallbacks +import com.isupatches.wisefy.constants.WiseFyCode + +internal class SearchModel( + private val presenter: SearchMvp.Presenter, + private val wiseFy: WiseFy +): SearchMvp.Model { + + @RequiresPermission(ACCESS_WIFI_STATE) + override fun getSavedNetwork(regexForSSID: String) { + wiseFy.getSavedNetwork(regexForSSID, object : GetSavedNetworkCallbacks { + override fun retrievedSavedNetwork(savedNetwork: WifiConfiguration) { + presenter.displaySavedNetwork(savedNetwork) + } + + override fun savedNetworkNotFound() { + presenter.displaySavedNetworkNotFound() + } + + override fun wisefyFailure(@WiseFyCode wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } + + @RequiresPermission(ACCESS_WIFI_STATE) + override fun getSavedNetworks(regexForSSID: String) { + wiseFy.getSavedNetworks(regexForSSID, object : GetSavedNetworksCallbacks { + override fun retrievedSavedNetworks(savedNetworks: List) { + presenter.displaySavedNetworks(savedNetworks) + } + + override fun noSavedNetworksFound() { + presenter.displayNoSavedNetworksFound() + } + + override fun wisefyFailure(@WiseFyCode wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } + + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) + override fun searchForAccessPoint(regexForSSID: String, timeout: Int, filterDuplicates: Boolean) { + wiseFy.searchForAccessPoint(regexForSSID, timeout, filterDuplicates, object : SearchForAccessPointCallbacks { + override fun accessPointFound(accessPoint: ScanResult) { + presenter.displayAccessPoint(accessPoint) + } + + override fun accessPointNotFound() { + presenter.displayAccessPointNotFound() + } + + override fun wisefyFailure(@WiseFyCode wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } + + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) + override fun searchForAccessPoints(regexForSSID: String, filterDuplicates: Boolean) { + wiseFy.searchForAccessPoints(regexForSSID, filterDuplicates, object : SearchForAccessPointsCallbacks { + override fun foundAccessPoints(accessPoints: List) { + presenter.displayAccessPoints(accessPoints) + } + + override fun noAccessPointsFound() { + presenter.displayNoAccessPointsFound() + } + + override fun wisefyFailure(@WiseFyCode wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } + + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) + override fun searchForSSID(regexForSSID: String, timeout: Int) { + wiseFy.searchForSSID(regexForSSID, timeout, object : SearchForSSIDCallbacks { + override fun ssidFound(ssid: String) { + presenter.displaySSID(ssid) + } + + override fun ssidNotFound() { + presenter.displaySSIDNotFound() + } + + override fun wisefyFailure(@WiseFyCode wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } + + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) + override fun searchForSSIDs(regexForSSID: String) { + wiseFy.searchForSSIDs(regexForSSID, object : SearchForSSIDsCallbacks { + override fun retrievedSSIDs(ssids: List) { + presenter.displaySSIDs(ssids) + } + + override fun noSSIDsFound() { + presenter.displayNoSSIDsFound() + } + + override fun wisefyFailure(@WiseFyCode wisefyFailureCode: Int) { + presenter.displayWiseFyFailure(wisefyFailureCode) + } + }) + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/search/SearchMvp.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/search/SearchMvp.kt new file mode 100644 index 00000000..dc164229 --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/search/SearchMvp.kt @@ -0,0 +1,63 @@ +package com.isupatches.wisefysample.ui.search + +import android.net.wifi.ScanResult +import android.net.wifi.WifiConfiguration +import com.isupatches.wisefysample.internal.base.BaseMvp + +internal interface SearchMvp { + + interface View : BaseMvp.View { + + fun displaySavedNetwork(savedNetwork: WifiConfiguration) + fun displaySavedNetworkNotFound() + fun displaySavedNetworks(savedNetworks: List) + fun displayNoSavedNetworksFound() + fun displayAccessPoint(accessPoint: ScanResult) + fun displayAccessPointNotFound() + fun displayAccessPoints(accessPoints: List) + fun displayNoAccessPointsFound() + fun displaySSID(ssid: String) + fun displaySSIDNotFound() + fun displaySSIDs(ssids: List) + fun displayNoSSIDsFound() + } + + interface Presenter : BaseMvp.Presenter { + + /* + * Model call-throughs + */ + fun getSavedNetwork(regexForSSID: String) + fun getSavedNetworks(regexForSSID: String) + fun searchForAccessPoint(regexForSSID: String, timeout: Int, filterDuplicates: Boolean) + fun searchForAccessPoints(regexForSSID: String, filterDuplicates: Boolean) + fun searchForSSID(regexForSSID: String, timeout: Int) + fun searchForSSIDs(regexForSSID: String) + + /* + * View Callbacks + */ + fun displaySavedNetwork(savedNetwork: WifiConfiguration) + fun displaySavedNetworkNotFound() + fun displaySavedNetworks(savedNetworks: List) + fun displayNoSavedNetworksFound() + fun displayAccessPoint(accessPoint: ScanResult) + fun displayAccessPointNotFound() + fun displayAccessPoints(accessPoints: List) + fun displayNoAccessPointsFound() + fun displaySSID(ssid: String) + fun displaySSIDNotFound() + fun displaySSIDs(ssids: List) + fun displayNoSSIDsFound() + } + + interface Model { + + fun getSavedNetwork(regexForSSID: String) + fun getSavedNetworks(regexForSSID: String) + fun searchForAccessPoint(regexForSSID: String, timeout: Int, filterDuplicates: Boolean) + fun searchForAccessPoints(regexForSSID: String, filterDuplicates: Boolean) + fun searchForSSID(regexForSSID: String, timeout: Int) + fun searchForSSIDs(regexForSSID: String) + } +} diff --git a/wisefysample/src/main/java/com/isupatches/wisefysample/ui/search/SearchPresenter.kt b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/search/SearchPresenter.kt new file mode 100644 index 00000000..878eb0cc --- /dev/null +++ b/wisefysample/src/main/java/com/isupatches/wisefysample/ui/search/SearchPresenter.kt @@ -0,0 +1,101 @@ +package com.isupatches.wisefysample.ui.search + +import android.Manifest.permission.ACCESS_COARSE_LOCATION +import android.Manifest.permission.ACCESS_WIFI_STATE +import android.net.wifi.ScanResult +import android.net.wifi.WifiConfiguration +import androidx.annotation.RequiresPermission + +import com.isupatches.wisefy.WiseFy +import com.isupatches.wisefysample.internal.base.BasePresenter + +internal class SearchPresenter( + wiseFy: WiseFy +) : BasePresenter(), SearchMvp.Presenter { + + private val model = SearchModel(this, wiseFy) + + /* + * Model call-throughs + */ + + override fun getSavedNetwork(regexForSSID: String) { + model.getSavedNetwork(regexForSSID) + } + + override fun getSavedNetworks(regexForSSID: String) { + model.getSavedNetworks(regexForSSID) + } + + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) + override fun searchForAccessPoint(regexForSSID: String, timeout: Int, filterDuplicates: Boolean) { + model.searchForAccessPoint(regexForSSID, timeout, filterDuplicates) + } + + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) + override fun searchForAccessPoints(regexForSSID: String, filterDuplicates: Boolean) { + model.searchForAccessPoints(regexForSSID, filterDuplicates) + } + + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) + override fun searchForSSID(regexForSSID: String, timeout: Int) { + model.searchForSSID(regexForSSID, timeout) + } + + @RequiresPermission(allOf = [ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE]) + override fun searchForSSIDs(regexForSSID: String) { + model.searchForSSIDs(regexForSSID) + } + + /* + * View callbacks + */ + + override fun displaySavedNetwork(savedNetwork: WifiConfiguration) { + doSafelyWithView { view -> view.displaySavedNetwork(savedNetwork) } + } + + override fun displaySavedNetworkNotFound() { + doSafelyWithView { view -> view.displaySavedNetworkNotFound() } + } + + override fun displaySavedNetworks(savedNetworks: List) { + doSafelyWithView { view -> view.displaySavedNetworks(savedNetworks) } + } + + override fun displayNoSavedNetworksFound() { + doSafelyWithView { view -> view.displayNoSavedNetworksFound() } + } + + override fun displayAccessPoint(accessPoint: ScanResult) { + doSafelyWithView { view -> view.displayAccessPoint(accessPoint) } + } + + override fun displayAccessPointNotFound() { + doSafelyWithView { view -> view.displayAccessPointNotFound() } + } + + override fun displayAccessPoints(accessPoints: List) { + doSafelyWithView { view -> view.displayAccessPoints(accessPoints) } + } + + override fun displayNoAccessPointsFound() { + doSafelyWithView { view -> view.displayNoAccessPointsFound() } + } + + override fun displaySSID(ssid: String) { + doSafelyWithView { view -> view.displaySSID(ssid) } + } + + override fun displaySSIDNotFound() { + doSafelyWithView { view -> view.displaySSIDNotFound() } + } + + override fun displaySSIDs(ssids: List) { + doSafelyWithView { view -> view.displaySSIDs(ssids) } + } + + override fun displayNoSSIDsFound() { + doSafelyWithView { view -> view.displayNoSSIDsFound() } + } +} diff --git a/wisefysample/src/main/res/drawable/button_pressed.xml b/wisefysample/src/main/res/drawable/button_pressed.xml new file mode 100644 index 00000000..b294c566 --- /dev/null +++ b/wisefysample/src/main/res/drawable/button_pressed.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/wisefysample/src/main/res/drawable/button_selector.xml b/wisefysample/src/main/res/drawable/button_selector.xml new file mode 100644 index 00000000..5e142055 --- /dev/null +++ b/wisefysample/src/main/res/drawable/button_selector.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/wisefysample/src/main/res/drawable/button_unpressed.xml b/wisefysample/src/main/res/drawable/button_unpressed.xml new file mode 100644 index 00000000..48a60bf6 --- /dev/null +++ b/wisefysample/src/main/res/drawable/button_unpressed.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/wisefysample/src/main/res/drawable/ic_add_circle.xml b/wisefysample/src/main/res/drawable/ic_add_circle.xml new file mode 100644 index 00000000..1882a199 --- /dev/null +++ b/wisefysample/src/main/res/drawable/ic_add_circle.xml @@ -0,0 +1,9 @@ + + + diff --git a/wisefysample/src/main/res/drawable/ic_apps.xml b/wisefysample/src/main/res/drawable/ic_apps.xml new file mode 100644 index 00000000..4bb879ec --- /dev/null +++ b/wisefysample/src/main/res/drawable/ic_apps.xml @@ -0,0 +1,9 @@ + + + diff --git a/wisefysample/src/main/res/drawable/ic_home.xml b/wisefysample/src/main/res/drawable/ic_home.xml new file mode 100644 index 00000000..0c36320f --- /dev/null +++ b/wisefysample/src/main/res/drawable/ic_home.xml @@ -0,0 +1,9 @@ + + + diff --git a/wisefysample/src/main/res/drawable/ic_launcher_background.xml b/wisefysample/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 00000000..91fd4e4a --- /dev/null +++ b/wisefysample/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,9 @@ + + + + diff --git a/wisefysample/src/main/res/drawable/ic_launcher_foreground.xml b/wisefysample/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 00000000..6ec36c05 --- /dev/null +++ b/wisefysample/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,13 @@ + + + + diff --git a/wisefysample/src/main/res/drawable/ic_remove_circle.xml b/wisefysample/src/main/res/drawable/ic_remove_circle.xml new file mode 100644 index 00000000..6d8dc776 --- /dev/null +++ b/wisefysample/src/main/res/drawable/ic_remove_circle.xml @@ -0,0 +1,9 @@ + + + diff --git a/wisefysample/src/main/res/drawable/ic_search.xml b/wisefysample/src/main/res/drawable/ic_search.xml new file mode 100644 index 00000000..6fafa170 --- /dev/null +++ b/wisefysample/src/main/res/drawable/ic_search.xml @@ -0,0 +1,9 @@ + + + diff --git a/wisefysample/src/main/res/layout/activity_main.xml b/wisefysample/src/main/res/layout/activity_main.xml new file mode 100644 index 00000000..68cf1f08 --- /dev/null +++ b/wisefysample/src/main/res/layout/activity_main.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + diff --git a/wisefysample/src/main/res/layout/dialog_permission_error.xml b/wisefysample/src/main/res/layout/dialog_permission_error.xml new file mode 100644 index 00000000..a4cde166 --- /dev/null +++ b/wisefysample/src/main/res/layout/dialog_permission_error.xml @@ -0,0 +1,32 @@ + + + + + + + + \ No newline at end of file diff --git a/wisefysample/src/main/res/layout/dialog_permission_rationale.xml b/wisefysample/src/main/res/layout/dialog_permission_rationale.xml new file mode 100644 index 00000000..9225d01d --- /dev/null +++ b/wisefysample/src/main/res/layout/dialog_permission_rationale.xml @@ -0,0 +1,32 @@ + + + + + + + + \ No newline at end of file diff --git a/wisefysample/src/main/res/layout/fragment_add.xml b/wisefysample/src/main/res/layout/fragment_add.xml new file mode 100644 index 00000000..e1460376 --- /dev/null +++ b/wisefysample/src/main/res/layout/fragment_add.xml @@ -0,0 +1,118 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + +